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    /// or `bare-user-shared` repository, read access to the repository is
266    /// sufficient, because each object has the inode mode 0644. For a
267    /// `bare-user` or `bare-user-only` repository, the account must have read
268    /// permission on each content object. The logical mode of the file sets
269    /// the inode mode of its object, so a file with the logical mode 0600 has
270    /// an object with the inode mode 0600. Each content object of a
271    /// `bare-user-private` repository has the inode mode 0400, so the account
272    /// must be the owner of each content object or have privilege. For a
273    /// `bare` or `bare-split-xattrs` repository, the account must be able to
274    /// read every object and its extended attributes.
275    ///
276    /// # Framing and memory
277    ///
278    /// The frame limit is [`MIN_FRAME_LIMIT`](crate::remote::proto::MIN_FRAME_LIMIT)
279    /// in the two directions. Each direction goes through a buffer of 64 KiB.
280    /// Each chunk of a body, except the last chunk, holds 64 KiB less 4 bytes.
281    ///
282    /// A body streams through one chunk buffer, so no content object is whole
283    /// in memory. For a stored file, the session reads at most one byte past
284    /// the stated length. A ref listing is whole in memory, up to
285    /// [`MAX_REF_LISTING`] bytes.
286    ///
287    /// The memory of a session is the two stream buffers, the chunk buffer,
288    /// one `Get` frame, and the reader of the current body. That reader is a
289    /// `FileReader` with a read-ahead of 4 KiB to 256 KiB, or a compressor and
290    /// two buffers of 64 KiB for a built `.filez`. A `Get` frame at the frame
291    /// limit adds about 2 MiB, because the frame body and the decoded path are
292    /// in memory at the same time.
293    ///
294    /// If the input buffer holds no whole frame, the next read can wait. The
295    /// session flushes `output` before that read. It also flushes `output`
296    /// after each `Error` message.
297    ///
298    /// # End of a session
299    ///
300    /// At an end of file of `input` at a frame boundary, the method returns
301    /// `Ok`. An empty `input` also gives `Ok`. Every other end of the session
302    /// is an error. The session tells the peer about the failure:
303    ///
304    /// - If the failure has a wire code, the session sends an `Error` message
305    ///   with that code.
306    /// - If the view fails before the reply, the session sends an `Error`
307    ///   message with the code `internal` in place of the reply. A file that
308    ///   the process cannot read is an example.
309    /// - If a read of `input` fails with an error other than an end of file,
310    ///   the session sends an `Error` message with the code `internal`.
311    /// - If a body fails after its reply, the session ends the body with the
312    ///   abandon marker and an `Error` message with the code `internal`.
313    /// - If a write of a reply or of a body to `output` fails, the session
314    ///   sends nothing more.
315    ///
316    /// If the session cannot deliver the `Error` message, the returned error
317    /// does not change.
318    ///
319    /// # Errors
320    ///
321    /// - [`Error::Remote`] with the code `version-unsupported` if the
322    ///   `PullHello` states version 0.
323    /// - [`Error::Remote`] with the code `protocol` if a message is out of
324    ///   order or is a kind of the push.
325    /// - [`Error::Remote`] with the code `protocol` if a frame is malformed, or
326    ///   if `input` ends inside a frame.
327    /// - [`Error::Remote`] with the code `protocol` if a `ListRefs` holds more
328    ///   than [`MAX_REF_PATTERNS`] entries in its two lists, an entry over the
329    ///   limits of one entry, or an entry that [`RefSelector::parse`]
330    ///   refuses. An entry given two times counts two times. The check of the
331    ///   limits of an entry comes before the parse. The message of a refused
332    ///   entry under `collections` names that key.
333    /// - [`Error::Remote`] with the code `limit-exceeded` if a ref listing is
334    ///   larger than [`MAX_REF_LISTING`].
335    /// - [`Error::Remote`] with the code `limit-exceeded` if a frame is larger
336    ///   than the limit.
337    /// - [`Error::Remote`] with the code `internal` if the codec refuses a
338    ///   message that the session writes.
339    /// - Each error of [`ArchiveView::get`] if the view fails before the
340    ///   reply.
341    /// - Each other error of [`build_ref_listing`](Repo::build_ref_listing).
342    ///   The session sends it as `internal`.
343    /// - [`Error::Io`] if a read of `input` fails with an error other than an
344    ///   end of file.
345    /// - [`Error::Io`] with the error of the read if a body fails after its
346    ///   reply. For a stored file that ends before its stated length, the
347    ///   kind is `UnexpectedEof`. For a stored file that holds more, the kind
348    ///   is `InvalidData`.
349    /// - [`Error::Io`] if a write of a reply or of a body to `output` fails.
350    pub async fn send<R, W>(&self, input: R, output: W, access: &ReadAccess) -> Result<()>
351    where
352        R: AsyncRead + Unpin + Send,
353        W: AsyncWrite + Unpin + Send,
354    {
355        self.send_with(input, output, access, &SendOptions::default())
356            .await
357    }
358
359    /// Serves one pull session as [`send`](Repo::send) does, with the
360    /// options `opts`.
361    ///
362    /// The session gives each [`SendEvent`] to
363    /// [`SendOptions::on_event`]. A ref listing of a `ListRefs` with the
364    /// `collections` key reads the top level of `refs/mirrors/`. For each
365    /// directory there whose name fails the collection-id rule, the session
366    /// gives one [`SendEvent::InvalidCollectionDir`], at the first listing
367    /// that finds it. The listing leaves out the directory. The event does
368    /// not change the session, and the peer gets no message of it.
369    ///
370    /// When the view answers `summary` or `summary.sig` with
371    /// [`ArchiveAnswer::StaleSummary`], the session gives one
372    /// [`SendEvent::StaleSummary`], at the first such answer. The peer gets a
373    /// `GetReply` with `found` set to `false`, as for an absent path.
374    ///
375    /// # Errors
376    ///
377    /// The errors of [`send`](Repo::send).
378    pub async fn send_with<R, W>(
379        &self,
380        input: R,
381        output: W,
382        access: &ReadAccess,
383        opts: &SendOptions,
384    ) -> Result<()>
385    where
386        R: AsyncRead + Unpin + Send,
387        W: AsyncWrite + Unpin + Send,
388    {
389        self.send_capped(input, output, access, opts, MAX_REF_LISTING)
390            .await
391    }
392
393    /// Serves the session of [`send_with`](Repo::send_with) with a cap of
394    /// `listing_cap` bytes on each ref listing.
395    pub(crate) async fn send_capped<R, W>(
396        &self,
397        input: R,
398        output: W,
399        access: &ReadAccess,
400        opts: &SendOptions,
401        listing_cap: u64,
402    ) -> Result<()>
403    where
404        R: AsyncRead + Unpin + Send,
405        W: AsyncWrite + Unpin + Send,
406    {
407        let mut session = Session {
408            repo: self.clone(),
409            access: access.clone(),
410            listing_cap,
411            on_event: opts.on_event.clone(),
412            warned: HashSet::new(),
413            stale_reported: false,
414            view: ArchiveView::new(self.clone()),
415            reader: FrameReader::new(BufReader::with_capacity(STREAM_BUFFER, input)),
416            writer: FrameWriter::new(BufWriter::with_capacity(STREAM_BUFFER, output)),
417            chunk: Vec::new(),
418        };
419        let failure = match session.run().await {
420            Ok(()) => return Ok(()),
421            Err(failure) => failure,
422        };
423        Err(match failure {
424            Failure::Wire(e) => {
425                session.send_error(&e).await;
426                Error::Remote(e)
427            }
428            Failure::Internal(e) => {
429                session
430                    .send_error(&remote::Error::Internal(e.to_string()))
431                    .await;
432                e
433            }
434            Failure::Abandoned(e) => {
435                let _ = session.writer.flush().await;
436                e
437            }
438            Failure::Silent(e) => e,
439        })
440    }
441}
442
443struct Session<R, W> {
444    repo: Repo,
445    /// The read rights of the client.
446    access: ReadAccess,
447    /// The size cap of each ref listing.
448    listing_cap: u64,
449    /// The callback of the events of the session.
450    on_event: Option<SendEventFn>,
451    /// The names of the invalid collection directories that the session
452    /// reported.
453    warned: HashSet<String>,
454    /// `true` once the session reported a stale summary.
455    stale_reported: bool,
456    view: ArchiveView,
457    reader: FrameReader<BufReader<R>>,
458    writer: FrameWriter<BufWriter<W>>,
459    /// The chunk buffer of the bodies. Every body of the session uses it.
460    chunk: Vec<u8>,
461}
462
463impl<R, W> Session<R, W>
464where
465    R: AsyncRead + Unpin + Send,
466    W: AsyncWrite + Unpin + Send,
467{
468    /// Runs the session until the input ends or the session fails.
469    async fn run(&mut self) -> std::result::Result<(), Failure> {
470        match self.next().await? {
471            Some(Message::PullHello(hello)) => self.hello(hello).await?,
472            Some(other) => return Err(out_of_order(&other)),
473            None => return Ok(()),
474        }
475        loop {
476            // The futures of the reader are not cancel-safe. To learn if the
477            // next read can wait, the loop reads the buffer and polls no read.
478            if !complete_frame(self.reader.get_ref().buffer()) {
479                self.writer.flush().await.map_err(output)?;
480            }
481            match self.next().await? {
482                Some(Message::Get(path)) => self.get(&path).await?,
483                Some(Message::ListRefs(request)) => self.list_refs(&request).await?,
484                Some(other) => return Err(out_of_order(&other)),
485                None => return Ok(()),
486            }
487        }
488    }
489
490    async fn next(&mut self) -> std::result::Result<Option<Message>, Failure> {
491        self.reader.read_message().await.map_err(input)
492    }
493
494    /// Writes one message. The flush rule of the loop in `run` flushes it.
495    async fn reply(&mut self, msg: &Message) -> std::result::Result<(), Failure> {
496        self.writer.write_message(msg).await.map_err(output)
497    }
498
499    /// Sends an `Error` message and flushes the output.
500    ///
501    /// The method ignores a failure to send the message, because the peer can
502    /// be gone.
503    async fn send_error(&mut self, error: &remote::Error) {
504        let msg = Message::Error(error.to_message());
505        if self.writer.write_message(&msg).await.is_ok() {
506            let _ = self.writer.flush().await;
507        }
508    }
509
510    /// Replies with the lower of the client version and the highest server
511    /// version.
512    ///
513    /// The server speaks each version from 1 up.
514    async fn hello(&mut self, hello: PullHello) -> std::result::Result<(), Failure> {
515        if hello.version == 0 {
516            return Err(Failure::Wire(remote::Error::VersionUnsupported(format!(
517                "pull protocol version 0: the server speaks versions 1 to {PULL_PROTOCOL_VERSION}"
518            ))));
519        }
520        let version = hello.version.min(PULL_PROTOCOL_VERSION);
521        self.reply(&Message::PullHelloReply(PullHelloReply { version }))
522            .await
523    }
524
525    /// Answers one `Get`.
526    ///
527    /// The method drops the body before the next `Get`, so a built `.filez`
528    /// gives its compressor back to the view first.
529    async fn get(&mut self, path: &str) -> std::result::Result<(), Failure> {
530        let answer = self
531            .view
532            .get(path, &self.access)
533            .await
534            .map_err(Failure::Internal)?;
535        let found = |len| Message::GetReply(GetReply { found: true, len });
536        match answer {
537            ArchiveAnswer::Bytes(bytes) => {
538                self.reply(&found(Some(bytes.len() as u64))).await?;
539                write_bytes(&mut self.writer, &bytes).await
540            }
541            ArchiveAnswer::Stream { len, body } => {
542                self.reply(&found(len)).await?;
543                write_body(&mut self.writer, &mut self.chunk, len, body).await
544            }
545            ArchiveAnswer::StaleSummary { item } => {
546                if let Some(on_event) = &self.on_event
547                    && !self.stale_reported
548                {
549                    self.stale_reported = true;
550                    on_event(&SendEvent::StaleSummary {
551                        item: item.to_string(),
552                    });
553                }
554                self.reply(&not_found()).await
555            }
556            ArchiveAnswer::NotFound | ArchiveAnswer::Refused => self.reply(&not_found()).await,
557        }
558    }
559
560    /// Answers one `ListRefs` with the listing of `request`.
561    ///
562    /// Each failure comes before the reply, so the session sends an `Error`
563    /// message in place of the reply. The session reports each invalid
564    /// collection directory of the listing that it did not report before.
565    async fn list_refs(&mut self, request: &ListRefsRequest) -> std::result::Result<(), Failure> {
566        let protocol = |why: String| Failure::Wire(remote::Error::Protocol(why));
567        let collections = request.collections.as_deref();
568        let count = request.refs.len() + collections.map_or(0, <[String]>::len);
569        if count > MAX_REF_PATTERNS {
570            return Err(protocol(format!(
571                "ListRefs: {count} entries, over the limit of {MAX_REF_PATTERNS}"
572            )));
573        }
574        let lists = [
575            ("", request.refs.as_slice()),
576            ("collections: ", collections.unwrap_or_default()),
577        ];
578        for (label, entries) in lists {
579            for entry in entries {
580                if entry.len() > MAX_REF_ENTRY_LEN || entry.split('/').count() > MAX_REF_ENTRY_PARTS
581                {
582                    return Err(protocol(format!(
583                        "ListRefs: {label}an entry of {} bytes is over the limit of \
584                         {MAX_REF_ENTRY_PARTS} parts or {MAX_REF_ENTRY_LEN} bytes",
585                        entry.len()
586                    )));
587                }
588            }
589        }
590        let refs = RefSelector::parse(request.refs.iter().map(String::as_str))
591            .map_err(|e| protocol(format!("ListRefs: {e}")))?;
592        let collections = collections
593            .map(|entries| RefSelector::parse(entries.iter().map(String::as_str)))
594            .transpose()
595            .map_err(|e| protocol(format!("ListRefs: collections: {e}")))?;
596        let listing = self
597            .repo
598            .build_ref_listing_capped(&refs, collections.as_ref(), &self.access, self.listing_cap)
599            .await
600            .map_err(|e| match e {
601                Error::Remote(e @ remote::Error::LimitExceeded(_)) => Failure::Wire(e),
602                other => Failure::Internal(other),
603            })?;
604        for name in listing.invalid_collection_dirs {
605            if let Some(on_event) = &self.on_event
606                && !self.warned.contains(&name)
607            {
608                self.warned.insert(name.clone());
609                on_event(&SendEvent::InvalidCollectionDir { name });
610            }
611        }
612        let reply = GetReply {
613            found: true,
614            len: Some(listing.bytes.len() as u64),
615        };
616        self.reply(&Message::GetReply(reply)).await?;
617        write_bytes(&mut self.writer, &listing.bytes).await
618    }
619}
620
621/// Writes `bytes` as the chunks of a pull body, and ends the body.
622///
623/// The chunks have the shape that [`write_body`] gives.
624async fn write_bytes<W: AsyncWrite + Unpin>(
625    writer: &mut FrameWriter<W>,
626    bytes: &[u8],
627) -> std::result::Result<(), Failure> {
628    for chunk in bytes.chunks(CHUNK) {
629        writer.write_object_data(chunk).await.map_err(output)?;
630    }
631    writer.end_object().await.map_err(output)
632}
633
634/// Writes `body` as the chunks of a pull body, and ends the body.
635///
636/// Each chunk except the last chunk is full. If `len` is set, the function
637/// reads at most `len + 1` bytes. It abandons a body that ends sooner or
638/// holds more.
639async fn write_body<W, B>(
640    writer: &mut FrameWriter<W>,
641    chunk: &mut Vec<u8>,
642    len: Option<u64>,
643    body: B,
644) -> std::result::Result<(), Failure>
645where
646    W: AsyncWrite + Unpin,
647    B: AsyncRead + Unpin,
648{
649    if chunk.is_empty() {
650        chunk.resize(CHUNK, 0);
651    }
652    let mut body = body.take(len.map_or(u64::MAX, |len| len.saturating_add(1)));
653    let mut total = 0u64;
654    loop {
655        let n = match fill(&mut body, chunk).await {
656            Ok(n) => n,
657            Err(e) => return abandon(writer, Error::Io(e)).await,
658        };
659        total += n as u64;
660        if let Some(len) = len {
661            if total > len {
662                let e = io::Error::new(
663                    io::ErrorKind::InvalidData,
664                    "the file holds more than its stated length",
665                );
666                return abandon(writer, Error::Io(e)).await;
667            }
668            if n < CHUNK && total < len {
669                let e = io::Error::new(
670                    io::ErrorKind::UnexpectedEof,
671                    "the file ended before its stated length",
672                );
673                return abandon(writer, Error::Io(e)).await;
674            }
675        }
676        if n > 0 {
677            writer
678                .write_object_data(&chunk[..n])
679                .await
680                .map_err(output)?;
681        }
682        if n < CHUNK {
683            return writer.end_object().await.map_err(output);
684        }
685    }
686}
687
688/// Reads from `body` until `chunk` is full or the body ends.
689///
690/// A built `.filez` gives its header alone in the first read. Its deflate
691/// stream gives the output in bursts. Because of this, one read seldom fills
692/// the chunk.
693async fn fill<B: AsyncRead + Unpin>(body: &mut B, chunk: &mut [u8]) -> io::Result<usize> {
694    let mut filled = 0;
695    while filled < chunk.len() {
696        match body.read(&mut chunk[filled..]).await? {
697            0 => break,
698            n => filled += n,
699        }
700    }
701    Ok(filled)
702}
703
704/// Abandons the body with the abandon marker and an `Error` with `internal`.
705async fn abandon<W: AsyncWrite + Unpin>(
706    writer: &mut FrameWriter<W>,
707    error: Error,
708) -> std::result::Result<(), Failure> {
709    let msg = remote::Error::Internal(error.to_string()).to_message();
710    writer.abandon_body(&msg).await.map_err(output)?;
711    Err(Failure::Abandoned(error))
712}
713
714/// A compile-time check that the future of a session is `Send`.
715///
716/// The future can run on a thread pool.
717const _: fn() = || {
718    fn assert_send<T: Send>(_: T) {}
719    let _ = |repo: &Repo, access: &ReadAccess| {
720        assert_send(repo.send(futures_lite::io::empty(), futures_lite::io::sink(), access))
721    };
722    fn assert_send_sync<T: Send + Sync>() {}
723    assert_send_sync::<SendOptions>();
724    assert_send_sync::<SendEvent>();
725};
726
727#[cfg(test)]
728mod tests {
729    use std::pin::Pin;
730    use std::task::{Context, Poll};
731
732    use futures_lite::future::block_on;
733
734    use super::*;
735    use crate::remote::ErrorCode;
736    use crate::remote::proto::ObjectRead;
737
738    /// A reader that gives `ok` bytes of `0x5a` and then fails.
739    ///
740    /// If `ok` is `None`, the reader never ends. `read` counts the bytes that
741    /// the reader gave.
742    struct Source {
743        ok: Option<usize>,
744        read: usize,
745    }
746
747    impl AsyncRead for Source {
748        fn poll_read(
749            mut self: Pin<&mut Self>,
750            _cx: &mut Context<'_>,
751            buf: &mut [u8],
752        ) -> Poll<io::Result<usize>> {
753            let left = self.ok.map_or(usize::MAX, |ok| ok - self.read);
754            if left == 0 {
755                return Poll::Ready(Err(io::Error::other("the disk failed")));
756            }
757            // Short reads, as a pipe or a deflate stream gives them.
758            let n = buf.len().min(left).min(10_000);
759            buf[..n].fill(0x5a);
760            self.read += n;
761            Poll::Ready(Ok(n))
762        }
763    }
764
765    /// Writes one found reply of `len` and its body from `body` into a
766    /// buffer.
767    ///
768    /// Returns the result and the bytes written.
769    fn serve<B: AsyncRead + Unpin>(
770        len: Option<u64>,
771        body: B,
772    ) -> (std::result::Result<(), Failure>, Vec<u8>) {
773        let mut writer = FrameWriter::new(Vec::new());
774        let mut chunk = Vec::new();
775        let result = block_on(async {
776            let reply = GetReply { found: true, len };
777            writer
778                .write_message(&Message::GetReply(reply))
779                .await
780                .unwrap();
781            write_body(&mut writer, &mut chunk, len, body).await
782        });
783        (result, writer.into_inner())
784    }
785
786    /// Returns the chunk lengths after the reply frame at the start of
787    /// `bytes`.
788    ///
789    /// The list ends with the chunk of length 0 or the abandon marker.
790    fn chunk_lengths(bytes: &[u8]) -> Vec<u32> {
791        let frame = u32::from_be_bytes(bytes[..4].try_into().unwrap()) as usize;
792        let mut at = 4 + frame;
793        let mut lengths = Vec::new();
794        loop {
795            let len = u32::from_be_bytes(bytes[at..at + 4].try_into().unwrap());
796            lengths.push(len);
797            if len == 0 || len == crate::remote::proto::ABANDON {
798                return lengths;
799            }
800            at += 4 + len as usize;
801        }
802    }
803
804    /// A reader that fails partway ends the body with the abandon marker
805    /// and an `Error` with `internal`. The session writes the full chunk
806    /// before the failure and no byte after it.
807    #[test]
808    fn a_reader_that_fails_partway_abandons_the_body() {
809        let (result, bytes) = serve(
810            None,
811            Source {
812                ok: Some(100_000),
813                read: 0,
814            },
815        );
816        let Err(Failure::Abandoned(Error::Io(e))) = result else {
817            panic!("the body was not abandoned");
818        };
819        assert_eq!(e.to_string(), "the disk failed");
820        assert_eq!(
821            chunk_lengths(&bytes),
822            [CHUNK as u32, crate::remote::proto::ABANDON]
823        );
824
825        let mut reader = FrameReader::new(&bytes[..]);
826        block_on(async {
827            let reply = reader.read_message().await.unwrap();
828            assert_eq!(
829                reply,
830                Some(Message::GetReply(GetReply {
831                    found: true,
832                    len: None
833                }))
834            );
835            let mut buf = vec![0u8; 200_000];
836            let mut got = 0;
837            let err = loop {
838                match reader.read_object_data(&mut buf).await {
839                    Ok(ObjectRead::Data(n)) => got += n,
840                    Ok(other) => panic!("the body ended with {other:?}"),
841                    Err(e) => break e,
842                }
843            };
844            assert_eq!(got, CHUNK);
845            assert_eq!(err.code(), Some(ErrorCode::Internal));
846            assert_eq!(err.to_message().message, "i/o error: the disk failed");
847            assert_eq!(reader.read_message().await.unwrap(), None);
848        });
849    }
850
851    /// Each chunk except the last chunk is full. A body of a whole number of
852    /// chunks ends with the chunk of length 0 alone.
853    #[test]
854    fn each_chunk_but_the_last_is_full() {
855        for (size, expected) in [
856            (0, vec![0]),
857            (1, vec![1, 0]),
858            (CHUNK, vec![CHUNK as u32, 0]),
859            (2 * CHUNK + 1, vec![CHUNK as u32, CHUNK as u32, 1, 0]),
860        ] {
861            for len in [None, Some(size as u64)] {
862                let (result, bytes) = serve(len, &vec![7u8; size][..]);
863                assert!(result.is_ok(), "{size} {len:?}");
864                assert_eq!(chunk_lengths(&bytes), expected, "{size} {len:?}");
865            }
866        }
867    }
868
869    /// Bytes in memory go out as the chunks that a body of the same bytes
870    /// gives.
871    #[test]
872    fn bytes_take_the_chunks_of_a_body() {
873        for size in [0, 1, CHUNK, CHUNK + 1, 2 * CHUNK + 1] {
874            let data = vec![7u8; size];
875            let len = Some(size as u64);
876            let (result, expected) = serve(len, &data[..]);
877            assert!(result.is_ok(), "{size}");
878            let mut writer = FrameWriter::new(Vec::new());
879            let result = block_on(async {
880                let reply = GetReply { found: true, len };
881                writer
882                    .write_message(&Message::GetReply(reply))
883                    .await
884                    .unwrap();
885                write_bytes(&mut writer, &data).await
886            });
887            assert!(result.is_ok(), "{size}");
888            assert_eq!(writer.into_inner(), expected, "{size}");
889        }
890    }
891
892    /// A stated length limits the read to one byte past it. The session
893    /// abandons a body that ends sooner or holds more, with the error of its
894    /// kind.
895    #[test]
896    fn a_stated_length_bounds_the_read() {
897        let mut source = Source { ok: None, read: 0 };
898        let (result, bytes) = serve(Some(10), &mut source);
899        let Err(Failure::Abandoned(Error::Io(e))) = result else {
900            panic!("a long body was not abandoned");
901        };
902        assert_eq!(e.kind(), io::ErrorKind::InvalidData);
903        assert_eq!(source.read, 11);
904        assert_eq!(chunk_lengths(&bytes), [crate::remote::proto::ABANDON]);
905
906        let (result, bytes) = serve(Some(20), &[1u8; 10][..]);
907        let Err(Failure::Abandoned(Error::Io(e))) = result else {
908            panic!("a short body was not abandoned");
909        };
910        assert_eq!(e.kind(), io::ErrorKind::UnexpectedEof);
911        assert_eq!(chunk_lengths(&bytes), [crate::remote::proto::ABANDON]);
912
913        // The next read finds a body that falls short at a chunk boundary.
914        let (result, bytes) = serve(Some(CHUNK as u64 + 1), &vec![1u8; CHUNK][..]);
915        assert!(matches!(result, Err(Failure::Abandoned(_))));
916        assert_eq!(
917            chunk_lengths(&bytes),
918            [CHUNK as u32, crate::remote::proto::ABANDON]
919        );
920    }
921
922    #[test]
923    fn a_complete_frame_is_its_length_and_its_bytes() {
924        assert!(!complete_frame(&[]));
925        assert!(!complete_frame(&[0, 0, 0]));
926        assert!(!complete_frame(&[0, 0, 0, 2, 14]));
927        assert!(complete_frame(&[0, 0, 0, 2, 14, 0]));
928        assert!(complete_frame(&[0, 0, 0, 2, 14, 0, 0]));
929        assert!(!complete_frame(&[0xff, 0xff, 0xff, 0xff, 0]));
930        // A frame of length 0 is whole. The reader refuses it.
931        assert!(complete_frame(&[0, 0, 0, 0]));
932    }
933
934    /// A ref listing over the cap of the session is `limit-exceeded` in place
935    /// of the reply. A listing of exactly the cap goes out whole.
936    #[test]
937    fn a_ref_listing_over_the_cap_is_limit_exceeded() {
938        let dir = std::env::temp_dir().join(format!(
939            "ostrya-send-listing-cap-{}-{}",
940            std::process::id(),
941            crate::write::unique()
942        ));
943        let _ = std::fs::remove_dir_all(&dir);
944        ostrya_rt::block_on(async {
945            let repo = Repo::create(&dir, crate::CreateOptions::new(crate::RepoMode::BareUser))
946                .await
947                .unwrap();
948            let config =
949                crate::RepoConfig::parse("[core]\nrepo_version=1\nmode=bare-user\n").unwrap();
950            let access = crate::access::ClientAccess::from_config(&config).unwrap();
951            let access = ReadAccess::new(
952                std::sync::Arc::new(access),
953                crate::access::AuthItem::Anonymous,
954                None,
955            );
956            let listing = repo
957                .build_ref_listing(&crate::RefSelector::parse([]).unwrap(), None, &access)
958                .await
959                .unwrap()
960                .bytes;
961            let mut input = FrameWriter::new(Vec::new());
962            for msg in [
963                Message::PullHello(PullHello {
964                    version: 1,
965                    agent: None,
966                }),
967                Message::ListRefs(ListRefsRequest::default()),
968            ] {
969                input.write_message(&msg).await.unwrap();
970            }
971            let input = input.into_inner();
972
973            let mut out = Vec::new();
974            let result = repo
975                .send_capped(
976                    &input[..],
977                    &mut out,
978                    &access,
979                    &SendOptions::default(),
980                    listing.len() as u64 - 1,
981                )
982                .await;
983            assert!(
984                matches!(result, Err(Error::Remote(remote::Error::LimitExceeded(_)))),
985                "{result:?}"
986            );
987            let mut reader = FrameReader::new(&out[..]);
988            assert!(matches!(
989                reader.read_message().await.unwrap(),
990                Some(Message::PullHelloReply(_))
991            ));
992            let Some(Message::Error(e)) = reader.read_message().await.unwrap() else {
993                panic!("the session sent no Error");
994            };
995            assert_eq!(e.code, ErrorCode::LimitExceeded);
996            assert_eq!(reader.read_message().await.unwrap(), None);
997
998            let mut out = Vec::new();
999            repo.send_capped(
1000                &input[..],
1001                &mut out,
1002                &access,
1003                &SendOptions::default(),
1004                listing.len() as u64,
1005            )
1006            .await
1007            .unwrap();
1008            let mut reader = FrameReader::new(&out[..]);
1009            reader.read_message().await.unwrap();
1010            assert_eq!(
1011                reader.read_message().await.unwrap(),
1012                Some(Message::GetReply(GetReply {
1013                    found: true,
1014                    len: Some(listing.len() as u64)
1015                }))
1016            );
1017            let mut body = Vec::new();
1018            let mut buf = vec![0u8; 4096];
1019            loop {
1020                match reader.read_object_data(&mut buf).await.unwrap() {
1021                    ObjectRead::Data(n) => body.extend_from_slice(&buf[..n]),
1022                    ObjectRead::End => break,
1023                    ObjectRead::Abandoned => panic!("the body was abandoned"),
1024                }
1025            }
1026            assert_eq!(body, listing);
1027            assert_eq!(reader.read_message().await.unwrap(), None);
1028        });
1029        let _ = std::fs::remove_dir_all(&dir);
1030    }
1031
1032    /// The line of an invalid collection directory names its path and
1033    /// escapes each control character.
1034    #[test]
1035    fn the_line_of_an_invalid_collection_dir_escapes_control_characters() {
1036        let event = SendEvent::InvalidCollectionDir {
1037            name: "bad\nforged line\t\u{7f}".to_owned(),
1038        };
1039        assert_eq!(
1040            event.to_string(),
1041            "refs/mirrors/bad\\nforged line\\t\\u{7f}: the directory name is not a \
1042             collection id, and the ref listing leaves out the directory"
1043        );
1044    }
1045
1046    /// The escaped text keeps each run of other characters and escapes each
1047    /// control character at the start, in the middle, and at the end.
1048    #[test]
1049    fn the_escaped_text_keeps_the_runs_between_control_characters() {
1050        struct Escaped {
1051            inner: &'static str,
1052        }
1053        impl fmt::Display for Escaped {
1054            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1055                write_escaped(f, self.inner)
1056            }
1057        }
1058        for (text, expected) in [
1059            ("", ""),
1060            ("plain é name", "plain é name"),
1061            ("\n", "\\n"),
1062            ("\tab\r\ncd\u{1b}é\u{7f}", "\\tab\\r\\ncd\\u{1b}é\\u{7f}"),
1063            ("\0start", "\\u{0}start"),
1064            ("mid\u{1}dle", "mid\\u{1}dle"),
1065            ("end\n", "end\\n"),
1066        ] {
1067            assert_eq!(Escaped { inner: text }.to_string(), expected, "{text:?}");
1068        }
1069    }
1070
1071    /// The chunk payload is equal to the chunk payload of the push, so the
1072    /// two directions write the same shape.
1073    #[test]
1074    fn the_chunk_and_the_buffer_fill_one_write() {
1075        assert_eq!(CHUNK, 65_532);
1076        assert_eq!(CHUNK + 4, STREAM_BUFFER);
1077    }
1078}