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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//! Connection Information

use std::convert::Infallible;
use std::fmt;
use std::io;
use std::str::FromStr;

use camino::Utf8Path;
use camino::Utf8PathBuf;
use http::uri::Authority;
use tokio::net::{TcpStream, UnixStream};

#[cfg(feature = "tls")]
pub mod tls;
#[cfg(feature = "tls")]
pub use self::tls::HasTlsConnectionInfo;
#[cfg(feature = "tls")]
pub use self::tls::TlsConnectionInfo;
pub use crate::stream::duplex::DuplexAddr;

/// The transport protocol used for a connection.
///
/// This is for informational purposes only, and can be used
/// to select the appropriate transport when a transport should
/// be pre-negotiated (e.g. ALPN or a Duplex socket).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Protocol {
    /// HTTP transports
    Http(http::Version),

    /// gRPC
    Grpc,

    /// WebSocket
    WebSocket,

    /// Other protocol
    Other(String),
}

impl std::fmt::Display for Protocol {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            // http::Version uses the debug format to write out the version
            Self::Http(version) => write!(f, "{:?}", version),
            Self::Grpc => write!(f, "gRPC"),
            Self::WebSocket => write!(f, "WebSocket"),
            Self::Other(s) => write!(f, "{}", s),
        }
    }
}

impl Protocol {
    /// Create a new protocol with the given http version.
    pub fn http(version: http::Version) -> Self {
        Self::Http(version)
    }

    /// New gRPC protocol
    pub fn grpc() -> Self {
        Self::Grpc
    }

    /// New WebSocket protocol
    pub fn web_socket() -> Self {
        Self::WebSocket
    }
}

impl From<http::Version> for Protocol {
    fn from(version: http::Version) -> Self {
        Self::Http(version)
    }
}

impl FromStr for Protocol {
    type Err = Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "http/0.9" => Ok(Self::Http(http::Version::HTTP_09)),
            "http/1.0" => Ok(Self::Http(http::Version::HTTP_10)),
            "http/1.1" => Ok(Self::Http(http::Version::HTTP_11)),
            "h2" => Ok(Self::Http(http::Version::HTTP_2)),
            "h3" => Ok(Self::Http(http::Version::HTTP_3)),
            "gRPC" => Ok(Self::Grpc),
            "WebSocket" => Ok(Self::WebSocket),
            _ => Ok(Self::Other(s.to_string())),
        }
    }
}

/// Canonicalize a socket address, converting IPv4 addresses which are
/// mapped into IPv6 addresses into standard IPv4 addresses.
#[cfg(feature = "stream")]
fn make_canonical(addr: std::net::SocketAddr) -> std::net::SocketAddr {
    match addr.ip() {
        std::net::IpAddr::V4(_) => addr,
        std::net::IpAddr::V6(ip) => {
            if let Some(ip) = ip.to_ipv4_mapped() {
                std::net::SocketAddr::new(std::net::IpAddr::V4(ip), addr.port())
            } else {
                addr
            }
        }
    }
}

/// Connection address for a unix domain socket.
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct UnixAddr {
    path: Option<Utf8PathBuf>,
}

impl UnixAddr {
    /// Does this socket have a name
    pub fn is_named(&self) -> bool {
        self.path.is_some()
    }

    /// Get the path of this socket.
    pub fn path(&self) -> Option<&Utf8Path> {
        self.path.as_deref()
    }

    /// Create a new address from a path.
    pub fn from_pathbuf(path: Utf8PathBuf) -> Self {
        Self { path: Some(path) }
    }

    /// Create a new address without a path.
    pub fn unnamed() -> Self {
        Self { path: None }
    }
}

impl fmt::Display for UnixAddr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(path) = self.path() {
            write!(f, "unix://{}", path)
        } else {
            write!(f, "unix://")
        }
    }
}

impl TryFrom<std::os::unix::net::SocketAddr> for UnixAddr {
    type Error = io::Error;
    fn try_from(addr: std::os::unix::net::SocketAddr) -> Result<Self, Self::Error> {
        Ok(Self {
            path: addr
                .as_pathname()
                .map(|p| {
                    Utf8Path::from_path(p).ok_or_else(|| {
                        io::Error::new(io::ErrorKind::InvalidData, "not a utf-8 path")
                    })
                })
                .transpose()?
                .map(|path| path.to_owned()),
        })
    }
}

impl TryFrom<tokio::net::unix::SocketAddr> for UnixAddr {
    type Error = io::Error;
    fn try_from(addr: tokio::net::unix::SocketAddr) -> Result<Self, Self::Error> {
        Ok(Self {
            path: addr
                .as_pathname()
                .map(|p| {
                    Utf8Path::from_path(p).ok_or_else(|| {
                        io::Error::new(io::ErrorKind::InvalidData, "not a utf-8 path")
                    })
                })
                .transpose()?
                .map(|path| path.to_owned()),
        })
    }
}

/// A socket address for a Braid stream.
///
/// Supports more than just network socket addresses, also support Unix socket addresses (paths)
/// and unnamed Duplex and Unix socket connections.
#[cfg(feature = "stream")]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum BraidAddr {
    /// A TCP socket address.
    Tcp(std::net::SocketAddr),

    /// Represents a duplex connection which has no address.
    Duplex,

    /// A Unix socket address.
    Unix(UnixAddr),
}

#[cfg(feature = "stream")]
impl std::fmt::Display for BraidAddr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Tcp(addr) => write!(f, "{}", addr),
            Self::Duplex => write!(f, "<duplex>"),
            Self::Unix(path) => write!(f, "{}", path),
        }
    }
}

#[cfg(feature = "stream")]
impl BraidAddr {
    /// Returns the TCP socket address, if this is a TCP socket address.
    pub fn tcp(&self) -> Option<std::net::SocketAddr> {
        match self {
            Self::Tcp(addr) => Some(*addr),
            _ => None,
        }
    }

    /// Returns the Unix socket address, if this is a Unix socket address.
    pub fn path(&self) -> Option<&Utf8Path> {
        match self {
            Self::Unix(addr) => addr.path(),
            _ => None,
        }
    }

    /// Returns the canonical TCP address, if this is a TCP socket address.
    pub fn canonical(self) -> Self {
        match self {
            Self::Tcp(addr) => Self::Tcp(make_canonical(addr)),
            _ => self,
        }
    }
}

#[cfg(feature = "stream")]
impl From<std::net::SocketAddr> for BraidAddr {
    fn from(addr: std::net::SocketAddr) -> Self {
        Self::Tcp(make_canonical(addr))
    }
}

#[cfg(feature = "stream")]
impl TryFrom<tokio::net::unix::SocketAddr> for BraidAddr {
    type Error = io::Error;
    fn try_from(addr: tokio::net::unix::SocketAddr) -> Result<Self, Self::Error> {
        Ok(Self::Unix(addr.try_into()?))
    }
}

#[cfg(feature = "stream")]
impl From<(std::net::IpAddr, u16)> for BraidAddr {
    fn from(addr: (std::net::IpAddr, u16)) -> Self {
        Self::Tcp(std::net::SocketAddr::new(addr.0, addr.1))
    }
}

#[cfg(feature = "stream")]
impl From<(std::net::Ipv4Addr, u16)> for BraidAddr {
    fn from(addr: (std::net::Ipv4Addr, u16)) -> Self {
        Self::Tcp(std::net::SocketAddr::new(
            std::net::IpAddr::V4(addr.0),
            addr.1,
        ))
    }
}

#[cfg(feature = "stream")]
impl From<(std::net::Ipv6Addr, u16)> for BraidAddr {
    fn from(addr: (std::net::Ipv6Addr, u16)) -> Self {
        Self::Tcp(std::net::SocketAddr::new(
            std::net::IpAddr::V6(addr.0),
            addr.1,
        ))
    }
}

#[cfg(feature = "stream")]
impl From<Utf8PathBuf> for BraidAddr {
    fn from(addr: Utf8PathBuf) -> Self {
        Self::Unix(UnixAddr::from_pathbuf(addr))
    }
}

#[cfg(feature = "stream")]
impl From<UnixAddr> for BraidAddr {
    fn from(addr: UnixAddr) -> Self {
        Self::Unix(addr)
    }
}

#[cfg(feature = "stream")]
impl From<DuplexAddr> for BraidAddr {
    fn from(_: DuplexAddr) -> Self {
        Self::Duplex
    }
}

/// Information about a connection to a stream.
#[cfg(feature = "stream")]
#[derive(Debug, Clone)]
pub struct ConnectionInfo<Addr = BraidAddr> {
    /// The protocol used for this connection.
    pub protocol: Option<Protocol>,

    /// The authority name for the server.
    pub authority: Option<Authority>,

    /// The local address for this connection.
    pub local_addr: Addr,

    /// The remote address for this connection.
    pub remote_addr: Addr,

    /// Buffer size
    pub buffer_size: Option<usize>,
}

/// Information about a connection to a stream.
#[cfg(not(feature = "stream"))]
#[derive(Debug, Clone)]
pub struct ConnectionInfo<Addr> {
    /// The protocol used for this connection.
    pub protocol: Option<Protocol>,

    /// The authority name for the server.
    pub authority: Option<Authority>,

    /// The local address for this connection.
    pub local_addr: Addr,

    /// The remote address for this connection.
    pub remote_addr: Addr,

    /// Buffer size
    pub buffer_size: Option<usize>,
}

impl<Addr> Default for ConnectionInfo<Addr>
where
    Addr: Default,
{
    fn default() -> Self {
        Self {
            protocol: None,
            authority: None,
            local_addr: Addr::default(),
            remote_addr: Addr::default(),
            buffer_size: None,
        }
    }
}

#[cfg(feature = "stream")]
impl ConnectionInfo<BraidAddr> {
    pub(crate) fn duplex(name: Authority, protocol: Option<Protocol>, buffer_size: usize) -> Self {
        ConnectionInfo {
            protocol,
            authority: Some(name),
            local_addr: BraidAddr::Duplex,
            remote_addr: BraidAddr::Duplex,
            buffer_size: Some(buffer_size),
        }
    }
}

#[cfg(not(feature = "stream"))]
impl ConnectionInfo<DuplexAddr> {
    pub(crate) fn duplex(name: Authority, protocol: Option<Protocol>, buffer_size: usize) -> Self {
        ConnectionInfo {
            protocol,
            authority: Some(name),
            local_addr: DuplexAddr::new(),
            remote_addr: DuplexAddr::new(),
            buffer_size: Some(buffer_size),
        }
    }
}

impl<Addr> ConnectionInfo<Addr> {
    /// The local address for this connection
    pub fn local_addr(&self) -> &Addr {
        &self.local_addr
    }

    /// The remote address for this connection
    pub fn remote_addr(&self) -> &Addr {
        &self.remote_addr
    }

    /// Map the addresses in this connection info to a new type.
    pub fn map<T, F>(self, f: F) -> ConnectionInfo<T>
    where
        F: Fn(Addr) -> T,
    {
        ConnectionInfo {
            protocol: self.protocol,
            authority: self.authority,
            local_addr: f(self.local_addr),
            remote_addr: f(self.remote_addr),
            buffer_size: self.buffer_size,
        }
    }
}

impl<Addr> TryFrom<&TcpStream> for ConnectionInfo<Addr>
where
    Addr: From<std::net::SocketAddr>,
{
    type Error = io::Error;

    fn try_from(stream: &TcpStream) -> Result<Self, Self::Error> {
        let local_addr = stream.local_addr()?;
        let remote_addr = stream.peer_addr()?;

        Ok(Self {
            protocol: None,
            authority: None,
            local_addr: local_addr.into(),
            remote_addr: remote_addr.into(),
            buffer_size: None,
        })
    }
}

impl<Addr> TryFrom<&UnixStream> for ConnectionInfo<Addr>
where
    Addr: From<UnixAddr>,
{
    type Error = io::Error;

    fn try_from(stream: &UnixStream) -> Result<Self, Self::Error> {
        let local_addr = match stream.local_addr() {
            Ok(addr) => addr.try_into().expect("unix socket address"),
            Err(e) if matches!(e.kind(), io::ErrorKind::InvalidInput) => UnixAddr::unnamed(),
            Err(e) => return Err(e),
        };

        let remote_addr = match stream.peer_addr() {
            Ok(addr) => addr.try_into().expect("unix socket address"),
            Err(e) if matches!(e.kind(), io::ErrorKind::InvalidInput) => UnixAddr::unnamed(),
            Err(e) => return Err(e),
        };

        Ok(Self {
            protocol: None,
            authority: None,
            local_addr: local_addr.into(),
            remote_addr: remote_addr.into(),
            buffer_size: None,
        })
    }
}

/// Trait for types which can provide connection information.
pub trait HasConnectionInfo {
    /// The address type for this connection.
    type Addr: fmt::Display + fmt::Debug;

    /// Get the connection information for this stream.
    fn info(&self) -> ConnectionInfo<Self::Addr>;
}

impl HasConnectionInfo for TcpStream {
    type Addr = std::net::SocketAddr;

    fn info(&self) -> ConnectionInfo<Self::Addr> {
        self.try_into()
            .expect("connection info should be available")
    }
}

impl HasConnectionInfo for UnixStream {
    type Addr = UnixAddr;

    fn info(&self) -> ConnectionInfo<Self::Addr> {
        ConnectionInfo {
            local_addr: self
                .local_addr()
                .expect("unable to get local address")
                .try_into()
                .expect("utf-8 unix socket address"),
            remote_addr: self
                .peer_addr()
                .expect("unable to get peer address")
                .try_into()
                .expect("utf-8 unix socket address"),
            ..Default::default()
        }
    }
}

#[cfg(test)]
mod tests {
    use std::net::{IpAddr, Ipv4Addr, SocketAddr};

    use http::Version;
    use tokio::net::{TcpListener, UnixListener};

    use super::*;

    #[test]
    fn protocol_display() {
        assert_eq!(Protocol::http(Version::HTTP_11).to_string(), "HTTP/1.1");
        assert_eq!(Protocol::http(Version::HTTP_2).to_string(), "HTTP/2.0");
        assert_eq!(Protocol::http(Version::HTTP_3).to_string(), "HTTP/3.0");
        assert_eq!(Protocol::http(Version::HTTP_10).to_string(), "HTTP/1.0");
        assert_eq!(Protocol::grpc().to_string(), "gRPC");
        assert_eq!(Protocol::web_socket().to_string(), "WebSocket");
    }

    #[test]
    fn parse_protocol() {
        assert_eq!(
            Protocol::from_str("http/1.1").unwrap(),
            Protocol::http(Version::HTTP_11)
        );
        assert_eq!(
            Protocol::from_str("h2").unwrap(),
            Protocol::http(Version::HTTP_2)
        );
        assert_eq!(
            Protocol::from_str("h3").unwrap(),
            Protocol::http(Version::HTTP_3)
        );
        assert_eq!(
            Protocol::from_str("http/1.0").unwrap(),
            Protocol::http(Version::HTTP_10)
        );
        assert_eq!(Protocol::from_str("gRPC").unwrap(), Protocol::grpc());
        assert_eq!(
            Protocol::from_str("WebSocket").unwrap(),
            Protocol::web_socket()
        );
        assert_eq!(
            Protocol::from_str("foo").unwrap(),
            Protocol::Other("foo".into())
        )
    }

    #[test]
    fn test_make_canonical() {
        assert_eq!(
            make_canonical("[::1]:8080".parse().unwrap()),
            "[::1]:8080".parse().unwrap()
        );
        assert_eq!(
            make_canonical("[::ffff:192.0.2.128]:8080".parse().unwrap()),
            "192.0.2.128:8080".parse().unwrap()
        )
    }

    #[test]
    fn connection_info_default() {
        let info = ConnectionInfo::<DuplexAddr>::default();
        assert_eq!(info.protocol, None);
        assert_eq!(info.authority, None);
        assert_eq!(info.local_addr, DuplexAddr::new());
        assert_eq!(info.remote_addr, DuplexAddr::new());
        assert_eq!(info.buffer_size, None);
    }

    #[test]
    fn unix_addr() {
        let addr = UnixAddr::from_pathbuf("/tmp/foo.sock".into());
        assert_eq!(addr.path(), Some("/tmp/foo.sock".into()));

        let addr = UnixAddr::unnamed();
        assert_eq!(addr.path(), None);
    }

    #[test]
    fn connection_info_map() {
        let info = ConnectionInfo {
            protocol: Some(Protocol::http(Version::HTTP_11)),
            authority: Some("example.com".parse().unwrap()),
            local_addr: "local",
            remote_addr: "remote",
            buffer_size: Some(1024),
        };

        let mapped = info.map(|addr| addr.to_string());
        assert_eq!(mapped.protocol, Some(Protocol::http(Version::HTTP_11)));
        assert_eq!(mapped.authority, Some("example.com".parse().unwrap()));
        assert_eq!(mapped.local_addr, "local".to_string());
    }

    #[tokio::test]
    async fn unix_connection_info_unnamed() {
        let (a, _) = UnixStream::pair().expect("pair");

        let info: ConnectionInfo<UnixAddr> = ConnectionInfo::try_from(&a).unwrap();
        assert_eq!(info.local_addr(), &UnixAddr::unnamed());
    }

    #[tokio::test]
    async fn unix_connection_info_named() {
        let tmp = tempfile::TempDir::with_prefix("unix-connection-info").unwrap();
        tokio::fs::create_dir_all(&tmp).await.unwrap();
        let path = tmp.path().join("socket.sock");

        let listener = UnixListener::bind(&path).unwrap();

        let conn = UnixStream::connect(&path).await.unwrap();

        let info: ConnectionInfo<UnixAddr> = ConnectionInfo::try_from(&conn).unwrap();

        assert_eq!(
            info.remote_addr(),
            &UnixAddr::from_pathbuf(path.try_into().unwrap())
        );

        drop(listener);
    }

    #[tokio::test]
    async fn tcp_connection_info() {
        let listener = TcpListener::bind(SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0))
            .await
            .unwrap();
        let addr = listener.local_addr().unwrap();

        let conn = TcpStream::connect(addr).await.unwrap();

        let info: ConnectionInfo<std::net::SocketAddr> = ConnectionInfo::try_from(&conn).unwrap();
        assert_eq!(info.remote_addr().ip(), IpAddr::V4(Ipv4Addr::LOCALHOST));
        assert_eq!(info.remote_addr().port(), addr.port());
    }
}