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
//! Connect hyper servers and clients to Unix-domain sockets.
//!
//! Most of this crate's functionality is borrowed from [hyperlocal](https://github.com/softprops/hyperlocal).
//! This crate supports async/await, while hyperlocal does not (yet).
//!
//! See [`UnixClient`] and [`UnixConnector`] for examples.

use core::{
    pin::Pin,
    task::{Context, Poll},
};
use failure::Error;
use futures_util::future::{FutureExt, TryFutureExt};
use hex::FromHex;
use pin_project::pin_project;
use std::borrow::Cow;
use std::future::Future;
use std::path::Path;

/// A type which implements `Into` for hyper's  [`hyper::Uri`] type
/// targetting unix domain sockets.
///
/// You can use this with any of
/// the HTTP factory methods on hyper's Client interface
/// and for creating requests.
///
/// ```no_run
/// extern crate hyper;
/// extern crate hyper_unix_connector;
///
/// let url: hyper::Uri = hyper_unix_connector::Uri::new(
///   "/path/to/socket", "/urlpath?key=value"
///  ).into();
///  let req = hyper::Request::get(url).body(()).unwrap();
/// ```
#[derive(Debug)]
pub struct Uri<'a> {
    /// url path including leading slash, path, and query string
    encoded: Cow<'a, str>,
}

impl<'a> Into<hyper::Uri> for Uri<'a> {
    fn into(self) -> hyper::Uri {
        self.encoded.as_ref().parse().unwrap()
    }
}

impl<'a> Uri<'a> {
    /// Productes a new `Uri` from path to domain socket and request path.
    /// request path should include a leading slash
    pub fn new<P>(socket: P, path: &'a str) -> Self
    where
        P: AsRef<Path>,
    {
        let host = hex::encode(socket.as_ref().to_string_lossy().as_bytes());
        let host_str = format!("unix://{}:0{}", host, path);
        Uri {
            encoded: Cow::Owned(host_str),
        }
    }

    // fixme: would like to just use hyper::Result and hyper::error::UriError here
    // but UriError its not exposed for external use
    fn socket_path(uri: &hyper::Uri) -> Option<String> {
        uri.host()
            .iter()
            .filter_map(|host| {
                Vec::from_hex(host)
                    .ok()
                    .map(|raw| String::from_utf8_lossy(&raw).into_owned())
            })
            .next()
    }
}

/// Wrapper around [`tokio::net::UnixListener`] that works with [`hyper`] servers.
///
/// Useful for making [`hyper`] servers listen on Unix sockets. For the client side, see
/// [`UnixClient`].
///
/// # Example
/// ```rust
/// # std::fs::remove_file("./my-unix-socket").unwrap_or_else(|_| ());
/// # let mut rt = tokio::runtime::Runtime::new().unwrap();
/// # rt.block_on(async {
/// use hyper::service::{make_service_fn, service_fn};
/// use hyper::{Body, Error, Response, Server};
/// use hyper_unix_connector::UnixConnector;
///
/// let uc: UnixConnector = tokio::net::UnixListener::bind("./my-unix-socket")
///     .unwrap()
///     .into();
/// Server::builder(uc).serve(make_service_fn(|_| {
///     async move {
///         Ok::<_, Error>(service_fn(|_| {
///             async move { Ok::<_, Error>(Response::new(Body::from("Hello, World"))) }
///         }))
///     }
/// }));
/// # });
/// # std::fs::remove_file("./my-unix-socket").unwrap_or_else(|_| ());
/// ```
#[derive(Debug)]
pub struct UnixConnector(tokio::net::UnixListener);

impl From<tokio::net::UnixListener> for UnixConnector {
    fn from(u: tokio::net::UnixListener) -> Self {
        UnixConnector(u)
    }
}

impl Into<tokio::net::UnixListener> for UnixConnector {
    fn into(self) -> tokio::net::UnixListener {
        self.0
    }
}

impl hyper::server::accept::Accept for UnixConnector {
    type Conn = tokio::net::UnixStream;
    type Error = Error;

    fn poll_accept(
        mut self: Pin<&mut Self>,
        cx: &mut Context,
    ) -> Poll<Option<Result<Self::Conn, Self::Error>>> {
        let fut = self
            .0
            .accept()
            .map_ok(|(stream, _addr)| stream)
            .map_err(|e| e.into())
            .map(|f| Some(f));
        Future::poll(Box::pin(fut).as_mut(), cx)
    }
}

/// Newtype for [`tokio::net::UnixStream`] so that it can work with hyper's `Client`.
#[pin_project]
#[derive(Debug)]
pub struct UDS(#[pin] tokio::net::UnixStream);

impl From<tokio::net::UnixStream> for UDS {
    fn from(f: tokio::net::UnixStream) -> Self {
        Self(f)
    }
}

impl Into<tokio::net::UnixStream> for UDS {
    fn into(self) -> tokio::net::UnixStream {
        self.0
    }
}

macro_rules! conn_impl_fn {
    ($fn: ident |$first_var: ident: $first_typ: ty, $($var: ident: $typ: ty),*| -> $ret: ty ;;) => {
        fn $fn ($first_var: $first_typ, $( $var: $typ ),* ) -> $ret {
            let ux: Pin<&mut tokio::net::UnixStream> = $first_var.project().0;
            ux.$fn($($var),*)
        }
    };
}

impl tokio::io::AsyncRead for UDS {
    conn_impl_fn!(poll_read |self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8]| -> Poll<std::io::Result<usize>> ;;);
}

impl tokio::io::AsyncWrite for UDS {
    conn_impl_fn!(poll_write    |self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]| -> Poll<std::io::Result<usize>> ;;);
    conn_impl_fn!(poll_flush    |self: Pin<&mut Self>, cx: &mut Context<'_>| -> Poll<std::io::Result<()>> ;;);
    conn_impl_fn!(poll_shutdown |self: Pin<&mut Self>, cx: &mut Context<'_>| -> Poll<std::io::Result<()>> ;;);
}

/// Converts [`Uri`] to [`tokio::net::UnixStream`].
///
/// Useful for making [`hyper`] clients connect to Unix-domain addresses. For the server side, see
/// [`UnixConnector`].
///
/// # Example
/// ```rust
/// use hyper_unix_connector::{Uri, UnixClient};
/// use hyper::{Body, Client};
///
/// let client: Client<UnixClient, Body> = Client::builder().build(UnixClient);
/// let addr: hyper::Uri = Uri::new("./my_unix_socket", "/").into();
/// client.get(addr);
/// ```
#[derive(Clone, Copy, Debug)]
pub struct UnixClient;

impl hyper::service::Service<hyper::Uri> for UnixClient {
    type Response = UDS;
    type Error = Error;
    type Future =
        Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;

    fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, dst: hyper::Uri) -> Self::Future {
        Box::pin(async move {
            match dst.scheme_str() {
                Some("unix") => (),
                _ => return Err(failure::format_err!("Invalid uri {:?}", dst)),
            }

            let path = match Uri::socket_path(&dst) {
                Some(path) => path,

                None => return Err(failure::format_err!("Invalid uri {:?}", dst)),
            };

            let st = tokio::net::UnixStream::connect(&path).await?;
            Ok(st.into())
        })
    }
}

impl hyper::client::connect::Connection for UDS {
    fn connected(&self) -> hyper::client::connect::Connected {
        hyper::client::connect::Connected::new()
    }
}

#[cfg(test)]
mod test {
    use crate::{UnixClient, UnixConnector, Uri};
    use failure::ResultExt;
    use futures_util::stream::{StreamExt, TryStreamExt};
    use hyper::service::{make_service_fn, service_fn};
    use hyper::{Body, Client, Error, Response, Server};

    #[test]
    fn ping() -> Result<(), failure::Error> {
        const PING_RESPONSE: &str = "Hello, World";
        const TEST_UNIX_ADDR: &str = "my-unix-socket";

        std::fs::remove_file(TEST_UNIX_ADDR).unwrap_or_else(|_| ());

        let mut rt = tokio::runtime::Runtime::new().context("Could not make tokio runtime")?;
        rt.block_on(async {
            // server
            let uc: UnixConnector = tokio::net::UnixListener::bind(TEST_UNIX_ADDR)
                .expect("bind unixlistener")
                .into();
            let srv_fut = Server::builder(uc).serve(make_service_fn(|_| {
                async move {
                    Ok::<_, Error>(service_fn(|_| {
                        async move { Ok::<_, Error>(Response::new(Body::from(PING_RESPONSE))) }
                    }))
                }
            }));

            // client
            let client: Client<UnixClient, Body> = Client::builder().build(UnixClient);

            tokio::spawn(async move {
                if let Err(e) = srv_fut.await {
                    panic!(e);
                }
            });

            let addr: hyper::Uri = Uri::new(TEST_UNIX_ADDR, "/").into();
            let body = client.get(addr).await.unwrap().into_body();
            let payload: Vec<u8> = body
                .map(|b| b.map(|v| v.to_vec()))
                .try_concat()
                .await
                .unwrap();
            let resp = String::from_utf8(payload).expect("body utf8");
            assert_eq!(resp, PING_RESPONSE);
        });

        std::fs::remove_file(TEST_UNIX_ADDR).unwrap_or_else(|_| ());

        Ok(())
    }
}