Skip to content

Commit aa109bb

Browse files
committed
tcp: add timeout to connection
Add a 3s timeout to all tcp connections, we do not want clients to keep the connections open forever. Also do not allow more than one message per connection. The API is a bit weird, we first get the message then have to poll again where it return None otherwise the reply will not be send. Signed-off-by: Paul Holzinger <pholzing@redhat.com>
1 parent e2ab2c8 commit aa109bb

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

src/dns/coredns.rs

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ use std::io::Error;
2323
use std::net::{IpAddr, SocketAddr};
2424
use std::sync::Arc;
2525
use std::sync::Mutex;
26+
use std::time::Duration;
2627
use tokio::net::TcpListener;
2728
use tokio::net::UdpSocket;
2829

@@ -108,8 +109,21 @@ impl CoreDns {
108109
let (mut hickory_stream, sender_original) =
109110
TcpStream::from_stream(AsyncIoTokioAsStd(stream), peer);
110111

111-
while let Some(message) = hickory_stream.next().await {
112-
self.process_message(message, &sender_original, Protocol::Tcp)
112+
// It is possible for a client to keep the tcp socket open forever and never send any data,
113+
// we do not want this so add a 3s timeout then we close the socket.
114+
match tokio::time::timeout(Duration::from_secs(3), hickory_stream.next()).await {
115+
Ok(message) => {
116+
if let Some(msg) = message {
117+
self.process_message(msg, &sender_original, Protocol::Tcp);
118+
// The API is a bit strange, first time we call next we get the message,
119+
// but we must call again to send our reply back
120+
hickory_stream.next().await;
121+
}
122+
}
123+
Err(_) => debug!(
124+
"Tcp connection {} was cancelled after 3s as it took to long to receive message",
125+
peer
126+
),
113127
}
114128
}
115129

0 commit comments

Comments
 (0)