• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010 - 2019 Andy Green <andy@warmcat.com>
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to
8  * deal in the Software without restriction, including without limitation the
9  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10  * sell copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22  * IN THE SOFTWARE.
23  */
24 
25 #include "private-lib-core.h"
26 
27 /*
28  * bitmap of control messages that are valid to receive for each http2 state
29  */
30 
31 static const uint16_t http2_rx_validity[] = {
32 	/* LWS_H2S_IDLE */
33 		(1 << LWS_H2_FRAME_TYPE_SETTINGS) |
34 		(1 << LWS_H2_FRAME_TYPE_PRIORITY) |
35 //		(1 << LWS_H2_FRAME_TYPE_WINDOW_UPDATE)| /* ignore */
36 		(1 << LWS_H2_FRAME_TYPE_HEADERS) |
37 		(1 << LWS_H2_FRAME_TYPE_CONTINUATION),
38 	/* LWS_H2S_RESERVED_LOCAL */
39 		(1 << LWS_H2_FRAME_TYPE_SETTINGS) |
40 		(1 << LWS_H2_FRAME_TYPE_RST_STREAM) |
41 		(1 << LWS_H2_FRAME_TYPE_PRIORITY) |
42 		(1 << LWS_H2_FRAME_TYPE_WINDOW_UPDATE),
43 	/* LWS_H2S_RESERVED_REMOTE */
44 		(1 << LWS_H2_FRAME_TYPE_SETTINGS) |
45 		(1 << LWS_H2_FRAME_TYPE_HEADERS) |
46 		(1 << LWS_H2_FRAME_TYPE_CONTINUATION) |
47 		(1 << LWS_H2_FRAME_TYPE_RST_STREAM) |
48 		(1 << LWS_H2_FRAME_TYPE_PRIORITY),
49 	/* LWS_H2S_OPEN */
50 		(1 << LWS_H2_FRAME_TYPE_DATA) |
51 		(1 << LWS_H2_FRAME_TYPE_HEADERS) |
52 		(1 << LWS_H2_FRAME_TYPE_PRIORITY) |
53 		(1 << LWS_H2_FRAME_TYPE_RST_STREAM) |
54 		(1 << LWS_H2_FRAME_TYPE_SETTINGS) |
55 		(1 << LWS_H2_FRAME_TYPE_PUSH_PROMISE) |
56 		(1 << LWS_H2_FRAME_TYPE_PING) |
57 		(1 << LWS_H2_FRAME_TYPE_GOAWAY) |
58 		(1 << LWS_H2_FRAME_TYPE_WINDOW_UPDATE) |
59 		(1 << LWS_H2_FRAME_TYPE_CONTINUATION),
60 	/* LWS_H2S_HALF_CLOSED_REMOTE */
61 		(1 << LWS_H2_FRAME_TYPE_SETTINGS) |
62 		(1 << LWS_H2_FRAME_TYPE_WINDOW_UPDATE) |
63 		(1 << LWS_H2_FRAME_TYPE_PRIORITY) |
64 		(1 << LWS_H2_FRAME_TYPE_RST_STREAM),
65 	/* LWS_H2S_HALF_CLOSED_LOCAL */
66 		(1 << LWS_H2_FRAME_TYPE_DATA) |
67 		(1 << LWS_H2_FRAME_TYPE_HEADERS) |
68 		(1 << LWS_H2_FRAME_TYPE_PRIORITY) |
69 		(1 << LWS_H2_FRAME_TYPE_RST_STREAM) |
70 		(1 << LWS_H2_FRAME_TYPE_SETTINGS) |
71 		(1 << LWS_H2_FRAME_TYPE_PUSH_PROMISE) |
72 		(1 << LWS_H2_FRAME_TYPE_PING) |
73 		(1 << LWS_H2_FRAME_TYPE_GOAWAY) |
74 		(1 << LWS_H2_FRAME_TYPE_WINDOW_UPDATE) |
75 		(1 << LWS_H2_FRAME_TYPE_CONTINUATION),
76 	/* LWS_H2S_CLOSED */
77 		(1 << LWS_H2_FRAME_TYPE_SETTINGS) |
78 		(1 << LWS_H2_FRAME_TYPE_PRIORITY) |
79 		(1 << LWS_H2_FRAME_TYPE_WINDOW_UPDATE) |
80 		(1 << LWS_H2_FRAME_TYPE_RST_STREAM),
81 };
82 
83 static const char *preface = "PRI * HTTP/2.0\x0d\x0a\x0d\x0aSM\x0d\x0a\x0d\x0a";
84 
85 static const char * const h2_state_names[] = {
86 	"LWS_H2S_IDLE",
87 	"LWS_H2S_RESERVED_LOCAL",
88 	"LWS_H2S_RESERVED_REMOTE",
89 	"LWS_H2S_OPEN",
90 	"LWS_H2S_HALF_CLOSED_REMOTE",
91 	"LWS_H2S_HALF_CLOSED_LOCAL",
92 	"LWS_H2S_CLOSED",
93 };
94 
95 #if 0
96 static const char * const h2_setting_names[] = {
97 	"",
98 	"H2SET_HEADER_TABLE_SIZE",
99 	"H2SET_ENABLE_PUSH",
100 	"H2SET_MAX_CONCURRENT_STREAMS",
101 	"H2SET_INITIAL_WINDOW_SIZE",
102 	"H2SET_MAX_FRAME_SIZE",
103 	"H2SET_MAX_HEADER_LIST_SIZE",
104 	"reserved",
105 	"H2SET_ENABLE_CONNECT_PROTOCOL"
106 };
107 
108 void
109 lws_h2_dump_settings(struct http2_settings *set)
110 {
111 	int n;
112 
113 	for (n = 1; n < H2SET_COUNT; n++)
114 		lwsl_notice("   %30s: %10d\n", h2_setting_names[n], set->s[n]);
115 }
116 #else
117 void
lws_h2_dump_settings(struct http2_settings * set)118 lws_h2_dump_settings(struct http2_settings *set)
119 {
120 }
121 #endif
122 
123 struct lws_h2_protocol_send *
lws_h2_new_pps(enum lws_h2_protocol_send_type type)124 lws_h2_new_pps(enum lws_h2_protocol_send_type type)
125 {
126 	struct lws_h2_protocol_send *pps = lws_malloc(sizeof(*pps), "pps");
127 
128 	if (pps)
129 		pps->type = type;
130 
131 	return pps;
132 }
133 
lws_h2_init(struct lws * wsi)134 void lws_h2_init(struct lws *wsi)
135 {
136 	wsi->h2.h2n->our_set = wsi->vhost->h2.set;
137 	wsi->h2.h2n->peer_set = lws_h2_defaults;
138 }
139 
140 void
lws_h2_state(struct lws * wsi,enum lws_h2_states s)141 lws_h2_state(struct lws *wsi, enum lws_h2_states s)
142 {
143 	if (!wsi)
144 		return;
145 	lwsl_info("%s: wsi %p: state %s -> %s\n", __func__, wsi,
146 			h2_state_names[wsi->h2.h2_state],
147 			h2_state_names[s]);
148 
149 	(void)h2_state_names;
150 	wsi->h2.h2_state = (uint8_t)s;
151 }
152 
153 int
lws_h2_update_peer_txcredit(struct lws * wsi,int sid,int bump)154 lws_h2_update_peer_txcredit(struct lws *wsi, int sid, int bump)
155 {
156 	struct lws *nwsi = lws_get_network_wsi(wsi);
157 	struct lws_h2_protocol_send *pps;
158 
159 	assert(wsi);
160 
161 	if (!bump)
162 		return 0;
163 
164 	if (sid == -1)
165 		sid = wsi->mux.my_sid;
166 
167 	lwsl_info("%s: sid %d: bump %d -> %d\n", __func__, sid, bump,
168 			(int)wsi->txc.peer_tx_cr_est + bump);
169 
170 	pps = lws_h2_new_pps(LWS_H2_PPS_UPDATE_WINDOW);
171 	if (!pps)
172 		return 1;
173 
174 	pps->u.update_window.sid = sid;
175 	pps->u.update_window.credit = bump;
176 	wsi->txc.peer_tx_cr_est += bump;
177 
178 	lws_wsi_txc_describe(&wsi->txc, __func__, wsi->mux.my_sid);
179 
180 	lws_pps_schedule(wsi, pps);
181 
182 	pps = lws_h2_new_pps(LWS_H2_PPS_UPDATE_WINDOW);
183 	if (!pps)
184 		return 1;
185 
186 	pps->u.update_window.sid = 0;
187 	pps->u.update_window.credit = bump;
188 	nwsi->txc.peer_tx_cr_est += bump;
189 
190 	lws_wsi_txc_describe(&nwsi->txc, __func__, nwsi->mux.my_sid);
191 
192 	lws_pps_schedule(nwsi, pps);
193 
194 	return 0;
195 }
196 
197 int
lws_h2_get_peer_txcredit_estimate(struct lws * wsi)198 lws_h2_get_peer_txcredit_estimate(struct lws *wsi)
199 {
200 	lws_wsi_txc_describe(&wsi->txc, __func__, wsi->mux.my_sid);
201 	return (int)wsi->txc.peer_tx_cr_est;
202 }
203 
204 static int
lws_h2_update_peer_txcredit_thresh(struct lws * wsi,int sid,int threshold,int bump)205 lws_h2_update_peer_txcredit_thresh(struct lws *wsi, int sid, int threshold, int bump)
206 {
207 	if (wsi->txc.peer_tx_cr_est > threshold)
208 		return 0;
209 
210 	return lws_h2_update_peer_txcredit(wsi, sid, bump);
211 }
212 
213 struct lws *
lws_wsi_server_new(struct lws_vhost * vh,struct lws * parent_wsi,unsigned int sid)214 lws_wsi_server_new(struct lws_vhost *vh, struct lws *parent_wsi,
215 			    unsigned int sid)
216 {
217 	struct lws *wsi;
218 	struct lws *nwsi = lws_get_network_wsi(parent_wsi);
219 	struct lws_h2_netconn *h2n = nwsi->h2.h2n;
220 
221 	/*
222 	 * The identifier of a newly established stream MUST be numerically
223    	 * greater than all streams that the initiating endpoint has opened or
224    	 * reserved.  This governs streams that are opened using a HEADERS frame
225    	 * and streams that are reserved using PUSH_PROMISE.  An endpoint that
226    	 * receives an unexpected stream identifier MUST respond with a
227    	 * connection error (Section 5.4.1) of type PROTOCOL_ERROR.
228 	 */
229 	if (sid <= h2n->highest_sid_opened) {
230 		lwsl_info("%s: tried to open lower sid %d (%d)\n", __func__,
231 				sid, (int)h2n->highest_sid_opened);
232 		lws_h2_goaway(nwsi, H2_ERR_PROTOCOL_ERROR, "Bad sid");
233 		return NULL;
234 	}
235 
236 	/* no more children allowed by parent */
237 	if (parent_wsi->mux.child_count + 1 >
238 	    parent_wsi->h2.h2n->our_set.s[H2SET_MAX_CONCURRENT_STREAMS]) {
239 		lwsl_notice("reached concurrent stream limit\n");
240 		return NULL;
241 	}
242 	wsi = lws_create_new_server_wsi(vh, parent_wsi->tsi);
243 	if (!wsi) {
244 		lwsl_notice("new server wsi failed (vh %p)\n", vh);
245 		return NULL;
246 	}
247 
248 	h2n->highest_sid_opened = sid;
249 
250 	lws_wsi_mux_insert(wsi, parent_wsi, sid);
251 
252 	wsi->mux_substream = 1;
253 	wsi->seen_nonpseudoheader = 0;
254 
255 	wsi->txc.tx_cr = nwsi->h2.h2n->peer_set.s[H2SET_INITIAL_WINDOW_SIZE];
256 	wsi->txc.peer_tx_cr_est =
257 			nwsi->h2.h2n->our_set.s[H2SET_INITIAL_WINDOW_SIZE];
258 
259 	lwsi_set_state(wsi, LRS_ESTABLISHED);
260 	lwsi_set_role(wsi, lwsi_role(parent_wsi));
261 
262 	wsi->protocol = &vh->protocols[0];
263 	if (lws_ensure_user_space(wsi))
264 		goto bail1;
265 
266 #if defined(LWS_WITH_SERVER_STATUS)
267 	wsi->vhost->conn_stats.h2_subs++;
268 #endif
269 
270 	/* get the ball rolling */
271 	lws_validity_confirmed(wsi);
272 
273 	lwsl_info("%s: %p new ch %p, sid %d, usersp=%p\n", __func__,
274 		  parent_wsi, wsi, sid, wsi->user_space);
275 
276 	lws_wsi_txc_describe(&wsi->txc, __func__, wsi->mux.my_sid);
277 	lws_wsi_txc_describe(&nwsi->txc, __func__, 0);
278 
279 	return wsi;
280 
281 bail1:
282 	/* undo the insert */
283 	parent_wsi->mux.child_list = wsi->mux.sibling_list;
284 	parent_wsi->mux.child_count--;
285 
286 	vh->context->count_wsi_allocated--;
287 
288 	if (wsi->user_space)
289 		lws_free_set_NULL(wsi->user_space);
290 	vh->protocols[0].callback(wsi, LWS_CALLBACK_WSI_DESTROY, NULL, NULL, 0);
291 	lws_vhost_unbind_wsi(wsi);
292 	lws_free(wsi);
293 
294 	return NULL;
295 }
296 
297 struct lws *
lws_wsi_h2_adopt(struct lws * parent_wsi,struct lws * wsi)298 lws_wsi_h2_adopt(struct lws *parent_wsi, struct lws *wsi)
299 {
300 	struct lws *nwsi = lws_get_network_wsi(parent_wsi);
301 
302 	/* no more children allowed by parent */
303 	if (parent_wsi->mux.child_count + 1 >
304 	    parent_wsi->h2.h2n->our_set.s[H2SET_MAX_CONCURRENT_STREAMS]) {
305 		lwsl_notice("reached concurrent stream limit\n");
306 		return NULL;
307 	}
308 
309 	/* sid is set just before issuing the headers, ensuring monoticity */
310 
311 	wsi->seen_nonpseudoheader = 0;
312 #if defined(LWS_WITH_CLIENT)
313 	wsi->client_mux_substream = 1;
314 #endif
315 	wsi->h2.initialized = 1;
316 
317 	if (!wsi->mux.my_sid) {
318 		wsi->mux.my_sid = nwsi->h2.h2n->highest_sid;
319 		nwsi->h2.h2n->highest_sid += 2;
320 	}
321 
322 	lws_wsi_mux_insert(wsi, parent_wsi, wsi->mux.my_sid);
323 
324 	wsi->txc.tx_cr = nwsi->h2.h2n->peer_set.s[H2SET_INITIAL_WINDOW_SIZE];
325 	wsi->txc.peer_tx_cr_est =
326 			nwsi->h2.h2n->our_set.s[H2SET_INITIAL_WINDOW_SIZE];
327 
328 	lws_wsi_txc_describe(&wsi->txc, __func__, wsi->mux.my_sid);
329 
330 	if (lws_ensure_user_space(wsi))
331 		goto bail1;
332 
333 	lws_role_transition(wsi, LWSIFR_CLIENT, LRS_H2_WAITING_TO_SEND_HEADERS,
334 			    &role_ops_h2);
335 
336 	lws_callback_on_writable(wsi);
337 
338 #if defined(LWS_WITH_SERVER_STATUS)
339 	wsi->vhost->conn_stats.h2_subs++;
340 #endif
341 
342 	return wsi;
343 
344 bail1:
345 	/* undo the insert */
346 	parent_wsi->mux.child_list = wsi->mux.sibling_list;
347 	parent_wsi->mux.child_count--;
348 
349 	if (wsi->user_space)
350 		lws_free_set_NULL(wsi->user_space);
351 	wsi->protocol->callback(wsi, LWS_CALLBACK_WSI_DESTROY, NULL, NULL, 0);
352 	lws_free(wsi);
353 
354 	return NULL;
355 }
356 
357 
lws_h2_issue_preface(struct lws * wsi)358 int lws_h2_issue_preface(struct lws *wsi)
359 {
360 	struct lws_h2_netconn *h2n = wsi->h2.h2n;
361 	struct lws_h2_protocol_send *pps;
362 
363 	if (lws_issue_raw(wsi, (uint8_t *)preface, strlen(preface)) !=
364 		(int)strlen(preface))
365 		return 1;
366 
367 	lws_role_transition(wsi, LWSIFR_CLIENT, LRS_H2_WAITING_TO_SEND_HEADERS,
368 			    &role_ops_h2);
369 
370 	h2n->count = 0;
371 	wsi->txc.tx_cr = 65535;
372 
373 	/*
374 	 * we must send a settings frame
375 	 */
376 	pps = lws_h2_new_pps(LWS_H2_PPS_MY_SETTINGS);
377 	if (!pps)
378 		return 1;
379 	lws_pps_schedule(wsi, pps);
380 	lwsl_info("%s: h2 client sending settings\n", __func__);
381 
382 	return 0;
383 }
384 
385 void
lws_pps_schedule(struct lws * wsi,struct lws_h2_protocol_send * pps)386 lws_pps_schedule(struct lws *wsi, struct lws_h2_protocol_send *pps)
387 {
388 	struct lws *nwsi = lws_get_network_wsi(wsi);
389 	struct lws_h2_netconn *h2n = nwsi->h2.h2n;
390 
391 	pps->next = h2n->pps;
392 	h2n->pps = pps;
393 	lws_rx_flow_control(wsi, LWS_RXFLOW_REASON_APPLIES_DISABLE |
394 				 LWS_RXFLOW_REASON_H2_PPS_PENDING);
395 	lws_callback_on_writable(wsi);
396 }
397 
398 int
lws_h2_goaway(struct lws * wsi,uint32_t err,const char * reason)399 lws_h2_goaway(struct lws *wsi, uint32_t err, const char *reason)
400 {
401 	struct lws_h2_netconn *h2n = wsi->h2.h2n;
402 	struct lws_h2_protocol_send *pps;
403 
404 	if (h2n->type == LWS_H2_FRAME_TYPE_COUNT)
405 		return 0;
406 
407 	pps = lws_h2_new_pps(LWS_H2_PPS_GOAWAY);
408 	if (!pps)
409 		return 1;
410 
411 	lwsl_info("%s: %p: ERR 0x%x, '%s'\n", __func__, wsi, (int)err, reason);
412 
413 	pps->u.ga.err = err;
414 	pps->u.ga.highest_sid = h2n->highest_sid;
415 	lws_strncpy(pps->u.ga.str, reason, sizeof(pps->u.ga.str));
416 	lws_pps_schedule(wsi, pps);
417 
418 	h2n->type = LWS_H2_FRAME_TYPE_COUNT; /* ie, IGNORE */
419 
420 	return 0;
421 }
422 
423 int
lws_h2_rst_stream(struct lws * wsi,uint32_t err,const char * reason)424 lws_h2_rst_stream(struct lws *wsi, uint32_t err, const char *reason)
425 {
426 	struct lws *nwsi = lws_get_network_wsi(wsi);
427 	struct lws_h2_netconn *h2n = nwsi->h2.h2n;
428 	struct lws_h2_protocol_send *pps;
429 
430 	if (!h2n)
431 		return 0;
432 
433 	if (!wsi->h2_stream_carries_ws && h2n->type == LWS_H2_FRAME_TYPE_COUNT)
434 		return 0;
435 
436 	pps = lws_h2_new_pps(LWS_H2_PPS_RST_STREAM);
437 	if (!pps)
438 		return 1;
439 
440 	lwsl_info("%s: RST_STREAM 0x%x, sid %d, REASON '%s'\n", __func__,
441 		  (int)err, wsi->mux.my_sid, reason);
442 
443 	pps->u.rs.sid = wsi->mux.my_sid;
444 	pps->u.rs.err = err;
445 
446 	lws_pps_schedule(wsi, pps);
447 
448 	h2n->type = LWS_H2_FRAME_TYPE_COUNT; /* ie, IGNORE */
449 	lws_h2_state(wsi, LWS_H2_STATE_CLOSED);
450 
451 	return 0;
452 }
453 
454 int
lws_h2_settings(struct lws * wsi,struct http2_settings * settings,unsigned char * buf,int len)455 lws_h2_settings(struct lws *wsi, struct http2_settings *settings,
456 		unsigned char *buf, int len)
457 {
458 	struct lws *nwsi = lws_get_network_wsi(wsi);
459 	unsigned int a, b;
460 
461 	if (!len)
462 		return 0;
463 
464 	if (len < LWS_H2_SETTINGS_LEN)
465 		return 1;
466 
467 	while (len >= LWS_H2_SETTINGS_LEN) {
468 		a = (buf[0] << 8) | buf[1];
469 		if (!a || a >= H2SET_COUNT)
470 			goto skip;
471 		b = buf[2] << 24 | buf[3] << 16 | buf[4] << 8 | buf[5];
472 
473 		switch (a) {
474 		case H2SET_HEADER_TABLE_SIZE:
475 			break;
476 		case H2SET_ENABLE_PUSH:
477 			if (b > 1) {
478 				lws_h2_goaway(nwsi, H2_ERR_PROTOCOL_ERROR,
479 					      "ENABLE_PUSH invalid arg");
480 				return 1;
481 			}
482 			break;
483 		case H2SET_MAX_CONCURRENT_STREAMS:
484 			break;
485 		case H2SET_INITIAL_WINDOW_SIZE:
486 			if (b > 0x7fffffff) {
487 				lws_h2_goaway(nwsi, H2_ERR_FLOW_CONTROL_ERROR,
488 					      "Inital Window beyond max");
489 				return 1;
490 			}
491 
492 #if defined(LWS_WITH_CLIENT)
493 #if defined(LWS_AMAZON_RTOS) || defined(LWS_AMAZON_LINUX)
494 			if (
495 #else
496 			if (wsi->flags & LCCSCF_H2_QUIRK_OVERFLOWS_TXCR &&
497 #endif
498 			    b == 0x7fffffff) {
499 				b >>= 4;
500 
501 				break;
502 			}
503 #endif
504 
505 			/*
506 			 * In addition to changing the flow-control window for
507 			 * streams that are not yet active, a SETTINGS frame
508 			 * can alter the initial flow-control window size for
509 			 * streams with active flow-control windows (that is,
510 			 * streams in the "open" or "half-closed (remote)"
511 			 * state).  When the value of
512 			 * SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver
513 			 * MUST adjust the size of all stream flow-control
514 			 * windows that it maintains by the difference between
515 			 * the new value and the old value.
516 			 */
517 
518 			lws_start_foreach_ll(struct lws *, w,
519 					     nwsi->mux.child_list) {
520 				lwsl_info("%s: adi child tc cr %d +%d -> %d",
521 					  __func__, (int)w->txc.tx_cr,
522 					  b - (unsigned int)settings->s[a],
523 					  (int)w->txc.tx_cr + b -
524 						  (unsigned int)settings->s[a]);
525 				w->txc.tx_cr += b - settings->s[a];
526 				if (w->txc.tx_cr > 0 &&
527 				    w->txc.tx_cr <=
528 						  (int32_t)(b - settings->s[a]))
529 
530 					lws_callback_on_writable(w);
531 			} lws_end_foreach_ll(w, mux.sibling_list);
532 
533 			break;
534 		case H2SET_MAX_FRAME_SIZE:
535 			if (b < wsi->vhost->h2.set.s[H2SET_MAX_FRAME_SIZE]) {
536 				lws_h2_goaway(nwsi, H2_ERR_PROTOCOL_ERROR,
537 					      "Frame size < initial");
538 				return 1;
539 			}
540 			if (b > 0x00ffffff) {
541 				lws_h2_goaway(nwsi, H2_ERR_PROTOCOL_ERROR,
542 					      "Settings Frame size above max");
543 				return 1;
544 			}
545 			break;
546 		case H2SET_MAX_HEADER_LIST_SIZE:
547 			break;
548 		}
549 		settings->s[a] = b;
550 		lwsl_info("http2 settings %d <- 0x%x\n", a, b);
551 skip:
552 		len -= LWS_H2_SETTINGS_LEN;
553 		buf += LWS_H2_SETTINGS_LEN;
554 	}
555 
556 	if (len)
557 		return 1;
558 
559 	lws_h2_dump_settings(settings);
560 
561 	return 0;
562 }
563 
564 /* RFC7640 Sect 6.9
565  *
566  * The WINDOW_UPDATE frame can be specific to a stream or to the entire
567  * connection.  In the former case, the frame's stream identifier
568  * indicates the affected stream; in the latter, the value "0" indicates
569  * that the entire connection is the subject of the frame.
570  *
571  * ...
572  *
573  * Two flow-control windows are applicable: the stream flow-control
574  * window and the connection flow-control window.  The sender MUST NOT
575  * send a flow-controlled frame with a length that exceeds the space
576  * available in either of the flow-control windows advertised by the
577  * receiver.  Frames with zero length with the END_STREAM flag set (that
578  * is, an empty DATA frame) MAY be sent if there is no available space
579  * in either flow-control window.
580  */
581 
582 int
lws_h2_tx_cr_get(struct lws * wsi)583 lws_h2_tx_cr_get(struct lws *wsi)
584 {
585 	int c = wsi->txc.tx_cr;
586 	struct lws *nwsi = lws_get_network_wsi(wsi);
587 
588 	if (!wsi->mux_substream && !nwsi->upgraded_to_http2)
589 		return ~0x80000000;
590 
591 	lwsl_info ("%s: %p: own tx credit %d: nwsi credit %d\n",
592 		     __func__, wsi, c, (int)nwsi->txc.tx_cr);
593 
594 	if (nwsi->txc.tx_cr < c)
595 		c = nwsi->txc.tx_cr;
596 
597 	if (c < 0)
598 		return 0;
599 
600 	return c;
601 }
602 
603 void
lws_h2_tx_cr_consume(struct lws * wsi,int consumed)604 lws_h2_tx_cr_consume(struct lws *wsi, int consumed)
605 {
606 	struct lws *nwsi = lws_get_network_wsi(wsi);
607 
608 	wsi->txc.tx_cr -= consumed;
609 
610 	if (nwsi != wsi)
611 		nwsi->txc.tx_cr -= consumed;
612 }
613 
lws_h2_frame_write(struct lws * wsi,int type,int flags,unsigned int sid,unsigned int len,unsigned char * buf)614 int lws_h2_frame_write(struct lws *wsi, int type, int flags,
615 		       unsigned int sid, unsigned int len, unsigned char *buf)
616 {
617 	struct lws *nwsi = lws_get_network_wsi(wsi);
618 	unsigned char *p = &buf[-LWS_H2_FRAME_HEADER_LENGTH];
619 	int n;
620 
621 	//if (wsi->h2_stream_carries_ws)
622 	// lwsl_hexdump_level(LLL_NOTICE, buf, len);
623 
624 	*p++ = len >> 16;
625 	*p++ = len >> 8;
626 	*p++ = len;
627 	*p++ = type;
628 	*p++ = flags;
629 	*p++ = sid >> 24;
630 	*p++ = sid >> 16;
631 	*p++ = sid >> 8;
632 	*p++ = sid;
633 
634 	lwsl_debug("%s: %p (eff %p). typ %d, fl 0x%x, sid=%d, len=%d, "
635 		   "txcr=%d, nwsi->txcr=%d\n", __func__, wsi, nwsi, type, flags,
636 		   sid, len, (int)wsi->txc.tx_cr, (int)nwsi->txc.tx_cr);
637 
638 	if (type == LWS_H2_FRAME_TYPE_DATA) {
639 		if (wsi->txc.tx_cr < (int)len)
640 			lwsl_info("%s: %p: sending payload len %d"
641 				 " but tx_cr only %d!\n", __func__, wsi,
642 				 len, (int)wsi->txc.tx_cr);
643 		lws_h2_tx_cr_consume(wsi, len);
644 	}
645 
646 	n = lws_issue_raw(nwsi, &buf[-LWS_H2_FRAME_HEADER_LENGTH],
647 			  len + LWS_H2_FRAME_HEADER_LENGTH);
648 	if (n < 0)
649 		return n;
650 
651 	if (n >= LWS_H2_FRAME_HEADER_LENGTH)
652 		return n - LWS_H2_FRAME_HEADER_LENGTH;
653 
654 	return n;
655 }
656 
lws_h2_set_bin(struct lws * wsi,int n,unsigned char * buf)657 static void lws_h2_set_bin(struct lws *wsi, int n, unsigned char *buf)
658 {
659 	*buf++ = n >> 8;
660 	*buf++ = n;
661 	*buf++ = wsi->h2.h2n->our_set.s[n] >> 24;
662 	*buf++ = wsi->h2.h2n->our_set.s[n] >> 16;
663 	*buf++ = wsi->h2.h2n->our_set.s[n] >> 8;
664 	*buf = wsi->h2.h2n->our_set.s[n];
665 }
666 
667 /* we get called on the network connection */
668 
lws_h2_do_pps_send(struct lws * wsi)669 int lws_h2_do_pps_send(struct lws *wsi)
670 {
671 	struct lws_h2_netconn *h2n = wsi->h2.h2n;
672 	struct lws_h2_protocol_send *pps = NULL;
673 	struct lws *cwsi;
674 	uint8_t set[LWS_PRE + 64], *p = &set[LWS_PRE], *q;
675 	int n, m = 0, flags = 0;
676 
677 	if (!h2n)
678 		return 1;
679 
680 	/* get the oldest pps */
681 
682 	lws_start_foreach_llp(struct lws_h2_protocol_send **, pps1, h2n->pps) {
683 		if ((*pps1)->next == NULL) { /* we are the oldest in the list */
684 			pps = *pps1; /* remove us from the list */
685 			*pps1 = NULL;
686 			continue;
687 		}
688 	} lws_end_foreach_llp(pps1, next);
689 
690 	if (!pps)
691 		return 1;
692 
693 	lwsl_info("%s: %p: %d\n", __func__, wsi, pps->type);
694 
695 	switch (pps->type) {
696 
697 	case LWS_H2_PPS_MY_SETTINGS:
698 
699 		/*
700 		 * if any of our settings varies from h2 "default defaults"
701 		 * then we must inform the peer
702 		 */
703 		for (n = 1; n < H2SET_COUNT; n++)
704 			if (h2n->our_set.s[n] != lws_h2_defaults.s[n]) {
705 				lwsl_debug("sending SETTING %d 0x%x\n", n,
706 					   (unsigned int)
707 						   wsi->h2.h2n->our_set.s[n]);
708 
709 				lws_h2_set_bin(wsi, n, &set[LWS_PRE + m]);
710 				m += sizeof(h2n->one_setting);
711 			}
712 		n = lws_h2_frame_write(wsi, LWS_H2_FRAME_TYPE_SETTINGS,
713 				       flags, LWS_H2_STREAM_ID_MASTER, m,
714 		     		       &set[LWS_PRE]);
715 		if (n != m) {
716 			lwsl_info("send %d %d\n", n, m);
717 			goto bail;
718 		}
719 		break;
720 
721 	case LWS_H2_PPS_SETTINGS_INITIAL_UPDATE_WINDOW:
722 		q = &set[LWS_PRE];
723 		*q++ = H2SET_INITIAL_WINDOW_SIZE >> 8;
724 		*q++ = H2SET_INITIAL_WINDOW_SIZE;
725 		*q++ = pps->u.update_window.credit >> 24;
726 		*q++ = pps->u.update_window.credit >> 16;
727 		*q++ = pps->u.update_window.credit >> 8;
728 		*q = pps->u.update_window.credit;
729 
730 		lwsl_debug("%s: resetting initial window to %d\n", __func__,
731 				(int)pps->u.update_window.credit);
732 
733 		n = lws_h2_frame_write(wsi, LWS_H2_FRAME_TYPE_SETTINGS,
734 				       flags, LWS_H2_STREAM_ID_MASTER, 6,
735 		     		       &set[LWS_PRE]);
736 		if (n != 6) {
737 			lwsl_info("send %d %d\n", n, m);
738 			goto bail;
739 		}
740 		break;
741 
742 	case LWS_H2_PPS_ACK_SETTINGS:
743 		/* send ack ... always empty */
744 		n = lws_h2_frame_write(wsi, LWS_H2_FRAME_TYPE_SETTINGS, 1,
745 				       LWS_H2_STREAM_ID_MASTER, 0,
746 				       &set[LWS_PRE]);
747 		if (n) {
748 			lwsl_err("ack tells %d\n", n);
749 			goto bail;
750 		}
751 		wsi->h2_acked_settings = 0;
752 		/* this is the end of the preface dance then? */
753 		if (lwsi_state(wsi) == LRS_H2_AWAIT_SETTINGS) {
754 			lwsi_set_state(wsi, LRS_ESTABLISHED);
755 #if defined(LWS_WITH_FILE_OPS)
756 			wsi->http.fop_fd = NULL;
757 #endif
758 			if (lws_is_ssl(lws_get_network_wsi(wsi)))
759 				break;
760 			/*
761 			 * we need to treat the headers from the upgrade as the
762 			 * first job.  So these need to get shifted to sid 1.
763 			 */
764 			h2n->swsi = lws_wsi_server_new(wsi->vhost, wsi, 1);
765 			if (!h2n->swsi)
766 				goto bail;
767 
768 			/* pass on the initial headers to SID 1 */
769 			h2n->swsi->http.ah = wsi->http.ah;
770 			wsi->http.ah = NULL;
771 
772 			lwsl_info("%s: inherited headers %p\n", __func__,
773 				  h2n->swsi->http.ah);
774 			h2n->swsi->txc.tx_cr =
775 				h2n->our_set.s[H2SET_INITIAL_WINDOW_SIZE];
776 			lwsl_info("initial tx credit on conn %p: %d\n",
777 				  h2n->swsi, (int)h2n->swsi->txc.tx_cr);
778 			h2n->swsi->h2.initialized = 1;
779 			/* demanded by HTTP2 */
780 			h2n->swsi->h2.END_STREAM = 1;
781 			lwsl_info("servicing initial http request\n");
782 
783 #if defined(LWS_WITH_SERVER_STATUS)
784 			wsi->vhost->conn_stats.h2_trans++;
785 #endif
786 #if defined(LWS_WITH_SERVER)
787 			if (lws_http_action(h2n->swsi))
788 				goto bail;
789 #endif
790 			break;
791 		}
792 		break;
793 
794 	/*
795 	 * h2 only has PING... ACK = 0 = ping, ACK = 1 = pong
796 	 */
797 
798 	case LWS_H2_PPS_PING:
799 	case LWS_H2_PPS_PONG:
800 		if (pps->type == LWS_H2_PPS_PING)
801 			lwsl_info("sending PING\n");
802 		else {
803 			lwsl_info("sending PONG\n");
804 			flags = LWS_H2_FLAG_SETTINGS_ACK;
805 		}
806 
807 		memcpy(&set[LWS_PRE], pps->u.ping.ping_payload, 8);
808 		n = lws_h2_frame_write(wsi, LWS_H2_FRAME_TYPE_PING, flags,
809 				       LWS_H2_STREAM_ID_MASTER, 8,
810 				       &set[LWS_PRE]);
811 		if (n != 8)
812 			goto bail;
813 
814 		break;
815 
816 	case LWS_H2_PPS_GOAWAY:
817 		lwsl_info("LWS_H2_PPS_GOAWAY\n");
818 		*p++ = pps->u.ga.highest_sid >> 24;
819 		*p++ = pps->u.ga.highest_sid >> 16;
820 		*p++ = pps->u.ga.highest_sid >> 8;
821 		*p++ = pps->u.ga.highest_sid;
822 		*p++ = pps->u.ga.err >> 24;
823 		*p++ = pps->u.ga.err >> 16;
824 		*p++ = pps->u.ga.err >> 8;
825 		*p++ = pps->u.ga.err;
826 		q = (unsigned char *)pps->u.ga.str;
827 		n = 0;
828 		while (*q && n++ < (int)sizeof(pps->u.ga.str))
829 			*p++ = *q++;
830 		h2n->we_told_goaway = 1;
831 		n = lws_h2_frame_write(wsi, LWS_H2_FRAME_TYPE_GOAWAY, 0,
832 				       LWS_H2_STREAM_ID_MASTER,
833 				       lws_ptr_diff(p, &set[LWS_PRE]),
834 				       &set[LWS_PRE]);
835 		if (n != 4) {
836 			lwsl_info("send %d %d\n", n, m);
837 			goto bail;
838 		}
839 		goto bail;
840 
841 	case LWS_H2_PPS_RST_STREAM:
842 		lwsl_info("LWS_H2_PPS_RST_STREAM\n");
843 		*p++ = pps->u.rs.err >> 24;
844 		*p++ = pps->u.rs.err >> 16;
845 		*p++ = pps->u.rs.err >> 8;
846 		*p++ = pps->u.rs.err;
847 		n = lws_h2_frame_write(wsi, LWS_H2_FRAME_TYPE_RST_STREAM,
848 				       0, pps->u.rs.sid, 4, &set[LWS_PRE]);
849 		if (n != 4) {
850 			lwsl_info("send %d %d\n", n, m);
851 			goto bail;
852 		}
853 		cwsi = lws_wsi_mux_from_id(wsi, pps->u.rs.sid);
854 		if (cwsi) {
855 			lwsl_debug("%s: closing cwsi %p %s %s (wsi %p)\n",
856 				   __func__, cwsi, cwsi->role_ops->name,
857 				   cwsi->protocol->name, wsi);
858 			lws_close_free_wsi(cwsi, 0, "reset stream");
859 		}
860 		break;
861 
862 	case LWS_H2_PPS_UPDATE_WINDOW:
863 		lwsl_info("Issuing LWS_H2_PPS_UPDATE_WINDOW: sid %d: add %d\n",
864 			    (int)pps->u.update_window.sid,
865 			    (int)pps->u.update_window.credit);
866 		*p++ = (pps->u.update_window.credit >> 24) & 0x7f; /* 31b */
867 		*p++ = pps->u.update_window.credit >> 16;
868 		*p++ = pps->u.update_window.credit >> 8;
869 		*p++ = pps->u.update_window.credit;
870 		n = lws_h2_frame_write(wsi, LWS_H2_FRAME_TYPE_WINDOW_UPDATE,
871 				       0, pps->u.update_window.sid, 4,
872 				       &set[LWS_PRE]);
873 		if (n != 4) {
874 			lwsl_info("send %d %d\n", n, m);
875 			goto bail;
876 		}
877 		break;
878 
879 	default:
880 		break;
881 	}
882 
883 	lws_free(pps);
884 
885 	return 0;
886 
887 bail:
888 	lws_free(pps);
889 
890 	return 1;
891 }
892 
893 static int
894 lws_h2_parse_end_of_frame(struct lws *wsi);
895 
896 /*
897  * The frame header part has just completely arrived.
898  * Perform actions for header completion.
899  */
900 static int
lws_h2_parse_frame_header(struct lws * wsi)901 lws_h2_parse_frame_header(struct lws *wsi)
902 {
903 	struct lws_h2_netconn *h2n = wsi->h2.h2n;
904 	struct lws_h2_protocol_send *pps;
905 	int n;
906 
907 	/*
908 	 * We just got the frame header
909 	 */
910 	h2n->count = 0;
911 	h2n->swsi = wsi;
912 	/* b31 is a reserved bit */
913 	h2n->sid = h2n->sid & 0x7fffffff;
914 
915 	if (h2n->sid && !(h2n->sid & 1)) {
916 		lws_h2_goaway(wsi, H2_ERR_PROTOCOL_ERROR, "Even Stream ID");
917 
918 		return 0;
919 	}
920 
921 	/* let the network wsi live a bit longer if subs are active */
922 
923 	if (!wsi->immortal_substream_count)
924 		lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE,
925 				wsi->vhost->keepalive_timeout ?
926 					wsi->vhost->keepalive_timeout : 31);
927 
928 	if (h2n->sid)
929 		h2n->swsi = lws_wsi_mux_from_id(wsi, h2n->sid);
930 
931 	lwsl_debug("%p (%p): fr hdr: typ 0x%x, fla 0x%x, sid 0x%x, len 0x%x\n",
932 		  wsi, h2n->swsi, h2n->type, h2n->flags, (unsigned int)h2n->sid,
933 		  (unsigned int)h2n->length);
934 
935 	if (h2n->we_told_goaway && h2n->sid > h2n->highest_sid)
936 		h2n->type = LWS_H2_FRAME_TYPE_COUNT; /* ie, IGNORE */
937 
938 	if (h2n->type == LWS_H2_FRAME_TYPE_COUNT)
939 		return 0;
940 
941 	if (h2n->length > h2n->our_set.s[H2SET_MAX_FRAME_SIZE]) {
942 		/*
943 		 * peer sent us something bigger than we told
944 		 * it we would allow
945 		 */
946 		lwsl_info("%s: received oversize frame %d\n", __func__,
947 			  (unsigned int)h2n->length);
948 		lws_h2_goaway(wsi, H2_ERR_FRAME_SIZE_ERROR,
949 			      "Peer ignored our frame size setting");
950 		return 1;
951 	}
952 
953 	if (h2n->swsi)
954 		lwsl_info("%s: wsi %p, State: %s, received cmd %d\n",
955 		  __func__, h2n->swsi,
956 		  h2_state_names[h2n->swsi->h2.h2_state], h2n->type);
957 	else {
958 		/* if it's data, either way no swsi means CLOSED state */
959 		if (h2n->type == LWS_H2_FRAME_TYPE_DATA) {
960 			if (h2n->sid <= h2n->highest_sid_opened
961 #if defined(LWS_WITH_CLIENT)
962 					&& wsi->client_h2_alpn
963 #endif
964 			) {
965 				lwsl_notice("ignoring straggling data fl 0x%x\n",
966 						h2n->flags);
967 				/* ie, IGNORE */
968 				h2n->type = LWS_H2_FRAME_TYPE_COUNT;
969 			} else {
970 				lws_h2_goaway(wsi, H2_ERR_STREAM_CLOSED,
971 				      "Data for nonexistent sid");
972 				return 0;
973 			}
974 		}
975 		/* if the sid is credible, treat as wsi for it closed */
976 		if (h2n->sid > h2n->highest_sid_opened &&
977 		    h2n->type != LWS_H2_FRAME_TYPE_HEADERS &&
978 		    h2n->type != LWS_H2_FRAME_TYPE_PRIORITY) {
979 			/* if not credible, reject it */
980 			lwsl_info("%s: wsi %p, No child for sid %d, rxcmd %d\n",
981 			  __func__, h2n->swsi, (unsigned int)h2n->sid, h2n->type);
982 			lws_h2_goaway(wsi, H2_ERR_STREAM_CLOSED,
983 				     "Data for nonexistent sid");
984 			return 0;
985 		}
986 	}
987 
988 	if (h2n->swsi && h2n->sid &&
989 	    !(http2_rx_validity[h2n->swsi->h2.h2_state] & (1 << h2n->type))) {
990 		lwsl_info("%s: wsi %p, State: %s, ILLEGAL cmdrx %d (OK 0x%x)\n",
991 			  __func__, h2n->swsi,
992 			  h2_state_names[h2n->swsi->h2.h2_state], h2n->type,
993 			  http2_rx_validity[h2n->swsi->h2.h2_state]);
994 
995 		if (h2n->swsi->h2.h2_state == LWS_H2_STATE_CLOSED ||
996 		    h2n->swsi->h2.h2_state == LWS_H2_STATE_HALF_CLOSED_REMOTE)
997 			n = H2_ERR_STREAM_CLOSED;
998 		else
999 			n = H2_ERR_PROTOCOL_ERROR;
1000 		lws_h2_goaway(wsi, n, "invalid rx for state");
1001 
1002 		return 0;
1003 	}
1004 
1005 	if (h2n->cont_exp && (h2n->cont_exp_sid != h2n->sid ||
1006 			      h2n->type != LWS_H2_FRAME_TYPE_CONTINUATION)) {
1007 		lwsl_info("%s: expected cont on sid %u (got %d on sid %u)\n",
1008 			  __func__, (unsigned int)h2n->cont_exp_sid, h2n->type,
1009 			  (unsigned int)h2n->sid);
1010 		h2n->cont_exp = 0;
1011 		if (h2n->cont_exp_headers)
1012 			n = H2_ERR_COMPRESSION_ERROR;
1013 		else
1014 			n = H2_ERR_PROTOCOL_ERROR;
1015 		lws_h2_goaway(wsi, n, "Continuation hdrs State");
1016 
1017 		return 0;
1018 	}
1019 
1020 	switch (h2n->type) {
1021 	case LWS_H2_FRAME_TYPE_DATA:
1022 		lwsl_info("seen incoming LWS_H2_FRAME_TYPE_DATA start\n");
1023 		if (!h2n->sid) {
1024 			lwsl_info("DATA: 0 sid\n");
1025 			lws_h2_goaway(wsi, H2_ERR_PROTOCOL_ERROR, "DATA 0 sid");
1026 			break;
1027 		}
1028 		lwsl_info("Frame header DATA: sid %u, flags 0x%x, len %u\n",
1029 				(unsigned int)h2n->sid, h2n->flags,
1030 				(unsigned int)h2n->length);
1031 
1032 		if (!h2n->swsi) {
1033 			lwsl_notice("DATA: NULL swsi\n");
1034 			break;
1035 		}
1036 
1037 		lwsl_info("DATA rx on state %d\n", h2n->swsi->h2.h2_state);
1038 
1039 		if (
1040 		    h2n->swsi->h2.h2_state == LWS_H2_STATE_HALF_CLOSED_REMOTE ||
1041 		    h2n->swsi->h2.h2_state == LWS_H2_STATE_CLOSED) {
1042 			lws_h2_goaway(wsi, H2_ERR_STREAM_CLOSED, "conn closed");
1043 			break;
1044 		}
1045 
1046 		if (h2n->length == 0)
1047 			lws_h2_parse_end_of_frame(wsi);
1048 
1049 		break;
1050 
1051 	case LWS_H2_FRAME_TYPE_PRIORITY:
1052 		lwsl_info("LWS_H2_FRAME_TYPE_PRIORITY complete frame\n");
1053 		if (!h2n->sid) {
1054 			lws_h2_goaway(wsi, H2_ERR_PROTOCOL_ERROR,
1055 				      "Priority has 0 sid");
1056 			break;
1057 		}
1058 		if (h2n->length != 5) {
1059 			lws_h2_goaway(wsi, H2_ERR_FRAME_SIZE_ERROR,
1060 				      "Priority has length other than 5");
1061 			break;
1062 		}
1063 		break;
1064 	case LWS_H2_FRAME_TYPE_PUSH_PROMISE:
1065 		lwsl_info("LWS_H2_FRAME_TYPE_PUSH_PROMISE complete frame\n");
1066 		lws_h2_goaway(wsi, H2_ERR_PROTOCOL_ERROR, "Server only");
1067 		break;
1068 
1069 	case LWS_H2_FRAME_TYPE_GOAWAY:
1070 		lwsl_debug("LWS_H2_FRAME_TYPE_GOAWAY received\n");
1071 		break;
1072 
1073 	case LWS_H2_FRAME_TYPE_RST_STREAM:
1074 		if (!h2n->sid)
1075 			return 1;
1076 		if (!h2n->swsi) {
1077 			if (h2n->sid <= h2n->highest_sid_opened)
1078 				break;
1079 			lws_h2_goaway(wsi, H2_ERR_PROTOCOL_ERROR,
1080 				      "crazy sid on RST_STREAM");
1081 			return 1;
1082 		}
1083 		if (h2n->length != 4) {
1084 			lws_h2_goaway(wsi, H2_ERR_FRAME_SIZE_ERROR,
1085 				      "RST_STREAM can only be length 4");
1086 			break;
1087 		}
1088 		lws_h2_state(h2n->swsi, LWS_H2_STATE_CLOSED);
1089 		break;
1090 
1091 	case LWS_H2_FRAME_TYPE_SETTINGS:
1092 		lwsl_info("LWS_H2_FRAME_TYPE_SETTINGS complete frame\n");
1093 		/* nonzero sid on settings is illegal */
1094 		if (h2n->sid) {
1095 			lws_h2_goaway(wsi, H2_ERR_PROTOCOL_ERROR,
1096 					 "Settings has nonzero sid");
1097 			break;
1098 		}
1099 
1100 		if (!(h2n->flags & LWS_H2_FLAG_SETTINGS_ACK)) {
1101 			if ((!h2n->length) || h2n->length % 6) {
1102 				lws_h2_goaway(wsi, H2_ERR_FRAME_SIZE_ERROR,
1103 						 "Settings length error");
1104 				break;
1105 			}
1106 
1107 			if (h2n->type == LWS_H2_FRAME_TYPE_COUNT)
1108 				return 0;
1109 
1110 			if (wsi->upgraded_to_http2 &&
1111 #if defined(LWS_WITH_CLIENT)
1112 			    (!(wsi->flags & LCCSCF_H2_QUIRK_NGHTTP2_END_STREAM) ||
1113 #else
1114 			    (
1115 #endif
1116 					    !wsi->h2_acked_settings)) {
1117 
1118 				pps = lws_h2_new_pps(LWS_H2_PPS_ACK_SETTINGS);
1119 				if (!pps)
1120 					return 1;
1121 				lws_pps_schedule(wsi, pps);
1122 				wsi->h2_acked_settings = 1;
1123 			}
1124 			break;
1125 		}
1126 		/* came to us with ACK set... not allowed to have payload */
1127 
1128 		if (h2n->length) {
1129 			lws_h2_goaway(wsi, H2_ERR_FRAME_SIZE_ERROR,
1130 				      "Settings with ACK not allowed payload");
1131 			break;
1132 		}
1133 		break;
1134 	case LWS_H2_FRAME_TYPE_PING:
1135 		if (h2n->sid) {
1136 			lws_h2_goaway(wsi, H2_ERR_PROTOCOL_ERROR,
1137 				      "Ping has nonzero sid");
1138 			break;
1139 		}
1140 		if (h2n->length != 8) {
1141 			lws_h2_goaway(wsi, H2_ERR_FRAME_SIZE_ERROR,
1142 				      "Ping payload can only be 8");
1143 			break;
1144 		}
1145 		break;
1146 	case LWS_H2_FRAME_TYPE_CONTINUATION:
1147 		lwsl_info("LWS_H2_FRAME_TYPE_CONTINUATION: sid = %u %d %d\n",
1148 			  (unsigned int)h2n->sid, (int)h2n->cont_exp,
1149 			  (int)h2n->cont_exp_sid);
1150 
1151 		if (!h2n->cont_exp ||
1152 		     h2n->cont_exp_sid != h2n->sid ||
1153 		     !h2n->sid ||
1154 		     !h2n->swsi) {
1155 			lws_h2_goaway(wsi, H2_ERR_PROTOCOL_ERROR,
1156 				      "unexpected CONTINUATION");
1157 			break;
1158 		}
1159 
1160 		if (h2n->swsi->h2.END_HEADERS) {
1161 			lws_h2_goaway(wsi, H2_ERR_PROTOCOL_ERROR,
1162 				      "END_HEADERS already seen");
1163 			break;
1164 		}
1165 		/* END_STREAM is in HEADERS, skip resetting it */
1166 		goto update_end_headers;
1167 
1168 	case LWS_H2_FRAME_TYPE_HEADERS:
1169 		lwsl_info("HEADERS: frame header: sid = %u\n",
1170 				(unsigned int)h2n->sid);
1171 		if (!h2n->sid) {
1172 			lws_h2_goaway(wsi, H2_ERR_PROTOCOL_ERROR, "sid 0");
1173 			return 1;
1174 		}
1175 
1176 		if (h2n->swsi && !h2n->swsi->h2.END_STREAM &&
1177 		    h2n->swsi->h2.END_HEADERS &&
1178 		    !(h2n->flags & LWS_H2_FLAG_END_STREAM)) {
1179 			lws_h2_goaway(wsi, H2_ERR_PROTOCOL_ERROR,
1180 				      "extra HEADERS together");
1181 			return 1;
1182 		}
1183 
1184 #if defined(LWS_WITH_CLIENT)
1185 		if (wsi->client_h2_alpn) {
1186 			if (h2n->sid) {
1187 				h2n->swsi = lws_wsi_mux_from_id(wsi, h2n->sid);
1188 				lwsl_info("HEADERS: nwsi %p: sid %u mapped "
1189 					  "to wsi %p\n", wsi,
1190 					  (unsigned int)h2n->sid, h2n->swsi);
1191 				if (!h2n->swsi)
1192 					break;
1193 			}
1194 			goto update_end_headers;
1195 		}
1196 #endif
1197 
1198 		if (!h2n->swsi) {
1199 			/* no more children allowed by parent */
1200 			if (wsi->mux.child_count + 1 >
1201 			    wsi->h2.h2n->our_set.s[H2SET_MAX_CONCURRENT_STREAMS]) {
1202 				lws_h2_goaway(wsi, H2_ERR_PROTOCOL_ERROR,
1203 				"Another stream not allowed");
1204 
1205 				return 1;
1206 			}
1207 
1208 			/*
1209 			 * The peer has sent us a HEADERS implying the creation
1210 			 * of a new stream
1211 			 */
1212 
1213 			h2n->swsi = lws_wsi_server_new(wsi->vhost, wsi,
1214 						       h2n->sid);
1215 			if (!h2n->swsi) {
1216 				lws_h2_goaway(wsi, H2_ERR_PROTOCOL_ERROR,
1217 					      "OOM");
1218 
1219 				return 1;
1220 			}
1221 
1222 			h2n->swsi->h2.initialized = 1;
1223 
1224 			if (lws_h2_update_peer_txcredit(h2n->swsi,
1225 					h2n->swsi->mux.my_sid, 4 * 65536))
1226 				goto cleanup_wsi;
1227 		}
1228 
1229 		/*
1230 		 * ah needs attaching to child wsi, even though
1231 		 * we only fill it from network wsi
1232 		 */
1233 		if (!h2n->swsi->http.ah)
1234 			if (lws_header_table_attach(h2n->swsi, 0)) {
1235 				lwsl_err("%s: Failed to get ah\n", __func__);
1236 				return 1;
1237 			}
1238 
1239 		/*
1240 		 * The first use of a new stream identifier implicitly closes
1241 		 * all streams in the "idle" state that might have been
1242 		 * initiated by that peer with a lower-valued stream identifier.
1243 		 *
1244 		 * For example, if a client sends a HEADERS frame on stream 7
1245 		 * without ever sending a frame on stream 5, then stream 5
1246 		 * transitions to the "closed" state when the first frame for
1247 		 * stream 7 is sent or received.
1248 		 */
1249 		lws_start_foreach_ll(struct lws *, w, wsi->mux.child_list) {
1250 			if (w->mux.my_sid < h2n->sid &&
1251 			    w->h2.h2_state == LWS_H2_STATE_IDLE)
1252 				lws_close_free_wsi(w, 0, "h2 sid close");
1253 			assert(w->mux.sibling_list != w);
1254 		} lws_end_foreach_ll(w, mux.sibling_list);
1255 
1256 		if (lws_check_opt(h2n->swsi->vhost->options,
1257 			       LWS_SERVER_OPTION_VH_H2_HALF_CLOSED_LONG_POLL)) {
1258 
1259 			/*
1260 			 * We don't directly timeout streams that enter the
1261 			 * half-closed remote state, allowing immortal long
1262 			 * poll
1263 			 */
1264 			lws_mux_mark_immortal(h2n->swsi);
1265 			lwsl_info("%s: %p: h2 stream entering long poll\n",
1266 					__func__, h2n->swsi);
1267 
1268 		} else {
1269 			h2n->swsi->h2.END_STREAM =
1270 					!!(h2n->flags & LWS_H2_FLAG_END_STREAM);
1271 			lwsl_debug("%s: hdr END_STREAM = %d\n",__func__,
1272 			  h2n->swsi->h2.END_STREAM);
1273 		}
1274 
1275 		h2n->cont_exp = !(h2n->flags & LWS_H2_FLAG_END_HEADERS);
1276 		h2n->cont_exp_sid = h2n->sid;
1277 		h2n->cont_exp_headers = 1;
1278 	//	lws_header_table_reset(h2n->swsi, 0);
1279 
1280 update_end_headers:
1281 		/* no END_HEADERS means CONTINUATION must come */
1282 		h2n->swsi->h2.END_HEADERS =
1283 				!!(h2n->flags & LWS_H2_FLAG_END_HEADERS);
1284 		lwsl_info("%p: END_HEADERS %d\n", h2n->swsi,
1285 			  h2n->swsi->h2.END_HEADERS);
1286 		if (h2n->swsi->h2.END_HEADERS)
1287 			h2n->cont_exp = 0;
1288 		lwsl_debug("END_HEADERS %d\n", h2n->swsi->h2.END_HEADERS);
1289 		break;
1290 
1291 cleanup_wsi:
1292 
1293 		return 1;
1294 
1295 	case LWS_H2_FRAME_TYPE_WINDOW_UPDATE:
1296 		if (h2n->length != 4) {
1297 			lws_h2_goaway(wsi, H2_ERR_FRAME_SIZE_ERROR,
1298 				      "window update frame not 4");
1299 			break;
1300 		}
1301 		lwsl_info("LWS_H2_FRAME_TYPE_WINDOW_UPDATE\n");
1302 		break;
1303 	case LWS_H2_FRAME_TYPE_COUNT:
1304 		break;
1305 	default:
1306 		lwsl_info("%s: ILLEGAL FRAME TYPE %d\n", __func__, h2n->type);
1307 		h2n->type = LWS_H2_FRAME_TYPE_COUNT; /* ie, IGNORE */
1308 		break;
1309 	}
1310 	if (h2n->length == 0)
1311 		h2n->frame_state = 0;
1312 
1313 	return 0;
1314 }
1315 
1316 static const char * const method_names[] = {
1317 	"GET", "POST",
1318 #if defined(LWS_WITH_HTTP_UNCOMMON_HEADERS)
1319 	"OPTIONS", "PUT", "PATCH", "DELETE",
1320 #endif
1321 	"CONNECT", "HEAD"
1322 };
1323 static unsigned char method_index[] = {
1324 	WSI_TOKEN_GET_URI,
1325 	WSI_TOKEN_POST_URI,
1326 #if defined(LWS_WITH_HTTP_UNCOMMON_HEADERS)
1327 	WSI_TOKEN_OPTIONS_URI,
1328 	WSI_TOKEN_PUT_URI,
1329 	WSI_TOKEN_PATCH_URI,
1330 	WSI_TOKEN_DELETE_URI,
1331 #endif
1332 	WSI_TOKEN_CONNECT,
1333 	WSI_TOKEN_HEAD_URI,
1334 };
1335 
1336 /*
1337  * The last byte of the whole frame has been handled.
1338  * Perform actions for frame completion.
1339  *
1340  * This is the crunch time for parsing that may have occured on a network
1341  * wsi with a pending partial send... we may call lws_http_action() to send
1342  * a response, conflicting with the partial.
1343  *
1344  * So in that case we change the wsi state and do the lws_http_action() in the
1345  * WRITABLE handler as a priority.
1346  */
1347 static int
lws_h2_parse_end_of_frame(struct lws * wsi)1348 lws_h2_parse_end_of_frame(struct lws *wsi)
1349 {
1350 	struct lws_h2_netconn *h2n = wsi->h2.h2n;
1351 	struct lws *eff_wsi = wsi;
1352 	const char *p;
1353 	int n;
1354 
1355 	h2n->frame_state = 0;
1356 	h2n->count = 0;
1357 
1358 	if (h2n->sid)
1359 		h2n->swsi = lws_wsi_mux_from_id(wsi, h2n->sid);
1360 
1361 	if (h2n->sid > h2n->highest_sid)
1362 		h2n->highest_sid = h2n->sid;
1363 
1364 	if (h2n->collected_priority && (h2n->dep & ~(1u << 31)) == h2n->sid) {
1365 		lws_h2_goaway(wsi, H2_ERR_PROTOCOL_ERROR, "depends on own sid");
1366 		return 0;
1367 	}
1368 
1369 	switch (h2n->type) {
1370 
1371 	case LWS_H2_FRAME_TYPE_SETTINGS:
1372 
1373 #if defined(LWS_WITH_CLIENT)
1374 		if (wsi->client_h2_alpn && !wsi->client_mux_migrated &&
1375 		    !(h2n->flags & LWS_H2_FLAG_SETTINGS_ACK)) {
1376 			struct lws_h2_protocol_send *pps;
1377 
1378 			/* migrate original client ask on to substream 1 */
1379 #if defined(LWS_WITH_FILE_OPS)
1380 			wsi->http.fop_fd = NULL;
1381 #endif
1382 			lwsl_info("%s: migrating\n", __func__);
1383 			wsi->client_mux_migrated = 1;
1384 			/*
1385 			 * we need to treat the headers from the upgrade as the
1386 			 * first job.  So these need to get shifted to sid 1.
1387 			 */
1388 			h2n->swsi = lws_wsi_server_new(wsi->vhost, wsi, 1);
1389 			if (!h2n->swsi)
1390 				return 1;
1391 			h2n->sid = 1;
1392 
1393 			assert(lws_wsi_mux_from_id(wsi, 1) == h2n->swsi);
1394 
1395 			lws_role_transition(wsi, LWSIFR_CLIENT,
1396 					    LRS_H2_WAITING_TO_SEND_HEADERS,
1397 					    &role_ops_h2);
1398 
1399 			lws_role_transition(h2n->swsi, LWSIFR_CLIENT,
1400 					    LRS_H2_WAITING_TO_SEND_HEADERS,
1401 					    &role_ops_h2);
1402 
1403 			/* pass on the initial headers to SID 1 */
1404 			h2n->swsi->http.ah = wsi->http.ah;
1405 			h2n->swsi->client_mux_substream = 1;
1406 #if defined(LWS_WITH_CLIENT)
1407 			h2n->swsi->flags = wsi->flags;
1408 #endif
1409 
1410 			h2n->swsi->protocol = wsi->protocol;
1411 			if (h2n->swsi->user_space &&
1412 			    !h2n->swsi->user_space_externally_allocated)
1413 				lws_free(h2n->swsi->user_space);
1414 			h2n->swsi->user_space = wsi->user_space;
1415 			h2n->swsi->user_space_externally_allocated =
1416 					wsi->user_space_externally_allocated;
1417 			h2n->swsi->opaque_user_data = wsi->opaque_user_data;
1418 			wsi->opaque_user_data = NULL;
1419 			h2n->swsi->txc.manual_initial_tx_credit =
1420 					wsi->txc.manual_initial_tx_credit;
1421 
1422 			wsi->user_space = NULL;
1423 
1424 			if (h2n->swsi->http.ah)
1425 				h2n->swsi->http.ah->wsi = h2n->swsi;
1426 			wsi->http.ah = NULL;
1427 
1428 			lwsl_info("%s: MIGRATING nwsi %p: swsi %p\n", __func__,
1429 				  wsi, h2n->swsi);
1430 			h2n->swsi->txc.tx_cr =
1431 				h2n->peer_set.s[H2SET_INITIAL_WINDOW_SIZE];
1432 			lwsl_info("%s: initial tx credit on conn %p: %d\n",
1433 				  __func__, h2n->swsi, (int)h2n->swsi->txc.tx_cr);
1434 			h2n->swsi->h2.initialized = 1;
1435 
1436 			/* set our initial window size */
1437 			if (!wsi->h2.initialized) {
1438 				wsi->txc.tx_cr =
1439 				     h2n->peer_set.s[H2SET_INITIAL_WINDOW_SIZE];
1440 
1441 				lwsl_info("%s: initial tx credit for us to "
1442 					  "write on master %p: %d\n", __func__,
1443 					  wsi, (int)wsi->txc.tx_cr);
1444 				wsi->h2.initialized = 1;
1445 			}
1446 
1447 			lws_callback_on_writable(h2n->swsi);
1448 
1449 			if (!wsi->h2_acked_settings ||
1450 			    !(wsi->flags & LCCSCF_H2_QUIRK_NGHTTP2_END_STREAM)
1451 			) {
1452 				pps = lws_h2_new_pps(LWS_H2_PPS_ACK_SETTINGS);
1453 				if (!pps)
1454 					return 1;
1455 				lws_pps_schedule(wsi, pps);
1456 				lwsl_info("%s: SETTINGS ack PPS\n", __func__);
1457 				wsi->h2_acked_settings = 1;
1458 			}
1459 
1460 			/* also attach any queued guys */
1461 
1462 			lws_wsi_mux_apply_queue(wsi);
1463 		}
1464 #endif
1465 		break;
1466 
1467 	case LWS_H2_FRAME_TYPE_CONTINUATION:
1468 	case LWS_H2_FRAME_TYPE_HEADERS:
1469 
1470 		if (!h2n->swsi)
1471 			break;
1472 
1473 		/* service the http request itself */
1474 
1475 		if (h2n->last_action_dyntable_resize) {
1476 			lws_h2_goaway(wsi, H2_ERR_COMPRESSION_ERROR,
1477 				"dyntable resize last in headers");
1478 			break;
1479 		}
1480 
1481 		if (!h2n->swsi->h2.END_HEADERS) {
1482 			/* we are not finished yet */
1483 			lwsl_info("witholding http action for continuation\n");
1484 			h2n->cont_exp_sid = h2n->sid;
1485 			h2n->cont_exp = 1;
1486 			break;
1487 		}
1488 
1489 		/* confirm the hpack stream state is reasonable for finishing */
1490 
1491 		if (h2n->hpack != HPKS_TYPE) {
1492 			/* hpack incomplete */
1493 			lwsl_info("hpack incomplete %d (type %d, len %u)\n",
1494 				  h2n->hpack, h2n->type,
1495 				  (unsigned int)h2n->hpack_len);
1496 			lws_h2_goaway(wsi, H2_ERR_COMPRESSION_ERROR,
1497 				      "hpack incomplete");
1498 			break;
1499 		}
1500 
1501 		/* this is the last part of HEADERS */
1502 		switch (h2n->swsi->h2.h2_state) {
1503 		case LWS_H2_STATE_IDLE:
1504 			lws_h2_state(h2n->swsi, LWS_H2_STATE_OPEN);
1505 			break;
1506 		case LWS_H2_STATE_RESERVED_REMOTE:
1507 			lws_h2_state(h2n->swsi, LWS_H2_STATE_HALF_CLOSED_LOCAL);
1508 			break;
1509 		}
1510 
1511 		lwsl_info("http req, wsi=%p, h2n->swsi=%p\n", wsi, h2n->swsi);
1512 		h2n->swsi->hdr_parsing_completed = 1;
1513 
1514 #if defined(LWS_WITH_CLIENT)
1515 		if (h2n->swsi->client_mux_substream &&
1516 		    lws_client_interpret_server_handshake(h2n->swsi)) {
1517 			lwsl_info("%s: cli int serv hs closed it\n", __func__);
1518 			break;
1519 		}
1520 #endif
1521 
1522 		if (lws_hdr_extant(h2n->swsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
1523 			h2n->swsi->http.rx_content_length  = atoll(
1524 				lws_hdr_simple_ptr(h2n->swsi,
1525 				      WSI_TOKEN_HTTP_CONTENT_LENGTH));
1526 			h2n->swsi->http.rx_content_remain =
1527 					h2n->swsi->http.rx_content_length;
1528 			lwsl_info("setting rx_content_length %lld\n",
1529 				  (long long)h2n->swsi->http.rx_content_length);
1530 		}
1531 
1532 		{
1533 			int n = 0, len;
1534 			char buf[256];
1535 			const unsigned char *c;
1536 
1537 			do {
1538 				c = lws_token_to_string(n);
1539 				if (!c) {
1540 					n++;
1541 					continue;
1542 				}
1543 
1544 				len = lws_hdr_total_length(h2n->swsi, n);
1545 				if (!len || len > (int)sizeof(buf) - 1) {
1546 					n++;
1547 					continue;
1548 				}
1549 
1550 				if (lws_hdr_copy(h2n->swsi, buf, sizeof buf,
1551 						 n) < 0) {
1552 					lwsl_info("    %s !oversize!\n",
1553 						  (char *)c);
1554 				} else {
1555 					buf[sizeof(buf) - 1] = '\0';
1556 
1557 					lwsl_info("    %s = %s\n",
1558 						  (char *)c, buf);
1559 				}
1560 				n++;
1561 			} while (c);
1562 		}
1563 
1564 		if (h2n->swsi->h2.h2_state == LWS_H2_STATE_HALF_CLOSED_REMOTE ||
1565 		    h2n->swsi->h2.h2_state == LWS_H2_STATE_CLOSED) {
1566 			lws_h2_goaway(wsi, H2_ERR_STREAM_CLOSED,
1567 				      "Banning service on CLOSED_REMOTE");
1568 			break;
1569 		}
1570 
1571 		switch (h2n->swsi->h2.h2_state) {
1572 		case LWS_H2_STATE_OPEN:
1573 			if (h2n->swsi->h2.END_STREAM)
1574 				lws_h2_state(h2n->swsi,
1575 					     LWS_H2_STATE_HALF_CLOSED_REMOTE);
1576 			break;
1577 		case LWS_H2_STATE_HALF_CLOSED_LOCAL:
1578 			if (h2n->swsi->h2.END_STREAM)
1579 				lws_h2_state(h2n->swsi, LWS_H2_STATE_CLOSED);
1580 			break;
1581 		}
1582 
1583 #if defined(LWS_WITH_CLIENT)
1584 		if (h2n->swsi->client_mux_substream) {
1585 			lwsl_info("%s: headers: client path\n", __func__);
1586 			break;
1587 		}
1588 #endif
1589 
1590 		if (!lws_hdr_total_length(h2n->swsi, WSI_TOKEN_HTTP_COLON_PATH) ||
1591 		    !lws_hdr_total_length(h2n->swsi, WSI_TOKEN_HTTP_COLON_METHOD) ||
1592 		    !lws_hdr_total_length(h2n->swsi, WSI_TOKEN_HTTP_COLON_SCHEME) ||
1593 		     lws_hdr_total_length(h2n->swsi, WSI_TOKEN_HTTP_COLON_STATUS) ||
1594 		     lws_hdr_extant(h2n->swsi, WSI_TOKEN_CONNECTION)) {
1595 			lws_h2_goaway(wsi, H2_ERR_PROTOCOL_ERROR,
1596 				      "Pseudoheader checks");
1597 			break;
1598 		}
1599 
1600 		if (lws_hdr_extant(h2n->swsi, WSI_TOKEN_TE)) {
1601 			n = lws_hdr_total_length(h2n->swsi, WSI_TOKEN_TE);
1602 
1603 			if (n != 8 ||
1604 			    strncmp(lws_hdr_simple_ptr(h2n->swsi, WSI_TOKEN_TE),
1605 				  "trailers", n)) {
1606 				lws_h2_goaway(wsi, H2_ERR_PROTOCOL_ERROR,
1607 					      "Illegal transfer-encoding");
1608 				break;
1609 			}
1610 		}
1611 
1612 #if defined(LWS_WITH_HTTP_STREAM_COMPRESSION)
1613 		lws_http_compression_validate(h2n->swsi);
1614 #endif
1615 
1616 #if defined(LWS_WITH_SERVER_STATUS)
1617 		wsi->vhost->conn_stats.h2_trans++;
1618 #endif
1619 		p = lws_hdr_simple_ptr(h2n->swsi, WSI_TOKEN_HTTP_COLON_METHOD);
1620 		/*
1621 		 * duplicate :path into the individual method uri header
1622 		 * index, so that it looks the same as h1 in the ah
1623 		 */
1624 		for (n = 0; n < (int)LWS_ARRAY_SIZE(method_names); n++)
1625 			if (!strcasecmp(p, method_names[n])) {
1626 				h2n->swsi->http.ah->frag_index[method_index[n]] =
1627 						h2n->swsi->http.ah->frag_index[
1628 				                     WSI_TOKEN_HTTP_COLON_PATH];
1629 				break;
1630 			}
1631 
1632 		lwsl_debug("%s: setting DEF_ACT from 0x%x\n", __func__,
1633 			   (unsigned int)h2n->swsi->wsistate);
1634 		lwsi_set_state(h2n->swsi, LRS_DEFERRING_ACTION);
1635 		lws_callback_on_writable(h2n->swsi);
1636 		break;
1637 
1638 	case LWS_H2_FRAME_TYPE_DATA:
1639 		lwsl_info("%s: DATA flags 0x%x\n", __func__, h2n->flags);
1640 		if (!h2n->swsi)
1641 			break;
1642 
1643 		if (lws_hdr_total_length(h2n->swsi,
1644 					 WSI_TOKEN_HTTP_CONTENT_LENGTH) &&
1645 		    h2n->swsi->h2.END_STREAM &&
1646 		    h2n->swsi->http.rx_content_length &&
1647 		    h2n->swsi->http.rx_content_remain) {
1648 			lws_h2_rst_stream(h2n->swsi, H2_ERR_PROTOCOL_ERROR,
1649 					  "Not enough rx content");
1650 			break;
1651 		}
1652 
1653 		if (h2n->swsi->h2.END_STREAM &&
1654 		    h2n->swsi->h2.h2_state == LWS_H2_STATE_OPEN)
1655 			lws_h2_state(h2n->swsi,
1656 				     LWS_H2_STATE_HALF_CLOSED_REMOTE);
1657 
1658 		if (h2n->swsi->h2.END_STREAM &&
1659 		    h2n->swsi->h2.h2_state == LWS_H2_STATE_HALF_CLOSED_LOCAL)
1660 			lws_h2_state(h2n->swsi, LWS_H2_STATE_CLOSED);
1661 
1662 #if defined(LWS_WITH_CLIENT)
1663 		/*
1664 		 * client... remote END_STREAM implies we weren't going to
1665 		 * send anything else anyway.
1666 		 */
1667 
1668 		if (h2n->swsi->client_mux_substream &&
1669 		    (h2n->flags & LWS_H2_FLAG_END_STREAM)) {
1670 			lwsl_info("%s: %p: DATA: end stream\n",
1671 				  __func__, h2n->swsi);
1672 
1673 			if (h2n->swsi->h2.h2_state == LWS_H2_STATE_OPEN) {
1674 				lws_h2_state(h2n->swsi,
1675 					     LWS_H2_STATE_HALF_CLOSED_REMOTE);
1676 		//		lws_h2_rst_stream(h2n->swsi, H2_ERR_NO_ERROR,
1677 		//				  "client done");
1678 
1679 		//		if (lws_http_transaction_completed_client(h2n->swsi))
1680 		//			lwsl_debug("tx completed returned close\n");
1681 			}
1682 
1683 			//if (h2n->swsi->h2.h2_state == LWS_H2_STATE_HALF_CLOSED_LOCAL)
1684 			{
1685 				lws_h2_state(h2n->swsi, LWS_H2_STATE_CLOSED);
1686 
1687 				lws_h2_rst_stream(h2n->swsi, H2_ERR_NO_ERROR,
1688 						  "client done");
1689 
1690 				if (lws_http_transaction_completed_client(h2n->swsi))
1691 					lwsl_debug("tx completed returned close\n");
1692 			}
1693 		}
1694 #endif
1695 		break;
1696 
1697 	case LWS_H2_FRAME_TYPE_PING:
1698 		if (h2n->flags & LWS_H2_FLAG_SETTINGS_ACK)
1699 			lws_validity_confirmed(wsi);
1700 		else {
1701 			/* they're sending us a ping request */
1702 			struct lws_h2_protocol_send *pps =
1703 					lws_h2_new_pps(LWS_H2_PPS_PONG);
1704 			if (!pps)
1705 				return 1;
1706 
1707 			lwsl_info("rx ping, preparing pong\n");
1708 
1709 			memcpy(pps->u.ping.ping_payload, h2n->ping_payload, 8);
1710 			lws_pps_schedule(wsi, pps);
1711 		}
1712 
1713 		break;
1714 
1715 	case LWS_H2_FRAME_TYPE_WINDOW_UPDATE:
1716 		/*
1717 		 * We only have an unsigned 31-bit (positive) increment possible
1718 		 */
1719 		h2n->hpack_e_dep &= ~(1u << 31);
1720 		lwsl_info("WINDOW_UPDATE: sid %u %u (0x%x)\n",
1721 			  (unsigned int)h2n->sid,
1722 			  (unsigned int)h2n->hpack_e_dep,
1723 			  (unsigned int)h2n->hpack_e_dep);
1724 
1725 		if (h2n->sid)
1726 			eff_wsi = h2n->swsi;
1727 
1728 		if (!eff_wsi) {
1729 			if (h2n->sid > h2n->highest_sid_opened)
1730 				lws_h2_goaway(wsi, H2_ERR_PROTOCOL_ERROR,
1731 					      "alien sid");
1732 			break; /* ignore */
1733 		}
1734 
1735 		if (eff_wsi->vhost->options &
1736 		        LWS_SERVER_OPTION_H2_JUST_FIX_WINDOW_UPDATE_OVERFLOW &&
1737 		    (uint64_t)eff_wsi->txc.tx_cr + (uint64_t)h2n->hpack_e_dep >
1738 		    (uint64_t)0x7fffffff)
1739 			h2n->hpack_e_dep = 0x7fffffff - eff_wsi->txc.tx_cr;
1740 
1741 		if ((uint64_t)eff_wsi->txc.tx_cr + (uint64_t)h2n->hpack_e_dep >
1742 		    (uint64_t)0x7fffffff) {
1743 			if (h2n->sid)
1744 				lws_h2_rst_stream(h2n->swsi,
1745 						  H2_ERR_FLOW_CONTROL_ERROR,
1746 						  "Flow control exceeded max");
1747 			else
1748 				lws_h2_goaway(wsi, H2_ERR_FLOW_CONTROL_ERROR,
1749 					      "Flow control exceeded max");
1750 			break;
1751 		}
1752 
1753 		if (!h2n->hpack_e_dep) {
1754 			lws_h2_goaway(wsi, H2_ERR_PROTOCOL_ERROR,
1755 				      "Zero length window update");
1756 			break;
1757 		}
1758 		n = eff_wsi->txc.tx_cr;
1759 		eff_wsi->txc.tx_cr += h2n->hpack_e_dep;
1760 
1761 		lws_wsi_txc_report_manual_txcr_in(eff_wsi,
1762 						  (int32_t)h2n->hpack_e_dep);
1763 
1764 		lws_wsi_txc_describe(&eff_wsi->txc, "WINDOW_UPDATE in",
1765 				     eff_wsi->mux.my_sid);
1766 
1767 		if (n <= 0 && eff_wsi->txc.tx_cr <= 0)
1768 			/* it helps, but won't change sendability for anyone */
1769 			break;
1770 
1771 		/*
1772 		 * It may have changed sendability (depends on SID 0 tx credit
1773 		 * too)... for us and any children waiting on us... reassess
1774 		 * blockage for all children first
1775 		 */
1776 		lws_start_foreach_ll(struct lws *, w, wsi->mux.child_list) {
1777 			lws_callback_on_writable(w);
1778 		} lws_end_foreach_ll(w, mux.sibling_list);
1779 
1780 		if (eff_wsi->txc.skint &&
1781 		    !lws_wsi_txc_check_skint(&eff_wsi->txc,
1782 					     lws_h2_tx_cr_get(eff_wsi)))
1783 			/*
1784 			 * This one became un-skint, schedule a writeable
1785 			 * callback
1786 			 */
1787 			lws_callback_on_writable(eff_wsi);
1788 
1789 		break;
1790 
1791 	case LWS_H2_FRAME_TYPE_GOAWAY:
1792 		lwsl_notice("GOAWAY: last sid %u, error 0x%08X, string '%s'\n",
1793 			  (unsigned int)h2n->goaway_last_sid,
1794 			  (unsigned int)h2n->goaway_err, h2n->goaway_str);
1795 
1796 		return 1;
1797 
1798 	case LWS_H2_FRAME_TYPE_RST_STREAM:
1799 		lwsl_info("LWS_H2_FRAME_TYPE_RST_STREAM: sid %u: reason 0x%x\n",
1800 			  (unsigned int)h2n->sid,
1801 			  (unsigned int)h2n->hpack_e_dep);
1802 		break;
1803 
1804 	case LWS_H2_FRAME_TYPE_COUNT: /* IGNORING FRAME */
1805 		break;
1806 	}
1807 
1808 	return 0;
1809 }
1810 
1811 /*
1812  * This may want to send something on the network wsi, which may be in the
1813  * middle of a partial send.  PPS sends are OK because they are queued to
1814  * go through the WRITABLE handler already.
1815  *
1816  * The read parser for the network wsi has no choice but to parse its stream
1817  * anyway, because otherwise it will not be able to get tx credit window
1818  * messages.
1819  *
1820  * Therefore if we will send non-PPS, ie, lws_http_action() for a stream
1821  * wsi, we must change its state and handle it as a priority in the
1822  * POLLOUT handler instead of writing it here.
1823  *
1824  * About closing... for the main network wsi, it should return nonzero to
1825  * close it all.  If it needs to close an swsi, it can do it here.
1826  */
1827 int
lws_h2_parser(struct lws * wsi,unsigned char * in,lws_filepos_t inlen,lws_filepos_t * inused)1828 lws_h2_parser(struct lws *wsi, unsigned char *in, lws_filepos_t inlen,
1829 	      lws_filepos_t *inused)
1830 {
1831 	struct lws_h2_netconn *h2n = wsi->h2.h2n;
1832 	struct lws_h2_protocol_send *pps;
1833 	unsigned char c, *oldin = in;
1834 	int n, m;
1835 
1836 	if (!h2n)
1837 		goto fail;
1838 
1839 	while (inlen--) {
1840 
1841 		c = *in++;
1842 
1843 		// lwsl_notice("%s: 0x%x\n", __func__, c);
1844 
1845 		switch (lwsi_state(wsi)) {
1846 		case LRS_H2_AWAIT_PREFACE:
1847 			if (preface[h2n->count++] != c)
1848 				goto fail;
1849 
1850 			if (preface[h2n->count])
1851 				break;
1852 
1853 			lwsl_info("http2: %p: established\n", wsi);
1854 			lwsi_set_state(wsi, LRS_H2_AWAIT_SETTINGS);
1855 			lws_validity_confirmed(wsi);
1856 			h2n->count = 0;
1857 			wsi->txc.tx_cr = 65535;
1858 
1859 			/*
1860 			 * we must send a settings frame -- empty one is OK...
1861 			 * that must be the first thing sent by server
1862 			 * and the peer must send a SETTINGS with ACK flag...
1863 			 */
1864 			pps = lws_h2_new_pps(LWS_H2_PPS_MY_SETTINGS);
1865 			if (!pps)
1866 				goto fail;
1867 			lws_pps_schedule(wsi, pps);
1868 			break;
1869 
1870 		case LRS_H2_WAITING_TO_SEND_HEADERS:
1871 		case LRS_ESTABLISHED:
1872 		case LRS_H2_AWAIT_SETTINGS:
1873 			if (h2n->frame_state != LWS_H2_FRAME_HEADER_LENGTH)
1874 				goto try_frame_start;
1875 
1876 			/*
1877 			 * post-header, preamble / payload / padding part
1878 			 */
1879 			h2n->count++;
1880 
1881 			if (h2n->flags & LWS_H2_FLAG_PADDED &&
1882 			    !h2n->pad_length) {
1883 				/*
1884 				 * Get the padding count... actual padding is
1885 				 * at the end of the frame.
1886 				 */
1887 				h2n->padding = c;
1888 				h2n->pad_length = 1;
1889 				h2n->preamble++;
1890 
1891 				if (h2n->padding > h2n->length - 1)
1892 					lws_h2_goaway(wsi,
1893 						      H2_ERR_PROTOCOL_ERROR,
1894 						      "execssive padding");
1895 				break; /* we consumed this */
1896 			}
1897 
1898 			if (h2n->flags & LWS_H2_FLAG_PRIORITY &&
1899 			    !h2n->collected_priority) {
1900 				/* going to be 5 preamble bytes */
1901 
1902 				lwsl_debug("PRIORITY FLAG:  0x%x\n", c);
1903 
1904 				if (h2n->preamble++ - h2n->pad_length < 4) {
1905 					h2n->dep = ((h2n->dep) << 8) | c;
1906 					break; /* we consumed this */
1907 				}
1908 				h2n->weight_temp = c;
1909 				h2n->collected_priority = 1;
1910 				lwsl_debug("PRI FL: dep 0x%x, weight 0x%02X\n",
1911 					   (unsigned int)h2n->dep,
1912 					   h2n->weight_temp);
1913 				break; /* we consumed this */
1914 			}
1915 			if (h2n->padding && h2n->count >
1916 			    (h2n->length - h2n->padding)) {
1917 				if (c) {
1918 					lws_h2_goaway(wsi, H2_ERR_PROTOCOL_ERROR,
1919 						      "nonzero padding");
1920 					break;
1921 				}
1922 				goto frame_end;
1923 			}
1924 
1925 			/* applies to wsi->h2.swsi which may be wsi */
1926 			switch(h2n->type) {
1927 
1928 			case LWS_H2_FRAME_TYPE_SETTINGS:
1929 				n = (h2n->count - 1 - h2n->preamble) %
1930 				     LWS_H2_SETTINGS_LEN;
1931 				h2n->one_setting[n] = c;
1932 				if (n != LWS_H2_SETTINGS_LEN - 1)
1933 					break;
1934 				lws_h2_settings(wsi, &h2n->peer_set,
1935 						h2n->one_setting,
1936 						LWS_H2_SETTINGS_LEN);
1937 				break;
1938 
1939 			case LWS_H2_FRAME_TYPE_CONTINUATION:
1940 			case LWS_H2_FRAME_TYPE_HEADERS:
1941 				if (!h2n->swsi)
1942 					break;
1943 				if (lws_hpack_interpret(h2n->swsi, c)) {
1944 					lwsl_info("%s: hpack failed\n",
1945 						  __func__);
1946 					goto fail;
1947 				}
1948 				break;
1949 
1950 			case LWS_H2_FRAME_TYPE_GOAWAY:
1951 				switch (h2n->inside++) {
1952 				case 0:
1953 				case 1:
1954 				case 2:
1955 				case 3:
1956 					h2n->goaway_last_sid <<= 8;
1957 					h2n->goaway_last_sid |= c;
1958 					h2n->goaway_str[0] = '\0';
1959 					break;
1960 
1961 				case 4:
1962 				case 5:
1963 				case 6:
1964 				case 7:
1965 					h2n->goaway_err <<= 8;
1966 					h2n->goaway_err |= c;
1967 					break;
1968 
1969 				default:
1970 					if (h2n->inside - 9 <
1971 					    sizeof(h2n->goaway_str) - 1)
1972 						h2n->goaway_str[
1973 						           h2n->inside - 9] = c;
1974 					h2n->goaway_str[
1975 					    sizeof(h2n->goaway_str) - 1] = '\0';
1976 					break;
1977 				}
1978 				break;
1979 
1980 			case LWS_H2_FRAME_TYPE_DATA:
1981 
1982 				lwsl_info("%s: LWS_H2_FRAME_TYPE_DATA: fl 0x%x\n",
1983 					  __func__, h2n->flags);
1984 
1985 				/*
1986 				 * let the network wsi live a bit longer if
1987 				 * subs are active... our frame may take a long
1988 				 * time to chew through
1989 				 */
1990 				if (!wsi->immortal_substream_count)
1991 					lws_set_timeout(wsi,
1992 					PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE,
1993 						wsi->vhost->keepalive_timeout ?
1994 					    wsi->vhost->keepalive_timeout : 31);
1995 
1996 				if (!h2n->swsi)
1997 					break;
1998 
1999 				if (lws_buflist_next_segment_len(
2000 						&h2n->swsi->buflist, NULL))
2001 					lwsl_info("%s: substream has pending\n",
2002 						  __func__);
2003 
2004 				if (lwsi_role_http(h2n->swsi) &&
2005 				    lwsi_state(h2n->swsi) == LRS_ESTABLISHED) {
2006 					lwsi_set_state(h2n->swsi, LRS_BODY);
2007 					lwsl_info("%s: swsi %p to LRS_BODY\n",
2008 							__func__, h2n->swsi);
2009 				}
2010 
2011 				if (lws_hdr_total_length(h2n->swsi,
2012 					     WSI_TOKEN_HTTP_CONTENT_LENGTH) &&
2013 				    h2n->swsi->http.rx_content_length &&
2014 				    h2n->swsi->http.rx_content_remain <
2015 						    inlen + 1 && /* last */
2016 				    h2n->inside < h2n->length) {
2017 					/* unread data in frame */
2018 					lws_h2_goaway(wsi,
2019 						      H2_ERR_PROTOCOL_ERROR,
2020 					    "More rx than content_length told");
2021 					break;
2022 				}
2023 
2024 				/*
2025 				 * We operate on a frame.  The RX we have at
2026 				 * hand may exceed the current frame.
2027 				 */
2028 
2029 				n = (int)inlen + 1;
2030 				if (n > (int)(h2n->length - h2n->count + 1)) {
2031 					n = h2n->length - h2n->count + 1;
2032 					lwsl_debug("---- restricting len to %d "
2033 						   "vs %ld\n", n, (long)inlen + 1);
2034 				}
2035 #if defined(LWS_WITH_CLIENT)
2036 				if (h2n->swsi->client_mux_substream) {
2037 					if (!h2n->swsi->protocol) {
2038 						lwsl_err("%s: swsi %p doesn't have protocol\n",
2039 							 __func__, h2n->swsi);
2040 						m = 1;
2041 					} else {
2042 						h2n->swsi->txc.peer_tx_cr_est -= n;
2043 						wsi->txc.peer_tx_cr_est -= n;
2044 						lws_wsi_txc_describe(&h2n->swsi->txc,
2045 							__func__,
2046 							h2n->swsi->mux.my_sid);
2047 					m = user_callback_handle_rxflow(
2048 						h2n->swsi->protocol->callback,
2049 						h2n->swsi,
2050 					  LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ,
2051 						h2n->swsi->user_space,
2052 						in - 1, n);
2053 					}
2054 
2055 					in += n - 1;
2056 					h2n->inside += n;
2057 					h2n->count += n - 1;
2058 					inlen -= n - 1;
2059 
2060 					if (m) {
2061 						lwsl_info("RECEIVE_CLIENT_HTTP "
2062 							  "closed it\n");
2063 						goto close_swsi_and_return;
2064 					}
2065 
2066 					break;
2067 				}
2068 #endif
2069 
2070 				if (lwsi_state(h2n->swsi) == LRS_DEFERRING_ACTION) {
2071 					m = lws_buflist_append_segment(
2072 						&h2n->swsi->buflist, in - 1, n);
2073 					if (m < 0)
2074 						return -1;
2075 					if (m) {
2076 						struct lws_context_per_thread *pt;
2077 
2078 						pt = &wsi->context->pt[(int)wsi->tsi];
2079 						lwsl_debug("%s: added %p to rxflow list\n",
2080 							   __func__, wsi);
2081 						lws_dll2_add_head(
2082 							&h2n->swsi->dll_buflist,
2083 							&pt->dll_buflist_owner);
2084 					}
2085 					in += n - 1;
2086 					h2n->inside += n;
2087 					h2n->count += n - 1;
2088 					inlen -= n - 1;
2089 
2090 					lwsl_debug("%s: deferred %d\n", __func__, n);
2091 					goto do_windows;
2092 				}
2093 
2094 				h2n->swsi->outer_will_close = 1;
2095 				/*
2096 				 * choose the length for this go so that we end at
2097 				 * the frame boundary, in the case there is already
2098 				 * more waiting leave it for next time around
2099 				 */
2100 
2101 				n = lws_read_h1(h2n->swsi, in - 1, n);
2102 				// lwsl_notice("%s: lws_read_h1 %d\n", __func__, n);
2103 				h2n->swsi->outer_will_close = 0;
2104 				/*
2105 				 * can return 0 in POST body with
2106 				 * content len exhausted somehow.
2107 				 */
2108 				if (n < 0 ||
2109 				    (!n && !lws_buflist_next_segment_len(
2110 						    &wsi->buflist, NULL))) {
2111 					lwsl_info("%s: lws_read_h1 told %d %u / %u\n",
2112 						__func__, n,
2113 						(unsigned int)h2n->count,
2114 						(unsigned int)h2n->length);
2115 					in += h2n->length - h2n->count;
2116 					h2n->inside = h2n->length;
2117 					h2n->count = h2n->length - 1;
2118 
2119 					//if (n < 0)
2120 					//	goto already_closed_swsi;
2121 					goto close_swsi_and_return;
2122 				}
2123 
2124 				inlen -= n - 1;
2125 				in += n - 1;
2126 				h2n->inside += n;
2127 				h2n->count += n - 1;
2128 				h2n->swsi->txc.peer_tx_cr_est -= n;
2129 				wsi->txc.peer_tx_cr_est -= n;
2130 
2131 do_windows:
2132 
2133 #if defined(LWS_WITH_CLIENT)
2134 				if (!(h2n->swsi->flags & LCCSCF_H2_MANUAL_RXFLOW))
2135 #endif
2136 				{
2137 					/*
2138 					 * The default behaviour is we just keep
2139 					 * cranking the other side's tx credit
2140 					 * back up, for simple bulk transfer as
2141 					 * fast as we can take it
2142 					 */
2143 
2144 					m = n; //(2 * h2n->length) + 65536;
2145 
2146 					/* update both the stream and nwsi */
2147 
2148 					lws_h2_update_peer_txcredit_thresh(h2n->swsi,
2149 								    h2n->sid, m, m);
2150 				}
2151 #if defined(LWS_WITH_CLIENT)
2152 				else {
2153 					/*
2154 					 * If he's handling it himself, only
2155 					 * repair the nwsi credit but allow the
2156 					 * stream credit to run down until the
2157 					 * user code deals with it
2158 					 */
2159 					lws_h2_update_peer_txcredit(wsi, 0, n);
2160 					h2n->swsi->txc.manual = 1;
2161 				}
2162 #endif
2163 				break;
2164 
2165 			case LWS_H2_FRAME_TYPE_PRIORITY:
2166 				if (h2n->count <= 4) {
2167 					h2n->dep <<= 8;
2168 					h2n->dep |= c;
2169 					break;
2170 				}
2171 				h2n->weight_temp = c;
2172 				lwsl_info("PRIORITY: dep 0x%x, weight 0x%02X\n",
2173 					  (unsigned int)h2n->dep, h2n->weight_temp);
2174 
2175 				if ((h2n->dep & ~(1u << 31)) == h2n->sid) {
2176 					lws_h2_goaway(wsi, H2_ERR_PROTOCOL_ERROR,
2177 						      "cant depend on own sid");
2178 					break;
2179 				}
2180 				break;
2181 
2182 			case LWS_H2_FRAME_TYPE_RST_STREAM:
2183 				h2n->hpack_e_dep <<= 8;
2184 				h2n->hpack_e_dep |= c;
2185 				break;
2186 
2187 			case LWS_H2_FRAME_TYPE_PUSH_PROMISE:
2188 				break;
2189 
2190 			case LWS_H2_FRAME_TYPE_PING:
2191 				if (h2n->flags & LWS_H2_FLAG_SETTINGS_ACK) { // ack
2192 				} else { /* they're sending us a ping request */
2193 					if (h2n->count > 8)
2194 						return 1;
2195 					h2n->ping_payload[h2n->count - 1] = c;
2196 				}
2197 				break;
2198 
2199 			case LWS_H2_FRAME_TYPE_WINDOW_UPDATE:
2200 				h2n->hpack_e_dep <<= 8;
2201 				h2n->hpack_e_dep |= c;
2202 				break;
2203 
2204 			case LWS_H2_FRAME_TYPE_COUNT: /* IGNORING FRAME */
2205 				break;
2206 
2207 			default:
2208 				lwsl_notice("%s: unhandled frame type %d\n",
2209 					    __func__, h2n->type);
2210 
2211 				goto fail;
2212 			}
2213 
2214 frame_end:
2215 			if (h2n->count > h2n->length) {
2216 				lwsl_notice("%s: count > length %u %u\n",
2217 					    __func__, (unsigned int)h2n->count,
2218 					    (unsigned int)h2n->length);
2219 				goto fail;
2220 			}
2221 			if (h2n->count != h2n->length)
2222 				break;
2223 
2224 			/*
2225 			 * end of frame just happened
2226 			 */
2227 			if (lws_h2_parse_end_of_frame(wsi))
2228 				goto fail;
2229 
2230 			break;
2231 
2232 try_frame_start:
2233 			if (h2n->frame_state <= 8) {
2234 
2235 				switch (h2n->frame_state++) {
2236 				case 0:
2237 					h2n->pad_length = 0;
2238 					h2n->collected_priority = 0;
2239 					h2n->padding = 0;
2240 					h2n->preamble = 0;
2241 					h2n->length = c;
2242 					h2n->inside = 0;
2243 					break;
2244 				case 1:
2245 				case 2:
2246 					h2n->length <<= 8;
2247 					h2n->length |= c;
2248 					break;
2249 				case 3:
2250 					h2n->type = c;
2251 					break;
2252 				case 4:
2253 					h2n->flags = c;
2254 					break;
2255 
2256 				case 5:
2257 				case 6:
2258 				case 7:
2259 				case 8:
2260 					h2n->sid <<= 8;
2261 					h2n->sid |= c;
2262 					break;
2263 				}
2264 			}
2265 
2266 			if (h2n->frame_state == LWS_H2_FRAME_HEADER_LENGTH)
2267 				if (lws_h2_parse_frame_header(wsi))
2268 					goto fail;
2269 			break;
2270 
2271 		default:
2272 			break;
2273 		}
2274 	}
2275 
2276 	*inused = in - oldin;
2277 
2278 	return 0;
2279 
2280 close_swsi_and_return:
2281 
2282 	lws_close_free_wsi(h2n->swsi, 0, "close_swsi_and_return");
2283 	h2n->swsi = NULL;
2284 	h2n->frame_state = 0;
2285 	h2n->count = 0;
2286 
2287 // already_closed_swsi:
2288 	*inused = in - oldin;
2289 
2290 	return 2;
2291 
2292 fail:
2293 	*inused = in - oldin;
2294 
2295 	return 1;
2296 }
2297 
2298 #if defined(LWS_WITH_CLIENT)
2299 int
lws_h2_client_handshake(struct lws * wsi)2300 lws_h2_client_handshake(struct lws *wsi)
2301 {
2302 	struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
2303 	uint8_t *buf, *start, *p, *p1, *end;
2304 	char *meth = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_METHOD),
2305 	     *uri = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_URI);
2306 	struct lws *nwsi = lws_get_network_wsi(wsi);
2307 	int n, m;
2308 	/*
2309 	 * The identifier of a newly established stream MUST be numerically
2310 	 * greater than all streams that the initiating endpoint has opened or
2311 	 * reserved.  This governs streams that are opened using a HEADERS frame
2312 	 * and streams that are reserved using PUSH_PROMISE.  An endpoint that
2313 	 * receives an unexpected stream identifier MUST respond with a
2314 	 * connection error (Section 5.4.1) of type PROTOCOL_ERROR.
2315 	 */
2316 	int sid = nwsi->h2.h2n->highest_sid_opened + 2;
2317 
2318 	lwsl_debug("%s\n", __func__);
2319 
2320 	nwsi->h2.h2n->highest_sid_opened = sid;
2321 	wsi->mux.my_sid = sid;
2322 
2323 	lwsl_info("%s: CLIENT_WAITING_TO_SEND_HEADERS: pollout (sid %d)\n",
2324 			__func__, wsi->mux.my_sid);
2325 
2326 	p = start = buf = pt->serv_buf + LWS_PRE;
2327 	end = start + (wsi->context->pt_serv_buf_size / 2) - LWS_PRE - 1;
2328 
2329 	/* it's time for us to send our client stream headers */
2330 
2331 	if (!meth)
2332 		meth = "GET";
2333 
2334 	if (lws_add_http_header_by_token(wsi,
2335 				WSI_TOKEN_HTTP_COLON_METHOD,
2336 				(unsigned char *)meth,
2337 				(int)strlen(meth), &p, end))
2338 		goto fail_length;
2339 
2340 	if (lws_add_http_header_by_token(wsi,
2341 				WSI_TOKEN_HTTP_COLON_SCHEME,
2342 				(unsigned char *)"https", 5,
2343 				&p, end))
2344 		goto fail_length;
2345 
2346 	if (lws_add_http_header_by_token(wsi,
2347 				WSI_TOKEN_HTTP_COLON_PATH,
2348 				(unsigned char *)uri,
2349 				lws_hdr_total_length(wsi, _WSI_TOKEN_CLIENT_URI),
2350 				&p, end))
2351 		goto fail_length;
2352 
2353 	if (lws_add_http_header_by_token(wsi,
2354 				WSI_TOKEN_HTTP_COLON_AUTHORITY,
2355 				(unsigned char *)lws_hdr_simple_ptr(wsi,
2356 						_WSI_TOKEN_CLIENT_ORIGIN),
2357 			lws_hdr_total_length(wsi, _WSI_TOKEN_CLIENT_ORIGIN),
2358 				&p, end))
2359 		goto fail_length;
2360 
2361 	if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HOST,
2362 				(unsigned char *)lws_hdr_simple_ptr(wsi,
2363 						_WSI_TOKEN_CLIENT_HOST),
2364 			lws_hdr_total_length(wsi, _WSI_TOKEN_CLIENT_HOST),
2365 				&p, end))
2366 		goto fail_length;
2367 
2368 	if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_USER_AGENT,
2369 				(unsigned char *)"lwsss", 5,
2370 				&p, end))
2371 		goto fail_length;
2372 
2373 	if (wsi->flags & LCCSCF_HTTP_MULTIPART_MIME) {
2374 		p1 = lws_http_multipart_headers(wsi, p);
2375 		if (!p1)
2376 			goto fail_length;
2377 		p = p1;
2378 	}
2379 
2380 	if (wsi->flags & LCCSCF_HTTP_X_WWW_FORM_URLENCODED) {
2381 		if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
2382 			   (unsigned char *)"application/x-www-form-urlencoded",
2383 			   33, &p, end))
2384 			goto fail_length;
2385 		lws_client_http_body_pending(wsi, 1);
2386 	}
2387 
2388 	/* give userland a chance to append, eg, cookies */
2389 
2390 	if (wsi->protocol->callback(wsi,
2391 				LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
2392 				wsi->user_space, &p, (end - p) - 12))
2393 		goto fail_length;
2394 
2395 	if (lws_finalize_http_header(wsi, &p, end))
2396 		goto fail_length;
2397 
2398 #if defined(LWS_WITH_DETAILED_LATENCY)
2399 	wsi->detlat.earliest_write_req_pre_write = lws_now_usecs();
2400 #endif
2401 
2402 	m = LWS_WRITE_HTTP_HEADERS;
2403 #if defined(LWS_WITH_CLIENT)
2404 	/* below is not needed in spec, indeed it destroys the long poll
2405 	 * feature, but required by nghttp2 */
2406 	if ((wsi->flags & LCCSCF_H2_QUIRK_NGHTTP2_END_STREAM) &&
2407 	    !(wsi->client_http_body_pending))
2408 		m |= LWS_WRITE_H2_STREAM_END;
2409 #endif
2410 
2411 	// lwsl_hexdump_notice(start, p - start);
2412 
2413 	n = lws_write(wsi, start, p - start, m);
2414 
2415 	if (n != (p - start)) {
2416 		lwsl_err("_write returned %d from %ld\n", n,
2417 			 (long)(p - start));
2418 		return -1;
2419 	}
2420 
2421 	/*
2422 	 * Normally let's charge up the peer tx credit a bit.  But if
2423 	 * MANUAL_REFLOW is set, just set it to the initial credit given in
2424 	 * the client create info
2425 	 */
2426 
2427 	n = 4 * 65536;
2428 	if (wsi->flags & LCCSCF_H2_MANUAL_RXFLOW) {
2429 		n = wsi->txc.manual_initial_tx_credit;
2430 		wsi->txc.manual = 1;
2431 	}
2432 
2433 	if (lws_h2_update_peer_txcredit(wsi, sid, n))
2434 		return 1;
2435 
2436 	lws_h2_state(wsi, LWS_H2_STATE_OPEN);
2437 	lwsi_set_state(wsi, LRS_ESTABLISHED);
2438 
2439 	if (wsi->flags & LCCSCF_HTTP_MULTIPART_MIME)
2440 		lws_callback_on_writable(wsi);
2441 
2442 	return 0;
2443 
2444 fail_length:
2445 	lwsl_err("Client hdrs too long: incr context info.pt_serv_buf_size\n");
2446 
2447 	return -1;
2448 }
2449 #endif
2450 
2451 #if defined(LWS_ROLE_WS)
2452 int
lws_h2_ws_handshake(struct lws * wsi)2453 lws_h2_ws_handshake(struct lws *wsi)
2454 {
2455 	uint8_t buf[LWS_PRE + 2048], *p = buf + LWS_PRE, *start = p,
2456 		*end = &buf[sizeof(buf) - 1];
2457 	const struct lws_http_mount *hit;
2458 	const char * uri_ptr;
2459 	int n, m;
2460 
2461 	if (lws_add_http_header_status(wsi, HTTP_STATUS_OK, &p, end))
2462 		return -1;
2463 
2464 	if (lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL) > 64)
2465 		return -1;
2466 
2467 	if (wsi->proxied_ws_parent && wsi->child_list) {
2468 		if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL)) {
2469 			if (lws_add_http_header_by_token(wsi, WSI_TOKEN_PROTOCOL,
2470 				(uint8_t *)lws_hdr_simple_ptr(wsi,
2471 							   WSI_TOKEN_PROTOCOL),
2472 				(int)strlen(lws_hdr_simple_ptr(wsi,
2473 							   WSI_TOKEN_PROTOCOL)),
2474 						 &p, end))
2475 			return -1;
2476 		}
2477 	} else {
2478 
2479 		/* we can only return the protocol header if:
2480 		 *  - one came in, and ... */
2481 		if (lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL) &&
2482 		    /*  - it is not an empty string */
2483 		    wsi->protocol->name && wsi->protocol->name[0]) {
2484 			if (lws_add_http_header_by_token(wsi, WSI_TOKEN_PROTOCOL,
2485 				(unsigned char *)wsi->protocol->name,
2486 				(int)strlen(wsi->protocol->name), &p, end))
2487 			return -1;
2488 		}
2489 	}
2490 
2491 	if (lws_finalize_http_header(wsi, &p, end))
2492 		return -1;
2493 
2494 	m = lws_ptr_diff(p, start);
2495 	// lwsl_hexdump_notice(start, m);
2496 	n = lws_write(wsi, start, m, LWS_WRITE_HTTP_HEADERS);
2497 	if (n != m) {
2498 		lwsl_err("_write returned %d from %d\n", n, m);
2499 
2500 		return -1;
2501 	}
2502 
2503 	/*
2504 	 * alright clean up, set our state to generic ws established, the
2505 	 * mode / state of the nwsi will get the h2 processing done.
2506 	 */
2507 
2508 	lwsi_set_state(wsi, LRS_ESTABLISHED);
2509 	wsi->lws_rx_parse_state = 0; // ==LWS_RXPS_NEW;
2510 
2511 	uri_ptr = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_COLON_PATH);
2512 	n = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COLON_PATH);
2513 	hit = lws_find_mount(wsi, uri_ptr, n);
2514 
2515 	if (hit && hit->cgienv &&
2516 	    wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_PMO, wsi->user_space,
2517 				    (void *)hit->cgienv, 0))
2518 		return 1;
2519 
2520 	lws_validity_confirmed(wsi);
2521 
2522 	return 0;
2523 }
2524 #endif
2525 
2526 int
lws_read_h2(struct lws * wsi,unsigned char * buf,lws_filepos_t len)2527 lws_read_h2(struct lws *wsi, unsigned char *buf, lws_filepos_t len)
2528 {
2529 	unsigned char *oldbuf = buf;
2530 	lws_filepos_t body_chunk_len;
2531 
2532 	// lwsl_notice("%s: h2 path: wsistate 0x%x len %d\n", __func__,
2533 	//		wsi->wsistate, (int)len);
2534 
2535 	/*
2536 	 * wsi here is always the network connection wsi, not a stream
2537 	 * wsi.  Once we unpicked the framing we will find the right
2538 	 * swsi and make it the target of the frame.
2539 	 *
2540 	 * If it's ws over h2, the nwsi will get us here to do the h2
2541 	 * processing, and that will call us back with the swsi +
2542 	 * ESTABLISHED state for the inner payload, handled in a later
2543 	 * case.
2544 	 */
2545 	while (len) {
2546 		int m;
2547 
2548 		/*
2549 		 * we were accepting input but now we stopped doing so
2550 		 */
2551 		if (lws_is_flowcontrolled(wsi)) {
2552 			lws_rxflow_cache(wsi, buf, 0, (int)len);
2553 			buf += len;
2554 			break;
2555 		}
2556 
2557 		/*
2558 		 * lws_h2_parser() may send something; when it gets the
2559 		 * whole frame, it will want to perform some action
2560 		 * involving a reply.  But we may be in a partial send
2561 		 * situation on the network wsi...
2562 		 *
2563 		 * Even though we may be in a partial send and unable to
2564 		 * send anything new, we still have to parse the network
2565 		 * wsi in order to gain tx credit to send, which is
2566 		 * potentially necessary to clear the old partial send.
2567 		 *
2568 		 * ALL network wsi-specific frames are sent by PPS
2569 		 * already, these are sent as a priority on the writable
2570 		 * handler, and so respect partial sends.  The only
2571 		 * problem is when a stream wsi wants to send an, eg,
2572 		 * reply headers frame in response to the parsing
2573 		 * we will do now... the *stream wsi* must stall in a
2574 		 * different state until it is able to do so from a
2575 		 * priority on the WRITABLE callback, same way that
2576 		 * file transfers operate.
2577 		 */
2578 
2579 		m = lws_h2_parser(wsi, buf, len, &body_chunk_len);
2580 		if (m && m != 2) {
2581 			lwsl_debug("%s: http2_parser bail: %d\n", __func__, m);
2582 			lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS,
2583 					   "lws_read_h2 bail");
2584 
2585 			return -1;
2586 		}
2587 		if (m == 2) {
2588 			/* swsi has been closed */
2589 			buf += body_chunk_len;
2590 			break;
2591 		}
2592 
2593 		buf += body_chunk_len;
2594 		len -= body_chunk_len;
2595 	}
2596 
2597 	return lws_ptr_diff(buf, oldbuf);
2598 }
2599 
2600 int
lws_h2_client_stream_long_poll_rxonly(struct lws * wsi)2601 lws_h2_client_stream_long_poll_rxonly(struct lws *wsi)
2602 {
2603 
2604 	if (!wsi->mux_substream)
2605 		return 1;
2606 
2607 	/*
2608 	 * Elect to send an empty DATA with END_STREAM, to force the stream
2609 	 * into HALF_CLOSED LOCAL
2610 	 */
2611 	wsi->h2.long_poll = 1;
2612 	wsi->h2.send_END_STREAM = 1;
2613 
2614 	// lws_header_table_detach(wsi, 0);
2615 
2616 	lws_callback_on_writable(wsi);
2617 
2618 	return 0;
2619 }
2620