Skip to content

Commit

Permalink
⏰ Time out connections that don't auth (#27)
Browse files Browse the repository at this point in the history
Fixes #26 

This change will time out connections that don't finish their TLS handshake within a set time, preventing the server from getting hung up trying to negotiate dead connections.

Eventually we should negotiate these connections without blocking the `accept` thread, but there would be a non-trivial amount of work to update the tests to the new behavior.
  • Loading branch information
haydenmc authored Feb 16, 2021
1 parent 60ce60c commit 631dae1
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions inc/TlsConnectionTransport.h
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

#include <arpa/inet.h>
#include <atomic>
#include <chrono>
#include <filesystem>
#include <functional>
#include <mutex>
Expand Down Expand Up @@ -180,6 +181,8 @@ class TlsConnectionTransport : public IConnectionTransport
private:
/* Static members */
static constexpr int BUFFER_SIZE = 512;
static constexpr std::chrono::milliseconds CONNECT_TIMEOUT =
std::chrono::milliseconds(2500);
/* Private members */
const bool isServer;
const int socketHandle;
Expand Down Expand Up @@ -241,10 +244,25 @@ class TlsConnectionTransport : public IConnectionTransport
// Indicate when we've exited this thread
connectionThreadEndedPromise.set_value_at_thread_exit();

// Keep track of how long it takes to connect, so we can time out
std::chrono::time_point<std::chrono::steady_clock> connectStartTime =
std::chrono::steady_clock::now();

// First, we need to connect.
int connectResult = isServer ? SSL_accept(ssl.get()) : SSL_connect(ssl.get());
while (connectResult == -1)
{
// Have we taken too long?
auto elapsedTime = (std::chrono::steady_clock::now() - connectStartTime);
if (elapsedTime > CONNECT_TIMEOUT)
{
// Whoops, took too long to connect.
spdlog::debug("{} SSL negotiation timed out");
sslConnectedPromise.set_value(false);
closeConnection();
return;
}

// We're not done connecting yet - figure out what we're waiting on
int connectError = SSL_get_error(ssl.get(), connectResult);
if (connectError == SSL_ERROR_WANT_READ)
Expand Down

0 comments on commit 631dae1

Please sign in to comment.