ostrya_remote/transport/mod.rs
1//! The endpoints, and the ssh and HTTP transports of the sessions.
2//!
3//! An [`Endpoint`] holds a remote address and the options of its transport.
4//! These calls open a session:
5//!
6//! - [`PushSession::connect`], or [`PushSession::prepare`] and then
7//! [`PreparedSession::open`], for a push to an endpoint
8//! - [`PullSession::connect`] for a pull from an endpoint
9//! - [`StreamSession::connect`] for a stream session to an [`SshAddress`]
10//!
11//! Over ssh, the session runs the ssh client as a child process, and the remote
12//! side runs the receive command or the send command. The frames of the
13//! session go over the standard input and the standard output of the child.
14//! Over HTTP, each step of a push session is one request to the server.
15
16mod http;
17mod ssh;
18
19use std::ffi::OsStr;
20use std::fmt;
21use std::time::Duration;
22
23use crate::error::{Error, Result};
24use crate::session::http::Endpoint as HttpEndpoint;
25use crate::session::{
26 PullSession, PushSession, SessionOptions, StreamSession, StreamSessionOptions,
27};
28
29pub(crate) use ssh::Transport;
30pub use ssh::{SshAddress, SshOptions, without_userinfo};
31
32/// The refusal of an `s3://` address by [`Endpoint::parse`].
33#[cfg(feature = "s3")]
34const S3_ADDRESS: &str = "an s3:// address needs credentials, which Endpoint::parse does not read: build the \
35 endpoint with s3::S3Endpoint::resolve";
36
37/// The refusal of an `s3://` address by [`Endpoint::parse`].
38#[cfg(not(feature = "s3"))]
39const S3_ADDRESS: &str = "an s3:// address needs the S3 support of ostrya-remote, and this build has none: turn on \
40 the feature s3";
41
42/// The refusal of an S3 endpoint by a push session constructor.
43#[cfg(feature = "s3")]
44const S3_SESSION: &str = "an S3 endpoint opens no push session: open its client with \
45 s3::Bucket::new";
46
47/// The longest wait for a pending message after a failed write, and for the
48/// exit of the ssh client. It applies to a session that
49/// [`PushSession::connect`] or [`StreamSession::connect`] opens.
50const PENDING_READ_LIMIT: Duration = Duration::from_secs(5);
51
52/// A remote address with the options of its transport.
53///
54/// [`Endpoint::parse`] reads an address and gives the default options. A
55/// caller can also build an endpoint from its parts, with options of its own.
56///
57/// The [`Debug`] output of [`Endpoint::Http`] is the output of
58/// [`FetcherOptions`](ostrya_fetch::FetcherOptions), which shows no
59/// credential, no header value, and no userinfo. The [`Debug`] output of
60/// `Endpoint::S3` is the output of `S3Endpoint`, which shows no secret
61/// access key and no session token.
62///
63/// The enum is `#[non_exhaustive]`, so a `match` outside this crate needs a
64/// wildcard arm. With the `s3` feature, it has the variant `Endpoint::S3`.
65/// A crate that matches each variant compiles with and without that
66/// feature.
67///
68/// # HTTP addresses
69///
70/// The forms are `http://HOST[:PORT][/PATH]` and `https://HOST[:PORT][/PATH]`.
71/// [`parse`](Endpoint::parse) refuses an `@` at any position, so it refuses
72/// userinfo. It also refuses a query, a fragment, an empty host, and a port
73/// that is not a number from 0 to 65535.
74#[derive(Debug, Clone)]
75// The HTTP variant is much larger than the ssh variant. A caller builds one
76// endpoint for each remote, so a box saves no work, and the variant stays
77// inline.
78#[allow(clippy::large_enum_variant)]
79#[non_exhaustive]
80pub enum Endpoint {
81 /// An ssh address and the options of the ssh client.
82 Ssh {
83 /// The ssh address.
84 address: SshAddress,
85 /// The options of the ssh client.
86 options: SshOptions,
87 },
88 /// The options of the HTTP client.
89 ///
90 /// [`mirrors`](ostrya_fetch::FetcherOptions::mirrors) holds the address:
91 /// exactly one mirror for a push, one or more for a pull.
92 Http(ostrya_fetch::FetcherOptions),
93 /// A bucket repository: the location, the credentials, and the HTTP
94 /// options of its client.
95 ///
96 /// [`s3::Bucket::new`](crate::s3::Bucket::new) opens its client.
97 /// [`PullSession::connect`] opens an HTTP pull session to it, with the
98 /// options of
99 /// [`S3Endpoint::pull_options`](crate::s3::S3Endpoint::pull_options). No
100 /// push session opens to it: [`PushSession::prepare`] and
101 /// [`PushSession::connect`] refuse it.
102 #[cfg(feature = "s3")]
103 #[cfg_attr(docsrs, doc(cfg(feature = "s3")))]
104 S3(crate::s3::S3Endpoint),
105}
106
107impl Endpoint {
108 /// Parses `address` into an endpoint with the default options.
109 ///
110 /// An address that starts with `http://` or `https://` gives
111 /// [`Endpoint::Http`] with
112 /// [`FetcherOptions::new`](ostrya_fetch::FetcherOptions::new) of the
113 /// address. Each other address gives [`Endpoint::Ssh`] with the default
114 /// [`SshOptions`].
115 ///
116 /// An `s3://` address is refused. An S3 endpoint needs credentials, and
117 /// this call reads none. With the `s3` feature,
118 /// `s3::S3Endpoint::resolve` builds the endpoint.
119 ///
120 /// # Errors
121 ///
122 /// - [`Error::InvalidInput`] if `address` is not one of the
123 /// [ssh forms](SshAddress#forms) or the
124 /// [HTTP forms](Endpoint#http-addresses), or if the parse refuses a
125 /// part of it. No refusal shows the userinfo of the address.
126 /// - [`Error::InvalidInput`] if `address` starts with `s3://`.
127 ///
128 /// # Examples
129 ///
130 /// ```
131 /// use ostrya_remote::transport::Endpoint;
132 /// # fn main() -> ostrya_remote::Result<()> {
133 /// let endpoint = Endpoint::parse("builder@repo.example.com:/srv/repo")?;
134 /// let Endpoint::Ssh { address, options } = endpoint else {
135 /// panic!("an scp-form address gives an ssh endpoint");
136 /// };
137 /// assert_eq!(address.to_string(), "ssh://builder@repo.example.com/srv/repo");
138 /// assert_eq!(options.remote_command, None);
139 ///
140 /// let Endpoint::Http(http) = Endpoint::parse("https://repo.example.com/")? else {
141 /// panic!("an https address gives an HTTP endpoint");
142 /// };
143 /// assert_eq!(http.mirrors, ["https://repo.example.com/"]);
144 /// # Ok(()) }
145 /// ```
146 pub fn parse(address: &str) -> Result<Endpoint> {
147 parse_endpoint(address, cfg!(windows))
148 }
149}
150
151/// Parses `address` as [`Endpoint::parse`] does, with the Windows rules of an
152/// ssh address if `windows` is `true`.
153fn parse_endpoint(address: &str, windows: bool) -> Result<Endpoint> {
154 if address.starts_with("s3://") {
155 return Err(Error::InvalidInput(S3_ADDRESS.into()));
156 }
157 if address.starts_with("http://") || address.starts_with("https://") {
158 // The message of the fetcher holds no userinfo.
159 ostrya_fetch::check_base_url(address)
160 .map_err(|e| Error::InvalidInput(format!("address: {e}")))?;
161 Ok(Endpoint::Http(ostrya_fetch::FetcherOptions::new(address)))
162 } else {
163 Ok(Endpoint::Ssh {
164 address: SshAddress::parse_with(address, windows)?,
165 options: SshOptions::default(),
166 })
167 }
168}
169
170/// The open of a session over ssh or HTTP.
171impl PushSession {
172 /// Opens a push session to `endpoint` over ssh or HTTP.
173 ///
174 /// The call starts the transport, sends `Hello` with `refs`, and reads
175 /// `HelloReply`. It is [`prepare`](PushSession::prepare) and then
176 /// [`PreparedSession::open`].
177 ///
178 /// # Errors
179 ///
180 /// - Each error of [`prepare`](PushSession::prepare).
181 /// - Each error of [`PreparedSession::open`].
182 ///
183 /// # tokio runtime
184 ///
185 /// Under the tokio backend, the call must run within a runtime that has
186 /// the IO driver and the time driver enabled. The runtime builder enables
187 /// them with `enable_io` and `enable_time`, or with `enable_all`.
188 ///
189 /// The child process, its pipes, and the connections of an HTTP session
190 /// need the IO driver. The time limits need the time driver. The session
191 /// runs on the runtime that opened it.
192 ///
193 /// # ssh time limits
194 ///
195 /// After a failed write, the session reads the message that the server can
196 /// have sent before it closed. The read takes at most five seconds. A
197 /// server that closed its input and keeps its output open with no message
198 /// cannot hold the session. When the time ends, the call returns the error
199 /// of the write, or [`Error::CommitOutcomeUnknown`] after `Commit`.
200 ///
201 /// [`commit`](PushSession::commit) and [`abort`](PushSession::abort) close
202 /// the standard input of the ssh client. They then wait at most five
203 /// seconds for the ssh client to exit. They also wait if the stream is
204 /// broken and if `commit` refuses its updates. An open that fails waits in
205 /// the same way.
206 ///
207 /// If the session failed with an I/O error and the ssh client exited with a
208 /// failure status, the call returns [`Error::Transport`] with the status.
209 /// The status is also added to the message of
210 /// [`Error::CommitOutcomeUnknown`]. A session that committed returns its
211 /// outcome, whatever the exit status.
212 ///
213 /// The session drops the child with no wait in three cases:
214 ///
215 /// - the caller drops the session without `commit` or `abort`
216 /// - the caller drops the future of `commit` or `abort` before it completes
217 /// - the ssh client does not exit within the limit
218 ///
219 /// In each case, the standard input of the child closes, so the child
220 /// reads end of file on it.
221 ///
222 /// # HTTP
223 ///
224 /// Each step of a session is one request to the receive endpoint of the
225 /// server. The client adds `_ostrya/receive/v1/session` to the path of the
226 /// address, and then `/ID` and the step. The response to `Hello` gives
227 /// the `ID` in its `ostrya-session` header, as 64 lowercase hex digits.
228 ///
229 /// `ostrya serve` serves the endpoint at the root of the server. An
230 /// address with a path works only behind a proxy that removes that path,
231 /// or with a host that mounts the `ReceiveEndpoint` of `ostrya-server`
232 /// under that path.
233 ///
234 /// `Hello`, `Have`, and `Commit` go as whole request bodies. Each object
235 /// stream is the streamed body of one `objects` request. Each response
236 /// body holds one frame: the reply of the step, or an `Error` message.
237 ///
238 /// After the client sent the request body, it waits for the response. The
239 /// wait is at most 6 minutes for `Hello` and at most 1 hour for `Commit`.
240 /// For each other request, the limit is the
241 /// [`progress_timeout`](ostrya_fetch::FetcherOptions::progress_timeout) of
242 /// the options of [`Endpoint::Http`]. The client sends a request again only
243 /// if the attempt failed before it sent any byte of the request.
244 ///
245 /// The options of [`Endpoint::Http`] must name exactly one mirror, the
246 /// push address. The client sets
247 /// [`max_outstanding`](ostrya_fetch::FetcherOptions::max_outstanding) to 32
248 /// and [`max_redirects`](ostrya_fetch::FetcherOptions::max_redirects) to 0,
249 /// whatever values the options hold. The 32 requests are one for each of
250 /// the at most 31 object streams of [`PushSession::send`], and one `Have`
251 /// or `Commit` request. The client follows no redirect, and a 3xx answer
252 /// is [`Error::Transport`].
253 ///
254 /// The fetcher carries the credential, the TLS settings, the proxy, and
255 /// the headers of the options to each request. The client takes each trust
256 /// setting of the options, also a bypass variant of
257 /// [`TrustRoots`](ostrya_fetch::TrustRoots) that verifies no certificate
258 /// chain. The caller owns the trust policy.
259 ///
260 /// # Examples
261 ///
262 /// The example deletes a ref on the server if the ref exists.
263 ///
264 /// ```no_run
265 /// use ostrya_fetch::BearerToken;
266 /// use ostrya_remote::proto::{Expected, RefUpdate};
267 /// use ostrya_remote::session::{PushSession, SessionOptions};
268 /// use ostrya_remote::transport::Endpoint;
269 /// # async fn run(token: String) -> ostrya_remote::Result<()> {
270 /// let mut endpoint = Endpoint::parse("https://repo.example.com/")?;
271 /// if let Endpoint::Http(http) = &mut endpoint {
272 /// http.bearer_token = Some(BearerToken { token });
273 /// }
274 /// let refs = vec!["exampleos/testing".to_owned()];
275 /// let session = PushSession::connect(endpoint, &refs, SessionOptions::default()).await?;
276 /// let Some(tip) = session.server().tip(&refs[0]) else {
277 /// return session.abort().await;
278 /// };
279 /// let update = RefUpdate { name: refs[0].clone(), expected: Expected::Commit(tip), new: None };
280 /// let outcome = session.commit(&[update], false).await?;
281 /// assert_eq!(outcome.refs[0].new, None);
282 /// # Ok(()) }
283 /// ```
284 pub async fn connect(
285 endpoint: Endpoint,
286 refs: &[String],
287 opts: SessionOptions,
288 ) -> Result<PushSession> {
289 PushSession::prepare(endpoint).await?.open(refs, opts).await
290 }
291
292 /// Checks `endpoint` and makes the transport ready to open.
293 ///
294 /// For an ssh endpoint, the call reads the `OSTRYA_SSH_COMMAND`
295 /// environment variable and builds the command line of the ssh client by
296 /// the rules of the [ssh command line](SshOptions#ssh-command-line).
297 /// [`check`](PushSession::check) makes the same checks alone.
298 ///
299 /// For an HTTP endpoint, the call builds the HTTP client from the options,
300 /// as [`connect`](PushSession::connect) states. With
301 /// [`TrustRoots::System`](ostrya_fetch::TrustRoots::System), an `https://`
302 /// endpoint reads the trust store of the host, by the rule of
303 /// [`Fetcher::new`](ostrya_fetch::Fetcher::new).
304 /// [`check`](PushSession::check) makes the checks of the options that
305 /// read no file alone.
306 ///
307 /// The call starts no ssh client and sends no request. It refuses each
308 /// value that [`connect`](PushSession::connect) refuses before it starts
309 /// the transport. A caller can make these checks before its own local
310 /// work, and open the session with [`PreparedSession::open`] after that
311 /// work.
312 ///
313 /// Under the tokio backend, the call must run within a runtime that has
314 /// the IO driver enabled, as [`connect`](PushSession::connect) states.
315 ///
316 /// # Errors
317 ///
318 /// - [`Error::InvalidInput`] if the ssh command or the receive command is
319 /// empty or holds only white space, or if the value of
320 /// `OSTRYA_SSH_COMMAND` is not UTF-8. [`SshOptions`] states the full
321 /// rule under [Empty values](SshOptions#empty-values).
322 /// - [`Error::InvalidInput`] if the options of an HTTP endpoint do not name
323 /// exactly one mirror, or if
324 /// [`check_base_url`](ostrya_fetch::check_base_url) refuses the mirror.
325 /// The message holds no userinfo.
326 /// - [`Error::InvalidInput`] for an `Endpoint::S3`.
327 /// - [`Error::Fetch`] if [`Fetcher::new`](ostrya_fetch::Fetcher::new)
328 /// refuses the options. Examples:
329 /// - a credential to an `http://` address, with
330 /// [`allow_cleartext_credentials`](ostrya_fetch::FetcherOptions::allow_cleartext_credentials)
331 /// set to `false`
332 /// - a bearer token and an `Authorization` header together
333 /// - a client key that needs a passphrase that the options do not hold
334 pub async fn prepare(endpoint: Endpoint) -> Result<PreparedSession> {
335 let env = std::env::var_os("OSTRYA_SSH_COMMAND");
336 let inner = prepare_with(endpoint, env.as_deref()).await?;
337 Ok(PreparedSession { inner })
338 }
339
340 /// Makes each refusal of [`prepare`](PushSession::prepare) that reads no
341 /// file, in the order of [`prepare`](PushSession::prepare), with the same
342 /// errors.
343 ///
344 /// For an ssh endpoint, the call reads the `OSTRYA_SSH_COMMAND`
345 /// environment variable and applies the rules of the
346 /// [ssh command line](SshOptions#ssh-command-line). For an HTTP endpoint,
347 /// it checks the push address and makes the checks of
348 /// [`check_options`](ostrya_fetch::check_options), so it reads the proxy
349 /// variables of the environment for
350 /// [`Proxy::Environment`](ostrya_fetch::Proxy::Environment). It reads no
351 /// file and no trust store, starts no ssh client, and builds no HTTP
352 /// client. A caller can make these checks before it resolves the files of
353 /// an endpoint, for example its token file and its PEM files.
354 ///
355 /// For an HTTP endpoint, [`prepare`](PushSession::prepare) also makes the
356 /// refusals of the TLS setup. So a success of this call does not show
357 /// that [`prepare`](PushSession::prepare) succeeds.
358 ///
359 /// # Errors
360 ///
361 /// - [`Error::InvalidInput`] if the ssh command or the receive command is
362 /// empty or holds only white space, or if the value of
363 /// `OSTRYA_SSH_COMMAND` is not UTF-8. [`SshOptions`] states the full
364 /// rule under [Empty values](SshOptions#empty-values).
365 /// - [`Error::InvalidInput`] if the options of an HTTP endpoint do not name
366 /// exactly one mirror, or if
367 /// [`check_base_url`](ostrya_fetch::check_base_url) refuses the mirror.
368 /// The message holds no userinfo.
369 /// - [`Error::InvalidInput`] for an `Endpoint::S3`.
370 /// - [`Error::Fetch`] if [`check_options`](ostrya_fetch::check_options)
371 /// refuses the options of an HTTP endpoint, for example a bad header, a
372 /// low-speed rule with a zero, or a bad proxy URL.
373 pub fn check(endpoint: &Endpoint) -> Result<()> {
374 match endpoint {
375 Endpoint::Ssh { options, .. } => {
376 let env = std::env::var_os("OSTRYA_SSH_COMMAND");
377 ssh_parts(options, env.as_deref()).map(drop)
378 }
379 Endpoint::Http(http) => http::check(http),
380 #[cfg(feature = "s3")]
381 Endpoint::S3(_) => Err(Error::InvalidInput(S3_SESSION.into())),
382 }
383 }
384}
385
386/// Returns the ssh command line and the receive command of a push with
387/// `options`, with `env` as the value of the `OSTRYA_SSH_COMMAND`
388/// environment variable.
389fn ssh_parts<'a>(options: &'a SshOptions, env: Option<&OsStr>) -> Result<(Vec<String>, &'a str)> {
390 let program = options.program(env)?;
391 let receive = ssh::receive_command(options.remote_command.as_deref())?;
392 Ok((program, receive))
393}
394
395/// A push session whose transport is checked and ready to open.
396///
397/// [`PushSession::prepare`] returns it. For ssh, it holds the command line of
398/// the ssh client. For HTTP, it holds the HTTP client and the credential of the
399/// session. No process runs and no request is sent before
400/// [`open`](PreparedSession::open).
401///
402/// The value is `Send + Sync`. Its `Debug` output shows the transport and the
403/// HTTP address alone, with no credential and no command line.
404pub struct PreparedSession {
405 inner: Prepared,
406}
407
408impl PreparedSession {
409 /// Opens the session, sends `Hello` with `refs`, and reads `HelloReply`.
410 ///
411 /// The call starts the ssh client, or sends the first HTTP request, as
412 /// [`PushSession::connect`] does. An ssh session has the ssh time limits of
413 /// [`PushSession::connect`].
414 ///
415 /// # Errors
416 ///
417 /// - An `Error` message from the server, as the [`Error`] variant of its
418 /// code.
419 /// - [`Error::Fetch`] if an HTTP request fails.
420 /// - [`Error::Transport`] if the ssh client cannot be started. The message
421 /// names the program.
422 /// - [`Error::Transport`] if an HTTP answer has a status that the endpoint
423 /// does not give, or a body that is not one frame. The message names the
424 /// URL and the status.
425 /// - [`Error::Transport`] if the HTTP answer to `Hello` has no session id.
426 /// - [`Error::Transport`] if the session fails with [`Error::Io`] and the
427 /// ssh client exits with a failure status. The message holds the status.
428 /// - [`Error::Protocol`] if the reply is not `HelloReply`, if its version
429 /// is not [`PROTOCOL_VERSION`](crate::proto::PROTOCOL_VERSION), or if
430 /// its refs are not the refs of `Hello` in order.
431 /// - [`Error::LimitExceeded`] if the `Hello` frame is more than
432 /// [`MIN_FRAME_LIMIT`](crate::proto::MIN_FRAME_LIMIT) bytes.
433 /// - [`Error::Protocol`] or [`Error::LimitExceeded`] if the codec refuses
434 /// a frame of the server over ssh, by the rules of
435 /// [`proto`](crate::proto#frames).
436 /// - [`Error::Io`] if a read or a write of the session fails.
437 pub async fn open(self, refs: &[String], opts: SessionOptions) -> Result<PushSession> {
438 self.inner.open(refs, opts).await
439 }
440}
441
442impl fmt::Debug for PreparedSession {
443 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
444 let mut out = f.debug_struct("PreparedSession");
445 match &self.inner {
446 Prepared::Ssh(_) => out.field("transport", &"ssh"),
447 Prepared::Http(endpoint) => out.field("transport", &"http").field("url", &endpoint.url),
448 };
449 out.finish_non_exhaustive()
450 }
451}
452
453/// The transport of a session, checked and ready to open.
454pub(crate) enum Prepared {
455 /// The command line of the ssh client.
456 Ssh(Vec<String>),
457 /// The receive endpoint of an HTTP server.
458 Http(HttpEndpoint),
459}
460
461/// Checks `endpoint` and makes the transport ready to open, with `env` as the
462/// value of the `OSTRYA_SSH_COMMAND` environment variable. For ssh, it builds
463/// the command line. For HTTP, it builds the HTTP client. It starts nothing and
464/// sends nothing.
465async fn prepare_with(endpoint: Endpoint, env: Option<&OsStr>) -> Result<Prepared> {
466 match endpoint {
467 Endpoint::Ssh { address, options } => {
468 let (program, receive) = ssh_parts(&options, env)?;
469 Ok(Prepared::Ssh(address.command_line(program, receive)))
470 }
471 // The HTTP preparation builds the fetcher. Its future is boxed, so
472 // that the future of an ssh connect does not hold it.
473 Endpoint::Http(http) => Ok(Prepared::Http(Box::pin(http::prepare(http)).await?)),
474 #[cfg(feature = "s3")]
475 Endpoint::S3(_) => Err(Error::InvalidInput(S3_SESSION.into())),
476 }
477}
478
479impl Prepared {
480 /// Opens a session over the transport, with the time limits of
481 /// [`PushSession::connect`].
482 async fn open(self, refs: &[String], opts: SessionOptions) -> Result<PushSession> {
483 self.open_with(refs, opts, PENDING_READ_LIMIT).await
484 }
485
486 /// Opens a session as [`open`](Prepared::open) does, with `limit` as the
487 /// time limit of an ssh session.
488 async fn open_with(
489 self,
490 refs: &[String],
491 opts: SessionOptions,
492 limit: Duration,
493 ) -> Result<PushSession> {
494 match self {
495 Prepared::Ssh(argv) => spawn_and_open(&argv, refs, opts, limit).await,
496 // The future is boxed, as the future of the HTTP preparation is.
497 Prepared::Http(endpoint) => {
498 Box::pin(PushSession::open_http(endpoint, refs, opts)).await
499 }
500 }
501 }
502}
503
504/// The open of a session over ssh.
505impl StreamSession {
506 /// Opens a stream session to the ssh address `address`.
507 ///
508 /// The call starts the ssh client, sends `PullHello`, and reads
509 /// `PullHelloReply`. The command line of the ssh client comes from
510 /// `options` by the rules of the
511 /// [ssh command line](SshOptions#ssh-command-line) of a pull. `session`
512 /// gives the agent in `PullHello` and the request limit of the session.
513 ///
514 /// The session has the ssh time limits of [`PushSession::connect`].
515 /// [`finish`](StreamSession::finish) waits for the ssh client as `commit`
516 /// and `abort` of a push do. The session puts no time limit on a read of
517 /// a reply.
518 ///
519 /// Under the tokio backend, the call must run within a runtime that has
520 /// the IO driver and the time driver enabled, as [`PushSession::connect`]
521 /// states. The session runs on the runtime that opened it.
522 ///
523 /// # Errors
524 ///
525 /// - An `Error` message from the server, as the [`Error`] variant of its
526 /// code.
527 /// - [`Error::InvalidInput`] if the ssh command or the send command is
528 /// empty or holds only white space, or if the value of
529 /// `OSTRYA_SSH_COMMAND` is not UTF-8.
530 /// - [`Error::Transport`] if the ssh client cannot be started. The message
531 /// names the program.
532 /// - [`Error::Transport`] if the session fails with [`Error::Io`] and the
533 /// ssh client exits with a failure status. The message holds the status.
534 /// - [`Error::VersionUnsupported`] if the reply has a pull version outside
535 /// 1 to [`PULL_PROTOCOL_VERSION`](crate::proto::PULL_PROTOCOL_VERSION).
536 /// The session then closes its output and sends no `Get`.
537 /// - [`Error::Protocol`] if the reply is not `PullHelloReply`.
538 /// - [`Error::Protocol`] if the [`agent`](StreamSessionOptions::agent) of
539 /// `session` holds a NUL byte.
540 /// - [`Error::LimitExceeded`] if the `PullHello` frame is more than
541 /// [`MIN_FRAME_LIMIT`](crate::proto::MIN_FRAME_LIMIT) bytes.
542 /// - [`Error::Protocol`] or [`Error::LimitExceeded`] if the codec refuses
543 /// a frame of the server, by the rules of
544 /// [`proto`](crate::proto#frames).
545 /// - [`Error::Io`] if a read or a write of the session fails, or if the
546 /// session ends before the reply.
547 ///
548 /// # Examples
549 ///
550 /// ```no_run
551 /// use futures_lite::AsyncReadExt;
552 /// use ostrya_remote::session::{StreamSession, StreamSessionOptions};
553 /// use ostrya_remote::transport::{SshAddress, SshOptions};
554 /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
555 /// let address = SshAddress::parse("builder@repo.example.com:/srv/repo")?;
556 /// let options = SshOptions::default();
557 /// let session = StreamSession::connect(&address, &options, StreamSessionOptions::default()).await?;
558 /// if let Some(mut body) = session.get("config", 1 << 20).await? {
559 /// let mut config = Vec::new();
560 /// body.read_to_end(&mut config).await?;
561 /// }
562 /// session.finish().await?;
563 /// # Ok(()) }
564 /// ```
565 pub async fn connect(
566 address: &SshAddress,
567 options: &SshOptions,
568 session: StreamSessionOptions,
569 ) -> Result<StreamSession> {
570 let env = std::env::var_os("OSTRYA_SSH_COMMAND");
571 let argv = pull_command_line(address, options, env.as_deref())?;
572 spawn_and_open_pull(&argv, session, PENDING_READ_LIMIT).await
573 }
574
575 /// Checks the command line of the ssh client that
576 /// [`connect`](StreamSession::connect) builds for `address` and
577 /// `options`.
578 ///
579 /// The call reads the `OSTRYA_SSH_COMMAND` environment variable, and
580 /// applies the [Empty values](SshOptions#empty-values) rules of a pull. It
581 /// starts no ssh client. A caller that opens sessions to more than one
582 /// remote can make this check for each remote before its first request.
583 ///
584 /// # Errors
585 ///
586 /// - [`Error::InvalidInput`] if the ssh command or the send command is
587 /// empty or holds only white space, or if the value of
588 /// `OSTRYA_SSH_COMMAND` is not UTF-8.
589 pub fn check_command_line(address: &SshAddress, options: &SshOptions) -> Result<()> {
590 let env = std::env::var_os("OSTRYA_SSH_COMMAND");
591 pull_command_line(address, options, env.as_deref()).map(drop)
592 }
593}
594
595/// The open of the session of a pull over ssh or HTTP.
596impl PullSession {
597 /// Opens the session of a pull to `endpoint`.
598 ///
599 /// For an [`Endpoint::Ssh`], the call is [`StreamSession::connect`] with
600 /// the address, the ssh options, and `opts`. The result is
601 /// [`PullSession::Stream`].
602 ///
603 /// For an [`Endpoint::Http`], the call builds the fetcher with
604 /// [`Fetcher::new`](ostrya_fetch::Fetcher::new), and the result is
605 /// [`PullSession::Http`]. The call sends no HTTP request.
606 ///
607 /// For an `Endpoint::S3`, the call builds the fetcher from the options
608 /// that `S3Endpoint::pull_options` gives, and the result is
609 /// [`PullSession::Http`]. The fetcher signs each request. The call sends
610 /// no HTTP request.
611 ///
612 /// Under the tokio backend, the call must run within a runtime that has
613 /// the IO driver and the time driver enabled, as [`PushSession::connect`]
614 /// states.
615 ///
616 /// # HTTP options
617 ///
618 /// The call gives the options of the endpoint to the fetcher with no
619 /// change:
620 ///
621 /// - The options can name one or more mirrors.
622 /// - The fetcher follows redirects up to
623 /// [`max_redirects`](ostrya_fetch::FetcherOptions::max_redirects).
624 /// - [`max_outstanding`](ostrya_fetch::FetcherOptions::max_outstanding) is
625 /// the request limit of the pull.
626 /// - A `User-Agent` entry of
627 /// [`headers`](ostrya_fetch::FetcherOptions::headers) sets the agent.
628 /// - The call does not apply [`check_base_url`](ostrya_fetch::check_base_url)
629 /// to the mirrors.
630 ///
631 /// The options give the agent and the request limit, so `opts` must set no
632 /// field.
633 ///
634 /// With [`TrustRoots::System`](ostrya_fetch::TrustRoots::System), the call
635 /// reads the trust store of the host by the rule of
636 /// [`Fetcher::new`](ostrya_fetch::Fetcher::new). An `https://` mirror
637 /// causes the read. The options that [`Endpoint::parse`] gives an
638 /// `http://` address also cause it, because their `max_redirects` is 10.
639 ///
640 /// # Errors
641 ///
642 /// - The errors of [`StreamSession::connect`] for an ssh endpoint.
643 /// - [`Error::InvalidInput`] if `opts` sets
644 /// [`agent`](StreamSessionOptions::agent) or
645 /// [`max_outstanding`](StreamSessionOptions::max_outstanding) for an HTTP
646 /// endpoint.
647 /// - [`Error::InvalidInput`] if the options of an HTTP endpoint name no
648 /// mirror.
649 /// - [`Error::InvalidInput`] for an `Endpoint::S3` if the signer refuses
650 /// its region, or if `opts` sets a field.
651 /// - [`Error::Fetch`] if [`Fetcher::new`](ostrya_fetch::Fetcher::new)
652 /// refuses the options of an HTTP endpoint or of an `Endpoint::S3`. An
653 /// example is an S3 endpoint at an `http://` URL with
654 /// [`allow_cleartext_credentials`](ostrya_fetch::FetcherOptions::allow_cleartext_credentials)
655 /// set to `false`.
656 pub async fn connect(endpoint: Endpoint, opts: StreamSessionOptions) -> Result<PullSession> {
657 match endpoint {
658 Endpoint::Ssh { address, options } => StreamSession::connect(&address, &options, opts)
659 .await
660 .map(PullSession::Stream),
661 // The future of the fetcher construction is boxed, so that the
662 // future of an ssh connect does not hold it.
663 Endpoint::Http(http) => Ok(PullSession::Http(
664 Box::pin(http::prepare_pull(http, opts)).await?,
665 )),
666 #[cfg(feature = "s3")]
667 // The S3 endpoint gives the options of a signed HTTP pull.
668 Endpoint::S3(s3) => Ok(PullSession::Http(
669 Box::pin(http::prepare_pull(s3.pull_options()?, opts)).await?,
670 )),
671 }
672 }
673}
674
675/// Builds the command line of the ssh client of a pull to `address`, with
676/// `env` as the value of the `OSTRYA_SSH_COMMAND` environment variable.
677fn pull_command_line(
678 address: &SshAddress,
679 options: &SshOptions,
680 env: Option<&OsStr>,
681) -> Result<Vec<String>> {
682 let program = options.program(env)?;
683 let send = ssh::send_command(options.remote_command.as_deref())?;
684 Ok(address.command_line(program, send))
685}
686
687/// Starts `argv` and opens a stream session over its standard input and
688/// standard output, with `limit` as the time limit of the session.
689async fn spawn_and_open_pull(
690 argv: &[String],
691 opts: StreamSessionOptions,
692 limit: Duration,
693) -> Result<StreamSession> {
694 let (input, output, transport) = Transport::spawn(argv, limit)?;
695 match StreamSession::open(input, output, opts, Some(limit)).await {
696 Ok(session) => Ok(session.with_transport(transport)),
697 Err(e) => transport.finish(Err(e)).await,
698 }
699}
700
701/// Opens a stream session as [`StreamSession::connect`] does, with the value of
702/// the environment variable and the time limit as parameters.
703#[cfg(test)]
704async fn connect_pull_with(
705 address: &SshAddress,
706 options: &SshOptions,
707 env: Option<&OsStr>,
708 opts: StreamSessionOptions,
709 limit: Duration,
710) -> Result<StreamSession> {
711 let argv = pull_command_line(address, options, env)?;
712 spawn_and_open_pull(&argv, opts, limit).await
713}
714
715/// Opens a push session as [`PushSession::connect`] does, with the value of
716/// the environment variable and the time limit as parameters.
717#[cfg(test)]
718async fn connect_with(
719 endpoint: Endpoint,
720 env: Option<&OsStr>,
721 refs: &[String],
722 opts: SessionOptions,
723 limit: Duration,
724) -> Result<PushSession> {
725 prepare_with(endpoint, env)
726 .await?
727 .open_with(refs, opts, limit)
728 .await
729}
730
731/// Starts `argv` and opens a push session over its standard input and
732/// standard output, with `limit` as the time limit of the session.
733async fn spawn_and_open(
734 argv: &[String],
735 refs: &[String],
736 opts: SessionOptions,
737 limit: Duration,
738) -> Result<PushSession> {
739 let (input, output, transport) = Transport::spawn(argv, limit)?;
740 match PushSession::open(input, output, refs, opts, Some(limit)).await {
741 Ok(session) => Ok(session.with_transport(transport)),
742 Err(e) => transport.finish(Err(e)).await,
743 }
744}
745
746#[cfg(test)]
747mod tests;