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
3.4 KiB
title, order, status
| title | order | status |
|---|---|---|
| S09. 全ルートに共通の前処理をする | 28 | draft |
すべてのリクエストに対して共通の処理を走らせたいことがあります。認証チェック、ロギング、レート制限などです。こうした処理はset_pre_routing_handler()で登録します。
基本の使い方
svr.set_pre_routing_handler(
[](const httplib::Request &req, httplib::Response &res) {
std::cout << req.method << " " << req.path << std::endl;
return httplib::Server::HandlerResponse::Unhandled;
});
Pre-routingハンドラは、ルーティングよりも前に呼ばれます。どのハンドラにもマッチしないリクエストも含めて、すべてのリクエストを捕まえられます。ただし、リクエストラインやヘッダーの解析中に拒否されたリクエスト(不正なリクエストの400、長すぎるURIの414、不正なRangeの416)には、このハンドラが呼ばれる前にサーバーが応答します。
戻り値のHandlerResponseがポイントです。
Unhandledを返す: 通常の処理を続行(ルーティングとハンドラ呼び出し)Handledを返す: ここでレスポンスが完了したとみなし、以降の処理をスキップ
認証チェックに使う
全ルート共通の認証を一箇所でかけられます。
svr.set_pre_routing_handler(
[](const httplib::Request &req, httplib::Response &res) {
if (req.path.rfind("/public", 0) == 0) {
return httplib::Server::HandlerResponse::Unhandled; // 認証不要
}
auto auth = req.get_header_value("Authorization");
if (auth.empty()) {
res.status = 401;
res.set_content("unauthorized", "text/plain");
return httplib::Server::HandlerResponse::Handled;
}
return httplib::Server::HandlerResponse::Unhandled;
});
認証が通らなければHandledを返してその場で401を返し、通ればUnhandledを返して通常のルーティングに進ませます。
特定ルートだけに認証をかけたい場合
全ルート共通ではなく、ルート単位で認証を分けたいときは、S11. Pre-request handlerでルート単位の認証を行うのほうが適しています。
接続の段階で断る
接続元のアドレスで絞り込むだけなら、リクエストを読む前に断れます。set_accept_handler()は、接続を受け付けた直後、リクエストを読む前(SSLServerならTLSハンドシェイクの前)に呼ばれます。falseを返すと、その接続は何も読まずに閉じられます。
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でレスポンスヘッダーを追加するを参照してください。