ostrya_remote/session/pull.rs
1//! The client session of a pull: the pipeline of `Get` and `ListRefs` frames
2//! and the bodies of the replies.
3
4use std::collections::btree_map::Entry;
5use std::collections::{BTreeMap, HashSet};
6use std::future::{Future, poll_fn};
7use std::io;
8use std::pin::Pin;
9use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
10use std::task::{Context, Poll, Waker, ready};
11use std::time::Duration;
12
13use futures_io::{AsyncRead, AsyncWrite};
14use futures_lite::io::{AsyncWriteExt, BufReader};
15use ostrya_core::RefSelector;
16use ostrya_fetch::Priority;
17use ostrya_fetch::gate::{Gate, Permit};
18
19use super::stream::{Input, Output};
20use crate::error::{Error, Result};
21use crate::proto::{
22 FrameReader, FrameWriter, GetReply, Kind, ListRefsRequest, MAX_REF_ENTRY_LEN,
23 MAX_REF_ENTRY_PARTS, MAX_REF_PATTERNS, MIN_FRAME_LIMIT, Message, PULL_PROTOCOL_VERSION,
24 PullHello, Step, encode_frame, protocol,
25};
26use crate::transport::Transport;
27
28/// The buffer size of the input of the session.
29const STREAM_BUFFER: usize = 64 * 1024;
30
31/// The most calls that hold a place at a time if the options give no number.
32const DEFAULT_OUTSTANDING: usize = 8;
33
34type Reader = FrameReader<BufReader<Input>>;
35type ReadFuture = Pin<Box<dyn Future<Output = Result<Option<Message>>> + Send>>;
36
37/// The options of a stream session.
38#[derive(Debug, Clone, Default)]
39pub struct StreamSessionOptions {
40 /// The `agent` value that the session sends in [`PullHello`].
41 ///
42 /// The default is `ostrya/<version>`, with the version of this crate.
43 pub agent: Option<String>,
44 /// The most [`get`](StreamSession::get) and
45 /// [`list_refs`](StreamSession::list_refs) calls that hold a place in the
46 /// [pipeline](StreamSession#pipeline) at a time.
47 ///
48 /// The default is 8. The session raises a value of 0 to 1.
49 pub max_outstanding: Option<usize>,
50}
51
52/// A client session of a pull, which reads the files and ref listings of a
53/// server.
54///
55/// [`connect`](StreamSession::connect) opens a session over ssh, and
56/// [`over_stream`](StreamSession::over_stream) opens one over a pair of byte
57/// streams. The session is `Send + Sync`. Concurrent
58/// [`get`](StreamSession::get) and [`list_refs`](StreamSession::list_refs)
59/// calls share the [pipeline](StreamSession#pipeline), and the replies come
60/// in the order of the frames.
61///
62/// If the session is dropped without [`finish`](StreamSession::finish), it
63/// sends nothing more and closes its output, so the server reads the end of
64/// its input. This is also true while the caller holds a [`PullBody`]. If
65/// [`connect`](StreamSession::connect) opened the session, the drop then drops
66/// the ssh client without a wait.
67///
68/// # Pipeline
69///
70/// The session opens with [`PullHello`]. It asks for files by their path
71/// with [`get`](StreamSession::get), and for ref listings with
72/// [`list_refs`](StreamSession::list_refs). All requests share one stream as
73/// a pipeline. A call takes its place and writes its frame under one lock, so
74/// the frames go on the wire in the order of the places.
75///
76/// A reply carries no request id. The reply of a call is the next reply
77/// after the reply of the call before it.
78///
79/// At most [`max_outstanding`](StreamSessionOptions::max_outstanding) calls
80/// hold a place at a time. A call holds its place from the write of its
81/// frame to the end of its reply.
82///
83/// If a [`get`](StreamSession::get) gets a [`GetReply`] whose `found` is
84/// `false`, that `GetReply` is the end of the reply. For each other reply,
85/// the end is the chunk that ends the body. When the session reads that
86/// chunk, it moves to the next reply, also while the caller still holds the
87/// [`PullBody`].
88///
89/// # Failures
90///
91/// Each of these events is a failure, and a failure ends the session:
92///
93/// - an `Error` message from the server
94/// - a reply of a kind that the session does not expect
95/// - a [`GetReply`] whose `found` is `false`, or that states no length, in
96/// reply to `ListRefs`
97/// - a stated length that is more than the cap of the call, or that is
98/// different from the sum of the chunks
99/// - a body that is longer than the cap of the call
100/// - a failed read or write
101/// - a drop of a `get` or `list_refs` future after the call took its place
102/// - a drop of a [`PullBody`] before its end
103/// - a [`finish`](StreamSession::finish) while the body of a reply is not read
104/// to its end
105///
106/// After a failure, each later call and each later read of a body fails. Its
107/// error has the variant and the message of the first failure.
108pub struct StreamSession {
109 inner: StreamInner,
110}
111
112struct StreamInner {
113 shared: Arc<Shared>,
114 /// The number of calls that hold a place in the pipeline at one time, at
115 /// least 1.
116 max_outstanding: usize,
117 /// The ssh client, for a session that [`StreamSession::connect`] opened.
118 /// The box keeps the session small.
119 transport: Option<Box<Transport>>,
120}
121
122/// The state that the session, its calls, and its bodies share.
123struct Shared {
124 /// The places of the pipeline.
125 places: Arc<Gate>,
126 /// The order of the writes: one call writes at a time, in the order in
127 /// which the calls arrived.
128 writing: Arc<Gate>,
129 write: Mutex<WriteSide>,
130 read: Mutex<ReadSide>,
131 /// The longest wait for a pending message after a failed write. `None`
132 /// waits with no limit.
133 pending_limit: Option<Duration>,
134}
135
136struct WriteSide {
137 /// The output, which a call takes while it writes its `Get` frame. It is
138 /// `None` after a write failed, after the session failed, or after the
139 /// session ended.
140 writer: Option<Output>,
141 /// The place of the next call.
142 next: u64,
143}
144
145struct ReadSide {
146 /// The reader. The call whose reply is next takes it while it reads the
147 /// head of its reply. The body of a found file reads it here, under the
148 /// lock. The end of the session can then drop it also while the caller
149 /// holds the body.
150 reader: Option<Box<Reader>>,
151 /// The read of the frame that follows the abandon marker of a body. It
152 /// holds the reader.
153 abandoned: Option<ReadFuture>,
154 /// The place whose reply is next.
155 turn: u64,
156 /// The waker of each call that waits for its reply, by place.
157 waiting: BTreeMap<u64, Waker>,
158 /// The first failure of the session.
159 failure: Option<Error>,
160}
161
162/// Returns a copy of `e` for a later call of a session that failed with `e`.
163///
164/// The copy has the variant and the message of `e`, and an I/O error keeps
165/// its kind. Each other variant with no wire code becomes `InvalidInput`.
166fn repeat(e: &Error) -> Error {
167 match e {
168 Error::Io(io) => Error::Io(io::Error::new(io.kind(), io.to_string())),
169 Error::Transport(msg) => Error::Transport(msg.clone()),
170 Error::InvalidInput(msg) => Error::InvalidInput(msg.clone()),
171 other if other.code().is_some() => other.to_message().into(),
172 other => Error::InvalidInput(other.to_string()),
173 }
174}
175
176/// Returns the `io::Error` that a body read gives for `e`.
177///
178/// It carries `e`. Its kind is the kind of an I/O error, and `Other` for
179/// each other error.
180fn body_error(e: Error) -> io::Error {
181 let kind = match &e {
182 Error::Io(io) => io.kind(),
183 _ => io::ErrorKind::Other,
184 };
185 io::Error::new(kind, e)
186}
187
188/// Returns the `ListRefs` request of a ref listing of `refs` and
189/// `collections`, by the rules of `PullSession` `# Ref patterns`.
190///
191/// # Errors
192///
193/// [`Error::InvalidInput`] if an entry is over [`MAX_REF_ENTRY_LEN`] bytes,
194/// with its `!` counted as one byte, or over [`MAX_REF_ENTRY_PARTS`] parts,
195/// or if more than [`MAX_REF_PATTERNS`] entries stay in the two lists.
196pub(super) fn wire_entries(
197 refs: &RefSelector,
198 collections: Option<&RefSelector>,
199) -> Result<ListRefsRequest> {
200 let mut count = 0;
201 let refs = list_entries(refs, &mut count)?;
202 let collections = collections
203 .map(|selector| list_entries(selector, &mut count))
204 .transpose()?;
205 Ok(ListRefsRequest { refs, collections })
206}
207
208/// Returns the entries of one list of a request, and adds their number to
209/// `count`, the number of entries of the request.
210///
211/// The positive entries come first, then the negative entries with their
212/// `!`. Each exact duplicate of one kind is removed.
213fn list_entries(selector: &RefSelector, count: &mut usize) -> Result<Vec<String>> {
214 let mut seen = HashSet::new();
215 let mut entries = Vec::new();
216 let positive = selector.positive().iter().map(|p| (false, p.as_str()));
217 let negative = selector.negative().iter().map(|p| (true, p.as_str()));
218 for (is_negative, text) in positive.chain(negative) {
219 if !seen.insert((is_negative, text)) {
220 continue;
221 }
222 let len = text.len() + usize::from(is_negative);
223 let parts = text.split('/').count();
224 if len > MAX_REF_ENTRY_LEN || parts > MAX_REF_ENTRY_PARTS {
225 return Err(Error::InvalidInput(format!(
226 "a ref pattern entry has {len} bytes and {parts} parts, over the limits of \
227 {MAX_REF_ENTRY_LEN} bytes and {MAX_REF_ENTRY_PARTS} parts"
228 )));
229 }
230 if *count == MAX_REF_PATTERNS {
231 return Err(Error::InvalidInput(format!(
232 "the ref listing names more than {MAX_REF_PATTERNS} distinct entries"
233 )));
234 }
235 *count += 1;
236 entries.push(if is_negative {
237 format!("!{text}")
238 } else {
239 text.to_owned()
240 });
241 }
242 Ok(entries)
243}
244
245fn eof(what: &str) -> Error {
246 Error::Io(io::Error::new(
247 io::ErrorKind::UnexpectedEof,
248 format!("the session ended before {what}"),
249 ))
250}
251
252/// Reads one message within `limit`. A failed read, an end of file, and a
253/// read that takes longer than `limit` give `None`.
254async fn read_pending(reader: &mut Reader, limit: Option<Duration>) -> Option<Message> {
255 let read = async { reader.read_message().await.ok().flatten() };
256 match limit {
257 None => read.await,
258 Some(limit) => {
259 let timeout = async {
260 ostrya_rt::Timer::after(limit).await;
261 None
262 };
263 futures_lite::future::or(read, timeout).await
264 }
265 }
266}
267
268impl Shared {
269 fn lock_read(&self) -> MutexGuard<'_, ReadSide> {
270 self.read.lock().unwrap_or_else(PoisonError::into_inner)
271 }
272
273 fn lock_write(&self) -> MutexGuard<'_, WriteSide> {
274 self.write.lock().unwrap_or_else(PoisonError::into_inner)
275 }
276
277 /// Returns the repeat of the first failure if the session failed.
278 fn check(&self) -> Result<()> {
279 match &self.lock_read().failure {
280 Some(first) => Err(repeat(first)),
281 None => Ok(()),
282 }
283 }
284
285 /// Ends the session with `e`, and returns `e` or the repeat of an earlier
286 /// failure.
287 ///
288 /// The first failure stays the failure of the session. The call drops the
289 /// reader and the writer, and wakes every waiting call.
290 ///
291 /// The call records the failure before it takes the writer. A call that
292 /// checks for a failure under the lock of the write side then cannot give
293 /// the writer back to a failed session.
294 fn fail(&self, e: Error) -> Error {
295 let (out, reader, abandoned, waiting) = {
296 let mut read = self.lock_read();
297 let out = match &read.failure {
298 Some(first) => repeat(first),
299 None => {
300 read.failure = Some(repeat(&e));
301 e
302 }
303 };
304 (
305 out,
306 read.reader.take(),
307 read.abandoned.take(),
308 std::mem::take(&mut read.waiting),
309 )
310 };
311 let writer = self.lock_write().writer.take();
312 drop((reader, abandoned, writer));
313 for waker in waiting.into_values() {
314 waker.wake();
315 }
316 out
317 }
318
319 /// Takes the reader for the call at `place` when its reply is next.
320 async fn wait_turn(&self, place: u64) -> Result<Box<Reader>> {
321 poll_fn(|cx| {
322 let mut read = self.lock_read();
323 if let Some(first) = &read.failure {
324 return Poll::Ready(Err(repeat(first)));
325 }
326 if read.turn == place
327 && let Some(reader) = read.reader.take()
328 {
329 return Poll::Ready(Ok(reader));
330 }
331 match read.waiting.entry(place) {
332 Entry::Occupied(mut stored) => {
333 if !stored.get().will_wake(cx.waker()) {
334 stored.insert(cx.waker().clone());
335 }
336 }
337 Entry::Vacant(slot) => {
338 slot.insert(cx.waker().clone());
339 }
340 }
341 Poll::Pending
342 })
343 .await
344 }
345
346 /// Gives back the reader after the reply of `place` ended, and wakes the
347 /// call whose reply is next.
348 fn advance(&self, reader: Box<Reader>, place: u64) {
349 let waker = {
350 let mut read = self.lock_read();
351 if read.failure.is_none() {
352 read.reader = Some(reader);
353 }
354 read.advance(place)
355 };
356 if let Some(waker) = waker {
357 waker.wake();
358 }
359 }
360
361 /// Gives back the reader for the body of the reply at the turn, which
362 /// reads it in place. If the session failed, the call drops the reader
363 /// and returns the repeat of the first failure.
364 fn lend(&self, reader: Box<Reader>) -> Result<()> {
365 let mut read = self.lock_read();
366 match &read.failure {
367 Some(first) => Err(repeat(first)),
368 None => {
369 read.reader = Some(reader);
370 Ok(())
371 }
372 }
373 }
374}
375
376impl ReadSide {
377 /// Moves the turn past the reply of `place`, and returns the waker of the
378 /// call whose reply is next.
379 fn advance(&mut self, place: u64) -> Option<Waker> {
380 self.turn = place + 1;
381 self.waiting.remove(&(place + 1))
382 }
383}
384
385/// A call that took its place in the pipeline.
386///
387/// If it is dropped before the call read the head of its reply, it ends the
388/// session. The reply of the call still arrives, and the codec is not
389/// cancel-safe.
390struct Placed<'a> {
391 shared: &'a Shared,
392 armed: bool,
393}
394
395impl Placed<'_> {
396 fn disarm(mut self) {
397 self.armed = false;
398 }
399}
400
401impl Drop for Placed<'_> {
402 fn drop(&mut self) {
403 if self.armed {
404 self.shared.fail(Error::InvalidInput(
405 "a call was dropped before its reply".into(),
406 ));
407 }
408 }
409}
410
411/// The open of a session over a pair of byte streams, and its calls.
412impl StreamSession {
413 /// Opens a session over a pair of byte streams.
414 ///
415 /// `input` carries the bytes from the server, and `output` the bytes to
416 /// it. The session sends [`PullHello`] with [`PULL_PROTOCOL_VERSION`] and
417 /// reads [`PullHelloReply`](crate::proto::PullHelloReply).
418 ///
419 /// The caller owns the liveness of the two streams. The session puts no
420 /// time limit on a read. A peer that stays silent keeps a call waiting
421 /// until the caller drops its future or closes the streams.
422 ///
423 /// # Errors
424 ///
425 /// - An `Error` message from the server, as the [`Error`] variant of its
426 /// code.
427 /// - [`Error::VersionUnsupported`] if the reply states a version out of
428 /// `1..=PULL_PROTOCOL_VERSION`. The session then closes `output` and
429 /// sends no `Get`.
430 /// - [`Error::Protocol`] if the reply is a message of another kind, or if
431 /// the codec refuses a frame of the reply.
432 /// - [`Error::Protocol`] if `agent` holds a NUL byte.
433 /// - [`Error::LimitExceeded`] if the `PullHello` frame or a frame of the
434 /// reply is longer than [`MIN_FRAME_LIMIT`].
435 /// - [`Error::Io`] if a read or a write of a stream fails. If `input`
436 /// ends before the reply, the kind is `UnexpectedEof`.
437 ///
438 /// If the write of `PullHello` fails with [`Error::Io`], the call then
439 /// reads the message that the server can have sent before it closed. If
440 /// that message is an `Error` message, the call returns its variant.
441 pub async fn over_stream<R, W>(input: R, output: W, opts: StreamSessionOptions) -> Result<Self>
442 where
443 R: AsyncRead + Unpin + Send + 'static,
444 W: AsyncWrite + Unpin + Send + 'static,
445 {
446 StreamSession::open(Box::new(input), Box::new(output), opts, None).await
447 }
448
449 /// Opens a session over `input` and `output`. `pending_limit` is the
450 /// longest wait for a pending message after a failed write.
451 pub(crate) async fn open(
452 input: Input,
453 output: Output,
454 opts: StreamSessionOptions,
455 pending_limit: Option<Duration>,
456 ) -> Result<StreamSession> {
457 let mut reader = FrameReader::new(BufReader::with_capacity(STREAM_BUFFER, input));
458 let mut writer = FrameWriter::new(output);
459 let agent = opts
460 .agent
461 .unwrap_or_else(|| format!("ostrya/{}", env!("CARGO_PKG_VERSION")));
462 let hello = Message::PullHello(PullHello {
463 version: PULL_PROTOCOL_VERSION,
464 agent: Some(agent),
465 });
466 let written = match writer.write_message(&hello).await {
467 Ok(()) => writer.flush().await,
468 Err(e) => Err(e),
469 };
470 if let Err(e) = written {
471 drop(writer);
472 return Err(match read_pending(&mut reader, pending_limit).await {
473 Some(Message::Error(sent)) if matches!(e, Error::Io(_)) => sent.into(),
474 _ => e,
475 });
476 }
477 let reply = match reader.read_message().await? {
478 Some(Message::PullHelloReply(reply)) => reply,
479 Some(Message::Error(e)) => return Err(e.into()),
480 Some(other) => {
481 return Err(protocol(format!(
482 "{:?} in reply to PullHello",
483 other.kind()
484 )));
485 }
486 None => return Err(eof("the reply to PullHello")),
487 };
488 if !(1..=PULL_PROTOCOL_VERSION).contains(&reply.version) {
489 let _ = writer.into_inner().close().await;
490 return Err(Error::VersionUnsupported(format!(
491 "the server replied with pull version {}, and the client speaks 1 to \
492 {PULL_PROTOCOL_VERSION}",
493 reply.version
494 )));
495 }
496 let outstanding = opts.max_outstanding.unwrap_or(DEFAULT_OUTSTANDING).max(1);
497 Ok(StreamSession {
498 inner: StreamInner {
499 shared: Arc::new(Shared {
500 places: Arc::new(Gate::new(outstanding)),
501 writing: Arc::new(Gate::new(1)),
502 write: Mutex::new(WriteSide {
503 writer: Some(writer.into_inner()),
504 next: 0,
505 }),
506 read: Mutex::new(ReadSide {
507 reader: Some(Box::new(reader)),
508 abandoned: None,
509 turn: 0,
510 waiting: BTreeMap::new(),
511 failure: None,
512 }),
513 pending_limit,
514 }),
515 max_outstanding: outstanding,
516 transport: None,
517 },
518 })
519 }
520
521 /// Attaches the child process whose standard streams the session uses.
522 pub(crate) fn with_transport(mut self, child: Transport) -> StreamSession {
523 self.inner.transport = Some(Box::new(child));
524 self
525 }
526
527 /// Returns the number of calls that hold a place in the pipeline at one
528 /// time, at least 1.
529 pub(crate) fn max_outstanding(&self) -> usize {
530 self.inner.max_outstanding
531 }
532
533 /// Asks for the file at `path` and waits for the head of its reply.
534 ///
535 /// `path` is relative to the repository root. The call returns `None` if
536 /// the server does not serve the path. The [`PullBody`] holds the body to
537 /// `max_len` bytes and to its stated length.
538 ///
539 /// If [`max_outstanding`](StreamSessionOptions::max_outstanding) calls hold
540 /// a place, the call waits. It then takes its place, and writes and
541 /// flushes its `Get` frame under one lock.
542 ///
543 /// The caller must read each body to its end, or drop it, before it
544 /// awaits a later `get`. A later call waits for the end of each earlier
545 /// body before it reads its own reply. If the future of the call is
546 /// dropped after the call took its place, the session ends.
547 ///
548 /// If the write of the `Get` frame fails, the call waits for the turn of
549 /// its reply. It then reads the message that the server can have sent
550 /// before it closed. If [`connect`](StreamSession::connect) opened the
551 /// session, this read takes the ssh time limits of
552 /// [`PushSession::connect`](super::PushSession::connect). If
553 /// [`over_stream`](StreamSession::over_stream) opened the session, this
554 /// read has no time limit.
555 ///
556 /// # Errors
557 ///
558 /// - [`Error::LimitExceeded`] if the `Get` frame of `path` is longer than
559 /// [`MIN_FRAME_LIMIT`]. The session stays usable, and the call writes
560 /// nothing.
561 /// - [`Error::Protocol`] if `path` holds a NUL byte. The session stays
562 /// usable, and the call writes nothing.
563 /// - The repeat of the first failure, if the session failed before the
564 /// call or while it waits.
565 /// - [`Error::LimitExceeded`] if the stated length of the body is more
566 /// than `max_len`. The session ends before it reads the body.
567 /// - [`Error::LimitExceeded`] if a frame of the reply is longer than
568 /// [`MIN_FRAME_LIMIT`].
569 /// - An `Error` message from the server, as the [`Error`] variant of its
570 /// code.
571 /// - [`Error::Protocol`] if the reply is a message of another kind, or if
572 /// the codec refuses a frame of the reply.
573 /// - [`Error::Io`] if a read or a write of the stream fails. If the stream
574 /// ends before the reply, the kind is `UnexpectedEof`.
575 ///
576 /// If the write of the `Get` frame fails and the server sent an `Error`
577 /// message before it closed, the call returns the variant of that
578 /// message. Otherwise it returns the [`Error::Io`] of the write.
579 ///
580 /// A failure ends the session, as [Failures](StreamSession#failures)
581 /// states.
582 pub async fn get(&self, path: &str, max_len: u64) -> Result<Option<PullBody>> {
583 self.inner.shared.check()?;
584 let get = Message::Get(path.to_owned());
585 let frame = encode_frame(&get, MIN_FRAME_LIMIT)?;
586 let Message::Get(path) = get else {
587 unreachable!("the message is a Get");
588 };
589 self.request(Kind::Get, frame, path, max_len).await
590 }
591
592 /// Asks for the ref listing of `refs` and `collections` and waits for the
593 /// head of its reply.
594 ///
595 /// `refs` selects the local refs. `collections` selects the collection
596 /// refs by `ID/NAME`, and `None` asks for no collection ref. The call
597 /// sends the entries of the two selectors by the rules of
598 /// [Ref patterns](super::PullSession#ref-patterns). The [`PullBody`] holds
599 /// the listing to `max_len` bytes and to its stated length.
600 ///
601 /// The call takes its place in the [pipeline](StreamSession#pipeline) as
602 /// [`get`](StreamSession::get) does, and it has the same rules for the
603 /// body and for a drop of its future.
604 ///
605 /// # Errors
606 ///
607 /// - [`Error::InvalidInput`] if the entries break a limit of
608 /// [Ref patterns](super::PullSession#ref-patterns). The session stays
609 /// usable, and the call writes nothing.
610 /// - [`Error::LimitExceeded`] if the `ListRefs` frame is longer than
611 /// [`MIN_FRAME_LIMIT`]. The session stays usable, and the call writes
612 /// nothing.
613 /// - [`Error::Protocol`] if the reply is a `GetReply` whose `found` is
614 /// `false`, or that states no length. The session fails.
615 /// - Each failure of the session that [`get`](StreamSession::get) lists.
616 /// If the server refuses an entry, the error is [`Error::Protocol`]. If
617 /// the listing is over the cap of the server, the error is
618 /// [`Error::LimitExceeded`].
619 ///
620 /// A failure ends the session, as [Failures](StreamSession#failures)
621 /// states.
622 pub async fn list_refs(
623 &self,
624 refs: &RefSelector,
625 collections: Option<&RefSelector>,
626 max_len: u64,
627 ) -> Result<PullBody> {
628 self.inner.shared.check()?;
629 let request = wire_entries(refs, collections)?;
630 let frame = encode_frame(&Message::ListRefs(request), MIN_FRAME_LIMIT)?;
631 let body = self
632 .request(Kind::ListRefs, frame, "ListRefs".to_owned(), max_len)
633 .await?;
634 Ok(body.expect("a ListRefs reply always has a body"))
635 }
636
637 /// Writes `frame`, a request of `kind`, in the pipeline and reads the
638 /// head of its reply.
639 ///
640 /// `label` names the request in the errors and in the body. A `GetReply`
641 /// whose `found` is `false` gives `None` for a `Get`, and fails the
642 /// session for a `ListRefs`. A `GetReply` that states no length also fails
643 /// the session for a `ListRefs`.
644 async fn request(
645 &self,
646 kind: Kind,
647 frame: Vec<u8>,
648 label: String,
649 max_len: u64,
650 ) -> Result<Option<PullBody>> {
651 let shared = &self.inner.shared;
652 let place = shared.places.acquire(Priority::Normal).await;
653 let turn = shared.writing.acquire(Priority::Normal).await;
654 shared.check()?;
655 let (seq, writer) = {
656 let mut write = shared.lock_write();
657 let seq = write.next;
658 write.next += 1;
659 (seq, write.writer.take())
660 };
661 let placed = Placed {
662 shared,
663 armed: true,
664 };
665 let written = match writer {
666 Some(mut writer) => {
667 let written = match writer.write_all(&frame).await {
668 Ok(()) => writer.flush().await.map_err(Error::from),
669 Err(e) => Err(e.into()),
670 };
671 // A failed write drops the writer, so the server reads the end
672 // of its input. The check of a failure runs under the lock of
673 // the write side: a session that failed during the write keeps
674 // no writer.
675 if written.is_ok() {
676 let mut write = shared.lock_write();
677 if shared.check().is_ok() {
678 write.writer = Some(writer);
679 }
680 }
681 written
682 }
683 // A write failed before this call: the call that failed gives the
684 // failure at its turn, and this call repeats it.
685 None => Ok(()),
686 };
687 drop(turn);
688 let mut reader = shared.wait_turn(seq).await?;
689 if let Err(e) = written {
690 let pending = read_pending(&mut reader, shared.pending_limit).await;
691 drop(reader);
692 placed.disarm();
693 return Err(shared.fail(match pending {
694 Some(Message::Error(sent)) if matches!(e, Error::Io(_)) => sent.into(),
695 _ => e,
696 }));
697 }
698 let reply = reader.read_message().await;
699 placed.disarm();
700 match reply {
701 Ok(Some(Message::GetReply(GetReply { found: false, .. })))
702 if kind == Kind::ListRefs =>
703 {
704 drop(reader);
705 Err(shared.fail(protocol("GetReply with found false in reply to ListRefs")))
706 }
707 Ok(Some(Message::GetReply(GetReply {
708 found: true,
709 len: None,
710 }))) if kind == Kind::ListRefs => {
711 drop(reader);
712 Err(shared.fail(protocol("GetReply with no length in reply to ListRefs")))
713 }
714 Ok(Some(Message::GetReply(GetReply { found: false, .. }))) => {
715 shared.advance(reader, seq);
716 drop(place);
717 Ok(None)
718 }
719 Ok(Some(Message::GetReply(GetReply { found: true, len }))) => {
720 if let Some(len) = len
721 && len > max_len
722 {
723 drop(reader);
724 return Err(shared.fail(Error::LimitExceeded(format!(
725 "{label}: a body of {len} bytes is over the limit {max_len}"
726 ))));
727 }
728 shared.lend(reader)?;
729 Ok(Some(PullBody {
730 len,
731 inner: Mutex::new(BodyInner {
732 shared: Arc::clone(shared),
733 state: BodyState::Reading,
734 place: Some(place),
735 seq,
736 path: label,
737 len,
738 max_len,
739 read: 0,
740 }),
741 }))
742 }
743 Ok(Some(Message::Error(e))) => Err(shared.fail(e.into())),
744 Ok(Some(other)) => {
745 Err(shared.fail(protocol(format!("{:?} in reply to {kind:?}", other.kind()))))
746 }
747 Ok(None) => Err(shared.fail(eof(&format!("the reply to {kind:?}")))),
748 Err(e) => Err(shared.fail(e)),
749 }
750 }
751
752 /// Ends the session.
753 ///
754 /// An end is clean if the session read the end of every reply. After a
755 /// clean end, the session closes its output at a frame boundary. The call
756 /// then returns `Ok`, whatever the exit status of the ssh client.
757 ///
758 /// At any other end, the session closes its output and drops its input
759 /// before it waits for the ssh client. Because the session drops the
760 /// input first, a server that is blocked in a write of a body does not
761 /// keep the client open. The session then fails with the error that the
762 /// call returns, and a later read of a held body repeats that error.
763 ///
764 /// If [`connect`](StreamSession::connect) opened the session, the call then
765 /// waits for the ssh client to exit. The wait takes the ssh time limits
766 /// of [`PushSession::connect`](super::PushSession::connect).
767 ///
768 /// # Errors
769 ///
770 /// - The repeat of the first failure, if the session failed.
771 /// - [`Error::InvalidInput`] if the body of a reply is not read to its
772 /// end, for example a body that the caller still holds.
773 /// - [`Error::Transport`] with the exit status, if the ssh client exited
774 /// with a failure status and the error of the session is
775 /// [`Error::Io`]. Only a session that [`connect`](StreamSession::connect)
776 /// opened returns it.
777 pub async fn finish(mut self) -> Result<()> {
778 let transport = self.inner.transport.take();
779 let shared = &self.inner.shared;
780 let next = shared.lock_write().next;
781 let unclean = {
782 let read = shared.lock_read();
783 match &read.failure {
784 Some(first) => Some(repeat(first)),
785 None if read.reader.is_none() || read.turn != next => Some(Error::InvalidInput(
786 "the session ended while a body was unread".into(),
787 )),
788 None => None,
789 }
790 };
791 let result = match unclean {
792 // The failure drops the reader and the writer, also while the
793 // caller holds a body, whose later read repeats the failure.
794 Some(e) => Err(shared.fail(e)),
795 None => {
796 let writer = shared.lock_write().writer.take();
797 if let Some(mut output) = writer {
798 let _ = output.close().await;
799 }
800 let reader = shared.lock_read().reader.take();
801 drop(reader);
802 Ok(())
803 }
804 };
805 match transport {
806 Some(transport) => transport.finish(result).await,
807 None => result,
808 }
809 }
810}
811
812impl Drop for StreamSession {
813 fn drop(&mut self) {
814 // A body that the caller holds keeps the shared state, so this drop
815 // closes the output.
816 let writer = self.inner.shared.lock_write().writer.take();
817 drop(writer);
818 }
819}
820
821/// The body of a reply to [`get`](StreamSession::get) or
822/// [`list_refs`](StreamSession::list_refs).
823///
824/// A `PullBody` is an `AsyncRead`. A read gives the bytes of the body until
825/// the chunk that ends it, and then end of file. When a read meets that
826/// chunk, the session moves to the next reply. The body is `Send + Sync`.
827///
828/// # Failures
829///
830/// Each of these events in a read ends the session:
831///
832/// - a body that is longer than the `max_len` of its call
833/// - a body whose stated length is different from the sum of its chunks
834/// - an `Error` message after the abandon marker
835/// - a failed read
836///
837/// The read then fails with an `io::Error` that carries the [`Error`] of the
838/// session, and each later read fails the same way. If that error is an
839/// [`Error::Io`], the `io::Error` has its kind. Otherwise the kind is
840/// `Other`.
841///
842/// The session can also fail for another reason, for example a dropped
843/// `get` or `list_refs` future, or [`StreamSession::finish`]. A later read
844/// of the body then fails with the first failure and reads no more of the
845/// body. A drop of the body before its end also ends the session.
846pub struct PullBody {
847 len: Option<u64>,
848 inner: Mutex<BodyInner>,
849}
850
851struct BodyInner {
852 shared: Arc<Shared>,
853 state: BodyState,
854 /// The place of the call, which the end of the body releases.
855 place: Option<Permit>,
856 seq: u64,
857 path: String,
858 len: Option<u64>,
859 max_len: u64,
860 /// The number of bytes of the body that the reads gave so far.
861 read: u64,
862}
863
864enum BodyState {
865 /// The read of the body is in progress. The read side of the session
866 /// holds the reader, or the read of the frame that follows the abandon
867 /// marker.
868 Reading,
869 /// The body ended.
870 Ended,
871 /// The session failed. Each read repeats the error.
872 Failed(Error),
873}
874
875impl PullBody {
876 /// Returns the length that the server stated for the body, if any.
877 // A body with no stated length has no answer to `is_empty`.
878 #[allow(clippy::len_without_is_empty)]
879 pub fn len(&self) -> Option<u64> {
880 self.len
881 }
882}
883
884impl std::fmt::Debug for PullBody {
885 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
886 f.debug_struct("PullBody")
887 .field("len", &self.len)
888 .finish_non_exhaustive()
889 }
890}
891
892impl BodyInner {
893 /// Ends the session with `e`, and returns the error of the read.
894 fn fail(&mut self, e: Error) -> io::Error {
895 let e = self.shared.fail(e);
896 self.state = BodyState::Failed(repeat(&e));
897 self.place = None;
898 body_error(e)
899 }
900
901 /// Adds `n` bytes to the count of the body, and checks the count against
902 /// the cap and the stated length.
903 fn count(&mut self, n: usize) -> Result<()> {
904 self.read += n as u64;
905 if self.read > self.max_len {
906 return Err(Error::LimitExceeded(format!(
907 "{}: the body passed the limit of {} bytes",
908 self.path, self.max_len
909 )));
910 }
911 if let Some(len) = self.len
912 && self.read > len
913 {
914 return Err(protocol(format!(
915 "{}: the body holds more than its stated length of {len} bytes",
916 self.path
917 )));
918 }
919 Ok(())
920 }
921
922 fn poll_read(&mut self, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<io::Result<usize>> {
923 match &self.state {
924 BodyState::Ended => return Poll::Ready(Ok(0)),
925 BodyState::Failed(e) => return Poll::Ready(Err(body_error(repeat(e)))),
926 BodyState::Reading => {}
927 }
928 let mut next = None;
929 // The bytes read, or 0 at the end of the body.
930 let got = {
931 let mut guard = self.shared.lock_read();
932 let read = &mut *guard;
933 loop {
934 if let Some(first) = &read.failure {
935 break Err(repeat(first));
936 }
937 if let Some(abandoned) = read.abandoned.as_mut() {
938 let frame = ready!(abandoned.as_mut().poll(cx));
939 read.abandoned = None;
940 break Err(match frame {
941 Ok(Some(Message::Error(sent))) => sent.into(),
942 Ok(Some(other)) => {
943 protocol(format!("{:?} after the abandon marker", other.kind()))
944 }
945 Ok(None) => eof("the Error after the abandon marker"),
946 Err(e) => e,
947 });
948 }
949 let Some(reader) = read.reader.as_mut() else {
950 unreachable!("the body holds the turn of the reader");
951 };
952 if buf.is_empty() {
953 return Poll::Ready(Ok(0));
954 }
955 match ready!(reader.poll_step(cx, buf)) {
956 Ok(Step::Data(n)) => break Ok(n),
957 Ok(Step::End) => {
958 if let Some(len) = self.len
959 && len != self.read
960 {
961 break Err(protocol(format!(
962 "{}: the body holds {} bytes, not its stated length of {len}",
963 self.path, self.read
964 )));
965 }
966 next = read.advance(self.seq);
967 break Ok(0);
968 }
969 Ok(Step::Marker(_)) => {
970 if let Some(mut reader) = read.reader.take() {
971 read.abandoned =
972 Some(Box::pin(async move { reader.read_message().await }));
973 }
974 }
975 Err(e) => break Err(e),
976 }
977 }
978 };
979 match got {
980 Ok(0) => {
981 self.state = BodyState::Ended;
982 self.place = None;
983 if let Some(waker) = next {
984 waker.wake();
985 }
986 Poll::Ready(Ok(0))
987 }
988 Ok(n) => Poll::Ready(match self.count(n) {
989 Ok(()) => Ok(n),
990 Err(e) => Err(self.fail(e)),
991 }),
992 Err(e) => Poll::Ready(Err(self.fail(e))),
993 }
994 }
995}
996
997impl AsyncRead for PullBody {
998 fn poll_read(
999 self: Pin<&mut Self>,
1000 cx: &mut Context<'_>,
1001 buf: &mut [u8],
1002 ) -> Poll<io::Result<usize>> {
1003 self.get_mut()
1004 .inner
1005 .get_mut()
1006 .unwrap_or_else(PoisonError::into_inner)
1007 .poll_read(cx, buf)
1008 }
1009}
1010
1011impl Drop for PullBody {
1012 fn drop(&mut self) {
1013 let inner = self.inner.get_mut().unwrap_or_else(PoisonError::into_inner);
1014 if matches!(inner.state, BodyState::Reading) {
1015 inner.shared.fail(Error::InvalidInput(
1016 "a pull body was dropped before its end".into(),
1017 ));
1018 }
1019 }
1020}
1021
1022#[cfg(test)]
1023mod tests {
1024 use super::*;
1025
1026 fn selector(entries: &[&str]) -> RefSelector {
1027 RefSelector::parse(entries.iter().copied()).unwrap()
1028 }
1029
1030 fn wire(entries: &[&str]) -> Vec<String> {
1031 wire_entries(&selector(entries), None).unwrap().refs
1032 }
1033
1034 /// `wire_entries` removes an exact duplicate of one kind and keeps the
1035 /// first appearance. An entry that another entry covers stays.
1036 #[test]
1037 fn exact_duplicates_are_removed_in_order() {
1038 assert_eq!(wire(&["x", "a", "x", "b", "a"]), ["x", "a", "b"]);
1039 assert_eq!(wire(&["a", "a/b", "a"]), ["a", "a/b"]);
1040 assert!(wire(&[]).is_empty());
1041 assert_eq!(wire(&["main"; 300]), ["main"]);
1042 }
1043
1044 /// The positive entries come first, then the negative entries with their
1045 /// `!`. A positive and a negative entry of the same text both stay.
1046 #[test]
1047 fn negative_entries_follow_positive_entries() {
1048 assert_eq!(
1049 wire(&["!x", "a/**", "!a/b/*", "x", "!x", "a/*"]),
1050 ["a/**", "x", "a/*", "!x", "!a/b/*"]
1051 );
1052 }
1053
1054 /// The limit counts positive and negative entries together.
1055 #[test]
1056 fn the_limit_counts_both_kinds() {
1057 let entries: Vec<String> = (0..=MAX_REF_PATTERNS)
1058 .map(|n| {
1059 if n % 2 == 0 {
1060 format!("r{n}")
1061 } else {
1062 format!("!r{n}")
1063 }
1064 })
1065 .collect();
1066 let entries: Vec<&str> = entries.iter().map(String::as_str).collect();
1067 let err = wire_entries(&selector(&entries), None).unwrap_err();
1068 assert!(matches!(err, Error::InvalidInput(_)), "{err:?}");
1069 assert_eq!(wire(&entries[1..]).len(), MAX_REF_PATTERNS);
1070 }
1071
1072 /// The two lists share the limit. An entry repeated within one list is
1073 /// sent one time, and the same entry in the two lists is sent in each
1074 /// list. An absent list and an empty list stay apart.
1075 #[test]
1076 fn the_two_lists_share_the_limit() {
1077 let names: Vec<String> = (0..MAX_REF_PATTERNS).map(|n| format!("r{n}")).collect();
1078 let names: Vec<&str> = names.iter().map(String::as_str).collect();
1079 let (half, rest) = names.split_at(MAX_REF_PATTERNS / 2);
1080 let request = wire_entries(&selector(half), Some(&selector(rest))).unwrap();
1081 assert_eq!(request.refs.len() + request.collections.unwrap().len(), 256);
1082 let err = wire_entries(&selector(half), Some(&selector(&names[..129]))).unwrap_err();
1083 assert!(matches!(err, Error::InvalidInput(_)), "{err:?}");
1084 let err = wire_entries(&selector(&names), Some(&selector(&["x/*"]))).unwrap_err();
1085 assert!(matches!(err, Error::InvalidInput(_)), "{err:?}");
1086
1087 let request =
1088 wire_entries(&selector(&["a", "a"]), Some(&selector(&["a", "!b", "a"]))).unwrap();
1089 assert_eq!(request.refs, ["a"]);
1090 assert_eq!(request.collections.unwrap(), ["a", "!b"]);
1091 assert_eq!(
1092 wire_entries(&selector(&[]), None).unwrap().collections,
1093 None
1094 );
1095 assert_eq!(
1096 wire_entries(&selector(&[]), Some(&selector(&[])))
1097 .unwrap()
1098 .collections,
1099 Some(Vec::new())
1100 );
1101 let full = wire_entries(&selector(&names), Some(&selector(&[]))).unwrap();
1102 assert_eq!(full.refs.len(), MAX_REF_PATTERNS);
1103 }
1104
1105 /// `wire_entries` refuses an entry over the limit of bytes or parts, and
1106 /// accepts an entry at the limit. The `!` counts as one byte and adds no
1107 /// part. The limits apply to an entry of each list.
1108 #[test]
1109 fn an_entry_over_a_limit_is_refused() {
1110 let parts = |n: usize| vec!["a"; n].join("/");
1111 let long = |n: usize| "a".repeat(n);
1112 for ok in [
1113 parts(MAX_REF_ENTRY_PARTS),
1114 long(MAX_REF_ENTRY_LEN),
1115 format!("!{}", long(MAX_REF_ENTRY_LEN - 1)),
1116 format!("!{}", parts(MAX_REF_ENTRY_PARTS)),
1117 ] {
1118 assert_eq!(wire(&[&ok]), [ok]);
1119 }
1120 for bad in [
1121 parts(MAX_REF_ENTRY_PARTS + 1),
1122 long(MAX_REF_ENTRY_LEN + 1),
1123 format!("!{}", long(MAX_REF_ENTRY_LEN)),
1124 format!("!{}", parts(MAX_REF_ENTRY_PARTS + 1)),
1125 ] {
1126 let err = wire_entries(&selector(&[&bad]), None).unwrap_err();
1127 assert!(matches!(err, Error::InvalidInput(_)), "{err:?}");
1128 let err = wire_entries(&selector(&[]), Some(&selector(&[&bad]))).unwrap_err();
1129 assert!(matches!(err, Error::InvalidInput(_)), "{err:?}");
1130 }
1131 }
1132}