1
0
Эх сурвалжийг харах

Add Server::CustomRoute() for HTTP methods outside the built-in set (#2553)

* 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.
yhirose 3 өдөр өмнө
parent
commit
254e576b50
39 өөрчлөгдсөн 588 нэмэгдсэн , 39 устгасан
  1. 33 0
      README.md
  2. 1 1
      docs-src/pages/en/cookbook/e01-sse-server.md
  3. 1 1
      docs-src/pages/en/cookbook/e02-sse-event-names.md
  4. 1 1
      docs-src/pages/en/cookbook/e03-sse-reconnect.md
  5. 1 1
      docs-src/pages/en/cookbook/e04-sse-client.md
  6. 3 0
      docs-src/pages/en/cookbook/index.md
  7. 3 1
      docs-src/pages/en/cookbook/s01-handlers.md
  8. 59 0
      docs-src/pages/en/cookbook/s23-custom-methods.md
  9. 1 1
      docs-src/pages/en/cookbook/t01-tls-backends.md
  10. 1 1
      docs-src/pages/en/cookbook/t02-cert-verification.md
  11. 1 1
      docs-src/pages/en/cookbook/t03-ssl-server.md
  12. 1 1
      docs-src/pages/en/cookbook/t04-mtls.md
  13. 1 1
      docs-src/pages/en/cookbook/t05-peer-cert.md
  14. 1 1
      docs-src/pages/en/cookbook/w01-websocket-echo.md
  15. 1 1
      docs-src/pages/en/cookbook/w02-websocket-ping.md
  16. 1 1
      docs-src/pages/en/cookbook/w03-websocket-close.md
  17. 1 1
      docs-src/pages/en/cookbook/w04-websocket-binary.md
  18. 1 1
      docs-src/pages/en/cookbook/w05-websocket-tls.md
  19. 1 1
      docs-src/pages/en/cookbook/w06-websocket-timeouts.md
  20. 1 1
      docs-src/pages/ja/cookbook/e01-sse-server.md
  21. 1 1
      docs-src/pages/ja/cookbook/e02-sse-event-names.md
  22. 1 1
      docs-src/pages/ja/cookbook/e03-sse-reconnect.md
  23. 1 1
      docs-src/pages/ja/cookbook/e04-sse-client.md
  24. 3 0
      docs-src/pages/ja/cookbook/index.md
  25. 3 1
      docs-src/pages/ja/cookbook/s01-handlers.md
  26. 59 0
      docs-src/pages/ja/cookbook/s23-custom-methods.md
  27. 1 1
      docs-src/pages/ja/cookbook/t01-tls-backends.md
  28. 1 1
      docs-src/pages/ja/cookbook/t02-cert-verification.md
  29. 1 1
      docs-src/pages/ja/cookbook/t03-ssl-server.md
  30. 1 1
      docs-src/pages/ja/cookbook/t04-mtls.md
  31. 1 1
      docs-src/pages/ja/cookbook/t05-peer-cert.md
  32. 1 1
      docs-src/pages/ja/cookbook/w01-websocket-echo.md
  33. 1 1
      docs-src/pages/ja/cookbook/w02-websocket-ping.md
  34. 1 1
      docs-src/pages/ja/cookbook/w03-websocket-close.md
  35. 1 1
      docs-src/pages/ja/cookbook/w04-websocket-binary.md
  36. 1 1
      docs-src/pages/ja/cookbook/w05-websocket-tls.md
  37. 1 1
      docs-src/pages/ja/cookbook/w06-websocket-timeouts.md
  38. 101 7
      httplib.h
  39. 294 0
      test/test.cc

+ 33 - 0
README.md

@@ -307,6 +307,39 @@ int main(void)
 
 `Post`, `Put`, `Patch`, `Delete` and `Options` methods are also supported.
 
+### Custom HTTP methods
+
+Methods outside the built-in set are rejected with `400 Bad Request` unless a handler is registered for them with `CustomRoute`. This covers the WebDAV methods of RFC 4918, `SUBSCRIBE` and friends from UPnP, and any other extension method.
+
+```c++
+svr.CustomRoute("PROPFIND", "/dav/:id", [](const Request& req, Response& res) {
+  // The request body is available as usual
+  auto id = req.path_params.at("id");
+  res.status = StatusCode::MultiStatus_207;
+  res.set_content(build_multistatus(req.body), "application/xml");
+});
+
+// A content reader overload is available too
+svr.CustomRoute("REPORT", "/dav/.*",
+                [](const Request& req, Response& res,
+                   const ContentReader& content_reader) {
+                  content_reader([&](const char* data, size_t data_length) {
+                    // ...
+                    return true;
+                  });
+                });
+```
+
+Patterns work exactly as they do for `Get` and the other methods, so regular expressions and path parameters are both available.
+
+Note the following:
+
+* The method name must be a valid HTTP method token (RFC 9110) and must be registered before `listen()` is called.
+* `GET`, `HEAD`, `POST`, `PUT`, `DELETE`, `CONNECT`, `OPTIONS`, `TRACE`, `PATCH` and `PRI` cannot be registered this way. Use the dedicated methods above instead.
+* A rejected registration makes `is_valid()` return `false`, and `listen()` then fails rather than starting a server with a route that would never fire.
+* Static file serving and WebSocket upgrades remain `GET`/`HEAD` only.
+* `Allow` and the WebDAV `DAV:` header are not generated automatically. Register an `Options` handler if clients need them.
+
 ### Bind a socket to multiple interfaces and any available port
 
 ```cpp

+ 1 - 1
docs-src/pages/en/cookbook/e01-sse-server.md

@@ -1,6 +1,6 @@
 ---
 title: "E01. Implement an SSE Server"
-order: 47
+order: 48
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/en/cookbook/e02-sse-event-names.md

@@ -1,6 +1,6 @@
 ---
 title: "E02. Use Named Events in SSE"
-order: 48
+order: 49
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/en/cookbook/e03-sse-reconnect.md

@@ -1,6 +1,6 @@
 ---
 title: "E03. Handle SSE Reconnection"
-order: 49
+order: 50
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/en/cookbook/e04-sse-client.md

@@ -1,6 +1,6 @@
 ---
 title: "E04. Receive SSE on the Client"
-order: 50
+order: 51
 status: "draft"
 ---
 

+ 3 - 0
docs-src/pages/en/cookbook/index.md

@@ -73,6 +73,9 @@ A collection of recipes that answer "How do I...?" questions. Each recipe is sel
 - [S21. Configure the thread pool](s21-thread-pool)
 - [S22. Talk over a Unix domain socket](s22-unix-socket)
 
+### Protocol Extensions
+- [S23. Handle custom HTTP methods](s23-custom-methods)
+
 ## TLS / Security
 
 - [T01. Choosing between OpenSSL, mbedTLS, and wolfSSL](t01-tls-backends)

+ 3 - 1
docs-src/pages/en/cookbook/s01-handlers.md

@@ -4,7 +4,7 @@ order: 20
 status: "draft"
 ---
 
-With `httplib::Server`, you register a handler per HTTP method. Just pass a pattern and a lambda to `Get()`, `Post()`, `Put()`, or `Delete()`.
+With `httplib::Server`, you register a handler per HTTP method. Just pass a pattern and a lambda to `Get()`, `Post()`, `Put()`, or `Delete()`. For methods outside the built-in set, such as WebDAV's `PROPFIND`, use `CustomRoute()`.
 
 ## Basic usage
 
@@ -64,3 +64,5 @@ To add a response header, use `res.set_header("Name", "Value")`.
 > **Note:** `listen()` is a blocking call. To run it on a different thread, wrap it in `std::thread`. If you need non-blocking startup, see [S18. Control startup order with `listen_after_bind`](../s18-listen-after-bind).
 
 > To use path parameters like `/users/:id`, see [S03. Use path parameters](../s03-path-params).
+
+> For methods outside the built-in set, such as WebDAV's `PROPFIND`, see [S23. Handle custom HTTP methods](../s23-custom-methods).

+ 59 - 0
docs-src/pages/en/cookbook/s23-custom-methods.md

@@ -0,0 +1,59 @@
+---
+title: "S23. Handle custom HTTP methods"
+order: 42
+status: "draft"
+---
+
+The server rejects HTTP methods it does not know with `400 Bad Request`. To accept an extension method, such as the WebDAV methods of RFC 4918 (`PROPFIND`, `PROPPATCH`, `MKCOL` and friends) or UPnP's `SUBSCRIBE`, register a handler with `CustomRoute()`. Registering the handler is what makes the server accept the method.
+
+## Basic usage
+
+```cpp
+svr.CustomRoute("PROPFIND", "/dav/:id",
+                [](const httplib::Request &req, httplib::Response &res) {
+                  // The request body is available as usual
+                  auto id = req.path_params.at("id");
+                  res.status = httplib::StatusCode::MultiStatus_207;
+                  res.set_content(build_multistatus(req.body), "application/xml");
+                });
+```
+
+Patterns work the same way as they do for `Get()`. Regular expressions and path parameters are both available.
+
+## Advertise your methods with OPTIONS
+
+A WebDAV client asks the server about its capabilities with `OPTIONS` before doing anything else. cpp-httplib generates neither the `DAV:` header nor `Allow`, so return them yourself. Forget this and clients will turn you away even though your `PROPFIND` works.
+
+```cpp
+svr.Options("/dav/.*", [](const httplib::Request &req, httplib::Response &res) {
+  res.set_header("DAV", "1");
+  res.set_header("Allow", "OPTIONS, GET, HEAD, PROPFIND, PROPPATCH, MKCOL");
+});
+```
+
+## Read the body as a stream
+
+There is a content reader overload, just like the one on `Post()`. Use it when you would rather not hold a large XML document in memory all at once.
+
+```cpp
+svr.CustomRoute("REPORT", "/dav/.*",
+                [](const httplib::Request &req, httplib::Response &res,
+                   const httplib::ContentReader &content_reader) {
+                  content_reader([&](const char *data, size_t data_length) {
+                    // Process it a chunk at a time
+                    return true;
+                  });
+                  res.status = httplib::StatusCode::MultiStatus_207;
+                });
+```
+
+## Things to keep in mind
+
+- The method name has to be a valid HTTP method token (RFC 9110), and it must be registered before you call `listen()`
+- `GET`, `HEAD`, `POST`, `PUT`, `DELETE`, `CONNECT`, `OPTIONS`, `TRACE`, `PATCH` and `PRI` cannot be registered here. Use the dedicated methods for those
+- A rejected registration makes `is_valid()` return `false` and `listen()` fail, so the server never starts holding a handler that would never run
+- Static file serving and WebSocket upgrades stay `GET`/`HEAD` only
+
+> **Note:** cpp-httplib takes you as far as routing the method. If you want to call it WebDAV, generating the `207 Multi-Status` XML, interpreting the `Depth` header and managing locks are all yours to implement. The protocol itself lives outside the library.
+
+> For the basics of registering handlers, see [S01. Register GET / POST / PUT / DELETE handlers](../s01-handlers).

+ 1 - 1
docs-src/pages/en/cookbook/t01-tls-backends.md

@@ -1,6 +1,6 @@
 ---
 title: "T01. Choosing Between OpenSSL, mbedTLS, and wolfSSL"
-order: 42
+order: 43
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/en/cookbook/t02-cert-verification.md

@@ -1,6 +1,6 @@
 ---
 title: "T02. Control SSL Certificate Verification"
-order: 43
+order: 44
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/en/cookbook/t03-ssl-server.md

@@ -1,6 +1,6 @@
 ---
 title: "T03. Start an SSL/TLS Server"
-order: 44
+order: 45
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/en/cookbook/t04-mtls.md

@@ -1,6 +1,6 @@
 ---
 title: "T04. Configure mTLS"
-order: 45
+order: 46
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/en/cookbook/t05-peer-cert.md

@@ -1,6 +1,6 @@
 ---
 title: "T05. Access the Peer Certificate on the Server Side"
-order: 46
+order: 47
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/en/cookbook/w01-websocket-echo.md

@@ -1,6 +1,6 @@
 ---
 title: "W01. Implement a WebSocket Echo Server and Client"
-order: 51
+order: 52
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/en/cookbook/w02-websocket-ping.md

@@ -1,6 +1,6 @@
 ---
 title: "W02. Set a WebSocket Heartbeat"
-order: 52
+order: 53
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/en/cookbook/w03-websocket-close.md

@@ -1,6 +1,6 @@
 ---
 title: "W03. Handle Connection Close"
-order: 53
+order: 54
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/en/cookbook/w04-websocket-binary.md

@@ -1,6 +1,6 @@
 ---
 title: "W04. Send and Receive Binary Frames"
-order: 54
+order: 55
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/en/cookbook/w05-websocket-tls.md

@@ -1,6 +1,6 @@
 ---
 title: "W05. Configure TLS for wss:// Connections"
-order: 55
+order: 56
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/en/cookbook/w06-websocket-timeouts.md

@@ -1,6 +1,6 @@
 ---
 title: "W06. Set Timeouts"
-order: 56
+order: 57
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/ja/cookbook/e01-sse-server.md

@@ -1,6 +1,6 @@
 ---
 title: "E01. SSEサーバーを実装する"
-order: 47
+order: 48
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/ja/cookbook/e02-sse-event-names.md

@@ -1,6 +1,6 @@
 ---
 title: "E02. SSEでイベント名を使い分ける"
-order: 48
+order: 49
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/ja/cookbook/e03-sse-reconnect.md

@@ -1,6 +1,6 @@
 ---
 title: "E03. SSEの再接続を処理する"
-order: 49
+order: 50
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/ja/cookbook/e04-sse-client.md

@@ -1,6 +1,6 @@
 ---
 title: "E04. SSEをクライアントで受信する"
-order: 50
+order: 51
 status: "draft"
 ---
 

+ 3 - 0
docs-src/pages/ja/cookbook/index.md

@@ -73,6 +73,9 @@ status: "draft"
 - [S21. マルチスレッド数を設定する](s21-thread-pool)
 - [S22. Unix domain socketで通信する](s22-unix-socket)
 
+### プロトコル拡張
+- [S23. カスタムHTTPメソッドを扱う](s23-custom-methods)
+
 ## TLS / セキュリティ
 
 - [T01. OpenSSL・mbedTLS・wolfSSLの選択指針](t01-tls-backends)

+ 3 - 1
docs-src/pages/ja/cookbook/s01-handlers.md

@@ -4,7 +4,7 @@ order: 20
 status: "draft"
 ---
 
-`httplib::Server`では、HTTPメソッドごとにハンドラを登録します。`Get()`、`Post()`、`Put()`、`Delete()`の各メソッドにパターンとラムダを渡すだけです。
+`httplib::Server`では、HTTPメソッドごとにハンドラを登録します。`Get()`、`Post()`、`Put()`、`Delete()`の各メソッドにパターンとラムダを渡すだけです。WebDAVの`PROPFIND`のような組み込み以外のメソッドを扱いたいときは、`CustomRoute()`を使います。
 
 ## 基本の使い方
 
@@ -64,3 +64,5 @@ svr.Get("/me", [](const httplib::Request &req, httplib::Response &res) {
 > **Note:** `listen()`はブロックする関数です。別スレッドで動かしたいときは`std::thread`で包むか、ノンブロッキング起動が必要なら[S18. `listen_after_bind`で起動順序を制御する](../s18-listen-after-bind)を参照してください。
 
 > パスパラメーター(`/users/:id`)を使いたい場合は[S03. パスパラメーターを使う](../s03-path-params)を参照してください。
+
+> WebDAVの`PROPFIND`のような組み込み以外のメソッドは[S23. カスタムHTTPメソッドを扱う](../s23-custom-methods)を参照してください。

+ 59 - 0
docs-src/pages/ja/cookbook/s23-custom-methods.md

@@ -0,0 +1,59 @@
+---
+title: "S23. カスタムHTTPメソッドを扱う"
+order: 42
+status: "draft"
+---
+
+サーバーは知らないHTTPメソッドを`400 Bad Request`で弾きます。RFC 4918のWebDAVメソッド(`PROPFIND`、`PROPPATCH`、`MKCOL`など)やUPnPの`SUBSCRIBE`のような拡張メソッドを受け付けたいときは、`CustomRoute()`でハンドラを登録してください。登録したことがそのまま「このメソッドを受け付ける」という意味になります。
+
+## 基本の使い方
+
+```cpp
+svr.CustomRoute("PROPFIND", "/dav/:id",
+                [](const httplib::Request &req, httplib::Response &res) {
+                  // リクエストボディも通常どおり読める
+                  auto id = req.path_params.at("id");
+                  res.status = httplib::StatusCode::MultiStatus_207;
+                  res.set_content(build_multistatus(req.body), "application/xml");
+                });
+```
+
+パターンの書き方は`Get()`などと同じです。正規表現もパスパラメーターもそのまま使えます。
+
+## OPTIONSで対応メソッドを知らせる
+
+WebDAVクライアントは接続すると、まず`OPTIONS`でサーバーの能力を問い合わせます。cpp-httplibは`DAV:`ヘッダーも`Allow`ヘッダーも自動生成しないので、自分で返してください。ここを忘れると、`PROPFIND`が正しく動いてもクライアントに拒否されます。
+
+```cpp
+svr.Options("/dav/.*", [](const httplib::Request &req, httplib::Response &res) {
+  res.set_header("DAV", "1");
+  res.set_header("Allow", "OPTIONS, GET, HEAD, PROPFIND, PROPPATCH, MKCOL");
+});
+```
+
+## ボディをストリーミングで受け取る
+
+`Post()`などと同じく、Content Reader版のオーバーロードがあります。大きなXMLを一度にメモリへ載せたくないときに使ってください。
+
+```cpp
+svr.CustomRoute("REPORT", "/dav/.*",
+                [](const httplib::Request &req, httplib::Response &res,
+                   const httplib::ContentReader &content_reader) {
+                  content_reader([&](const char *data, size_t data_length) {
+                    // 少しずつ処理する
+                    return true;
+                  });
+                  res.status = httplib::StatusCode::MultiStatus_207;
+                });
+```
+
+## 覚えておくこと
+
+- メソッド名はHTTPのトークン(RFC 9110)である必要があります。`listen()`より前に登録してください
+- `GET`、`HEAD`、`POST`、`PUT`、`DELETE`、`CONNECT`、`OPTIONS`、`TRACE`、`PATCH`、`PRI`は登録できません。これらには専用のメソッドを使ってください
+- 登録が拒否されると`is_valid()`が`false`になり、`listen()`が失敗します。呼ばれないハンドラを抱えたままサーバーが起動することはありません
+- 静的ファイルの配信とWebSocketのアップグレードは`GET`/`HEAD`のままです
+
+> **Note:** cpp-httplibが用意するのはメソッドのルーティングまでです。WebDAVを名乗るなら、`207 Multi-Status`のXML生成、`Depth`ヘッダーの解釈、ロックの管理は自分で実装することになります。プロトコルの本体はライブラリの外側です。
+
+> ハンドラ登録の基本は[S01. GET / POST / PUT / DELETEハンドラを登録する](../s01-handlers)を参照してください。

+ 1 - 1
docs-src/pages/ja/cookbook/t01-tls-backends.md

@@ -1,6 +1,6 @@
 ---
 title: "T01. OpenSSL・mbedTLS・wolfSSLの選択指針"
-order: 42
+order: 43
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/ja/cookbook/t02-cert-verification.md

@@ -1,6 +1,6 @@
 ---
 title: "T02. SSL証明書の検証を制御する"
-order: 43
+order: 44
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/ja/cookbook/t03-ssl-server.md

@@ -1,6 +1,6 @@
 ---
 title: "T03. SSL/TLSサーバーを立ち上げる"
-order: 44
+order: 45
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/ja/cookbook/t04-mtls.md

@@ -1,6 +1,6 @@
 ---
 title: "T04. mTLSを設定する"
-order: 45
+order: 46
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/ja/cookbook/t05-peer-cert.md

@@ -1,6 +1,6 @@
 ---
 title: "T05. サーバー側でピア証明書を参照する"
-order: 46
+order: 47
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/ja/cookbook/w01-websocket-echo.md

@@ -1,6 +1,6 @@
 ---
 title: "W01. WebSocketエコーサーバー/クライアントを実装する"
-order: 51
+order: 52
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/ja/cookbook/w02-websocket-ping.md

@@ -1,6 +1,6 @@
 ---
 title: "W02. ハートビートを設定する"
-order: 52
+order: 53
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/ja/cookbook/w03-websocket-close.md

@@ -1,6 +1,6 @@
 ---
 title: "W03. 接続クローズをハンドリングする"
-order: 53
+order: 54
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/ja/cookbook/w04-websocket-binary.md

@@ -1,6 +1,6 @@
 ---
 title: "W04. バイナリフレームを送受信する"
-order: 54
+order: 55
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/ja/cookbook/w05-websocket-tls.md

@@ -1,6 +1,6 @@
 ---
 title: "W05. wss接続でTLSを設定する"
-order: 55
+order: 56
 status: "draft"
 ---
 

+ 1 - 1
docs-src/pages/ja/cookbook/w06-websocket-timeouts.md

@@ -1,6 +1,6 @@
 ---
 title: "W06. タイムアウトを設定する"
-order: 56
+order: 57
 status: "draft"
 ---
 

+ 101 - 7
httplib.h

@@ -2107,6 +2107,17 @@ public:
   Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
   Server &Options(const std::string &pattern, Handler handler);
 
+  // Register a handler for an HTTP method outside the built-in set (e.g. the
+  // WebDAV methods from RFC 4918). Registering a method here is what makes the
+  // server accept it; an unregistered method is still rejected with 400.
+  // `method` must be a valid HTTP method token and must not be one of the
+  // built-in methods, which have their own registration functions above. A
+  // rejected registration makes is_valid() return false, so listen() fails.
+  Server &CustomRoute(const std::string &method, const std::string &pattern,
+                      Handler handler);
+  Server &CustomRoute(const std::string &method, const std::string &pattern,
+                      HandlerWithContentReader handler);
+
   Server &WebSocket(const std::string &pattern, WebSocketHandler handler);
   Server &WebSocket(const std::string &pattern, WebSocketHandler handler,
                     SubProtocolSelector sub_protocol_selector);
@@ -2226,9 +2237,21 @@ private:
       std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
                             HandlerWithContentReader>>;
 
+  // Both handler tables for one custom method live in a single entry, so that
+  // routing() needs only one map lookup per request to reach either of them.
+  struct CustomHandlerEntry {
+    Handlers handlers;
+    HandlersForContentReader handlers_for_content_reader;
+  };
+  using CustomHandlers = std::map<std::string, CustomHandlerEntry>;
+
   static std::unique_ptr<detail::MatcherBase>
   make_matcher(const std::string &pattern);
 
+  static const std::set<std::string> &builtin_methods();
+  CustomHandlerEntry *custom_entry_for_registration(const std::string &method);
+  const CustomHandlerEntry *find_custom_entry(const std::string &method) const;
+
   template <typename H>
   Server &add_handler(
       std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, H>> &handlers,
@@ -2292,6 +2315,10 @@ private:
   std::atomic<bool> is_running_{false};
   std::atomic<bool> is_decommissioned{false};
 
+  // Set when CustomRoute() refuses a registration. Written before listen(),
+  // read by is_valid() on the same thread, so it needs no synchronization.
+  bool has_invalid_registration_ = false;
+
   struct MountPointEntry {
     std::string mount_point;
     std::string base_dir;
@@ -2313,6 +2340,7 @@ private:
   Handlers delete_handlers_;
   HandlersForContentReader delete_handlers_for_content_reader_;
   Handlers options_handlers_;
+  CustomHandlers custom_handlers_;
 
   struct WebSocketHandlerEntry {
     std::unique_ptr<detail::MatcherBase> matcher;
@@ -12441,6 +12469,57 @@ inline Server &Server::Options(const std::string &pattern, Handler handler) {
   return add_handler(options_handlers_, pattern, std::move(handler));
 }
 
+inline const std::set<std::string> &Server::builtin_methods() {
+  thread_local const std::set<std::string> methods{
+      "GET",     "HEAD",    "POST",  "PUT",   "DELETE",
+      "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
+  return methods;
+}
+
+inline Server::CustomHandlerEntry *
+Server::custom_entry_for_registration(const std::string &method) {
+  // Built-in methods are refused for two different reasons. GET, HEAD, POST,
+  // PUT, DELETE, OPTIONS and PATCH are dispatched by the if/else chain in
+  // routing() before the custom tables are consulted, so a route registered
+  // for one of them could never fire. CONNECT, TRACE and PRI have no branch
+  // there and would be reachable, but they carry protocol-level meaning
+  // (tunnel setup, request echo, the HTTP/2 connection preface) that this
+  // library does not route.
+  if (!detail::fields::is_token(method) || builtin_methods().count(method)) {
+    output_error_log(Error::InvalidHTTPMethod, nullptr);
+    has_invalid_registration_ = true;
+    return nullptr;
+  }
+  return &custom_handlers_[method];
+}
+
+inline Server &Server::CustomRoute(const std::string &method,
+                                   const std::string &pattern,
+                                   Handler handler) {
+  auto *entry = custom_entry_for_registration(method);
+  if (!entry) { return *this; }
+  return add_handler(entry->handlers, pattern, std::move(handler));
+}
+
+inline Server &Server::CustomRoute(const std::string &method,
+                                   const std::string &pattern,
+                                   HandlerWithContentReader handler) {
+  auto *entry = custom_entry_for_registration(method);
+  if (!entry) { return *this; }
+  return add_handler(entry->handlers_for_content_reader, pattern,
+                     std::move(handler));
+}
+
+inline const Server::CustomHandlerEntry *
+Server::find_custom_entry(const std::string &method) const {
+  // find() alone would be correct here. The empty() check is what keeps the
+  // per-request cost off servers that never call CustomRoute(), which is the
+  // overwhelmingly common case; keep it rather than walking into the tree.
+  if (custom_handlers_.empty()) { return nullptr; }
+  auto it = custom_handlers_.find(method);
+  return it == custom_handlers_.end() ? nullptr : &it->second;
+}
+
 inline Server &Server::WebSocket(const std::string &pattern,
                                  WebSocketHandler handler) {
   websocket_handlers_.push_back(
@@ -12733,11 +12812,12 @@ inline bool Server::parse_request_line(const char *s, Request &req) const {
     if (count != 3) { return false; }
   }
 
-  thread_local const std::set<std::string> methods{
-      "GET",     "HEAD",    "POST",  "PUT",   "DELETE",
-      "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
+  // A method outside the built-in set is accepted only when a handler has been
+  // registered for it with CustomRoute().
+  const auto &methods = builtin_methods();
 
-  if (methods.find(req.method) == methods.end()) {
+  if (methods.find(req.method) == methods.end() &&
+      !find_custom_entry(req.method)) {
     output_error_log(Error::InvalidHTTPMethod, &req);
     return false;
   }
@@ -13372,7 +13452,14 @@ inline bool Server::routing(Request &req, Response &res, Stream &strm) {
     return true;
   }
 
-  if (detail::expect_content(req)) {
+  const auto *custom = find_custom_entry(req.method);
+
+  // The second clause mirrors what expect_content() does unconditionally for
+  // POST/PUT/PATCH/DELETE: a content reader route fires even when the request
+  // carries no body. Without it a body-less PROPFIND (RFC 4918 treats one as
+  // `allprop`) would skip its handler and fall through to 404.
+  if (detail::expect_content(req) ||
+      (custom && !custom->handlers_for_content_reader.empty())) {
     // Content reader handler
     {
       // Track whether the ContentReader was aborted due to the decompressed
@@ -13419,6 +13506,9 @@ inline bool Server::routing(Request &req, Response &res, Stream &strm) {
       } else if (req.method == "DELETE") {
         dispatched = dispatch_request_for_content_reader(
             req, res, std::move(reader), delete_handlers_for_content_reader_);
+      } else if (custom) {
+        dispatched = dispatch_request_for_content_reader(
+            req, res, std::move(reader), custom->handlers_for_content_reader);
       }
 
       if (dispatched) {
@@ -13455,6 +13545,8 @@ inline bool Server::routing(Request &req, Response &res, Stream &strm) {
     return dispatch_request(req, res, options_handlers_, strm);
   } else if (req.method == "PATCH") {
     return dispatch_request(req, res, patch_handlers_, strm);
+  } else if (custom) {
+    return dispatch_request(req, res, custom->handlers, strm);
   }
 
   res.status = StatusCode::BadRequest_400;
@@ -13972,7 +14064,7 @@ Server::process_request(Stream &strm, const std::string &remote_addr,
   return ret;
 }
 
-inline bool Server::is_valid() const { return true; }
+inline bool Server::is_valid() const { return !has_invalid_registration_; }
 
 inline bool Server::process_and_close_socket(socket_t sock) {
   std::string remote_addr;
@@ -17313,7 +17405,9 @@ inline SSLServer::~SSLServer() {
   if (ctx_) { tls::free_context(ctx_); }
 }
 
-inline bool SSLServer::is_valid() const { return ctx_ != nullptr; }
+inline bool SSLServer::is_valid() const {
+  return ctx_ != nullptr && Server::is_valid();
+}
 
 inline bool SSLServer::process_and_close_socket(socket_t sock) {
   using namespace tls;

+ 294 - 0
test/test.cc

@@ -3981,6 +3981,19 @@ TEST(BindServerTest, BindAndListenSeparatelySSL) {
   svr.stop();
 }
 
+// SSLServer::is_valid() overrides the base version, so it has to chain to it
+// or a rejected CustomRoute() registration would not stop the server binding.
+TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
+  SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
+                CLIENT_CA_CERT_DIR);
+  ASSERT_TRUE(svr.is_valid());
+
+  svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
+
+  EXPECT_FALSE(svr.is_valid());
+  EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
+}
+
 TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
   SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
                 nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
@@ -5206,6 +5219,38 @@ protected:
                  [&](const Request & /*req*/, Response &res) {
                    res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
                  })
+        .CustomRoute("PROPFIND", "/dav/:id",
+                     [&](const Request &req, Response &res) {
+                       res.set_header("x-body-size",
+                                      std::to_string(req.body.size()));
+                       res.set_header("x-matched-route", req.matched_route);
+                       res.set_header("x-dav-id", req.path_params.at("id"));
+                       res.status = StatusCode::MultiStatus_207;
+                       res.set_content(req.body, "application/xml");
+                     })
+        .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
+                     [&](const Request &req, Response &res) {
+                       res.set_header("x-dav-match", req.matches[1]);
+                       res.status = StatusCode::MultiStatus_207;
+                     })
+        .CustomRoute("MKCOL", "/dav-mkcol",
+                     [&](const Request &req, Response &res) {
+                       EXPECT_TRUE(req.body.empty());
+                       res.status = StatusCode::Created_201;
+                     })
+        .CustomRoute(
+            "REPORT", "/dav-report",
+            [&](const Request & /*req*/, Response &res,
+                const ContentReader &content_reader) {
+              std::string body;
+              content_reader([&](const char *data, size_t data_length) {
+                body.append(data, data_length);
+                return true;
+              });
+              res.set_header("x-body-size", std::to_string(body.size()));
+              res.status = StatusCode::MultiStatus_207;
+              res.set_content(body, "application/xml");
+            })
         .Get("/request-target",
              [&](const Request &req, Response & /*res*/) {
                EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
@@ -7994,6 +8039,176 @@ TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
   EXPECT_FALSE(cli_.is_socket_open());
 }
 
+TEST_F(ServerTest, CustomRouteReadsBody) {
+  const std::string xml =
+      R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
+
+  Request req;
+  req.method = "PROPFIND";
+  req.path = "/dav/dir";
+  req.set_header("Depth", "1");
+  req.body = xml;
+
+  auto res = cli_.send(req);
+
+  ASSERT_TRUE(res) << "Error: " << to_string(res.error());
+  EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
+  EXPECT_EQ(xml, res->body);
+  EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
+  EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
+}
+
+TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
+  Request req;
+  req.method = "PROPFIND";
+  req.path = "/dav/42";
+
+  auto res = cli_.send(req);
+
+  ASSERT_TRUE(res) << "Error: " << to_string(res.error());
+  EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
+  EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
+  EXPECT_EQ("42", res->get_header_value("x-dav-id"));
+}
+
+TEST_F(ServerTest, CustomRouteRegexPattern) {
+  Request req;
+  req.method = "PROPFIND";
+  req.path = "/dav-re/123";
+
+  auto res = cli_.send(req);
+
+  ASSERT_TRUE(res) << "Error: " << to_string(res.error());
+  EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
+  EXPECT_EQ("123", res->get_header_value("x-dav-match"));
+}
+
+TEST_F(ServerTest, CustomRouteWithoutBody) {
+  Request req;
+  req.method = "MKCOL";
+  req.path = "/dav-mkcol";
+
+  auto res = cli_.send(req);
+
+  ASSERT_TRUE(res) << "Error: " << to_string(res.error());
+  EXPECT_EQ(StatusCode::Created_201, res->status);
+}
+
+TEST_F(ServerTest, CustomRouteWithContentReader) {
+  const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
+
+  Request req;
+  req.method = "REPORT";
+  req.path = "/dav-report";
+  req.body = xml;
+
+  auto res = cli_.send(req);
+
+  ASSERT_TRUE(res) << "Error: " << to_string(res.error());
+  EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
+  EXPECT_EQ(xml, res->body);
+}
+
+// A content reader route must fire even when the request carries no body,
+// the way the built-in Delete(pattern, HandlerWithContentReader) does.
+// Without that, a body-less PROPFIND-style request would fall through to 404.
+TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
+  Request req;
+  req.method = "REPORT";
+  req.path = "/dav-report";
+
+  auto res = cli_.send(req);
+
+  ASSERT_TRUE(res) << "Error: " << to_string(res.error());
+  EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
+  EXPECT_EQ("0", res->get_header_value("x-body-size"));
+}
+
+TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
+  Request req;
+  req.method = "PROPFIND";
+  req.path = "/not-dav";
+
+  auto res = cli_.send(req);
+
+  ASSERT_TRUE(res) << "Error: " << to_string(res.error());
+  EXPECT_EQ(StatusCode::NotFound_404, res->status);
+}
+
+TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
+  Request req;
+  req.method = "UNLOCK";
+  req.path = "/dav/dir";
+
+  cli_.set_keep_alive(true);
+  auto res = cli_.send(req);
+
+  ASSERT_TRUE(res) << "Error: " << to_string(res.error());
+  EXPECT_EQ(StatusCode::BadRequest_400, res->status);
+  EXPECT_EQ("close", res->get_header_value("Connection"));
+  EXPECT_FALSE(cli_.is_socket_open());
+}
+
+TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
+  // The mount point serves this path, but only for GET and HEAD.
+  auto get_res = cli_.Get("/dir/index.html");
+  ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
+  ASSERT_EQ(StatusCode::OK_200, get_res->status);
+
+  Request req;
+  req.method = "PROPFIND";
+  req.path = "/dir/index.html";
+
+  auto res = cli_.send(req);
+
+  ASSERT_TRUE(res) << "Error: " << to_string(res.error());
+  EXPECT_EQ(StatusCode::NotFound_404, res->status);
+}
+
+TEST_F(ServerTest, CustomRouteKeepAlive) {
+  const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
+
+  cli_.set_keep_alive(true);
+
+  for (auto i = 0; i < 2; i++) {
+    Request req;
+    req.method = "PROPFIND";
+    req.path = "/dav/dir";
+    req.body = xml;
+
+    auto res = cli_.send(req);
+
+    ASSERT_TRUE(res) << "Error: " << to_string(res.error());
+    EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
+    EXPECT_EQ(xml, res->body);
+    EXPECT_TRUE(cli_.is_socket_open());
+  }
+
+  // A built-in method must still be served on the same connection.
+  cli_.set_keep_alive(false);
+
+  auto res = cli_.Get("/hi");
+  ASSERT_TRUE(res) << "Error: " << to_string(res.error());
+  EXPECT_EQ(StatusCode::OK_200, res->status);
+  EXPECT_EQ("close", res->get_header_value("Connection"));
+}
+
+TEST_F(ServerTest, CustomRouteExpect100Continue) {
+  const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
+
+  Request req;
+  req.method = "PROPFIND";
+  req.path = "/dav/dir";
+  req.set_header("Expect", "100-continue");
+  req.body = xml;
+
+  auto res = cli_.send(req);
+
+  ASSERT_TRUE(res) << "Error: " << to_string(res.error());
+  EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
+  EXPECT_EQ(xml, res->body);
+}
+
 TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
 
 #ifdef CPPHTTPLIB_ZLIB_SUPPORT
@@ -8964,6 +9179,10 @@ static void test_raw_request(const std::string &req,
           [&](const Request & /*req*/, Response &res) {
             res.set_content("ok", "text/plain");
           });
+  svr.CustomRoute("PROPFIND", "/dav",
+                  [&](const Request & /*req*/, Response &res) {
+                    res.status = StatusCode::MultiStatus_207;
+                  });
 
   // Server read timeout must be longer than the client read timeout for the
   // bug to reproduce, probably to force the server to process a request
@@ -9120,6 +9339,81 @@ TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
   EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
 }
 
+// A custom method with neither Content-Length nor Transfer-Encoding must be
+// answered right away rather than blocking on a read that waits for EOF.
+TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
+  std::string out;
+  test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
+  EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
+}
+
+TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
+  const char *methods[] = {"GET",     "HEAD",    "POST",  "PUT",   "DELETE",
+                           "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
+
+  for (const auto *method : methods) {
+    Server svr;
+    svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
+
+    EXPECT_FALSE(svr.is_valid()) << method;
+    EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
+  }
+}
+
+TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
+  const char *methods[] = {"",          "PRO PFIND", "PROP\tFIND", "PROP/FIND",
+                           "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
+
+  for (const auto *method : methods) {
+    Server svr;
+    svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
+
+    EXPECT_FALSE(svr.is_valid()) << method;
+  }
+}
+
+TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
+  const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
+                           "COPY",     "MOVE",      "LOCK",
+                           "UNLOCK",   "REPORT",    "SUBSCRIBE"};
+
+  Server svr;
+  for (const auto *method : methods) {
+    svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
+  }
+
+  EXPECT_TRUE(svr.is_valid());
+}
+
+TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
+  Server svr;
+  svr.CustomRoute("POST", "/x",
+                  [](const Request &, Response &, const ContentReader &) {});
+
+  EXPECT_FALSE(svr.is_valid());
+}
+
+TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
+  Server svr;
+  svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
+  svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
+  svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
+
+  EXPECT_FALSE(svr.is_valid());
+}
+
+TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
+  Server svr;
+
+  auto captured = Error::Success;
+  svr.set_error_logger(
+      [&](const Error &err, const Request * /*req*/) { captured = err; });
+
+  svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
+
+  EXPECT_EQ(Error::InvalidHTTPMethod, captured);
+}
+
 TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
   std::string out;
   std::string request(