xref: /lighttpd1.4/src/h2.c (revision f2e4e83a)
1 /*
2  * h2 - HTTP/2 protocol layer
3  *
4  * Copyright(c) 2020 Glenn Strauss gstrauss()gluelogic.com  All rights reserved
5  * License: BSD 3-clause (same as lighttpd)
6  */
7 #include "first.h"
8 #include "h2.h"
9 
10 #include <arpa/inet.h>  /* htonl() */
11 #include <stdint.h>     /* INT32_MAX INT32_MIN */
12 #include <stdlib.h>
13 #include <string.h>
14 
15 #include "base.h"
16 #include "buffer.h"
17 #include "chunk.h"
18 #include "fdevent.h"    /* FDEVENT_STREAM_REQUEST_BUFMIN */
19 #include "http_header.h"
20 #include "log.h"
21 #include "request.h"
22 #include "response.h"   /* http_response_omit_header() */
23 
24 
25 static request_st * h2_init_stream (request_st * const h2r, connection * const con);
26 
27 
28 static void
29 h2_send_settings_ack (connection * const con)
30 {
31     static const uint8_t settings_ack[] = {
32       /* SETTINGS w/ ACK */
33       0x00, 0x00, 0x00        /* frame length */
34      ,H2_FTYPE_SETTINGS       /* frame type */
35      ,H2_FLAG_ACK             /* frame flags */
36      ,0x00, 0x00, 0x00, 0x00  /* stream identifier */
37     };
38 
39     chunkqueue_append_mem(con->write_queue,
40                           (const char *)settings_ack, sizeof(settings_ack));
41 }
42 
43 
44 __attribute_cold__
45 static void
46 h2_send_rst_stream_id (uint32_t h2id, connection * const con, const request_h2error_t e)
47 {
48     union {
49       uint8_t c[16];
50       uint32_t u[4];          /*(alignment)*/
51     } rst_stream = { {        /*(big-endian numbers)*/
52       0x00, 0x00, 0x00        /* padding for alignment; do not send */
53       /* RST_STREAM */
54      ,0x00, 0x00, 0x04        /* frame length */
55      ,H2_FTYPE_RST_STREAM     /* frame type */
56      ,0x00                    /* frame flags */
57      ,0x00, 0x00, 0x00, 0x00  /* stream identifier (fill in below) */
58      ,0x00, 0x00, 0x00, 0x00  /* error code;       (fill in below) */
59     } };
60 
61     rst_stream.u[2] = htonl(h2id);
62     rst_stream.u[3] = htonl(e);
63     chunkqueue_append_mem(con->write_queue,  /*(+3 to skip over align padding)*/
64                           (const char *)rst_stream.c+3, sizeof(rst_stream)-3);
65 }
66 
67 
68 __attribute_cold__
69 static void
70 h2_send_rst_stream (request_st * const r, connection * const con, const request_h2error_t e)
71 {
72     r->h2state = H2_STATE_CLOSED;
73     h2_send_rst_stream_id(r->h2id, con, e);
74 }
75 
76 
77 __attribute_cold__
78 static void
79 h2_send_goaway_rst_stream (connection * const con)
80 {
81     h2con * const h2c = con->h2;
82     const int sent_goaway = h2c->sent_goaway;
83     for (uint32_t i = 0, rused = h2c->rused; i < rused; ++i) {
84         request_st * const r = h2c->r[i];
85         if (r->h2state == H2_STATE_CLOSED) continue;
86         /*(XXX: might consider always sending RST_STREAM)*/
87         if (!sent_goaway)
88             r->h2state = H2_STATE_CLOSED;
89         else /*(also sets r->h2state = H2_STATE_CLOSED)*/
90             h2_send_rst_stream(r, con, H2_E_PROTOCOL_ERROR);
91     }
92 }
93 
94 
95 void
96 h2_send_goaway (connection * const con, const request_h2error_t e)
97 {
98     /* future: RFC 7540 Section 6.8 notes that server initiating graceful
99      * connection shutdown SHOULD send GOAWAY with stream id 2^31-1 and a
100      * NO_ERROR code, and later send another GOAWAY with an updated last
101      * stream identifier.  (This is not done here, but doing so would be
102      * friendlier to clients that send streaming requests which the client
103      * is unable to retry.) */
104 
105     if (e != H2_E_NO_ERROR)
106         h2_send_goaway_rst_stream(con);
107     /*XXX: else should send RST_STREAM w/ CANCEL for any active PUSH_PROMISE */
108 
109     h2con * const h2c = con->h2;
110     if (h2c->sent_goaway && (h2c->sent_goaway > 0 || e == H2_E_NO_ERROR))
111         return;
112     h2c->sent_goaway = (e == H2_E_NO_ERROR) ? -1 : (int32_t)e;
113 
114     union {
115       uint8_t c[20];
116       uint32_t u[5];          /*(alignment)*/
117     } goaway = { {            /*(big-endian numbers)*/
118       0x00, 0x00, 0x00        /* padding for alignment; do not send */
119       /* GOAWAY */
120      ,0x00, 0x00, 0x08        /* frame length */
121      ,H2_FTYPE_GOAWAY         /* frame type */
122      ,0x00                    /* frame flags */
123      ,0x00, 0x00, 0x00, 0x00  /* stream identifier */
124      ,0x00, 0x00, 0x00, 0x00  /* last-stream-id (fill in below) */
125      ,0x00, 0x00, 0x00, 0x00  /* error code     (fill in below) */
126                               /* additional debug data (*); (optional)
127                                * adjust frame length if any additional
128                                * debug data is sent */
129     } };
130 
131     goaway.u[3] = htonl(h2c->h2_cid); /* last-stream-id */
132     goaway.u[4] = htonl(e);
133     chunkqueue_append_mem(con->write_queue,  /*(+3 to skip over align padding)*/
134                           (const char *)goaway.c+3, sizeof(goaway)-3);
135 }
136 
137 
138 __attribute_cold__
139 static void
140 h2_send_goaway_e (connection * const con, const request_h2error_t e)
141 {
142     h2_send_goaway(con, e);
143 }
144 
145 
146 static int
147 h2_recv_goaway (connection * const con, const uint8_t * const s, uint32_t len)
148 {
149     /*(s must be entire GOAWAY frame and len the frame length field)*/
150     /*assert(s[3] == H2_FTYPE_GOAWAY);*/
151     UNUSED(len);
152     if ((s[5] & ~0x80) | s[6] | s[7] | s[8]) { /*(GOAWAY stream id must be 0)*/
153         h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
154         return 0;
155     }
156     const uint32_t e = (s[13]<< 24) | (s[14]<< 16) | (s[15]<< 8) | s[16];
157   #if 0
158     /* XXX: debug: could log error code sent by peer */
159   #endif
160   #if 0
161     /* XXX: debug: could log additional debug info (if any) sent by peer */
162     if (len > 8) {
163     }
164   #endif
165   #if 0
166     /* XXX: could validate/use Last-Stream-ID sent by peer */
167     const uint32_t last_id = (s[9] << 24) | (s[10]<< 16) | (s[11]<< 8) | s[12];
168   #endif
169 
170     /* send PROTOCOL_ERROR back to peer if peer sent an error code
171      * (i.e. not NO_ERROR) in order to terminate connection more quickly */
172     h2_send_goaway(con, e==H2_E_NO_ERROR ? H2_E_NO_ERROR : H2_E_PROTOCOL_ERROR);
173     h2con * const h2c = con->h2;
174     if (0 == h2c->rused) return 0;
175     return 1;
176 }
177 
178 
179 static void
180 h2_recv_rst_stream (connection * const con, const uint8_t * const s, const uint32_t len)
181 {
182     /*(s must be entire RST_STREAM frame and len the frame length field)*/
183     /*assert(s[3] == H2_FTYPE_RST_STREAM);*/
184     if (4 != len) {                  /*(RST_STREAM frame length must be 4)*/
185         h2_send_goaway_e(con, H2_E_FRAME_SIZE_ERROR);
186         return;
187     }
188     const uint32_t id =
189       ((s[5] << 24) | (s[6] << 16) | (s[7] << 8) | s[8]) & ~0x80000000u;
190     if (0 == id) {                   /*(RST_STREAM id must not be 0)*/
191         h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
192         return;
193     }
194     h2con * const h2c = con->h2;
195     for (uint32_t i = 0, rused = h2c->rused; i < rused; ++i) {
196         request_st * const r = h2c->r[i];
197         if (r->h2id != id) continue;
198         if (r->h2state == H2_STATE_IDLE) {
199             /*(RST_STREAM must not be for stream in "idle" state)*/
200             h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
201             return;
202         }
203         /* XXX: ? add debug trace including error code from RST_STREAM ? */
204         r->h2state = H2_STATE_CLOSED;
205         return;
206     }
207     /* unknown/inactive stream id
208      * XXX: how should we handle RST_STREAM for unknown/inactive stream id?
209      * (stream id may have been closed recently and server forgot about it,
210      *  but client (peer) sent RST_STREAM prior to receiving stream end from
211      *  server)*/
212   #if 0
213     if (h2c->sent_goaway && h2c->h2_cid < id) return;
214     h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
215   #else
216     if (h2c->h2_cid < id) {
217         h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
218         return;
219     }
220   #endif
221 }
222 
223 
224 static void
225 h2_recv_ping (connection * const con, uint8_t * const s, const uint32_t len)
226 {
227   #if 0
228     union {
229       uint8_t c[20];
230       uint32_t u[5];          /*(alignment)*/
231     } ping = { {              /*(big-endian numbers)*/
232       0x00, 0x00, 0x00        /* padding for alignment; do not send */
233       /* PING */
234      ,0x00, 0x00, 0x08        /* frame length */
235      ,H2_FTYPE_PING           /* frame type */
236      ,H2_FLAG_ACK             /* frame flags */
237      ,0x00, 0x00, 0x00, 0x00  /* stream identifier */
238      ,0x00, 0x00, 0x00, 0x00  /* opaque            (fill in below) */
239      ,0x00, 0x00, 0x00, 0x00
240     } };
241   #endif
242 
243     /*(s must be entire PING frame and len the frame length field)*/
244     /*assert(s[3] == H2_FTYPE_PING);*/
245     if (8 != len) {                  /*(PING frame length must be 8)*/
246         h2_send_goaway_e(con, H2_E_FRAME_SIZE_ERROR);
247         return;
248     }
249     s[5] &= ~0x80; /* reserved bit must be ignored */
250     if (s[5] | s[6] | s[7] | s[8]) { /*(PING stream id must be 0)*/
251         h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
252         return;
253     }
254     if (s[4] & H2_FLAG_ACK) /*(ignore; unexpected if we did not send PING)*/
255         return;
256     /* reflect PING back to peer with frame flag ACK */
257     /* (9 byte frame header plus 8 byte PING payload = 17 bytes)*/
258     s[4] = H2_FLAG_ACK;
259     chunkqueue_append_mem(con->write_queue, (const char *)s, 17);
260 }
261 
262 
263 static void
264 h2_recv_priority (connection * const con, const uint8_t * const s, const uint32_t len)
265 {
266     /*(s must be entire PRIORITY frame and len the frame length field)*/
267     /*assert(s[3] == H2_FTYPE_PRIORITY);*/
268     if (5 != len) {                  /*(PRIORITY frame length must be 5)*/
269         h2_send_goaway_e(con, H2_E_FRAME_SIZE_ERROR);
270         return;
271     }
272     const uint32_t id =
273       ((s[5] << 24) | (s[6] << 16) | (s[7] << 8) | s[8]) & ~0x80000000u;
274     if (0 == id) {                   /*(PRIORITY id must not be 0)*/
275         h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
276         return;
277     }
278     const uint32_t prio =
279       ((s[9] << 24) | (s[10] << 16) | (s[11] << 8) | s[12]) & ~0x80000000u;
280   #if 0
281     uint32_t exclusive_dependency = (s[9] & 0x80) ? 1 : 0;
282     uint32_t weight = s[13];
283   #endif
284     h2con * const h2c = con->h2;
285     for (uint32_t i = 0, rused = h2c->rused; i < rused; ++i) {
286         request_st * const r = h2c->r[i];
287         if (r->h2id != id) continue;
288         /* XXX: TODO: update priority info */
289         if (prio == id) {
290             h2_send_rst_stream(r, con, H2_E_PROTOCOL_ERROR);
291             return;
292         }
293         return;
294     }
295     /* XXX: TODO: update priority info for unknown/inactive stream */
296     /*if (h2c->sent_goaway && h2c->h2_cid < id) return;*/
297     if (prio == id) {
298         h2_send_rst_stream_id(id, con, H2_E_PROTOCOL_ERROR);
299         return;
300     }
301 }
302 
303 
304 static void
305 h2_recv_window_update (connection * const con, const uint8_t * const s, const uint32_t len)
306 {
307     /*(s must be entire WINDOW_UPDATE frame and len the frame length field)*/
308     /*assert(s[3] == H2_FTYPE_WINDOW_UPDATE);*/
309     if (4 != len) {                  /*(WINDOW_UPDATE frame length must be 4)*/
310         h2_send_goaway_e(con, H2_E_FRAME_SIZE_ERROR);
311         return;
312     }
313     const uint32_t id =
314       ((s[5] << 24) | (s[6] << 16) | (s[7] << 8) | s[8]) & ~0x80000000u;
315     const int32_t v =
316       (int32_t)(((s[9] << 24)|(s[10] << 16)|(s[11] << 8)|s[12]) & ~0x80000000);
317     request_st *r = NULL;
318     if (0 == id)
319         r = &con->request;
320     else {
321         h2con * const h2c = con->h2;
322         for (uint32_t i = 0, rused = h2c->rused; i < rused; ++i) {
323             request_st * const rr = h2c->r[i];
324             if (rr->h2id != id) continue;
325             r = rr;
326             break;
327         }
328         /* peer should not send WINDOW_UPDATE for an inactive stream,
329          * but RFC 7540 does not explicitly call this out.  On the other hand,
330          * since there may be a temporary mismatch in stream state between
331          * peers, ignore window update if stream id is unknown/inactive.
332          * Also, it is not an error if GOAWAY sent and h2c->h2_cid < id */
333         if (NULL == r) {
334             if (h2c->h2_cid < id && 0 == h2c->sent_goaway)
335                 h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
336           #if 0
337             /*(needed for h2spec if testing with response < 16k+1 over TLS
338              * or response <= socket send buffer size over cleartext, due to
339              * completing response too quickly for the test frame sequence) */
340             if (v == 0)        /* h2spec: 6.9-2   (after we retired id 1) */
341                 h2_send_rst_stream_id(id, con, H2_E_PROTOCOL_ERROR);
342             if (v == INT32_MAX)/* h2spec: 6.9.1-3 (after we retired id 1) */
343                 h2_send_rst_stream_id(id, con, H2_E_FLOW_CONTROL_ERROR);
344           #endif
345             return;
346         }
347         /* MUST NOT be treated as error if stream is in closed state; ignore */
348         if (r->h2state == H2_STATE_CLOSED
349             || r->h2state == H2_STATE_HALF_CLOSED_LOCAL) return;
350     }
351     if (0 == v || r->h2_swin > INT32_MAX - v) {
352         request_h2error_t e = (0 == v)
353           ? H2_E_PROTOCOL_ERROR
354           : H2_E_FLOW_CONTROL_ERROR;
355         if (0 == id)
356             h2_send_goaway_e(con, e);
357         else
358             h2_send_rst_stream(r, con, e);
359         return;
360     }
361     r->h2_swin += v;
362 }
363 
364 
365 static void
366 h2_send_window_update (connection * const con, uint32_t h2id, const uint32_t len)
367 {
368     if (0 == len) return;
369     union {
370       uint8_t c[16];
371       uint32_t u[4];          /*(alignment)*/
372     } window_upd = { {        /*(big-endian numbers)*/
373       0x00, 0x00, 0x00        /* padding for alignment; do not send */
374       /* WINDOW_UPDATE */
375      ,0x00, 0x00, 0x04        /* frame length */
376      ,H2_FTYPE_WINDOW_UPDATE  /* frame type */
377      ,0x00                    /* frame flags */
378      ,0x00, 0x00, 0x00, 0x00  /* stream identifier      (fill in below) */
379      ,0x00, 0x00, 0x00, 0x00  /* window update increase (fill in below) */
380     } };
381 
382     window_upd.u[2] = htonl(h2id);
383     window_upd.u[3] = htonl(len);
384     chunkqueue_append_mem(con->write_queue,  /*(+3 to skip over align padding)*/
385                           (const char *)window_upd.c+3, sizeof(window_upd)-3);
386 }
387 
388 
389 static void
390 h2_parse_frame_settings (connection * const con, const uint8_t *s, uint32_t len)
391 {
392     /*(s and len must be SETTINGS frame payload)*/
393     /*(caller must validate frame len, frame type == 0x04, frame id == 0)*/
394     h2con * const h2c = con->h2;
395     for (; len >= 6; len -= 6, s += 6) {
396         uint32_t v = (s[2] << 24) | (s[3] << 16) | (s[4] << 8) | s[5];
397         switch (((s[0] << 8) | s[1])) {
398           case H2_SETTINGS_HEADER_TABLE_SIZE:
399             /* encoder may use any table size <= value sent by peer */
400             /* For simple compliance with RFC and constrained memory use,
401              * choose to not increase table size beyond the default 4096,
402              * but allow smaller sizes to be set and then reset up to 4096,
403              * e.g. set to 0 to evict all dynamic table entries,
404              * and then set to 4096 to restore dynamic table use */
405             if (v > 4096) v = 4096;
406             if (v == h2c->s_header_table_size) break;
407             h2c->s_header_table_size = v;
408             lshpack_enc_set_max_capacity(&h2c->encoder, v);
409             break;
410           case H2_SETTINGS_ENABLE_PUSH:
411             if ((v|1) != 1) { /*(v == 0 || v == 1)*/
412                 h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
413                 return;
414             }
415             h2c->s_enable_push = v;
416             break;
417           case H2_SETTINGS_MAX_CONCURRENT_STREAMS:
418             h2c->s_max_concurrent_streams = v;
419             break;
420           case H2_SETTINGS_INITIAL_WINDOW_SIZE:
421             if (v > INT32_MAX) { /*(2^31 - 1)*/
422                 h2_send_goaway_e(con, H2_E_FLOW_CONTROL_ERROR);
423                 return;
424             }
425             else if (h2c->rused) { /*(update existing streams)*/
426                 /*(underflow is ok; unsigned integer math)*/
427                 /*(h2c->s_initial_window_size is >= 0)*/
428                 int32_t diff =
429                   (int32_t)((uint32_t)v - (uint32_t)h2c->s_initial_window_size);
430                 for (uint32_t i = 0, rused = h2c->rused; i < rused; ++i) {
431                     request_st * const r = h2c->r[i];
432                     const int32_t swin = r->h2_swin;
433                     if (r->h2state == H2_STATE_HALF_CLOSED_LOCAL
434                         || r->h2state == H2_STATE_CLOSED) continue;
435                     if (diff >= 0
436                         ? swin > INT32_MAX - diff
437                         : swin < INT32_MIN - diff) {
438                         h2_send_rst_stream(r, con, H2_E_FLOW_CONTROL_ERROR);
439                         continue;
440                     }
441                     r->h2_swin += diff;
442                 }
443             }
444             h2c->s_initial_window_size = (int32_t)v;
445             break;
446           case H2_SETTINGS_MAX_FRAME_SIZE:
447             if (v < 16384 || v > 16777215) { /*[(2^14),(2^24-1)]*/
448                 h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
449                 return;
450             }
451             h2c->s_max_frame_size = v;
452             break;
453           case H2_SETTINGS_MAX_HEADER_LIST_SIZE:
454             h2c->s_max_header_list_size = v;
455             break;
456           default:
457             break;
458         }
459     }
460 
461     if (len) {
462         h2_send_goaway_e(con, H2_E_FRAME_SIZE_ERROR);
463         return;
464     }
465 
466     /* caller must send SETTINGS frame with ACK flag,
467      * if appropriate, and if h2c->sent_goaway is not set
468      * (Do not send ACK for Upgrade: h2c and HTTP2-Settings header) */
469 }
470 
471 
472 static void
473 h2_recv_settings (connection * const con, const uint8_t * const s, const uint32_t len)
474 {
475     /*(s must be entire SETTINGS frame, len must be the frame length field)*/
476     /*assert(s[3] == H2_FTYPE_SETTINGS);*/
477     if ((s[5] & ~0x80) | s[6] | s[7] | s[8]) {/*(SETTINGS stream id must be 0)*/
478         h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
479         return;
480     }
481 
482     h2con * const h2c = con->h2;
483     if (!(s[4] & H2_FLAG_ACK)) {
484         h2_parse_frame_settings(con, s+9, len);
485         if (h2c->sent_goaway <= 0)
486             h2_send_settings_ack(con);
487     }
488     else {
489         /* lighttpd currently sends SETTINGS in server preface, and not again,
490          * so this does not have to handle another SETTINGS frame being sent
491          * before receiving an ACK from prior SETTINGS frame.  (If it does,
492          * then we will need some sort of counter.) */
493         if (0 != len)
494             h2_send_goaway_e(con, H2_E_FRAME_SIZE_ERROR);
495         else if (h2c->sent_settings)
496             h2c->sent_settings = 0;
497         else /* SETTINGS with ACK for SETTINGS frame we did not send */
498             h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
499     }
500 }
501 
502 
503 static int
504 h2_recv_end_data (request_st * const r, connection * const con, const uint32_t alen)
505 {
506     chunkqueue * const reqbody_queue = r->reqbody_queue;
507     r->h2state = (r->h2state == H2_STATE_OPEN)
508       ? H2_STATE_HALF_CLOSED_REMOTE
509       : H2_STATE_CLOSED;
510     if (r->reqbody_length == -1)
511         r->reqbody_length = reqbody_queue->bytes_in + (off_t)alen;
512     else if (r->reqbody_length != reqbody_queue->bytes_in + (off_t)alen) {
513         if (0 == reqbody_queue->bytes_out) {
514             h2_send_rst_stream(r, con, H2_E_PROTOCOL_ERROR);
515             return 0;
516         } /* else let reqbody streaming consumer handle truncated reqbody */
517     }
518 
519     return 1;
520 }
521 
522 
523 static int
524 h2_recv_data (connection * const con, const uint8_t * const s, const uint32_t len)
525 {
526     /*(s must be entire DATA frame, len must be the frame length field)*/
527     /*assert(s[3] == H2_FTYPE_DATA);*/
528 
529     /* future: consider string refs rather than copying DATA from chunkqueue
530      * or try to consume entire chunk, or to split chunks with less copying */
531 
532     h2con * const h2c = con->h2;
533     const uint32_t id =
534       ((s[5] << 24) | (s[6] << 16) | (s[7] << 8) | s[8]) & ~0x80000000u;
535     if (0 == id || h2c->h2_cid < id) { /*(RST_STREAM id must not be 0)*/
536         h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
537         return 0;
538     }
539 
540     uint32_t alen = len; /* actual data len, minus padding */
541     uint32_t pad = 0;
542     if (s[4] & H2_FLAG_PADDED) {
543         pad = s[9];
544         if (pad >= len) {
545             h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
546             return 0;
547         }
548         alen -= (1 + pad);
549     }
550 
551     request_st * const h2r = &con->request;
552     if (h2r->h2_rwin <= 0 && 0 != alen) { /*(always proceed if 0 == alen)*/
553         /*(connection_state_machine_h2() must ensure con is rescheduled,
554          * when backends consume data if con->read_queue is not empty,
555          * whether or not con->fd has data to read from the network)*/
556         /*(leave frame in cq to be re-read later)*/
557         return 0;
558     }
559     /*(allow h2r->h2_rwin to dip below 0 so that entire frame is processed)*/
560     /*(not worried about underflow while
561      * SETTINGS_MAX_FRAME_SIZE is small (e.g. 16k or 32k) and
562      * SETTINGS_MAX_CONCURRENT_STREAMS is small (h2c->r[8]))*/
563     /*h2r->h2_rwin -= (int32_t)len;*//* update connection recv window (below) */
564 
565     request_st *r = NULL;
566     for (uint32_t i = 0, rused = h2c->rused; i < rused; ++i) {
567         request_st * const rr = h2c->r[i];
568         if (rr->h2id != id) continue;
569         r = rr;
570         break;
571     }
572     chunkqueue * const cq = con->read_queue;
573     if (NULL == r) {
574         /* XXX: TODO: might need to keep a list of recently retired streams
575          * for a few seconds so that if we send RST_STREAM, then we ignore
576          * further DATA and do not send connection error, though recv windows
577          * still must be updated. */
578         if (h2c->h2_cid < id || (!h2c->sent_goaway && 0 != alen))
579             h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
580         chunkqueue_mark_written(cq, 9+len);
581         return 0;
582     }
583 
584     if (r->h2state == H2_STATE_CLOSED
585         || r->h2state == H2_STATE_HALF_CLOSED_REMOTE) {
586         h2_send_rst_stream_id(id, con, H2_E_STREAM_CLOSED);
587         chunkqueue_mark_written(cq, 9+len);
588         h2_send_window_update(con, 0, len); /*(h2r->h2_rwin)*/
589         return 1;
590     }
591 
592     if (r->h2_rwin <= 0 && 0 != alen) {/*(always proceed if 0==alen)*/
593         if (r->conf.stream_request_body & FDEVENT_STREAM_REQUEST_BUFMIN) {
594             /*(connection_state_machine_h2() must ensure con is rescheduled,
595              * when backends consume data if con->read_queue is not empty,
596              * whether or not con->fd has data to read from the network)*/
597             /*(leave frame in cq to be re-read later)*/
598             return 0;
599         }
600     }
601     /*(allow h2r->h2_rwin to dip below 0 so that entire frame is processed)*/
602     /*(undeflow will not occur (with reasonable SETTINGS_MAX_FRAME_SIZE used)
603      * since windows updated elsewhere and data is streamed to temp files if
604      * not FDEVENT_STREAM_REQUEST_BUFMIN)*/
605     /*r->h2_rwin -= (int32_t)len;*/
606     h2_send_window_update(con, r->h2id, len); /*(r->h2_rwin)*/
607     h2_send_window_update(con, 0, len);       /*(h2r->h2_rwin)*/
608 
609     chunkqueue * const dst = r->reqbody_queue;
610 
611     if (r->reqbody_length >= 0 && r->reqbody_length < dst->bytes_in + alen) {
612         /* data exceeds Content-Length specified (client mistake) */
613       #if 0 /* truncate */
614         alen = r->reqbody_length - dst->bytes_in;
615         /*(END_STREAM may follow in 0-length DATA frame or HEADERS (trailers))*/
616       #else /* reject */
617         h2_send_rst_stream(r, con, H2_E_PROTOCOL_ERROR);
618         chunkqueue_mark_written(cq, 9+len);
619         return 1;
620       #endif
621     }
622 
623     /*(accounting for mod_accesslog and mod_rrdtool)*/
624     chunkqueue * const rq = r->read_queue;
625     rq->bytes_in  += (off_t)alen;
626     rq->bytes_out += (off_t)alen;
627 
628     /* r->conf.max_request_size is in kBytes */
629     const off_t max_request_size = (off_t)r->conf.max_request_size << 10;
630     if (0 != max_request_size
631         && dst->bytes_in + (off_t)alen > max_request_size) {
632         if (0 == r->http_status) {
633             r->http_status = 413; /* Payload Too Large */
634             log_error(r->conf.errh, __FILE__, __LINE__,
635               "request-size too long: %lld -> 413",
636               (long long) (dst->bytes_in + (off_t)alen));
637         }
638         chunkqueue_mark_written(cq, 9+len);
639         return 1;
640     }
641 
642     if ((s[4] & H2_FLAG_END_STREAM) && !h2_recv_end_data(r, con, alen)) {
643         chunkqueue_mark_written(cq, 9+len);
644         return 1;
645     }
646 
647     chunkqueue_mark_written(cq, 9 + ((s[4] & H2_FLAG_PADDED) ? 1 : 0));
648 
649   #if 0
650     if (pad) {
651         /* XXX: future optimization: if data is at end of chunk, then adjust
652          * size of chunk by reducing c->mem->used to avoid copying chunk
653          * when it is split (below) since the split would be due to padding
654          * (also adjust cq->bytes_out)*/
655         /*(might quickly check 9+len == cqlen if cqlen passed in as param)*/
656         /*(then check if cq->last contains all of padding, or leave alone)*/
657         /*(if handled here, then set pad = 0 here)*/
658     }
659   #endif
660 
661     /*(similar decision logic to that in http_chunk_uses_tempfile())*/
662     const chunk * const c = dst->last;
663     if ((c && c->type == FILE_CHUNK && c->file.is_temp)
664         || dst->bytes_in - dst->bytes_out + alen > 65536) {
665         log_error_st * const errh = r->conf.errh;
666         if (0 != chunkqueue_steal_with_tempfiles(dst, cq, (off_t)alen, errh)) {
667             h2_send_rst_stream(r, con, H2_E_INTERNAL_ERROR);
668             return 0;
669         }
670     }
671     else
672         chunkqueue_steal(dst, cq, (off_t)alen);
673 
674     if (pad)
675         chunkqueue_mark_written(cq, pad);
676     return 1;
677 }
678 
679 
680 __attribute_cold__
681 static uint32_t
682 h2_frame_cq_compact (chunkqueue * const cq, uint32_t len)
683 {
684     /*(marked cold since most frames not expect to cross chunk boundary)*/
685 
686     /*(must be guaranteed by caller)*/
687         /*assert(chunkqueue_length(cq) >= len);*/
688         /*assert(cq->first != cq->last);*//*(multiple chunks)*/
689     /* caller must guarantee that chunks in chunkqueue are all MEM_CHUNK */
690 
691     /* move data to beginning of buffer if offset is large or data is short */
692     chunk *c = cq->first;
693     uint32_t mlen = buffer_string_length(c->mem);
694     if (mlen < c->offset) {
695         memmove(c->mem->ptr, c->mem->ptr + c->offset, mlen);
696         buffer_string_set_length(c->mem, mlen);
697         c->offset = 0;
698     }
699 
700     /* combine first mem chunk with next non-empty mem chunks up to len
701      * (loop if next chunk is empty) */
702     /* (modified from connection_handle_read_post_cq_compact()) */
703     uint32_t clen = mlen;
704     do {
705         buffer * const mem = c->next->mem;
706         const off_t offset = c->next->offset;
707         mlen = buffer_string_length(mem) - (uint32_t)offset;
708         force_assert(c->type == MEM_CHUNK);
709         force_assert(c->next->type == MEM_CHUNK);
710         if (mlen > clen - len) {
711             mlen = clen - len;
712             buffer_append_string_len(c->mem, mem->ptr+offset, mlen);
713             c->next->offset += mlen;
714             return len;
715         }
716 
717         buffer_append_string_len(c->mem, mem->ptr+offset, mlen);
718         clen += mlen;
719         /*(swap first and second chunk, then remove first chunk)*/
720         c->next->offset = c->offset;
721         c->next->mem = c->mem;
722         c->mem = mem;
723         c->offset = offset + (off_t)mlen;
724         chunkqueue_remove_finished_chunks(cq);
725     } while ((c = cq->first)); /*(need to re-read cq->first)*/
726     return clen;
727 }
728 
729 
730 __attribute_cold__
731 static uint32_t
732 h2_recv_continuation (uint32_t n, uint32_t clen, const off_t cqlen, chunkqueue * const cq, connection * const con)
733 {
734     chunk *c = cq->first;
735     uint8_t *s = (uint8_t *)(c->mem->ptr + c->offset);
736     uint32_t m = n;
737     uint32_t flags;
738     h2con * const h2c = con->h2;
739     const uint32_t fsize = h2c->s_max_frame_size;
740     const uint32_t id =
741       ((s[5] << 24) | (s[6] << 16) | (s[7] << 8) | s[8]) & ~0x80000000u;
742     do {
743         if (cqlen < n+9) return n+9; /* incomplete frame; go on */
744         if (clen < n+9) {
745             clen = h2_frame_cq_compact(cq, n+9);
746             c = cq->first; /*(reload after h2_frame_cq_compact())*/
747             s = (uint8_t *)(c->mem->ptr + c->offset);
748         }
749         if (s[n+3] != H2_FTYPE_CONTINUATION) {
750             h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
751             return 0;
752         }
753         flags = s[n+4];
754         const uint32_t flen = (s[n+0]<<16)|(s[n+1]<<8)|s[n+2];
755         if (id != (uint32_t)((s[n+5]<<24)|(s[n+6]<<16)|(s[n+7]<<8)|s[n+8])) {
756             h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
757             return 0;
758         }
759         if (flen > fsize) {
760             h2_send_goaway_e(con, H2_E_FRAME_SIZE_ERROR);
761             return 0;
762         }
763         n += 9+flen;
764         if (n >= 65536) { /*(very oversized for hpack)*/
765             h2_send_goaway_e(con, H2_E_FRAME_SIZE_ERROR);
766             return 0;
767         }
768         if (clen < n) {
769             clen = h2_frame_cq_compact(cq, n);
770             c = cq->first; /*(reload after h2_frame_cq_compact())*/
771             s = (uint8_t *)(c->mem->ptr + c->offset);
772         }
773     } while (!(flags & H2_FLAG_END_HEADERS));
774 
775     /* If some CONTINUATION frames were concatenated to earlier frames while
776      * processing above, but END_HEADERS were not received, then the next time
777      * data was read, initial frame size might exceed SETTINGS_MAX_FRAME_SIZE.
778      * (This describes the current lighttpd implementation in h2_parse_frames())
779      * While a flag could be set and checked to avoid this, such situations of
780      * large HEADERS (and CONTINUATION) across multiple network reads is
781      * expected to be rare.  Reparse and concatenate below.
782      *
783      * Aside: why would the authors of RFC 7540 go through the trouble of
784      * creating a CONTINUATION frame that must be special-cased when use of
785      * CONTINUATION is so restricted e.g. no other intervening frames and
786      * that HEADERS and PUSH_PROMISE HPACK must be parsed as a single block?
787      * IMHO, it would have been simpler to avoid CONTINUATION entirely, and have
788      * a special-case for HEADERS and PUSH_PROMISE to be allowed to exceed
789      * SETTINGS_MAX_FRAME_SIZE with implementations providing a different limit.
790      * While intermediates would not know such a limit of origin servers,
791      * there could have been a reasonable default set with a different SETTINGS
792      * parameter aimed just at HEADERS and PUSH_PROMISE.  The parameter
793      * SETTINGS_MAX_HEADER_LIST_SIZE could even have been (re)used, had it been
794      * given a reasonable initial value instead of "unlimited", since HPACK
795      * encoded headers are smaller than the HPACK decoded headers to which the
796      * limit SETTINGS_MAX_HEADER_LIST_SIZE applies. */
797 
798     n = m; /* reset n to beginning of first CONTINUATION frame */
799 
800     /* Eliminate padding from first frame (HEADERS or PUSH_PROMISE) if PADDED */
801     if (s[4] & H2_FLAG_PADDED) {
802         const uint32_t plen = s[9];
803         /* validate padding */
804         const uint32_t flen = (s[0]<<16)|(s[1]<<8)|s[2];
805         if (flen < 1 + plen + ((s[n+4] & H2_FLAG_PRIORITY) ? 5 : 0)) {
806             /* Padding that exceeds the size remaining for the header block
807              * fragment MUST be treated as a PROTOCOL_ERROR. */
808             h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
809             return 0;
810         }
811         /* set padding to 0 since we will overwrite padding in merge below */
812         /* (alternatively, could memmove() 9 bytes of frame header over the
813          *  pad length octet, remove PADDED flag, add 1 to c->offset,
814          *  add 1 to s, subtract 1 from clen and substract 1 from cqlen,
815          *  substract 1 from n) */
816         s[9] = 0;
817         /* set offset to beginning of padding at end of first frame */
818         m -= plen;
819     }
820 
821     do {
822         const uint32_t flen = (s[n+0]<<16)|(s[n+1]<<8)|s[n+2];
823         flags = s[n+4];
824         memmove(s+m, s+n+9, flen);
825         m += flen;
826         n += 9+flen;
827     } while (!(flags & H2_FLAG_END_HEADERS));
828     /* overwrite frame size */
829     m -= 9; /*(temporarily remove frame header from len)*/
830     s[0] = (m >> 16) & 0xFF;
831     s[1] = (m >>  8) & 0xFF;
832     s[2] = (m      ) & 0xFF;
833     m += 9;
834     /* adjust chunk c->mem */
835     if (n < clen) { /*(additional frames after CONTINUATION)*/
836         memmove(s+m, s+n, clen-n);
837         n = m + (clen-n);
838     }
839     else
840         n = m;
841     buffer_string_set_length(c->mem, n + (uint32_t)c->offset);
842 
843     return m;
844 }
845 
846 
847 __attribute_cold__
848 static request_st *
849 h2_recv_trailers_r (connection * const con, h2con * const h2c, const uint32_t id, const uint32_t flags)
850 {
851     /* rant: RFC 7230 HTTP/1.1 trailer-part would have been much simpler
852      * to support in RFC 7540 HTTP/2 as a distinct frame type rather than
853      * HEADERS.  As trailers are not known at the time the request is made,
854      * reuse of such trailers is limited and so a theoretical TRAILERS frame
855      * could have been implemented without HPACK encoding, and would have
856      * been more straightforward to implement than overloading and having to
857      * handle multiple cases for HEADERS.  TRAILERS support could then also
858      * be optional, like in HTTP/1.1 */
859     request_st *r = NULL;
860     for (uint32_t i = 0, rused = h2c->rused; i < rused; ++i) {
861         request_st * const rr = h2c->r[i];
862         if (rr->h2id != id) continue;
863         r = rr;
864         break;
865     }
866     if (NULL == r) {
867         h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
868         return NULL;
869     }
870     if (r->h2state != H2_STATE_OPEN
871         && r->h2state != H2_STATE_HALF_CLOSED_LOCAL) {
872         h2_send_rst_stream(r, con, H2_E_STREAM_CLOSED);
873         return NULL;
874     }
875     /* RFC 7540 is not explicit in restricting HEADERS (trailers) following
876      * (optional) DATA frames, but in following HTTP/1.1, we limit to single
877      * (optional) HEADERS (+ CONTINUATIONs) after (optional) DATA frame(s)
878      * and require that the HEADERS frame set END_STREAM flag. */
879     if (!(flags & H2_FLAG_END_STREAM)) {
880         h2_send_rst_stream(r, con, H2_E_PROTOCOL_ERROR);
881         return NULL;
882     }
883 
884     return h2_recv_end_data(r, con, 0) ? r : NULL;
885 }
886 
887 
888 static void
889 h2_parse_headers_frame (request_st * const restrict r, const unsigned char *psrc, const uint32_t plen, const int trailers)
890 {
891     h2con * const h2c = r->con->h2;
892     struct lshpack_dec * const restrict decoder = &h2c->decoder;
893     const unsigned char * const endp = psrc + plen;
894     http_header_parse_ctx hpctx;
895     hpctx.hlen     = 0;
896     hpctx.pseudo   = 1;
897     hpctx.scheme   = 0;
898     hpctx.trailers = trailers;
899     hpctx.max_request_field_size = r->conf.max_request_field_size;
900     hpctx.http_parseopts = r->conf.http_parseopts;
901     const int log_request_header = r->conf.log_request_header;
902     int rc = LSHPACK_OK;
903     /*buffer_clear(&r->target);*//*(initial state)*/
904 
905     /*(h2_init_con() resized h2r->tmp_buf to 64k; shared with r->tmp_buf)*/
906     buffer * const tb = r->tmp_buf;
907     force_assert(tb->size >= 65536);/*(sanity check; remove in future)*/
908     const lsxpack_strlen_t tbsz = (tb->size <= LSXPACK_MAX_STRLEN)
909       ? tb->size
910       : LSXPACK_MAX_STRLEN;
911 
912     /* note: #define LSHPACK_DEC_HTTP1X_OUTPUT 1 (default) configures
913      * decoder to produce output in format: "field-name: value\r\n"
914      * future: modify build system to define value to 0 in lshpack.h
915      * against which lighttpd builds (or define value in build systems)
916      * Then adjust code below to not use the HTTP/1.x compatibility,
917      * as it is less efficient to copy into HTTP/1.1 request and reparse
918      * than it is to directly parse each decoded header line. */
919     lsxpack_header_t lsx;
920     while (psrc < endp) {
921         memset(&lsx, 0, sizeof(lsxpack_header_t));
922         lsx.buf = tb->ptr;
923         lsx.val_len = tbsz;
924         rc = lshpack_dec_decode(decoder, &psrc, endp, &lsx);
925         if (0 == lsx.name_len)
926             rc = LSHPACK_ERR_BAD_DATA;
927         if (rc == LSHPACK_OK) {
928             hpctx.k = lsx.buf+lsx.name_offset;
929             hpctx.v = lsx.buf+lsx.val_offset;
930             hpctx.klen = lsx.name_len;
931             hpctx.vlen = lsx.val_len;
932 
933             if (log_request_header)
934                 log_error(r->conf.errh, __FILE__, __LINE__,
935                   "fd:%d id:%u rqst: %.*s: %.*s", r->con->fd, r->h2id,
936                   (int)hpctx.klen, hpctx.k, (int)hpctx.vlen, hpctx.v);
937 
938             r->http_status = http_request_parse_header(r, &hpctx);
939             if (0 != r->http_status)
940                 break;
941         }
942       #if 0 /*(see catch-all below)*/
943         /* Send GOAWAY (further below) (decoder state not maintained on error)
944          * (see comments above why decoder state must be maintained) */
945         /* XXX: future: could try to send :status 431 here
946          * and reset other active streams in H2_STATE_OPEN */
947         else if (rc == LSHPACK_ERR_MORE_BUF) {
948             /* XXX: TODO if (r->conf.log_request_header_on_error) */
949             r->http_status = 431; /* Request Header Fields Too Large */
950             /*(try to avoid reading/buffering more data for this request)*/
951             r->h2_rwin = 0; /*(out-of-sync with peer, but is error case)*/
952             /*r->h2state = H2_STATE_HALF_CLOSED_REMOTE*/
953             /* psrc was not advanced if LSHPACK_ERR_MORE_BUF;
954              * processing must stop (since not retrying w/ larger buf)*/
955             break;
956         }
957       #endif
958         else { /* LSHPACK_ERR_BAD_DATA */
959             /* GOAWAY with H2_E_PROTOCOL_ERROR is not specific enough
960              * to tell peer to not retry request, so send RST_STREAM
961              * (slightly more specific, but not by much) before GOAWAY*/
962             /* LSHPACK_ERR_MORE_BUF is treated as an attack, send GOAWAY
963              * (h2r->tmp_buf was resized to 64k in h2_init_con()) */
964             request_h2error_t err = H2_E_COMPRESSION_ERROR;
965             if (rc != LSHPACK_ERR_BAD_DATA) {
966                 /* LSHPACK_ERR_TOO_LARGE, LSHPACK_ERR_MORE_BUF */
967                 err = H2_E_PROTOCOL_ERROR;
968                 h2_send_rst_stream(r, r->con, err);
969             }
970             if (!h2c->sent_goaway && !trailers)
971                 h2c->h2_cid = r->h2id;
972             h2_send_goaway_e(r->con, err);
973             h2_retire_stream(r, r->con);
974             break;
975         }
976     }
977 
978     hpctx.hlen += 2;
979     r->rqst_header_len = hpctx.hlen;
980     /*(accounting for mod_accesslog and mod_rrdtool)*/
981     chunkqueue * const rq = r->read_queue;
982     rq->bytes_in  += (off_t)hpctx.hlen;
983     rq->bytes_out += (off_t)hpctx.hlen;
984 
985     if (0 == r->http_status && LSHPACK_OK == rc) {
986         if (hpctx.pseudo)
987             r->http_status =
988               http_request_validate_pseudohdrs(r, hpctx.scheme,
989                                                hpctx.http_parseopts);
990         if (0 == r->http_status)
991             http_request_headers_process_h2(r, r->con->proto_default_port);
992     }
993 }
994 
995 
996 static int
997 h2_recv_headers (connection * const con, uint8_t * const s, uint32_t flen)
998 {
999     request_st *r = NULL;
1000     h2con * const h2c = con->h2;
1001     const uint32_t id =
1002       ((s[5] << 24) | (s[6] << 16) | (s[7] << 8) | s[8]) & ~0x80000000u;
1003     if (0 == id) { /* HEADERS, PUSH_PROMISE stream id must != 0 */
1004         h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
1005         return 0;
1006     }
1007     if (!(id & 1)) { /* stream id from client must be odd */
1008         h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
1009         return 0;
1010     }
1011 
1012     request_st * const h2r = &con->request;
1013     int trailers = 0;
1014 
1015     if (id > h2c->h2_cid) {
1016         if (h2c->rused == sizeof(h2c->r)/sizeof(*h2c->r)) {
1017             if (0 == h2c->sent_settings) { /*(see h2_recv_settings() comments)*/
1018                 /* too many active streams; refuse new stream */
1019                 h2c->h2_cid = id;
1020                 h2_send_rst_stream_id(id, con, H2_E_REFUSED_STREAM);
1021                 return 1;
1022             }
1023             else {
1024                 /* alternative: stop processing frames and defer processing this
1025                  * HEADERS frame until num active streams drops below limit.
1026                  * lighttpd sends SETTINGS_MAX_CONCURRENT_STREAMS <limit> with
1027                  * server Connection Preface, so a well-behaved client will
1028                  * adjust after it sends its initial requests.
1029                  * (e.g. h2load -n 100 -m 100 sends 100 requests upon connect)*/
1030                 return -1;
1031             }
1032         }
1033         /* Note: MUST process HPACK decode even if already sent GOAWAY.
1034          * This is necessary since there may be active streams not in
1035          * H2_STATE_HALF_CLOSED_REMOTE, e.g. H2_STATE_OPEN, still possibly
1036          * receiving DATA and, more relevantly, still might receive HEADERS
1037          * frame with trailers, for which the decoder state is required.
1038          * XXX: future might try to reduce other processing done if sent
1039          *      GOAWAY, e.g. might avoid allocating (request_st *r) */
1040         r = h2_init_stream(h2r, con);
1041         r->h2id = id;
1042         r->h2state = (s[4] & H2_FLAG_END_STREAM)
1043           ? H2_STATE_HALF_CLOSED_REMOTE
1044           : H2_STATE_OPEN;
1045         /* Note: timestamps here are updated only after receipt of entire header
1046          * (HEADERS frame might have been sent in multiple packets
1047          *  and CONTINUATION frames may have been sent in multiple packets)
1048          * (affects high precision timestamp, if enabled)
1049          * (large sets of headers are not typical, and even when they do
1050          *  occur, they will typically be sent within the same second)
1051          * (future: might keep high precision timestamp in h2con when first
1052          *  packet of HEADERS or PUSH_PROMISE is received, and clear that
1053          *  timestamp when frame + CONTINUATION(s) are complete (so that
1054          *  re-read of initial frame does not overwrite the timestamp))
1055          */
1056         r->start_ts = log_epoch_secs;
1057         if (r->conf.high_precision_timestamps)
1058             log_clock_gettime_realtime(&r->start_hp);
1059     }
1060     else {
1061         r = h2_recv_trailers_r(con, h2c, id, s[4]); /* (cold code path) */
1062         if (NULL == r)
1063             return (h2c->sent_goaway > 0) ? 0 : 1;
1064         trailers = 1;
1065     }
1066 
1067     const unsigned char *psrc = s + 9;
1068     uint32_t alen = flen;
1069     if (s[4] & H2_FLAG_PADDED) {
1070         ++psrc;
1071         const uint32_t pad = s[9];
1072         if (flen < 1 + pad + ((s[4] & H2_FLAG_PRIORITY) ? 5 : 0)) {
1073             /* Padding that exceeds the size remaining for the header block
1074              * fragment MUST be treated as a PROTOCOL_ERROR. */
1075             h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
1076             h2_retire_stream(r, con);
1077             return 0;
1078         }
1079         alen -= (1 + pad); /*(alen is adjusted for PRIORITY below)*/
1080     }
1081     if (s[4] & H2_FLAG_PRIORITY) {
1082         /* XXX: TODO: handle PRIORITY (prio fields start at *psrc) */
1083         const uint32_t prio =
1084           ((psrc[0]<<24)|(psrc[1]<<16)|(psrc[2]<<8)|psrc[3]) & ~0x80000000u;
1085         if (prio == id) {
1086             h2_send_rst_stream(r, con, H2_E_PROTOCOL_ERROR);
1087             h2_retire_stream(r, con);
1088             return 1;
1089         }
1090       #if 0
1091         uint32_t exclusive_dependency = (psrc[0] & 0x80) ? 1 : 0;
1092         uint32_t weight = psrc[4];
1093       #endif
1094         psrc += 5;
1095         alen -= 5;
1096     }
1097 
1098     h2_parse_headers_frame(r, psrc, alen, trailers);
1099 
1100   #if 0 /*(handled in h2_parse_frames() as a connection error)*/
1101     if (s[3] == H2_FTYPE_PUSH_PROMISE) {
1102         /* Had to process HPACK to keep HPACK tables sync'd with peer but now
1103          * discard the request if PUSH_PROMISE, since not expected, as this code
1104          * is running as a server, not as a client.
1105          * XXX: future might try to reduce other processing done if
1106          * discarding, e.g. might avoid allocating (request_st *r) */
1107         /* rant: PUSH_PROMISE could have been a flag on HEADERS frame
1108          *       instead of an independent frame type */
1109         r->http_status = 0;
1110         h2_retire_stream(r, con);
1111     }
1112   #endif
1113 
1114     if (!h2c->sent_goaway) {
1115         h2c->h2_cid = id;
1116         if (!(r->rqst_htags & HTTP_HEADER_CONTENT_LENGTH))
1117             r->reqbody_length = (s[4] & H2_FLAG_END_STREAM) ? 0 : -1;
1118       #if 0
1119         else if (r->reqbody_length > 0 && (s[4] & H2_FLAG_END_STREAM)) {
1120             /*(handled in connection_handle_read_post_state())*/
1121             /* XXX: TODO if (r->conf.log_request_header_on_error) */
1122             r->http_status = 400; /* Bad Request */
1123         }
1124       #endif
1125 
1126         /* RFC 7540 Section 8. HTTP Message Exchanges
1127          * 8.1.2.6. Malformed Requests and Responses
1128          *   For malformed requests, a server MAY send an HTTP
1129          *   response prior to closing or resetting the stream.
1130          * However, h2spec expects stream PROTOCOL_ERROR.
1131          * (This is unfortunate, since we would rather send
1132          *  400 Bad Request which tells client *do not* retry
1133          *  the bad request without modification)
1134          * https://github.com/summerwind/h2spec/issues/120
1135          * https://github.com/summerwind/h2spec/issues/121
1136          * https://github.com/summerwind/h2spec/issues/122
1137          */
1138       #if 0
1139         if (400 == r->http_status) {
1140             h2_send_rst_stream(r, con, H2_E_PROTOCOL_ERROR);
1141             h2_retire_stream(r, con);
1142         }
1143       #endif
1144     }
1145     else if (h2c->h2_cid < id) {
1146         /* Had to process HPACK to keep HPACK tables sync'd with peer
1147          * but now discard the request if id is after id sent in GOAWAY.
1148          * XXX: future might try to reduce other processing done if
1149          * discarding, e.g. might avoid allocating (request_st *r) */
1150         r->http_status = 0;
1151         h2_retire_stream(r, con);
1152     }
1153 
1154     return 1;
1155 }
1156 
1157 
1158 int
1159 h2_parse_frames (connection * const con)
1160 {
1161     /* read and process HTTP/2 frames from socket */
1162     h2con * const h2c = con->h2;
1163     chunkqueue * const cq = con->read_queue;
1164     /* initial max frame size is the minimum: 16k
1165      * (lighttpd does not currently increase max frame size)
1166      * (lighttpd does not currently decrease max frame size)
1167      * (XXX: If SETTINGS_MAX_FRAME_SIZE were increased and then decreased,
1168      *       should accept the larger frame size until SETTINGS is ACK'd) */
1169     const uint32_t fsize = h2c->s_max_frame_size;
1170     for (off_t cqlen = chunkqueue_length(cq); cqlen >= 9; ) {
1171         chunk *c = cq->first;
1172         /*assert(c->type == MEM_CHUNK);*/
1173         /* copy data if frame header crosses chunk boundary
1174          * future: be more efficient than blind full chunk copy */
1175         uint32_t clen = buffer_string_length(c->mem) - c->offset;
1176         if (clen < 9) {
1177             clen = h2_frame_cq_compact(cq, 9);
1178             c = cq->first; /*(reload after h2_frame_cq_compact())*/
1179         }
1180         uint8_t *s = (uint8_t *)(c->mem->ptr + c->offset);
1181         uint32_t flen = (s[0] << 16) | (s[1] << 8) | s[2];
1182         if (flen > fsize) {
1183             h2_send_goaway_e(con, H2_E_FRAME_SIZE_ERROR);
1184             return 0;
1185         }
1186 
1187         /*(handle PUSH_PROMISE as connection error further below)*/
1188         /*if (s[3] == H2_FTYPE_HEADERS || s[3] == H2_FTYPE_PUSH_PROMISE)*/
1189 
1190         if (s[3] == H2_FTYPE_HEADERS) {
1191             if (cqlen < 9+flen) return 1; /* incomplete frame; go on */
1192             if (clen < 9+flen) {
1193                 clen = h2_frame_cq_compact(cq, 9+flen);
1194                 c = cq->first; /*(reload after h2_frame_cq_compact())*/
1195                 s = (uint8_t *)(c->mem->ptr + c->offset);
1196             }
1197 
1198             if (!(s[4] & H2_FLAG_END_HEADERS)) {
1199                 /* collect CONTINUATION frames (cold code path) */
1200                 /* note: h2_recv_continuation() return value is overloaded
1201                  * and the resulting clen is 9+flen of *concatenated* frames */
1202                 clen = h2_recv_continuation(9+flen, clen, cqlen, cq, con);
1203                 if (0 == clen)    return 0;
1204                 if (cqlen < clen) return 1; /* incomplete frames; go on */
1205                 c = cq->first; /*(reload after h2_recv_continuation())*/
1206                 s = (uint8_t *)(c->mem->ptr + c->offset);
1207                 /* frame size was also updated and might (legitimately)
1208                  * exceed SETTINGS_MAX_FRAME_SIZE, so do not test fsize again */
1209                 flen = (s[0]<<16)|(s[1]<<8)|s[2];
1210                 /* recalculate after CONTINUATION removed */
1211                 cqlen = chunkqueue_length(cq);
1212             }
1213 
1214             int rc = h2_recv_headers(con, s, flen);
1215             cqlen -= (9+flen);
1216             if (rc >= 0)
1217                 chunkqueue_mark_written(cq, 9+flen);
1218             if (rc <= 0)
1219                 return 0;
1220             con->read_idle_ts = log_epoch_secs;
1221         }
1222         else if (s[3] == H2_FTYPE_DATA) {
1223             /* future: might try to stream data for incomplete frames,
1224              * but that would require keeping additional state for partially
1225              * read frames, including cleaning up if errors occur.
1226              * Since well-behaved clients do not intentionally send partial
1227              * frames, and try to resend if socket buffers are full, this is
1228              * probably not a big concern in practice. */
1229             if (cqlen < 9+flen) return 1; /* incomplete frame; go on */
1230             con->read_idle_ts = log_epoch_secs;
1231             /*(h2_recv_data() must consume frame from cq or else return 0)*/
1232             if (!h2_recv_data(con, s, flen))
1233                 return 0;
1234             cqlen -= (9+flen);
1235         }
1236         else {
1237             /* frame types below are expected to be small
1238              * most frame types below have fixed (small) size
1239              *   4 bytes - WINDOW_UPDATE
1240              *   5 bytes - PRIORITY
1241              *   8 bytes - PING
1242              *   4 bytes - RST_STREAM
1243              * some are variable size
1244              *     SETTINGS (6 * #settings; 6 defined in RFC 7540 Section 6.5)
1245              *     GOAWAY   (8 + optional additional debug data (variable))
1246              * XXX: might add sanity check for a max flen here,
1247              *      before waiting to read partial frame
1248              *      (fsize limit is still enforced above for all frames)
1249              */
1250             if (cqlen < 9+flen) return 1; /* incomplete frame; go on */
1251             if (clen < 9+flen) {
1252                 clen = h2_frame_cq_compact(cq, 9+flen);
1253                 c = cq->first; /*(reload after h2_frame_cq_compact())*/
1254                 s = (uint8_t *)(c->mem->ptr + c->offset);
1255             }
1256             switch (s[3]) { /* frame type */
1257               case H2_FTYPE_WINDOW_UPDATE:
1258                 h2_recv_window_update(con, s, flen);
1259                 break;
1260               case H2_FTYPE_PRIORITY:
1261                 h2_recv_priority(con, s, flen);
1262                 break;
1263               case H2_FTYPE_SETTINGS:
1264                 h2_recv_settings(con, s, flen);
1265                 break;
1266               case H2_FTYPE_PING:
1267                 h2_recv_ping(con, s, flen);
1268                 break;
1269               case H2_FTYPE_RST_STREAM:
1270                 h2_recv_rst_stream(con, s, flen);
1271                 break;
1272               case H2_FTYPE_GOAWAY:
1273                 if (!h2_recv_goaway(con, s, flen)) return 0;
1274                 break;
1275               case H2_FTYPE_PUSH_PROMISE: /*not expected from client*/
1276               case H2_FTYPE_CONTINUATION: /*handled with HEADERS*/
1277                 h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
1278                 return 0;
1279               default: /* ignore unknown frame types */
1280                 break;
1281             }
1282             cqlen -= (9+flen);
1283             chunkqueue_mark_written(cq, 9+flen);
1284         }
1285 
1286         if (h2c->sent_goaway > 0) return 0;
1287     }
1288 
1289     return 1;
1290 }
1291 
1292 
1293 int
1294 h2_want_read (connection * const con)
1295 {
1296     chunkqueue * const cq = con->read_queue;
1297     if (chunkqueue_is_empty(cq)) return 1;
1298 
1299     /* check for partial frame */
1300     const off_t cqlen = cq->bytes_in - cq->bytes_out; /*chunkqueue_length(cq);*/
1301     if (cqlen < 9) return 1;
1302     chunk *c = cq->first;
1303     uint32_t clen = buffer_string_length(c->mem) - c->offset;
1304     if (clen < 9) {
1305         clen = h2_frame_cq_compact(cq, 9);
1306         c = cq->first; /*(reload after h2_frame_cq_compact())*/
1307     }
1308     uint8_t *s = (uint8_t *)(c->mem->ptr + c->offset);
1309     uint32_t flen = (s[0] << 16) | (s[1] << 8) | s[2];
1310     if (clen < 9+flen) return 1;
1311 
1312     /* check if not HEADERS, or if HEADERS has END_HEADERS flag */
1313     if (s[3] != H2_FTYPE_HEADERS || (s[4] & H2_FLAG_END_HEADERS))
1314         return 0;
1315 
1316     /* check for partial CONTINUATION frames */
1317     for (uint32_t n = 9+flen; cqlen >= n+9; n += 9+flen) {
1318         if (clen < n+9) {
1319             clen = h2_frame_cq_compact(cq, n+9);
1320             c = cq->first; /*(reload after h2_frame_cq_compact())*/
1321             s = (uint8_t *)(c->mem->ptr + c->offset);
1322         }
1323         flen = (s[n+0] << 16) | (s[n+1] << 8) | s[n+2];
1324         if (cqlen < n+9+flen) return 1; /* incomplete frame; go on */
1325         if (s[4] & H2_FLAG_END_HEADERS) return 0;
1326     }
1327 
1328     return 1;
1329 }
1330 
1331 
1332 static int
1333 h2_recv_client_connection_preface (connection * const con)
1334 {
1335     /* check if the client Connection Preface (24 bytes) has been received
1336      * (initial SETTINGS frame should immediately follow, but is not checked) */
1337     chunkqueue * const cq = con->read_queue;
1338     if (chunkqueue_length(cq) < 24) {
1339         chunk * const c = cq->first;
1340         if (c && buffer_string_length(c->mem) - c->offset >= 4) {
1341             const char * const s = c->mem->ptr + c->offset;
1342             if (s[0]!='P'||s[1]!='R'||s[2]!='I'||s[3]!=' ') {
1343                 h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
1344                 return 1; /* error; done receiving connection preface */
1345             }
1346         }
1347         return 0; /*(not ready yet)*/
1348     }
1349 
1350     static const char h2preface[] = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
1351     chunk *c = cq->first;
1352     const uint32_t clen = buffer_string_length(c->mem) - c->offset;
1353     if (clen < 24) h2_frame_cq_compact(cq, 24);
1354     c = cq->first; /*(reload after h2_frame_cq_compact())*/
1355     const uint8_t * const s = (uint8_t *)(c->mem->ptr + c->offset);
1356     if (0 == memcmp(s, h2preface, 24)) /* sizeof(h2preface)-1) */
1357         chunkqueue_mark_written(cq, 24);
1358     else
1359         h2_send_goaway_e(con, H2_E_PROTOCOL_ERROR);
1360     return 1; /* done receiving connection preface (even if error occurred) */
1361 }
1362 
1363 
1364 __attribute_cold__
1365 static int
1366 h2_read_client_connection_preface (struct connection * const con, chunkqueue * const cq, off_t max_bytes)
1367 {
1368     /* temporary con->network_read() filter until connection preface received */
1369 
1370     /*(alternatively, func ptr could be saved in an element in (h2con *))*/
1371     void ** const hctx = con->plugin_ctx+0; /*(0 idx used for h2)*/
1372     int(* const network_read)(struct connection *, chunkqueue *, off_t) =
1373       (int(*)(struct connection *, chunkqueue *, off_t))(uintptr_t)(*hctx);
1374     if (max_bytes < 24) max_bytes = 24; /*(should not happen)*/
1375     int rc = (network_read)(con, cq, max_bytes);
1376     if (NULL == con->h2) return rc; /*(unexpected; already cleaned up)*/
1377     if (-1 != rc && h2_recv_client_connection_preface(con)) {
1378         con->network_read = network_read;
1379         *hctx = NULL;
1380         /*(intentionally update timestamp only after reading preface complete)*/
1381         con->read_idle_ts = log_epoch_secs;
1382     }
1383     return rc;
1384 }
1385 
1386 
1387 void
1388 h2_init_con (request_st * const restrict h2r, connection * const restrict con, const buffer * const restrict http2_settings)
1389 {
1390     h2con * const h2c = calloc(1, sizeof(h2con));
1391     force_assert(h2c);
1392     con->h2 = h2c;
1393     con->read_idle_ts = log_epoch_secs;
1394     con->keep_alive_idle = h2r->conf.max_keep_alive_idle;
1395 
1396     h2r->h2_rwin = 65535;                 /* h2 connection recv window */
1397     h2r->h2_swin = 65535;                 /* h2 connection send window */
1398     /* settings sent from peer */         /* initial values */
1399     h2c->s_header_table_size     = 4096;  /* SETTINGS_HEADER_TABLE_SIZE      */
1400     h2c->s_enable_push           = 1;     /* SETTINGS_ENABLE_PUSH            */
1401     h2c->s_max_concurrent_streams= ~0u;   /* SETTINGS_MAX_CONCURRENT_STREAMS */
1402     h2c->s_initial_window_size   = 65535; /* SETTINGS_INITIAL_WINDOW_SIZE    */
1403     h2c->s_max_frame_size        = 16384; /* SETTINGS_MAX_FRAME_SIZE         */
1404     h2c->s_max_header_list_size  = ~0u;   /* SETTINGS_MAX_HEADER_LIST_SIZE   */
1405     h2c->sent_settings           = log_epoch_secs; /*(send SETTINGS below)*/
1406 
1407     lshpack_dec_init(&h2c->decoder);
1408     lshpack_enc_init(&h2c->encoder);
1409     lshpack_enc_use_hist(&h2c->encoder, 1);
1410 
1411     if (http2_settings) /*(if Upgrade: h2c)*/
1412         h2_parse_frame_settings(con, (uint8_t *)CONST_BUF_LEN(http2_settings));
1413 
1414     static const uint8_t h2settings[] = { /*(big-endian numbers)*/
1415       /* SETTINGS */
1416       0x00, 0x00, 0x0c        /* frame length */ /* 6 * 2 for two settings */
1417      ,H2_FTYPE_SETTINGS       /* frame type */
1418      ,0x00                    /* frame flags */
1419      ,0x00, 0x00, 0x00, 0x00  /* stream identifier */
1420      ,0x00, H2_SETTINGS_MAX_CONCURRENT_STREAMS
1421      ,0x00, 0x00, 0x00, 0x08  /* 8 */
1422      #if 0  /* ? explicitly disable dynamic table ? (and adjust frame length) */
1423             /* If this is sent, must wait until peer sends SETTINGS with ACK
1424              * before disabling dynamic table in HPACK decoder */
1425             /*(before calling lshpack_dec_set_max_capacity(&h2c->decoder, 0))*/
1426      ,0x00, H2_SETTINGS_HEADER_TABLE_SIZE
1427      ,0x00, 0x00, 0x00, 0x00  /* 0 */
1428      #endif
1429      #if 0  /* ? explicitly disable push ?       (and adjust frame length) */
1430      ,0x00, H2_SETTINGS_ENABLE_PUSH
1431      ,0x00, 0x00, 0x00, 0x00  /* 0 */
1432      #endif
1433      #if 0  /* ? increase from default (65535) ? (and adjust frame length) */
1434      ,0x00, H2_SETTINGS_INITIAL_WINDOW_SIZE
1435      ,0x00, 0x02, 0x00, 0x00  /* 131072 */
1436      #endif
1437      #if 0  /* ? increase from default (16384) ? (and adjust frame length) */
1438      ,0x00, H2_SETTINGS_MAX_FRAME_SIZE
1439      ,0x00, 0x00, 0x80, 0x00  /* 32768 */
1440      #endif
1441      ,0x00, H2_SETTINGS_MAX_HEADER_LIST_SIZE
1442      ,0x00, 0x00, 0xFF, 0xFF  /* 65535 */
1443 
1444      #if 0
1445       /* WINDOW_UPDATE */
1446      ,0x00, 0x00, 0x04        /* frame length */
1447      ,H2_FTYPE_WINDOW_UPDATE  /* frame type */
1448      ,0x00                    /* frame flags */
1449      ,0x00, 0x00, 0x00, 0x00  /* stream identifier */
1450      ,0x00, 0x01, 0x00, 0x01  /* 65537 */ /* increase connection rwin to 128k */
1451      #endif
1452     };
1453 
1454     /*h2r->h2_rwin += 65537;*//*(enable if WINDOWS_UPDATE is sent above)*/
1455     chunkqueue_append_mem(con->write_queue,
1456                           (const char *)h2settings, sizeof(h2settings));
1457 
1458     if (!h2_recv_client_connection_preface(con)) {
1459         /*(alternatively, func ptr could be saved in an element in (h2con *))*/
1460         con->plugin_ctx[0] = (void *)(uintptr_t)con->network_read;
1461         con->network_read = h2_read_client_connection_preface;
1462         /* note: no steps taken to reset con->network_read() on error
1463          * as con->network_read() is always set in connection_accepted() */
1464     }
1465 
1466     buffer_string_prepare_copy(h2r->tmp_buf, 65535);
1467 }
1468 
1469 
1470 static void
1471 h2_send_hpack (request_st * const r, connection * const con, const char *data, uint32_t dlen, const uint32_t flags)
1472 {
1473     union {
1474       uint8_t c[12];
1475       uint32_t u[3];          /*(alignment)*/
1476     } headers = { {           /*(big-endian numbers)*/
1477       0x00, 0x00, 0x00        /* padding for alignment; do not send */
1478       /* HEADERS */
1479      ,0x00, 0x00, 0x00        /* frame length      (fill in below) */
1480      ,H2_FTYPE_HEADERS        /* frame type */
1481      ,(uint8_t)flags          /* frame flags (e.g. END_STREAM for trailers) */
1482      ,0x00, 0x00, 0x00, 0x00  /* stream identifier (fill in below) */
1483     } };
1484 
1485     headers.u[2] = htonl(r->h2id);
1486 
1487     /* similar to h2_send_data(), but unlike DATA frames there is a HEADERS
1488      * frame potentially followed by CONTINUATION frame(s) here, and the final
1489      * HEADERS or CONTINUATION frame here has END_HEADERS flag set.
1490      * For trailers, END_STREAM flag is set on HEADERS frame. */
1491 
1492     /*(approximate space needed for frames (header + payload)
1493      * with slight over-estimate of 16 bytes per frame header (> 9)
1494      * and minimum SETTING_MAX_FRAME_SIZE of 16k (could be larger)
1495      * (dlen >> 14)+1 is num 16k frames needed, multipled by 16 bytes
1496      *  per frame can be appoximated with (dlen>>10) + 9)*/
1497     buffer * const b =
1498       chunkqueue_append_buffer_open_sz(con->write_queue, dlen + (dlen>>10) + 9);
1499     char * restrict ptr = b->ptr;
1500     h2con * const h2c = con->h2;
1501     const uint32_t fsize = h2c->s_max_frame_size;
1502     do {
1503         const uint32_t len = dlen < fsize ? dlen : fsize;
1504         headers.c[3] = (len >> 16) & 0xFF; /*(off +3 to skip over align pad)*/
1505         headers.c[4] = (len >>  8) & 0xFF;
1506         headers.c[5] = (len      ) & 0xFF;
1507         if (len == dlen)
1508             headers.c[7] |= H2_FLAG_END_HEADERS;
1509       #if 0
1510         chunkqueue_append_mem(con->write_queue,  /*(+3 to skip over align pad)*/
1511                               (const char *)headers.c+3, sizeof(headers)-3);
1512         chunkqueue_append_mem(con->write_queue, data, len);
1513       #else
1514         memcpy(ptr, headers.c+3, sizeof(headers)-3);
1515         memcpy(ptr+sizeof(headers)-3, data, len);
1516         ptr  += len + sizeof(headers)-3;
1517       #endif
1518         data += len;
1519         dlen -= len;
1520         /*(include H2_FLAG_END_STREAM in HEADERS frame, not CONTINUATION)*/
1521         headers.c[6] = H2_FTYPE_CONTINUATION; /*(if additional frames needed)*/
1522         headers.c[7] = 0x00; /*(off +3 to skip over align pad)*/
1523     } while (dlen);
1524     buffer_string_set_length(b, (uint32_t)(ptr - b->ptr));
1525     chunkqueue_append_buffer_commit(con->write_queue);
1526 }
1527 
1528 
1529 void
1530 h2_send_headers (request_st * const r, connection * const con)
1531 {
1532     /*(set keep_alive_idle; out-of-place and non-event for most configs,
1533      * but small attempt to (maybe) preserve behavior for specific configs)*/
1534     con->keep_alive_idle = r->conf.max_keep_alive_idle;
1535 
1536     /* specialized version of http_response_write_header(); send headers
1537      * directly to HPACK encoder, rather than double-buffering in chunkqueue */
1538 
1539     if (304 == r->http_status && (r->resp_htags & HTTP_HEADER_CONTENT_ENCODING))
1540         http_header_response_unset(r, HTTP_HEADER_CONTENT_ENCODING,
1541                                    CONST_STR_LEN("Content-Encoding"));
1542 
1543     /*(h2_init_con() resized h2r->tmp_buf to 64k; shared with r->tmp_buf)*/
1544     buffer * const tb = r->tmp_buf;
1545     force_assert(tb->size >= 65536);/*(sanity check; remove in future)*/
1546     unsigned char *dst = (unsigned char *)tb->ptr;
1547     unsigned char * const dst_end = (unsigned char *)tb->ptr + tb->size;
1548 
1549     h2con * const h2c = con->h2;
1550     struct lshpack_enc * const encoder = &h2c->encoder;
1551     lsxpack_header_t lsx;
1552     uint32_t alen = 7+3+4; /* ":status: xxx\r\n" */
1553     const int log_response_header = r->conf.log_response_header;
1554     const int resp_header_repeated = r->resp_header_repeated;
1555 
1556     char status[12] = ":status: ";
1557     int x = r->http_status; /*(expect status < 1000; should be [100-599])*/
1558     status[11] = (x % 10) + '0';
1559     status[10] = (x / 10 % 10) + '0';
1560     status[9]  = (x / 100) + '0';
1561 
1562     if (log_response_header)
1563         log_error(r->conf.errh, __FILE__, __LINE__,
1564           "fd:%d id:%u resp: %.*s", r->con->fd, r->h2id, 12, status);
1565 
1566     memset(&lsx, 0, sizeof(lsxpack_header_t));
1567     lsx.buf = status;
1568     lsx.name_offset = 0;
1569     lsx.name_len = 7;
1570     lsx.val_offset = 9;
1571     lsx.val_len = 3;
1572     dst = lshpack_enc_encode(encoder, dst, dst_end, &lsx);
1573     if (dst == (unsigned char *)tb->ptr) {
1574         h2_send_rst_stream(r, con, H2_E_INTERNAL_ERROR);
1575         return;
1576     }
1577 
1578     /* add all headers */
1579     for (uint32_t i = 0, used = r->resp_headers.used; i < used; ++i) {
1580         data_string * const restrict ds =(data_string *)r->resp_headers.data[i];
1581         const uint32_t klen = buffer_string_length(&ds->key);
1582         const uint32_t vlen = buffer_string_length(&ds->value);
1583         const char * const restrict k = ds->key.ptr;
1584         if (0 == vlen || 0 == klen) continue;
1585         if ((k[0] & 0xdf) == 'X' && http_response_omit_header(r, ds))
1586             continue;
1587         alen += klen + vlen + 4;
1588 
1589         if (alen > LSXPACK_MAX_STRLEN) {
1590             /* ls-hpack default limit (UINT16_MAX) is per-line, due to field
1591              * sizes of lsx.name_offset,lsx.name_len,lsx.val_offset,lsx.val_len
1592              * However, similar to elsewhere, limit total size of expanded
1593              * headers to (very generous) 64k - 1.  Peers might allow less. */
1594             h2_send_rst_stream(r, con, H2_E_INTERNAL_ERROR);
1595             return;
1596         }
1597 
1598         /* HTTP/2 requires lowercase keys
1599          * ls-hpack requires key and value be in same buffer
1600          * Since keys are typically short, append (and lowercase) key onto
1601          * end of value buffer */
1602         char * const v = buffer_string_prepare_append(&ds->value, klen);
1603         for (uint32_t j = 0; j < klen; ++j)
1604             v[j] = (k[j] < 'A' || k[j] > 'Z') ? k[j] : (k[j] | 0x20);
1605         /*buffer_commit(&ds->value, klen);*//*(not necessary; truncated below)*/
1606 
1607         uint32_t voff = 0;
1608         const char *n;
1609         lsx.buf = ds->value.ptr;
1610         do {
1611             n = !resp_header_repeated
1612               ? NULL
1613               : memchr(lsx.buf+voff, '\n', vlen - voff);
1614 
1615             memset(&lsx, 0, sizeof(lsxpack_header_t));
1616             lsx.buf = ds->value.ptr;
1617             lsx.name_offset = vlen;
1618             lsx.name_len = klen;
1619             lsx.val_offset = voff;
1620             if (NULL == n)
1621                 lsx.val_len = vlen - voff;
1622             else {
1623                 /* multiple headers (same field-name) separated by "\r\n"
1624                  * and then "field-name: " (see http_header_response_insert())*/
1625                 voff = (uint32_t)(n + 1 - lsx.buf);
1626                 lsx.val_len = voff - 2 - lsx.val_offset; /*(-2 for "\r\n")*/
1627                 voff += klen + 2;
1628             }
1629 
1630             if (log_response_header)
1631                 log_error(r->conf.errh, __FILE__, __LINE__,
1632                   "fd:%d id:%u resp: %.*s: %.*s", r->con->fd, r->h2id,
1633                   (int)klen, lsx.buf + lsx.name_offset,
1634                   (int)lsx.val_len, lsx.buf + lsx.val_offset);
1635 
1636             unsigned char * const dst_in = dst;
1637             dst = lshpack_enc_encode(encoder, dst, dst_end, &lsx);
1638             if (dst == dst_in) {
1639                 buffer_string_set_length(&ds->value, vlen); /*(restore prior value)*/
1640                 h2_send_rst_stream(r, con, H2_E_INTERNAL_ERROR);
1641                 return;
1642             }
1643         } while (n);
1644         buffer_string_set_length(&ds->value, vlen); /*(restore prior value)*/
1645     }
1646 
1647     if (!(r->resp_htags & HTTP_HEADER_DATE)) {
1648         /* HTTP/1.1 and later requires a Date: header */
1649         /* "date: " 6-chars + 30-chars for "%a, %d %b %Y %H:%M:%S GMT" + '\0' */
1650         static char tstr[36] = "date: ";
1651 
1652         memset(&lsx, 0, sizeof(lsxpack_header_t));
1653         lsx.buf = tstr;
1654         lsx.name_offset = 0;
1655         lsx.name_len = 4;
1656         lsx.val_offset = 6;
1657         lsx.val_len = 29;
1658 
1659         /* cache the generated timestamp */
1660         static time_t tlast;
1661         const time_t cur_ts = log_epoch_secs;
1662         if (tlast != cur_ts) {
1663             tlast = cur_ts;
1664             strftime(tstr+6, sizeof(tstr)-6,
1665                      "%a, %d %b %Y %H:%M:%S GMT", gmtime(&tlast));
1666         }
1667 
1668         alen += 35+2;
1669 
1670         if (log_response_header)
1671             log_error(r->conf.errh, __FILE__, __LINE__,
1672               "fd:%d id:%u resp: %.*s", r->con->fd, r->h2id, 35, tstr);
1673 
1674         unsigned char * const dst_in = dst;
1675         dst = lshpack_enc_encode(encoder, dst, dst_end, &lsx);
1676         if (dst == dst_in) {
1677             h2_send_rst_stream(r, con, H2_E_INTERNAL_ERROR);
1678             return;
1679         }
1680     }
1681 
1682     if (!(r->resp_htags & HTTP_HEADER_SERVER)
1683         && !buffer_string_is_empty(r->conf.server_tag)) {
1684         buffer * const b = chunk_buffer_acquire();
1685         const uint32_t vlen = buffer_string_length(r->conf.server_tag);
1686         buffer_copy_string_len(b, CONST_STR_LEN("server: "));
1687         buffer_append_string_len(b, CONST_BUF_LEN(r->conf.server_tag));
1688 
1689         alen += 6+vlen+4;
1690 
1691         if (log_response_header)
1692             log_error(r->conf.errh, __FILE__, __LINE__,
1693               "fd:%d id:%u resp: %.*s", r->con->fd, r->h2id,
1694               (int)6+vlen+2, b->ptr);
1695 
1696         memset(&lsx, 0, sizeof(lsxpack_header_t));
1697         lsx.buf = b->ptr;
1698         lsx.name_offset = 0;
1699         lsx.name_len = 6;
1700         lsx.val_offset = 8;
1701         lsx.val_len = vlen;
1702         unsigned char * const dst_in = dst;
1703         dst = lshpack_enc_encode(encoder, dst, dst_end, &lsx);
1704         chunk_buffer_release(b);
1705         if (dst == dst_in) {
1706             h2_send_rst_stream(r, con, H2_E_INTERNAL_ERROR);
1707             return;
1708         }
1709     }
1710 
1711     alen += 2; /* "virtual" blank line ("\r\n") ending headers */
1712     r->resp_header_len = alen;
1713     /*(accounting for mod_accesslog and mod_rrdtool)*/
1714     chunkqueue * const wq = r->write_queue;
1715     wq->bytes_in  += (off_t)alen;
1716     wq->bytes_out += (off_t)alen;
1717 
1718     const uint32_t dlen = (uint32_t)((char *)dst - tb->ptr);
1719     const uint32_t flags =
1720       (r->resp_body_finished && chunkqueue_is_empty(r->write_queue))
1721         ? H2_FLAG_END_STREAM
1722         : 0;
1723     h2_send_hpack(r, con, tb->ptr, dlen, flags);
1724 }
1725 
1726 
1727 __attribute_cold__
1728 __attribute_noinline__
1729 static void
1730 h2_send_headers_block (request_st * const r, connection * const con, const char * const hdrs, const uint32_t hlen, uint32_t flags)
1731 {
1732     unsigned short hoff[8192]; /* max num header lines + 3; 16k on stack */
1733     hoff[0] = 1;                         /* number of lines */
1734     hoff[1] = 0;                         /* base offset for all lines */
1735     /*hoff[2] = ...;*/                   /* offset from base for 2nd line */
1736     uint32_t rc = http_header_parse_hoff(hdrs, hlen, hoff);
1737     if (0 == rc || rc > USHRT_MAX || hoff[0] >= sizeof(hoff)/sizeof(hoff[0])-1
1738         || 1 == hoff[0]) { /*(initial blank line (should not happen))*/
1739         /* error if headers incomplete or too many header fields */
1740         log_error(r->conf.errh, __FILE__, __LINE__,
1741                   "oversized response-header");
1742         hoff[0] = 1;
1743         hoff[1] = 0;
1744         http_header_parse_hoff(CONST_STR_LEN(":status: 500\r\n\r\n"), hoff);
1745     }
1746 
1747     /*(h2_init_con() resized h2r->tmp_buf to 64k; shared with r->tmp_buf)*/
1748     buffer * const tb = r->tmp_buf;
1749     force_assert(tb->size >= 65536);/*(sanity check; remove in future)*/
1750     unsigned char *dst = (unsigned char *)tb->ptr;
1751     unsigned char * const dst_end = (unsigned char *)tb->ptr + tb->size;
1752 
1753     h2con * const h2c = con->h2;
1754     struct lshpack_enc * const encoder = &h2c->encoder;
1755     lsxpack_header_t lsx;
1756 
1757     int i = 1;
1758     if (hdrs[0] == ':') {
1759         i = 2;
1760         /* expect first line to contain ":status: ..." if pseudo-header,
1761          * and expecting single pseudo-header for headers, zero for trailers */
1762         /*assert(0 == memcmp(hdrs, ":status: ", sizeof(":status: ")-1));*/
1763         memset(&lsx, 0, sizeof(lsxpack_header_t));
1764         *(const char **)&lsx.buf = hdrs;
1765         lsx.name_offset = 0;
1766         lsx.name_len = sizeof(":status")-1;
1767         lsx.val_offset = lsx.name_len + 2;
1768         lsx.val_len = 3;
1769         dst = lshpack_enc_encode(encoder, dst, dst_end, &lsx);
1770         if (dst == (unsigned char *)tb->ptr) {
1771             h2_send_rst_stream(r, con, H2_E_INTERNAL_ERROR);
1772             return;
1773         }
1774     }
1775 
1776     /*(note: not expecting any other pseudo-headers)*/
1777 
1778     /* note: expects field-names are lowercased (http_response_write_header())*/
1779 
1780     for (; i < hoff[0]; ++i) {
1781         const char *k = hdrs + ((i > 1) ? hoff[i] : 0);
1782         const char *end = hdrs + hoff[i+1];
1783         const char *v = memchr(k, ':', end-k);
1784         /* XXX: DOES NOT handle line wrapping (which is deprecated by RFCs)
1785          * (not expecting line wrapping; not produced internally by lighttpd,
1786          *  though possible from backends or with custom lua code)*/
1787         if (NULL == v || k == v) continue;
1788         uint32_t klen = v - k;
1789         if (0 == klen) continue;
1790         do { ++v; } while (*v == ' ' || *v == '\t'); /*(expect single ' ')*/
1791       #ifdef __COVERITY__
1792         /*(k has at least .:\n by now, so end[-2] valid)*/
1793         force_assert(end >= k + 2);
1794       #endif
1795         if (end[-2] != '\r') /*(header line must end "\r\n")*/
1796             continue;
1797         end -= 2;
1798         uint32_t vlen = end - v;
1799         if (0 == vlen) continue;
1800         memset(&lsx, 0, sizeof(lsxpack_header_t));
1801         *(const char **)&lsx.buf = hdrs;
1802         lsx.name_offset = k - hdrs;
1803         lsx.name_len = klen;
1804         lsx.val_offset = v - hdrs;
1805         lsx.val_len = vlen;
1806         unsigned char * const dst_in = dst;
1807         dst = lshpack_enc_encode(encoder, dst, dst_end, &lsx);
1808         if (dst == dst_in) {
1809             h2_send_rst_stream(r, con, H2_E_INTERNAL_ERROR);
1810             return;
1811         }
1812     }
1813     uint32_t dlen = (uint32_t)((char *)dst - tb->ptr);
1814     h2_send_hpack(r, con, tb->ptr, dlen, flags);
1815 }
1816 
1817 
1818 void
1819 h2_send_100_continue (request_st * const r, connection * const con)
1820 {
1821     /* place frame directly in con->write_queue for accounting to be part of
1822      * HTTP/2 protocol overhead, and not part of response header or body len */
1823     /* 100 Continue is small and will always fit in SETTING_MAX_FRAME_SIZE;
1824      * i.e. there will not be any CONTINUATION frames here */
1825 
1826     /* XXX: need to update hpack dynamic table,
1827      * or else could hard-code header block fragment
1828      * { 0x48, 0x03, 0x31, 0x30, 0x30 }
1829      */
1830 
1831     /* short header block, so reuse shared code used for trailers
1832      * rather than adding something specific for ls-hpack here */
1833 
1834     h2_send_headers_block(r, con, CONST_STR_LEN(":status: 100\r\n\r\n"), 0);
1835 }
1836 
1837 
1838 static void
1839 h2_send_end_stream_data (request_st * const r, connection * const con);
1840 
1841 __attribute_cold__
1842 __attribute_noinline__
1843 static void
1844 h2_send_end_stream_trailers (request_st * const r, connection * const con, const buffer * const trailers)
1845 {
1846     /*(trailers are merged into response headers if trailers are received before
1847      * sending response headers to client.  However, if streaming response, then
1848      * trailers might need handling here)*/
1849 
1850     /* parse and lowercase field-names in trailers */
1851     unsigned short hoff[8192]; /* max num header lines + 3; 16k on stack */
1852     hoff[0] = 1;                         /* number of lines */
1853     hoff[1] = 0;                         /* base offset for all lines */
1854     /*hoff[2] = ...;*/                   /* offset from base for 2nd line */
1855     uint32_t rc = http_header_parse_hoff(CONST_BUF_LEN(trailers), hoff);
1856     if (0 == rc || rc > USHRT_MAX || hoff[0] >= sizeof(hoff)/sizeof(hoff[0])-1
1857         || 1 == hoff[0]) { /*(initial blank line (should not happen))*/
1858         /* skip trailers if incomplete, too many fields, or too long (> 64k-1)*/
1859         h2_send_end_stream_data(r, con);
1860         return;
1861     }
1862 
1863     char * const ptr = trailers->ptr;
1864     for (int i = 1; i < hoff[0]; ++i) {
1865         char *k = ptr + ((i > 1) ? hoff[i] : 0);
1866         if (*k == ':') {
1867             /*(pseudo-header should not appear in trailers)*/
1868             h2_send_end_stream_data(r, con);
1869             return;
1870         }
1871         const char * const colon = memchr(k, ':', ptr+hoff[i+1]-k);
1872         if (NULL == colon) continue;
1873         do {
1874             if (*k >= 'A' && *k <= 'Z') *k |= 0x20;
1875         } while (++k != colon);
1876     }
1877 
1878     h2_send_headers_block(r, con, CONST_BUF_LEN(trailers), H2_FLAG_END_STREAM);
1879 }
1880 
1881 
1882 #if 0 /*(replaced by h2_send_headers())*/
1883 void
1884 h2_send_cqheaders (request_st * const r, connection * const con)
1885 {
1886     /*(assumes HTTP/1.1 response headers have been prepended as first chunk)
1887      *(future: if r->write_queue is bypassed for headers, adjust
1888      * r->write_queue bytes counts (bytes_in, bytes_out) with header len)*/
1889     /* note: expects field-names are lowercased (http_response_write_header())*/
1890     chunk * const c = r->write_queue->first;
1891     const uint32_t len = buffer_string_length(c->mem) - (uint32_t)c->offset;
1892     uint32_t flags = (r->resp_body_finished && NULL == c->next)
1893       ? H2_FLAG_END_STREAM
1894       : 0;
1895     h2_send_headers_block(r, con, c->mem->ptr + c->offset, len, flags);
1896     chunkqueue_mark_written(r->write_queue, len);
1897 }
1898 #endif
1899 
1900 
1901 #if 0
1902 
1903 void
1904 h2_send_data (request_st * const r, connection * const con, const char *data, uint32_t dlen)
1905 {
1906     /* Note: dlen should be <= MAX_WRITE_LIMIT in order to share resources */
1907 
1908     union {
1909       uint8_t c[12];
1910       uint32_t u[3];          /*(alignment)*/
1911     } dataframe = { {         /*(big-endian numbers)*/
1912       0x00, 0x00, 0x00        /* padding for alignment; do not send */
1913       /* DATA */
1914      ,0x00, 0x00, 0x00        /* frame length      (fill in below) */
1915      ,H2_FTYPE_DATA           /* frame type */
1916      ,0x00                    /* frame flags */
1917      ,0x00, 0x00, 0x00, 0x00  /* stream identifier (fill in below) */
1918     } };
1919 
1920     dataframe.u[2] = htonl(r->h2id);
1921 
1922     /* XXX: does not provide an optimization to send final set of data with
1923      *      END_STREAM flag; see h2_send_end_stream_data() to end stream */
1924 
1925     /* adjust stream and connection windows */
1926     /*assert(dlen <= INT32_MAX);*//* dlen should be <= MAX_WRITE_LIMIT */
1927     request_st * const h2r = &con->request;
1928     if (r->h2_swin   < 0) return;
1929     if (h2r->h2_swin < 0) return;
1930     if ((int32_t)dlen > r->h2_swin)   dlen = (uint32_t)r->h2_swin;
1931     if ((int32_t)dlen > h2r->h2_swin) dlen = (uint32_t)h2r->h2_swin;
1932     if (0 == dlen) return;
1933     r->h2_swin   -= (int32_t)dlen;
1934     h2r->h2_swin -= (int32_t)dlen;
1935 
1936     /* XXX: future: should have an interface which processes chunkqueue
1937      * and takes string refs to mmap FILE_CHUNK to avoid extra copying
1938      * since the result is likely to be consumed by TLS modules */
1939 
1940     /*(approximate space needed for frames (header + payload)
1941      * with slight over-estimate of 16 bytes per frame header (> 9)
1942      * and minimum SETTING_MAX_FRAME_SIZE of 16k (could be larger)
1943      * (dlen >> 14)+1 is num 16k frames needed, multipled by 16 bytes
1944      *  per frame can be appoximated with (dlen>>10) + 9)*/
1945     buffer * const b =
1946       chunkqueue_append_buffer_open_sz(con->write_queue, dlen + (dlen>>10) + 9);
1947     char * restrict ptr = b->ptr;
1948     h2con * const h2c = con->h2;
1949     const uint32_t fsize = h2c->s_max_frame_size;
1950     do {
1951         const uint32_t len = dlen < fsize ? dlen : fsize;
1952         dataframe.c[3] = (len >> 16) & 0xFF; /*(off +3 to skip over align pad)*/
1953         dataframe.c[4] = (len >>  8) & 0xFF;
1954         dataframe.c[5] = (len      ) & 0xFF;
1955       #if 0
1956         chunkqueue_append_mem(con->write_queue,  /*(+3 to skip over align pad)*/
1957                               (const char *)dataframe.c+3, sizeof(dataframe)-3);
1958         chunkqueue_append_mem(con->write_queue, data, len);
1959       #else
1960         memcpy(ptr, dataframe.c+3, sizeof(dataframe)-3);
1961         memcpy(ptr+sizeof(dataframe)-3, data, len);
1962         ptr  += len + sizeof(dataframe)-3;
1963       #endif
1964         data += len;
1965         dlen -= len;
1966     } while (dlen);
1967     buffer_string_set_length(b, (uint32_t)(ptr - b->ptr));
1968     chunkqueue_append_buffer_commit(con->write_queue);
1969 }
1970 
1971 #endif
1972 
1973 
1974 void
1975 h2_send_cqdata (request_st * const r, connection * const con, chunkqueue * const cq, uint32_t dlen)
1976 {
1977     /* Note: dlen should be <= MAX_WRITE_LIMIT in order to share resources */
1978 
1979     union {
1980       uint8_t c[12];
1981       uint32_t u[3];          /*(alignment)*/
1982     } dataframe = { {         /*(big-endian numbers)*/
1983       0x00, 0x00, 0x00        /* padding for alignment; do not send */
1984       /* DATA */
1985      ,0x00, 0x00, 0x00        /* frame length      (fill in below) */
1986      ,H2_FTYPE_DATA           /* frame type */
1987      ,0x00                    /* frame flags */
1988      ,0x00, 0x00, 0x00, 0x00  /* stream identifier (fill in below) */
1989     } };
1990 
1991     dataframe.u[2] = htonl(r->h2id);
1992 
1993     /* XXX: does not provide an optimization to send final set of data with
1994      *      END_STREAM flag; see h2_send_end_stream_data() to end stream */
1995 
1996     /* adjust stream and connection windows */
1997     /*assert(dlen <= INT32_MAX);*//* dlen should be <= MAX_WRITE_LIMIT */
1998     request_st * const h2r = &con->request;
1999     if (r->h2_swin   < 0) return;
2000     if (h2r->h2_swin < 0) return;
2001     if ((int32_t)dlen > r->h2_swin)   dlen = (uint32_t)r->h2_swin;
2002     if ((int32_t)dlen > h2r->h2_swin) dlen = (uint32_t)h2r->h2_swin;
2003     if (0 == dlen) return;
2004     r->h2_swin   -= (int32_t)dlen;
2005     h2r->h2_swin -= (int32_t)dlen;
2006 
2007     /* XXX: future: should have an interface which processes chunkqueue
2008      * and takes string refs to mmap FILE_CHUNK to avoid extra copying
2009      * since the result is likely to be consumed by TLS modules */
2010 
2011     h2con * const h2c = con->h2;
2012     const uint32_t fsize = h2c->s_max_frame_size;
2013     do {
2014         const uint32_t len = dlen < fsize ? dlen : fsize;
2015         dataframe.c[3] = (len >> 16) & 0xFF; /*(off +3 to skip over align pad)*/
2016         dataframe.c[4] = (len >>  8) & 0xFF;
2017         dataframe.c[5] = (len      ) & 0xFF;
2018         chunkqueue_append_mem(con->write_queue,  /*(+3 to skip over align pad)*/
2019                               (const char *)dataframe.c+3, sizeof(dataframe)-3);
2020         chunkqueue_steal(con->write_queue, cq, (off_t)dlen);
2021         dlen -= len;
2022     } while (dlen);
2023 }
2024 
2025 
2026 static void
2027 h2_send_end_stream_data (request_st * const r, connection * const con)
2028 {
2029     union {
2030       uint8_t c[12];
2031       uint32_t u[3];          /*(alignment)*/
2032     } dataframe = { {         /*(big-endian numbers)*/
2033       0x00, 0x00, 0x00        /* padding for alignment; do not send */
2034       /* DATA */
2035      ,0x00, 0x00, 0x00        /* frame length */
2036      ,H2_FTYPE_DATA           /* frame type */
2037      ,H2_FLAG_END_STREAM      /* frame flags */
2038      ,0x00, 0x00, 0x00, 0x00  /* stream identifier (fill in below) */
2039     } };
2040 
2041     dataframe.u[2] = htonl(r->h2id);
2042     r->h2state = H2_STATE_CLOSED;
2043     /*(ignore window updates when sending 0-length DATA frame with END_STREAM)*/
2044     chunkqueue_append_mem(con->write_queue,  /*(+3 to skip over align pad)*/
2045                           (const char *)dataframe.c+3, sizeof(dataframe)-3);
2046 }
2047 
2048 
2049 void
2050 h2_send_end_stream (request_st * const r, connection * const con)
2051 {
2052     if (r->state != CON_STATE_ERROR && r->resp_body_finished) {
2053         /* CON_STATE_RESPONSE_END */
2054         if (r->gw_dechunk && r->gw_dechunk->done
2055             && !buffer_is_empty(&r->gw_dechunk->b))
2056             h2_send_end_stream_trailers(r, con, &r->gw_dechunk->b);
2057         else
2058             h2_send_end_stream_data(r, con);
2059     }
2060     else { /* CON_STATE_ERROR */
2061         h2_send_rst_stream(r, con, H2_E_INTERNAL_ERROR);
2062     }
2063 }
2064 
2065 
2066 /*
2067  * (XXX: might move below to separate file)
2068  */
2069 #include "base64.h"
2070 #include "chunk.h"
2071 #include "plugin.h"
2072 #include "plugin_config.h"
2073 #include "reqpool.h"
2074 
2075 
2076 static request_st *
2077 h2_init_stream (request_st * const h2r, connection * const con)
2078 {
2079     h2con * const h2c = con->h2;
2080     ++con->request_count;
2081     force_assert(h2c->rused < sizeof(h2c->r)/sizeof(*h2c->r));
2082     /* initialize stream as subrequest (request_st *) */
2083     request_st * const r = request_acquire(con);
2084     /* XXX: TODO: assign default priority, etc.
2085      *      Perhaps store stream id and priority in separate table */
2086     h2c->r[h2c->rused++] = r;
2087     r->h2_rwin = h2c->s_initial_window_size;
2088     r->h2_swin = h2c->s_initial_window_size;
2089     r->http_version = HTTP_VERSION_2;
2090 
2091     /* copy config state from h2r */
2092     server * const srv = con->srv;
2093     const uint32_t used = srv->config_context->used;
2094     r->conditional_is_valid = h2r->conditional_is_valid;
2095     memcpy(r->cond_cache, h2r->cond_cache, used * sizeof(cond_cache_t));
2096   #ifdef HAVE_PCRE_H
2097     if (used > 1) /*(save 128b per con if no conditions)*/
2098         memcpy(r->cond_match, h2r->cond_match, used * sizeof(cond_match_t));
2099   #endif
2100     /*(see config_reset_config())*/
2101     r->server_name = h2r->server_name;
2102     memcpy(&r->conf, &h2r->conf, sizeof(request_config));
2103 
2104     /* stream id must be assigned by caller */
2105     return r;
2106 }
2107 
2108 
2109 static void
2110 h2_release_stream (request_st * const r, connection * const con)
2111 {
2112     if (r->http_status) {
2113         /* (see comment in connection_handle_response_end_state()) */
2114         plugins_call_handle_request_done(r);
2115 
2116       #if 0
2117         /* (fuzzy accounting for mod_accesslog, mod_rrdtool to avoid
2118          *  double counting, but HTTP/2 framing and HPACK-encoded headers in
2119          *  con->read_queue and con->write_queue are not equivalent to the
2120          *  HPACK-decoded headers and request and response bodies in stream
2121          *  r->read_queue and r->write_queue) */
2122         /* DISABLED since mismatches invalidate the relationship between
2123          * con->bytes_in and con->bytes_out */
2124         con->read_queue->bytes_in   -= r->read_queue->bytes_in;
2125         con->write_queue->bytes_out -= r->write_queue->bytes_out;
2126       #else
2127         UNUSED(con);
2128       #endif
2129     }
2130 
2131     request_release(r);
2132 }
2133 
2134 
2135 void
2136 h2_retire_stream (request_st *r, connection * const con)
2137 {
2138     if (r == NULL) return; /*(should not happen)*/
2139     h2con * const h2c = con->h2;
2140     request_st ** const ar = h2c->r;
2141     for (uint32_t i = 0, j = 0, rused = h2c->rused; i < rused; ++i) {
2142         if (ar[i] != r)
2143             ar[j++] = ar[i];
2144         else {
2145             h2_release_stream(r, con);
2146             r = NULL;
2147         }
2148     }
2149     if (r == NULL) /* found */
2150         h2c->r[--h2c->rused] = NULL;
2151     /*else ... should not happen*/
2152 }
2153 
2154 
2155 void
2156 h2_retire_con (request_st * const h2r, connection * const con)
2157 {
2158     h2con * const h2c = con->h2;
2159     if (NULL == h2c) return;
2160 
2161     if (h2r->state != CON_STATE_ERROR) { /*(CON_STATE_RESPONSE_END)*/
2162         h2_send_goaway(con, H2_E_NO_ERROR);
2163         for (uint32_t i = 0, rused = h2c->rused; i < rused; ++i) {
2164             /*(unexpected if CON_STATE_RESPONSE_END)*/
2165             request_st * const r = h2c->r[i];
2166             h2_send_rst_stream(r, con, H2_E_INTERNAL_ERROR);
2167             h2_release_stream(r, con);
2168         }
2169         if (!chunkqueue_is_empty(con->write_queue)) {
2170             /* similar to connection_handle_write() but without error checks,
2171              * without MAX_WRITE_LIMIT, and without connection throttling */
2172             /*h2r->conf.bytes_per_second = 0;*/         /* disable rate limit */
2173             /*h2r->conf.global_bytes_per_second = 0;*/  /* disable rate limit */
2174             /*con->traffic_limit_reached = 0;*/
2175             chunkqueue * const cq = con->write_queue;
2176             const off_t len = chunkqueue_length(cq);
2177             off_t written = cq->bytes_out;
2178             con->network_write(con, cq, len);
2179             /*(optional accounting)*/
2180             written = cq->bytes_out - written;
2181             con->bytes_written += written;
2182             con->bytes_written_cur_second += written;
2183             if (h2r->conf.global_bytes_per_second_cnt_ptr)
2184                 *(h2r->conf.global_bytes_per_second_cnt_ptr) += written;
2185         }
2186     }
2187     else { /* CON_STATE_ERROR */
2188         for (uint32_t i = 0, rused = h2c->rused; i < rused; ++i) {
2189             request_st * const r = h2c->r[i];
2190             h2_release_stream(r, con);
2191         }
2192         /* XXX: perhaps attempt to send GOAWAY?  Not when CON_STATE_ERROR */
2193     }
2194 
2195     con->h2 = NULL;
2196 
2197     /* future: might keep a pool of reusable (h2con *) */
2198     lshpack_enc_cleanup(&h2c->encoder);
2199     lshpack_dec_cleanup(&h2c->decoder);
2200     free(h2c);
2201 }
2202 
2203 
2204 static void
2205 h2_con_upgrade_h2c (request_st * const h2r, const buffer * const http2_settings)
2206 {
2207     /* status: (h2r->state == CON_STATE_REQUEST_END) for Upgrade: h2c */
2208 
2209     /* HTTP/1.1 101 Switching Protocols
2210      * Connection: Upgrade
2211      * Upgrade: h2c
2212      */
2213   #if 1
2214     static const char switch_proto[] = "HTTP/1.1 101 Switching Protocols\r\n"
2215                                        "Connection: Upgrade\r\n"
2216                                        "Upgrade: h2c\r\n\r\n";
2217     chunkqueue_append_mem(h2r->write_queue,
2218                           CONST_STR_LEN(switch_proto));
2219     h2r->resp_header_len = sizeof(switch_proto)-1;
2220   #else
2221     h2r->http_status = 101;
2222     http_header_response_set(h2r, HTTP_HEADER_UPGRADE, CONST_STR_LEN("Upgrade"),
2223                                                        CONST_STR_LEN("h2c"));
2224     http_response_write_header(h2r);
2225     http_response_reset(h2r);
2226     h2r->http_status = 0;
2227   #endif
2228 
2229     connection * const con = h2r->con;
2230     h2_init_con(h2r, con, http2_settings);
2231     if (con->h2->sent_goaway) return;
2232 
2233     con->h2->h2_cid = 1; /* stream id 1 is assigned to h2c upgrade */
2234 
2235     /* copy request state from &con->request to subrequest r
2236      * XXX: would be nice if there were a cleaner way to do this
2237      * (This is fragile and must be kept in-sync with request_st in request.h)*/
2238 
2239     request_st * const r = h2_init_stream(h2r, con);
2240     /*(undo double-count; already incremented in CON_STATE_REQUEST_START)*/
2241     --con->request_count;
2242     r->state = h2r->state; /* CON_STATE_REQUEST_END */
2243     r->http_status = 0;
2244     r->http_method = h2r->http_method;
2245     r->h2state = H2_STATE_HALF_CLOSED_REMOTE;
2246     r->h2id = 1;
2247     r->rqst_htags = h2r->rqst_htags;
2248     h2r->rqst_htags = 0;
2249     r->rqst_header_len = h2r->rqst_header_len;
2250     h2r->rqst_header_len = 0;
2251     r->rqst_headers = h2r->rqst_headers;        /* copy struct */
2252     memset(&h2r->rqst_headers, 0, sizeof(array));
2253     r->uri = h2r->uri;                          /* copy struct */
2254   #if 0
2255     r->physical = h2r->physical;                /* copy struct */
2256     r->env = h2r->env;                          /* copy struct */
2257   #endif
2258     memset(&h2r->rqst_headers, 0, sizeof(array));
2259     memset(&h2r->uri, 0, sizeof(request_uri));
2260   #if 0
2261     memset(&h2r->physical, 0, sizeof(physical));
2262     memset(&h2r->env, 0, sizeof(array));
2263   #endif
2264   #if 0 /* expect empty request body */
2265     r->reqbody_length = h2r->reqbody_length; /* currently always 0 */
2266     r->te_chunked = h2r->te_chunked;         /* must be 0 */
2267     swap(r->reqbody_queue, h2r->reqbody_queue); /*currently always empty queue*/
2268   #endif
2269     r->http_host = h2r->http_host;
2270     h2r->http_host = NULL;
2271   #if 0
2272     r->server_name = h2r->server_name;
2273     h2r->server_name = NULL;
2274   #endif
2275     r->target = h2r->target;                    /* copy struct */
2276     r->target_orig = h2r->target_orig;          /* copy struct */
2277   #if 0
2278     r->pathinfo = h2r->pathinfo;                /* copy struct */
2279     r->server_name_buf = h2r->server_name_buf;  /* copy struct */
2280   #endif
2281     memset(&h2r->target, 0, sizeof(buffer));
2282     memset(&h2r->target_orig, 0, sizeof(buffer));
2283   #if 0
2284     memset(&h2r->pathinfo, 0, sizeof(buffer));
2285     memset(&h2r->server_name_buf, 0, sizeof(buffer));
2286   #endif
2287   #if 0
2288     /* skip copying response structures, other state not yet modified in h2r */
2289     /* r write_queue and read_queue are intentionally separate from h2r */
2290     /* r->gw_dechunk must be NULL for HTTP/2 */
2291     /* bytes_written_ckpt and bytes_read_ckpt are for HTTP/1.1 */
2292     /* error handlers have not yet been set */
2293   #endif
2294   #if 0
2295     r->loops_per_request = h2r->loops_per_request;
2296     r->async_callback = h2r->async_callback;
2297   #endif
2298     r->keep_alive = h2r->keep_alive;
2299     r->tmp_buf = h2r->tmp_buf;                /* shared; same as srv->tmp_buf */
2300     r->start_hp = h2r->start_hp;                /* copy struct */
2301     r->start_ts = h2r->start_ts;
2302 
2303     /* Note: HTTP/1.1 101 Switching Protocols is not immediately written to
2304      * the network here.  As this is called from cleartext Upgrade: h2c,
2305      * we choose to delay sending the status until the beginning of the response
2306      * to the HTTP/1.1 request which included Upgrade: h2c */
2307 }
2308 
2309 
2310 int
2311 h2_check_con_upgrade_h2c (request_st * const r)
2312 {
2313     /* RFC7540 3.2 Starting HTTP/2 for "http" URIs */
2314 
2315     buffer *http_connection, *http2_settings;
2316     buffer *upgrade = http_header_request_get(r, HTTP_HEADER_UPGRADE,
2317                                               CONST_STR_LEN("Upgrade"));
2318     if (NULL == upgrade) return 0;
2319     http_connection = http_header_request_get(r, HTTP_HEADER_CONNECTION,
2320                                               CONST_STR_LEN("Connection"));
2321     if (NULL == http_connection) {
2322         http_header_request_unset(r, HTTP_HEADER_UPGRADE,
2323                                   CONST_STR_LEN("Upgrade"));
2324         return 0;
2325     }
2326     if (r->http_version != HTTP_VERSION_1_1) {
2327         http_header_request_unset(r, HTTP_HEADER_UPGRADE,
2328                                   CONST_STR_LEN("Upgrade"));
2329         http_header_remove_token(http_connection, CONST_STR_LEN("Upgrade"));
2330         return 0;
2331     }
2332 
2333     if (!http_header_str_contains_token(CONST_BUF_LEN(upgrade),
2334                                         CONST_STR_LEN("h2c")))
2335         return 0;
2336 
2337     http2_settings = http_header_request_get(r, HTTP_HEADER_HTTP2_SETTINGS,
2338                                              CONST_STR_LEN("HTTP2-Settings"));
2339     if (NULL != http2_settings) {
2340         if (0 == r->reqbody_length) {
2341             buffer * const b = r->tmp_buf;
2342             buffer_clear(b);
2343             if (r->conf.h2proto > 1/*(must be enabled with server.h2c feature)*/
2344                 &&
2345                 http_header_str_contains_token(CONST_BUF_LEN(http_connection),
2346                                                CONST_STR_LEN("HTTP2-Settings"))
2347                 && buffer_append_base64_decode(b, CONST_BUF_LEN(http2_settings),
2348                                                BASE64_URL)) {
2349                 h2_con_upgrade_h2c(r, b);
2350                 r->http_version = HTTP_VERSION_2;
2351             } /* else ignore if invalid base64 */
2352         }
2353         else {
2354             /* ignore Upgrade: h2c if request body present since we do not
2355              * (currently) handle request body before transition to h2c */
2356             /* RFC7540 3.2 Requests that contain a payload body MUST be sent
2357              * in their entirety before the client can send HTTP/2 frames. */
2358         }
2359         http_header_request_unset(r, HTTP_HEADER_HTTP2_SETTINGS,
2360                                   CONST_STR_LEN("HTTP2-Settings"));
2361         http_header_remove_token(http_connection, CONST_STR_LEN("HTTP2-Settings"));
2362     } /* else ignore Upgrade: h2c; HTTP2-Settings required for Upgrade: h2c */
2363     http_header_request_unset(r, HTTP_HEADER_UPGRADE,
2364                               CONST_STR_LEN("Upgrade"));
2365     http_header_remove_token(http_connection, CONST_STR_LEN("Upgrade"));
2366     return (r->http_version == HTTP_VERSION_2);
2367 }
2368