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
use std::{
    net::SocketAddr,
    pin::Pin,
    task::{
        Context,
        Poll,
    },
};

// Support for axum's connection info trait.
#[cfg(feature = "axum")]
use axum::extract::connect_info::Connected;
use muxado::typed::TypedStream;
use tokio::io::{
    AsyncRead,
    AsyncWrite,
};

use crate::{
    config::ProxyProto,
    internals::proto::{
        EdgeType,
        ProxyHeader,
    },
};
/// A connection from an ngrok tunnel.
///
/// This implements [AsyncRead]/[AsyncWrite], as well as providing access to the
/// address from which the connection to the ngrok edge originated.
pub(crate) struct ConnInner {
    pub(crate) info: Info,
    pub(crate) stream: TypedStream,
}

#[derive(Clone)]
pub(crate) struct Info {
    pub(crate) header: ProxyHeader,
    pub(crate) remote_addr: SocketAddr,
    pub(crate) proxy_proto: ProxyProto,
    pub(crate) app_protocol: Option<String>,
    pub(crate) verify_upstream_tls: bool,
}

impl ConnInfo for Info {
    fn remote_addr(&self) -> SocketAddr {
        self.remote_addr
    }
}

impl EdgeConnInfo for Info {
    fn edge_type(&self) -> EdgeType {
        self.header.edge_type
    }
    fn passthrough_tls(&self) -> bool {
        self.header.passthrough_tls
    }
}

impl EndpointConnInfo for Info {
    fn proto(&self) -> &str {
        self.header.proto.as_str()
    }
}

/// An incoming connection over an ngrok tunnel.
/// Effectively a trait alias for async read+write, plus connection info.
pub trait Conn: ConnInfo + AsyncRead + AsyncWrite + Unpin + Send + 'static {}

/// Information common to all ngrok connections.
pub trait ConnInfo {
    /// Returns the client address that initiated the connection to the ngrok
    /// edge.
    fn remote_addr(&self) -> SocketAddr;
}

/// Information about connections via ngrok edges.
pub trait EdgeConnInfo {
    /// Returns the edge type for this connection.
    fn edge_type(&self) -> EdgeType;
    /// Returns whether the connection includes the tls handshake and encrypted
    /// stream.
    fn passthrough_tls(&self) -> bool;
}

/// Information about connections via ngrok endpoints.
pub trait EndpointConnInfo {
    /// Returns the endpoint protocol.
    fn proto(&self) -> &str;
}

macro_rules! make_conn_type {
	(info EdgeConnInfo, $wrapper:tt) => {
		impl EdgeConnInfo for $wrapper {
			fn edge_type(&self) -> EdgeType {
				self.inner.info.edge_type()
			}
			fn passthrough_tls(&self) -> bool {
				self.inner.info.passthrough_tls()
			}
		}
	};
	(info EndpointConnInfo, $wrapper:tt) => {
		impl EndpointConnInfo for $wrapper {
			fn proto(&self) -> &str {
				self.inner.info.proto()
			}
		}
	};
    ($(#[$outer:meta])* $wrapper:ident, $($m:tt),*) => {
        $(#[$outer])*
        pub struct $wrapper {
            pub(crate) inner: ConnInner,
        }

        impl Conn for $wrapper {}

        impl ConnInfo for $wrapper {
			fn remote_addr(&self) -> SocketAddr {
				self.inner.info.remote_addr()
			}
        }

		impl AsyncRead for $wrapper {
			fn poll_read(
				mut self: Pin<&mut Self>,
				cx: &mut Context<'_>,
				buf: &mut tokio::io::ReadBuf<'_>,
			) -> Poll<std::io::Result<()>> {
				Pin::new(&mut *self.inner.stream).poll_read(cx, buf)
			}
		}

		impl AsyncWrite for $wrapper {
			fn poll_write(
				mut self: Pin<&mut Self>,
				cx: &mut Context<'_>,
				buf: &[u8],
			) -> Poll<Result<usize, std::io::Error>> {
				Pin::new(&mut *self.inner.stream).poll_write(cx, buf)
			}
			fn poll_flush(
				mut self: Pin<&mut Self>,
				cx: &mut Context<'_>,
			) -> Poll<Result<(), std::io::Error>> {
				Pin::new(&mut *self.inner.stream).poll_flush(cx)
			}
			fn poll_shutdown(
				mut self: Pin<&mut Self>,
				cx: &mut Context<'_>,
			) -> Poll<Result<(), std::io::Error>> {
				Pin::new(&mut *self.inner.stream).poll_shutdown(cx)
			}
		}

		#[cfg_attr(docsrs, doc(cfg(feature = "axum")))]
		#[cfg(feature = "axum")]
		impl Connected<&$wrapper> for SocketAddr {
			fn connect_info(target: &$wrapper) -> Self {
				target.inner.info.remote_addr()
			}
		}

		$(
			make_conn_type!(info $m, $wrapper);
		)*
    };
}

make_conn_type! {
    /// A connection via an ngrok Edge.
    EdgeConn, EdgeConnInfo
}

make_conn_type! {
    /// A connection via an ngrok Endpoint.
    EndpointConn, EndpointConnInfo
}