mirror of
https://github.com/yhirose/cpp-httplib.git
synced 2026-09-02 14:53:46 +00:00
* Add Server::CustomRoute() for HTTP methods outside the built-in set parse_request_line validates the request method against a fixed whitelist and rejects anything else with 400 before routing runs. That blocks WebDAV, where PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK and UNLOCK are ordinary methods defined by RFC 4918, and it blocks extension methods such as UPnP's SUBSCRIBE. The need has been open since #847. Registering a handler is now what makes the server accept a method: svr.CustomRoute("PROPFIND", "/dav/:id", handler); Because custom methods go through the normal dispatch path, patterns work the way they do for Get() and friends, and the request body is available in req.body. Serving these methods through set_pre_routing_handler was never enough: the body has not been read at that point, so PROPPATCH and LOCK, which require one, could not be implemented at all. A HandlerWithContentReader overload is available too. The content reader gate in routing() also fires when a custom method carries no body, matching what expect_content() does unconditionally for POST/PUT/PATCH/DELETE, so a body-less PROPFIND (RFC 4918 treats one as allprop) reaches its handler instead of falling through to 404. Method names are validated as RFC 9110 tokens, and the ten built-in methods are refused. Seven of them are dispatched by the if/else chain in routing() before the custom tables are consulted, so a route registered for one could never fire; CONNECT, TRACE and PRI carry protocol-level meaning this library does not route. A refused registration makes is_valid() return false, so listen() fails rather than starting a server holding a handler that would never run. This is also why SSLServer::is_valid() now chains to Server::is_valid() instead of only checking ctx_. Servers that never call CustomRoute() keep the previous per-request cost: the built-in method set is checked first and short-circuits, and the custom lookup returns early on an empty map. * Add cookbook recipe for custom HTTP methods The CustomRoute() docs were a section inside S01, which pushed that page to 90 lines, the longest in the cookbook, and mixed a separate feature into a page about registering GET/POST/PUT/DELETE handlers. Move the section into its own recipe and give it room for the part that was missing: the OPTIONS handler returning DAV: and Allow, which WebDAV clients probe for before anything else. S01 goes back to 68 lines and keeps a pointer to the new page. The recipe is titled after the API rather than after WebDAV, and says outright that generating the 207 Multi-Status XML, interpreting Depth and managing locks are the reader's job. Routing the method is all the library does. S23 takes order 42, so the TLS, SSE and WebSocket recipes shift to 43-57. That only moves the sort key. Filenames, the T01/E01/W01 labels, the published URLs and every cross-reference are untouched.
3.0 KiB
3.0 KiB
title, order, status
| title | order | status |
|---|---|---|
| T05. サーバー側でピア証明書を参照する | 47 | draft |
mTLS構成では、接続してきたクライアントの証明書をハンドラの中で読めます。証明書のCN(Common Name)やSAN(Subject Alternative Name)を取り出して、ユーザーを特定したり、ログに残したりできます。
基本の使い方
svr.Get("/me", [](const httplib::Request &req, httplib::Response &res) {
auto cert = req.peer_cert();
if (!cert) {
res.status = 401;
res.set_content("no client certificate", "text/plain");
return;
}
auto cn = cert.subject_cn();
res.set_content("hello, " + cn, "text/plain");
});
req.peer_cert()はtls::PeerCertオブジェクトを返します。boolに変換できるので、まずは証明書の有無を確認してから使います。
取り出せる情報
PeerCertからは、以下の情報を取得できます。
auto cert = req.peer_cert();
std::string cn = cert.subject_cn(); // CN
std::string issuer = cert.issuer_name(); // 発行者
std::string serial = cert.serial(); // シリアル番号
time_t not_before, not_after;
cert.validity(not_before, not_after); // 有効期間
auto sans = cert.sans(); // SAN一覧
for (const auto &san : sans) {
std::cout << san.value << std::endl;
}
ホスト名がSANに含まれるかを確認するヘルパーもあります。
if (cert.check_hostname("alice.corp.example.com")) {
// 一致
}
証明書ベースの認可
CNやSANを使って、ルート単位でアクセス制御できます。
svr.set_pre_request_handler(
[](const httplib::Request &req, httplib::Response &res) {
auto cert = req.peer_cert();
if (!cert) {
res.status = 401;
return httplib::Server::HandlerResponse::Handled;
}
if (req.matched_route.rfind("/admin", 0) == 0) {
auto cn = cert.subject_cn();
if (!is_admin_cn(cn)) {
res.status = 403;
return httplib::Server::HandlerResponse::Handled;
}
}
return httplib::Server::HandlerResponse::Unhandled;
});
Pre-requestハンドラと組み合わせれば、共通の認可ロジックを一箇所にまとめられます。詳しくはS11. Pre-request handlerでルート単位の認証を行うを参照してください。
SNI(Server Name Indication)
クライアントが指定してきたサーバー名は、cpp-httplibが自動で処理します。同じサーバーで複数のドメインをホストする場合にSNIが使われますが、通常はハンドラ側で意識する必要はありません。
Warning:
req.peer_cert()は、mTLSが有効で、かつクライアントが証明書を提示した場合のみ有効な値を返します。通常のTLS接続では空のPeerCertが返ります。使う前に必ずboolチェックしてください。
mTLSの設定方法はT04. mTLSを設定するを参照してください。