Skip to main content

ostrya/
send.rs

1//! One pull session over a pair of streams: the serving side of the pull over
2//! ssh.
3
4use std::collections::HashSet;
5use std::fmt;
6use std::io;
7use std::sync::Arc;
8
9use futures_io::{AsyncRead, AsyncWrite};
10use futures_lite::io::{AsyncReadExt, BufReader, BufWriter};
11use ostrya_core::RefSelector;
12
13use crate::access::ReadAccess;
14use crate::archive::{ArchiveAnswer, ArchiveView};
15use crate::error::{Error, Result};
16use crate::remote;
17use crate::remote::proto::{
18    FrameReader, FrameWriter, GetReply, ListRefsRequest, MAX_REF_ENTRY_LEN, MAX_REF_ENTRY_PARTS,
19    MAX_REF_LISTING, MAX_REF_PATTERNS, Message, PULL_PROTOCOL_VERSION, PullHello, PullHelloReply,
20};
21use crate::repo::Repo;
22
23/// The buffer size of each direction of the session stream.
24const STREAM_BUFFER: usize = 64 * 1024;
25
26/// The payload size of each chunk of a body, except the last chunk.
27///
28/// Each write to the output is at most [`STREAM_BUFFER`] bytes, because a
29/// full chunk and its 4-byte length fill the output buffer. No write holds a
30/// chunk length alone.
31const CHUNK: usize = STREAM_BUFFER - 4;
32
33/// The callback that receives each [`SendEvent`] of a session.
34///
35/// The session calls it in its own task, so the callback must return soon.
36pub type SendEventFn = Arc<dyn Fn(&SendEvent) + Send + Sync>;
37
38/// The options of [`Repo::send_with`].
39///
40/// The struct is `#[non_exhaustive]`, so a caller starts from
41/// [`SendOptions::default`] and sets the fields.
42#[derive(Clone, Default)]
43#[non_exhaustive]
44pub struct SendOptions {
45    /// The callback for each [`SendEvent`] of the session, or `None`.
46    ///
47    /// A host writes the event to its log, for example the
48    /// [`Display`](fmt::Display) text of the event on standard error. The
49    /// default is `None`, which drops each event.
50    pub on_event: Option<SendEventFn>,
51}
52
53/// The debug text shows a callback that is set as `<callback>`.
54impl fmt::Debug for SendOptions {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        f.debug_struct("SendOptions")
57            .field("on_event", &self.on_event.as_ref().map(|_| "<callback>"))
58            .finish()
59    }
60}
61
62/// An event of a session of [`Repo::send_with`], which
63/// [`SendOptions::on_event`] receives.
64///
65/// [`Display`](fmt::Display) writes one line for the log of the host. It
66/// writes each ASCII control character of a name as an escape sequence, for
67/// example `\n`, so the line holds no line break.
68#[derive(Debug, Clone, PartialEq, Eq)]
69#[non_exhaustive]
70pub enum SendEvent {
71    /// A ref listing of the session left out a directory under
72    /// `refs/mirrors/` whose name fails the collection-id rule
73    /// ([`is_collection_id`](crate::is_collection_id)).
74    ///
75    /// The session reports each name one time, at the first listing that
76    /// finds it. Only a `ListRefs` with the `collections` key reads the
77    /// directories under `refs/mirrors/`.
78    #[non_exhaustive]
79    InvalidCollectionDir {
80        /// The name of the directory.
81        name: String,
82    },
83    /// The session answered `summary` or `summary.sig` as an absent path,
84    /// because the `.access` file of the item of the client does not hold
85    /// the access digest of the item ([`ArchiveAnswer::StaleSummary`]).
86    ///
87    /// The summary of the item does not match the client groups. The session
88    /// reports the event one time, at the first request that finds it.
89    #[non_exhaustive]
90    StaleSummary {
91        /// The text of the auth item of the client.
92        item: String,
93    },
94}
95
96impl SendEvent {
97    /// Returns `true` if the event is a warning: the session served the
98    /// request. Each other event is an error of a request that the session
99    /// did not serve.
100    ///
101    /// [`InvalidCollectionDir`](SendEvent::InvalidCollectionDir) is a
102    /// warning, and [`StaleSummary`](SendEvent::StaleSummary) is an error.
103    pub fn is_warning(&self) -> bool {
104        match self {
105            SendEvent::InvalidCollectionDir { .. } => true,
106            SendEvent::StaleSummary { .. } => false,
107        }
108    }
109}
110
111impl fmt::Display for SendEvent {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        match self {
114            SendEvent::InvalidCollectionDir { name } => {
115                f.write_str("refs/mirrors/")?;
116                write_escaped(f, name)?;
117                f.write_str(
118                    ": the directory name is not a collection id, and the ref listing leaves \
119                     out the directory",
120                )
121            }
122            SendEvent::StaleSummary { item } => {
123                f.write_str("the summary of the auth item ")?;
124                write_escaped(f, item)?;
125                f.write_str(
126                    " does not match the client groups, and the session does not serve it; \
127                     run `ostrya summary -u`",
128                )
129            }
130        }
131    }
132}
133
134/// Writes `text` with each ASCII control character as its escape sequence.
135///
136/// The function writes each run of characters with no control character in
137/// one call, so a long name gives few writes to the sink of the formatter.
138pub(crate) fn write_escaped(f: &mut fmt::Formatter<'_>, text: &str) -> fmt::Result {
139    let mut rest = text;
140    while let Some(at) = rest.find(|c: char| c.is_ascii_control()) {
141        f.write_str(&rest[..at])?;
142        // A control character is ASCII, so it is one byte.
143        let c = char::from(rest.as_bytes()[at]);
144        write!(f, "{}", c.escape_default())?;
145        rest = &rest[at + 1..];
146    }
147    f.write_str(rest)
148}
149
150/// The kind of failure that ends a session.
151enum Failure {
152    /// A failure with a wire code. The session sends it to the peer. The
153    /// caller gets it as [`Error::Remote`].
154    Wire(remote::Error),
155    /// A failure on the server side. The session sends it to the peer as
156    /// `internal`. The caller gets the error unchanged.
157    Internal(Error),
158    /// A body that failed after its reply. The session wrote the abandon
159    /// marker and the `Error` frame before it made this value. The caller
160    /// gets the error unchanged.
161    Abandoned(Error),
162    /// A failure of the output. The session sends nothing.
163    Silent(Error),
164}
165
166/// Maps a codec error of the reader to a failure.
167///
168/// An end of file inside a frame is `protocol`. Another error of the input
169/// stream is a failure of the server. Every other error keeps its wire code.
170fn input(error: remote::Error) -> Failure {
171    match error {
172        remote::Error::Io(e) if e.kind() == io::ErrorKind::UnexpectedEof => Failure::Wire(
173            remote::Error::Protocol("the input ended inside a frame".to_owned()),
174        ),
175        remote::Error::Io(e) => Failure::Internal(Error::Io(e)),
176        other => Failure::Wire(other),
177    }
178}
179
180/// Maps an error of the writer to a failure.
181///
182/// An error of the output stream is silent. If the codec refuses a message,
183/// the failure is `internal`, whatever code the codec gives. The refusal is a
184/// fault of the server.
185fn output(error: remote::Error) -> Failure {
186    match error {
187        remote::Error::Io(e) => Failure::Silent(Error::Io(e)),
188        other => Failure::Wire(remote::Error::Internal(other.to_string())),
189    }
190}
191
192fn out_of_order(msg: &Message) -> Failure {
193    Failure::Wire(remote::Error::Protocol(format!(
194        "{:?} is out of order",
195        msg.kind()
196    )))
197}
198
199/// Returns the `GetReply` of a path that the session does not serve.
200fn not_found() -> Message {
201    Message::GetReply(GetReply {
202        found: false,
203        len: None,
204    })
205}
206
207/// Returns `true` if `buf` starts with a whole frame.
208///
209/// A whole frame is its 4-byte length and that number of bytes.
210fn complete_frame(buf: &[u8]) -> bool {
211    match buf.first_chunk::<4>() {
212        Some(prefix) => buf.len() - 4 >= u32::from_be_bytes(*prefix) as usize,
213        None => false,
214    }
215}
216
217/// Methods that serve a pull session.
218impl Repo {
219    /// Serves one pull session over the streams `input` and `output`, with
220    /// the read rights `access`.
221    ///
222    /// The session reads a `PullHello` message and then `Get` and `ListRefs`
223    /// messages of a client from `input`. It writes the replies and the bodies
224    /// to `output`. This method is the serving side of a pull over ssh. It
225    /// does not close `output`.
226    ///
227    /// # Requests
228    ///
229    /// The session answers each `Get` through one [`ArchiveView`] of this
230    /// repository, with `access`. All requests of the session share the
231    /// parsed `config` and the idle compressors of the view. The session reads
232    /// one `Get`, answers it to the end of its body, and then reads the next
233    /// request.
234    ///
235    /// - If the view does not find the path, or refuses it, the reply is a
236    ///   `GetReply` with `found` set to `false`. The session continues.
237    /// - If the view serves the path, the reply is a `GetReply` with `found`
238    ///   set to `true`. The reply holds the length if the view knows it. The
239    ///   body follows as chunks.
240    ///
241    /// The session answers each `ListRefs` with the listing that
242    /// [`build_ref_listing`](Repo::build_ref_listing) builds for its two
243    /// lists of entries and `access`. The entries of field 0 select the local
244    /// refs. The entries under the key `collections` select the collection
245    /// refs, and with no such key the listing holds no collection ref.
246    /// The entries are ref patterns with an optional leading `!`, which
247    /// [`RefSelector::parse`] reads. A `ListRefs` holds at most
248    /// [`MAX_REF_PATTERNS`] entries in its two lists together, and each entry
249    /// holds at most [`MAX_REF_ENTRY_PARTS`] parts and [`MAX_REF_ENTRY_LEN`]
250    /// bytes. The reply is a `GetReply` with `found` set to `true` and the
251    /// length of the listing. The listing follows as chunks.
252    ///
253    /// # Access
254    ///
255    /// `access` gives the refs that the session serves. A ref that `access`
256    /// does not read, and a path under `refs/` that names no ref, get a
257    /// `GetReply` with `found` set to `false`, as an absent path does. The
258    /// listing of `ListRefs` holds the refs that `access` reads. `summary`
259    /// and `summary.sig` give the files of the summary of the item of
260    /// `access`, by the rules of [`ArchiveView`](crate::ArchiveView#read-access).
261    /// An item with no summary, and a summary whose `.access` file does not
262    /// match, get `found` set to `false`.
263    ///
264    /// The session opens no transaction and takes no lock. For an `archive`,
265    /// `bare-user`, `bare-user-only`, or `bare-user-shared` repository, read
266    /// access to the repository is sufficient. For a `bare` or
267    /// `bare-split-xattrs` repository, the account must be able to read every
268    /// object and its extended attributes.
269    ///
270    /// # Framing and memory
271    ///
272    /// The frame limit is [`MIN_FRAME_LIMIT`](crate::remote::proto::MIN_FRAME_LIMIT)
273    /// in the two directions. Each direction goes through a buffer of 64 KiB.
274    /// Each chunk of a body, except the last chunk, holds 64 KiB less 4 bytes.
275    ///
276    /// A body streams through one chunk buffer, so no content object is whole
277    /// in memory. For a stored file, the session reads at most one byte past
278    /// the stated length. A ref listing is whole in memory, up to
279    /// [`MAX_REF_LISTING`] bytes.
280    ///
281    /// The memory of a session is the two stream buffers, the chunk buffer,
282    /// one `Get` frame, and the reader of the current body. That reader is a
283    /// `FileReader` with a read-ahead of 4 KiB to 256 KiB, or a compressor and
284    /// two buffers of 64 KiB for a built `.filez`. A `Get` frame at the frame
285    /// limit adds about 2 MiB, because the frame body and the decoded path are
286    /// in memory at the same time.
287    ///
288    /// If the input buffer holds no whole frame, the next read can wait. The
289    /// session flushes `output` before that read. It also flushes `output`
290    /// after each `Error` message.
291    ///
292    /// # End of a session
293    ///
294    /// At an end of file of `input` at a frame boundary, the method returns
295    /// `Ok`. An empty `input` also gives `Ok`. Every other end of the session
296    /// is an error. The session tells the peer about the failure:
297    ///
298    /// - If the failure has a wire code, the session sends an `Error` message
299    ///   with that code.
300    /// - If the view fails before the reply, the session sends an `Error`
301    ///   message with the code `internal` in place of the reply. A file that
302    ///   the process cannot read is an example.
303    /// - If a read of `input` fails with an error other than an end of file,
304    ///   the session sends an `Error` message with the code `internal`.
305    /// - If a body fails after its reply, the session ends the body with the
306    ///   abandon marker and an `Error` message with the code `internal`.
307    /// - If a write of a reply or of a body to `output` fails, the session
308    ///   sends nothing more.
309    ///
310    /// If the session cannot deliver the `Error` message, the returned error
311    /// does not change.
312    ///
313    /// # Errors
314    ///
315    /// - [`Error::Remote`] with the code `version-unsupported` if the
316    ///   `PullHello` states version 0.
317    /// - [`Error::Remote`] with the code `protocol` if a message is out of
318    ///   order or is a kind of the push.
319    /// - [`Error::Remote`] with the code `protocol` if a frame is malformed, or
320    ///   if `input` ends inside a frame.
321    /// - [`Error::Remote`] with the code `protocol` if a `ListRefs` holds more
322    ///   than [`MAX_REF_PATTERNS`] entries in its two lists, an entry over the
323    ///   limits of one entry, or an entry that [`RefSelector::parse`]
324    ///   refuses. An entry given two times counts two times. The check of the
325    ///   limits of an entry comes before the parse. The message of a refused
326    ///   entry under `collections` names that key.
327    /// - [`Error::Remote`] with the code `limit-exceeded` if a ref listing is
328    ///   larger than [`MAX_REF_LISTING`].
329    /// - [`Error::Remote`] with the code `limit-exceeded` if a frame is larger
330    ///   than the limit.
331    /// - [`Error::Remote`] with the code `internal` if the codec refuses a
332    ///   message that the session writes.
333    /// - Each error of [`ArchiveView::get`] if the view fails before the
334    ///   reply.
335    /// - Each other error of [`build_ref_listing`](Repo::build_ref_listing).
336    ///   The session sends it as `internal`.
337    /// - [`Error::Io`] if a read of `input` fails with an error other than an
338    ///   end of file.
339    /// - [`Error::Io`] with the error of the read if a body fails after its
340    ///   reply. For a stored file that ends before its stated length, the
341    ///   kind is `UnexpectedEof`. For a stored file that holds more, the kind
342    ///   is `InvalidData`.
343    /// - [`Error::Io`] if a write of a reply or of a body to `output` fails.
344    pub async fn send<R, W>(&self, input: R, output: W, access: &ReadAccess) -> Result<()>
345    where
346        R: AsyncRead + Unpin + Send,
347        W: AsyncWrite + Unpin + Send,
348    {
349        self.send_with(input, output, access, &SendOptions::default())
350            .await
351    }
352
353    /// Serves one pull session as [`send`](Repo::send) does, with the
354    /// options `opts`.
355    ///
356    /// The session gives each [`SendEvent`] to
357    /// [`SendOptions::on_event`]. A ref listing of a `ListRefs` with the
358    /// `collections` key reads the top level of `refs/mirrors/`. For each
359    /// directory there whose name fails the collection-id rule, the session
360    /// gives one [`SendEvent::InvalidCollectionDir`], at the first listing
361    /// that finds it. The listing leaves out the directory. The event does
362    /// not change the session, and the peer gets no message of it.
363    ///
364    /// When the view answers `summary` or `summary.sig` with
365    /// [`ArchiveAnswer::StaleSummary`], the session gives one
366    /// [`SendEvent::StaleSummary`], at the first such answer. The peer gets a
367    /// `GetReply` with `found` set to `false`, as for an absent path.
368    ///
369    /// # Errors
370    ///
371    /// The errors of [`send`](Repo::send).
372    pub async fn send_with<R, W>(
373        &self,
374        input: R,
375        output: W,
376        access: &ReadAccess,
377        opts: &SendOptions,
378    ) -> Result<()>
379    where
380        R: AsyncRead + Unpin + Send,
381        W: AsyncWrite + Unpin + Send,
382    {
383        self.send_capped(input, output, access, opts, MAX_REF_LISTING)
384            .await
385    }
386
387    /// Serves the session of [`send_with`](Repo::send_with) with a cap of
388    /// `listing_cap` bytes on each ref listing.
389    pub(crate) async fn send_capped<R, W>(
390        &self,
391        input: R,
392        output: W,
393        access: &ReadAccess,
394        opts: &SendOptions,
395        listing_cap: u64,
396    ) -> Result<()>
397    where
398        R: AsyncRead + Unpin + Send,
399        W: AsyncWrite + Unpin + Send,
400    {
401        let mut session = Session {
402            repo: self.clone(),
403            access: access.clone(),
404            listing_cap,
405            on_event: opts.on_event.clone(),
406            warned: HashSet::new(),
407            stale_reported: false,
408            view: ArchiveView::new(self.clone()),
409            reader: FrameReader::new(BufReader::with_capacity(STREAM_BUFFER, input)),
410            writer: FrameWriter::new(BufWriter::with_capacity(STREAM_BUFFER, output)),
411            chunk: Vec::new(),
412        };
413        let failure = match session.run().await {
414            Ok(()) => return Ok(()),
415            Err(failure) => failure,
416        };
417        Err(match failure {
418            Failure::Wire(e) => {
419                session.send_error(&e).await;
420                Error::Remote(e)
421            }
422            Failure::Internal(e) => {
423                session
424                    .send_error(&remote::Error::Internal(e.to_string()))
425                    .await;
426                e
427            }
428            Failure::Abandoned(e) => {
429                let _ = session.writer.flush().await;
430                e
431            }
432            Failure::Silent(e) => e,
433        })
434    }
435}
436
437struct Session<R, W> {
438    repo: Repo,
439    /// The read rights of the client.
440    access: ReadAccess,
441    /// The size cap of each ref listing.
442    listing_cap: u64,
443    /// The callback of the events of the session.
444    on_event: Option<SendEventFn>,
445    /// The names of the invalid collection directories that the session
446    /// reported.
447    warned: HashSet<String>,
448    /// `true` once the session reported a stale summary.
449    stale_reported: bool,
450    view: ArchiveView,
451    reader: FrameReader<BufReader<R>>,
452    writer: FrameWriter<BufWriter<W>>,
453    /// The chunk buffer of the bodies. Every body of the session uses it.
454    chunk: Vec<u8>,
455}
456
457impl<R, W> Session<R, W>
458where
459    R: AsyncRead + Unpin + Send,
460    W: AsyncWrite + Unpin + Send,
461{
462    /// Runs the session until the input ends or the session fails.
463    async fn run(&mut self) -> std::result::Result<(), Failure> {
464        match self.next().await? {
465            Some(Message::PullHello(hello)) => self.hello(hello).await?,
466            Some(other) => return Err(out_of_order(&other)),
467            None => return Ok(()),
468        }
469        loop {
470            // The futures of the reader are not cancel-safe. To learn if the
471            // next read can wait, the loop reads the buffer and polls no read.
472            if !complete_frame(self.reader.get_ref().buffer()) {
473                self.writer.flush().await.map_err(output)?;
474            }
475            match self.next().await? {
476                Some(Message::Get(path)) => self.get(&path).await?,
477                Some(Message::ListRefs(request)) => self.list_refs(&request).await?,
478                Some(other) => return Err(out_of_order(&other)),
479                None => return Ok(()),
480            }
481        }
482    }
483
484    async fn next(&mut self) -> std::result::Result<Option<Message>, Failure> {
485        self.reader.read_message().await.map_err(input)
486    }
487
488    /// Writes one message. The flush rule of the loop in `run` flushes it.
489    async fn reply(&mut self, msg: &Message) -> std::result::Result<(), Failure> {
490        self.writer.write_message(msg).await.map_err(output)
491    }
492
493    /// Sends an `Error` message and flushes the output.
494    ///
495    /// The method ignores a failure to send the message, because the peer can
496    /// be gone.
497    async fn send_error(&mut self, error: &remote::Error) {
498        let msg = Message::Error(error.to_message());
499        if self.writer.write_message(&msg).await.is_ok() {
500            let _ = self.writer.flush().await;
501        }
502    }
503
504    /// Replies with the lower of the client version and the highest server
505    /// version.
506    ///
507    /// The server speaks each version from 1 up.
508    async fn hello(&mut self, hello: PullHello) -> std::result::Result<(), Failure> {
509        if hello.version == 0 {
510            return Err(Failure::Wire(remote::Error::VersionUnsupported(format!(
511                "pull protocol version 0: the server speaks versions 1 to {PULL_PROTOCOL_VERSION}"
512            ))));
513        }
514        let version = hello.version.min(PULL_PROTOCOL_VERSION);
515        self.reply(&Message::PullHelloReply(PullHelloReply { version }))
516            .await
517    }
518
519    /// Answers one `Get`.
520    ///
521    /// The method drops the body before the next `Get`, so a built `.filez`
522    /// gives its compressor back to the view first.
523    async fn get(&mut self, path: &str) -> std::result::Result<(), Failure> {
524        let answer = self
525            .view
526            .get(path, &self.access)
527            .await
528            .map_err(Failure::Internal)?;
529        let found = |len| Message::GetReply(GetReply { found: true, len });
530        match answer {
531            ArchiveAnswer::Bytes(bytes) => {
532                self.reply(&found(Some(bytes.len() as u64))).await?;
533                write_bytes(&mut self.writer, &bytes).await
534            }
535            ArchiveAnswer::Stream { len, body } => {
536                self.reply(&found(len)).await?;
537                write_body(&mut self.writer, &mut self.chunk, len, body).await
538            }
539            ArchiveAnswer::StaleSummary { item } => {
540                if let Some(on_event) = &self.on_event
541                    && !self.stale_reported
542                {
543                    self.stale_reported = true;
544                    on_event(&SendEvent::StaleSummary {
545                        item: item.to_string(),
546                    });
547                }
548                self.reply(&not_found()).await
549            }
550            ArchiveAnswer::NotFound | ArchiveAnswer::Refused => self.reply(&not_found()).await,
551        }
552    }
553
554    /// Answers one `ListRefs` with the listing of `request`.
555    ///
556    /// Each failure comes before the reply, so the session sends an `Error`
557    /// message in place of the reply. The session reports each invalid
558    /// collection directory of the listing that it did not report before.
559    async fn list_refs(&mut self, request: &ListRefsRequest) -> std::result::Result<(), Failure> {
560        let protocol = |why: String| Failure::Wire(remote::Error::Protocol(why));
561        let collections = request.collections.as_deref();
562        let count = request.refs.len() + collections.map_or(0, <[String]>::len);
563        if count > MAX_REF_PATTERNS {
564            return Err(protocol(format!(
565                "ListRefs: {count} entries, over the limit of {MAX_REF_PATTERNS}"
566            )));
567        }
568        let lists = [
569            ("", request.refs.as_slice()),
570            ("collections: ", collections.unwrap_or_default()),
571        ];
572        for (label, entries) in lists {
573            for entry in entries {
574                if entry.len() > MAX_REF_ENTRY_LEN || entry.split('/').count() > MAX_REF_ENTRY_PARTS
575                {
576                    return Err(protocol(format!(
577                        "ListRefs: {label}an entry of {} bytes is over the limit of \
578                         {MAX_REF_ENTRY_PARTS} parts or {MAX_REF_ENTRY_LEN} bytes",
579                        entry.len()
580                    )));
581                }
582            }
583        }
584        let refs = RefSelector::parse(request.refs.iter().map(String::as_str))
585            .map_err(|e| protocol(format!("ListRefs: {e}")))?;
586        let collections = collections
587            .map(|entries| RefSelector::parse(entries.iter().map(String::as_str)))
588            .transpose()
589            .map_err(|e| protocol(format!("ListRefs: collections: {e}")))?;
590        let listing = self
591            .repo
592            .build_ref_listing_capped(&refs, collections.as_ref(), &self.access, self.listing_cap)
593            .await
594            .map_err(|e| match e {
595                Error::Remote(e @ remote::Error::LimitExceeded(_)) => Failure::Wire(e),
596                other => Failure::Internal(other),
597            })?;
598        for name in listing.invalid_collection_dirs {
599            if let Some(on_event) = &self.on_event
600                && !self.warned.contains(&name)
601            {
602                self.warned.insert(name.clone());
603                on_event(&SendEvent::InvalidCollectionDir { name });
604            }
605        }
606        let reply = GetReply {
607            found: true,
608            len: Some(listing.bytes.len() as u64),
609        };
610        self.reply(&Message::GetReply(reply)).await?;
611        write_bytes(&mut self.writer, &listing.bytes).await
612    }
613}
614
615/// Writes `bytes` as the chunks of a pull body, and ends the body.
616///
617/// The chunks have the shape that [`write_body`] gives.
618async fn write_bytes<W: AsyncWrite + Unpin>(
619    writer: &mut FrameWriter<W>,
620    bytes: &[u8],
621) -> std::result::Result<(), Failure> {
622    for chunk in bytes.chunks(CHUNK) {
623        writer.write_object_data(chunk).await.map_err(output)?;
624    }
625    writer.end_object().await.map_err(output)
626}
627
628/// Writes `body` as the chunks of a pull body, and ends the body.
629///
630/// Each chunk except the last chunk is full. If `len` is set, the function
631/// reads at most `len + 1` bytes. It abandons a body that ends sooner or
632/// holds more.
633async fn write_body<W, B>(
634    writer: &mut FrameWriter<W>,
635    chunk: &mut Vec<u8>,
636    len: Option<u64>,
637    body: B,
638) -> std::result::Result<(), Failure>
639where
640    W: AsyncWrite + Unpin,
641    B: AsyncRead + Unpin,
642{
643    if chunk.is_empty() {
644        chunk.resize(CHUNK, 0);
645    }
646    let mut body = body.take(len.map_or(u64::MAX, |len| len.saturating_add(1)));
647    let mut total = 0u64;
648    loop {
649        let n = match fill(&mut body, chunk).await {
650            Ok(n) => n,
651            Err(e) => return abandon(writer, Error::Io(e)).await,
652        };
653        total += n as u64;
654        if let Some(len) = len {
655            if total > len {
656                let e = io::Error::new(
657                    io::ErrorKind::InvalidData,
658                    "the file holds more than its stated length",
659                );
660                return abandon(writer, Error::Io(e)).await;
661            }
662            if n < CHUNK && total < len {
663                let e = io::Error::new(
664                    io::ErrorKind::UnexpectedEof,
665                    "the file ended before its stated length",
666                );
667                return abandon(writer, Error::Io(e)).await;
668            }
669        }
670        if n > 0 {
671            writer
672                .write_object_data(&chunk[..n])
673                .await
674                .map_err(output)?;
675        }
676        if n < CHUNK {
677            return writer.end_object().await.map_err(output);
678        }
679    }
680}
681
682/// Reads from `body` until `chunk` is full or the body ends.
683///
684/// A built `.filez` gives its header alone in the first read. Its deflate
685/// stream gives the output in bursts. Because of this, one read seldom fills
686/// the chunk.
687async fn fill<B: AsyncRead + Unpin>(body: &mut B, chunk: &mut [u8]) -> io::Result<usize> {
688    let mut filled = 0;
689    while filled < chunk.len() {
690        match body.read(&mut chunk[filled..]).await? {
691            0 => break,
692            n => filled += n,
693        }
694    }
695    Ok(filled)
696}
697
698/// Abandons the body with the abandon marker and an `Error` with `internal`.
699async fn abandon<W: AsyncWrite + Unpin>(
700    writer: &mut FrameWriter<W>,
701    error: Error,
702) -> std::result::Result<(), Failure> {
703    let msg = remote::Error::Internal(error.to_string()).to_message();
704    writer.abandon_body(&msg).await.map_err(output)?;
705    Err(Failure::Abandoned(error))
706}
707
708/// A compile-time check that the future of a session is `Send`.
709///
710/// The future can run on a thread pool.
711const _: fn() = || {
712    fn assert_send<T: Send>(_: T) {}
713    let _ = |repo: &Repo, access: &ReadAccess| {
714        assert_send(repo.send(futures_lite::io::empty(), futures_lite::io::sink(), access))
715    };
716    fn assert_send_sync<T: Send + Sync>() {}
717    assert_send_sync::<SendOptions>();
718    assert_send_sync::<SendEvent>();
719};
720
721#[cfg(test)]
722mod tests {
723    use std::pin::Pin;
724    use std::task::{Context, Poll};
725
726    use futures_lite::future::block_on;
727
728    use super::*;
729    use crate::remote::ErrorCode;
730    use crate::remote::proto::ObjectRead;
731
732    /// A reader that gives `ok` bytes of `0x5a` and then fails.
733    ///
734    /// If `ok` is `None`, the reader never ends. `read` counts the bytes that
735    /// the reader gave.
736    struct Source {
737        ok: Option<usize>,
738        read: usize,
739    }
740
741    impl AsyncRead for Source {
742        fn poll_read(
743            mut self: Pin<&mut Self>,
744            _cx: &mut Context<'_>,
745            buf: &mut [u8],
746        ) -> Poll<io::Result<usize>> {
747            let left = self.ok.map_or(usize::MAX, |ok| ok - self.read);
748            if left == 0 {
749                return Poll::Ready(Err(io::Error::other("the disk failed")));
750            }
751            // Short reads, as a pipe or a deflate stream gives them.
752            let n = buf.len().min(left).min(10_000);
753            buf[..n].fill(0x5a);
754            self.read += n;
755            Poll::Ready(Ok(n))
756        }
757    }
758
759    /// Writes one found reply of `len` and its body from `body` into a
760    /// buffer.
761    ///
762    /// Returns the result and the bytes written.
763    fn serve<B: AsyncRead + Unpin>(
764        len: Option<u64>,
765        body: B,
766    ) -> (std::result::Result<(), Failure>, Vec<u8>) {
767        let mut writer = FrameWriter::new(Vec::new());
768        let mut chunk = Vec::new();
769        let result = block_on(async {
770            let reply = GetReply { found: true, len };
771            writer
772                .write_message(&Message::GetReply(reply))
773                .await
774                .unwrap();
775            write_body(&mut writer, &mut chunk, len, body).await
776        });
777        (result, writer.into_inner())
778    }
779
780    /// Returns the chunk lengths after the reply frame at the start of
781    /// `bytes`.
782    ///
783    /// The list ends with the chunk of length 0 or the abandon marker.
784    fn chunk_lengths(bytes: &[u8]) -> Vec<u32> {
785        let frame = u32::from_be_bytes(bytes[..4].try_into().unwrap()) as usize;
786        let mut at = 4 + frame;
787        let mut lengths = Vec::new();
788        loop {
789            let len = u32::from_be_bytes(bytes[at..at + 4].try_into().unwrap());
790            lengths.push(len);
791            if len == 0 || len == crate::remote::proto::ABANDON {
792                return lengths;
793            }
794            at += 4 + len as usize;
795        }
796    }
797
798    /// A reader that fails partway ends the body with the abandon marker
799    /// and an `Error` with `internal`. The session writes the full chunk
800    /// before the failure and no byte after it.
801    #[test]
802    fn a_reader_that_fails_partway_abandons_the_body() {
803        let (result, bytes) = serve(
804            None,
805            Source {
806                ok: Some(100_000),
807                read: 0,
808            },
809        );
810        let Err(Failure::Abandoned(Error::Io(e))) = result else {
811            panic!("the body was not abandoned");
812        };
813        assert_eq!(e.to_string(), "the disk failed");
814        assert_eq!(
815            chunk_lengths(&bytes),
816            [CHUNK as u32, crate::remote::proto::ABANDON]
817        );
818
819        let mut reader = FrameReader::new(&bytes[..]);
820        block_on(async {
821            let reply = reader.read_message().await.unwrap();
822            assert_eq!(
823                reply,
824                Some(Message::GetReply(GetReply {
825                    found: true,
826                    len: None
827                }))
828            );
829            let mut buf = vec![0u8; 200_000];
830            let mut got = 0;
831            let err = loop {
832                match reader.read_object_data(&mut buf).await {
833                    Ok(ObjectRead::Data(n)) => got += n,
834                    Ok(other) => panic!("the body ended with {other:?}"),
835                    Err(e) => break e,
836                }
837            };
838            assert_eq!(got, CHUNK);
839            assert_eq!(err.code(), Some(ErrorCode::Internal));
840            assert_eq!(err.to_message().message, "i/o error: the disk failed");
841            assert_eq!(reader.read_message().await.unwrap(), None);
842        });
843    }
844
845    /// Each chunk except the last chunk is full. A body of a whole number of
846    /// chunks ends with the chunk of length 0 alone.
847    #[test]
848    fn each_chunk_but_the_last_is_full() {
849        for (size, expected) in [
850            (0, vec![0]),
851            (1, vec![1, 0]),
852            (CHUNK, vec![CHUNK as u32, 0]),
853            (2 * CHUNK + 1, vec![CHUNK as u32, CHUNK as u32, 1, 0]),
854        ] {
855            for len in [None, Some(size as u64)] {
856                let (result, bytes) = serve(len, &vec![7u8; size][..]);
857                assert!(result.is_ok(), "{size} {len:?}");
858                assert_eq!(chunk_lengths(&bytes), expected, "{size} {len:?}");
859            }
860        }
861    }
862
863    /// Bytes in memory go out as the chunks that a body of the same bytes
864    /// gives.
865    #[test]
866    fn bytes_take_the_chunks_of_a_body() {
867        for size in [0, 1, CHUNK, CHUNK + 1, 2 * CHUNK + 1] {
868            let data = vec![7u8; size];
869            let len = Some(size as u64);
870            let (result, expected) = serve(len, &data[..]);
871            assert!(result.is_ok(), "{size}");
872            let mut writer = FrameWriter::new(Vec::new());
873            let result = block_on(async {
874                let reply = GetReply { found: true, len };
875                writer
876                    .write_message(&Message::GetReply(reply))
877                    .await
878                    .unwrap();
879                write_bytes(&mut writer, &data).await
880            });
881            assert!(result.is_ok(), "{size}");
882            assert_eq!(writer.into_inner(), expected, "{size}");
883        }
884    }
885
886    /// A stated length limits the read to one byte past it. The session
887    /// abandons a body that ends sooner or holds more, with the error of its
888    /// kind.
889    #[test]
890    fn a_stated_length_bounds_the_read() {
891        let mut source = Source { ok: None, read: 0 };
892        let (result, bytes) = serve(Some(10), &mut source);
893        let Err(Failure::Abandoned(Error::Io(e))) = result else {
894            panic!("a long body was not abandoned");
895        };
896        assert_eq!(e.kind(), io::ErrorKind::InvalidData);
897        assert_eq!(source.read, 11);
898        assert_eq!(chunk_lengths(&bytes), [crate::remote::proto::ABANDON]);
899
900        let (result, bytes) = serve(Some(20), &[1u8; 10][..]);
901        let Err(Failure::Abandoned(Error::Io(e))) = result else {
902            panic!("a short body was not abandoned");
903        };
904        assert_eq!(e.kind(), io::ErrorKind::UnexpectedEof);
905        assert_eq!(chunk_lengths(&bytes), [crate::remote::proto::ABANDON]);
906
907        // The next read finds a body that falls short at a chunk boundary.
908        let (result, bytes) = serve(Some(CHUNK as u64 + 1), &vec![1u8; CHUNK][..]);
909        assert!(matches!(result, Err(Failure::Abandoned(_))));
910        assert_eq!(
911            chunk_lengths(&bytes),
912            [CHUNK as u32, crate::remote::proto::ABANDON]
913        );
914    }
915
916    #[test]
917    fn a_complete_frame_is_its_length_and_its_bytes() {
918        assert!(!complete_frame(&[]));
919        assert!(!complete_frame(&[0, 0, 0]));
920        assert!(!complete_frame(&[0, 0, 0, 2, 14]));
921        assert!(complete_frame(&[0, 0, 0, 2, 14, 0]));
922        assert!(complete_frame(&[0, 0, 0, 2, 14, 0, 0]));
923        assert!(!complete_frame(&[0xff, 0xff, 0xff, 0xff, 0]));
924        // A frame of length 0 is whole. The reader refuses it.
925        assert!(complete_frame(&[0, 0, 0, 0]));
926    }
927
928    /// A ref listing over the cap of the session is `limit-exceeded` in place
929    /// of the reply. A listing of exactly the cap goes out whole.
930    #[test]
931    fn a_ref_listing_over_the_cap_is_limit_exceeded() {
932        let dir = std::env::temp_dir().join(format!(
933            "ostrya-send-listing-cap-{}-{}",
934            std::process::id(),
935            crate::write::unique()
936        ));
937        let _ = std::fs::remove_dir_all(&dir);
938        ostrya_rt::block_on(async {
939            let repo = Repo::create(&dir, crate::CreateOptions::new(crate::RepoMode::BareUser))
940                .await
941                .unwrap();
942            let config =
943                crate::RepoConfig::parse("[core]\nrepo_version=1\nmode=bare-user\n").unwrap();
944            let access = crate::access::ClientAccess::from_config(&config, &dir).unwrap();
945            let access = ReadAccess::new(
946                std::sync::Arc::new(access),
947                crate::access::AuthItem::Anonymous,
948                None,
949            );
950            let listing = repo
951                .build_ref_listing(&crate::RefSelector::parse([]).unwrap(), None, &access)
952                .await
953                .unwrap()
954                .bytes;
955            let mut input = FrameWriter::new(Vec::new());
956            for msg in [
957                Message::PullHello(PullHello {
958                    version: 1,
959                    agent: None,
960                }),
961                Message::ListRefs(ListRefsRequest::default()),
962            ] {
963                input.write_message(&msg).await.unwrap();
964            }
965            let input = input.into_inner();
966
967            let mut out = Vec::new();
968            let result = repo
969                .send_capped(
970                    &input[..],
971                    &mut out,
972                    &access,
973                    &SendOptions::default(),
974                    listing.len() as u64 - 1,
975                )
976                .await;
977            assert!(
978                matches!(result, Err(Error::Remote(remote::Error::LimitExceeded(_)))),
979                "{result:?}"
980            );
981            let mut reader = FrameReader::new(&out[..]);
982            assert!(matches!(
983                reader.read_message().await.unwrap(),
984                Some(Message::PullHelloReply(_))
985            ));
986            let Some(Message::Error(e)) = reader.read_message().await.unwrap() else {
987                panic!("the session sent no Error");
988            };
989            assert_eq!(e.code, ErrorCode::LimitExceeded);
990            assert_eq!(reader.read_message().await.unwrap(), None);
991
992            let mut out = Vec::new();
993            repo.send_capped(
994                &input[..],
995                &mut out,
996                &access,
997                &SendOptions::default(),
998                listing.len() as u64,
999            )
1000            .await
1001            .unwrap();
1002            let mut reader = FrameReader::new(&out[..]);
1003            reader.read_message().await.unwrap();
1004            assert_eq!(
1005                reader.read_message().await.unwrap(),
1006                Some(Message::GetReply(GetReply {
1007                    found: true,
1008                    len: Some(listing.len() as u64)
1009                }))
1010            );
1011            let mut body = Vec::new();
1012            let mut buf = vec![0u8; 4096];
1013            loop {
1014                match reader.read_object_data(&mut buf).await.unwrap() {
1015                    ObjectRead::Data(n) => body.extend_from_slice(&buf[..n]),
1016                    ObjectRead::End => break,
1017                    ObjectRead::Abandoned => panic!("the body was abandoned"),
1018                }
1019            }
1020            assert_eq!(body, listing);
1021            assert_eq!(reader.read_message().await.unwrap(), None);
1022        });
1023        let _ = std::fs::remove_dir_all(&dir);
1024    }
1025
1026    /// The line of an invalid collection directory names its path and
1027    /// escapes each control character.
1028    #[test]
1029    fn the_line_of_an_invalid_collection_dir_escapes_control_characters() {
1030        let event = SendEvent::InvalidCollectionDir {
1031            name: "bad\nforged line\t\u{7f}".to_owned(),
1032        };
1033        assert_eq!(
1034            event.to_string(),
1035            "refs/mirrors/bad\\nforged line\\t\\u{7f}: the directory name is not a \
1036             collection id, and the ref listing leaves out the directory"
1037        );
1038    }
1039
1040    /// The escaped text keeps each run of other characters and escapes each
1041    /// control character at the start, in the middle, and at the end.
1042    #[test]
1043    fn the_escaped_text_keeps_the_runs_between_control_characters() {
1044        struct Escaped {
1045            inner: &'static str,
1046        }
1047        impl fmt::Display for Escaped {
1048            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1049                write_escaped(f, self.inner)
1050            }
1051        }
1052        for (text, expected) in [
1053            ("", ""),
1054            ("plain é name", "plain é name"),
1055            ("\n", "\\n"),
1056            ("\tab\r\ncd\u{1b}é\u{7f}", "\\tab\\r\\ncd\\u{1b}é\\u{7f}"),
1057            ("\0start", "\\u{0}start"),
1058            ("mid\u{1}dle", "mid\\u{1}dle"),
1059            ("end\n", "end\\n"),
1060        ] {
1061            assert_eq!(Escaped { inner: text }.to_string(), expected, "{text:?}");
1062        }
1063    }
1064
1065    /// The chunk payload is equal to the chunk payload of the push, so the
1066    /// two directions write the same shape.
1067    #[test]
1068    fn the_chunk_and_the_buffer_fill_one_write() {
1069        assert_eq!(CHUNK, 65_532);
1070        assert_eq!(CHUNK + 4, STREAM_BUFFER);
1071    }
1072}