Просмотр исходного кода

Add Server::set_accept_handler() to refuse connections before reading

There was no way to refuse a connection before the server read a
request from it, or before the TLS handshake on SSLServer. The earliest
hook was the pre-routing handler, after the request head had been read.

set_accept_handler() takes a callback that gets each accepted socket
and returns whether to serve it. Both accept paths, with and without
keep-alive parking, go through one function, admit_accepted_socket(),
which sets the socket timeouts first, so that a handler reading from
the socket cannot block forever. A refused or throwing handler closes
the socket; an exception is reported as Error::UserCallbackException.

Fix #2700
yhirose 3 дней назад
Родитель
Сommit
7bd99c5ddf
5 измененных файлов с 185 добавлено и 7 удалено
  1. 19 1
      README.md
  2. 17 0
      docs-src/pages/en/cookbook/s09-pre-routing.md
  3. 17 0
      docs-src/pages/ja/cookbook/s09-pre-routing.md
  4. 27 6
      httplib.h
  5. 105 0
      test/test.cc

+ 19 - 1
README.md

@@ -587,9 +587,27 @@ svr.set_pre_request_handler([](const auto& req, auto& res) {
 > [!NOTE]
 > Because the body has not been read yet, `req.body` and form fields parsed from the body are not available in the pre-request handler. Inspect headers, the path, query parameters, or `req.matched_route` instead.
 
+### Accept handler
+
+The accept handler runs for each accepted connection before anything is read from it, and before the TLS handshake on `SSLServer`. Return `false` to close the connection.
+
+```cpp
+svr.set_accept_handler([](socket_t sock) {
+  sockaddr_storage addr;
+  socklen_t len = sizeof(addr);
+  if (getpeername(sock, reinterpret_cast<sockaddr *>(&addr), &len) != 0) {
+    return false;
+  }
+  return is_allowed(addr); // Your own check
+});
+```
+
+> [!NOTE]
+> The handler runs on the thread that accepts connections, so a slow handler delays every new connection. With `set_keep_alive_parking(true)`, that thread also hands out the next requests on kept-alive connections, so those wait too. The server owns `sock` and closes it after a refusal, so the handler must not close it. If the handler throws, the connection is closed and the error logger receives `Error::UserCallbackException`.
+
 ### Handler execution order
 
-`set_start_handler` runs once when the server starts. For each request, handlers run in the following order:
+`set_start_handler` runs once when the server starts, and `set_accept_handler` once for each connection, before any request on it. For each request, handlers run in the following order:
 
 ```
 Request received

+ 17 - 0
docs-src/pages/en/cookbook/s09-pre-routing.md

@@ -51,4 +51,21 @@ If auth fails, return `Handled` to respond with 401 immediately. If it passes, r
 
 If you want different auth rules per route rather than a single global check, `set_pre_request_handler()` is a better fit. See [S11. Authenticate per route with a pre-request handler](../s11-pre-request).
 
+## Refuse at the connection
+
+If all you need is to filter by the peer address, you can refuse the connection before any request is read. `set_accept_handler()` runs right after a connection is accepted, before the request is read (and before the TLS handshake on `SSLServer`). Return `false`, and the connection is closed without reading from it.
+
+```cpp
+svr.set_accept_handler([](socket_t sock) {
+  sockaddr_storage addr;
+  socklen_t len = sizeof(addr);
+  if (getpeername(sock, reinterpret_cast<sockaddr *>(&addr), &len) != 0) {
+    return false;
+  }
+  return is_allowed(addr); // your own check
+});
+```
+
+The handler runs on the thread that accepts connections, so a slow handler holds up every new connection. The server closes the socket, so don't close it in the handler.
+
 > **Note:** If all you want is to modify the response, `set_post_routing_handler()` is the right tool. See [S10. Add response headers with a post-routing handler](../s10-post-routing).

+ 17 - 0
docs-src/pages/ja/cookbook/s09-pre-routing.md

@@ -51,4 +51,21 @@ svr.set_pre_routing_handler(
 
 全ルート共通ではなく、ルート単位で認証を分けたいときは、[S11. Pre-request handlerでルート単位の認証を行う](../s11-pre-request)のほうが適しています。
 
+## 接続の段階で断る
+
+接続元のアドレスで絞り込むだけなら、リクエストを読む前に断れます。`set_accept_handler()`は、接続を受け付けた直後、リクエストを読む前(`SSLServer`ならTLSハンドシェイクの前)に呼ばれます。`false`を返すと、その接続は何も読まずに閉じられます。
+
+```cpp
+svr.set_accept_handler([](socket_t sock) {
+  sockaddr_storage addr;
+  socklen_t len = sizeof(addr);
+  if (getpeername(sock, reinterpret_cast<sockaddr *>(&addr), &len) != 0) {
+    return false;
+  }
+  return is_allowed(addr); // 自前の判定
+});
+```
+
+このハンドラは接続を受け付けるスレッドで動くので、時間のかかる処理を入れると新しい接続がすべて待たされます。また、ソケットはサーバーが閉じるので、ハンドラの中では閉じないでください。
+
 > **Note:** レスポンスを加工したいだけなら、`set_post_routing_handler()`のほうが適切です。[S10. Post-routing handlerでレスポンスヘッダーを追加する](../s10-post-routing)を参照してください。

+ 27 - 6
httplib.h

@@ -2298,6 +2298,8 @@ public:
 
   using StartHandler = std::function<void()>;
 
+  using AcceptHandler = std::function<bool(socket_t sock)>;
+
   using WebSocketHandler =
       std::function<void(const Request &, ws::WebSocket &)>;
   using SubProtocolSelector =
@@ -2363,6 +2365,8 @@ public:
 
   Server &set_start_handler(StartHandler handler);
 
+  Server &set_accept_handler(AcceptHandler handler);
+
   Server &set_logger(Logger logger);
   Server &set_pre_compression_logger(Logger logger);
   Server &set_error_logger(ErrorLogger error_logger);
@@ -2438,8 +2442,9 @@ protected:
                        const std::function<void(Request &)> &setup_request,
                        bool *websocket_upgraded = nullptr);
 
-  // Runs the per-connection serving loop and stops an exception thrown by a
-  // user callback from escaping the worker thread.
+  // Runs a user callback, or the per-connection serving loop that calls user
+  // callbacks, and stops an exception thrown by one from escaping the
+  // server's threads.
   //
   // process_request() wraps only routing() and the hooks before a WebSocket
   // upgrade in a try/catch. Content providers, the post-routing, error,
@@ -2542,7 +2547,7 @@ private:
   bool listen_internal();
   bool accept_loop(TaskQueue &task_queue);
   bool parking_loop(TaskQueue &task_queue);
-  void prepare_accepted_socket(socket_t sock) const;
+  bool admit_accepted_socket(socket_t sock) const;
   struct PlainConnection;
   void resume_connection(std::shared_ptr<KeepAliveConnection> conn);
   bool abandon_listen_socket();
@@ -2647,6 +2652,7 @@ private:
   HandlerWithResponse pre_request_handler_;
   Expect100ContinueHandler expect_100_continue_handler_;
   StartHandler start_handler_;
+  AcceptHandler accept_handler_;
 
   mutable std::mutex logger_mutex_;
   Logger logger_;
@@ -14873,6 +14879,11 @@ inline Server &Server::set_start_handler(StartHandler handler) {
   return *this;
 }
 
+inline Server &Server::set_accept_handler(AcceptHandler handler) {
+  accept_handler_ = std::move(handler);
+  return *this;
+}
+
 inline Server &Server::set_address_family(int family) {
   address_family_ = family;
   return *this;
@@ -15678,12 +15689,22 @@ inline bool Server::listen_internal() {
   return ret;
 }
 
-inline void Server::prepare_accepted_socket(socket_t sock) const {
+// Closes the socket and returns false when the accept handler refuses it.
+inline bool Server::admit_accepted_socket(socket_t sock) const {
   detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec_,
                               read_timeout_usec_);
   detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec_,
                               write_timeout_usec_);
   if (tcp_nodelay_) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
+
+  // After the timeouts, so that a handler reading from the socket returns.
+  if (accept_handler_ &&
+      !serve_guarded([&]() { return accept_handler_(sock); })) {
+    detail::shutdown_socket(sock);
+    detail::close_socket(sock);
+    return false;
+  }
+  return true;
 }
 
 // Serves each connection on one worker thread for its whole life.
@@ -15722,7 +15743,7 @@ inline bool Server::accept_loop(TaskQueue &task_queue) {
       break;
     }
 
-    prepare_accepted_socket(sock);
+    if (!admit_accepted_socket(sock)) { continue; }
 
     if (!task_queue.enqueue(
             [this, sock]() { process_and_close_socket(sock); })) {
@@ -16684,7 +16705,7 @@ inline bool Server::parking_loop(TaskQueue &task_queue) {
           }
           // Some platforms make it non-blocking like the listening socket.
           detail::set_nonblocking(sock, false);
-          prepare_accepted_socket(sock);
+          if (!admit_accepted_socket(sock)) { continue; }
           park(new_keep_alive_connection(sock), now);
           if (idle.count() > 0) { next_idle = now + idle; }
         }

+ 105 - 0
test/test.cc

@@ -34676,6 +34676,11 @@ bool sees_eof(socket_t sock, std::chrono::steady_clock::time_point deadline) {
          detail::read_socket(sock, &c, 1, 0) <= 0;
 }
 
+// Whether the server closes `sock` without answering a request.
+bool get_refused(socket_t sock, int timeout_ms) {
+  return send_get(sock) && sees_eof(sock, in_ms(timeout_ms));
+}
+
 bool wait_until(const std::function<bool()> &cond, int timeout_ms) {
   auto deadline = in_ms(timeout_ms);
   while (!cond()) {
@@ -35037,3 +35042,103 @@ TEST(KeepAliveParkingTest, StopClosesParkedTlsConnections) {
             std::chrono::milliseconds(500));
 }
 #endif
+
+TEST(AcceptHandlerTest, RefusedConnectionIsClosedUnread) {
+  using namespace parking_test;
+  for (auto parking : {false, true}) {
+    SCOPED_TRACE(parking);
+    Server svr;
+    serve_ok(svr, threads(2));
+    svr.set_keep_alive_parking(parking);
+    std::atomic<int> served{0};
+    svr.set_pre_routing_handler([&](const Request &, Response &) {
+      served++;
+      return Server::HandlerResponse::Unhandled;
+    });
+    std::atomic<bool> allow{false};
+    std::atomic<bool> peer_seen{false};
+    svr.set_accept_handler([&](socket_t sock) {
+      sockaddr_in addr{};
+      socklen_t len = sizeof(addr);
+      peer_seen =
+          getpeername(sock, reinterpret_cast<sockaddr *>(&addr), &len) == 0 &&
+          addr.sin_family == AF_INET &&
+          ntohl(addr.sin_addr.s_addr) == INADDR_LOOPBACK;
+      return allow.load();
+    });
+    RunningServer running(svr);
+    Sockets socks;
+
+    EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
+    EXPECT_TRUE(peer_seen);
+    EXPECT_EQ(0, served);
+
+    allow = true;
+    EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
+    EXPECT_EQ(1, served);
+  }
+}
+
+TEST(AcceptHandlerTest, HandlerSeesTheReadTimeout) {
+  using namespace parking_test;
+  Server svr;
+  serve_ok(svr, threads(1));
+  svr.set_read_timeout(std::chrono::milliseconds(50));
+  std::atomic<bool> timed_out{false};
+  svr.set_accept_handler([&](socket_t sock) {
+    char c;
+    timed_out = detail::read_socket(sock, &c, 1, 0) < 0;
+    return true;
+  });
+  RunningServer running(svr);
+  Sockets socks;
+
+  auto sock = socks.connect(running.port);
+  EXPECT_TRUE(wait_until([&] { return timed_out.load(); }, 1000));
+  EXPECT_TRUE(get_ok(sock, 1000));
+}
+
+#ifndef CPPHTTPLIB_NO_EXCEPTIONS
+TEST(AcceptHandlerTest, ThrowingHandlerRefusesTheConnection) {
+  using namespace parking_test;
+  Server svr;
+  serve_ok(svr, threads(1));
+  std::atomic<bool> throws{true};
+  svr.set_accept_handler([&](socket_t) -> bool {
+    if (throws) { throw std::runtime_error("refused"); }
+    return true;
+  });
+  std::atomic<int> logged{0};
+  svr.set_error_logger([&](const Error &err, const Request *) {
+    if (err == Error::UserCallbackException) { logged++; }
+  });
+  RunningServer running(svr);
+  Sockets socks;
+
+  EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
+  EXPECT_EQ(1, logged);
+
+  throws = false;
+  EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
+}
+#endif
+
+#ifdef CPPHTTPLIB_SSL_ENABLED
+TEST(AcceptHandlerTest, RefusedTlsConnectionSkipsTheHandshake) {
+  using namespace parking_test;
+  for (auto parking : {false, true}) {
+    SCOPED_TRACE(parking);
+    SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
+    ASSERT_TRUE(svr.is_valid());
+    serve_ok(svr, threads(1));
+    svr.set_keep_alive_parking(parking);
+    svr.set_accept_handler([](socket_t) { return false; });
+    RunningServer running(svr);
+    Sockets socks;
+
+    // A handshake on a plain request would fail and set ssl_last_error().
+    EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
+    EXPECT_EQ(0, svr.ssl_last_error());
+  }
+}
+#endif