Debian Codegraph @

third_party/rust/hyper/src/server/tcp.rs

raw
1 use std::fmt;
2 use std::io;
3 use std::net::{SocketAddr, TcpListener as StdTcpListener};
4 use std::time::Duration;
5 use socket2::TcpKeepalive;
6
7 use tokio::net::TcpListener;
8 use tokio::time::Sleep;
9 use tracing::{debug, error, trace};
10
11 use crate::common::{task, Future, Pin, Poll};
12
13 #[allow(unreachable_pub)] // https://github.com/rust-lang/rust/issues/57411
14 pub use self::addr_stream::AddrStream;
15 use super::accept::Accept;
16
17 #[derive(Default, Debug, Clone, Copy)]
18 struct TcpKeepaliveConfig {
19 time: Option<Duration>,
20 interval: Option<Duration>,
21 retries: Option<u32>,
22 }
23
24 impl TcpKeepaliveConfig {
25 /// Converts into a `socket2::TcpKeealive` if there is any keep alive configuration.
26 fn into_socket2(self) -> Option<TcpKeepalive> {
27 let mut dirty = false;
28 let mut ka = TcpKeepalive::new();
29 if let Some(time) = self.time {
30 ka = ka.with_time(time);
31 dirty = true
32 }
33 if let Some(interval) = self.interval {
34 ka = Self::ka_with_interval(ka, interval, &mut dirty)
35 };
36 if let Some(retries) = self.retries {
37 ka = Self::ka_with_retries(ka, retries, &mut dirty)
38 };
39 if dirty {
40 Some(ka)
41 } else {
42 None
43 }
44 }
45
46 #[cfg(any(
47 target_os = "android",
48 target_os = "dragonfly",
49 target_os = "freebsd",
50 target_os = "fuchsia",
51 target_os = "illumos",
52 target_os = "linux",
53 target_os = "netbsd",
54 target_vendor = "apple",
55 windows,
56 ))]
57 fn ka_with_interval(ka: TcpKeepalive, interval: Duration, dirty: &mut bool) -> TcpKeepalive {
58 *dirty = true;
59 ka.with_interval(interval)
60 }
61
62 #[cfg(not(any(
63 target_os = "android",
64 target_os = "dragonfly",
65 target_os = "freebsd",
66 target_os = "fuchsia",
67 target_os = "illumos",
68 target_os = "linux",
69 target_os = "netbsd",
70 target_vendor = "apple",
71 windows,
72 )))]
73 fn ka_with_interval(ka: TcpKeepalive, _: Duration, _: &mut bool) -> TcpKeepalive {
74 ka // no-op as keepalive interval is not supported on this platform
75 }
76
77 #[cfg(any(
78 target_os = "android",
79 target_os = "dragonfly",
80 target_os = "freebsd",
81 target_os = "fuchsia",
82 target_os = "illumos",
83 target_os = "linux",
84 target_os = "netbsd",
85 target_vendor = "apple",
86 ))]
87 fn ka_with_retries(ka: TcpKeepalive, retries: u32, dirty: &mut bool) -> TcpKeepalive {
88 *dirty = true;
89 ka.with_retries(retries)
90 }
91
92 #[cfg(not(any(
93 target_os = "android",
94 target_os = "dragonfly",
95 target_os = "freebsd",
96 target_os = "fuchsia",
97 target_os = "illumos",
98 target_os = "linux",
99 target_os = "netbsd",
100 target_vendor = "apple",
101 )))]
102 fn ka_with_retries(ka: TcpKeepalive, _: u32, _: &mut bool) -> TcpKeepalive {
103 ka // no-op as keepalive retries is not supported on this platform
104 }
105 }
106
107 /// A stream of connections from binding to an address.
108 #[must_use = "streams do nothing unless polled"]
109 pub struct AddrIncoming {
110 addr: SocketAddr,
111 listener: TcpListener,
112 sleep_on_errors: bool,
113 tcp_keepalive_config: TcpKeepaliveConfig,
114 tcp_nodelay: bool,
115 timeout: Option<Pin<Box<Sleep>>>,
116 }
117
118 impl AddrIncoming {
119 pub(super) fn new(addr: &SocketAddr) -> crate::Result<Self> {
120 let std_listener = StdTcpListener::bind(addr).map_err(crate::Error::new_listen)?;
121
122 AddrIncoming::from_std(std_listener)
123 }
124
125 pub(super) fn from_std(std_listener: StdTcpListener) -> crate::Result<Self> {
126 // TcpListener::from_std doesn't set O_NONBLOCK
127 std_listener
128 .set_nonblocking(true)
129 .map_err(crate::Error::new_listen)?;
130 let listener = TcpListener::from_std(std_listener).map_err(crate::Error::new_listen)?;
131 AddrIncoming::from_listener(listener)
132 }
133
134 /// Creates a new `AddrIncoming` binding to provided socket address.
135 pub fn bind(addr: &SocketAddr) -> crate::Result<Self> {
136 AddrIncoming::new(addr)
137 }
138
139 /// Creates a new `AddrIncoming` from an existing `tokio::net::TcpListener`.
140 pub fn from_listener(listener: TcpListener) -> crate::Result<Self> {
141 let addr = listener.local_addr().map_err(crate::Error::new_listen)?;
142 Ok(AddrIncoming {
143 listener,
144 addr,
145 sleep_on_errors: true,
146 tcp_keepalive_config: TcpKeepaliveConfig::default(),
147 tcp_nodelay: false,
148 timeout: None,
149 })
150 }
151
152 /// Get the local address bound to this listener.
153 pub fn local_addr(&self) -> SocketAddr {
154 self.addr
155 }
156
157 /// Set the duration to remain idle before sending TCP keepalive probes.
158 ///
159 /// If `None` is specified, keepalive is disabled.
160 pub fn set_keepalive(&mut self, time: Option<Duration>) -> &mut Self {
161 self.tcp_keepalive_config.time = time;
162 self
163 }
164
165 /// Set the duration between two successive TCP keepalive retransmissions,
166 /// if acknowledgement to the previous keepalive transmission is not received.
167 pub fn set_keepalive_interval(&mut self, interval: Option<Duration>) -> &mut Self {
168 self.tcp_keepalive_config.interval = interval;
169 self
170 }
171
172 /// Set the number of retransmissions to be carried out before declaring that remote end is not available.
173 pub fn set_keepalive_retries(&mut self, retries: Option<u32>) -> &mut Self {
174 self.tcp_keepalive_config.retries = retries;
175 self
176 }
177
178 /// Set the value of `TCP_NODELAY` option for accepted connections.
179 pub fn set_nodelay(&mut self, enabled: bool) -> &mut Self {
180 self.tcp_nodelay = enabled;
181 self
182 }
183
184 /// Set whether to sleep on accept errors.
185 ///
186 /// A possible scenario is that the process has hit the max open files
187 /// allowed, and so trying to accept a new connection will fail with
188 /// `EMFILE`. In some cases, it's preferable to just wait for some time, if
189 /// the application will likely close some files (or connections), and try
190 /// to accept the connection again. If this option is `true`, the error
191 /// will be logged at the `error` level, since it is still a big deal,
192 /// and then the listener will sleep for 1 second.
193 ///
194 /// In other cases, hitting the max open files should be treat similarly
195 /// to being out-of-memory, and simply error (and shutdown). Setting
196 /// this option to `false` will allow that.
197 ///
198 /// Default is `true`.
199 pub fn set_sleep_on_errors(&mut self, val: bool) {
200 self.sleep_on_errors = val;
201 }
202
203 fn poll_next_(&mut self, cx: &mut task::Context<'_>) -> Poll<io::Result<AddrStream>> {
204 // Check if a previous timeout is active that was set by IO errors.
205 if let Some(ref mut to) = self.timeout {
206 ready!(Pin::new(to).poll(cx));
207 }
208 self.timeout = None;
209
210 loop {
211 match ready!(self.listener.poll_accept(cx)) {
212 Ok((socket, remote_addr)) => {
213 if let Some(tcp_keepalive) = &self.tcp_keepalive_config.into_socket2() {
214 let sock_ref = socket2::SockRef::from(&socket);
215 if let Err(e) = sock_ref.set_tcp_keepalive(tcp_keepalive) {
216 trace!("error trying to set TCP keepalive: {}", e);
217 }
218 }
219 if let Err(e) = socket.set_nodelay(self.tcp_nodelay) {
220 trace!("error trying to set TCP nodelay: {}", e);
221 }
222 let local_addr = socket.local_addr()?;
223 return Poll::Ready(Ok(AddrStream::new(socket, remote_addr, local_addr)));
224 }
225 Err(e) => {
226 // Connection errors can be ignored directly, continue by
227 // accepting the next request.
228 if is_connection_error(&e) {
229 debug!("accepted connection already errored: {}", e);
230 continue;
231 }
232
233 if self.sleep_on_errors {
234 error!("accept error: {}", e);
235
236 // Sleep 1s.
237 let mut timeout = Box::pin(tokio::time::sleep(Duration::from_secs(1)));
238
239 match timeout.as_mut().poll(cx) {
240 Poll::Ready(()) => {
241 // Wow, it's been a second already? Ok then...
242 continue;
243 }
244 Poll::Pending => {
245 self.timeout = Some(timeout);
246 return Poll::Pending;
247 }
248 }
249 } else {
250 return Poll::Ready(Err(e));
251 }
252 }
253 }
254 }
255 }
256 }
257
258 impl Accept for AddrIncoming {
259 type Conn = AddrStream;
260 type Error = io::Error;
261
262 fn poll_accept(
263 mut self: Pin<&mut Self>,
264 cx: &mut task::Context<'_>,
265 ) -> Poll<Option<Result<Self::Conn, Self::Error>>> {
266 let result = ready!(self.poll_next_(cx));
267 Poll::Ready(Some(result))
268 }
269 }
270
271 /// This function defines errors that are per-connection. Which basically
272 /// means that if we get this error from `accept()` system call it means
273 /// next connection might be ready to be accepted.
274 ///
275 /// All other errors will incur a timeout before next `accept()` is performed.
276 /// The timeout is useful to handle resource exhaustion errors like ENFILE
277 /// and EMFILE. Otherwise, could enter into tight loop.
278 fn is_connection_error(e: &io::Error) -> bool {
279 matches!(
280 e.kind(),
281 io::ErrorKind::ConnectionRefused
282 | io::ErrorKind::ConnectionAborted
283 | io::ErrorKind::ConnectionReset
284 )
285 }
286
287 impl fmt::Debug for AddrIncoming {
288 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289 f.debug_struct("AddrIncoming")
290 .field("addr", &self.addr)
291 .field("sleep_on_errors", &self.sleep_on_errors)
292 .field("tcp_keepalive_config", &self.tcp_keepalive_config)
293 .field("tcp_nodelay", &self.tcp_nodelay)
294 .finish()
295 }
296 }
297
298 mod addr_stream {
299 use std::io;
300 use std::net::SocketAddr;
301 #[cfg(unix)]
302 use std::os::unix::io::{AsRawFd, RawFd};
303 use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
304 use tokio::net::TcpStream;
305
306 use crate::common::{task, Pin, Poll};
307
308 pin_project_lite::pin_project! {
309 /// A transport returned yieled by `AddrIncoming`.
310 #[derive(Debug)]
311 pub struct AddrStream {
312 #[pin]
313 inner: TcpStream,
314 pub(super) remote_addr: SocketAddr,
315 pub(super) local_addr: SocketAddr
316 }
317 }
318
319 impl AddrStream {
320 pub(super) fn new(
321 tcp: TcpStream,
322 remote_addr: SocketAddr,
323 local_addr: SocketAddr,
324 ) -> AddrStream {
325 AddrStream {
326 inner: tcp,
327 remote_addr,
328 local_addr,
329 }
330 }
331
332 /// Returns the remote (peer) address of this connection.
333 #[inline]
334 pub fn remote_addr(&self) -> SocketAddr {
335 self.remote_addr
336 }
337
338 /// Returns the local address of this connection.
339 #[inline]
340 pub fn local_addr(&self) -> SocketAddr {
341 self.local_addr
342 }
343
344 /// Consumes the AddrStream and returns the underlying IO object
345 #[inline]
346 pub fn into_inner(self) -> TcpStream {
347 self.inner
348 }
349
350 /// Attempt to receive data on the socket, without removing that data
351 /// from the queue, registering the current task for wakeup if data is
352 /// not yet available.
353 pub fn poll_peek(
354 &mut self,
355 cx: &mut task::Context<'_>,
356 buf: &mut tokio::io::ReadBuf<'_>,
357 ) -> Poll<io::Result<usize>> {
358 self.inner.poll_peek(cx, buf)
359 }
360 }
361
362 impl AsyncRead for AddrStream {
363 #[inline]
364 fn poll_read(
365 self: Pin<&mut Self>,
366 cx: &mut task::Context<'_>,
367 buf: &mut ReadBuf<'_>,
368 ) -> Poll<io::Result<()>> {
369 self.project().inner.poll_read(cx, buf)
370 }
371 }
372
373 impl AsyncWrite for AddrStream {
374 #[inline]
375 fn poll_write(
376 self: Pin<&mut Self>,
377 cx: &mut task::Context<'_>,
378 buf: &[u8],
379 ) -> Poll<io::Result<usize>> {
380 self.project().inner.poll_write(cx, buf)
381 }
382
383 #[inline]
384 fn poll_write_vectored(
385 self: Pin<&mut Self>,
386 cx: &mut task::Context<'_>,
387 bufs: &[io::IoSlice<'_>],
388 ) -> Poll<io::Result<usize>> {
389 self.project().inner.poll_write_vectored(cx, bufs)
390 }
391
392 #[inline]
393 fn poll_flush(self: Pin<&mut Self>, _cx: &mut task::Context<'_>) -> Poll<io::Result<()>> {
394 // TCP flush is a noop
395 Poll::Ready(Ok(()))
396 }
397
398 #[inline]
399 fn poll_shutdown(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> {
400 self.project().inner.poll_shutdown(cx)
401 }
402
403 #[inline]
404 fn is_write_vectored(&self) -> bool {
405 // Note that since `self.inner` is a `TcpStream`, this could
406 // *probably* be hard-coded to return `true`...but it seems more
407 // correct to ask it anyway (maybe we're on some platform without
408 // scatter-gather IO?)
409 self.inner.is_write_vectored()
410 }
411 }
412
413 #[cfg(unix)]
414 impl AsRawFd for AddrStream {
415 fn as_raw_fd(&self) -> RawFd {
416 self.inner.as_raw_fd()
417 }
418 }
419 }
420
421 #[cfg(test)]
422 mod tests {
423 use std::time::Duration;
424 use crate::server::tcp::TcpKeepaliveConfig;
425
426 #[test]
427 fn no_tcp_keepalive_config() {
428 assert!(TcpKeepaliveConfig::default().into_socket2().is_none());
429 }
430
431 #[test]
432 fn tcp_keepalive_time_config() {
433 let mut kac = TcpKeepaliveConfig::default();
434 kac.time = Some(Duration::from_secs(60));
435 if let Some(tcp_keepalive) = kac.into_socket2() {
436 assert!(format!("{tcp_keepalive:?}").contains("time: Some(60s)"));
437 } else {
438 panic!("test failed");
439 }
440 }
441
442 #[cfg(any(
443 target_os = "android",
444 target_os = "dragonfly",
445 target_os = "freebsd",
446 target_os = "fuchsia",
447 target_os = "illumos",
448 target_os = "linux",
449 target_os = "netbsd",
450 target_vendor = "apple",
451 windows,
452 ))]
453 #[test]
454 fn tcp_keepalive_interval_config() {
455 let mut kac = TcpKeepaliveConfig::default();
456 kac.interval = Some(Duration::from_secs(1));
457 if let Some(tcp_keepalive) = kac.into_socket2() {
458 assert!(format!("{tcp_keepalive:?}").contains("interval: Some(1s)"));
459 } else {
460 panic!("test failed");
461 }
462 }
463
464 #[cfg(any(
465 target_os = "android",
466 target_os = "dragonfly",
467 target_os = "freebsd",
468 target_os = "fuchsia",
469 target_os = "illumos",
470 target_os = "linux",
471 target_os = "netbsd",
472 target_vendor = "apple",
473 ))]
474 #[test]
475 fn tcp_keepalive_retries_config() {
476 let mut kac = TcpKeepaliveConfig::default();
477 kac.retries = Some(3);
478 if let Some(tcp_keepalive) = kac.into_socket2() {
479 assert!(format!("{tcp_keepalive:?}").contains("retries: Some(3)"));
480 } else {
481 panic!("test failed");
482 }
483 }
484 }