1 /*
2  * Copyright (c) 2014-2016 DeNA Co., Ltd., Kazuho Oku, Fastly, Inc.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a copy
5  * of this software and associated documentation files (the "Software"), to
6  * deal in the Software without restriction, including without limitation the
7  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
8  * sell copies of the Software, and to permit persons to whom the Software is
9  * furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
20  * IN THE SOFTWARE.
21  */
22 #ifndef h2o_h
23 #define h2o_h
24 
25 #ifdef __cplusplus
26 extern "C" {
27 #endif
28 
29 #include <assert.h>
30 #include <stddef.h>
31 #include <stdint.h>
32 #include <string.h>
33 #include <stdlib.h>
34 #include <sys/time.h>
35 #include <sys/socket.h>
36 #include <time.h>
37 #include <unistd.h>
38 #include <openssl/ssl.h>
39 #include "h2o/filecache.h"
40 #include "h2o/header.h"
41 #include "h2o/hostinfo.h"
42 #include "h2o/memcached.h"
43 #include "h2o/redis.h"
44 #include "h2o/linklist.h"
45 #include "h2o/httpclient.h"
46 #include "h2o/memory.h"
47 #include "h2o/multithread.h"
48 #include "h2o/rand.h"
49 #include "h2o/socket.h"
50 #include "h2o/string_.h"
51 #include "h2o/time_.h"
52 #include "h2o/token.h"
53 #include "h2o/url.h"
54 #include "h2o/version.h"
55 #include "h2o/balancer.h"
56 #include "h2o/http2_common.h"
57 #include "h2o/send_state.h"
58 
59 #ifndef H2O_USE_BROTLI
60 /* disabled for all but the standalone server, since the encoder is written in C++ */
61 #define H2O_USE_BROTLI 0
62 #endif
63 
64 #ifndef H2O_MAX_HEADERS
65 #define H2O_MAX_HEADERS 100
66 #endif
67 #ifndef H2O_MAX_REQLEN
68 #define H2O_MAX_REQLEN (8192 + 4096 * (H2O_MAX_HEADERS))
69 #endif
70 
71 #ifndef H2O_SOMAXCONN
72 /* simply use a large value, and let the kernel clip it to the internal max */
73 #define H2O_SOMAXCONN 65535
74 #endif
75 
76 #define H2O_HTTP2_MIN_STREAM_WINDOW_SIZE 65535
77 #define H2O_HTTP2_MAX_STREAM_WINDOW_SIZE 16777216
78 
79 #define H2O_DEFAULT_MAX_REQUEST_ENTITY_SIZE (1024 * 1024 * 1024)
80 #define H2O_DEFAULT_MAX_DELEGATIONS 5
81 #define H2O_DEFAULT_HANDSHAKE_TIMEOUT_IN_SECS 10
82 #define H2O_DEFAULT_HANDSHAKE_TIMEOUT (H2O_DEFAULT_HANDSHAKE_TIMEOUT_IN_SECS * 1000)
83 #define H2O_DEFAULT_HTTP1_REQ_TIMEOUT_IN_SECS 10
84 #define H2O_DEFAULT_HTTP1_REQ_TIMEOUT (H2O_DEFAULT_HTTP1_REQ_TIMEOUT_IN_SECS * 1000)
85 #define H2O_DEFAULT_HTTP1_REQ_IO_TIMEOUT_IN_SECS 5
86 #define H2O_DEFAULT_HTTP1_REQ_IO_TIMEOUT (H2O_DEFAULT_HTTP1_REQ_IO_TIMEOUT_IN_SECS * 1000)
87 #define H2O_DEFAULT_HTTP1_UPGRADE_TO_HTTP2 1
88 #define H2O_DEFAULT_HTTP2_IDLE_TIMEOUT_IN_SECS 10
89 #define H2O_DEFAULT_HTTP2_IDLE_TIMEOUT (H2O_DEFAULT_HTTP2_IDLE_TIMEOUT_IN_SECS * 1000)
90 #define H2O_DEFAULT_HTTP2_GRACEFUL_SHUTDOWN_TIMEOUT_IN_SECS 0 /* no timeout */
91 #define H2O_DEFAULT_HTTP2_GRACEFUL_SHUTDOWN_TIMEOUT (H2O_DEFAULT_HTTP2_GRACEFUL_SHUTDOWN_TIMEOUT_IN_SECS * 1000)
92 #define H2O_DEFAULT_HTTP2_ACTIVE_STREAM_WINDOW_SIZE H2O_HTTP2_MAX_STREAM_WINDOW_SIZE
93 #define H2O_DEFAULT_HTTP3_ACTIVE_STREAM_WINDOW_SIZE H2O_DEFAULT_HTTP2_ACTIVE_STREAM_WINDOW_SIZE
94 #define H2O_DEFAULT_PROXY_IO_TIMEOUT_IN_SECS 30
95 #define H2O_DEFAULT_PROXY_IO_TIMEOUT (H2O_DEFAULT_PROXY_IO_TIMEOUT_IN_SECS * 1000)
96 #define H2O_DEFAULT_HAPPY_EYEBALLS_NAME_RESOLUTION_DELAY 50
97 #define H2O_DEFAULT_HAPPY_EYEBALLS_CONNECTION_ATTEMPT_DELAY 250
98 #define H2O_DEFAULT_PROXY_SSL_SESSION_CACHE_CAPACITY 4096
99 #define H2O_DEFAULT_PROXY_SSL_SESSION_CACHE_DURATION 86400000 /* 24 hours */
100 #define H2O_DEFAULT_PROXY_HTTP2_MAX_CONCURRENT_STREAMS 100
101 
102 typedef struct st_h2o_conn_t h2o_conn_t;
103 typedef struct st_h2o_context_t h2o_context_t;
104 typedef struct st_h2o_req_t h2o_req_t;
105 typedef struct st_h2o_ostream_t h2o_ostream_t;
106 typedef struct st_h2o_configurator_command_t h2o_configurator_command_t;
107 typedef struct st_h2o_configurator_t h2o_configurator_t;
108 typedef struct st_h2o_pathconf_t h2o_pathconf_t;
109 typedef struct st_h2o_hostconf_t h2o_hostconf_t;
110 typedef struct st_h2o_globalconf_t h2o_globalconf_t;
111 typedef struct st_h2o_mimemap_t h2o_mimemap_t;
112 typedef struct st_h2o_logconf_t h2o_logconf_t;
113 typedef struct st_h2o_headers_command_t h2o_headers_command_t;
114 
115 /**
116  * basic structure of a handler (an object that MAY generate a response)
117  * The handlers should register themselves to h2o_context_t::handlers.
118  */
119 typedef struct st_h2o_handler_t {
120     size_t _config_slot;
121     void (*on_context_init)(struct st_h2o_handler_t *self, h2o_context_t *ctx);
122     void (*on_context_dispose)(struct st_h2o_handler_t *self, h2o_context_t *ctx);
123     void (*dispose)(struct st_h2o_handler_t *self);
124     int (*on_req)(struct st_h2o_handler_t *self, h2o_req_t *req);
125     /**
126      * If the flag is set, protocol handler may invoke the request handler before receiving the end of the request body. The request
127      * handler can determine if the protocol handler has actually done so by checking if `req->proceed_req` is set to non-NULL.
128      * In such case, the handler should replace `req->write_req.cb` (and ctx) with its own callback to receive the request body
129      * bypassing the buffer of the protocol handler. Parts of the request body being received before the handler replacing the
130      * callback is accessible via `req->entity`.
131      * The request handler can delay replacing the callback to a later moment. In such case, the handler can determine if
132      * `req->entity` already contains a complete request body by checking if `req->proceed_req` is NULL.
133      */
134     unsigned supports_request_streaming : 1;
135 } h2o_handler_t;
136 
137 /**
138  * basic structure of a filter (an object that MAY modify a response)
139  * The filters should register themselves to h2o_context_t::filters.
140  */
141 typedef struct st_h2o_filter_t {
142     size_t _config_slot;
143     void (*on_context_init)(struct st_h2o_filter_t *self, h2o_context_t *ctx);
144     void (*on_context_dispose)(struct st_h2o_filter_t *self, h2o_context_t *ctx);
145     void (*dispose)(struct st_h2o_filter_t *self);
146     void (*on_setup_ostream)(struct st_h2o_filter_t *self, h2o_req_t *req, h2o_ostream_t **slot);
147     void (*on_informational)(struct st_h2o_filter_t *self, h2o_req_t *req);
148 } h2o_filter_t;
149 
150 /**
151  * basic structure of a logger (an object that MAY log a request)
152  * The loggers should register themselves to h2o_context_t::loggers.
153  */
154 typedef struct st_h2o_logger_t {
155     size_t _config_slot;
156     void (*on_context_init)(struct st_h2o_logger_t *self, h2o_context_t *ctx);
157     void (*on_context_dispose)(struct st_h2o_logger_t *self, h2o_context_t *ctx);
158     void (*dispose)(struct st_h2o_logger_t *self);
159     void (*log_access)(struct st_h2o_logger_t *self, h2o_req_t *req);
160 } h2o_logger_t;
161 
162 /**
163  * contains stringified representations of a timestamp
164  */
165 typedef struct st_h2o_timestamp_string_t {
166     char rfc1123[H2O_TIMESTR_RFC1123_LEN + 1];
167     char log[H2O_TIMESTR_LOG_LEN + 1];
168 } h2o_timestamp_string_t;
169 
170 /**
171  * a timestamp.
172  * Applications should call h2o_get_timestamp to obtain a timestamp.
173  */
174 typedef struct st_h2o_timestamp_t {
175     struct timeval at;
176     h2o_timestamp_string_t *str;
177 } h2o_timestamp_t;
178 
179 typedef struct st_h2o_casper_conf_t {
180     /**
181      * capacity bits (0 to disable casper)
182      */
183     unsigned capacity_bits;
184     /**
185      * whether if all type of files should be tracked (or only the blocking assets)
186      */
187     int track_all_types;
188 } h2o_casper_conf_t;
189 
190 typedef struct st_h2o_envconf_t {
191     /**
192      * parent
193      */
194     struct st_h2o_envconf_t *parent;
195     /**
196      * list of names to be unset
197      */
198     h2o_iovec_vector_t unsets;
199     /**
200      * list of name-value pairs to be set
201      */
202     h2o_iovec_vector_t sets;
203 } h2o_envconf_t;
204 
205 struct st_h2o_pathconf_t {
206     /**
207      * globalconf to which the pathconf belongs
208      */
209     h2o_globalconf_t *global;
210     /**
211      * pathname in lower case, may or may not have "/" at last, NULL terminated, or is {NULL,0} if is fallback or extension-level
212      */
213     h2o_iovec_t path;
214     /**
215      * list of handlers
216      */
217     H2O_VECTOR(h2o_handler_t *) handlers;
218     /**
219      * list of filters to be applied unless when processing a subrequest.
220      * The address of the list is set in `req->filters` and used when processing a request.
221      */
222     H2O_VECTOR(h2o_filter_t *) _filters;
223     /**
224      * list of loggers to be applied unless when processing a subrequest.
225      * The address of the list is set in `req->loggers` and used when processing a request.
226      */
227     H2O_VECTOR(h2o_logger_t *) _loggers;
228     /**
229      * mimemap
230      */
231     h2o_mimemap_t *mimemap;
232     /**
233      * env
234      */
235     h2o_envconf_t *env;
236     /**
237      * error-log
238      */
239     struct {
240         /**
241          * if request-level errors should be emitted to stderr
242          */
243         unsigned emit_request_errors : 1;
244     } error_log;
245 };
246 
247 struct st_h2o_hostconf_t {
248     /**
249      * reverse reference to the global configuration
250      */
251     h2o_globalconf_t *global;
252     /**
253      * host and port
254      */
255     struct {
256         /**
257          * host and port (in lower-case; base is NULL-terminated)
258          */
259         h2o_iovec_t hostport;
260         /**
261          *  in lower-case; base is NULL-terminated
262          */
263         h2o_iovec_t host;
264         /**
265          * port number (or 65535 if default)
266          */
267         uint16_t port;
268     } authority;
269     /**
270      * A boolean indicating that this hostconf can only be used for a request with the ":authority" pseudo-header field / "Host"
271      * that matches hostport. When strict_match is false, then this hostconf is eligible for use as the fallback hostconf for a
272      * request that does not match any applicable hostconf.
273      */
274     uint8_t strict_match;
275     /**
276      * list of path configurations
277      */
278     H2O_VECTOR(h2o_pathconf_t *) paths;
279     /**
280      * catch-all path configuration
281      */
282     h2o_pathconf_t fallback_path;
283     /**
284      * mimemap
285      */
286     h2o_mimemap_t *mimemap;
287     /**
288      * http2
289      */
290     struct {
291         /**
292          * whether if blocking assets being pulled should be given highest priority in case of clients that do not implement
293          * dependency-based prioritization
294          */
295         unsigned reprioritize_blocking_assets : 1;
296         /**
297          * if server push should be used
298          */
299         unsigned push_preload : 1;
300         /**
301          * if cross origin pushes should be authorized
302          */
303         unsigned allow_cross_origin_push : 1;
304         /**
305          * casper settings
306          */
307         h2o_casper_conf_t casper;
308     } http2;
309 };
310 
311 typedef struct st_h2o_protocol_callbacks_t {
312     void (*request_shutdown)(h2o_context_t *ctx);
313     int (*foreach_request)(h2o_context_t *ctx, int (*cb)(h2o_req_t *req, void *cbdata), void *cbdata);
314 } h2o_protocol_callbacks_t;
315 
316 typedef h2o_iovec_t (*final_status_handler_cb)(void *ctx, h2o_globalconf_t *gconf, h2o_req_t *req);
317 typedef const struct st_h2o_status_handler_t {
318     h2o_iovec_t name;
319     h2o_iovec_t (*final)(void *ctx, h2o_globalconf_t *gconf, h2o_req_t *req); /* mandatory, will be passed the optional context */
320     void *(*init)(void); /* optional callback, allocates a context that will be passed to per_thread() */
321     void (*per_thread)(void *priv, h2o_context_t *ctx); /* optional callback, will be called for each thread */
322 } h2o_status_handler_t;
323 
324 typedef H2O_VECTOR(h2o_status_handler_t *) h2o_status_callbacks_t;
325 
326 typedef enum h2o_send_informational_mode {
327     H2O_SEND_INFORMATIONAL_MODE_EXCEPT_H1,
328     H2O_SEND_INFORMATIONAL_MODE_NONE,
329     H2O_SEND_INFORMATIONAL_MODE_ALL
330 } h2o_send_informational_mode_t;
331 
332 struct st_h2o_globalconf_t {
333     /**
334      * a NULL-terminated list of host contexts (h2o_hostconf_t)
335      */
336     h2o_hostconf_t **hosts;
337     /**
338      * The hostconf that will be used when none of the hostconfs for the listener match the request and they all have strict-match:
339      * ON.
340      */
341     h2o_hostconf_t *fallback_host;
342     /**
343      * list of configurators
344      */
345     h2o_linklist_t configurators;
346     /**
347      * name of the server (not the hostname)
348      */
349     h2o_iovec_t server_name;
350     /**
351      * formated "sf-token" or "sf-string" for the proxy-status header
352      */
353     h2o_iovec_t proxy_status_identity;
354     /**
355      * maximum size of the accepted request entity (e.g. POST data)
356      */
357     size_t max_request_entity_size;
358     /**
359      * maximum count for delegations
360      */
361     unsigned max_delegations;
362     /**
363      * setuid user (or NULL)
364      */
365     char *user;
366     /**
367      * sets up the h2o_return map if true.
368      */
369     int usdt_selective_tracing;
370 
371     /**
372      * SSL handshake timeout
373      */
374     uint64_t handshake_timeout;
375 
376     struct {
377         /**
378          * request timeout (in milliseconds)
379          */
380         uint64_t req_timeout;
381         /**
382          * request io timeout (in milliseconds)
383          */
384         uint64_t req_io_timeout;
385         /**
386          * a boolean value indicating whether or not to upgrade to HTTP/2
387          */
388         int upgrade_to_http2;
389         /**
390          * list of callbacks
391          */
392         h2o_protocol_callbacks_t callbacks;
393     } http1;
394 
395     struct {
396         /**
397          * idle timeout (in milliseconds)
398          */
399         uint64_t idle_timeout;
400         /**
401          * graceful shutdown timeout (in milliseconds)
402          */
403         uint64_t graceful_shutdown_timeout;
404         /**
405          * maximum number of HTTP2 requests (per connection) to be handled simultaneously internally.
406          * H2O accepts at most 256 requests over HTTP/2, but internally limits the number of in-flight requests to the value
407          * specified by this property in order to limit the resources allocated to a single connection.
408          */
409         size_t max_concurrent_requests_per_connection;
410         /**
411          * maximum number of HTTP2 streaming requests (per connection) to be handled simultaneously internally.
412          */
413         size_t max_concurrent_streaming_requests_per_connection;
414         /**
415          * maximum nuber of streams (per connection) to be allowed in IDLE / CLOSED state (used for tracking dependencies).
416          */
417         size_t max_streams_for_priority;
418         /**
419          * size of the stream-level flow control window (once it becomes active)
420          */
421         uint32_t active_stream_window_size;
422         /**
423          * conditions for latency optimization
424          */
425         h2o_socket_latency_optimization_conditions_t latency_optimization;
426         /**
427          * list of callbacks
428          */
429         h2o_protocol_callbacks_t callbacks;
430         /* */
431         h2o_iovec_t origin_frame;
432     } http2;
433 
434     struct {
435         /**
436          * idle timeout (in milliseconds)
437          */
438         uint64_t idle_timeout;
439         /**
440          * graceful shutdown timeout (in milliseconds)
441          */
442         uint64_t graceful_shutdown_timeout;
443         /**
444          * receive window size of the unblocked request stream
445          */
446         uint32_t active_stream_window_size;
447         /**
448          * See quicly_context_t::ack_frequency
449          */
450         uint16_t ack_frequency;
451         /**
452          * a boolean indicating if the delayed ack extension should be used (default true)
453          */
454         uint8_t allow_delayed_ack : 1;
455         /**
456          * a boolean indicating if UDP GSO should be used when possible
457          */
458         uint8_t use_gso : 1;
459         /**
460          * the callbacks
461          */
462         h2o_protocol_callbacks_t callbacks;
463     } http3;
464 
465     struct {
466         /**
467          * io timeout (in milliseconds)
468          */
469         uint64_t io_timeout;
470         /**
471          * io timeout (in milliseconds)
472          */
473         uint64_t connect_timeout;
474         /**
475          * io timeout (in milliseconds)
476          */
477         uint64_t first_byte_timeout;
478         /**
479          * keepalive timeout (in milliseconds)
480          */
481         uint64_t keepalive_timeout;
482         /**
483          * a boolean flag if set to true, instructs the proxy to close the frontend h1 connection on behalf of the upstream
484          */
485         unsigned forward_close_connection : 1;
486         /**
487          * a boolean flag if set to true, instructs the proxy to preserve the x-forwarded-proto header passed by the client
488          */
489         unsigned preserve_x_forwarded_proto : 1;
490         /**
491          * a boolean flag if set to true, instructs the proxy to preserve the server header passed by the origin
492          */
493         unsigned preserve_server_header : 1;
494         /**
495          * a boolean flag if set to true, instructs the proxy to emit x-forwarded-proto and x-forwarded-for headers
496          */
497         unsigned emit_x_forwarded_headers : 1;
498         /**
499          * a boolean flag if set to true, instructs the proxy to emit a via header
500          */
501         unsigned emit_via_header : 1;
502         /**
503          * a boolean flag if set to true, instructs the proxy to emit a date header, if it's missing from the upstream response
504          */
505         unsigned emit_missing_date_header : 1;
506         /**
507          * maximum size to buffer for the response
508          */
509         size_t max_buffer_size;
510 
511         struct {
512             uint32_t max_concurrent_streams;
513         } http2;
514 
515         /**
516          * See the documentation of `h2o_httpclient_t::protocol_selector.ratio`.
517          */
518         struct {
519             int8_t http2;
520             int8_t http3;
521         } protocol_ratio;
522 
523         /**
524          * global socketpool
525          */
526         h2o_socketpool_t global_socketpool;
527     } proxy;
528 
529     /**
530      * enum indicating to what clients h2o sends 1xx response
531      */
532     h2o_send_informational_mode_t send_informational_mode;
533 
534     /**
535      * mimemap
536      */
537     h2o_mimemap_t *mimemap;
538 
539     /**
540      * filecache
541      */
542     struct {
543         /* capacity of the filecache */
544         size_t capacity;
545     } filecache;
546 
547     /* status */
548     h2o_status_callbacks_t statuses;
549 
550     size_t _num_config_slots;
551 };
552 
553 enum {
554     H2O_COMPRESS_HINT_AUTO = 0,    /* default: let h2o negociate compression based on the configuration */
555     H2O_COMPRESS_HINT_DISABLE,     /* compression was explicitly disabled for this request */
556     H2O_COMPRESS_HINT_ENABLE,      /* compression was explicitly enabled for this request */
557     H2O_COMPRESS_HINT_ENABLE_GZIP, /* compression was explicitly enabled for this request, asking for gzip */
558     H2O_COMPRESS_HINT_ENABLE_BR,   /* compression was explicitly enabled for this request, asking for br */
559 };
560 
561 /**
562  * holds various attributes related to the mime-type
563  */
564 typedef struct st_h2o_mime_attributes_t {
565     /**
566      * whether if the content can be compressed by using gzip
567      */
568     char is_compressible;
569     /**
570      * how the resource should be prioritized
571      */
572     enum { H2O_MIME_ATTRIBUTE_PRIORITY_NORMAL = 0, H2O_MIME_ATTRIBUTE_PRIORITY_HIGHEST } priority;
573 } h2o_mime_attributes_t;
574 
575 extern h2o_mime_attributes_t h2o_mime_attributes_as_is;
576 
577 /**
578  * represents either a mime-type (and associated info), or contains pathinfo in case of a dynamic type (e.g. .php files)
579  */
580 typedef struct st_h2o_mimemap_type_t {
581     enum { H2O_MIMEMAP_TYPE_MIMETYPE = 0, H2O_MIMEMAP_TYPE_DYNAMIC = 1 } type;
582     union {
583         struct {
584             h2o_iovec_t mimetype;
585             h2o_mime_attributes_t attr;
586         };
587         struct {
588             h2o_pathconf_t pathconf;
589         } dynamic;
590     } data;
591 } h2o_mimemap_type_t;
592 
593 enum {
594     /* http1 protocol errors */
595     H2O_STATUS_ERROR_400 = 0,
596     H2O_STATUS_ERROR_403,
597     H2O_STATUS_ERROR_404,
598     H2O_STATUS_ERROR_405,
599     H2O_STATUS_ERROR_413,
600     H2O_STATUS_ERROR_416,
601     H2O_STATUS_ERROR_417,
602     H2O_STATUS_ERROR_500,
603     H2O_STATUS_ERROR_502,
604     H2O_STATUS_ERROR_503,
605     H2O_STATUS_ERROR_MAX,
606 };
607 
608 /**
609  * holds various data related to the context
610  */
611 typedef struct st_h2o_context_storage_item_t {
612     void (*dispose)(void *data);
613     void *data;
614 } h2o_context_storage_item_t;
615 
616 typedef H2O_VECTOR(h2o_context_storage_item_t) h2o_context_storage_t;
617 
618 /**
619  * context of the http server.
620  */
621 struct st_h2o_context_t {
622     /**
623      * points to the loop (either uv_loop_t or h2o_evloop_t, depending on the value of H2O_USE_LIBUV)
624      */
625     h2o_loop_t *loop;
626     /**
627      * pointer to the global configuration
628      */
629     h2o_globalconf_t *globalconf;
630     /**
631      * queue for receiving messages from other contexts
632      */
633     h2o_multithread_queue_t *queue;
634     /**
635      * receivers
636      */
637     struct {
638         h2o_multithread_receiver_t hostinfo_getaddr;
639     } receivers;
640     /**
641      * open file cache
642      */
643     h2o_filecache_t *filecache;
644     /**
645      * context scope storage for general use
646      */
647     h2o_context_storage_t storage;
648     /**
649      * flag indicating if shutdown has been requested
650      */
651     int shutdown_requested;
652 
653     struct {
654         /**
655          * link-list of h2o_http1_conn_t
656          */
657         h2o_linklist_t _conns;
658         struct {
659             uint64_t request_timeouts;
660             uint64_t request_io_timeouts;
661         } events;
662     } http1;
663 
664     struct {
665         /**
666          * link-list of h2o_http2_conn_t
667          */
668         h2o_linklist_t _conns;
669         /**
670          * timeout entry used for graceful shutdown
671          */
672         h2o_timer_t _graceful_shutdown_timeout;
673         struct {
674             /**
675              * counter for http2 errors internally emitted by h2o
676              */
677             uint64_t protocol_level_errors[H2O_HTTP2_ERROR_MAX];
678             /**
679              * premature close on read
680              */
681             uint64_t read_closed;
682             /**
683              * premature close on write
684              */
685             uint64_t write_closed;
686             /**
687              * counter for http2 idle timeouts
688              */
689             uint64_t idle_timeouts;
690             /**
691              * streaming request counter
692              */
693             uint64_t streaming_requests;
694         } events;
695     } http2;
696 
697     struct {
698         /**
699          * link-list of h2o_http3_server_conn_t
700          */
701         h2o_linklist_t _conns;
702         /**
703          * timeout entry used for graceful shutdown
704          */
705         h2o_timer_t _graceful_shutdown_timeout;
706         struct {
707             /**
708              * number of packets forwarded to another node in a cluster
709              */
710             uint64_t packet_forwarded;
711             /**
712              * number of forwarded packets received from another node in a cluster
713              */
714             uint64_t forwarded_packet_received;
715         } events;
716     } http3;
717 
718     struct {
719         /**
720          * the default client context for proxy
721          */
722         h2o_httpclient_ctx_t client_ctx;
723         /**
724          * the default connection pool for proxy
725          */
726         h2o_httpclient_connection_pool_t connpool;
727     } proxy;
728 
729     struct {
730         /**
731          * counter for SSL errors
732          */
733         uint64_t errors;
734         /**
735          * counter for selected ALPN protocols
736          */
737         uint64_t alpn_h1;
738         uint64_t alpn_h2;
739         /**
740          * counter for handshakes
741          */
742         uint64_t handshake_full;
743         uint64_t handshake_resume;
744         /**
745          * summations of handshake latency in microsecond
746          */
747         uint64_t handshake_accum_time_full;
748         uint64_t handshake_accum_time_resume;
749     } ssl;
750 
751     /**
752      * aggregated quic stats
753      */
754     h2o_quic_stats_t quic_stats;
755 
756     /**
757      * pointer to per-module configs
758      */
759     void **_module_configs;
760 
761     struct {
762         struct timeval tv_at;
763         h2o_timestamp_string_t *value;
764     } _timestamp_cache;
765 
766     /**
767      * counter for http1 error status internally emitted by h2o
768      */
769     uint64_t emitted_error_status[H2O_STATUS_ERROR_MAX];
770 
771     H2O_VECTOR(h2o_pathconf_t *) _pathconfs_inited;
772 };
773 
774 /**
775  * an object that generates a response.
776  * The object is typically constructed by handlers calling the h2o_start_response function.
777  */
778 typedef struct st_h2o_generator_t {
779     /**
780      * called by the core to request new data to be pushed via the h2o_send function.
781      */
782     void (*proceed)(struct st_h2o_generator_t *self, h2o_req_t *req);
783     /**
784      * called by the core when there is a need to terminate the response abruptly
785      */
786     void (*stop)(struct st_h2o_generator_t *self, h2o_req_t *req);
787 } h2o_generator_t;
788 
789 /**
790  * the maximum size of sendvec when a pull (i.e. non-raw) vector is used. Note also that bufcnt must be set to one when a pull mode
791  * vector is used.
792  */
793 #define H2O_PULL_SENDVEC_MAX_SIZE 65536
794 
795 typedef struct st_h2o_sendvec_t h2o_sendvec_t;
796 
797 typedef struct st_h2o_sendvec_callbacks_t {
798     /**
799      * optional callback used to serialize the bytes held by the vector. Returns if the operation succeeded. When false is returned,
800      * the generator is considered as been error-closed by itself.  If the callback is NULL, the data is pre-flattened and available
801      * in `h2o_sendvec_t::raw`.
802      */
803     int (*flatten)(h2o_sendvec_t *vec, h2o_req_t *req, h2o_iovec_t dst, size_t off);
804     /**
805      * optional callback that can be used to retain the buffer after flattening all data. This allows H3 to re-flatten data upon
806      * retransmission. Increments the reference counter if `is_incr` is set to true, otherwise the counter is decremented.
807      */
808     void (*update_refcnt)(h2o_sendvec_t *vec, h2o_req_t *req, int is_incr);
809 } h2o_sendvec_callbacks_t;
810 
811 /**
812  * send vector. Unlike an ordinary `h2o_iovec_t`, the vector has a callback that allows the sender to delay the flattening of data
813  * until it becomes necessary.
814  */
815 struct st_h2o_sendvec_t {
816     /**
817      *
818      */
819     const h2o_sendvec_callbacks_t *callbacks;
820     /**
821      * size of the vector
822      */
823     size_t len;
824     /**
825      *
826      */
827     union {
828         char *raw;
829         uint64_t cb_arg[2];
830     };
831 };
832 
833 /**
834  * an output stream that may alter the output.
835  * The object is typically constructed by filters calling the h2o_prepend_ostream function.
836  */
837 struct st_h2o_ostream_t {
838     /**
839      * points to the next output stream
840      */
841     struct st_h2o_ostream_t *next;
842     /**
843      * called by the core to send output.
844      * Intermediary output streams should process the given output and call the h2o_ostream_send_next function if any data can be
845      * sent.
846      */
847     void (*do_send)(struct st_h2o_ostream_t *self, h2o_req_t *req, h2o_sendvec_t *bufs, size_t bufcnt, h2o_send_state_t state);
848     /**
849      * called by the core when there is a need to terminate the response abruptly
850      */
851     void (*stop)(struct st_h2o_ostream_t *self, h2o_req_t *req);
852     /**
853      * called by the core via h2o_send_informational
854      */
855     void (*send_informational)(struct st_h2o_ostream_t *self, h2o_req_t *req);
856 };
857 
858 /**
859  * a HTTP response
860  */
861 typedef struct st_h2o_res_t {
862     /**
863      * status code
864      */
865     int status;
866     /**
867      * reason phrase
868      */
869     const char *reason;
870     /**
871      * length of the content (that is sent as the Content-Length header).
872      * The default value is SIZE_MAX, which means that the length is indeterminate.
873      * Generators should set this value whenever possible.
874      */
875     size_t content_length;
876     /**
877      * list of response headers
878      */
879     h2o_headers_t headers;
880     /**
881      * mime-related attributes (may be NULL)
882      */
883     h2o_mime_attributes_t *mime_attr;
884     /**
885      * retains the original response header before rewritten by ostream filters
886      */
887     struct {
888         int status;
889         h2o_headers_t headers;
890     } original;
891 } h2o_res_t;
892 
893 /**
894  * debug state (currently only for HTTP/2)
895  */
896 typedef struct st_h2o_http2_debug_state_t {
897     h2o_iovec_vector_t json;
898     ssize_t conn_flow_in;
899     ssize_t conn_flow_out;
900 } h2o_http2_debug_state_t;
901 
902 typedef struct st_h2o_conn_callbacks_t {
903     /**
904      * getsockname (return size of the obtained address, or 0 if failed)
905      */
906     socklen_t (*get_sockname)(h2o_conn_t *conn, struct sockaddr *sa);
907     /**
908      * getpeername (return size of the obtained address, or 0 if failed)
909      */
910     socklen_t (*get_peername)(h2o_conn_t *conn, struct sockaddr *sa);
911     /**
912      * returns picotls connection object used by the connection (or NULL if TLS is not used)
913      */
914     ptls_t *(*get_ptls)(h2o_conn_t *conn);
915     /**
916      * returns if the connection is target of tracing
917      */
918     int (*skip_tracing)(h2o_conn_t *conn);
919     /**
920      * optional (i.e. may be NULL) callback for server push
921      */
922     void (*push_path)(h2o_req_t *req, const char *abspath, size_t abspath_len, int is_critical);
923     /**
924      * debug state callback (optional)
925      */
926     h2o_http2_debug_state_t *(*get_debug_state)(h2o_req_t *req, int hpack_enabled);
927     /**
928      * returns number of requests inflight (optional, only supported by H2, H3)
929      */
930     uint32_t (*num_reqs_inflight)(h2o_conn_t *conn);
931     /**
932      * optional callbacks that return the tracer registry
933      */
934     quicly_tracer_t *(*get_tracer)(h2o_conn_t *conn);
935     /**
936      * An optional callback reporting an RTT estimate between the HTTP server and the HTTP client, measured in microseconds. At the
937      * moment, this callback is available only for HTTP/2. For HTTP/2, time difference between when the SETTINGS frame was sent and
938      * when a SETTINGS-ack was received is used as the estimate. The callback will return a negative value if the information is not
939      * yet available.
940      */
941     int64_t (*get_rtt)(h2o_conn_t *conn);
942     /**
943      * logging callbacks (all of them are optional)
944      */
945     union {
946         struct {
947             struct {
948                 h2o_iovec_t (*cc_name)(h2o_req_t *req);
949                 h2o_iovec_t (*delivery_rate)(h2o_req_t *req);
950             } transport;
951             struct {
952                 h2o_iovec_t (*protocol_version)(h2o_req_t *req);
953                 h2o_iovec_t (*session_reused)(h2o_req_t *req);
954                 h2o_iovec_t (*cipher)(h2o_req_t *req);
955                 h2o_iovec_t (*cipher_bits)(h2o_req_t *req);
956                 h2o_iovec_t (*session_id)(h2o_req_t *req);
957                 h2o_iovec_t (*server_name)(h2o_req_t *req);
958                 h2o_iovec_t (*negotiated_protocol)(h2o_req_t *req);
959             } ssl;
960             struct {
961                 h2o_iovec_t (*request_index)(h2o_req_t *req);
962             } http1;
963             struct {
964                 h2o_iovec_t (*stream_id)(h2o_req_t *req);
965                 h2o_iovec_t (*priority_received)(h2o_req_t *req);
966                 h2o_iovec_t (*priority_received_exclusive)(h2o_req_t *req);
967                 h2o_iovec_t (*priority_received_parent)(h2o_req_t *req);
968                 h2o_iovec_t (*priority_received_weight)(h2o_req_t *req);
969                 h2o_iovec_t (*priority_actual)(h2o_req_t *req);
970                 h2o_iovec_t (*priority_actual_parent)(h2o_req_t *req);
971                 h2o_iovec_t (*priority_actual_weight)(h2o_req_t *req);
972             } http2;
973             struct {
974                 h2o_iovec_t (*stream_id)(h2o_req_t *req);
975                 h2o_iovec_t (*quic_stats)(h2o_req_t *req);
976                 h2o_iovec_t (*quic_version)(h2o_req_t *req);
977             } http3;
978         };
979         h2o_iovec_t (*callbacks[1])(h2o_req_t *req);
980     } log_;
981 } h2o_conn_callbacks_t;
982 
983 /**
984  * basic structure of an HTTP connection (HTTP/1, HTTP/2, etc.)
985  */
986 struct st_h2o_conn_t {
987     /**
988      * the context of the server
989      */
990     h2o_context_t *ctx;
991     /**
992      * NULL-terminated list of hostconfs bound to the connection
993      */
994     h2o_hostconf_t **hosts;
995     /**
996      * time when the connection was established
997      */
998     struct timeval connected_at;
999     /**
1000      * connection id
1001      */
1002     uint64_t id;
1003     /**
1004      * callbacks
1005      */
1006     const h2o_conn_callbacks_t *callbacks;
1007     /**
1008      * connection UUID (UUIDv4 in the string representation).
1009      */
1010     struct {
1011         char str[H2O_UUID_STR_RFC4122_LEN + 1];
1012         uint8_t is_initialized;
1013     } _uuid;
1014 };
1015 
1016 /**
1017  * filter used for capturing a response (can be used to implement subreq)
1018  */
1019 typedef struct st_h2o_req_prefilter_t {
1020     struct st_h2o_req_prefilter_t *next;
1021     void (*on_setup_ostream)(struct st_h2o_req_prefilter_t *self, h2o_req_t *req, h2o_ostream_t **slot);
1022 } h2o_req_prefilter_t;
1023 
1024 typedef struct st_h2o_req_overrides_t {
1025     /**
1026      * specific client context (or NULL)
1027      */
1028     h2o_httpclient_ctx_t *client_ctx;
1029     /**
1030      * connpool to be used when connecting to upstream (or NULL)
1031      */
1032     h2o_httpclient_connection_pool_t *connpool;
1033     /**
1034      * upstream to connect to (or NULL)
1035      */
1036     h2o_url_t *upstream;
1037     /**
1038      * parameters for rewriting the `Location` header (only used if match.len != 0)
1039      */
1040     struct {
1041         /**
1042          * if the prefix of the location header matches the url, then the header will be rewritten
1043          */
1044         h2o_url_t *match;
1045         /**
1046          * path prefix to be inserted upon rewrite
1047          */
1048         h2o_iovec_t path_prefix;
1049     } location_rewrite;
1050     /**
1051      * whether if the PROXY header should be sent
1052      */
1053     unsigned use_proxy_protocol : 1;
1054     /**
1055      * whether the proxied request should preserve host
1056      */
1057     unsigned proxy_preserve_host : 1;
1058     /**
1059      * headers rewrite commands to be used when sending requests to upstream (or NULL)
1060      */
1061     h2o_headers_command_t *headers_cmds;
1062 } h2o_req_overrides_t;
1063 
1064 /**
1065  * additional information for extension-based dynamic content
1066  */
1067 typedef struct st_h2o_filereq_t {
1068     h2o_iovec_t script_name;
1069     h2o_iovec_t path_info;
1070     h2o_iovec_t local_path;
1071 } h2o_filereq_t;
1072 
1073 /**
1074  * Called be the protocol handler to submit chunk of request body to the generator. The callback returns 0 if successful, otherwise
1075  * a non-zero value. Once `write_req.cb` is called, subsequent invocations MUST be postponed until the `proceed_req` is called. At
1076  * the moment, `write_req_cb` is required to create a copy of data being provided before returning. To avoid copying, we should
1077  * consider delegating the responsibility of retaining the buffer to the caller.
1078  */
1079 typedef int (*h2o_write_req_cb)(void *ctx, int is_end_stream);
1080 /**
1081  * Called by the generator, in response to `h2o_write_req_cb` to indicate to the protocol handler that new chunk can be submitted,
1082  * or to notify that an error has occurred. In the latter case, write might not be inflight. Note that `errstr` will be NULL (rather
1083  * than an error code indicating EOS) when called in response to `h2o_write_req_cb` with `is_end_stream` set to 1.
1084  */
1085 typedef void (*h2o_proceed_req_cb)(h2o_req_t *req, const char *errstr);
1086 /**
1087  *
1088  */
1089 typedef void (*h2o_forward_datagram_cb)(h2o_req_t *req, h2o_iovec_t *datagrams, size_t num_datagrams);
1090 
1091 #define H2O_SEND_SERVER_TIMING_BASIC 1
1092 #define H2O_SEND_SERVER_TIMING_PROXY 2
1093 
1094 /**
1095  * a HTTP request
1096  */
1097 struct st_h2o_req_t {
1098     /**
1099      * the underlying connection
1100      */
1101     h2o_conn_t *conn;
1102     /**
1103      * the request sent by the client (as is)
1104      */
1105     struct {
1106         /**
1107          * scheme (http, https, etc.)
1108          */
1109         const h2o_url_scheme_t *scheme;
1110         /**
1111          * authority (a.k.a. the Host header; the value is supplemented if missing before the handlers are being called)
1112          */
1113         h2o_iovec_t authority;
1114         /**
1115          * method
1116          */
1117         h2o_iovec_t method;
1118         /**
1119          * abs-path of the request (unmodified)
1120          */
1121         h2o_iovec_t path;
1122         /**
1123          * offset of '?' within path, or SIZE_MAX if not found
1124          */
1125         size_t query_at;
1126     } input;
1127     /**
1128      * the host context
1129      */
1130     h2o_hostconf_t *hostconf;
1131     /**
1132      * the path context
1133      */
1134     h2o_pathconf_t *pathconf;
1135     /**
1136      * filters and the size of it
1137      */
1138     h2o_filter_t **filters;
1139     size_t num_filters;
1140     /**
1141      * loggers and the size of it
1142      */
1143     h2o_logger_t **loggers;
1144     size_t num_loggers;
1145     /**
1146      * the handler that has been executed
1147      */
1148     h2o_handler_t *handler;
1149     /**
1150      * scheme (http, https, etc.)
1151      */
1152     const h2o_url_scheme_t *scheme;
1153     /**
1154      * authority (of the processing request)
1155      */
1156     h2o_iovec_t authority;
1157     /**
1158      * method (of the processing request)
1159      */
1160     h2o_iovec_t method;
1161     /**
1162      * abs-path of the processing request
1163      */
1164     h2o_iovec_t path;
1165     /**
1166      * offset of '?' within path, or SIZE_MAX if not found
1167      */
1168     size_t query_at;
1169     /**
1170      * normalized path of the processing request (i.e. no "." or "..", no query)
1171      */
1172     h2o_iovec_t path_normalized;
1173     /**
1174      * Map of indexes of `path_normalized` into the next character in `path`; built only if `path` required normalization
1175      */
1176     size_t *norm_indexes;
1177     /**
1178      * authority's prefix matched with `*` against defined hosts
1179      */
1180     h2o_iovec_t authority_wildcard_match;
1181     /**
1182      * filters assigned per request
1183      */
1184     h2o_req_prefilter_t *prefilters;
1185     /**
1186      * additional information (becomes available for extension-based dynamic content)
1187      */
1188     h2o_filereq_t *filereq;
1189     /**
1190      * overrides (maybe NULL)
1191      */
1192     h2o_req_overrides_t *overrides;
1193     /**
1194      * the HTTP version (represented as 0xMMmm (M=major, m=minor))
1195      */
1196     int version;
1197     /**
1198      * list of request headers
1199      */
1200     h2o_headers_t headers;
1201     /**
1202      * the request entity (base == NULL if none), can't be used if the handler is streaming the body
1203      */
1204     h2o_iovec_t entity;
1205     /**
1206      * amount of request body being received
1207      */
1208     size_t req_body_bytes_received;
1209     /**
1210      * If different of SIZE_MAX, the numeric value of the received content-length: header
1211      */
1212     size_t content_length;
1213     /**
1214      * timestamp when the request was processed
1215      */
1216     h2o_timestamp_t processed_at;
1217     /**
1218      * additional timestamps
1219      */
1220     struct {
1221         struct timeval request_begin_at;
1222         struct timeval request_body_begin_at;
1223         struct timeval response_start_at;
1224         struct timeval response_end_at;
1225     } timestamps;
1226     /**
1227      * proxy stats
1228      */
1229     struct {
1230         struct {
1231             uint64_t total;
1232             uint64_t header;
1233             uint64_t body;
1234         } bytes_written;
1235         struct {
1236             uint64_t total;
1237             uint64_t header;
1238             uint64_t body;
1239         } bytes_read;
1240         h2o_httpclient_timings_t timestamps;
1241         h2o_httpclient_conn_properties_t conn;
1242     } proxy_stats;
1243     /**
1244      * the response
1245      */
1246     h2o_res_t res;
1247     /**
1248      * number of bytes sent by the generator (excluding headers)
1249      */
1250     uint64_t bytes_sent;
1251     /**
1252      * the number of times the request can be reprocessed (excluding delegation)
1253      */
1254     unsigned remaining_reprocesses;
1255     /**
1256      * the number of times the request can be delegated
1257      */
1258     unsigned remaining_delegations;
1259 
1260     /**
1261      * environment variables
1262      */
1263     h2o_iovec_vector_t env;
1264 
1265     /**
1266      * error log for the request (`h2o_req_log_error` must be used for error logging)
1267      */
1268     h2o_buffer_t *error_logs;
1269 
1270     /**
1271      * error log redirection called by `h2o_req_log_error`. By default, the error is appended to `error_logs`. The callback is
1272      * replaced by mruby middleware to send the error log to the rack handler.
1273      */
1274     struct {
1275         void (*cb)(void *data, h2o_iovec_t prefix, h2o_iovec_t msg);
1276         void *data;
1277     } error_log_delegate;
1278 
1279     /* flags */
1280 
1281     /**
1282      * whether or not the connection is persistent.
1283      * Applications should set this flag to zero in case the connection cannot be kept keep-alive (due to an error etc.)
1284      */
1285     unsigned char http1_is_persistent : 1;
1286     /**
1287      * whether if the response has been delegated (i.e. reproxied).
1288      * For delegated responses, redirect responses would be handled internally.
1289      */
1290     unsigned char res_is_delegated : 1;
1291     /**
1292      * set by the generator if the protocol handler should replay the request upon seeing 425
1293      */
1294     unsigned char reprocess_if_too_early : 1;
1295     /**
1296      * set by the prxy handler if the http2 upstream refused the stream so the client can retry the request
1297      */
1298     unsigned char upstream_refused : 1;
1299     /**
1300      * if h2o_process_request has been called
1301      */
1302     unsigned char process_called : 1;
1303     /**
1304      * Indicates if requested to serve something other than HTTP (e.g., websocket, upgrade, CONNECT, ...) using the streaming API.
1305      * When the protocol handler returns a successful response, filters are skipped.
1306      */
1307     unsigned char is_tunnel_req : 1;
1308 
1309     /**
1310      * whether if the response should include server-timing header. Logical OR of H2O_SEND_SERVER_TIMING_*
1311      */
1312     unsigned send_server_timing;
1313 
1314     /**
1315      * Whether the producer of the response has explicitly disabled or
1316      * enabled compression. One of H2O_COMPRESS_HINT_*
1317      */
1318     char compress_hint;
1319 
1320     /**
1321      * the Upgrade request header (or { NULL, 0 } if not available)
1322      */
1323     h2o_iovec_t upgrade;
1324 
1325     /**
1326      * preferred chunk size by the ostream
1327      */
1328     size_t preferred_chunk_size;
1329 
1330     /**
1331      * callback and context for receiving request body (see h2o_handler_t::supports_request_streaming for details)
1332      */
1333     struct {
1334         h2o_write_req_cb cb;
1335         void *ctx;
1336     } write_req;
1337 
1338     /**
1339      * callback and context for receiving more request body (see h2o_handler_t::supports_request_streaming for details)
1340      */
1341     h2o_proceed_req_cb proceed_req;
1342 
1343     /**
1344      * Callbacks used for forwarding datagrams. Write-side is assumed to use `write_req.ctx` for retaining the context if necessary.
1345      */
1346     struct {
1347         h2o_forward_datagram_cb write_, read_;
1348     } forward_datagram;
1349 
1350     /* internal structure */
1351     h2o_generator_t *_generator;
1352     h2o_ostream_t *_ostr_top;
1353     size_t _next_filter_index;
1354     h2o_timer_t _timeout_entry;
1355 
1356     /* per-request memory pool (placed at the last since the structure is large) */
1357     h2o_mem_pool_t pool;
1358 };
1359 
1360 typedef struct st_h2o_accept_ctx_t {
1361     h2o_context_t *ctx;
1362     h2o_hostconf_t **hosts;
1363     SSL_CTX *ssl_ctx;
1364     h2o_iovec_t *http2_origin_frame;
1365     int expect_proxy_line;
1366     h2o_multithread_receiver_t *libmemcached_receiver;
1367 } h2o_accept_ctx_t;
1368 
1369 /* util */
1370 
1371 extern const char h2o_http2_npn_protocols[];
1372 extern const char h2o_npn_protocols[];
1373 extern const h2o_iovec_t h2o_http2_alpn_protocols[];
1374 extern const h2o_iovec_t h2o_alpn_protocols[];
1375 
1376 /**
1377  * accepts a connection
1378  */
1379 void h2o_accept(h2o_accept_ctx_t *ctx, h2o_socket_t *sock);
1380 /**
1381  * creates a new connection
1382  */
1383 static h2o_conn_t *h2o_create_connection(size_t sz, h2o_context_t *ctx, h2o_hostconf_t **hosts, struct timeval connected_at,
1384                                          const h2o_conn_callbacks_t *callbacks);
1385 /**
1386  * returns the uuid of the connection as a null-terminated string.
1387  */
1388 static const char *h2o_conn_get_uuid(h2o_conn_t *conn);
1389 /**
1390  * returns if the connection is still in early-data state (i.e., if there is a risk of received requests being a replay)
1391  */
1392 static int h2o_conn_is_early_data(h2o_conn_t *conn);
1393 /**
1394  * setups accept context for memcached SSL resumption
1395  */
1396 void h2o_accept_setup_memcached_ssl_resumption(h2o_memcached_context_t *ctx, unsigned expiration);
1397 /**
1398  * setups accept context for redis SSL resumption
1399  */
1400 void h2o_accept_setup_redis_ssl_resumption(const char *host, uint16_t port, unsigned expiration, const char *prefix);
1401 /**
1402  * returns the protocol version (e.g. "HTTP/1.1", "HTTP/2")
1403  */
1404 size_t h2o_stringify_protocol_version(char *dst, int version);
1405 /**
1406  * builds the proxy header defined by the PROXY PROTOCOL
1407  */
1408 size_t h2o_stringify_proxy_header(h2o_conn_t *conn, char *buf);
1409 #define H2O_PROXY_HEADER_MAX_LENGTH                                                                                                \
1410     (sizeof("PROXY TCP6 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 65535 65535\r\n") - 1)
1411 /**
1412  * extracts path to be pushed from `Link: rel=preload` header.
1413  */
1414 void h2o_extract_push_path_from_link_header(h2o_mem_pool_t *pool, const char *value, size_t value_len, h2o_iovec_t base_path,
1415                                             const h2o_url_scheme_t *input_scheme, h2o_iovec_t input_authority,
1416                                             const h2o_url_scheme_t *base_scheme, h2o_iovec_t *base_authority,
1417                                             void (*cb)(void *ctx, const char *path, size_t path_len, int is_critical), void *cb_ctx,
1418                                             h2o_iovec_t *filtered_value, int allow_cross_origin_push);
1419 /**
1420  * return a bitmap of compressible types, by parsing the `accept-encoding` header
1421  */
1422 int h2o_get_compressible_types(const h2o_headers_t *headers);
1423 #define H2O_COMPRESSIBLE_GZIP 1
1424 #define H2O_COMPRESSIBLE_BROTLI 2
1425 /**
1426  * builds destination URL or path, by contatenating the prefix and path_info of the request
1427  */
1428 h2o_iovec_t h2o_build_destination(h2o_req_t *req, const char *prefix, size_t prefix_len, int use_path_normalized);
1429 /**
1430  * encodes the duration value of the `server-timing` header
1431  */
1432 void h2o_add_server_timing_header(h2o_req_t *req, int uses_trailer);
1433 /**
1434  * encodes the duration value of the `server-timing` trailer
1435  */
1436 h2o_iovec_t h2o_build_server_timing_trailer(h2o_req_t *req, const char *prefix, size_t prefix_len, const char *suffix,
1437                                             size_t suffix_len);
1438 /**
1439  * release all thread-local resources used by h2o
1440  */
1441 void h2o_cleanup_thread(void);
1442 
1443 extern uint64_t h2o_connection_id;
1444 
1445 /* request */
1446 
1447 /**
1448  * initializes the request structure
1449  * @param req the request structure
1450  * @param conn the underlying connection
1451  * @param src if not NULL, the request structure would be a shallow copy of src
1452  */
1453 void h2o_init_request(h2o_req_t *req, h2o_conn_t *conn, h2o_req_t *src);
1454 /**
1455  * releases resources allocated for handling a request
1456  */
1457 void h2o_dispose_request(h2o_req_t *req);
1458 /**
1459  * Checks and returns if pseudo headers meet the constraints. This function should be called by each protocol implementation before
1460  * passing the request to `h2o_process_request`.
1461  */
1462 int h2o_req_validate_pseudo_headers(h2o_req_t *req);
1463 /**
1464  * called by the connection layer to start processing a request that is ready
1465  */
1466 void h2o_process_request(h2o_req_t *req);
1467 /**
1468  * returns the first handler that will be used for the request
1469  */
1470 h2o_handler_t *h2o_get_first_handler(h2o_req_t *req);
1471 /**
1472  * delegates the request to the next handler
1473  */
1474 void h2o_delegate_request(h2o_req_t *req);
1475 /**
1476  * calls h2o_delegate_request using zero_timeout callback
1477  */
1478 void h2o_delegate_request_deferred(h2o_req_t *req);
1479 /**
1480  * reprocesses a request once more (used for internal redirection)
1481  */
1482 void h2o_reprocess_request(h2o_req_t *req, h2o_iovec_t method, const h2o_url_scheme_t *scheme, h2o_iovec_t authority,
1483                            h2o_iovec_t path, h2o_req_overrides_t *overrides, int is_delegated);
1484 /**
1485  * calls h2o_reprocess_request using zero_timeout callback
1486  */
1487 void h2o_reprocess_request_deferred(h2o_req_t *req, h2o_iovec_t method, const h2o_url_scheme_t *scheme, h2o_iovec_t authority,
1488                                     h2o_iovec_t path, h2o_req_overrides_t *overrides, int is_delegated);
1489 /**
1490  *
1491  */
1492 void h2o_replay_request(h2o_req_t *req);
1493 /**
1494  *
1495  */
1496 void h2o_replay_request_deferred(h2o_req_t *req);
1497 /**
1498  * called by handlers to set the generator
1499  * @param req the request
1500  * @param generator the generator
1501  */
1502 void h2o_start_response(h2o_req_t *req, h2o_generator_t *generator);
1503 /**
1504  * called by filters to insert output-stream filters for modifying the response
1505  * @param req the request
1506  * @param alignment of the memory to be allocated for the ostream filter
1507  * @param size of the memory to be allocated for the ostream filter
1508  * @param slot where the stream should be inserted
1509  * @return pointer to the ostream filter
1510  */
1511 h2o_ostream_t *h2o_add_ostream(h2o_req_t *req, size_t alignment, size_t sz, h2o_ostream_t **slot);
1512 /**
1513  * prepares the request for processing by looking at the method, URI, headers
1514  */
1515 h2o_hostconf_t *h2o_req_setup(h2o_req_t *req);
1516 /**
1517  * binds configurations to the request
1518  */
1519 void h2o_req_bind_conf(h2o_req_t *req, h2o_hostconf_t *hostconf, h2o_pathconf_t *pathconf);
1520 /**
1521  *
1522  */
1523 static int h2o_send_state_is_in_progress(h2o_send_state_t s);
1524 /**
1525  * Initializes a send vector that refers to mutable memory region. When the `proceed` callback is invoked, it is possible for the
1526  * generator to reuse (or release) that memory region.
1527  */
1528 void h2o_sendvec_init_raw(h2o_sendvec_t *vec, const void *base, size_t len);
1529 /**
1530  * Initializes a send vector that refers to immutable memory region. It is the responsible of the generator to preserve the contents
1531  * of the specified memory region until the user of the send vector finishes using the send vector.
1532  */
1533 void h2o_sendvec_init_immutable(h2o_sendvec_t *vec, const void *base, size_t len);
1534 /**
1535  *
1536  */
1537 int h2o_sendvec_flatten_raw(h2o_sendvec_t *vec, h2o_req_t *req, h2o_iovec_t dst, size_t off);
1538 /**
1539  * called by the generators to send output
1540  * note: generators should free itself after sending the final chunk (i.e. calling the function with is_final set to true)
1541  * @param req the request
1542  * @param bufs an array of buffers
1543  * @param bufcnt length of the buffers array
1544  * @param state describes if the output is final, has an error, or is in progress
1545  */
1546 void h2o_send(h2o_req_t *req, h2o_iovec_t *bufs, size_t bufcnt, h2o_send_state_t state);
1547 void h2o_sendvec(h2o_req_t *req, h2o_sendvec_t *vecs, size_t veccnt, h2o_send_state_t state);
1548 /**
1549  * creates an uninitialized prefilter and returns pointer to it
1550  */
1551 h2o_req_prefilter_t *h2o_add_prefilter(h2o_req_t *req, size_t alignment, size_t sz);
1552 /**
1553  * requests the next prefilter or filter (if any) to setup the ostream if necessary
1554  */
1555 static void h2o_setup_next_prefilter(h2o_req_prefilter_t *self, h2o_req_t *req, h2o_ostream_t **slot);
1556 /**
1557  * requests the next filter (if any) to setup the ostream if necessary
1558  */
1559 static void h2o_setup_next_ostream(h2o_req_t *req, h2o_ostream_t **slot);
1560 /**
1561  * called by the ostream filters to send output to the next ostream filter
1562  * note: ostream filters should free itself after sending the final chunk (i.e. calling the function with is_final set to true)
1563  * note: ostream filters must not set is_final flag to TRUE unless is_final flag of the do_send callback was set as such
1564  * @param ostr current ostream filter
1565  * @param req the request
1566  * @param bufs an array of buffers
1567  * @param bufcnt length of the buffers array
1568  * @param state whether the output is in progress, final, or in error
1569  */
1570 void h2o_ostream_send_next(h2o_ostream_t *ostream, h2o_req_t *req, h2o_sendvec_t *bufs, size_t bufcnt, h2o_send_state_t state);
1571 /**
1572  * called by the connection layer to request additional data to the generator
1573  */
1574 static void h2o_proceed_response(h2o_req_t *req);
1575 void h2o_proceed_response_deferred(h2o_req_t *req);
1576 /**
1577  * if NULL, supplements h2o_req_t::mime_attr
1578  */
1579 void h2o_req_fill_mime_attributes(h2o_req_t *req);
1580 /**
1581  * returns an environment variable
1582  */
1583 static h2o_iovec_t *h2o_req_getenv(h2o_req_t *req, const char *name, size_t name_len, int allocate_if_not_found);
1584 /**
1585  * unsets an environment variable
1586  */
1587 static void h2o_req_unsetenv(h2o_req_t *req, const char *name, size_t name_len);
1588 
1589 /* config */
1590 
1591 h2o_envconf_t *h2o_config_create_envconf(h2o_envconf_t *src);
1592 void h2o_config_setenv(h2o_envconf_t *envconf, const char *name, const char *value);
1593 void h2o_config_unsetenv(h2o_envconf_t *envconf, const char *name);
1594 
1595 /**
1596  * initializes pathconf
1597  * @param path path to serve, or NULL if fallback or extension-level
1598  * @param mimemap mimemap to use, or NULL if fallback or extension-level
1599  */
1600 void h2o_config_init_pathconf(h2o_pathconf_t *pathconf, h2o_globalconf_t *globalconf, const char *path, h2o_mimemap_t *mimemap);
1601 /**
1602  *
1603  */
1604 void h2o_config_dispose_pathconf(h2o_pathconf_t *pathconf);
1605 /**
1606  * initializes the global configuration
1607  */
1608 void h2o_config_init(h2o_globalconf_t *config);
1609 /**
1610  * registers a host context
1611  */
1612 h2o_hostconf_t *h2o_config_register_host(h2o_globalconf_t *config, h2o_iovec_t host, uint16_t port);
1613 /**
1614  * registers a path context
1615  * @param hostconf host-level configuration that the path-level configuration belongs to
1616  * @param path path
1617  * @param flags unused and must be set to zero
1618  *
1619  * Handling of the path argument has changed in version 2.0 (of the standard server).
1620  *
1621  * Before 2.0, the function implicitely added a trailing `/` to the supplied path (if it did not end with a `/`), and when receiving
1622  * a HTTP request for a matching path without the trailing `/`, libh2o sent a 301 response redirecting the client to a URI with a
1623  * trailing `/`.
1624  *
1625  * Since 2.0, the function retains the exact path given as the argument, and the handlers of the pathconf is invoked if one of the
1626  * following conditions are met:
1627  *
1628  * * request path is an exact match to the configuration path
1629  * * configuration path does not end with a `/`, and the request path begins with the configuration path followed by a `/`
1630  */
1631 h2o_pathconf_t *h2o_config_register_path(h2o_hostconf_t *hostconf, const char *path, int flags);
1632 /**
1633  * registers an extra status handler
1634  */
1635 void h2o_config_register_status_handler(h2o_globalconf_t *config, h2o_status_handler_t *status_handler);
1636 /**
1637  * disposes of the resources allocated for the global configuration
1638  */
1639 void h2o_config_dispose(h2o_globalconf_t *config);
1640 /**
1641  * creates a handler associated to a given pathconf
1642  */
1643 h2o_handler_t *h2o_create_handler(h2o_pathconf_t *conf, size_t sz);
1644 /**
1645  * creates a filter associated to a given pathconf
1646  */
1647 h2o_filter_t *h2o_create_filter(h2o_pathconf_t *conf, size_t sz);
1648 /**
1649  * creates a logger associated to a given pathconf
1650  */
1651 h2o_logger_t *h2o_create_logger(h2o_pathconf_t *conf, size_t sz);
1652 
1653 /* context */
1654 
1655 /**
1656  * initializes the context
1657  */
1658 void h2o_context_init(h2o_context_t *context, h2o_loop_t *loop, h2o_globalconf_t *config);
1659 /**
1660  * disposes of the resources allocated for the context
1661  */
1662 void h2o_context_dispose(h2o_context_t *context);
1663 /**
1664  * requests shutdown to the connections governed by the context
1665  */
1666 void h2o_context_request_shutdown(h2o_context_t *context);
1667 /**
1668  *
1669  */
1670 void h2o_context_init_pathconf_context(h2o_context_t *ctx, h2o_pathconf_t *pathconf);
1671 /**
1672  *
1673  */
1674 void h2o_context_dispose_pathconf_context(h2o_context_t *ctx, h2o_pathconf_t *pathconf);
1675 
1676 /**
1677  * returns current timestamp
1678  * @param ctx the context
1679  * @param pool memory pool (used when ts != NULL)
1680  * @param ts buffer to store the timestamp (optional)
1681  * @return current time in UTC
1682  */
1683 static h2o_timestamp_t h2o_get_timestamp(h2o_context_t *ctx, h2o_mem_pool_t *pool);
1684 void h2o_context_update_timestamp_string_cache(h2o_context_t *ctx);
1685 /**
1686  * returns per-module context set
1687  */
1688 static void *h2o_context_get_handler_context(h2o_context_t *ctx, h2o_handler_t *handler);
1689 /**
1690  * sets per-module context
1691  */
1692 static void h2o_context_set_handler_context(h2o_context_t *ctx, h2o_handler_t *handler, void *handler_ctx);
1693 /**
1694  * returns per-module context set by the on_context_init callback
1695  */
1696 static void *h2o_context_get_filter_context(h2o_context_t *ctx, h2o_filter_t *filter);
1697 /**
1698  * sets per-module filter context
1699  */
1700 static void h2o_context_set_filter_context(h2o_context_t *ctx, h2o_filter_t *filter, void *filter_ctx);
1701 /**
1702  * returns per-module context set by the on_context_init callback
1703  */
1704 static void *h2o_context_get_logger_context(h2o_context_t *ctx, h2o_logger_t *logger);
1705 /*
1706  * return the address associated with the key in the context storage
1707  */
1708 static void **h2o_context_get_storage(h2o_context_t *ctx, size_t *key, void (*dispose_cb)(void *));
1709 
1710 /* built-in generators */
1711 
1712 enum {
1713     /**
1714      * enforces the http1 protocol handler to close the connection after sending the response
1715      */
1716     H2O_SEND_ERROR_HTTP1_CLOSE_CONNECTION = 0x1,
1717     /**
1718      * if set, does not flush the registered response headers
1719      */
1720     H2O_SEND_ERROR_KEEP_HEADERS = 0x2,
1721     /**
1722      * indicates a broken or incomplete HTTP request, and that some fields of `h2o_req_t` e.g., `input` might be NULL
1723      */
1724     H2O_SEND_ERROR_BROKEN_REQUEST = 0x04
1725 };
1726 
1727 /**
1728  * Add a `date:` header to the response
1729  */
1730 void h2o_resp_add_date_header(h2o_req_t *req);
1731 /**
1732  * Sends the given string as the response. The function copies the string so that the caller can discard it immediately.
1733  *
1734  * Be careful of calling the function asynchronously, because there is a chance of the request object getting destroyed before the
1735  * function is being invoked.  This could happpen for example when the client abruptly closing the connection. There are two ways to
1736  * detect the destruction:
1737  *
1738  * * allocate a memory chunk using the request's memory pool with a destructor that you define; i.e. call `h2o_mem_alloc_shared(
1739  *   &req->pool, obj_size, my_destructor)`. When the request object is destroyed, `my_destructor` will be invoked as part of the
1740  *   memory reclamation process.
1741  * * register the `stop` callback of the generator that is bound to the request. The downside of the approach is that a generator
1742  *   is not associated to a request until all the response headers become ready to be sent, i.e., when `h2o_start_response` is
1743  *   called.
1744  */
1745 void h2o_send_inline(h2o_req_t *req, const char *body, size_t len);
1746 /**
1747  * sends the given information as an error response to the client. Uses h2o_send_inline internally, so the same restrictions apply.
1748  */
1749 void h2o_send_error_generic(h2o_req_t *req, int status, const char *reason, const char *body, int flags);
1750 #define H2O_SEND_ERROR_XXX(status)                                                                                                 \
1751     static inline void h2o_send_error_##status(h2o_req_t *req, const char *reason, const char *body, int flags)                    \
1752     {                                                                                                                              \
1753         req->conn->ctx->emitted_error_status[H2O_STATUS_ERROR_##status]++;                                                         \
1754         h2o_send_error_generic(req, status, reason, body, flags);                                                                  \
1755     }
1756 
1757 H2O_SEND_ERROR_XXX(400)
1758 H2O_SEND_ERROR_XXX(403)
1759 H2O_SEND_ERROR_XXX(404)
1760 H2O_SEND_ERROR_XXX(405)
1761 H2O_SEND_ERROR_XXX(413)
1762 H2O_SEND_ERROR_XXX(416)
1763 H2O_SEND_ERROR_XXX(417)
1764 H2O_SEND_ERROR_XXX(500)
1765 H2O_SEND_ERROR_XXX(502)
1766 H2O_SEND_ERROR_XXX(503)
1767 
1768 /**
1769  * sends error response using zero timeout; can be called by output filters while processing the headers.  Uses h2o_send_inline
1770  * internally, so the same restrictions apply.
1771  */
1772 void h2o_send_error_deferred(h2o_req_t *req, int status, const char *reason, const char *body, int flags);
1773 /**
1774  * sends a redirect response.  Uses (the equivalent of) h2o_send_inline internally, so the same restrictions apply.
1775  */
1776 void h2o_send_redirect(h2o_req_t *req, int status, const char *reason, const char *url, size_t url_len);
1777 /**
1778  * handles redirect internally.
1779  */
1780 void h2o_send_redirect_internal(h2o_req_t *req, h2o_iovec_t method, const char *url_str, size_t url_len, int preserve_overrides);
1781 /**
1782  * returns method to be used after redirection
1783  */
1784 h2o_iovec_t h2o_get_redirect_method(h2o_iovec_t method, int status);
1785 /**
1786  * registers push path (if necessary) by parsing a Link header
1787  * this returns a version of `value` that removes the links that had the `x-http2-push-only` attribute
1788  */
1789 h2o_iovec_t h2o_push_path_in_link_header(h2o_req_t *req, const char *value, size_t value_len);
1790 /**
1791  * sends 1xx response
1792  */
1793 void h2o_send_informational(h2o_req_t *req);
1794 /**
1795  *
1796  */
1797 static int h2o_req_can_stream_request(h2o_req_t *req);
1798 /**
1799  * resolves internal redirect url for dest regarding req's hostconf
1800  */
1801 int h2o_req_resolve_internal_redirect_url(h2o_req_t *req, h2o_iovec_t dest, h2o_url_t *resolved);
1802 /**
1803  * logs an error
1804  */
1805 void h2o_req_log_error(h2o_req_t *req, const char *module, const char *fmt, ...) __attribute__((format(printf, 3, 4)));
1806 void h2o_write_error_log(h2o_iovec_t prefix, h2o_iovec_t msg);
1807 
1808 /* log */
1809 
1810 enum { H2O_LOGCONF_ESCAPE_APACHE, H2O_LOGCONF_ESCAPE_JSON };
1811 
1812 /**
1813  * compiles a log configuration
1814  */
1815 h2o_logconf_t *h2o_logconf_compile(const char *fmt, int escape, char *errbuf);
1816 /**
1817  * disposes of a log configuration
1818  */
1819 void h2o_logconf_dispose(h2o_logconf_t *logconf);
1820 /**
1821  * logs a request
1822  */
1823 char *h2o_log_request(h2o_logconf_t *logconf, h2o_req_t *req, size_t *len, char *buf);
1824 
1825 /* proxy */
1826 
1827 /**
1828  * processes a request (by sending the request upstream)
1829  */
1830 void h2o__proxy_process_request(h2o_req_t *req);
1831 
1832 /* mime mapper */
1833 
1834 /**
1835  * initializes the mimemap (the returned chunk is refcounted)
1836  */
1837 h2o_mimemap_t *h2o_mimemap_create(void);
1838 /**
1839  * clones a mimemap
1840  */
1841 h2o_mimemap_t *h2o_mimemap_clone(h2o_mimemap_t *src);
1842 /**
1843  *
1844  */
1845 void h2o_mimemap_on_context_init(h2o_mimemap_t *mimemap, h2o_context_t *ctx);
1846 /**
1847  *
1848  */
1849 void h2o_mimemap_on_context_dispose(h2o_mimemap_t *mimemap, h2o_context_t *ctx);
1850 /**
1851  * returns if the map contains a dynamic type
1852  */
1853 int h2o_mimemap_has_dynamic_type(h2o_mimemap_t *mimemap);
1854 /**
1855  * sets the default mime-type
1856  */
1857 void h2o_mimemap_set_default_type(h2o_mimemap_t *mimemap, const char *mime, h2o_mime_attributes_t *attr);
1858 /**
1859  * adds a mime-type mapping
1860  */
1861 void h2o_mimemap_define_mimetype(h2o_mimemap_t *mimemap, const char *ext, const char *mime, h2o_mime_attributes_t *attr);
1862 /**
1863  * adds a mime-type mapping
1864  */
1865 h2o_mimemap_type_t *h2o_mimemap_define_dynamic(h2o_mimemap_t *mimemap, const char **exts, h2o_globalconf_t *globalconf);
1866 /**
1867  * removes a mime-type mapping
1868  */
1869 void h2o_mimemap_remove_type(h2o_mimemap_t *mimemap, const char *ext);
1870 /**
1871  * clears all mime-type mapping
1872  */
1873 void h2o_mimemap_clear_types(h2o_mimemap_t *mimemap);
1874 /**
1875  * sets the default mime-type
1876  */
1877 h2o_mimemap_type_t *h2o_mimemap_get_default_type(h2o_mimemap_t *mimemap);
1878 /**
1879  * returns the mime-type corresponding to given extension
1880  */
1881 h2o_mimemap_type_t *h2o_mimemap_get_type_by_extension(h2o_mimemap_t *mimemap, h2o_iovec_t ext);
1882 /**
1883  * returns the mime-type corresponding to given mimetype
1884  */
1885 h2o_mimemap_type_t *h2o_mimemap_get_type_by_mimetype(h2o_mimemap_t *mimemap, h2o_iovec_t mime, int exact_match_only);
1886 /**
1887  * returns the default mime attributes given a mime type
1888  */
1889 void h2o_mimemap_get_default_attributes(const char *mime, h2o_mime_attributes_t *attr);
1890 
1891 /* various handlers */
1892 
1893 /* lib/access_log.c */
1894 
1895 typedef struct st_h2o_access_log_filehandle_t h2o_access_log_filehandle_t;
1896 
1897 int h2o_access_log_open_log(const char *path);
1898 h2o_access_log_filehandle_t *h2o_access_log_open_handle(const char *path, const char *fmt, int escape);
1899 h2o_logger_t *h2o_access_log_register(h2o_pathconf_t *pathconf, h2o_access_log_filehandle_t *handle);
1900 void h2o_access_log_register_configurator(h2o_globalconf_t *conf);
1901 
1902 /* lib/handler/server_timing.c */
1903 void h2o_server_timing_register(h2o_pathconf_t *pathconf, int enforce);
1904 void h2o_server_timing_register_configurator(h2o_globalconf_t *conf);
1905 
1906 /* lib/compress.c */
1907 
1908 enum { H2O_COMPRESS_FLAG_PARTIAL, H2O_COMPRESS_FLAG_FLUSH, H2O_COMPRESS_FLAG_EOS };
1909 
1910 /**
1911  * compressor context
1912  */
1913 typedef struct st_h2o_compress_context_t {
1914     /**
1915      * name used in content-encoding header
1916      */
1917     h2o_iovec_t name;
1918     /**
1919      * compress or decompress callback (inbufs are raw buffers)
1920      */
1921     h2o_send_state_t (*do_transform)(struct st_h2o_compress_context_t *self, h2o_sendvec_t *inbufs, size_t inbufcnt,
1922                                      h2o_send_state_t state, h2o_sendvec_t **outbufs, size_t *outbufcnt);
1923     /**
1924      * push buffer
1925      */
1926     char *push_buf;
1927 } h2o_compress_context_t;
1928 
1929 typedef struct st_h2o_compress_args_t {
1930     size_t min_size;
1931     struct {
1932         int quality; /* -1 if disabled */
1933     } gzip;
1934     struct {
1935         int quality; /* -1 if disabled */
1936     } brotli;
1937 } h2o_compress_args_t;
1938 
1939 /**
1940  * registers the gzip/brotli encoding output filter (added by default, for now)
1941  */
1942 void h2o_compress_register(h2o_pathconf_t *pathconf, h2o_compress_args_t *args);
1943 /**
1944  * compresses given chunk
1945  */
1946 h2o_send_state_t h2o_compress_transform(h2o_compress_context_t *self, h2o_req_t *req, h2o_sendvec_t *inbufs, size_t inbufcnt,
1947                                         h2o_send_state_t state, h2o_sendvec_t **outbufs, size_t *outbufcnt);
1948 /**
1949  * instantiates the gzip compressor
1950  */
1951 h2o_compress_context_t *h2o_compress_gzip_open(h2o_mem_pool_t *pool, int quality);
1952 /**
1953  * instantiates the gzip decompressor
1954  */
1955 h2o_compress_context_t *h2o_compress_gunzip_open(h2o_mem_pool_t *pool);
1956 /**
1957  * instantiates the brotli compressor (only available if H2O_USE_BROTLI is set)
1958  */
1959 h2o_compress_context_t *h2o_compress_brotli_open(h2o_mem_pool_t *pool, int quality, size_t estimated_cotent_length,
1960                                                  size_t preferred_chunk_size);
1961 /**
1962  * registers the configurator for the gzip/brotli output filter
1963  */
1964 void h2o_compress_register_configurator(h2o_globalconf_t *conf);
1965 
1966 /* lib/handler/throttle_resp.c */
1967 /**
1968  * registers the throttle response filter
1969  */
1970 void h2o_throttle_resp_register(h2o_pathconf_t *pathconf);
1971 /**
1972  * configurator
1973  */
1974 void h2o_throttle_resp_register_configurator(h2o_globalconf_t *conf);
1975 
1976 /* lib/errordoc.c */
1977 
1978 typedef struct st_h2o_errordoc_t {
1979     int status;
1980     h2o_iovec_t url; /* can be relative */
1981 } h2o_errordoc_t;
1982 
1983 /**
1984  * registers the errordocument output filter
1985  */
1986 void h2o_errordoc_register(h2o_pathconf_t *pathconf, h2o_errordoc_t *errdocs, size_t cnt);
1987 /**
1988  *
1989  */
1990 void h2o_errordoc_register_configurator(h2o_globalconf_t *conf);
1991 
1992 /* lib/expires.c */
1993 
1994 enum { H2O_EXPIRES_MODE_ABSOLUTE, H2O_EXPIRES_MODE_MAX_AGE };
1995 
1996 typedef struct st_h2o_expires_args_t {
1997     int mode;
1998     union {
1999         const char *absolute;
2000         uint64_t max_age;
2001     } data;
2002 } h2o_expires_args_t;
2003 
2004 /**
2005  * registers a filter that adds an Expires (or Cache-Control) header
2006  */
2007 void h2o_expires_register(h2o_pathconf_t *pathconf, h2o_expires_args_t *args);
2008 /**
2009  *
2010  */
2011 void h2o_expires_register_configurator(h2o_globalconf_t *conf);
2012 
2013 /* lib/fastcgi.c */
2014 
2015 typedef struct st_h2o_fastcgi_handler_t h2o_fastcgi_handler_t;
2016 
2017 #define H2O_DEFAULT_FASTCGI_IO_TIMEOUT 30000
2018 
2019 typedef struct st_h2o_fastcgi_config_vars_t {
2020     uint64_t io_timeout;
2021     uint64_t keepalive_timeout; /* 0 to disable */
2022     h2o_iovec_t document_root;  /* .base=NULL if not set */
2023     int send_delegated_uri;     /* whether to send the rewritten HTTP_HOST & REQUEST_URI by delegation, or the original */
2024     struct {
2025         void (*dispose)(h2o_fastcgi_handler_t *handler, void *data);
2026         void *data;
2027     } callbacks;
2028 } h2o_fastcgi_config_vars_t;
2029 
2030 /**
2031  * registers the fastcgi handler to the context
2032  */
2033 h2o_fastcgi_handler_t *h2o_fastcgi_register(h2o_pathconf_t *pathconf, h2o_url_t *upstream, h2o_fastcgi_config_vars_t *vars);
2034 /**
2035  * registers the fastcgi handler to the context
2036  */
2037 h2o_fastcgi_handler_t *h2o_fastcgi_register_by_spawnproc(h2o_pathconf_t *pathconf, char **argv, h2o_fastcgi_config_vars_t *vars);
2038 /**
2039  * registers the configurator
2040  */
2041 void h2o_fastcgi_register_configurator(h2o_globalconf_t *conf);
2042 
2043 /* lib/file.c */
2044 
2045 enum {
2046     H2O_FILE_FLAG_NO_ETAG = 0x1,
2047     H2O_FILE_FLAG_DIR_LISTING = 0x2,
2048     H2O_FILE_FLAG_SEND_COMPRESSED = 0x4,
2049     H2O_FILE_FLAG_GUNZIP = 0x8
2050 };
2051 
2052 typedef struct st_h2o_file_handler_t h2o_file_handler_t;
2053 
2054 extern const char **h2o_file_default_index_files;
2055 
2056 /**
2057  * sends given file as the response to the client
2058  */
2059 int h2o_file_send(h2o_req_t *req, int status, const char *reason, const char *path, h2o_iovec_t mime_type, int flags);
2060 /**
2061  * registers a handler that serves a directory of statically-served files
2062  * @param pathconf
2063  * @param virtual_path
2064  * @param real_path
2065  * @param index_files optional NULL-terminated list of of filenames to be considered as the "directory-index"
2066  * @param mimemap the mimemap (h2o_mimemap_create is called internally if the argument is NULL)
2067  */
2068 h2o_file_handler_t *h2o_file_register(h2o_pathconf_t *pathconf, const char *real_path, const char **index_files,
2069                                       h2o_mimemap_t *mimemap, int flags);
2070 /**
2071  * registers a handler that serves a specific file
2072  * @param pathconf
2073  * @param virtual_path
2074  * @param real_path
2075  * @param index_files optional NULL-terminated list of of filenames to be considered as the "directory-index"
2076  * @param mimemap the mimemap (h2o_mimemap_create is called internally if the argument is NULL)
2077  */
2078 h2o_handler_t *h2o_file_register_file(h2o_pathconf_t *pathconf, const char *real_path, h2o_mimemap_type_t *mime_type, int flags);
2079 /**
2080  * returns the associated mimemap
2081  */
2082 h2o_mimemap_t *h2o_file_get_mimemap(h2o_file_handler_t *handler);
2083 /**
2084  * registers the configurator
2085  */
2086 void h2o_file_register_configurator(h2o_globalconf_t *conf);
2087 
2088 /* lib/headers.c */
2089 
2090 enum {
2091     H2O_HEADERS_CMD_NULL,
2092     H2O_HEADERS_CMD_ADD,                /* adds a new header line */
2093     H2O_HEADERS_CMD_APPEND,             /* adds a new header line or contenates to the existing header */
2094     H2O_HEADERS_CMD_MERGE,              /* merges the value into a comma-listed values of the named header */
2095     H2O_HEADERS_CMD_SET,                /* sets a header line, overwriting the existing one (if any) */
2096     H2O_HEADERS_CMD_SETIFEMPTY,         /* sets a header line if empty */
2097     H2O_HEADERS_CMD_UNSET,              /* removes the named header(s) */
2098     H2O_HEADERS_CMD_UNSETUNLESS,        /* only keeps the named header(s) */
2099     H2O_HEADERS_CMD_COOKIE_UNSET,       /* removes the named cookie(s) */
2100     H2O_HEADERS_CMD_COOKIE_UNSETUNLESS, /* only keeps the named cookie(s) */
2101 };
2102 
2103 typedef enum h2o_headers_command_when {
2104     H2O_HEADERS_CMD_WHEN_FINAL,
2105     H2O_HEADERS_CMD_WHEN_EARLY,
2106     H2O_HEADERS_CMD_WHEN_ALL,
2107 } h2o_headers_command_when_t;
2108 
2109 typedef struct st_h2o_headers_command_arg_t {
2110     h2o_iovec_t *name; /* maybe a token */
2111     h2o_iovec_t value;
2112 } h2o_headers_command_arg_t;
2113 
2114 struct st_h2o_headers_command_t {
2115     int cmd;
2116     h2o_headers_command_arg_t *args;
2117     size_t num_args;
2118     h2o_headers_command_when_t when;
2119 };
2120 
2121 /**
2122  * registers a list of commands terminated by cmd==H2O_HEADERS_CMD_NULL
2123  */
2124 void h2o_headers_register(h2o_pathconf_t *pathconf, h2o_headers_command_t *cmds);
2125 /**
2126  * returns whether if the given name can be registered to the filter
2127  */
2128 int h2o_headers_is_prohibited_name(const h2o_token_t *token);
2129 /**
2130  * registers the configurator
2131  */
2132 void h2o_headers_register_configurator(h2o_globalconf_t *conf);
2133 
2134 /* lib/proxy.c */
2135 
2136 typedef struct st_h2o_proxy_config_vars_t {
2137     uint64_t io_timeout;
2138     uint64_t connect_timeout;
2139     uint64_t first_byte_timeout;
2140     uint64_t keepalive_timeout;
2141     struct {
2142         uint64_t name_resolution_delay;
2143         uint64_t connection_attempt_delay;
2144     } happy_eyeballs;
2145     unsigned preserve_host : 1;
2146     unsigned use_proxy_protocol : 1;
2147     unsigned tunnel_enabled : 1;
2148     unsigned connect_proxy_status_enabled : 1;
2149     h2o_headers_command_t *headers_cmds;
2150     size_t max_buffer_size;
2151     struct {
2152         uint32_t max_concurrent_streams;
2153     } http2;
2154     h2o_httpclient_protocol_ratio_t protocol_ratio;
2155 } h2o_proxy_config_vars_t;
2156 
2157 /**
2158  * registers the reverse proxy handler to the context
2159  */
2160 void h2o_proxy_register_reverse_proxy(h2o_pathconf_t *pathconf, h2o_proxy_config_vars_t *config, h2o_socketpool_t *sockpool);
2161 /**
2162  * registers the configurator
2163  */
2164 void h2o_proxy_register_configurator(h2o_globalconf_t *conf);
2165 
2166 /* lib/redirect.c */
2167 
2168 typedef struct st_h2o_redirect_handler_t h2o_redirect_handler_t;
2169 
2170 /**
2171  * registers the redirect handler to the context
2172  * @param pathconf
2173  * @param internal whether if the redirect is internal or external
2174  * @param status status code to be sent (e.g. 301, 303, 308, ...)
2175  * @param prefix prefix of the destitation URL
2176  */
2177 h2o_redirect_handler_t *h2o_redirect_register(h2o_pathconf_t *pathconf, int internal, int status, const char *prefix);
2178 /**
2179  * registers the configurator
2180  */
2181 void h2o_redirect_register_configurator(h2o_globalconf_t *conf);
2182 
2183 /* lib/handler/reproxy.c */
2184 
2185 typedef struct st_h2o_reproxy_handler_t h2o_reproxy_handler_t;
2186 
2187 /**
2188  * registers the reproxy filter
2189  */
2190 void h2o_reproxy_register(h2o_pathconf_t *pathconf);
2191 /**
2192  * registers the configurator
2193  */
2194 void h2o_reproxy_register_configurator(h2o_globalconf_t *conf);
2195 
2196 /* lib/handler/connect.c */
2197 
2198 typedef struct st_h2o_connect_acl_entry_t {
2199     uint8_t allow_; /* true if allow, false if deny */
2200     enum { H2O_CONNECT_ACL_ADDRESS_ANY, H2O_CONNECT_ACL_ADDRESS_V4, H2O_CONNECT_ACL_ADDRESS_V6 } addr_family;
2201     union {
2202         uint32_t v4;
2203         uint8_t v6[16];
2204     } addr;
2205     size_t addr_mask;
2206     uint16_t port; /* 0 indicates ANY */
2207 } h2o_connect_acl_entry_t;
2208 
2209 /**
2210  * registers the connect handler to the context
2211  */
2212 void h2o_connect_register(h2o_pathconf_t *pathconf, h2o_proxy_config_vars_t *config, h2o_connect_acl_entry_t *acl_entries,
2213                           size_t num_acl_entries);
2214 /**
2215  * Parses a ACL line and stores the result in `output`. If successful, returns NULL, otherwise a string indicating the problem is
2216  * being returned.
2217  */
2218 const char *h2o_connect_parse_acl(h2o_connect_acl_entry_t *output, const char *input);
2219 /**
2220  * Checks if access to given target is permissible, and returns a boolean indicating the result.
2221  */
2222 int h2o_connect_lookup_acl(h2o_connect_acl_entry_t *acl_entries, size_t num_acl_entries, struct sockaddr *target);
2223 
2224 /* lib/handler/status.c */
2225 
2226 /**
2227  * registers the status handler
2228  */
2229 void h2o_status_register(h2o_pathconf_t *pathconf);
2230 /**
2231  * registers the duration handler
2232  */
2233 void h2o_duration_stats_register(h2o_globalconf_t *conf);
2234 /**
2235  * registers the configurator
2236  */
2237 void h2o_status_register_configurator(h2o_globalconf_t *conf);
2238 
2239 /* lib/handler/headers_util.c */
2240 
2241 struct headers_util_add_arg_t;
2242 
2243 /**
2244  * appends a headers command to the list
2245  */
2246 void h2o_headers_append_command(h2o_headers_command_t **cmds, int cmd, h2o_headers_command_arg_t *args, size_t num_args,
2247                                 h2o_headers_command_when_t when);
2248 /**
2249  * rewrite headers by the command provided
2250  */
2251 void h2o_rewrite_headers(h2o_mem_pool_t *pool, h2o_headers_t *headers, h2o_headers_command_t *cmd);
2252 
2253 /* lib/handler/http2_debug_state.c */
2254 
2255 /**
2256  * registers the http2 debug state handler
2257  */
2258 void h2o_http2_debug_state_register(h2o_hostconf_t *hostconf, int hpack_enabled);
2259 /**
2260  * registers the configurator
2261  */
2262 void h2o_http2_debug_state_register_configurator(h2o_globalconf_t *conf);
2263 
2264 /* lib/handler/conn_state.c */
2265 
2266 /**
2267  *
2268  */
2269 void h2o_self_trace_register(h2o_pathconf_t *conf);
2270 /**
2271  *
2272  */
2273 void h2o_self_trace_register_configurator(h2o_globalconf_t *conf);
2274 
2275 /* inline defs */
2276 
2277 #ifdef H2O_NO_64BIT_ATOMICS
2278 extern pthread_mutex_t h2o_conn_id_mutex;
2279 #endif
2280 
h2o_create_connection(size_t sz,h2o_context_t * ctx,h2o_hostconf_t ** hosts,struct timeval connected_at,const h2o_conn_callbacks_t * callbacks)2281 inline h2o_conn_t *h2o_create_connection(size_t sz, h2o_context_t *ctx, h2o_hostconf_t **hosts, struct timeval connected_at,
2282                                          const h2o_conn_callbacks_t *callbacks)
2283 {
2284     h2o_conn_t *conn = (h2o_conn_t *)h2o_mem_alloc(sz);
2285 
2286     conn->ctx = ctx;
2287     conn->hosts = hosts;
2288     conn->connected_at = connected_at;
2289 #ifdef H2O_NO_64BIT_ATOMICS
2290     pthread_mutex_lock(&h2o_conn_id_mutex);
2291     conn->id = ++h2o_connection_id;
2292     pthread_mutex_unlock(&h2o_conn_id_mutex);
2293 #else
2294     conn->id = __sync_add_and_fetch(&h2o_connection_id, 1);
2295 #endif
2296     conn->callbacks = callbacks;
2297     conn->_uuid.is_initialized = 0;
2298 
2299     return conn;
2300 }
2301 
h2o_conn_get_uuid(h2o_conn_t * conn)2302 inline const char *h2o_conn_get_uuid(h2o_conn_t *conn)
2303 {
2304     if (conn->_uuid.is_initialized)
2305         return conn->_uuid.str;
2306     h2o_generate_uuidv4(conn->_uuid.str);
2307     conn->_uuid.is_initialized = 1;
2308     return conn->_uuid.str;
2309 }
2310 
h2o_conn_is_early_data(h2o_conn_t * conn)2311 inline int h2o_conn_is_early_data(h2o_conn_t *conn)
2312 {
2313     ptls_t *tls;
2314     if (conn->callbacks->get_ptls == NULL)
2315         return 0;
2316     if ((tls = conn->callbacks->get_ptls(conn)) == NULL)
2317         return 0;
2318     if (ptls_handshake_is_complete(tls))
2319         return 0;
2320     return 1;
2321 }
2322 
h2o_proceed_response(h2o_req_t * req)2323 inline void h2o_proceed_response(h2o_req_t *req)
2324 {
2325     if (req->_generator != NULL) {
2326         req->_generator->proceed(req->_generator, req);
2327     } else {
2328         req->_ostr_top->do_send(req->_ostr_top, req, NULL, 0, H2O_SEND_STATE_FINAL);
2329     }
2330 }
2331 
h2o_req_getenv(h2o_req_t * req,const char * name,size_t name_len,int allocate_if_not_found)2332 inline h2o_iovec_t *h2o_req_getenv(h2o_req_t *req, const char *name, size_t name_len, int allocate_if_not_found)
2333 {
2334     size_t i;
2335     for (i = 0; i != req->env.size; i += 2)
2336         if (h2o_memis(req->env.entries[i].base, req->env.entries[i].len, name, name_len))
2337             return req->env.entries + i + 1;
2338     if (!allocate_if_not_found)
2339         return NULL;
2340     h2o_vector_reserve(&req->pool, &req->env, req->env.size + 2);
2341     req->env.entries[req->env.size++] = h2o_iovec_init(name, name_len);
2342     req->env.entries[req->env.size++] = h2o_iovec_init(NULL, 0);
2343     return req->env.entries + req->env.size - 1;
2344 }
2345 
h2o_req_unsetenv(h2o_req_t * req,const char * name,size_t name_len)2346 inline void h2o_req_unsetenv(h2o_req_t *req, const char *name, size_t name_len)
2347 {
2348     size_t i;
2349     for (i = 0; i != req->env.size; i += 2)
2350         if (h2o_memis(req->env.entries[i].base, req->env.entries[i].len, name, name_len))
2351             goto Found;
2352     /* not found */
2353     return;
2354 Found:
2355     memmove(req->env.entries + i, req->env.entries + i + 2, req->env.size - i - 2);
2356     req->env.size -= 2;
2357 }
2358 
h2o_send_state_is_in_progress(h2o_send_state_t s)2359 inline int h2o_send_state_is_in_progress(h2o_send_state_t s)
2360 {
2361     return s == H2O_SEND_STATE_IN_PROGRESS;
2362 }
2363 
h2o_setup_next_ostream(h2o_req_t * req,h2o_ostream_t ** slot)2364 inline void h2o_setup_next_ostream(h2o_req_t *req, h2o_ostream_t **slot)
2365 {
2366     h2o_filter_t *next;
2367 
2368     if (req->_next_filter_index < req->num_filters) {
2369         next = req->filters[req->_next_filter_index++];
2370         next->on_setup_ostream(next, req, slot);
2371     }
2372 }
2373 
h2o_setup_next_prefilter(h2o_req_prefilter_t * self,h2o_req_t * req,h2o_ostream_t ** slot)2374 inline void h2o_setup_next_prefilter(h2o_req_prefilter_t *self, h2o_req_t *req, h2o_ostream_t **slot)
2375 {
2376     h2o_req_prefilter_t *next = self->next;
2377 
2378     if (next != NULL)
2379         next->on_setup_ostream(next, req, slot);
2380     else
2381         h2o_setup_next_ostream(req, slot);
2382 }
2383 
h2o_get_timestamp(h2o_context_t * ctx,h2o_mem_pool_t * pool)2384 inline h2o_timestamp_t h2o_get_timestamp(h2o_context_t *ctx, h2o_mem_pool_t *pool)
2385 {
2386     time_t prev_sec = ctx->_timestamp_cache.tv_at.tv_sec;
2387     ctx->_timestamp_cache.tv_at = h2o_gettimeofday(ctx->loop);
2388     if (ctx->_timestamp_cache.tv_at.tv_sec != prev_sec)
2389         h2o_context_update_timestamp_string_cache(ctx);
2390 
2391     h2o_timestamp_t ts;
2392     ts.at = ctx->_timestamp_cache.tv_at;
2393     h2o_mem_link_shared(pool, ctx->_timestamp_cache.value);
2394     ts.str = ctx->_timestamp_cache.value;
2395 
2396     return ts;
2397 }
2398 
h2o_context_get_handler_context(h2o_context_t * ctx,h2o_handler_t * handler)2399 inline void *h2o_context_get_handler_context(h2o_context_t *ctx, h2o_handler_t *handler)
2400 {
2401     return ctx->_module_configs[handler->_config_slot];
2402 }
2403 
h2o_context_set_handler_context(h2o_context_t * ctx,h2o_handler_t * handler,void * handler_ctx)2404 inline void h2o_context_set_handler_context(h2o_context_t *ctx, h2o_handler_t *handler, void *handler_ctx)
2405 {
2406     ctx->_module_configs[handler->_config_slot] = handler_ctx;
2407 }
2408 
h2o_context_get_filter_context(h2o_context_t * ctx,h2o_filter_t * filter)2409 inline void *h2o_context_get_filter_context(h2o_context_t *ctx, h2o_filter_t *filter)
2410 {
2411     return ctx->_module_configs[filter->_config_slot];
2412 }
2413 
h2o_context_set_filter_context(h2o_context_t * ctx,h2o_filter_t * filter,void * filter_ctx)2414 inline void h2o_context_set_filter_context(h2o_context_t *ctx, h2o_filter_t *filter, void *filter_ctx)
2415 {
2416     ctx->_module_configs[filter->_config_slot] = filter_ctx;
2417 }
2418 
h2o_context_get_logger_context(h2o_context_t * ctx,h2o_logger_t * logger)2419 inline void *h2o_context_get_logger_context(h2o_context_t *ctx, h2o_logger_t *logger)
2420 {
2421     return ctx->_module_configs[logger->_config_slot];
2422 }
2423 
h2o_context_get_storage(h2o_context_t * ctx,size_t * key,void (* dispose_cb)(void *))2424 inline void **h2o_context_get_storage(h2o_context_t *ctx, size_t *key, void (*dispose_cb)(void *))
2425 {
2426     /* SIZE_MAX might not be available in case the file is included from a C++ source file */
2427     size_t size_max = (size_t)-1;
2428     if (*key == size_max)
2429         *key = ctx->storage.size;
2430     if (ctx->storage.size <= *key) {
2431         h2o_vector_reserve(NULL, &ctx->storage, *key + 1);
2432         memset(ctx->storage.entries + ctx->storage.size, 0, (*key + 1 - ctx->storage.size) * sizeof(ctx->storage.entries[0]));
2433         ctx->storage.size = *key + 1;
2434     }
2435 
2436     ctx->storage.entries[*key].dispose = dispose_cb;
2437     return &ctx->storage.entries[*key].data;
2438 }
2439 
h2o_context_set_logger_context(h2o_context_t * ctx,h2o_logger_t * logger,void * logger_ctx)2440 static inline void h2o_context_set_logger_context(h2o_context_t *ctx, h2o_logger_t *logger, void *logger_ctx)
2441 {
2442     ctx->_module_configs[logger->_config_slot] = logger_ctx;
2443 }
2444 
h2o_req_can_stream_request(h2o_req_t * req)2445 inline int h2o_req_can_stream_request(h2o_req_t *req)
2446 {
2447     h2o_handler_t *first_handler = h2o_get_first_handler(req);
2448     return first_handler != NULL && first_handler->supports_request_streaming;
2449 }
2450 
2451 #define COMPUTE_DURATION(name, from, until)                                                                                        \
2452     static inline int h2o_time_compute_##name(struct st_h2o_req_t *req, int64_t *delta_usec)                                       \
2453     {                                                                                                                              \
2454         if (h2o_timeval_is_null((from)) || h2o_timeval_is_null((until))) {                                                         \
2455             return 0;                                                                                                              \
2456         }                                                                                                                          \
2457         *delta_usec = h2o_timeval_subtract((from), (until));                                                                       \
2458         return 1;                                                                                                                  \
2459     }
2460 
2461 COMPUTE_DURATION(connect_time, &req->conn->connected_at, &req->timestamps.request_begin_at)
2462 COMPUTE_DURATION(header_time, &req->timestamps.request_begin_at,
2463                  h2o_timeval_is_null(&req->timestamps.request_body_begin_at) ? &req->processed_at.at
2464                                                                              : &req->timestamps.request_body_begin_at)
2465 COMPUTE_DURATION(body_time,
2466                  h2o_timeval_is_null(&req->timestamps.request_body_begin_at) ? &req->processed_at.at
2467                                                                              : &req->timestamps.request_body_begin_at,
2468                  &req->processed_at.at)
2469 COMPUTE_DURATION(request_total_time, &req->timestamps.request_begin_at, &req->processed_at.at)
2470 COMPUTE_DURATION(process_time, &req->processed_at.at, &req->timestamps.response_start_at)
2471 COMPUTE_DURATION(response_time, &req->timestamps.response_start_at, &req->timestamps.response_end_at)
2472 COMPUTE_DURATION(total_time, &req->timestamps.request_begin_at, &req->timestamps.response_end_at)
2473 
2474 COMPUTE_DURATION(proxy_idle_time, &req->timestamps.request_begin_at, &req->proxy_stats.timestamps.start_at)
2475 COMPUTE_DURATION(proxy_connect_time, &req->proxy_stats.timestamps.start_at, &req->proxy_stats.timestamps.request_begin_at)
2476 COMPUTE_DURATION(proxy_request_time, &req->proxy_stats.timestamps.request_begin_at, &req->proxy_stats.timestamps.request_end_at)
2477 COMPUTE_DURATION(proxy_process_time, &req->proxy_stats.timestamps.request_end_at, &req->proxy_stats.timestamps.response_start_at)
2478 COMPUTE_DURATION(proxy_response_time, &req->proxy_stats.timestamps.response_start_at, &req->proxy_stats.timestamps.response_end_at)
2479 COMPUTE_DURATION(proxy_total_time, &req->proxy_stats.timestamps.request_begin_at, &req->proxy_stats.timestamps.response_end_at)
2480 
2481 #undef COMPUTE_DURATION
2482 
2483 #ifdef __cplusplus
2484 }
2485 #endif
2486 
2487 #endif
2488