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