apt-transport 0.1.0

APT transport abstraction, allowing for custom APT transport implementations in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
use std::collections::HashMap;

use crate::{
    Error,
    message::{Message, MessageType},
    message_stream::MessageStream,
};
use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncWrite, AsyncWriteExt, BufReader};

/// Asynchronous event stream for APT transport implementations.
pub struct AptStream {
    inner: Box<dyn AsyncBufRead + Unpin + Send>,
    message_stream: MessageStream,
    output_stream: Box<dyn AsyncWrite + Unpin + Send>,
    has_initialized: bool,
}

impl AptStream {
    /// Create a new `AsyncAptStream` with stdin/stdout as the underlying streams.
    pub fn new() -> Self {
        Self {
            inner: Box::new(BufReader::new(tokio::io::stdin())),
            message_stream: MessageStream::default(),
            output_stream: Box::new(tokio::io::stdout()),
            has_initialized: false,
        }
    }

    /// Sets the input stream for reading APT requests.
    ///
    /// Must only be set before any requests are processed
    /// (i.e. the first call to `.next()`), and should
    /// ultimately be routed to the stdin of the transport process
    /// that `apt` has spawned.
    pub fn with_input_stream(
        mut self,
        input_stream: Box<dyn AsyncBufRead + Unpin + Send>,
    ) -> Result<Self, Error> {
        if self.has_initialized {
            return Err(Error::StreamAlreadyInitialized);
        }
        self.inner = Box::new(input_stream);
        Ok(self)
    }

    /// Sets the output stream for all response writes.
    ///
    /// Must only be set before any requests are processed
    /// (i.e. the first call to `.next()`), and should
    /// ultimately be routed to the stdout of the transport process
    /// that `apt` has spawned.
    pub fn with_output_stream(
        mut self,
        output_stream: Box<dyn AsyncWrite + Unpin + Send>,
    ) -> Result<Self, Error> {
        if self.has_initialized {
            return Err(Error::StreamAlreadyInitialized);
        }
        self.output_stream = output_stream;
        Ok(self)
    }

    /// Pulls the next APT request from the stream.
    pub async fn next<'a>(&'a mut self) -> Result<Option<AptRequest<'a>>, Error> {
        if !self.has_initialized {
            self.has_initialized = true;

            // Synthesize a capabilities request at the start of the stream
            log::debug!("synthesizing capabilities request");
            let capabilities_req = AptRequest::Capabilities(CapabilitiesRequest { this: self });

            return Ok(Some(capabilities_req));
        }

        // Read lines until we get a complete message
        let mut line = String::new();
        loop {
            log::trace!("reading line from input stream");
            line.clear();
            let nread = self.inner.as_mut().read_line(&mut line).await?;
            log::trace!(
                "read {} bytes from input stream: {:?}",
                nread,
                line.as_bytes()
            );

            if let Some(message_result) = self.message_stream.push_line(line.as_bytes()) {
                log::debug!("complete message received");
                log::trace!("complete message received: {:?}", message_result);

                match message_result {
                    Ok(message) => {
                        let apt_request = AptRequest::<'a>::try_from_message((self, message)).await;

                        return match apt_request {
                            Ok(req) => {
                                log::debug!("APT request parse OK");
                                Ok(Some(req))
                            }
                            Err(e) => {
                                log::debug!("APT request parse error: {e:#?}");
                                Err(e)
                            }
                        };
                    }
                    Err(e) => {
                        log::debug!("APT message parse error: {e:?}");
                        return Err(e);
                    }
                }
            } else if nread == 0 {
                // EOF reached
                log::debug!("EOF reached on input stream");
                return Ok(None);
            }
        }
    }
}

/// An APT request.
pub enum AptRequest<'a> {
    /// A request for capabilities
    Capabilities(CapabilitiesRequest<'a>),
    /// A configuration request
    Configuration(ConfigRequest),
    /// A URI acquire request
    Uri(UriRequest<'a>),
}

/// An APT capabilities request.
pub struct CapabilitiesRequest<'a> {
    this: &'a mut AptStream,
}

impl<'a> CapabilitiesRequest<'a> {
    /// Creates a response for the capabilities request.
    #[must_use = "responses must be sent to the APT client with `.send().await`"]
    pub fn respond(self) -> CapabilitiesResponse<'a> {
        CapabilitiesResponse::new(self.this)
    }
}

/// A builder for APT capabilities responses.
pub struct CapabilitiesResponse<'a> {
    this: &'a mut AptStream,
    single_instance: bool,
    send_config: bool,
    pipeline: bool,
    local_only: bool,
    removable: bool,
    needs_cleanup: bool,
    version: String,
}

impl CapabilitiesResponse<'_> {
    /// Creates a new builder.
    #[must_use]
    fn new(this: &mut AptStream) -> CapabilitiesResponse<'_> {
        CapabilitiesResponse {
            this,
            single_instance: false,
            send_config: false,
            pipeline: false,
            local_only: false,
            removable: false,
            needs_cleanup: false,
            version: env!("CARGO_PKG_VERSION").to_string(),
        }
    }

    /// Whether or not to advertise single-instance support.
    #[must_use = "responses must be sent with `.send().await`"]
    pub fn single_instance(mut self, enabled: bool) -> Self {
        self.single_instance = enabled;
        self
    }

    /// Whether or not to advertise send-config support.
    #[must_use = "responses must be sent with `.send().await`"]
    pub fn send_config(mut self, enabled: bool) -> Self {
        self.send_config = enabled;
        self
    }

    /// Sets the version string to advertise.
    ///
    /// By default this is set to the `apt-transport` crate version, though
    /// this can be (should be) overridden to match the transport implementation version:
    ///
    /// ```ignore
    /// response.version(env!("CARGO_PKG_VERSION")).send().await?;
    /// ```
    #[must_use = "responses must be sent with `.send().await`"]
    pub fn version<S: Into<String>>(mut self, version: S) -> Self {
        self.version = version.into();
        self
    }

    /// Whether or not to advertise pipeline support.
    #[must_use = "responses must be sent with `.send().await`"]
    pub fn pipeline(mut self, enabled: bool) -> Self {
        self.pipeline = enabled;
        self
    }

    // Whether or not to advertise local-only support.
    #[must_use = "responses must be sent with `.send().await`"]
    pub fn local_only(mut self, enabled: bool) -> Self {
        self.local_only = enabled;
        self
    }

    /// Whether or not to advertise removable support.
    #[must_use = "responses must be sent with `.send().await`"]
    pub fn removable(mut self, enabled: bool) -> Self {
        self.removable = enabled;
        self
    }

    /// Whether or not to advertise needs-cleanup support.
    #[must_use = "responses must be sent with `.send().await`"]
    pub fn needs_cleanup(mut self, enabled: bool) -> Self {
        self.needs_cleanup = enabled;
        self
    }

    /// Responds with the given capabilities.
    pub async fn send(self) -> Result<(), Error> {
        let msg = Message::new(
            MessageType::Capabilities,
            vec![
                ("Version", &self.version),
                (
                    "Send-Config",
                    if self.send_config { "true" } else { "false" },
                ),
                (
                    "Single-Instance",
                    if self.single_instance {
                        "true"
                    } else {
                        "false"
                    },
                ),
                ("Pipeline", if self.pipeline { "true" } else { "false" }),
                ("Local-Only", if self.local_only { "true" } else { "false" }),
                ("Removable", if self.removable { "true" } else { "false" }),
                (
                    "Needs-Cleanup",
                    if self.needs_cleanup { "true" } else { "false" },
                ),
            ],
        )
        .to_string();

        log::debug!("sending capabilities response");
        log::trace!("sending capabilities response: {}", msg.trim());
        self.this
            .output_stream
            .as_mut()
            .write_all(msg.as_bytes())
            .await?;

        log::debug!("flushing output stream");
        self.this.output_stream.as_mut().flush().await?;

        log::debug!("capabilities response sent successfully");
        Ok(())
    }
}

/// Configuration request, containing all configuration options.
///
/// This request has no response.
pub struct ConfigRequest {
    options: HashMap<String, String>,
}

impl ConfigRequest {
    fn from(message: Message) -> Self {
        let options = message
            .headers
            .into_iter()
            .filter_map(|(key, value)| {
                if key == "Config-Item" {
                    let (key, value) = value.split_once('=')?;
                    Some((key.to_string(), value.to_string()))
                } else {
                    None
                }
            })
            .collect::<HashMap<String, String>>();

        ConfigRequest { options }
    }

    /// Gets the configuration options.
    pub fn options(&self) -> &HashMap<String, String> {
        &self.options
    }
}

/// A request against the URI.
pub struct UriRequest<'a> {
    this: &'a mut AptStream,
    uri: String,
    repo_uri: String,
    filename: String,
}

impl<'a> UriRequest<'a> {
    /// Attempts to parse the URI request from the message.
    async fn from(this: &'a mut AptStream, message: Message) -> Result<UriRequest<'a>, Error> {
        let Ok(uri) = message.header("URI") else {
            let msg = Message::uri_failure("", "Missing URI header").to_string();
            this.output_stream.write_all(msg.as_bytes()).await?;
            this.output_stream.as_mut().flush().await?;
            return Err(Error::HeaderNotFound("URI".to_string()));
        };

        let Ok(filename) = message.header("Filename") else {
            let msg = Message::uri_failure(uri, "Missing Filename header").to_string();
            this.output_stream.write_all(msg.as_bytes()).await?;
            this.output_stream.as_mut().flush().await?;
            return Err(Error::HeaderNotFound("Filename".to_string()));
        };

        let Ok(target_uri) = message.header("Target-Site") else {
            let msg = Message::uri_failure(uri, "Missing Target-Site header").to_string();
            this.output_stream.write_all(msg.as_bytes()).await?;
            this.output_stream.as_mut().flush().await?;
            return Err(Error::HeaderNotFound("Target-Site".to_string()));
        };

        Ok(UriRequest {
            this,
            uri: uri.to_string(),
            repo_uri: target_uri.to_string(),
            filename: filename.to_string(),
        })
    }

    /// Gets the URI for the request.
    pub fn uri(&self) -> &str {
        &self.uri
    }

    /// The filename to save the acquired URI to.
    pub fn filename(&self) -> &str {
        &self.filename
    }

    /// The originally configured URI for the repository.
    ///
    /// This is different from `uri()` in that it is the original
    /// URI configured in the APT sources, whereas `uri()` has the
    /// full URI that is being requested.
    pub fn repo_uri(&self) -> &str {
        &self.repo_uri
    }

    /// Sends a status (update message) to the APT client,
    /// indicating progress on the request.
    ///
    /// This does not consume the request, so multiple status
    /// updates can be sent for a single request.
    pub async fn send_status(&mut self, status: &str) -> Result<(), Error> {
        let msg = Message::status(status).to_string();
        self.this
            .output_stream
            .as_mut()
            .write_all(msg.as_bytes())
            .await?;
        self.this.output_stream.as_mut().flush().await?;
        Ok(())
    }

    /// Responds with a failure for the URI request.
    ///
    /// This immediately cancels the fetch and notifies APT of the failure.
    pub async fn fail(self, reason: &str) -> Result<(), Error> {
        let msg = Message::uri_failure(&self.uri, reason).to_string();
        self.this
            .output_stream
            .as_mut()
            .write_all(msg.as_bytes())
            .await?;
        self.this.output_stream.as_mut().flush().await?;
        Ok(())
    }

    /// Begins the response for the URI request.
    ///
    /// This tells APT that the initial metadata fetch was successful,
    /// and provides the size and last-modified time of the resource.
    pub async fn start(
        self,
        size_in_bytes: u64,
        last_modified: &str,
    ) -> Result<UriResponse<'a>, Error> {
        let msg = Message::uri_start(&self.uri, size_in_bytes, last_modified).to_string();
        self.this
            .output_stream
            .as_mut()
            .write_all(msg.as_bytes())
            .await?;
        self.this.output_stream.as_mut().flush().await?;
        Ok(UriResponse {
            this: self.this,
            uri: self.uri,
            filename: self.filename,
        })
    }
}

/// A builder for URI responses.
pub struct UriResponse<'a> {
    this: &'a mut AptStream,
    uri: String,
    filename: String,
}

impl UriResponse<'_> {
    /// Tells the APT client that the URI request has completed successfully.
    pub async fn complete(self) -> Result<(), Error> {
        let msg = Message::uri_success(&self.uri, &self.filename).to_string();
        self.this
            .output_stream
            .as_mut()
            .write_all(msg.as_bytes())
            .await?;
        self.this.output_stream.as_mut().flush().await?;
        Ok(())
    }

    /// Tells the APT client that the URI request has failed.
    pub async fn fail(self, reason: &str) -> Result<(), Error> {
        let msg = Message::uri_failure(&self.uri, reason).to_string();
        self.this
            .output_stream
            .as_mut()
            .write_all(msg.as_bytes())
            .await?;
        self.this.output_stream.as_mut().flush().await?;
        Ok(())
    }

    /// Creates a writer for writing the URI data to the target file.
    ///
    /// Creates the file with user read/write permissions only.
    pub async fn writer(&self) -> Result<impl tokio::io::AsyncWrite + 'static, Error> {
        Ok(tokio::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .mode(0o600)
            .open(self.filename.clone())
            .await?)
    }
}

trait TryFromMessage<'a>: Sized {
    type Error;

    async fn try_from_message(msg: (&'a mut AptStream, Message)) -> Result<Self, Self::Error>;
}

impl<'a> TryFromMessage<'a> for AptRequest<'a> {
    type Error = Error;

    async fn try_from_message(
        (this, message): (&'a mut AptStream, Message),
    ) -> Result<Self, Self::Error> {
        match message.message_type {
            MessageType::Configuration => {
                let config_request = ConfigRequest::from(message);
                Ok(AptRequest::Configuration(config_request))
            }
            MessageType::URIAcquire => {
                let uri_request = UriRequest::from(this, message).await?;
                Ok(AptRequest::Uri(uri_request))
            }
            other => Err(Error::UnexpectedMessageType(other, message)),
        }
    }
}