2 * libwebsockets - small server side websockets and web server implementation
4 * Copyright (C) 2010-2018 Andy Green <andy@warmcat.com>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation:
9 * version 2.1 of the License.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22 #include <core/private.h>
24 #define LWS_CPYAPP(ptr, str) { strcpy(ptr, str); ptr += strlen(str); }
27 * client-parser.c: lws_ws_client_rx_sm() needs to be roughly kept in
28 * sync with changes here, esp related to ext draining
32 lws_ws_rx_sm(struct lws *wsi, char already_processed, unsigned char c)
34 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
35 int callback_action = LWS_CALLBACK_RECEIVE;
36 struct lws_ext_pm_deflate_rx_ebufs pmdrx;
37 unsigned short close_code;
41 #if !defined(LWS_WITHOUT_EXTENSIONS)
42 int rx_draining_ext = 0;
46 pmdrx.eb_in.token = NULL;
48 pmdrx.eb_out.token = NULL;
51 if (wsi->socket_is_permanently_unusable)
54 switch (wsi->lws_rx_parse_state) {
56 #if !defined(LWS_WITHOUT_EXTENSIONS)
57 if (wsi->ws->rx_draining_ext) {
58 pmdrx.eb_in.token = NULL;
60 pmdrx.eb_out.token = NULL;
62 lws_remove_wsi_from_draining_ext_list(wsi);
64 lwsl_debug("%s: doing draining flow\n", __func__);
69 switch (wsi->ws->ietf_spec_revision) {
72 * no prepended frame key any more
74 wsi->ws->all_zero_nonce = 1;
78 lwsl_warn("lws_ws_rx_sm: unknown spec version %d\n",
79 wsi->ws->ietf_spec_revision);
83 case LWS_RXPS_04_mask_1:
86 wsi->ws->all_zero_nonce = 0;
87 wsi->lws_rx_parse_state = LWS_RXPS_04_mask_2;
89 case LWS_RXPS_04_mask_2:
92 wsi->ws->all_zero_nonce = 0;
93 wsi->lws_rx_parse_state = LWS_RXPS_04_mask_3;
95 case LWS_RXPS_04_mask_3:
98 wsi->ws->all_zero_nonce = 0;
101 * start from the zero'th byte in the XOR key buffer since
102 * this is the start of a frame with a new key
105 wsi->ws->mask_idx = 0;
107 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_1;
111 * 04 logical framing from the spec (all this is masked when incoming
112 * and has to be unmasked)
114 * We ignore the possibility of extension data because we don't
115 * negotiate any extensions at the moment.
118 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
119 * +-+-+-+-+-------+-+-------------+-------------------------------+
120 * |F|R|R|R| opcode|R| Payload len | Extended payload length |
121 * |I|S|S|S| (4) |S| (7) | (16/63) |
122 * |N|V|V|V| |V| | (if payload len==126/127) |
124 * +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
125 * | Extended payload length continued, if payload len == 127 |
126 * + - - - - - - - - - - - - - - - +-------------------------------+
127 * | | Extension data |
128 * +-------------------------------+ - - - - - - - - - - - - - - - +
130 * +---------------------------------------------------------------+
131 * : Application data :
132 * +---------------------------------------------------------------+
134 * We pass payload through to userland as soon as we get it, ignoring
135 * FIN. It's up to userland to buffer it up if it wants to see a
136 * whole unfragmented block of the original size (which may be up to
140 case LWS_RXPS_04_FRAME_HDR_1:
143 wsi->ws->opcode = c & 0xf;
144 wsi->ws->rsv = c & 0x70;
145 wsi->ws->final = !!((c >> 7) & 1);
146 wsi->ws->defeat_check_utf8 = 0;
148 if (((wsi->ws->opcode) & 8) && !wsi->ws->final) {
149 lws_close_reason(wsi, LWS_CLOSE_STATUS_PROTOCOL_ERR,
150 (uint8_t *)"frag ctl", 8);
154 switch (wsi->ws->opcode) {
155 case LWSWSOPC_TEXT_FRAME:
156 wsi->ws->check_utf8 = lws_check_opt(
157 wsi->context->options,
158 LWS_SERVER_OPTION_VALIDATE_UTF8);
160 case LWSWSOPC_BINARY_FRAME:
161 if (wsi->ws->opcode == LWSWSOPC_BINARY_FRAME)
162 wsi->ws->check_utf8 = 0;
163 if (wsi->ws->continuation_possible) {
164 lws_close_reason(wsi,
165 LWS_CLOSE_STATUS_PROTOCOL_ERR,
166 (uint8_t *)"bad cont", 8);
169 wsi->ws->rsv_first_msg = (c & 0x70);
170 #if !defined(LWS_WITHOUT_EXTENSIONS)
172 * set the expectation that we will have to
173 * fake up the zlib trailer to the inflator for this
176 wsi->ws->pmd_trailer_application = !!(c & 0x40);
178 wsi->ws->frame_is_binary =
179 wsi->ws->opcode == LWSWSOPC_BINARY_FRAME;
180 wsi->ws->first_fragment = 1;
181 wsi->ws->continuation_possible = !wsi->ws->final;
183 case LWSWSOPC_CONTINUATION:
184 if (!wsi->ws->continuation_possible) {
185 lws_close_reason(wsi,
186 LWS_CLOSE_STATUS_PROTOCOL_ERR,
187 (uint8_t *)"bad cont", 8);
192 wsi->ws->check_utf8 = 0;
205 lws_close_reason(wsi, LWS_CLOSE_STATUS_PROTOCOL_ERR,
206 (uint8_t *)"bad opc", 7);
207 lwsl_info("illegal opcode\n");
211 if (wsi->ws->owed_a_fin &&
212 (wsi->ws->opcode == LWSWSOPC_TEXT_FRAME ||
213 wsi->ws->opcode == LWSWSOPC_BINARY_FRAME)) {
214 lwsl_info("hey you owed us a FIN\n");
215 lws_close_reason(wsi, LWS_CLOSE_STATUS_PROTOCOL_ERR,
216 (uint8_t *)"bad fin", 7);
219 if ((!(wsi->ws->opcode & 8)) && wsi->ws->final) {
220 wsi->ws->continuation_possible = 0;
221 wsi->ws->owed_a_fin = 0;
225 wsi->ws->owed_a_fin = 1;
227 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;
230 #if !defined(LWS_WITHOUT_EXTENSIONS)
231 !wsi->ws->count_act_ext ||
233 (wsi->ws->rsv & ~0x40))) {
234 lws_close_reason(wsi, LWS_CLOSE_STATUS_PROTOCOL_ERR,
235 (uint8_t *)"rsv bits", 8);
240 case LWS_RXPS_04_FRAME_HDR_LEN:
242 wsi->ws->this_frame_masked = !!(c & 0x80);
246 /* control frames are not allowed to have big lengths */
247 if (wsi->ws->opcode & 8)
248 goto illegal_ctl_length;
250 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;
253 /* control frames are not allowed to have big lengths */
254 if (wsi->ws->opcode & 8)
255 goto illegal_ctl_length;
257 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;
260 wsi->ws->rx_packet_length = c & 0x7f;
263 if (wsi->ws->this_frame_masked)
264 wsi->lws_rx_parse_state =
265 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
267 if (wsi->ws->rx_packet_length) {
268 wsi->lws_rx_parse_state =
269 LWS_RXPS_WS_FRAME_PAYLOAD;
271 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
278 case LWS_RXPS_04_FRAME_HDR_LEN16_2:
279 wsi->ws->rx_packet_length = c << 8;
280 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1;
283 case LWS_RXPS_04_FRAME_HDR_LEN16_1:
284 wsi->ws->rx_packet_length |= c;
285 if (wsi->ws->this_frame_masked)
286 wsi->lws_rx_parse_state =
287 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
289 wsi->lws_rx_parse_state =
290 LWS_RXPS_WS_FRAME_PAYLOAD;
294 case LWS_RXPS_04_FRAME_HDR_LEN64_8:
296 lwsl_warn("b63 of length must be zero\n");
297 /* kill the connection */
301 wsi->ws->rx_packet_length = ((size_t)c) << 56;
303 wsi->ws->rx_packet_length = 0;
305 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;
308 case LWS_RXPS_04_FRAME_HDR_LEN64_7:
310 wsi->ws->rx_packet_length |= ((size_t)c) << 48;
312 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;
315 case LWS_RXPS_04_FRAME_HDR_LEN64_6:
317 wsi->ws->rx_packet_length |= ((size_t)c) << 40;
319 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;
322 case LWS_RXPS_04_FRAME_HDR_LEN64_5:
324 wsi->ws->rx_packet_length |= ((size_t)c) << 32;
326 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;
329 case LWS_RXPS_04_FRAME_HDR_LEN64_4:
330 wsi->ws->rx_packet_length |= ((size_t)c) << 24;
331 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3;
334 case LWS_RXPS_04_FRAME_HDR_LEN64_3:
335 wsi->ws->rx_packet_length |= ((size_t)c) << 16;
336 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2;
339 case LWS_RXPS_04_FRAME_HDR_LEN64_2:
340 wsi->ws->rx_packet_length |= ((size_t)c) << 8;
341 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1;
344 case LWS_RXPS_04_FRAME_HDR_LEN64_1:
345 wsi->ws->rx_packet_length |= ((size_t)c);
346 if (wsi->ws->this_frame_masked)
347 wsi->lws_rx_parse_state =
348 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
350 wsi->lws_rx_parse_state = LWS_RXPS_WS_FRAME_PAYLOAD;
353 case LWS_RXPS_07_COLLECT_FRAME_KEY_1:
354 wsi->ws->mask[0] = c;
356 wsi->ws->all_zero_nonce = 0;
357 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_2;
360 case LWS_RXPS_07_COLLECT_FRAME_KEY_2:
361 wsi->ws->mask[1] = c;
363 wsi->ws->all_zero_nonce = 0;
364 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_3;
367 case LWS_RXPS_07_COLLECT_FRAME_KEY_3:
368 wsi->ws->mask[2] = c;
370 wsi->ws->all_zero_nonce = 0;
371 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_4;
374 case LWS_RXPS_07_COLLECT_FRAME_KEY_4:
375 wsi->ws->mask[3] = c;
377 wsi->ws->all_zero_nonce = 0;
378 wsi->lws_rx_parse_state = LWS_RXPS_WS_FRAME_PAYLOAD;
379 wsi->ws->mask_idx = 0;
380 if (wsi->ws->rx_packet_length == 0) {
381 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
387 case LWS_RXPS_WS_FRAME_PAYLOAD:
388 assert(wsi->ws->rx_ubuf);
390 if (wsi->ws->rx_ubuf_head + LWS_PRE >= wsi->ws->rx_ubuf_alloc) {
391 lwsl_err("Attempted overflow \n");
394 if (!(already_processed & ALREADY_PROCESSED_IGNORE_CHAR)) {
395 if (wsi->ws->all_zero_nonce)
396 wsi->ws->rx_ubuf[LWS_PRE +
397 (wsi->ws->rx_ubuf_head++)] = c;
399 wsi->ws->rx_ubuf[LWS_PRE +
400 (wsi->ws->rx_ubuf_head++)] =
401 c ^ wsi->ws->mask[(wsi->ws->mask_idx++) & 3];
403 --wsi->ws->rx_packet_length;
406 if (!wsi->ws->rx_packet_length) {
407 lwsl_debug("%s: ws fragment length exhausted\n",
409 /* spill because we have the whole frame */
410 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
413 #if !defined(LWS_WITHOUT_EXTENSIONS)
414 if (wsi->ws->rx_draining_ext) {
415 lwsl_debug("%s: UNTIL_EXHAUSTED draining\n", __func__);
416 goto drain_extension;
420 * if there's no protocol max frame size given, we are
421 * supposed to default to context->pt_serv_buf_size
423 if (!wsi->protocol->rx_buffer_size &&
424 wsi->ws->rx_ubuf_head != wsi->context->pt_serv_buf_size)
427 if (wsi->protocol->rx_buffer_size &&
428 wsi->ws->rx_ubuf_head != wsi->protocol->rx_buffer_size)
431 /* spill because we filled our rx buffer */
434 * is this frame a control packet we should take care of at this
435 * layer? If so service it and hide it from the user callback
438 lwsl_parser("spill on %s\n", wsi->protocol->name);
440 switch (wsi->ws->opcode) {
443 if (wsi->ws->peer_has_sent_close)
446 wsi->ws->peer_has_sent_close = 1;
448 pp = &wsi->ws->rx_ubuf[LWS_PRE];
449 if (lws_check_opt(wsi->context->options,
450 LWS_SERVER_OPTION_VALIDATE_UTF8) &&
451 wsi->ws->rx_ubuf_head > 2 &&
452 lws_check_utf8(&wsi->ws->utf8, pp + 2,
453 wsi->ws->rx_ubuf_head - 2))
456 /* is this an acknowledgment of our close? */
457 if (lwsi_state(wsi) == LRS_AWAITING_CLOSE_ACK) {
459 * fine he has told us he is closing too, let's
462 lwsl_parser("seen client close ack\n");
465 if (lwsi_state(wsi) == LRS_RETURNED_CLOSE)
466 /* if he sends us 2 CLOSE, kill him */
469 if (lws_partial_buffered(wsi)) {
471 * if we're in the middle of something,
472 * we can't do a normal close response and
473 * have to just close our end.
475 wsi->socket_is_permanently_unusable = 1;
476 lwsl_parser("Closing on peer close "
477 "due to pending tx\n");
481 if (wsi->ws->rx_ubuf_head >= 2) {
482 close_code = (pp[0] << 8) | pp[1];
483 if (close_code < 1000 ||
484 close_code == 1004 ||
485 close_code == 1005 ||
486 close_code == 1006 ||
487 close_code == 1012 ||
488 close_code == 1013 ||
489 close_code == 1014 ||
490 close_code == 1015 ||
491 (close_code >= 1016 && close_code < 3000)
493 pp[0] = (LWS_CLOSE_STATUS_PROTOCOL_ERR >> 8) & 0xff;
494 pp[1] = LWS_CLOSE_STATUS_PROTOCOL_ERR & 0xff;
498 if (user_callback_handle_rxflow(
499 wsi->protocol->callback, wsi,
500 LWS_CALLBACK_WS_PEER_INITIATED_CLOSE,
502 &wsi->ws->rx_ubuf[LWS_PRE],
503 wsi->ws->rx_ubuf_head))
506 lwsl_parser("server sees client close packet\n");
507 lwsi_set_state(wsi, LRS_RETURNED_CLOSE);
508 /* deal with the close packet contents as a PONG */
509 wsi->ws->payload_is_close = 1;
510 goto process_as_ping;
513 lwsl_info("received %d byte ping, sending pong\n",
514 wsi->ws->rx_ubuf_head);
516 if (wsi->ws->ping_pending_flag) {
518 * there is already a pending ping payload
519 * we should just log and drop
521 lwsl_parser("DROP PING since one pending\n");
525 /* control packets can only be < 128 bytes long */
526 if (wsi->ws->rx_ubuf_head > 128 - 3) {
527 lwsl_parser("DROP PING payload too large\n");
531 /* stash the pong payload */
532 memcpy(wsi->ws->ping_payload_buf + LWS_PRE,
533 &wsi->ws->rx_ubuf[LWS_PRE],
534 wsi->ws->rx_ubuf_head);
536 wsi->ws->ping_payload_len = wsi->ws->rx_ubuf_head;
537 wsi->ws->ping_pending_flag = 1;
539 /* get it sent as soon as possible */
540 lws_callback_on_writable(wsi);
542 wsi->ws->rx_ubuf_head = 0;
546 lwsl_info("received pong\n");
547 lwsl_hexdump(&wsi->ws->rx_ubuf[LWS_PRE],
548 wsi->ws->rx_ubuf_head);
550 if (wsi->ws->await_pong) {
551 lwsl_info("received expected PONG on wsi %p\n",
553 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
554 wsi->ws->await_pong = 0;
557 * prepare to send the ping again if nothing
558 * sent to countermand it
561 __lws_sul_insert(&pt->pt_sul_owner,
563 (lws_usec_t)wsi->context->ws_ping_pong_interval *
568 callback_action = LWS_CALLBACK_RECEIVE_PONG;
571 case LWSWSOPC_TEXT_FRAME:
572 case LWSWSOPC_BINARY_FRAME:
573 case LWSWSOPC_CONTINUATION:
577 lwsl_parser("unknown opc %x\n", wsi->ws->opcode);
583 * No it's real payload, pass it up to the user callback.
585 * We have been statefully collecting it in the
586 * LWS_RXPS_WS_FRAME_PAYLOAD clause above.
588 * It's nicely buffered with the pre-padding taken care of
589 * so it can be sent straight out again using lws_write.
591 * However, now we have a chunk of it, we want to deal with it
592 * all here. Since this may be input to permessage-deflate and
593 * there are block limits on that for input and output, we may
597 pmdrx.eb_in.token = &wsi->ws->rx_ubuf[LWS_PRE];
598 pmdrx.eb_in.len = wsi->ws->rx_ubuf_head;
600 /* for the non-pm-deflate case */
602 pmdrx.eb_out = pmdrx.eb_in;
604 if (wsi->ws->opcode == LWSWSOPC_PONG && !pmdrx.eb_in.len)
606 #if !defined(LWS_WITHOUT_EXTENSIONS)
612 // lwsl_notice("%s: pmdrx.eb_in.len: %d\n", __func__,
613 // (int)pmdrx.eb_in.len);
615 if (lwsi_state(wsi) == LRS_RETURNED_CLOSE ||
616 lwsi_state(wsi) == LRS_AWAITING_CLOSE_ACK)
619 n = PMDR_DID_NOTHING;
621 #if !defined(LWS_WITHOUT_EXTENSIONS)
622 lin = pmdrx.eb_in.len;
624 // lwsl_hexdump_notice(ebuf.token, ebuf.len);
625 lwsl_ext("%s: +++ passing %d %p to ext\n", __func__,
626 pmdrx.eb_in.len, pmdrx.eb_in.token);
628 n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_RX, &pmdrx, 0);
629 lwsl_debug("%s: ext says %d / ebuf.len %d\n", __func__,
630 n, pmdrx.eb_out.len);
631 if (wsi->ws->rx_draining_ext)
632 already_processed &= ~ALREADY_PROCESSED_NO_CB;
636 * ebuf may be pointing somewhere completely different
637 * now, it's the output
639 #if !defined(LWS_WITHOUT_EXTENSIONS)
642 * we may rely on this to get RX, just drop
645 wsi->socket_is_permanently_unusable = 1;
648 if (n == PMDR_DID_NOTHING)
651 lwsl_debug("%s: post ext ret %d, ebuf in %d / out %d\n",
652 __func__, n, pmdrx.eb_in.len,
655 #if !defined(LWS_WITHOUT_EXTENSIONS)
656 if (rx_draining_ext && !pmdrx.eb_out.len) {
657 lwsl_debug(" --- ending drain on 0 read\n");
661 if (n == PMDR_HAS_PENDING)
663 * extension had more...
664 * main loop will come back
666 lws_add_wsi_to_draining_ext_list(wsi);
668 lws_remove_wsi_from_draining_ext_list(wsi);
670 rx_draining_ext = wsi->ws->rx_draining_ext;
673 if (pmdrx.eb_out.len &&
674 wsi->ws->check_utf8 && !wsi->ws->defeat_check_utf8) {
675 if (lws_check_utf8(&wsi->ws->utf8,
678 lws_close_reason(wsi,
679 LWS_CLOSE_STATUS_INVALID_PAYLOAD,
680 (uint8_t *)"bad utf8", 8);
684 /* we are ending partway through utf-8 character? */
685 if (!wsi->ws->rx_packet_length &&
686 wsi->ws->final && wsi->ws->utf8
687 #if !defined(LWS_WITHOUT_EXTENSIONS)
688 /* if ext not negotiated, going to be UNKNOWN */
689 && (n == PMDR_EMPTY_FINAL || n == PMDR_UNKNOWN)
692 lwsl_info("FINAL utf8 error\n");
693 lws_close_reason(wsi,
694 LWS_CLOSE_STATUS_INVALID_PAYLOAD,
695 (uint8_t *)"partial utf8", 12);
697 lwsl_notice("utf8 error\n");
698 lwsl_hexdump_notice(pmdrx.eb_out.token,
705 /* if pmd not enabled, in == out */
707 if (n == PMDR_DID_NOTHING
708 #if !defined(LWS_WITHOUT_EXTENSIONS)
713 pmdrx.eb_in.len -= pmdrx.eb_out.len;
715 if (!wsi->wsistate_pre_close &&
716 (pmdrx.eb_out.len >= 0 ||
717 callback_action == LWS_CALLBACK_RECEIVE_PONG ||
718 n == PMDR_EMPTY_FINAL)) {
719 if (pmdrx.eb_out.len)
720 pmdrx.eb_out.token[pmdrx.eb_out.len] = '\0';
722 if (wsi->protocol->callback &&
723 !(already_processed & ALREADY_PROCESSED_NO_CB)) {
724 if (callback_action ==
725 LWS_CALLBACK_RECEIVE_PONG)
726 lwsl_info("Doing pong callback\n");
728 ret = user_callback_handle_rxflow(
729 wsi->protocol->callback, wsi,
730 (enum lws_callback_reasons)
736 wsi->ws->first_fragment = 0;
739 #if !defined(LWS_WITHOUT_EXTENSIONS)
744 } while (pmdrx.eb_in.len
745 #if !defined(LWS_WITHOUT_EXTENSIONS)
751 wsi->ws->rx_ubuf_head = 0;
759 lwsl_warn("Control frame with xtended length is illegal\n");
760 /* kill the connection */
766 lws_remaining_packet_payload(struct lws *wsi)
768 return wsi->ws->rx_packet_length;
771 LWS_VISIBLE int lws_frame_is_binary(struct lws *wsi)
773 return wsi->ws->frame_is_binary;
777 lws_add_wsi_to_draining_ext_list(struct lws *wsi)
779 #if !defined(LWS_WITHOUT_EXTENSIONS)
780 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
782 if (wsi->ws->rx_draining_ext)
785 lwsl_debug("%s: RX EXT DRAINING: Adding to list\n", __func__);
787 wsi->ws->rx_draining_ext = 1;
788 wsi->ws->rx_draining_ext_list = pt->ws.rx_draining_ext_list;
789 pt->ws.rx_draining_ext_list = wsi;
794 lws_remove_wsi_from_draining_ext_list(struct lws *wsi)
796 #if !defined(LWS_WITHOUT_EXTENSIONS)
797 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
798 struct lws **w = &pt->ws.rx_draining_ext_list;
800 if (!wsi->ws->rx_draining_ext)
803 lwsl_debug("%s: RX EXT DRAINING: Removing from list\n", __func__);
805 wsi->ws->rx_draining_ext = 0;
807 /* remove us from context draining ext list */
810 /* if us, point it instead to who we were pointing to */
811 *w = wsi->ws->rx_draining_ext_list;
814 w = &((*w)->ws->rx_draining_ext_list);
816 wsi->ws->rx_draining_ext_list = NULL;
821 lws_0405_frame_mask_generate(struct lws *wsi)
824 /* fetch the per-frame nonce */
826 n = lws_get_random(lws_get_context(wsi), wsi->ws->mask, 4);
828 lwsl_parser("Unable to read from random device %s %d\n",
829 SYSTEM_RANDOM_FILEPATH, n);
833 /* start masking from first byte of masking key buffer */
834 wsi->ws->mask_idx = 0;
840 lws_sul_wsping_cb(lws_sorted_usec_list_t *sul)
842 struct lws *wsi = lws_container_of(sul, struct lws, sul_ping);
845 * The sul_ping timer came up... either it's time to send a PING
846 * (!wsi->ws->send_check_ping), or we didn't get the PONG in time
847 * (wsi->ws->send_check_ping)
850 if (!wsi->ws->send_check_ping) {
851 lwsl_info("%s: req pp on wsi %p\n", __func__, wsi);
853 wsi->ws->send_check_ping = 1;
854 lws_set_timeout(wsi, PENDING_TIMEOUT_WS_PONG_CHECK_SEND_PING,
855 wsi->context->timeout_secs);
856 lws_callback_on_writable(wsi);
861 if (wsi->ws->await_pong) {
862 /* it didn't return the PONG in time */
864 lwsl_info("%s: wsi %p: failed to send PONG\n", __func__, wsi);
865 __lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS,
871 lws_server_init_wsi_for_ws(struct lws *wsi)
873 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
876 lwsi_set_state(wsi, LRS_ESTABLISHED);
878 if (wsi->context->ws_ping_pong_interval && !wsi->http2_substream ) {
879 wsi->sul_ping.cb = lws_sul_wsping_cb;
880 __lws_sul_insert(&pt->pt_sul_owner, &wsi->sul_ping,
881 (lws_usec_t)wsi->context->ws_ping_pong_interval *
886 * create the frame buffer for this connection according to the
887 * size mentioned in the protocol definition. If 0 there, use
888 * a big default for compatibility
891 n = (int)wsi->protocol->rx_buffer_size;
893 n = wsi->context->pt_serv_buf_size;
895 wsi->ws->rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */, "rx_ubuf");
896 if (!wsi->ws->rx_ubuf) {
897 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
900 wsi->ws->rx_ubuf_alloc = n;
901 lwsl_debug("Allocating RX buffer %d\n", n);
903 #if !defined(LWS_WITH_ESP32)
904 if (!wsi->h2_stream_carries_ws)
905 if (setsockopt(wsi->desc.sockfd, SOL_SOCKET, SO_SNDBUF,
906 (const char *)&n, sizeof n)) {
907 lwsl_warn("Failed to set SNDBUF to %d", n);
912 /* notify user code that we're ready to roll */
914 if (wsi->protocol->callback)
915 if (wsi->protocol->callback(wsi, LWS_CALLBACK_ESTABLISHED,
922 wsi->h2_stream_carries_ws))
925 lwsl_debug("ws established\n");
933 lws_is_final_fragment(struct lws *wsi)
935 #if !defined(LWS_WITHOUT_EXTENSIONS)
936 lwsl_debug("%s: final %d, rx pk length %ld, draining %ld\n", __func__,
937 wsi->ws->final, (long)wsi->ws->rx_packet_length,
938 (long)wsi->ws->rx_draining_ext);
939 return wsi->ws->final && !wsi->ws->rx_packet_length &&
940 !wsi->ws->rx_draining_ext;
942 return wsi->ws->final && !wsi->ws->rx_packet_length;
947 lws_is_first_fragment(struct lws *wsi)
949 return wsi->ws->first_fragment;
952 LWS_VISIBLE unsigned char
953 lws_get_reserved_bits(struct lws *wsi)
958 LWS_VISIBLE LWS_EXTERN int
959 lws_get_close_length(struct lws *wsi)
961 return wsi->ws->close_in_ping_buffer_len;
964 LWS_VISIBLE LWS_EXTERN unsigned char *
965 lws_get_close_payload(struct lws *wsi)
967 return &wsi->ws->ping_payload_buf[LWS_PRE];
970 LWS_VISIBLE LWS_EXTERN void
971 lws_close_reason(struct lws *wsi, enum lws_close_status status,
972 unsigned char *buf, size_t len)
974 unsigned char *p, *start;
975 int budget = sizeof(wsi->ws->ping_payload_buf) - LWS_PRE;
977 assert(lwsi_role_ws(wsi));
979 start = p = &wsi->ws->ping_payload_buf[LWS_PRE];
981 *p++ = (((int)status) >> 8) & 0xff;
982 *p++ = ((int)status) & 0xff;
985 while (len-- && p < start + budget)
988 wsi->ws->close_in_ping_buffer_len = lws_ptr_diff(p, start);
992 lws_is_ws_with_ext(struct lws *wsi)
994 #if defined(LWS_WITHOUT_EXTENSIONS)
997 return lwsi_role_ws(wsi) && !!wsi->ws->count_act_ext;
1002 rops_handle_POLLIN_ws(struct lws_context_per_thread *pt, struct lws *wsi,
1003 struct lws_pollfd *pollfd)
1005 unsigned int pending = 0;
1006 struct lws_tokens ebuf;
1009 #if defined(LWS_WITH_HTTP2)
1014 lwsl_err("ws role wsi with no ws\n");
1015 return LWS_HPI_RET_PLEASE_CLOSE_ME;
1018 // lwsl_notice("%s: %s\n", __func__, wsi->protocol->name);
1020 //lwsl_info("%s: wsistate 0x%x, pollout %d\n", __func__,
1021 // wsi->wsistate, pollfd->revents & LWS_POLLOUT);
1024 * something went wrong with parsing the handshake, and
1025 * we ended up back in the event loop without completing it
1027 if (lwsi_state(wsi) == LRS_PRE_WS_SERVING_ACCEPT) {
1028 wsi->socket_is_permanently_unusable = 1;
1029 return LWS_HPI_RET_PLEASE_CLOSE_ME;
1035 if (lwsi_state(wsi) == LRS_WAITING_CONNECT) {
1036 #if !defined(LWS_NO_CLIENT)
1037 if ((pollfd->revents & LWS_POLLOUT) &&
1038 lws_handle_POLLOUT_event(wsi, pollfd)) {
1039 lwsl_debug("POLLOUT event closed it\n");
1040 return LWS_HPI_RET_PLEASE_CLOSE_ME;
1043 n = lws_client_socket_service(wsi, pollfd, NULL);
1045 return LWS_HPI_RET_WSI_ALREADY_DIED;
1047 return LWS_HPI_RET_HANDLED;
1050 /* 1: something requested a callback when it was OK to write */
1052 if ((pollfd->revents & LWS_POLLOUT) &&
1053 lwsi_state_can_handle_POLLOUT(wsi) &&
1054 lws_handle_POLLOUT_event(wsi, pollfd)) {
1055 if (lwsi_state(wsi) == LRS_RETURNED_CLOSE)
1056 lwsi_set_state(wsi, LRS_FLUSHING_BEFORE_CLOSE);
1058 return LWS_HPI_RET_PLEASE_CLOSE_ME;
1061 if (lwsi_state(wsi) == LRS_RETURNED_CLOSE ||
1062 lwsi_state(wsi) == LRS_WAITING_TO_SEND_CLOSE) {
1064 * we stopped caring about anything except control
1065 * packets. Force flow control off, defeat tx
1068 lws_rx_flow_control(wsi, 1);
1069 #if !defined(LWS_WITHOUT_EXTENSIONS)
1071 wsi->ws->tx_draining_ext = 0;
1074 #if !defined(LWS_WITHOUT_EXTENSIONS)
1075 if (wsi->ws->tx_draining_ext) {
1076 lws_handle_POLLOUT_event(wsi, pollfd);
1077 //lwsl_notice("%s: tx drain\n", __func__);
1079 * We cannot deal with new RX until the TX ext path has
1080 * been drained. It's because new rx will, eg, crap on
1081 * the wsi rx buf that may be needed to retain state.
1083 * TX ext drain path MUST go through event loop to avoid
1086 lws_callback_on_writable(wsi);
1087 return LWS_HPI_RET_HANDLED;
1090 if ((pollfd->revents & LWS_POLLIN) && lws_is_flowcontrolled(wsi)) {
1091 /* We cannot deal with any kind of new RX because we are
1092 * RX-flowcontrolled.
1094 lwsl_info("%s: flowcontrolled, ignoring rx\n", __func__);
1096 if (__lws_change_pollfd(wsi, LWS_POLLIN, 0))
1099 return LWS_HPI_RET_HANDLED;
1102 if (lws_is_flowcontrolled(wsi))
1103 return LWS_HPI_RET_HANDLED;
1105 #if defined(LWS_WITH_HTTP2)
1106 if (wsi->http2_substream || wsi->upgraded_to_http2) {
1107 wsi1 = lws_get_network_wsi(wsi);
1108 if (wsi1 && lws_has_buffered_out(wsi1))
1109 /* We cannot deal with any kind of new RX
1110 * because we are dealing with a partial send
1111 * (new RX may trigger new http_action() that
1112 * expect to be able to send)
1114 return LWS_HPI_RET_HANDLED;
1118 #if !defined(LWS_WITHOUT_EXTENSIONS)
1119 /* 2: RX Extension needs to be drained
1122 if (wsi->ws->rx_draining_ext) {
1124 lwsl_debug("%s: RX EXT DRAINING: Service\n", __func__);
1125 #ifndef LWS_NO_CLIENT
1126 if (lwsi_role_client(wsi)) {
1127 n = lws_ws_client_rx_sm(wsi, 0);
1130 return LWS_HPI_RET_PLEASE_CLOSE_ME;
1133 n = lws_ws_rx_sm(wsi, ALREADY_PROCESSED_IGNORE_CHAR, 0);
1135 return LWS_HPI_RET_HANDLED;
1138 if (wsi->ws->rx_draining_ext)
1140 * We have RX EXT content to drain, but can't do it
1141 * right now. That means we cannot do anything lower
1144 return LWS_HPI_RET_HANDLED;
1147 /* 3: buflist needs to be drained
1150 //lws_buflist_describe(&wsi->buflist, wsi);
1151 ebuf.len = (int)lws_buflist_next_segment_len(&wsi->buflist,
1154 lwsl_info("draining buflist (len %d)\n", ebuf.len);
1159 if (!(pollfd->revents & pollfd->events & LWS_POLLIN) && !wsi->http.ah)
1160 return LWS_HPI_RET_HANDLED;
1162 if (lws_is_flowcontrolled(wsi)) {
1163 lwsl_info("%s: %p should be rxflow (bm 0x%x)..\n",
1164 __func__, wsi, wsi->rxflow_bitmap);
1165 return LWS_HPI_RET_HANDLED;
1168 if (!(lwsi_role_client(wsi) &&
1169 (lwsi_state(wsi) != LRS_ESTABLISHED &&
1170 lwsi_state(wsi) != LRS_AWAITING_CLOSE_ACK &&
1171 lwsi_state(wsi) != LRS_H2_WAITING_TO_SEND_HEADERS))) {
1173 * In case we are going to react to this rx by scheduling
1174 * writes, we need to restrict the amount of rx to the size
1175 * the protocol reported for rx buffer.
1177 * Otherwise we get a situation we have to absorb possibly a
1178 * lot of reads before we get a chance to drain them by writing
1179 * them, eg, with echo type tests in autobahn.
1183 ebuf.token = pt->serv_buf;
1184 if (lwsi_role_ws(wsi))
1185 ebuf.len = wsi->ws->rx_ubuf_alloc;
1187 ebuf.len = wsi->context->pt_serv_buf_size;
1189 if ((unsigned int)ebuf.len > wsi->context->pt_serv_buf_size)
1190 ebuf.len = wsi->context->pt_serv_buf_size;
1192 if ((int)pending > ebuf.len)
1195 ebuf.len = lws_ssl_capable_read(wsi, ebuf.token,
1196 pending ? (int)pending :
1200 lwsl_info("%s: zero length read\n",
1202 return LWS_HPI_RET_PLEASE_CLOSE_ME;
1203 case LWS_SSL_CAPABLE_MORE_SERVICE:
1204 lwsl_info("SSL Capable more service\n");
1205 return LWS_HPI_RET_HANDLED;
1206 case LWS_SSL_CAPABLE_ERROR:
1207 lwsl_info("%s: LWS_SSL_CAPABLE_ERROR\n",
1209 return LWS_HPI_RET_PLEASE_CLOSE_ME;
1213 * coverity thinks ssl_capable_read() may read over
1214 * 2GB. Dissuade it...
1216 ebuf.len &= 0x7fffffff;
1222 * give any active extensions a chance to munge the buffer
1223 * before parse. We pass in a pointer to an lws_tokens struct
1224 * prepared with the default buffer and content length that's in
1225 * there. Rather than rewrite the default buffer, extensions
1226 * that expect to grow the buffer can adapt .token to
1227 * point to their own per-connection buffer in the extension
1228 * user allocation. By default with no extensions or no
1229 * extension callback handling, just the normal input buffer is
1230 * used then so it is efficient.
1235 /* service incoming data */
1236 //lws_buflist_describe(&wsi->buflist, wsi);
1238 #if defined(LWS_ROLE_H2)
1239 if (lwsi_role_h2(wsi) && lwsi_state(wsi) != LRS_BODY &&
1240 lwsi_state(wsi) != LRS_DISCARD_BODY)
1241 n = lws_read_h2(wsi, ebuf.token,
1245 n = lws_read_h1(wsi, ebuf.token,
1251 return LWS_HPI_RET_WSI_ALREADY_DIED;
1253 //lws_buflist_describe(&wsi->buflist, wsi);
1254 //lwsl_notice("%s: consuming %d / %d\n", __func__, n, ebuf.len);
1255 if (lws_buflist_aware_consume(wsi, &ebuf, n, buffered))
1256 return LWS_HPI_RET_PLEASE_CLOSE_ME;
1264 #if !defined(LWS_NO_CLIENT)
1265 && !wsi->client_h2_alpn
1268 lwsl_info("%s: %p: detaching ah\n", __func__, wsi);
1269 lws_header_table_detach(wsi, 0);
1272 pending = lws_ssl_pending(wsi);
1274 if (lws_is_ws_with_ext(wsi))
1275 pending = pending > wsi->ws->rx_ubuf_alloc ?
1276 wsi->ws->rx_ubuf_alloc : pending;
1278 pending = pending > wsi->context->pt_serv_buf_size ?
1279 wsi->context->pt_serv_buf_size : pending;
1283 if (buffered && /* were draining, now nothing left */
1284 !lws_buflist_next_segment_len(&wsi->buflist, NULL)) {
1285 lwsl_info("%s: %p flow buf: drained\n", __func__, wsi);
1286 /* having drained the rxflow buffer, can rearm POLLIN */
1287 #ifdef LWS_NO_SERVER
1290 __lws_rx_flow_control(wsi);
1291 /* n ignored, needed for NO_SERVER case */
1295 return LWS_HPI_RET_HANDLED;
1299 int rops_handle_POLLOUT_ws(struct lws *wsi)
1301 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
1302 int write_type = LWS_WRITE_PONG;
1303 #if !defined(LWS_WITHOUT_EXTENSIONS)
1304 struct lws_ext_pm_deflate_rx_ebufs pmdrx;
1309 #if !defined(LWS_WITHOUT_EXTENSIONS)
1310 lwsl_debug("%s: %s: wsi->ws->tx_draining_ext %d\n", __func__,
1311 wsi->protocol->name, wsi->ws->tx_draining_ext);
1314 /* Priority 3: pending control packets (pong or close)
1316 * 3a: close notification packet requested from close api
1319 if (lwsi_state(wsi) == LRS_WAITING_TO_SEND_CLOSE) {
1320 lwsl_debug("sending close packet\n");
1321 lwsl_hexdump_debug(&wsi->ws->ping_payload_buf[LWS_PRE],
1322 wsi->ws->close_in_ping_buffer_len);
1323 wsi->waiting_to_send_close_frame = 0;
1324 n = lws_write(wsi, &wsi->ws->ping_payload_buf[LWS_PRE],
1325 wsi->ws->close_in_ping_buffer_len,
1328 if (wsi->close_needs_ack) {
1329 lwsi_set_state(wsi, LRS_AWAITING_CLOSE_ACK);
1330 lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_ACK,
1332 lwsl_debug("sent close, await ack\n");
1334 return LWS_HP_RET_BAIL_OK;
1336 wsi->close_needs_ack = 0;
1337 lwsi_set_state(wsi, LRS_RETURNED_CLOSE);
1340 return LWS_HP_RET_BAIL_DIE;
1343 /* else, the send failed and we should just hang up */
1345 if ((lwsi_role_ws(wsi) && wsi->ws->ping_pending_flag) ||
1346 (lwsi_state(wsi) == LRS_RETURNED_CLOSE &&
1347 wsi->ws->payload_is_close)) {
1349 if (wsi->ws->payload_is_close)
1350 write_type = LWS_WRITE_CLOSE;
1352 if (wsi->wsistate_pre_close) {
1353 /* we started close flow, forget pong */
1354 wsi->ws->ping_pending_flag = 0;
1355 return LWS_HP_RET_BAIL_OK;
1357 lwsl_info("issuing pong %d on wsi %p\n",
1358 wsi->ws->ping_payload_len, wsi);
1361 n = lws_write(wsi, &wsi->ws->ping_payload_buf[LWS_PRE],
1362 wsi->ws->ping_payload_len, write_type);
1364 return LWS_HP_RET_BAIL_DIE;
1366 /* well he is sent, mark him done */
1367 wsi->ws->ping_pending_flag = 0;
1368 if (wsi->ws->payload_is_close) {
1370 /* oh... a close frame was it... then we are done */
1371 return LWS_HP_RET_BAIL_DIE;
1374 /* otherwise for PING, leave POLLOUT active either way */
1375 return LWS_HP_RET_BAIL_OK;
1378 if (!wsi->socket_is_permanently_unusable &&
1379 wsi->ws->send_check_ping && wsi->context->ws_ping_pong_interval) {
1381 lwsl_info("%s: issuing ping on wsi %p: %s %s h2: %d\n", __func__, wsi,
1382 wsi->role_ops->name, wsi->protocol->name,
1383 wsi->http2_substream);
1384 wsi->ws->send_check_ping = 0;
1385 wsi->ws->await_pong = 1;
1386 n = lws_write(wsi, &wsi->ws->ping_payload_buf[LWS_PRE],
1389 return LWS_HP_RET_BAIL_DIE;
1391 /* give it a few seconds to respond with the PONG */
1393 __lws_sul_insert(&pt->pt_sul_owner, &wsi->sul_ping,
1394 (lws_usec_t)wsi->context->timeout_secs *
1397 return LWS_HP_RET_BAIL_OK;
1400 /* Priority 4: if we are closing, not allowed to send more data frags
1401 * which means user callback or tx ext flush banned now
1403 if (lwsi_state(wsi) == LRS_RETURNED_CLOSE)
1404 return LWS_HP_RET_USER_SERVICE;
1406 #if !defined(LWS_WITHOUT_EXTENSIONS)
1407 /* Priority 5: Tx path extension with more to send
1409 * These are handled as new fragments each time around
1410 * So while we must block new writeable callback to enforce
1411 * payload ordering, but since they are always complete
1412 * fragments control packets can interleave OK.
1414 if (wsi->ws->tx_draining_ext) {
1415 lwsl_ext("SERVICING TX EXT DRAINING\n");
1416 if (lws_write(wsi, NULL, 0, LWS_WRITE_CONTINUATION) < 0)
1417 return LWS_HP_RET_BAIL_DIE;
1418 /* leave POLLOUT active */
1419 return LWS_HP_RET_BAIL_OK;
1422 /* Priority 6: extensions
1424 if (!wsi->ws->extension_data_pending && !wsi->ws->tx_draining_ext) {
1425 lwsl_ext("%s: !wsi->ws->extension_data_pending\n", __func__);
1426 return LWS_HP_RET_USER_SERVICE;
1430 * Check in on the active extensions, see if they had pending stuff to
1431 * spill... they need to get the first look-in otherwise sequence will
1434 * coming here with a NULL, zero-length ebuf means just spill pending
1438 if (wsi->role_ops == &role_ops_raw_skt ||
1439 wsi->role_ops == &role_ops_raw_file)
1444 /* default to nobody has more to spill */
1447 pmdrx.eb_in.token = NULL;
1448 pmdrx.eb_in.len = 0;
1450 /* give every extension a chance to spill */
1452 m = lws_ext_cb_active(wsi, LWS_EXT_CB_PACKET_TX_PRESEND,
1455 lwsl_err("ext reports fatal error\n");
1456 return LWS_HP_RET_BAIL_DIE;
1460 * at least one extension told us he has more
1461 * to spill, so we will go around again after
1465 /* assuming they gave us something to send, send it */
1467 if (pmdrx.eb_in.len) {
1468 n = lws_issue_raw(wsi, (unsigned char *)pmdrx.eb_in.token,
1471 lwsl_info("closing from POLLOUT spill\n");
1472 return LWS_HP_RET_BAIL_DIE;
1475 * Keep amount spilled small to minimize chance of this
1477 if (n != pmdrx.eb_in.len) {
1478 lwsl_err("Unable to spill ext %d vs %d\n",
1479 pmdrx.eb_in.len, n);
1480 return LWS_HP_RET_BAIL_DIE;
1485 /* no extension has more to spill */
1491 * There's more to spill from an extension, but we just sent
1492 * something... did that leave the pipe choked?
1495 if (!lws_send_pipe_choked(wsi))
1496 /* no we could add more */
1499 lwsl_info("choked in POLLOUT service\n");
1502 * Yes, he's choked. Leave the POLLOUT masked on so we will
1503 * come back here when he is unchoked. Don't call the user
1504 * callback to enforce ordering of spilling, he'll get called
1505 * when we come back here and there's nothing more to spill.
1508 return LWS_HP_RET_BAIL_OK;
1511 wsi->ws->extension_data_pending = 0;
1514 return LWS_HP_RET_USER_SERVICE;
1518 rops_service_flag_pending_ws(struct lws_context *context, int tsi)
1520 #if !defined(LWS_WITHOUT_EXTENSIONS)
1521 struct lws_context_per_thread *pt = &context->pt[tsi];
1525 /* POLLIN faking (the pt lock is taken by the parent) */
1528 * 1) For all guys with already-available ext data to drain, if they are
1529 * not flowcontrolled, fake their POLLIN status
1531 wsi = pt->ws.rx_draining_ext_list;
1532 while (wsi && wsi->position_in_fds_table != LWS_NO_FDS_POS) {
1533 pt->fds[wsi->position_in_fds_table].revents |=
1534 pt->fds[wsi->position_in_fds_table].events & LWS_POLLIN;
1535 if (pt->fds[wsi->position_in_fds_table].revents & LWS_POLLIN)
1538 wsi = wsi->ws->rx_draining_ext_list;
1548 rops_close_via_role_protocol_ws(struct lws *wsi, enum lws_close_status reason)
1553 if (!wsi->ws->close_in_ping_buffer_len && /* already a reason */
1554 (reason == LWS_CLOSE_STATUS_NOSTATUS ||
1555 reason == LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY))
1558 lwsl_debug("%s: sending close indication...\n", __func__);
1560 /* if no prepared close reason, use 1000 and no aux data */
1562 if (!wsi->ws->close_in_ping_buffer_len) {
1563 wsi->ws->close_in_ping_buffer_len = 2;
1564 wsi->ws->ping_payload_buf[LWS_PRE] = (reason >> 8) & 0xff;
1565 wsi->ws->ping_payload_buf[LWS_PRE + 1] = reason & 0xff;
1568 wsi->waiting_to_send_close_frame = 1;
1569 wsi->close_needs_ack = 1;
1570 lwsi_set_state(wsi, LRS_WAITING_TO_SEND_CLOSE);
1571 __lws_set_timeout(wsi, PENDING_TIMEOUT_CLOSE_SEND, 5);
1573 lws_callback_on_writable(wsi);
1579 rops_close_role_ws(struct lws_context_per_thread *pt, struct lws *wsi)
1584 #if !defined(LWS_WITHOUT_EXTENSIONS)
1586 if (wsi->ws->rx_draining_ext) {
1587 struct lws **w = &pt->ws.rx_draining_ext_list;
1589 wsi->ws->rx_draining_ext = 0;
1590 /* remove us from context draining ext list */
1593 *w = wsi->ws->rx_draining_ext_list;
1596 w = &((*w)->ws->rx_draining_ext_list);
1598 wsi->ws->rx_draining_ext_list = NULL;
1601 if (wsi->ws->tx_draining_ext) {
1602 struct lws **w = &pt->ws.tx_draining_ext_list;
1603 lwsl_ext("%s: CLEARING tx_draining_ext\n", __func__);
1604 wsi->ws->tx_draining_ext = 0;
1605 /* remove us from context draining ext list */
1608 *w = wsi->ws->tx_draining_ext_list;
1611 w = &((*w)->ws->tx_draining_ext_list);
1613 wsi->ws->tx_draining_ext_list = NULL;
1616 lws_free_set_NULL(wsi->ws->rx_ubuf);
1618 wsi->ws->ping_payload_len = 0;
1619 wsi->ws->ping_pending_flag = 0;
1621 /* deallocate any active extension contexts */
1623 if (lws_ext_cb_active(wsi, LWS_EXT_CB_DESTROY, NULL, 0) < 0)
1624 lwsl_warn("extension destruction failed\n");
1630 rops_write_role_protocol_ws(struct lws *wsi, unsigned char *buf, size_t len,
1631 enum lws_write_protocol *wp)
1633 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
1634 #if !defined(LWS_WITHOUT_EXTENSIONS)
1635 enum lws_write_protocol wpt;
1637 struct lws_ext_pm_deflate_rx_ebufs pmdrx;
1638 int masked7 = lwsi_role_client(wsi);
1639 unsigned char is_masked_bit = 0;
1640 unsigned char *dropmask = NULL;
1641 size_t orig_len = len;
1644 // lwsl_err("%s: wp 0x%x len %d\n", __func__, *wp, (int)len);
1645 #if !defined(LWS_WITHOUT_EXTENSIONS)
1646 if (wsi->ws->tx_draining_ext) {
1647 /* remove us from the list */
1648 struct lws **w = &pt->ws.tx_draining_ext_list;
1650 lwsl_ext("%s: CLEARING tx_draining_ext\n", __func__);
1651 wsi->ws->tx_draining_ext = 0;
1652 /* remove us from context draining ext list */
1655 *w = wsi->ws->tx_draining_ext_list;
1658 w = &((*w)->ws->tx_draining_ext_list);
1660 wsi->ws->tx_draining_ext_list = NULL;
1663 *wp = (wsi->ws->tx_draining_stashed_wp & 0xc0) |
1664 LWS_WRITE_CONTINUATION;
1667 * When we are just flushing (len == 0), we can trust the
1668 * stashed wp info completely. Otherwise adjust it to the
1669 * FIN status of the incoming packet.
1672 if (!(wpt & LWS_WRITE_NO_FIN) && len)
1673 *wp &= ~LWS_WRITE_NO_FIN;
1675 lwsl_ext("FORCED draining wp to 0x%02X "
1676 "(stashed 0x%02X, incoming 0x%02X)\n", *wp,
1677 wsi->ws->tx_draining_stashed_wp, wpt);
1681 /* reset the ping wait */
1682 if (wsi->context->ws_ping_pong_interval) {
1683 wsi->sul_ping.cb = lws_sul_wsping_cb;
1684 __lws_sul_insert(&pt->pt_sul_owner, &wsi->sul_ping,
1685 (lws_usec_t)wsi->context->ws_ping_pong_interval *
1688 if (((*wp) & 0x1f) == LWS_WRITE_HTTP ||
1689 ((*wp) & 0x1f) == LWS_WRITE_HTTP_FINAL ||
1690 ((*wp) & 0x1f) == LWS_WRITE_HTTP_HEADERS_CONTINUATION ||
1691 ((*wp) & 0x1f) == LWS_WRITE_HTTP_HEADERS)
1696 /* if we are continuing a frame that already had its header done */
1698 if (wsi->ws->inside_frame) {
1699 lwsl_debug("INSIDE FRAME\n");
1700 goto do_more_inside_frame;
1703 wsi->ws->clean_buffer = 1;
1706 * give a chance to the extensions to modify payload
1707 * the extension may decide to produce unlimited payload erratically
1708 * (eg, compression extension), so we require only that if he produces
1709 * something, it will be a complete fragment of the length known at
1710 * the time (just the fragment length known), and if he has
1711 * more we will come back next time he is writeable and allow him to
1712 * produce more fragments until he's drained.
1714 * This allows what is sent each time it is writeable to be limited to
1715 * a size that can be sent without partial sends or blocking, allows
1716 * interleaving of control frames and other connection service.
1719 pmdrx.eb_in.token = buf;
1720 pmdrx.eb_in.len = (int)len;
1722 /* for the non-pm-deflate case */
1724 pmdrx.eb_out = pmdrx.eb_in;
1727 case LWS_WRITE_PING:
1728 case LWS_WRITE_PONG:
1729 case LWS_WRITE_CLOSE:
1732 #if !defined(LWS_WITHOUT_EXTENSIONS)
1733 n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_TX, &pmdrx, *wp);
1736 lwsl_ext("%s: defl ext ret %d, ext in remaining %d, "
1737 "out %d compressed (wp 0x%x)\n", __func__, n,
1738 (int)pmdrx.eb_in.len, (int)pmdrx.eb_out.len, *wp);
1740 if (n == PMDR_HAS_PENDING) {
1741 lwsl_ext("%s: HAS PENDING: write drain len %d "
1742 "(wp 0x%x) SETTING tx_draining_ext "
1743 "(remaining in %d)\n", __func__,
1744 (int)pmdrx.eb_out.len, *wp,
1745 (int)pmdrx.eb_in.len);
1746 /* extension requires further draining */
1747 wsi->ws->tx_draining_ext = 1;
1748 wsi->ws->tx_draining_ext_list =
1749 pt->ws.tx_draining_ext_list;
1750 pt->ws.tx_draining_ext_list = wsi;
1751 /* we must come back to do more */
1752 lws_callback_on_writable(wsi);
1754 * keep a copy of the write type for the overall
1755 * action that has provoked generation of these
1756 * fragments, so the last guy can use its FIN state.
1758 wsi->ws->tx_draining_stashed_wp = *wp;
1760 * Despite what we may have thought, this is definitely
1761 * NOT the last fragment, because the extension asserted
1762 * he has more coming. For example, the extension may
1763 * be compressing, and has saved up everything until the
1764 * end, where the output is larger than one chunk.
1766 * Make sure this intermediate one doesn't actually
1767 * go out with a FIN.
1769 *wp |= LWS_WRITE_NO_FIN;
1772 if (pmdrx.eb_out.len && wsi->ws->stashed_write_pending) {
1773 wsi->ws->stashed_write_pending = 0;
1774 *wp = ((*wp) & 0xc0) | (int)wsi->ws->stashed_write_type;
1779 * an extension did something we need to keep... for example, if
1780 * compression extension, it has already updated its state according
1781 * to this being issued
1783 if (buf != pmdrx.eb_out.token) {
1785 * ext might eat it, but not have anything to issue yet.
1786 * In that case we have to follow his lead, but stash and
1787 * replace the write type that was lost here the first time.
1789 if (len && !pmdrx.eb_out.len) {
1790 if (!wsi->ws->stashed_write_pending)
1791 wsi->ws->stashed_write_type =
1793 wsi->ws->stashed_write_pending = 1;
1797 * extension recreated it:
1798 * need to buffer this if not all sent
1800 wsi->ws->clean_buffer = 0;
1803 buf = pmdrx.eb_out.token;
1804 len = pmdrx.eb_out.len;
1807 lwsl_err("null buf (%d)\n", (int)len);
1811 switch (wsi->ws->ietf_spec_revision) {
1815 dropmask = &buf[0 - pre];
1816 is_masked_bit = 0x80;
1819 switch ((*wp) & 0xf) {
1820 case LWS_WRITE_TEXT:
1821 n = LWSWSOPC_TEXT_FRAME;
1823 case LWS_WRITE_BINARY:
1824 n = LWSWSOPC_BINARY_FRAME;
1826 case LWS_WRITE_CONTINUATION:
1827 n = LWSWSOPC_CONTINUATION;
1830 case LWS_WRITE_CLOSE:
1833 case LWS_WRITE_PING:
1836 case LWS_WRITE_PONG:
1840 lwsl_warn("lws_write: unknown write opc / wp\n");
1844 if (!((*wp) & LWS_WRITE_NO_FIN))
1850 buf[-pre + 1] = (unsigned char)(len | is_masked_bit);
1855 buf[-pre + 1] = 126 | is_masked_bit;
1856 buf[-pre + 2] = (unsigned char)(len >> 8);
1857 buf[-pre + 3] = (unsigned char)len;
1861 buf[-pre + 1] = 127 | is_masked_bit;
1862 #if defined __LP64__
1863 buf[-pre + 2] = (len >> 56) & 0x7f;
1864 buf[-pre + 3] = len >> 48;
1865 buf[-pre + 4] = len >> 40;
1866 buf[-pre + 5] = len >> 32;
1873 buf[-pre + 6] = (unsigned char)(len >> 24);
1874 buf[-pre + 7] = (unsigned char)(len >> 16);
1875 buf[-pre + 8] = (unsigned char)(len >> 8);
1876 buf[-pre + 9] = (unsigned char)len;
1882 do_more_inside_frame:
1885 * Deal with masking if we are in client -> server direction and
1890 if (!wsi->ws->inside_frame)
1891 if (lws_0405_frame_mask_generate(wsi)) {
1892 lwsl_err("frame mask generation failed\n");
1897 * in v7, just mask the payload
1899 if (dropmask) { /* never set if already inside frame */
1900 for (n = 4; n < (int)len + 4; n++)
1901 dropmask[n] = dropmask[n] ^ wsi->ws->mask[
1902 (wsi->ws->mask_idx++) & 3];
1904 /* copy the frame nonce into place */
1905 memcpy(dropmask, wsi->ws->mask, 4);
1909 if (lwsi_role_h2_ENCAPSULATION(wsi)) {
1910 struct lws *encap = lws_get_network_wsi(wsi);
1912 assert(encap != wsi);
1913 return encap->role_ops->write_role_protocol(wsi, buf - pre,
1917 switch ((*wp) & 0x1f) {
1918 case LWS_WRITE_TEXT:
1919 case LWS_WRITE_BINARY:
1920 case LWS_WRITE_CONTINUATION:
1921 if (!wsi->h2_stream_carries_ws) {
1924 * give any active extensions a chance to munge the
1925 * buffer before send. We pass in a pointer to an
1926 * lws_tokens struct prepared with the default buffer
1927 * and content length that's in there. Rather than
1928 * rewrite the default buffer, extensions that expect
1929 * to grow the buffer can adapt .token to point to their
1930 * own per-connection buffer in the extension user
1931 * allocation. By default with no extensions or no
1932 * extension callback handling, just the normal input
1933 * buffer is used then so it is efficient.
1935 * callback returns 1 in case it wants to spill more
1938 * This takes care of holding the buffer if send is
1939 * incomplete, ie, if wsi->ws->clean_buffer is 0
1940 * (meaning an extension meddled with the buffer). If
1941 * wsi->ws->clean_buffer is 1, it will instead return
1942 * to the user code how much OF THE USER BUFFER was
1946 n = lws_issue_raw_ext_access(wsi, buf - pre, len + pre);
1947 wsi->ws->inside_frame = 1;
1951 if (n == (int)len + pre) {
1952 /* everything in the buffer was handled
1953 * (or rebuffered...) */
1954 wsi->ws->inside_frame = 0;
1955 return (int)orig_len;
1959 * it is how many bytes of user buffer got sent... may
1960 * be < orig_len in which case callback when writable
1961 * has already been arranged and user code can call
1962 * lws_write() again with the rest later.
1973 return lws_issue_raw(wsi, (unsigned char *)buf - pre, len + pre);
1977 rops_close_kill_connection_ws(struct lws *wsi, enum lws_close_status reason)
1979 lws_dll2_remove(&wsi->sul_ping.list);
1980 /* deal with ws encapsulation in h2 */
1981 #if defined(LWS_WITH_HTTP2)
1982 if (wsi->http2_substream && wsi->h2_stream_carries_ws)
1983 return role_ops_h2.close_kill_connection(wsi, reason);
1992 rops_callback_on_writable_ws(struct lws *wsi)
1994 #if defined(LWS_WITH_HTTP2)
1995 if (lwsi_role_h2_ENCAPSULATION(wsi)) {
1996 /* we know then that it has an h2 parent */
1997 struct lws *enc = role_ops_h2.encapsulation_parent(wsi);
2000 if (enc->role_ops->callback_on_writable(wsi))
2008 rops_init_vhost_ws(struct lws_vhost *vh,
2009 const struct lws_context_creation_info *info)
2011 #if !defined(LWS_WITHOUT_EXTENSIONS)
2012 #ifdef LWS_WITH_PLUGINS
2013 struct lws_plugin *plugin = vh->context->plugin_list;
2016 if (vh->context->plugin_extension_count) {
2019 while (info->extensions && info->extensions[m].callback)
2023 * give the vhost a unified list of extensions including the
2024 * ones that came from plugins
2026 vh->ws.extensions = lws_zalloc(sizeof(struct lws_extension) *
2027 (m + vh->context->plugin_extension_count + 1),
2029 if (!vh->ws.extensions)
2032 memcpy((struct lws_extension *)vh->ws.extensions, info->extensions,
2033 sizeof(struct lws_extension) * m);
2034 plugin = vh->context->plugin_list;
2036 memcpy((struct lws_extension *)&vh->ws.extensions[m],
2037 plugin->caps.extensions,
2038 sizeof(struct lws_extension) *
2039 plugin->caps.count_extensions);
2040 m += plugin->caps.count_extensions;
2041 plugin = plugin->list;
2045 vh->ws.extensions = info->extensions;
2052 rops_destroy_vhost_ws(struct lws_vhost *vh)
2054 #ifdef LWS_WITH_PLUGINS
2055 #if !defined(LWS_WITHOUT_EXTENSIONS)
2056 if (vh->context->plugin_extension_count)
2057 lws_free((void *)vh->ws.extensions);
2064 #if defined(LWS_WITH_HTTP_PROXY)
2066 ws_destroy_proxy_buf(struct lws_dll2 *d, void *user)
2075 rops_destroy_role_ws(struct lws *wsi)
2077 #if defined(LWS_WITH_HTTP_PROXY)
2078 lws_dll2_foreach_safe(&wsi->ws->proxy_owner, NULL, ws_destroy_proxy_buf);
2081 lws_free_set_NULL(wsi->ws);
2086 struct lws_role_ops role_ops_ws = {
2087 /* role name */ "ws",
2089 /* check_upgrades */ NULL,
2090 /* init_context */ NULL,
2091 /* init_vhost */ rops_init_vhost_ws,
2092 /* destroy_vhost */ rops_destroy_vhost_ws,
2093 /* periodic_checks */ NULL,
2094 /* service_flag_pending */ rops_service_flag_pending_ws,
2095 /* handle_POLLIN */ rops_handle_POLLIN_ws,
2096 /* handle_POLLOUT */ rops_handle_POLLOUT_ws,
2097 /* perform_user_POLLOUT */ NULL,
2098 /* callback_on_writable */ rops_callback_on_writable_ws,
2099 /* tx_credit */ NULL,
2100 /* write_role_protocol */ rops_write_role_protocol_ws,
2101 /* encapsulation_parent */ NULL,
2102 /* alpn_negotiated */ NULL,
2103 /* close_via_role_protocol */ rops_close_via_role_protocol_ws,
2104 /* close_role */ rops_close_role_ws,
2105 /* close_kill_connection */ rops_close_kill_connection_ws,
2106 /* destroy_role */ rops_destroy_role_ws,
2107 /* adoption_bind */ NULL,
2108 /* client_bind */ NULL,
2109 /* adoption_cb clnt, srv */ { LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED,
2110 LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED },
2111 /* rx_cb clnt, srv */ { LWS_CALLBACK_CLIENT_RECEIVE,
2112 LWS_CALLBACK_RECEIVE },
2113 /* writeable cb clnt, srv */ { LWS_CALLBACK_CLIENT_WRITEABLE,
2114 LWS_CALLBACK_SERVER_WRITEABLE },
2115 /* close cb clnt, srv */ { LWS_CALLBACK_CLIENT_CLOSED,
2116 LWS_CALLBACK_CLOSED },
2117 /* protocol_bind cb c, srv */ { LWS_CALLBACK_WS_CLIENT_BIND_PROTOCOL,
2118 LWS_CALLBACK_WS_SERVER_BIND_PROTOCOL },
2119 /* protocol_unbind cb c, srv */ { LWS_CALLBACK_WS_CLIENT_DROP_PROTOCOL,
2120 LWS_CALLBACK_WS_SERVER_DROP_PROTOCOL },
2121 /* file handles */ 0