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
487
488
489
490
//! Transports for communicating with the docker daemon

use crate::{Error, Result};

use futures_util::{
    io::{AsyncRead, AsyncWrite},
    stream::{self, Stream},
    StreamExt, TryFutureExt,
};
use hyper::{
    body::Bytes,
    client::{Client, HttpConnector},
    header, Body, Method, Request, Response, StatusCode,
};
#[cfg(feature = "tls")]
use hyper_openssl::HttpsConnector;
#[cfg(unix)]
use hyperlocal::UnixConnector;
#[cfg(unix)]
use hyperlocal::Uri as DomainUri;
use pin_project::pin_project;

use serde::{Deserialize, Serialize};
use url::Url;

use std::{
    io,
    iter::IntoIterator,
    path::PathBuf,
    pin::Pin,
    task::{Context, Poll},
};

#[derive(Debug, Default, Clone)]
/// Helper structure used as a container for HTTP headers passed to a request
pub(crate) struct Headers(Vec<(&'static str, String)>);

impl Headers {
    /// Shortcut for when one does not want headers in a request
    pub fn none() -> Option<Headers> {
        None
    }

    /// Adds a single key=value header pair
    pub fn add<V>(&mut self, key: &'static str, val: V)
    where
        V: Into<String>,
    {
        self.0.push((key, val.into()))
    }

    /// Constructs an instance of Headers with initial pair, usually used when there is only
    /// a need for one header.
    pub fn single<V>(key: &'static str, val: V) -> Self
    where
        V: Into<String>,
    {
        let mut h = Self::default();
        h.add(key, val);
        h
    }
}

impl IntoIterator for Headers {
    type Item = (&'static str, String);
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

/// Types of payload that can be sent
pub(crate) enum Payload<B: Into<Body>> {
    None,
    #[allow(dead_code)]
    Text(B),
    Json(B),
    XTar(B),
    Tar(B),
}

impl Payload<Body> {
    /// Creates an empty payload
    pub fn empty() -> Self {
        Payload::None
    }
}

impl<B: Into<Body>> Payload<B> {
    /// Extracts the inner body if there is one and returns it
    pub fn into_inner(self) -> Option<B> {
        match self {
            Self::None => None,
            Self::Text(b) => Some(b),
            Self::Json(b) => Some(b),
            Self::XTar(b) => Some(b),
            Self::Tar(b) => Some(b),
        }
    }

    /// Returns the mime type of this payload
    pub fn mime_type(&self) -> Option<mime::Mime> {
        match &self {
            Self::None => None,
            Self::Text(_) => None,
            Self::Json(_) => Some(mime::APPLICATION_JSON),
            Self::XTar(_) => Some("application/x-tar".parse().expect("parsed mime")),
            Self::Tar(_) => Some("application/tar".parse().expect("parsed mime")),
        }
    }

    /// Checks if there is no payload
    pub fn is_none(&self) -> bool {
        matches!(self, Self::None)
    }
}

/// Transports are types which define the means of communication
/// with the docker daemon
#[derive(Clone, Debug)]
pub enum Transport {
    /// A network tcp interface
    Tcp {
        client: Client<HttpConnector>,
        host: Url,
    },
    /// TCP/TLS
    #[cfg(feature = "tls")]
    #[cfg_attr(docsrs, doc(cfg(feature = "tls")))]
    EncryptedTcp {
        client: Client<HttpsConnector<HttpConnector>>,
        host: Url,
    },
    /// A Unix domain socket
    #[cfg(unix)]
    Unix {
        client: Client<UnixConnector>,
        path: PathBuf,
    },
}

impl Transport {
    pub fn remote_addr(&self) -> &str {
        match &self {
            Self::Tcp { ref host, .. } => host.as_ref(),
            #[cfg(feature = "tls")]
            Self::EncryptedTcp { ref host, .. } => host.as_ref(),
            Self::Unix { ref path, .. } => path.to_str().unwrap_or_default(),
        }
    }

    pub(crate) async fn request<B>(
        &self,
        method: Method,
        endpoint: impl AsRef<str>,
        body: Payload<B>,
        headers: Option<Headers>,
    ) -> Result<Response<Body>>
    where
        B: Into<Body>,
    {
        let req = self.build_request(method, endpoint, body, headers, Request::builder())?;

        self.send_request(req).await
    }

    pub(crate) async fn request_string<B>(
        &self,
        method: Method,
        endpoint: impl AsRef<str>,
        body: Payload<B>,
        headers: Option<Headers>,
    ) -> Result<String>
    where
        B: Into<Body>,
    {
        let body = self.get_body(method, endpoint, body, headers).await?;
        let bytes = hyper::body::to_bytes(body).await?;
        String::from_utf8(bytes.to_vec()).map_err(Error::from)
    }

    pub(crate) fn stream_chunks<'transport, B>(
        &'transport self,
        method: Method,
        endpoint: impl AsRef<str> + 'transport,
        body: Payload<B>,
        headers: Option<Headers>,
    ) -> impl Stream<Item = Result<Bytes>> + 'transport
    where
        B: Into<Body> + 'transport,
    {
        self.get_chunk_stream(method, endpoint, body, headers)
            .try_flatten_stream()
    }

    pub(crate) fn stream_json_chunks<'transport, B>(
        &'transport self,
        method: Method,
        endpoint: impl AsRef<str> + 'transport,
        body: Payload<B>,
        headers: Option<Headers>,
    ) -> impl Stream<Item = Result<Bytes>> + 'transport
    where
        B: Into<Body> + 'transport,
    {
        self.get_json_chunk_stream(method, endpoint, body, headers)
            .try_flatten_stream()
    }

    pub(crate) async fn stream_upgrade<B>(
        &self,
        method: Method,
        endpoint: impl AsRef<str>,
        body: Payload<B>,
    ) -> Result<impl AsyncRead + AsyncWrite>
    where
        B: Into<Body>,
    {
        self.stream_upgrade_tokio(method, endpoint, body)
            .await
            .map(Compat::new)
            .map_err(Error::from)
    }

    async fn get_body<B>(
        &self,
        method: Method,
        endpoint: impl AsRef<str>,
        body: Payload<B>,
        headers: Option<Headers>,
    ) -> Result<Body>
    where
        B: Into<Body>,
    {
        let response = self.request(method, endpoint, body, headers).await?;

        let status = response.status();

        match status {
            // Success case: pass on the response
            StatusCode::OK
            | StatusCode::CREATED
            | StatusCode::SWITCHING_PROTOCOLS
            | StatusCode::NO_CONTENT => Ok(response.into_body()),
            _ => {
                let bytes = hyper::body::to_bytes(response.into_body()).await?;
                let message_body = String::from_utf8(bytes.to_vec())?;

                Err(Error::Fault {
                    code: status,
                    message: Self::get_error_message(&message_body).unwrap_or_else(|| {
                        status
                            .canonical_reason()
                            .unwrap_or("unknown error code")
                            .to_owned()
                    }),
                })
            }
        }
    }

    async fn get_chunk_stream<B>(
        &self,
        method: Method,
        endpoint: impl AsRef<str>,
        body: Payload<B>,
        headers: Option<Headers>,
    ) -> Result<impl Stream<Item = Result<Bytes>>>
    where
        B: Into<Body>,
    {
        self.get_body(method, endpoint, body, headers)
            .await
            .map(stream_body)
    }

    async fn get_json_chunk_stream<B>(
        &self,
        method: Method,
        endpoint: impl AsRef<str>,
        body: Payload<B>,
        headers: Option<Headers>,
    ) -> Result<impl Stream<Item = Result<Bytes>>>
    where
        B: Into<Body>,
    {
        self.get_body(method, endpoint, body, headers)
            .await
            .map(stream_json_body)
    }

    /// Builds an HTTP request.
    fn build_request<B>(
        &self,
        method: Method,
        endpoint: impl AsRef<str>,
        body: Payload<B>,
        headers: Option<Headers>,
        builder: hyper::http::request::Builder,
    ) -> Result<Request<Body>>
    where
        B: Into<Body>,
    {
        let ep = endpoint.as_ref();
        let ep = format!(
            "/{}{}{}",
            crate::VERSION,
            if !ep.starts_with('/') { "/" } else { "" },
            ep
        );

        // As noted in [Versioning](https://docs.docker.com/engine/api/v1.41/#section/Versioning), all requests
        // should be prefixed with the API version as the ones without will stop being supported in future releases
        let uri: hyper::Uri = match self {
            Transport::Tcp { host, .. } => format!("{}{}", host, ep)
                .parse()
                .map_err(Error::InvalidUri)?,
            #[cfg(feature = "tls")]
            Transport::EncryptedTcp { host, .. } => format!("{}{}", host, ep)
                .parse()
                .map_err(Error::InvalidUri)?,
            #[cfg(unix)]
            Transport::Unix { path, .. } => DomainUri::new(&path, &ep).into(),
        };
        let req = builder.method(method).uri(&uri);
        let mut req = req.header(header::HOST, "");

        if let Some(h) = headers {
            for (k, v) in h.into_iter() {
                req = req.header(k, v);
            }
        }

        // early return
        if body.is_none() {
            return Ok(req.body(Body::empty())?);
        }

        let mime = body.mime_type();
        if let Some(c) = mime {
            req = req.header(header::CONTENT_TYPE, &c.to_string());
        }

        // it's ok to unwrap, we check that the body is not none
        req.body(body.into_inner().unwrap().into())
            .map_err(Error::from)
    }

    /// Send the given request to the docker daemon and return a Future of the response.
    async fn send_request(&self, req: Request<Body>) -> Result<Response<Body>> {
        match self {
            Transport::Tcp { ref client, .. } => client.request(req),
            #[cfg(feature = "tls")]
            Transport::EncryptedTcp { ref client, .. } => client.request(req),
            #[cfg(unix)]
            Transport::Unix { ref client, .. } => client.request(req),
        }
        .await
        .map_err(Error::from)
    }

    /// Makes an HTTP request, upgrading the connection to a TCP
    /// stream on success.
    ///
    /// This method can be used for operations such as viewing
    /// docker container logs interactively.
    async fn stream_upgrade_tokio<B>(
        &self,
        method: Method,
        endpoint: impl AsRef<str>,
        body: Payload<B>,
    ) -> Result<hyper::upgrade::Upgraded>
    where
        B: Into<Body>,
    {
        let req = self.build_request(
            method,
            endpoint,
            body,
            Headers::none(),
            Request::builder()
                .header(header::CONNECTION, "Upgrade")
                .header(header::UPGRADE, "tcp"),
        )?;

        let response = self.send_request(req).await?;
        match response.status() {
            StatusCode::SWITCHING_PROTOCOLS => Ok(hyper::upgrade::on(response).await?),
            _ => Err(Error::ConnectionNotUpgraded),
        }
    }

    /// Extract the error message content from an HTTP response that
    /// contains a Docker JSON error structure.
    fn get_error_message(body: &str) -> Option<String> {
        serde_json::from_str::<ErrorResponse>(body)
            .map(|e| e.message)
            .ok()
    }
}

#[pin_project]
struct Compat<S> {
    #[pin]
    tokio_multiplexer: S,
}

impl<S> Compat<S> {
    fn new(tokio_multiplexer: S) -> Self {
        Self { tokio_multiplexer }
    }
}

impl<S> AsyncRead for Compat<S>
where
    S: tokio::io::AsyncRead,
{
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        let mut readbuf = tokio::io::ReadBuf::new(buf);
        match self.project().tokio_multiplexer.poll_read(cx, &mut readbuf) {
            Poll::Pending => Poll::Pending,
            Poll::Ready(Ok(())) => Poll::Ready(Ok(readbuf.filled().len())),
            Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
        }
    }
}

impl<S> AsyncWrite for Compat<S>
where
    S: tokio::io::AsyncWrite,
{
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        self.project().tokio_multiplexer.poll_write(cx, buf)
    }
    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        self.project().tokio_multiplexer.poll_flush(cx)
    }
    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        self.project().tokio_multiplexer.poll_shutdown(cx)
    }
}

#[derive(Serialize, Deserialize)]
struct ErrorResponse {
    message: String,
}

fn stream_body(body: Body) -> impl Stream<Item = Result<Bytes>> {
    async fn unfold(mut body: Body) -> Option<(Result<Bytes>, Body)> {
        body.next()
            .await
            .map(|chunk| (chunk.map_err(Error::from), body))
    }

    stream::unfold(body, unfold)
}

static JSON_WHITESPACE: &[u8] = b"\r\n";

fn stream_json_body(body: Body) -> impl Stream<Item = Result<Bytes>> {
    async fn unfold(mut body: Body) -> Option<(Result<Bytes>, Body)> {
        let mut chunk = Vec::new();
        while let Some(chnk) = body.next().await {
            match chnk {
                Ok(chnk) => {
                    chunk.extend(chnk.to_vec());
                    if chnk.ends_with(JSON_WHITESPACE) {
                        break;
                    }
                }
                Err(e) => {
                    return Some((Err(Error::from(e)), body));
                }
            }
        }

        Some((Ok(Bytes::from(chunk)), body))
    }

    stream::unfold(body, unfold)
}