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#ifndef min
28#define min(a, b) ((a) < (b) ? (a) : (b))
29#endif
30
31
32/*
33 * We have to take care about parsing because the headers may be split
34 * into multiple fragments.  They may contain unknown headers with arbitrary
35 * argument lengths.  So, we parse using a single-character at a time state
36 * machine that is completely independent of packet size.
37 *
38 * Returns <0 for error or length of chars consumed from buf (up to len)
39 */
40
41int
42lws_read_h1(struct lws *wsi, unsigned char *buf, lws_filepos_t len)
43{
44	unsigned char *last_char, *oldbuf = buf;
45	lws_filepos_t body_chunk_len;
46	size_t n;
47
48	lwsl_debug("%s: h1 path: wsi state 0x%x\n", __func__, lwsi_state(wsi));
49
50	switch (lwsi_state(wsi)) {
51
52	case LRS_ISSUING_FILE:
53		return 0;
54
55	case LRS_ESTABLISHED:
56
57		if (lwsi_role_ws(wsi))
58			goto ws_mode;
59
60		if (lwsi_role_client(wsi))
61			break;
62
63		wsi->hdr_parsing_completed = 0;
64
65		/* fallthru */
66
67	case LRS_HEADERS:
68		if (!wsi->http.ah) {
69			lwsl_err("%s: LRS_HEADERS: NULL ah\n", __func__);
70			assert(0);
71		}
72		lwsl_parser("issuing %d bytes to parser\n", (int)len);
73#if defined(LWS_ROLE_WS) && defined(LWS_WITH_CLIENT)
74		if (lws_ws_handshake_client(wsi, &buf, (size_t)len))
75			goto bail;
76#endif
77		last_char = buf;
78		if (lws_handshake_server(wsi, &buf, (size_t)len))
79			/* Handshake indicates this session is done. */
80			goto bail;
81
82		/* we might have transitioned to RAW */
83		if (wsi->role_ops == &role_ops_raw_skt
84#if defined(LWS_ROLE_RAW_FILE)
85				||
86		    wsi->role_ops == &role_ops_raw_file
87#endif
88		    )
89			 /* we gave the read buffer to RAW handler already */
90			goto read_ok;
91
92		/*
93		 * It's possible that we've exhausted our data already, or
94		 * rx flow control has stopped us dealing with this early,
95		 * but lws_handshake_server doesn't update len for us.
96		 * Figure out how much was read, so that we can proceed
97		 * appropriately:
98		 */
99		len -= (unsigned int)lws_ptr_diff(buf, last_char);
100
101		if (!wsi->hdr_parsing_completed)
102			/* More header content on the way */
103			goto read_ok;
104
105		switch (lwsi_state(wsi)) {
106			case LRS_ESTABLISHED:
107			case LRS_HEADERS:
108				goto read_ok;
109			case LRS_ISSUING_FILE:
110				goto read_ok;
111			case LRS_DISCARD_BODY:
112			case LRS_BODY:
113				wsi->http.rx_content_remain =
114						wsi->http.rx_content_length;
115				if (wsi->http.rx_content_remain)
116					goto http_postbody;
117
118				/* there is no POST content */
119				goto postbody_completion;
120			default:
121				break;
122		}
123		break;
124
125	case LRS_DISCARD_BODY:
126	case LRS_BODY:
127http_postbody:
128		lwsl_info("%s: http post body: cl set %d, remain %d, len %d\n", __func__,
129			    (int)wsi->http.content_length_given,
130			    (int)wsi->http.rx_content_remain, (int)len);
131
132		if (wsi->http.content_length_given && !wsi->http.rx_content_remain)
133			goto postbody_completion;
134
135		while (len && (!wsi->http.content_length_given || wsi->http.rx_content_remain)) {
136			/* Copy as much as possible, up to the limit of:
137			 * what we have in the read buffer (len)
138			 * remaining portion of the POST body (content_remain)
139			 */
140			if (wsi->http.content_length_given)
141				body_chunk_len = min(wsi->http.rx_content_remain, len);
142			else
143				body_chunk_len = len;
144			wsi->http.rx_content_remain -= body_chunk_len;
145			// len -= body_chunk_len;
146#ifdef LWS_WITH_CGI
147			if (wsi->http.cgi) {
148				struct lws_cgi_args args;
149
150				args.ch = LWS_STDIN;
151				args.stdwsi = &wsi->http.cgi->lsp->stdwsi[0];
152				args.data = buf;
153				args.len = (int)(unsigned int)body_chunk_len;
154
155				/* returns how much used */
156				n = (unsigned int)user_callback_handle_rxflow(
157					wsi->a.protocol->callback,
158					wsi, LWS_CALLBACK_CGI_STDIN_DATA,
159					wsi->user_space,
160					(void *)&args, 0);
161				if ((int)n < 0)
162					goto bail;
163			} else {
164#endif
165				if (lwsi_state(wsi) != LRS_DISCARD_BODY) {
166					lwsl_info("%s: HTTP_BODY %d\n", __func__, (int)body_chunk_len);
167					n = (unsigned int)wsi->a.protocol->callback(wsi,
168						LWS_CALLBACK_HTTP_BODY, wsi->user_space,
169						buf, (size_t)body_chunk_len);
170					if (n)
171						goto bail;
172				}
173				n = (size_t)body_chunk_len;
174#ifdef LWS_WITH_CGI
175			}
176#endif
177			lwsl_info("%s: advancing buf by %d\n", __func__, (int)n);
178			buf += n;
179
180#if defined(LWS_ROLE_H2)
181			if (lwsi_role_h2(wsi) && !wsi->http.content_length_given) {
182				struct lws *w = lws_get_network_wsi(wsi);
183
184				if (w)
185					lwsl_info("%s: h2: nwsi h2 flags %d\n", __func__,
186						w->h2.h2n ? w->h2.h2n->flags: -1);
187
188				if (w && w->h2.h2n && !(w->h2.h2n->flags & 1)) {
189					lwsl_info("%s: h2, no cl, not END_STREAM, continuing\n", __func__);
190					lws_set_timeout(wsi,
191						PENDING_TIMEOUT_HTTP_CONTENT,
192						(int)wsi->a.context->timeout_secs);
193					break;
194				}
195				goto postbody_completion;
196			}
197#endif
198
199			if (wsi->http.rx_content_remain)  {
200				lws_set_timeout(wsi,
201						PENDING_TIMEOUT_HTTP_CONTENT,
202						(int)wsi->a.context->timeout_secs);
203				break;
204			}
205			/* he sent all the content in time */
206postbody_completion:
207#ifdef LWS_WITH_CGI
208			/*
209			 * If we're running a cgi, we can't let him off the
210			 * hook just because he sent his POST data
211			 */
212			if (wsi->http.cgi)
213				lws_set_timeout(wsi, PENDING_TIMEOUT_CGI,
214						(int)wsi->a.context->timeout_secs);
215			else
216#endif
217			lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
218#ifdef LWS_WITH_CGI
219			if (!wsi->http.cgi)
220#endif
221			{
222#if defined(LWS_WITH_SERVER)
223				if (lwsi_state(wsi) == LRS_DISCARD_BODY) {
224					/*
225					 * repeat the transaction completed
226					 * that got us into this state, having
227					 * consumed the pending body now
228					 */
229
230					if (lws_http_transaction_completed(wsi))
231						goto bail;
232					break;
233				}
234#endif
235				lwsl_info("HTTP_BODY_COMPLETION: %s (%s)\n",
236					  lws_wsi_tag(wsi), wsi->a.protocol->name);
237
238				n = (unsigned int)wsi->a.protocol->callback(wsi,
239					LWS_CALLBACK_HTTP_BODY_COMPLETION,
240					wsi->user_space, NULL, 0);
241				if (n) {
242					lwsl_info("%s: bailing after BODY_COMPLETION\n", __func__);
243					goto bail;
244				}
245
246				if (wsi->mux_substream)
247					lwsi_set_state(wsi, LRS_ESTABLISHED);
248			}
249
250			break;
251		}
252		break;
253
254	case LRS_RETURNED_CLOSE:
255	case LRS_AWAITING_CLOSE_ACK:
256	case LRS_WAITING_TO_SEND_CLOSE:
257	case LRS_SHUTDOWN:
258
259ws_mode:
260#if defined(LWS_WITH_CLIENT) && defined(LWS_ROLE_WS)
261		// lwsl_notice("%s: ws_mode\n", __func__);
262		if (lws_ws_handshake_client(wsi, &buf, (size_t)len))
263			goto bail;
264#endif
265#if defined(LWS_ROLE_WS)
266		if (lwsi_role_ws(wsi) && lwsi_role_server(wsi) &&
267			/*
268			 * for h2 we are on the swsi
269			 */
270		    lws_parse_ws(wsi, &buf, (size_t)len) < 0) {
271			lwsl_info("%s: lws_parse_ws bailed\n", __func__);
272			goto bail;
273		}
274#endif
275		// lwsl_notice("%s: ws_mode: buf moved on by %d\n", __func__,
276		//	       lws_ptr_diff(buf, oldbuf));
277		break;
278
279	case LRS_DEFERRING_ACTION:
280		lwsl_notice("%s: LRS_DEFERRING_ACTION\n", __func__);
281		break;
282
283	case LRS_SSL_ACK_PENDING:
284		break;
285
286	case LRS_FLUSHING_BEFORE_CLOSE:
287		break;
288
289	case LRS_DEAD_SOCKET:
290		lwsl_err("%s: Unhandled state LRS_DEAD_SOCKET\n", __func__);
291		goto bail;
292		// assert(0);
293		/* fallthru */
294
295	case LRS_WAITING_CONNECT: /* observed on warmcat.com */
296		break;
297
298	default:
299		lwsl_err("%s: Unhandled state %d\n", __func__, lwsi_state(wsi));
300		goto bail;
301	}
302
303read_ok:
304	/* Nothing more to do for now */
305//	lwsl_info("%s: %p: read_ok, used %ld (len %d, state %d)\n", __func__,
306//		  wsi, (long)(buf - oldbuf), (int)len, wsi->state);
307
308	return lws_ptr_diff(buf, oldbuf);
309
310bail:
311	/*
312	 * h2 / h2-ws calls us recursively in
313	 *
314	 * lws_read_h1()->
315	 *   lws_h2_parser()->
316	 *     lws_read_h1()
317	 *
318	 * pattern, having stripped the h2 framing in the middle.
319	 *
320	 * When taking down the whole connection, make sure that only the
321	 * outer lws_read() does the wsi close.
322	 */
323	if (!wsi->outer_will_close)
324		lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS,
325				   "lws_read_h1 bail");
326
327	return -1;
328}
329#if defined(LWS_WITH_SERVER)
330static int
331lws_h1_server_socket_service(struct lws *wsi, struct lws_pollfd *pollfd)
332{
333	struct lws_context_per_thread *pt = &wsi->a.context->pt[(int)wsi->tsi];
334	struct lws_tokens ebuf;
335	int n, buffered;
336
337	if (lwsi_state(wsi) == LRS_DEFERRING_ACTION)
338		goto try_pollout;
339
340	/* any incoming data ready? */
341
342	if (!(pollfd->revents & pollfd->events & LWS_POLLIN))
343		goto try_pollout;
344
345	/*
346	 * If we previously just did POLLIN when IN and OUT were signaled
347	 * (because POLLIN processing may have used up the POLLOUT), don't let
348	 * that happen twice in a row... next time we see the situation favour
349	 * POLLOUT
350	 */
351
352	if (wsi->favoured_pollin &&
353	    (pollfd->revents & pollfd->events & LWS_POLLOUT)) {
354		// lwsl_notice("favouring pollout\n");
355		wsi->favoured_pollin = 0;
356		goto try_pollout;
357	}
358
359	/*
360	 * We haven't processed that the tunnel is set up yet, so
361	 * defer reading
362	 */
363
364	if (lwsi_state(wsi) == LRS_SSL_ACK_PENDING)
365		return LWS_HPI_RET_HANDLED;
366
367	/* these states imply we MUST have an ah attached */
368
369	if ((lwsi_state(wsi) == LRS_ESTABLISHED ||
370	     lwsi_state(wsi) == LRS_ISSUING_FILE ||
371	     lwsi_state(wsi) == LRS_HEADERS ||
372	     lwsi_state(wsi) == LRS_DOING_TRANSACTION || /* at least, SSE */
373	     lwsi_state(wsi) == LRS_DISCARD_BODY ||
374	     lwsi_state(wsi) == LRS_BODY)) {
375
376		if (!wsi->http.ah && lws_header_table_attach(wsi, 0)) {
377			lwsl_info("%s: %s: ah not available\n", __func__,
378				  lws_wsi_tag(wsi));
379			goto try_pollout;
380		}
381
382		/*
383		 * We got here because there was specifically POLLIN...
384		 * regardless of our buflist state, we need to get it,
385		 * and either use it, or append to the buflist and use
386		 * buflist head material.
387		 *
388		 * We will not notice a connection close until the buflist is
389		 * exhausted and we tried to do a read of some kind.
390		 */
391
392		ebuf.token = NULL;
393		ebuf.len = 0;
394		buffered = lws_buflist_aware_read(pt, wsi, &ebuf, 0, __func__);
395		switch (ebuf.len) {
396		case 0:
397			lwsl_info("%s: read 0 len a\n", __func__);
398			wsi->seen_zero_length_recv = 1;
399			if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
400				goto fail;
401#if !defined(LWS_WITHOUT_EXTENSIONS)
402			/*
403			 * autobahn requires us to win the race between close
404			 * and draining the extensions
405			 */
406			if (wsi->ws &&
407			    (wsi->ws->rx_draining_ext ||
408			     wsi->ws->tx_draining_ext))
409				goto try_pollout;
410#endif
411			/*
412			 * normally, we respond to close with logically closing
413			 * our side immediately
414			 */
415			goto fail;
416
417		case LWS_SSL_CAPABLE_ERROR:
418			goto fail;
419		case LWS_SSL_CAPABLE_MORE_SERVICE:
420			goto try_pollout;
421		}
422
423		/* just ignore incoming if waiting for close */
424		if (lwsi_state(wsi) == LRS_FLUSHING_BEFORE_CLOSE) {
425			lwsl_notice("%s: just ignoring\n", __func__);
426			goto try_pollout;
427		}
428
429		if (lwsi_state(wsi) == LRS_ISSUING_FILE) {
430			// lwsl_notice("stashing: wsi %p: bd %d\n", wsi, buffered);
431			if (lws_buflist_aware_finished_consuming(wsi, &ebuf, 0,
432							buffered, __func__))
433				return LWS_HPI_RET_PLEASE_CLOSE_ME;
434
435			goto try_pollout;
436		}
437
438		/*
439		 * Otherwise give it to whoever wants it according to the
440		 * connection state
441		 */
442#if defined(LWS_ROLE_H2)
443		if (lwsi_role_h2(wsi) && lwsi_state(wsi) != LRS_BODY)
444			n = lws_read_h2(wsi, ebuf.token, (unsigned int)ebuf.len);
445		else
446#endif
447			n = lws_read_h1(wsi, ebuf.token, (unsigned int)ebuf.len);
448		if (n < 0) /* we closed wsi */
449			return LWS_HPI_RET_WSI_ALREADY_DIED;
450
451		// lwsl_notice("%s: consumed %d\n", __func__, n);
452
453		if (lws_buflist_aware_finished_consuming(wsi, &ebuf, n,
454							 buffered, __func__))
455			return LWS_HPI_RET_PLEASE_CLOSE_ME;
456
457		/*
458		 * during the parsing our role changed to something non-http,
459		 * so the ah has no further meaning
460		 */
461
462		if (wsi->http.ah &&
463		    !lwsi_role_h1(wsi) &&
464		    !lwsi_role_h2(wsi) &&
465		    !lwsi_role_cgi(wsi))
466			lws_header_table_detach(wsi, 0);
467
468		/*
469		 * He may have used up the writability above, if we will defer
470		 * POLLOUT processing in favour of POLLIN, note it
471		 */
472
473		if (pollfd->revents & LWS_POLLOUT)
474			wsi->favoured_pollin = 1;
475
476		return LWS_HPI_RET_HANDLED;
477	}
478
479	/*
480	 * He may have used up the writability above, if we will defer POLLOUT
481	 * processing in favour of POLLIN, note it
482	 */
483
484	if (pollfd->revents & LWS_POLLOUT)
485		wsi->favoured_pollin = 1;
486
487try_pollout:
488
489	/* this handles POLLOUT for http serving fragments */
490
491	if (!(pollfd->revents & LWS_POLLOUT))
492		return LWS_HPI_RET_HANDLED;
493
494	/* one shot */
495	if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
496		lwsl_notice("%s a\n", __func__);
497		goto fail;
498	}
499
500	/* clear back-to-back write detection */
501	wsi->could_have_pending = 0;
502
503	if (lwsi_state(wsi) == LRS_DEFERRING_ACTION) {
504		lwsl_debug("%s: LRS_DEFERRING_ACTION now writable\n", __func__);
505
506		lwsi_set_state(wsi, LRS_ESTABLISHED);
507		if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
508			lwsl_info("failed at set pollfd\n");
509			goto fail;
510		}
511	}
512
513	if (!wsi->hdr_parsing_completed)
514		return LWS_HPI_RET_HANDLED;
515
516	if (lwsi_state(wsi) != LRS_ISSUING_FILE) {
517
518		if (lws_has_buffered_out(wsi)) {
519			//lwsl_notice("%s: completing partial\n", __func__);
520			if (lws_issue_raw(wsi, NULL, 0) < 0) {
521				lwsl_info("%s signalling to close\n", __func__);
522				goto fail;
523			}
524			return LWS_HPI_RET_HANDLED;
525		}
526
527		n = user_callback_handle_rxflow(wsi->a.protocol->callback, wsi,
528						LWS_CALLBACK_HTTP_WRITEABLE,
529						wsi->user_space, NULL, 0);
530		if (n < 0) {
531			lwsl_info("writeable_fail\n");
532			goto fail;
533		}
534
535		return LWS_HPI_RET_HANDLED;
536	}
537
538#if defined(LWS_WITH_FILE_OPS)
539
540	/* >0 == completion, <0 == error
541	 *
542	 * We'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
543	 * it's done.  That's the case even if we just completed the
544	 * send, so wait for that.
545	 */
546	n = lws_serve_http_file_fragment(wsi);
547	if (n < 0)
548		goto fail;
549#endif
550
551	return LWS_HPI_RET_HANDLED;
552
553
554fail:
555	lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS,
556			   "server socket svc fail");
557
558	return LWS_HPI_RET_WSI_ALREADY_DIED;
559}
560#endif
561
562static int
563rops_handle_POLLIN_h1(struct lws_context_per_thread *pt, struct lws *wsi,
564		       struct lws_pollfd *pollfd)
565{
566	if (lwsi_state(wsi) == LRS_IDLING) {
567		uint8_t buf[1];
568		int rlen;
569
570		/*
571		 * h1 staggered spins here in IDLING if we don't close it.
572		 * It shows POLLIN but the tls connection returns ERROR if
573		 * you try to read it.
574		 */
575
576		// lwsl_notice("%s: %p: wsistate 0x%x %s, revents 0x%x\n",
577		//	    __func__, wsi, wsi->wsistate, wsi->role_ops->name,
578		//	    pollfd->revents);
579
580		rlen = lws_ssl_capable_read(wsi, buf, sizeof(buf));
581		if (rlen == LWS_SSL_CAPABLE_ERROR)
582			return LWS_HPI_RET_PLEASE_CLOSE_ME;
583	}
584
585#ifdef LWS_WITH_CGI
586	if (wsi->http.cgi && (pollfd->revents & LWS_POLLOUT)) {
587		if (lws_handle_POLLOUT_event(wsi, pollfd))
588			return LWS_HPI_RET_PLEASE_CLOSE_ME;
589
590		return LWS_HPI_RET_HANDLED;
591	}
592#endif
593
594	/* Priority 2: pre- compression transform */
595
596#if defined(LWS_WITH_HTTP_STREAM_COMPRESSION)
597	if (wsi->http.comp_ctx.buflist_comp ||
598	    wsi->http.comp_ctx.may_have_more) {
599		enum lws_write_protocol wp = LWS_WRITE_HTTP;
600
601		lwsl_info("%s: completing comp partial (buflist_comp %p, may %d)\n",
602				__func__, wsi->http.comp_ctx.buflist_comp,
603				wsi->http.comp_ctx.may_have_more
604				);
605
606		if (lws_rops_fidx(wsi->role_ops, LWS_ROPS_write_role_protocol) &&
607		    lws_rops_func_fidx(wsi->role_ops, LWS_ROPS_write_role_protocol).
608					write_role_protocol(wsi, NULL, 0, &wp) < 0) {
609			lwsl_info("%s signalling to close\n", __func__);
610			return LWS_HPI_RET_PLEASE_CLOSE_ME;
611		}
612		lws_callback_on_writable(wsi);
613
614		if (!wsi->http.comp_ctx.buflist_comp &&
615		    !wsi->http.comp_ctx.may_have_more &&
616		    wsi->http.deferred_transaction_completed) {
617			wsi->http.deferred_transaction_completed = 0;
618			if (lws_http_transaction_completed(wsi))
619				return LWS_HPI_RET_PLEASE_CLOSE_ME;
620		}
621
622		return LWS_HPI_RET_HANDLED;
623	}
624#endif
625
626        if (lws_is_flowcontrolled(wsi))
627                /* We cannot deal with any kind of new RX because we are
628                 * RX-flowcontrolled.
629                 */
630		return LWS_HPI_RET_HANDLED;
631
632#if defined(LWS_WITH_SERVER)
633	if (!lwsi_role_client(wsi)) {
634		int n;
635
636		lwsl_debug("%s: %s: wsistate 0x%x\n", __func__, lws_wsi_tag(wsi),
637			   (unsigned int)wsi->wsistate);
638
639		if (pollfd->revents & LWS_POLLHUP &&
640		    !lws_buflist_total_len(&wsi->buflist))
641			return LWS_HPI_RET_PLEASE_CLOSE_ME;
642
643		n = lws_h1_server_socket_service(wsi, pollfd);
644		if (n != LWS_HPI_RET_HANDLED)
645			return n;
646		if (lwsi_state(wsi) != LRS_SSL_INIT)
647			if (lws_server_socket_service_ssl(wsi,
648							  LWS_SOCK_INVALID,
649					!!(pollfd->revents & LWS_POLLIN)))
650				return LWS_HPI_RET_PLEASE_CLOSE_ME;
651
652		return LWS_HPI_RET_HANDLED;
653	}
654#endif
655
656#if defined(LWS_WITH_CLIENT)
657	if ((pollfd->revents & LWS_POLLIN) &&
658	     wsi->hdr_parsing_completed && !wsi->told_user_closed) {
659
660		/*
661		 * In SSL mode we get POLLIN notification about
662		 * encrypted data in.
663		 *
664		 * But that is not necessarily related to decrypted
665		 * data out becoming available; in may need to perform
666		 * other in or out before that happens.
667		 *
668		 * simply mark ourselves as having readable data
669		 * and turn off our POLLIN
670		 */
671		wsi->client_rx_avail = 1;
672		if (lws_change_pollfd(wsi, LWS_POLLIN, 0))
673			return LWS_HPI_RET_PLEASE_CLOSE_ME;
674
675		//lwsl_notice("calling back %s\n", wsi->a.protocol->name);
676
677		/* let user code know, he'll usually ask for writeable
678		 * callback and drain / re-enable it there
679		 */
680		if (user_callback_handle_rxflow(wsi->a.protocol->callback, wsi,
681					       LWS_CALLBACK_RECEIVE_CLIENT_HTTP,
682						wsi->user_space, NULL, 0)) {
683			lwsl_info("RECEIVE_CLIENT_HTTP closed it\n");
684			return LWS_HPI_RET_PLEASE_CLOSE_ME;
685		}
686
687		return LWS_HPI_RET_HANDLED;
688	}
689#endif
690
691//	if (lwsi_state(wsi) == LRS_ESTABLISHED)
692//		return LWS_HPI_RET_HANDLED;
693
694#if defined(LWS_WITH_CLIENT)
695	if ((pollfd->revents & LWS_POLLOUT) &&
696	    lws_handle_POLLOUT_event(wsi, pollfd)) {
697		lwsl_debug("POLLOUT event closed it\n");
698		return LWS_HPI_RET_PLEASE_CLOSE_ME;
699	}
700
701	if (lws_http_client_socket_service(wsi, pollfd))
702		return LWS_HPI_RET_WSI_ALREADY_DIED;
703#endif
704
705	if (lwsi_state(wsi) == LRS_WAITING_CONNECT &&
706	    (pollfd->revents & LWS_POLLHUP))
707		return LWS_HPI_RET_PLEASE_CLOSE_ME;
708
709	return LWS_HPI_RET_HANDLED;
710}
711
712static int
713rops_handle_POLLOUT_h1(struct lws *wsi)
714{
715
716
717	if (lwsi_state(wsi) == LRS_ISSUE_HTTP_BODY ||
718	    lwsi_state(wsi) == LRS_WAITING_SERVER_REPLY) {
719#if defined(LWS_WITH_HTTP_PROXY)
720		if (wsi->http.proxy_clientside) {
721			unsigned char *buf, prebuf[LWS_PRE + 1024];
722			size_t len = lws_buflist_next_segment_len(
723					&wsi->parent->http.buflist_post_body, &buf);
724			int n;
725
726			if (len > sizeof(prebuf) - LWS_PRE)
727				len = sizeof(prebuf) - LWS_PRE;
728
729			if (len) {
730				memcpy(prebuf + LWS_PRE, buf, len);
731
732				lwsl_debug("%s: %s: proxying body %d %d %d %d %d\n",
733						__func__, lws_wsi_tag(wsi), (int)len,
734						(int)wsi->http.tx_content_length,
735						(int)wsi->http.tx_content_remain,
736						(int)wsi->http.rx_content_length,
737						(int)wsi->http.rx_content_remain
738						);
739
740				n = lws_write(wsi, prebuf + LWS_PRE, len, LWS_WRITE_HTTP);
741				if (n < 0) {
742					lwsl_err("%s: PROXY_BODY: write %d failed\n",
743						 __func__, (int)len);
744					return LWS_HP_RET_BAIL_DIE;
745				}
746
747				lws_buflist_use_segment(&wsi->parent->http.buflist_post_body, len);
748
749			}
750
751			if (wsi->parent->http.buflist_post_body) {
752				lws_callback_on_writable(wsi);
753				return LWS_HP_RET_DROP_POLLOUT;
754			}
755
756			lwsl_wsi_err(wsi, "nothing to send");
757#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)
758			/* prepare ourselves to do the parsing */
759			wsi->http.ah->parser_state = WSI_TOKEN_NAME_PART;
760			wsi->http.ah->lextable_pos = 0;
761#if defined(LWS_WITH_CUSTOM_HEADERS)
762			wsi->http.ah->unk_pos = 0;
763#endif
764#endif
765			lwsi_set_state(wsi, LRS_WAITING_SERVER_REPLY);
766			lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE,
767					(int)wsi->a.context->timeout_secs);
768
769			return LWS_HP_RET_DROP_POLLOUT;
770		}
771#endif
772		return LWS_HP_RET_USER_SERVICE;
773	}
774
775	if (lwsi_role_client(wsi))
776		return LWS_HP_RET_USER_SERVICE;
777
778	return LWS_HP_RET_BAIL_OK;
779}
780
781static int
782rops_write_role_protocol_h1(struct lws *wsi, unsigned char *buf, size_t len,
783			    enum lws_write_protocol *wp)
784{
785	size_t olen = len;
786	int n;
787
788#if defined(LWS_WITH_HTTP_STREAM_COMPRESSION)
789	if (wsi->http.lcs && (((*wp) & 0x1f) == LWS_WRITE_HTTP_FINAL ||
790			      ((*wp) & 0x1f) == LWS_WRITE_HTTP)) {
791		unsigned char mtubuf[1500 + LWS_PRE +
792				     LWS_HTTP_CHUNK_HDR_MAX_SIZE +
793				     LWS_HTTP_CHUNK_TRL_MAX_SIZE],
794			      *out = mtubuf + LWS_PRE +
795				     LWS_HTTP_CHUNK_HDR_MAX_SIZE;
796		size_t o = sizeof(mtubuf) - LWS_PRE -
797			   LWS_HTTP_CHUNK_HDR_MAX_SIZE -
798			   LWS_HTTP_CHUNK_TRL_MAX_SIZE;
799
800		n = lws_http_compression_transform(wsi, buf, len, wp, &out, &o);
801		if (n)
802			return n;
803
804		lwsl_info("%s: %s: transformed %d bytes to %d "
805			   "(wp 0x%x, more %d)\n", __func__,
806			   lws_wsi_tag(wsi), (int)len,
807			   (int)o, (int)*wp, wsi->http.comp_ctx.may_have_more);
808
809		if (!o)
810			return (int)olen;
811
812		if (wsi->http.comp_ctx.chunking) {
813			char c[LWS_HTTP_CHUNK_HDR_MAX_SIZE + 2];
814			/*
815			 * this only needs dealing with on http/1.1 to allow
816			 * pipelining
817			 */
818			n = lws_snprintf(c, sizeof(c), "%X\x0d\x0a", (int)o);
819			lwsl_info("%s: chunk (%d) %s", __func__, (int)o, c);
820			out -= n;
821			o += (unsigned int)n;
822			memcpy(out, c, (unsigned int)n);
823			out[o++] = '\x0d';
824			out[o++] = '\x0a';
825
826			if (((*wp) & 0x1f) == LWS_WRITE_HTTP_FINAL) {
827				lwsl_info("%s: final chunk\n", __func__);
828				out[o++] = '0';
829				out[o++] = '\x0d';
830				out[o++] = '\x0a';
831				out[o++] = '\x0d';
832				out[o++] = '\x0a';
833			}
834		}
835
836		buf = out;
837		len = o;
838	}
839#endif
840
841	n = lws_issue_raw(wsi, (unsigned char *)buf, len);
842	if (n < 0)
843		return n;
844
845	/* hide there may have been compression */
846
847	return (int)olen;
848}
849
850static int
851rops_alpn_negotiated_h1(struct lws *wsi, const char *alpn)
852{
853	lwsl_debug("%s: client %d\n", __func__, lwsi_role_client(wsi));
854#if defined(LWS_WITH_CLIENT)
855	if (lwsi_role_client(wsi)) {
856		/*
857		 * If alpn asserts it is http/1.1, server support for KA is
858		 * mandatory.
859		 *
860		 * Knowing this lets us proceed with sending pipelined headers
861		 * before we received the first response headers.
862		 */
863		wsi->keepalive_active = 1;
864	}
865#endif
866
867	return 0;
868}
869
870static int
871rops_destroy_role_h1(struct lws *wsi)
872{
873	struct lws_context_per_thread *pt = &wsi->a.context->pt[(int)wsi->tsi];
874	struct allocated_headers *ah;
875
876	/* we may not have an ah, but may be on the waiting list... */
877	lwsl_info("%s: ah det due to close\n", __func__);
878	__lws_header_table_detach(wsi, 0);
879
880	 ah = pt->http.ah_list;
881
882	while (ah) {
883		if (ah->in_use && ah->wsi == wsi) {
884			lwsl_err("%s: ah leak: wsi %s\n", __func__,
885					lws_wsi_tag(wsi));
886			ah->in_use = 0;
887			ah->wsi = NULL;
888			pt->http.ah_count_in_use--;
889			break;
890		}
891		ah = ah->next;
892	}
893
894#if defined(LWS_WITH_HTTP_STREAM_COMPRESSION)
895	lws_http_compression_destroy(wsi);
896#endif
897
898#ifdef LWS_ROLE_WS
899	lws_free_set_NULL(wsi->ws);
900#endif
901	return 0;
902}
903
904#if defined(LWS_WITH_SERVER)
905
906static int
907rops_adoption_bind_h1(struct lws *wsi, int type, const char *vh_prot_name)
908{
909	if (!(type & LWS_ADOPT_HTTP))
910		return 0; /* no match */
911
912	if (type & _LWS_ADOPT_FINISH && !lwsi_role_http(wsi))
913		return 0;
914
915	if (type & _LWS_ADOPT_FINISH) {
916		if (!lws_header_table_attach(wsi, 0))
917			lwsl_debug("Attached ah immediately\n");
918		else
919			lwsl_info("%s: waiting for ah\n", __func__);
920
921		return 1;
922	}
923
924#if defined(LWS_WITH_SERVER) && defined(LWS_WITH_SECURE_STREAMS)
925	if (wsi->a.vhost->ss_handle &&
926	    wsi->a.vhost->ss_handle->policy->protocol == LWSSSP_RAW) {
927		lws_role_transition(wsi, LWSIFR_SERVER, (type & LWS_ADOPT_ALLOW_SSL) ?
928				LRS_SSL_INIT : LRS_ESTABLISHED, &role_ops_raw_skt);
929		return 1;
930	}
931#endif
932
933	/* If Non-TLS and HTTP2 prior knowledge is enabled, skip to clear text HTTP2 */
934
935#if defined(LWS_WITH_HTTP2)
936	if ((!(type & LWS_ADOPT_ALLOW_SSL)) && (wsi->a.vhost->options & LWS_SERVER_OPTION_H2_PRIOR_KNOWLEDGE)) {
937		lwsl_info("http/2 prior knowledge\n");
938		lws_metrics_tag_wsi_add(wsi, "upg", "h2_prior");
939		lws_role_call_alpn_negotiated(wsi, "h2");
940	}
941	else
942#endif
943		lws_role_transition(wsi, LWSIFR_SERVER, (type & LWS_ADOPT_ALLOW_SSL) ?
944				LRS_SSL_INIT : LRS_HEADERS, &role_ops_h1);
945
946	/*
947	 * Otherwise, we have to bind to h1 as a default even when we're actually going to
948	 * replace it as an h2 bind later.  So don't take this seriously if the
949	 * default is disabled (ws upgrade caees properly about it)
950	 */
951
952	if (!vh_prot_name && wsi->a.vhost->default_protocol_index <
953			     wsi->a.vhost->count_protocols)
954		wsi->a.protocol = &wsi->a.vhost->protocols[
955				wsi->a.vhost->default_protocol_index];
956	else
957		wsi->a.protocol = &wsi->a.vhost->protocols[0];
958
959	/* the transport is accepted... give him time to negotiate */
960	lws_set_timeout(wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
961			(int)wsi->a.context->timeout_secs);
962
963	return 1; /* bound */
964}
965
966#endif
967
968#if defined(LWS_WITH_CLIENT)
969
970static const char * const http_methods[] = {
971	"GET", "POST", "OPTIONS", "HEAD", "PUT", "PATCH", "DELETE", "CONNECT"
972};
973
974static int
975rops_client_bind_h1(struct lws *wsi, const struct lws_client_connect_info *i)
976{
977	int n;
978
979	if (!i) {
980		/* we are finalizing an already-selected role */
981
982		/*
983		 * If we stay in http, assuming there wasn't already-set
984		 * external user_space, since we know our initial protocol
985		 * we can assign the user space now, otherwise do it after the
986		 * ws subprotocol negotiated
987		 */
988		if (!wsi->user_space && wsi->stash->cis[CIS_METHOD])
989			if (lws_ensure_user_space(wsi))
990				return 1;
991
992		 /*
993		  * For ws, default to http/1.1 only.  If i->alpn had been set
994		  * though, defer to whatever he has set in there (eg, "h2").
995		  *
996		  * The problem is he has to commit to h2 before he can find
997		  * out if the server has the SETTINGS for ws-over-h2 enabled;
998		  * if not then ws is not possible on that connection.  So we
999		  * only try h2 if he assertively said to use h2 alpn, otherwise
1000		  * ws implies alpn restriction to h1.
1001		  */
1002		if (!wsi->stash->cis[CIS_METHOD] && !wsi->stash->cis[CIS_ALPN])
1003			wsi->stash->cis[CIS_ALPN] = "http/1.1";
1004
1005		/* if we went on the ah waiting list, it's ok, we can wait.
1006		 *
1007		 * When we do get the ah, now or later, he will end up at
1008		 * lws_http_client_connect_via_info2().
1009		 */
1010		if (lws_header_table_attach(wsi, 0)
1011#if defined(LWS_WITH_CLIENT)
1012				< 0)
1013			/*
1014			 * if we failed here, the connection is already closed
1015			 * and freed.
1016			 */
1017			return -1;
1018#else
1019			)
1020				return 0;
1021#endif
1022
1023		return 0;
1024	}
1025
1026	/*
1027	 * Clients that want to be h1, h2, or ws all start out as h1
1028	 * (we don't yet know if the server supports h2 or ws), unless their
1029	 * alpn is only "h2"
1030	 */
1031
1032//	if (i->alpn && !strcmp(i->alpn, "h2"))
1033//		return 0; /* we are h1, he only wants h2 */
1034
1035	if (!i->method) { /* websockets */
1036#if defined(LWS_ROLE_WS)
1037		if (lws_create_client_ws_object(i, wsi))
1038			goto fail_wsi;
1039
1040		goto bind_h1;
1041#else
1042		lwsl_err("%s: ws role not configured\n", __func__);
1043
1044		goto fail_wsi;
1045#endif
1046	}
1047
1048	/* if a recognized http method, bind to it */
1049
1050	for (n = 0; n < (int)LWS_ARRAY_SIZE(http_methods); n++)
1051		if (!strcmp(i->method, http_methods[n]))
1052			goto bind_h1;
1053
1054	/* other roles may bind to it */
1055
1056	return 0; /* no match */
1057
1058bind_h1:
1059	/* assert the mode and union status (hdr) clearly */
1060	lws_role_transition(wsi, LWSIFR_CLIENT, LRS_UNCONNECTED, &role_ops_h1);
1061
1062	return 1; /* matched */
1063
1064fail_wsi:
1065	return -1;
1066}
1067#endif
1068
1069static int
1070rops_close_kill_connection_h1(struct lws *wsi, enum lws_close_status reason)
1071{
1072#if defined(LWS_WITH_HTTP_PROXY)
1073	if (!wsi->http.proxy_clientside)
1074		return 0;
1075
1076	wsi->http.proxy_clientside = 0;
1077
1078	if (user_callback_handle_rxflow(wsi->a.protocol->callback, wsi,
1079					LWS_CALLBACK_COMPLETED_CLIENT_HTTP,
1080					wsi->user_space, NULL, 0))
1081		return 0;
1082#endif
1083	return 0;
1084}
1085
1086int
1087rops_pt_init_destroy_h1(struct lws_context *context,
1088		    const struct lws_context_creation_info *info,
1089		    struct lws_context_per_thread *pt, int destroy)
1090{
1091	/*
1092	 * We only want to do this once... we will do it if no h2 support
1093	 * otherwise let h2 ops do it.
1094	 */
1095#if !defined(LWS_ROLE_H2) && defined(LWS_WITH_SERVER)
1096	if (!destroy) {
1097
1098		pt->sul_ah_lifecheck.cb = lws_sul_http_ah_lifecheck;
1099
1100		__lws_sul_insert_us(&pt->pt_sul_owner[LWSSULLI_MISS_IF_SUSPENDED],
1101				 &pt->sul_ah_lifecheck, 30 * LWS_US_PER_SEC);
1102	} else
1103		lws_dll2_remove(&pt->sul_ah_lifecheck.list);
1104#endif
1105
1106	return 0;
1107}
1108
1109static const lws_rops_t rops_table_h1[] = {
1110	/*  1 */ { .pt_init_destroy	  = rops_pt_init_destroy_h1 },
1111	/*  2 */ { .handle_POLLIN	  = rops_handle_POLLIN_h1 },
1112	/*  3 */ { .handle_POLLOUT	  = rops_handle_POLLOUT_h1 },
1113	/*  4 */ { .write_role_protocol	  = rops_write_role_protocol_h1 },
1114	/*  5 */ { .alpn_negotiated	  = rops_alpn_negotiated_h1 },
1115	/*  6 */ { .close_kill_connection = rops_close_kill_connection_h1 },
1116	/*  7 */ { .destroy_role	  = rops_destroy_role_h1 },
1117#if defined(LWS_WITH_SERVER)
1118	/*  8 */ { .adoption_bind	  = rops_adoption_bind_h1 },
1119#endif
1120#if defined(LWS_WITH_CLIENT)
1121	/*  8 if client and no server */
1122	/*  9 */ { .client_bind		  = rops_client_bind_h1 },
1123#endif
1124};
1125
1126const struct lws_role_ops role_ops_h1 = {
1127	/* role name */			"h1",
1128	/* alpn id */			"http/1.1",
1129	/* rops_table */		rops_table_h1,
1130	/* rops_idx */			{
1131	  /* LWS_ROPS_check_upgrades */
1132	  /* LWS_ROPS_pt_init_destroy */		0x01,
1133	  /* LWS_ROPS_init_vhost */
1134	  /* LWS_ROPS_destroy_vhost */			0x00,
1135	  /* LWS_ROPS_service_flag_pending */
1136	  /* LWS_ROPS_handle_POLLIN */			0x02,
1137	  /* LWS_ROPS_handle_POLLOUT */
1138	  /* LWS_ROPS_perform_user_POLLOUT */		0x30,
1139	  /* LWS_ROPS_callback_on_writable */
1140	  /* LWS_ROPS_tx_credit */			0x00,
1141	  /* LWS_ROPS_write_role_protocol */
1142	  /* LWS_ROPS_encapsulation_parent */		0x40,
1143	  /* LWS_ROPS_alpn_negotiated */
1144	  /* LWS_ROPS_close_via_role_protocol */	0x50,
1145	  /* LWS_ROPS_close_role */
1146	  /* LWS_ROPS_close_kill_connection */		0x06,
1147	  /* LWS_ROPS_destroy_role */
1148#if defined(LWS_WITH_SERVER)
1149	  /* LWS_ROPS_adoption_bind */			0x78,
1150#else
1151	  /* LWS_ROPS_adoption_bind */			0x70,
1152#endif
1153	  /* LWS_ROPS_client_bind */
1154#if defined(LWS_WITH_CLIENT)
1155#if defined(LWS_WITH_SERVER)
1156	  /* LWS_ROPS_issue_keepalive */		0x90,
1157#else
1158	  /* LWS_ROPS_issue_keepalive */		0x80,
1159#endif
1160#else
1161	  /* LWS_ROPS_issue_keepalive */		0x00,
1162#endif
1163					},
1164	/* adoption_cb clnt, srv */	{ LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED,
1165					  LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED },
1166	/* rx_cb clnt, srv */		{ LWS_CALLBACK_RECEIVE_CLIENT_HTTP,
1167					  0 /* may be POST, etc */ },
1168	/* writeable cb clnt, srv */	{ LWS_CALLBACK_CLIENT_HTTP_WRITEABLE,
1169					  LWS_CALLBACK_HTTP_WRITEABLE },
1170	/* close cb clnt, srv */	{ LWS_CALLBACK_CLOSED_CLIENT_HTTP,
1171					  LWS_CALLBACK_CLOSED_HTTP },
1172	/* protocol_bind cb c, srv */	{ LWS_CALLBACK_CLIENT_HTTP_BIND_PROTOCOL,
1173					  LWS_CALLBACK_HTTP_BIND_PROTOCOL },
1174	/* protocol_unbind cb c, srv */	{ LWS_CALLBACK_CLIENT_HTTP_DROP_PROTOCOL,
1175					  LWS_CALLBACK_HTTP_DROP_PROTOCOL },
1176	/* file_handle */		0,
1177};
1178