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
//! Dual-protocol server implementation.
//!
//! See [`bind_dual_protocol()`] and [`DualProtocolAcceptor`].

use std::fmt::{self, Debug, Formatter};
use std::future::Future;
use std::io::ErrorKind;
use std::net::{SocketAddr, TcpListener};
use std::pin::Pin;
use std::task::{Context, Poll};
use std::{io, slice};

use axum_server::accept::Accept;
use axum_server::tls_rustls::{RustlsAcceptor, RustlsConfig};
use axum_server::Server;
use bytes::Bytes;
use http::{Request, Response};
use http_body_util::{Either as BodyEither, Empty};
use pin_project::pin_project;
use tokio::io::ReadBuf;
use tokio::net::TcpStream;
use tokio_rustls::server::TlsStream;
use tokio_util::either::Either as TokioEither;
use tower_service::Service as TowerService;

use crate::UpgradeHttp;

/// Create a [`Server`] that will bind to the provided address, accepting both
/// HTTP and HTTPS on the same port.
#[must_use]
pub fn bind_dual_protocol(
	address: SocketAddr,
	config: RustlsConfig,
) -> Server<DualProtocolAcceptor> {
	let acceptor = DualProtocolAcceptor::new(config);

	Server::bind(address).acceptor(acceptor)
}

/// Create a [`Server`] from an existing [`TcpListener`], accepting both
/// HTTP and HTTPS on the same port.
#[must_use]
pub fn from_tcp_dual_protocol(
	listener: TcpListener,
	config: RustlsConfig,
) -> Server<DualProtocolAcceptor> {
	let acceptor = DualProtocolAcceptor::new(config);

	Server::from_tcp(listener).acceptor(acceptor)
}

/// Supplies configuration methods for [`Server`] with [`DualProtocolAcceptor`].
///
/// See [`bind_dual_protocol()`] for easy creation.
pub trait ServerExt {
	/// Set if HTTP connections should be automatically upgraded to HTTPS.
	///
	/// See [`UpgradeHttp`] for more details.
	#[must_use]
	fn set_upgrade(self, upgrade: bool) -> Self;
}

impl ServerExt for Server<DualProtocolAcceptor> {
	fn set_upgrade(mut self, upgrade: bool) -> Self {
		self.get_mut().set_upgrade(upgrade);
		self
	}
}

/// The protocol used by this connection. See
/// [`Request::extensions()`](Request::extensions()).
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Protocol {
	/// This connection is encrypted with TLS.
	Tls,
	/// This connection is unencrypted.
	Plain,
}

/// Simultaneous HTTP and HTTPS [`Accept`]or.
#[derive(Debug, Clone)]
pub struct DualProtocolAcceptor {
	/// [`RustlsAcceptor`] re-used to handle HTTPS requests.
	rustls: RustlsAcceptor,
	/// Stores if HTTP connections should be automatically upgraded to HTTPS.
	///
	/// See [`UpgradeHttp`] for more details.
	upgrade: bool,
}

impl DualProtocolAcceptor {
	/// Create a new [`DualProtocolAcceptor`].
	#[must_use]
	pub fn new(config: RustlsConfig) -> Self {
		Self {
			rustls: RustlsAcceptor::new(config),
			upgrade: false,
		}
	}

	/// Set if HTTP connections should be automatically upgraded to HTTPS.
	///
	/// See [`UpgradeHttp`] for more details.
	pub fn set_upgrade(&mut self, upgrade: bool) {
		self.upgrade = upgrade;
	}
}

impl<Service: Clone> Accept<TcpStream, Service> for DualProtocolAcceptor {
	type Stream = TokioEither<TlsStream<TcpStream>, TcpStream>;
	type Service = DualProtocolService<Service>;
	type Future = DualProtocolAcceptorFuture<Service>;

	fn accept(&self, stream: TcpStream, service: Service) -> Self::Future {
		let service = if self.upgrade {
			DualProtocolServiceBuilder::new_upgrade(service)
		} else {
			DualProtocolServiceBuilder::new_service(service)
		};

		DualProtocolAcceptorFuture::new(stream, service, self.rustls.clone())
	}
}

/// [`Future`](Accept::Future) type for [`DualProtocolAcceptor`].
#[derive(Debug)]
#[pin_project(project = DualProtocolAcceptorFutureProj)]
pub struct DualProtocolAcceptorFuture<Service: Clone>(
	/// State. `enum` variants can't be private, so this solution was used to
	/// hide implementation details.
	#[pin]
	FutureState<Service>,
);

/// State of accepting a new request for [`DualProtocolAcceptorFuture`].
#[derive(Debug)]
#[pin_project(project = FutuereStateProj)]
enum FutureState<Service: Clone> {
	/// Peeking state, still trying to determine if the incoming request is HTTP
	/// or HTTPS.
	Peek(Option<PeekState<Service>>),
	/// HTTPS state, it was determined that the incoming request is HTTPS, now
	/// the [`RustlsAcceptor`] has to be polled to completion.
	Https(#[pin] <RustlsAcceptor as Accept<TcpStream, DualProtocolService<Service>>>::Future),
}

/// Data necessary to peek and proceed to the next state.
#[derive(Debug)]
struct PeekState<Service> {
	/// Transport.
	stream: TcpStream,
	/// User-provided [`Service`](TowerService)
	service: DualProtocolServiceBuilder<Service>,
	/// Used to proceed to the [`Https`](FutureState::Https) state if
	/// necessary.
	rustls: RustlsAcceptor,
}

impl<Service: Clone> DualProtocolAcceptorFuture<Service> {
	/// Create a new [`DualProtocolAcceptorFuture`] in the
	/// [`Peek`](FutureState::Peek) state.
	const fn new(
		stream: TcpStream,
		service: DualProtocolServiceBuilder<Service>,
		rustls: RustlsAcceptor,
	) -> Self {
		Self(FutureState::Peek(Some(PeekState {
			stream,
			service,
			rustls,
		})))
	}
}

impl<Service: Clone> DualProtocolAcceptorFutureProj<'_, Service> {
	/// Proceed to the [`Https`](FutureState::Https) state.
	fn upgrade(
		&mut self,
		future: <RustlsAcceptor as Accept<TcpStream, DualProtocolService<Service>>>::Future,
	) {
		self.0.set(FutureState::Https(future));
	}
}

impl<Service: Clone> Future for DualProtocolAcceptorFuture<Service> {
	type Output = io::Result<(
		TokioEither<TlsStream<TcpStream>, TcpStream>,
		DualProtocolService<Service>,
	)>;

	fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
		let mut this = self.project();

		// After successfully peeking, continue without unnecessary yielding.
		loop {
			match this.0.as_mut().project() {
				FutuereStateProj::Peek(inner) => {
					let peek = inner.as_mut().expect("polled again after `Poll::Ready`");

					let mut byte = 0;
					let mut buffer = ReadBuf::new(slice::from_mut(&mut byte));

					match peek.stream.poll_peek(cx, &mut buffer) {
						// If `MSG_PEEK` returns `0`, the socket was closed.
						Poll::Ready(Ok(0)) => {
							return Poll::Ready(Err(ErrorKind::UnexpectedEof.into()))
						}
						Poll::Ready(Ok(_)) => {
							let PeekState {
								stream,
								service,
								rustls,
							} = inner.take().expect("`inner` was already consumed");

							// The first byte in the TLS protocol is always `0x16`.
							if byte == 0x16 {
								this.upgrade(rustls.accept(stream, service.build(Protocol::Tls)));
							} else {
								return Poll::Ready(Ok((
									TokioEither::Right(stream),
									service.build(Protocol::Plain),
								)));
							}
						}
						Poll::Ready(Err(err)) => return Poll::Ready(Err(err)),
						Poll::Pending => return Poll::Pending,
					}
				}
				FutuereStateProj::Https(future) => {
					return future
						.poll(cx)
						.map_ok(|(stream, service)| (TokioEither::Left(stream), service))
				}
			}
		}
	}
}

/// Hold the user-supplied app until the protocol type is determined.
#[derive(Debug)]
struct DualProtocolServiceBuilder<Service>(ServiceServe<Service>);

/// [`Service`](TowerService) wrapping user-supplied app to apply global
/// [`Layer`](tower_layer::Layer)s according to configuration.
#[derive(Clone, Debug)]
pub struct DualProtocolService<Service: Clone> {
	/// The user-supplied [`Service`](TowerService).
	service: ServiceServe<Service>,
	/// The protocol this connection is using.
	protocol: Protocol,
}

/// Holds [`Service`](TowerService) to serve for [`DualProtocolService`].
#[derive(Clone, Debug)]
enum ServiceServe<Service> {
	/// No configuration applied, so we will pass-through the user-supplied
	/// [`Service`](TowerService) as is.
	Service(Service),
	/// Configured to automatically upgrade HTTP requests to HTTPS, so we wrap
	/// the user-supplied [`Service`](TowerService) in the [`UpgradeHttp`]
	/// [`Service`](TowerService).
	Upgrade(UpgradeHttp<Service>),
}

impl<Service: Clone> DualProtocolServiceBuilder<Service> {
	/// Create a [`DualProtocolService`] in the
	/// [`Service`](ServiceServe::Service) state.
	const fn new_service(service: Service) -> Self {
		Self(ServiceServe::Service(service))
	}

	/// Create a [`DualProtocolService`] in the
	/// [`Upgrade`](ServiceServe::Upgrade) state.
	const fn new_upgrade(service: Service) -> Self {
		Self(ServiceServe::Upgrade(UpgradeHttp::new(service)))
	}

	/// Create a [`DualProtocolService`] when the protocol is established.
	fn build(self, protocol: Protocol) -> DualProtocolService<Service> {
		DualProtocolService {
			service: self.0,
			protocol,
		}
	}
}

impl<Service, RequestBody, ResponseBody> TowerService<Request<RequestBody>>
	for DualProtocolService<Service>
where
	Service: Clone + TowerService<Request<RequestBody>, Response = Response<ResponseBody>>,
{
	type Response = Response<BodyEither<ResponseBody, BodyEither<ResponseBody, Empty<Bytes>>>>;
	type Error = Service::Error;
	type Future = DualProtocolServiceFuture<Service, RequestBody, ResponseBody>;

	fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
		match &mut self.service {
			ServiceServe::Service(service) => service.poll_ready(cx),
			ServiceServe::Upgrade(service) => service.poll_ready(cx),
		}
	}

	fn call(&mut self, mut req: Request<RequestBody>) -> Self::Future {
		let _ = req.extensions_mut().insert(self.protocol);

		match &mut self.service {
			ServiceServe::Service(service) => {
				DualProtocolServiceFuture::new_service(service.call(req))
			}
			ServiceServe::Upgrade(service) => {
				DualProtocolServiceFuture::new_upgrade(service.call(req))
			}
		}
	}
}

/// [`Future`](TowerService::Future) type for [`DualProtocolService`].
#[pin_project]
pub struct DualProtocolServiceFuture<Service, RequestBody, ResponseBody>(
	#[pin] FutureServe<Service, RequestBody, ResponseBody>,
)
where
	Service: TowerService<Request<RequestBody>, Response = Response<ResponseBody>>;

/// Holds [`Future`] to serve for [`DualProtocolServiceFuture`].
#[derive(Debug)]
#[pin_project(project = DualProtocolServiceFutureProj)]
enum FutureServe<Service, RequestBody, ResponseBody>
where
	Service: TowerService<Request<RequestBody>, Response = Response<ResponseBody>>,
{
	/// Pass-through the user-supplied [`Future`](TowerService::Future).
	Service(#[pin] Service::Future),
	/// Use the [`UpgradeHttp`] [`Future`](TowerService::Future).
	Upgrade(#[pin] <UpgradeHttp<Service> as TowerService<Request<RequestBody>>>::Future),
}

// Rust can't figure out the correct bounds.
impl<Service, RequestBody, ResponseBody> Debug
	for DualProtocolServiceFuture<Service, RequestBody, ResponseBody>
where
	Service: TowerService<Request<RequestBody>, Response = Response<ResponseBody>>,
	FutureServe<Service, RequestBody, ResponseBody>: Debug,
{
	fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
		formatter
			.debug_tuple("DualProtocolServiceFuture")
			.field(&self.0)
			.finish()
	}
}

impl<Service, RequestBody, ResponseBody>
	DualProtocolServiceFuture<Service, RequestBody, ResponseBody>
where
	Service: TowerService<Request<RequestBody>, Response = Response<ResponseBody>>,
{
	/// Create a [`DualProtocolServiceFuture`] in the
	/// [`Service`](FutureServe::Service) state.
	const fn new_service(future: Service::Future) -> Self {
		Self(FutureServe::Service(future))
	}

	/// Create a [`DualProtocolServiceFuture`] in the
	/// [`Upgrade`](FutureServe::Upgrade) state.
	const fn new_upgrade(
		future: <UpgradeHttp<Service> as TowerService<Request<RequestBody>>>::Future,
	) -> Self {
		Self(FutureServe::Upgrade(future))
	}
}

impl<Service, RequestBody, ResponseBody> Future
	for DualProtocolServiceFuture<Service, RequestBody, ResponseBody>
where
	Service: TowerService<Request<RequestBody>, Response = Response<ResponseBody>>,
{
	type Output = Result<
		Response<BodyEither<ResponseBody, BodyEither<ResponseBody, Empty<Bytes>>>>,
		Service::Error,
	>;

	fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
		match self.project().0.project() {
			DualProtocolServiceFutureProj::Service(future) => future
				.poll(cx)
				.map_ok(|response| response.map(BodyEither::Left)),
			DualProtocolServiceFutureProj::Upgrade(future) => future
				.poll(cx)
				.map_ok(|response| response.map(BodyEither::Right)),
		}
	}
}