2 * libwebsockets - small server side websockets and web server implementation
4 * Copyright (C) 2010-2013 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 "private-libwebsockets.h"
24 const unsigned char lextable[] = {
28 #define FAIL_CHAR 0x08
30 int LWS_WARN_UNUSED_RESULT
31 lextable_decode(int pos, char c)
33 if (c >= 'A' && c <= 'Z')
37 if (lextable[pos] & (1 << 7)) { /* 1-byte, fail on mismatch */
38 if ((lextable[pos] & 0x7f) != c)
42 if (lextable[pos] == FAIL_CHAR)
47 if (lextable[pos] == FAIL_CHAR)
50 /* b7 = 0, end or 3-byte */
51 if (lextable[pos] < FAIL_CHAR) /* terminal marker */
54 if (lextable[pos] == c) /* goto */
55 return pos + (lextable[pos + 1]) +
56 (lextable[pos + 2] << 8);
63 // doesn't scrub the ah rxbuffer by default, parent must do if needed
66 lws_header_table_reset(struct lws *wsi, int autoservice)
68 struct allocated_headers *ah = wsi->u.hdr.ah;
69 struct lws_context_per_thread *pt;
70 struct lws_pollfd *pfd;
72 /* if we have the idea we're resetting 'our' ah, must be bound to one */
74 /* ah also concurs with ownership */
75 assert(ah->wsi == wsi);
77 /* init the ah to reflect no headers or data have appeared yet */
78 memset(ah->frag_index, 0, sizeof(ah->frag_index));
82 /* since we will restart the ah, our new headers are not completed */
83 // wsi->hdr_parsing_completed = 0;
86 * if we inherited pending rx (from socket adoption deferred
87 * processing), apply and free it.
89 if (wsi->u.hdr.preamble_rx) {
90 memcpy(ah->rx, wsi->u.hdr.preamble_rx,
91 wsi->u.hdr.preamble_rx_len);
92 ah->rxlen = wsi->u.hdr.preamble_rx_len;
93 lws_free_set_NULL(wsi->u.hdr.preamble_rx);
96 lwsl_notice("%s: calling service on readbuf ah\n", __func__);
98 pt = &wsi->context->pt[(int)wsi->tsi];
100 /* unlike a normal connect, we have the headers already
101 * (or the first part of them anyway)
103 pfd = &pt->fds[wsi->position_in_fds_table];
104 pfd->revents |= LWS_POLLIN;
105 lwsl_err("%s: calling service\n", __func__);
106 lws_service_fd_tsi(wsi->context, pfd, wsi->tsi);
111 int LWS_WARN_UNUSED_RESULT
112 lws_header_table_attach(struct lws *wsi, int autoservice)
114 struct lws_context *context = wsi->context;
115 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
116 struct lws_pollargs pa;
120 lwsl_info("%s: wsi %p: ah %p (tsi %d, count = %d) in\n", __func__, (void *)wsi,
121 (void *)wsi->u.hdr.ah, wsi->tsi, pt->ah_count_in_use);
123 /* if we are already bound to one, just clear it down */
125 lwsl_info("cleardown\n");
130 pwsi = &pt->ah_wait_list;
133 /* if already waiting on list, if no new ah just ret */
134 if (pt->ah_count_in_use ==
135 context->max_http_header_pool) {
136 lwsl_notice("%s: no free ah to attach\n", __func__);
139 /* new ah.... remove ourselves from waiting list */
140 *pwsi = wsi->u.hdr.ah_wait_list; /* set our prev to our next */
141 wsi->u.hdr.ah_wait_list = NULL; /* no next any more */
142 pt->ah_wait_list_length--;
145 pwsi = &(*pwsi)->u.hdr.ah_wait_list;
148 * pool is all busy... add us to waiting list and return that we
149 * weren't able to deliver it right now
151 if (pt->ah_count_in_use == context->max_http_header_pool) {
152 lwsl_notice("%s: adding %p to ah waiting list\n", __func__, wsi);
153 wsi->u.hdr.ah_wait_list = pt->ah_wait_list;
154 pt->ah_wait_list = wsi;
155 pt->ah_wait_list_length++;
157 /* we cannot accept input then */
159 _lws_change_pollfd(wsi, LWS_POLLIN, 0, &pa);
163 for (n = 0; n < context->max_http_header_pool; n++)
164 if (!pt->ah_pool[n].in_use)
167 /* if the count of in use said something free... */
168 assert(n != context->max_http_header_pool);
170 wsi->u.hdr.ah = &pt->ah_pool[n];
171 wsi->u.hdr.ah->in_use = 1;
172 pt->ah_pool[n].wsi = wsi; /* mark our owner */
173 pt->ah_count_in_use++;
175 _lws_change_pollfd(wsi, 0, LWS_POLLIN, &pa);
177 lwsl_info("%s: wsi %p: ah %p: count %d (on exit)\n", __func__,
178 (void *)wsi, (void *)wsi->u.hdr.ah, pt->ah_count_in_use);
184 /* and reset the rx state */
185 wsi->u.hdr.ah->rxpos = 0;
186 wsi->u.hdr.ah->rxlen = 0;
188 lws_header_table_reset(wsi, autoservice);
189 time(&wsi->u.hdr.ah->assigned);
191 #ifndef LWS_NO_CLIENT
192 if (wsi->state == LWSS_CLIENT_UNCONNECTED)
193 if (!lws_client_connect_via_info2(wsi))
194 /* our client connect has failed, the wsi
208 int lws_header_table_detach(struct lws *wsi, int autoservice)
210 struct lws_context *context = wsi->context;
211 struct allocated_headers *ah = wsi->u.hdr.ah;
212 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
213 struct lws_pollargs pa;
217 lwsl_info("%s: wsi %p: ah %p (tsi=%d, count = %d)\n", __func__,
218 (void *)wsi, (void *)ah, wsi->tsi,
219 pt->ah_count_in_use);
221 if (wsi->u.hdr.preamble_rx)
222 lws_free_set_NULL(wsi->u.hdr.preamble_rx);
224 /* may not be detached while he still has unprocessed rx */
225 if (ah && ah->rxpos != ah->rxlen) {
226 lwsl_err("%s: %p: CANNOT DETACH rxpos:%d, rxlen:%d\n", __func__, wsi,
227 ah->rxpos, ah->rxlen);
228 assert(ah->rxpos == ah->rxlen);
235 pwsi = &pt->ah_wait_list;
236 if (!ah) { /* remove from wait list if none attached */
239 lwsl_info("%s: wsi %p, remv wait\n",
241 *pwsi = wsi->u.hdr.ah_wait_list;
242 wsi->u.hdr.ah_wait_list = NULL;
243 pt->ah_wait_list_length--;
246 pwsi = &(*pwsi)->u.hdr.ah_wait_list;
248 /* no ah, not on list... no more business here */
251 /* we did have an ah attached */
253 if (ah->assigned && now - ah->assigned > 3) {
255 * we're detaching the ah, but it was held an
256 * unreasonably long time
258 lwsl_notice("%s: wsi %p: ah held %ds, "
259 "ah.rxpos %d, ah.rxlen %d, mode/state %d %d,"
260 "wsi->more_rx_waiting %d\n", __func__, wsi,
261 (int)(now - ah->assigned),
262 ah->rxpos, ah->rxlen, wsi->mode, wsi->state,
263 wsi->more_rx_waiting);
268 /* if we think we're detaching one, there should be one in use */
269 assert(pt->ah_count_in_use > 0);
270 /* and this specific one should have been in use */
272 wsi->u.hdr.ah = NULL;
273 ah->wsi = NULL; /* no owner */
275 /* oh there is nobody on the waiting list... leave it at that then */
278 pt->ah_count_in_use--;
283 /* somebody else on same tsi is waiting, give it to oldest guy */
285 lwsl_info("pt wait list %p\n", *pwsi);
286 while ((*pwsi)->u.hdr.ah_wait_list)
287 pwsi = &(*pwsi)->u.hdr.ah_wait_list;
290 lwsl_info("last wsi in wait list %p\n", wsi);
293 ah->wsi = wsi; /* new owner */
294 /* and reset the rx state */
297 lws_header_table_reset(wsi, autoservice);
298 time(&wsi->u.hdr.ah->assigned);
300 /* clients acquire the ah and then insert themselves in fds table... */
301 if (wsi->position_in_fds_table != -1) {
302 lwsl_info("%s: Enabling %p POLLIN\n", __func__, wsi);
304 /* he has been stuck waiting for an ah, but now his wait is over,
307 _lws_change_pollfd(wsi, 0, LWS_POLLIN, &pa);
310 /* point prev guy to next guy in list instead */
311 *pwsi = wsi->u.hdr.ah_wait_list;
312 /* the guy who got one is out of the list */
313 wsi->u.hdr.ah_wait_list = NULL;
314 pt->ah_wait_list_length--;
316 #ifndef LWS_NO_CLIENT
317 if (wsi->state == LWSS_CLIENT_UNCONNECTED)
318 if (!lws_client_connect_via_info2(wsi)) {
319 /* our client connect has failed, the wsi
328 assert(!!pt->ah_wait_list_length == !!(int)(long)pt->ah_wait_list);
330 lwsl_info("%s: wsi %p: ah %p (tsi=%d, count = %d)\n", __func__,
331 (void *)wsi, (void *)ah, wsi->tsi,
332 pt->ah_count_in_use);
339 lws_hdr_fragment_length(struct lws *wsi, enum lws_token_indexes h, int frag_idx)
343 n = wsi->u.hdr.ah->frag_index[h];
348 return wsi->u.hdr.ah->frags[n].len;
349 n = wsi->u.hdr.ah->frags[n].nfrag;
350 } while (frag_idx-- && n);
355 LWS_VISIBLE int lws_hdr_total_length(struct lws *wsi, enum lws_token_indexes h)
360 n = wsi->u.hdr.ah->frag_index[h];
364 len += wsi->u.hdr.ah->frags[n].len;
365 n = wsi->u.hdr.ah->frags[n].nfrag;
371 LWS_VISIBLE int lws_hdr_copy_fragment(struct lws *wsi, char *dst, int len,
372 enum lws_token_indexes h, int frag_idx)
375 int f = wsi->u.hdr.ah->frag_index[h];
380 while (n < frag_idx) {
381 f = wsi->u.hdr.ah->frags[f].nfrag;
387 if (wsi->u.hdr.ah->frags[f].len >= len)
390 memcpy(dst, wsi->u.hdr.ah->data + wsi->u.hdr.ah->frags[f].offset,
391 wsi->u.hdr.ah->frags[f].len);
392 dst[wsi->u.hdr.ah->frags[f].len] = '\0';
394 return wsi->u.hdr.ah->frags[f].len;
397 LWS_VISIBLE int lws_hdr_copy(struct lws *wsi, char *dst, int len,
398 enum lws_token_indexes h)
400 int toklen = lws_hdr_total_length(wsi, h);
406 n = wsi->u.hdr.ah->frag_index[h];
411 strcpy(dst, &wsi->u.hdr.ah->data[wsi->u.hdr.ah->frags[n].offset]);
412 dst += wsi->u.hdr.ah->frags[n].len;
413 n = wsi->u.hdr.ah->frags[n].nfrag;
419 char *lws_hdr_simple_ptr(struct lws *wsi, enum lws_token_indexes h)
423 n = wsi->u.hdr.ah->frag_index[h];
427 return wsi->u.hdr.ah->data + wsi->u.hdr.ah->frags[n].offset;
430 int LWS_WARN_UNUSED_RESULT
431 lws_pos_in_bounds(struct lws *wsi)
433 if (wsi->u.hdr.ah->pos < (unsigned int)wsi->context->max_http_header_data)
436 if (wsi->u.hdr.ah->pos == wsi->context->max_http_header_data) {
437 lwsl_err("Ran out of header data space\n");
442 * with these tests everywhere, it should never be able to exceed
443 * the limit, only meet the limit
446 lwsl_err("%s: pos %d, limit %d\n", __func__, wsi->u.hdr.ah->pos,
447 wsi->context->max_http_header_data);
453 int LWS_WARN_UNUSED_RESULT
454 lws_hdr_simple_create(struct lws *wsi, enum lws_token_indexes h, const char *s)
456 wsi->u.hdr.ah->nfrag++;
457 if (wsi->u.hdr.ah->nfrag == ARRAY_SIZE(wsi->u.hdr.ah->frags)) {
458 lwsl_warn("More hdr frags than we can deal with, dropping\n");
462 wsi->u.hdr.ah->frag_index[h] = wsi->u.hdr.ah->nfrag;
464 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].offset = wsi->u.hdr.ah->pos;
465 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len = 0;
466 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].nfrag = 0;
469 if (lws_pos_in_bounds(wsi))
472 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = *s;
474 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len++;
480 signed char char_to_hex(const char c)
482 if (c >= '0' && c <= '9')
485 if (c >= 'a' && c <= 'f')
488 if (c >= 'A' && c <= 'F')
494 static int LWS_WARN_UNUSED_RESULT
495 issue_char(struct lws *wsi, unsigned char c)
497 unsigned short frag_len;
499 if (lws_pos_in_bounds(wsi))
502 frag_len = wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len;
504 * If we haven't hit the token limit, just copy the character into
507 if (frag_len < wsi->u.hdr.current_token_limit) {
508 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = c;
510 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len++;
514 /* Insert a null character when we *hit* the limit: */
515 if (frag_len == wsi->u.hdr.current_token_limit) {
516 if (lws_pos_in_bounds(wsi))
518 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = '\0';
519 lwsl_warn("header %i exceeds limit %d\n",
520 wsi->u.hdr.parser_state,
521 wsi->u.hdr.current_token_limit);
527 int LWS_WARN_UNUSED_RESULT
528 lws_parse(struct lws *wsi, unsigned char c)
530 static const unsigned char methods[] = {
533 WSI_TOKEN_OPTIONS_URI,
536 WSI_TOKEN_DELETE_URI,
538 struct allocated_headers *ah = wsi->u.hdr.ah;
539 struct lws_context *context = wsi->context;
540 unsigned int n, m, enc = 0;
542 assert(wsi->u.hdr.ah);
544 switch (wsi->u.hdr.parser_state) {
547 lwsl_parser("WSI_TOK_(%d) '%c'\n", wsi->u.hdr.parser_state, c);
549 /* collect into malloc'd buffers */
550 /* optional initial space swallow */
551 if (!ah->frags[ah->frag_index[wsi->u.hdr.parser_state]].len &&
555 for (m = 0; m < ARRAY_SIZE(methods); m++)
556 if (wsi->u.hdr.parser_state == methods[m])
558 if (m == ARRAY_SIZE(methods))
559 /* it was not any of the methods */
562 /* special URI processing... end at space */
565 /* enforce starting with / */
566 if (!ah->frags[ah->nfrag].len)
567 if (issue_char(wsi, '/') < 0)
570 if (wsi->u.hdr.ups == URIPS_SEEN_SLASH_DOT_DOT) {
572 * back up one dir level if possible
573 * safe against header fragmentation because
574 * the method URI can only be in 1 fragment
576 if (ah->frags[ah->nfrag].len > 2) {
578 ah->frags[ah->nfrag].len--;
581 ah->frags[ah->nfrag].len--;
582 } while (ah->frags[ah->nfrag].len > 1 &&
583 ah->data[ah->pos] != '/');
587 /* begin parsing HTTP version: */
588 if (issue_char(wsi, '\0') < 0)
590 wsi->u.hdr.parser_state = WSI_TOKEN_HTTP;
596 * special URI processing... convert %xx
599 switch (wsi->u.hdr.ues) {
602 wsi->u.hdr.ues = URIES_SEEN_PERCENT;
606 case URIES_SEEN_PERCENT:
607 if (char_to_hex(c) < 0)
608 /* illegal post-% char */
611 wsi->u.hdr.esc_stash = c;
612 wsi->u.hdr.ues = URIES_SEEN_PERCENT_H1;
615 case URIES_SEEN_PERCENT_H1:
616 if (char_to_hex(c) < 0)
617 /* illegal post-% char */
620 c = (char_to_hex(wsi->u.hdr.esc_stash) << 4) |
623 wsi->u.hdr.ues = URIES_IDLE;
629 * special URI processing...
630 * convert /.. or /... or /../ etc to /
632 * convert // or /// etc to /
633 * leave /.dir or whatever alone
636 switch (wsi->u.hdr.ups) {
640 /* genuine delimiter */
641 if ((c == '&' || c == ';') && !enc) {
642 if (issue_char(wsi, c) < 0)
644 /* swallow the terminator */
645 ah->frags[ah->nfrag].len--;
646 /* link to next fragment */
647 ah->frags[ah->nfrag].nfrag = ah->nfrag + 1;
649 if (ah->nfrag >= ARRAY_SIZE(ah->frags))
651 /* start next fragment after the & */
652 wsi->u.hdr.post_literal_equal = 0;
653 ah->frags[ah->nfrag].offset = ah->pos;
654 ah->frags[ah->nfrag].len = 0;
655 ah->frags[ah->nfrag].nfrag = 0;
658 /* uriencoded = in the name part, disallow */
659 if (c == '=' && enc &&
660 ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS] &&
661 !wsi->u.hdr.post_literal_equal)
664 /* after the real =, we don't care how many = */
665 if (c == '=' && !enc)
666 wsi->u.hdr.post_literal_equal = 1;
669 if (c == '+' && !enc)
671 /* issue the first / always */
672 if (c == '/' && !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS])
673 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
675 case URIPS_SEEN_SLASH:
676 /* swallow subsequent slashes */
679 /* track and swallow the first . after / */
681 wsi->u.hdr.ups = URIPS_SEEN_SLASH_DOT;
684 wsi->u.hdr.ups = URIPS_IDLE;
686 case URIPS_SEEN_SLASH_DOT:
687 /* swallow second . */
689 wsi->u.hdr.ups = URIPS_SEEN_SLASH_DOT_DOT;
692 /* change /./ to / */
694 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
697 /* it was like /.dir ... regurgitate the . */
698 wsi->u.hdr.ups = URIPS_IDLE;
699 if (issue_char(wsi, '.') < 0)
703 case URIPS_SEEN_SLASH_DOT_DOT:
705 /* /../ or /..[End of URI] --> backup to last / */
706 if (c == '/' || c == '?') {
708 * back up one dir level if possible
709 * safe against header fragmentation because
710 * the method URI can only be in 1 fragment
712 if (ah->frags[ah->nfrag].len > 2) {
714 ah->frags[ah->nfrag].len--;
717 ah->frags[ah->nfrag].len--;
718 } while (ah->frags[ah->nfrag].len > 1 &&
719 ah->data[ah->pos] != '/');
721 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
722 if (ah->frags[ah->nfrag].len > 1)
727 /* /..[^/] ... regurgitate and allow */
729 if (issue_char(wsi, '.') < 0)
731 if (issue_char(wsi, '.') < 0)
733 wsi->u.hdr.ups = URIPS_IDLE;
737 if (c == '?' && !enc &&
738 !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS]) { /* start of URI arguments */
739 if (wsi->u.hdr.ues != URIES_IDLE)
742 /* seal off uri header */
743 if (issue_char(wsi, '\0') < 0)
746 /* move to using WSI_TOKEN_HTTP_URI_ARGS */
748 if (ah->nfrag >= ARRAY_SIZE(ah->frags))
750 ah->frags[ah->nfrag].offset = ah->pos;
751 ah->frags[ah->nfrag].len = 0;
752 ah->frags[ah->nfrag].nfrag = 0;
754 wsi->u.hdr.post_literal_equal = 0;
755 ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS] = ah->nfrag;
756 wsi->u.hdr.ups = URIPS_IDLE;
762 if (wsi->u.hdr.parser_state != WSI_TOKEN_CHALLENGE &&
764 if (wsi->u.hdr.ues != URIES_IDLE)
768 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
772 n = issue_char(wsi, c);
776 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
779 /* per-protocol end of headers management */
781 if (wsi->u.hdr.parser_state == WSI_TOKEN_CHALLENGE)
782 goto set_parsing_complete;
785 /* collecting and checking a name part */
786 case WSI_TOKEN_NAME_PART:
787 lwsl_parser("WSI_TOKEN_NAME_PART '%c' (mode=%d)\n", c, wsi->mode);
789 wsi->u.hdr.lextable_pos =
790 lextable_decode(wsi->u.hdr.lextable_pos, c);
792 * Server needs to look out for unknown methods...
794 if (wsi->u.hdr.lextable_pos < 0 &&
795 wsi->mode == LWSCM_HTTP_SERVING) {
796 /* this is not a header we know about */
797 for (m = 0; m < ARRAY_SIZE(methods); m++)
798 if (ah->frag_index[methods[m]]) {
800 * already had the method, no idea what
801 * this crap from the client is, ignore
803 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
807 * hm it's an unknown http method from a client in fact,
810 if (m == ARRAY_SIZE(methods)) {
811 lwsl_info("Unknown method - dropping\n");
817 * ...otherwise for a client, let him ignore unknown headers
818 * coming from the server
820 if (wsi->u.hdr.lextable_pos < 0) {
821 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
825 if (lextable[wsi->u.hdr.lextable_pos] < FAIL_CHAR) {
828 n = ((unsigned int)lextable[wsi->u.hdr.lextable_pos] << 8) |
829 lextable[wsi->u.hdr.lextable_pos + 1];
831 lwsl_parser("known hdr %d\n", n);
832 for (m = 0; m < ARRAY_SIZE(methods); m++)
833 if (n == methods[m] &&
834 ah->frag_index[methods[m]]) {
835 lwsl_warn("Duplicated method\n");
840 * WSORIGIN is protocol equiv to ORIGIN,
841 * JWebSocket likes to send it, map to ORIGIN
843 if (n == WSI_TOKEN_SWORIGIN)
844 n = WSI_TOKEN_ORIGIN;
846 wsi->u.hdr.parser_state = (enum lws_token_indexes)
847 (WSI_TOKEN_GET_URI + n);
849 if (context->token_limits)
850 wsi->u.hdr.current_token_limit =
851 context->token_limits->token_limit[
852 wsi->u.hdr.parser_state];
854 wsi->u.hdr.current_token_limit =
855 wsi->context->max_http_header_data;
857 if (wsi->u.hdr.parser_state == WSI_TOKEN_CHALLENGE)
858 goto set_parsing_complete;
867 if (ah->nfrag == ARRAY_SIZE(ah->frags)) {
868 lwsl_warn("More hdr frags than we can deal with\n");
872 ah->frags[ah->nfrag].offset = ah->pos;
873 ah->frags[ah->nfrag].len = 0;
874 ah->frags[ah->nfrag].nfrag = 0;
876 n = ah->frag_index[wsi->u.hdr.parser_state];
877 if (!n) { /* first fragment */
878 ah->frag_index[wsi->u.hdr.parser_state] = ah->nfrag;
882 while (ah->frags[n].nfrag)
883 n = ah->frags[n].nfrag;
884 ah->frags[n].nfrag = ah->nfrag;
886 if (issue_char(wsi, ' ') < 0)
890 /* skipping arg part of a name we didn't recognize */
891 case WSI_TOKEN_SKIPPING:
892 lwsl_parser("WSI_TOKEN_SKIPPING '%c'\n", c);
895 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
898 case WSI_TOKEN_SKIPPING_SAW_CR:
899 lwsl_parser("WSI_TOKEN_SKIPPING_SAW_CR '%c'\n", c);
900 if (wsi->u.hdr.ues != URIES_IDLE)
903 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
904 wsi->u.hdr.lextable_pos = 0;
906 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
908 /* we're done, ignore anything else */
910 case WSI_PARSING_COMPLETE:
911 lwsl_parser("WSI_PARSING_COMPLETE '%c'\n", c);
917 set_parsing_complete:
918 if (wsi->u.hdr.ues != URIES_IDLE)
920 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
921 if (lws_hdr_total_length(wsi, WSI_TOKEN_VERSION))
922 wsi->ietf_spec_revision =
923 atoi(lws_hdr_simple_ptr(wsi, WSI_TOKEN_VERSION));
925 lwsl_parser("v%02d hdrs completed\n", wsi->ietf_spec_revision);
927 wsi->u.hdr.parser_state = WSI_PARSING_COMPLETE;
928 wsi->hdr_parsing_completed = 1;
933 lwsl_notice(" forbidding on uri sanitation\n");
934 lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
938 LWS_VISIBLE int lws_frame_is_binary(struct lws *wsi)
940 return wsi->u.ws.frame_is_binary;
944 lws_rx_sm(struct lws *wsi, unsigned char c)
946 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
947 int callback_action = LWS_CALLBACK_RECEIVE;
948 int ret = 0, n, rx_draining_ext = 0;
949 struct lws_tokens eff_buf;
951 if (wsi->socket_is_permanently_unusable)
954 switch (wsi->lws_rx_parse_state) {
956 if (wsi->u.ws.rx_draining_ext) {
957 struct lws **w = &pt->rx_draining_ext_list;
959 eff_buf.token = NULL;
960 eff_buf.token_len = 0;
961 wsi->u.ws.rx_draining_ext = 0;
962 /* remove us from context draining ext list */
965 *w = wsi->u.ws.rx_draining_ext_list;
968 w = &((*w)->u.ws.rx_draining_ext_list);
970 wsi->u.ws.rx_draining_ext_list = NULL;
972 lwsl_err("%s: doing draining flow\n", __func__);
974 goto drain_extension;
976 switch (wsi->ietf_spec_revision) {
979 * no prepended frame key any more
981 wsi->u.ws.all_zero_nonce = 1;
985 lwsl_warn("lws_rx_sm: unknown spec version %d\n",
986 wsi->ietf_spec_revision);
990 case LWS_RXPS_04_mask_1:
991 wsi->u.ws.mask[1] = c;
993 wsi->u.ws.all_zero_nonce = 0;
994 wsi->lws_rx_parse_state = LWS_RXPS_04_mask_2;
996 case LWS_RXPS_04_mask_2:
997 wsi->u.ws.mask[2] = c;
999 wsi->u.ws.all_zero_nonce = 0;
1000 wsi->lws_rx_parse_state = LWS_RXPS_04_mask_3;
1002 case LWS_RXPS_04_mask_3:
1003 wsi->u.ws.mask[3] = c;
1005 wsi->u.ws.all_zero_nonce = 0;
1008 * start from the zero'th byte in the XOR key buffer since
1009 * this is the start of a frame with a new key
1012 wsi->u.ws.mask_idx = 0;
1014 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_1;
1018 * 04 logical framing from the spec (all this is masked when incoming
1019 * and has to be unmasked)
1021 * We ignore the possibility of extension data because we don't
1022 * negotiate any extensions at the moment.
1025 * 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
1026 * +-+-+-+-+-------+-+-------------+-------------------------------+
1027 * |F|R|R|R| opcode|R| Payload len | Extended payload length |
1028 * |I|S|S|S| (4) |S| (7) | (16/63) |
1029 * |N|V|V|V| |V| | (if payload len==126/127) |
1031 * +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
1032 * | Extended payload length continued, if payload len == 127 |
1033 * + - - - - - - - - - - - - - - - +-------------------------------+
1034 * | | Extension data |
1035 * +-------------------------------+ - - - - - - - - - - - - - - - +
1037 * +---------------------------------------------------------------+
1038 * : Application data :
1039 * +---------------------------------------------------------------+
1041 * We pass payload through to userland as soon as we get it, ignoring
1042 * FIN. It's up to userland to buffer it up if it wants to see a
1043 * whole unfragmented block of the original size (which may be up to
1047 case LWS_RXPS_04_FRAME_HDR_1:
1050 wsi->u.ws.opcode = c & 0xf;
1051 wsi->u.ws.rsv = c & 0x70;
1052 wsi->u.ws.final = !!((c >> 7) & 1);
1054 switch (wsi->u.ws.opcode) {
1055 case LWSWSOPC_TEXT_FRAME:
1056 case LWSWSOPC_BINARY_FRAME:
1057 wsi->u.ws.rsv_first_msg = (c & 0x70);
1058 wsi->u.ws.frame_is_binary =
1059 wsi->u.ws.opcode == LWSWSOPC_BINARY_FRAME;
1071 lwsl_info("illegal opcode\n");
1074 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;
1077 case LWS_RXPS_04_FRAME_HDR_LEN:
1079 wsi->u.ws.this_frame_masked = !!(c & 0x80);
1083 /* control frames are not allowed to have big lengths */
1084 if (wsi->u.ws.opcode & 8)
1085 goto illegal_ctl_length;
1087 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;
1090 /* control frames are not allowed to have big lengths */
1091 if (wsi->u.ws.opcode & 8)
1092 goto illegal_ctl_length;
1094 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;
1097 wsi->u.ws.rx_packet_length = c & 0x7f;
1098 if (wsi->u.ws.this_frame_masked)
1099 wsi->lws_rx_parse_state =
1100 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
1102 if (wsi->u.ws.rx_packet_length)
1103 wsi->lws_rx_parse_state =
1104 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1106 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1113 case LWS_RXPS_04_FRAME_HDR_LEN16_2:
1114 wsi->u.ws.rx_packet_length = c << 8;
1115 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1;
1118 case LWS_RXPS_04_FRAME_HDR_LEN16_1:
1119 wsi->u.ws.rx_packet_length |= c;
1120 if (wsi->u.ws.this_frame_masked)
1121 wsi->lws_rx_parse_state =
1122 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
1124 wsi->lws_rx_parse_state =
1125 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1128 case LWS_RXPS_04_FRAME_HDR_LEN64_8:
1130 lwsl_warn("b63 of length must be zero\n");
1131 /* kill the connection */
1134 #if defined __LP64__
1135 wsi->u.ws.rx_packet_length = ((size_t)c) << 56;
1137 wsi->u.ws.rx_packet_length = 0;
1139 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;
1142 case LWS_RXPS_04_FRAME_HDR_LEN64_7:
1143 #if defined __LP64__
1144 wsi->u.ws.rx_packet_length |= ((size_t)c) << 48;
1146 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;
1149 case LWS_RXPS_04_FRAME_HDR_LEN64_6:
1150 #if defined __LP64__
1151 wsi->u.ws.rx_packet_length |= ((size_t)c) << 40;
1153 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;
1156 case LWS_RXPS_04_FRAME_HDR_LEN64_5:
1157 #if defined __LP64__
1158 wsi->u.ws.rx_packet_length |= ((size_t)c) << 32;
1160 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;
1163 case LWS_RXPS_04_FRAME_HDR_LEN64_4:
1164 wsi->u.ws.rx_packet_length |= ((size_t)c) << 24;
1165 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3;
1168 case LWS_RXPS_04_FRAME_HDR_LEN64_3:
1169 wsi->u.ws.rx_packet_length |= ((size_t)c) << 16;
1170 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2;
1173 case LWS_RXPS_04_FRAME_HDR_LEN64_2:
1174 wsi->u.ws.rx_packet_length |= ((size_t)c) << 8;
1175 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1;
1178 case LWS_RXPS_04_FRAME_HDR_LEN64_1:
1179 wsi->u.ws.rx_packet_length |= ((size_t)c);
1180 if (wsi->u.ws.this_frame_masked)
1181 wsi->lws_rx_parse_state =
1182 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
1184 wsi->lws_rx_parse_state =
1185 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1188 case LWS_RXPS_07_COLLECT_FRAME_KEY_1:
1189 wsi->u.ws.mask[0] = c;
1191 wsi->u.ws.all_zero_nonce = 0;
1192 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_2;
1195 case LWS_RXPS_07_COLLECT_FRAME_KEY_2:
1196 wsi->u.ws.mask[1] = c;
1198 wsi->u.ws.all_zero_nonce = 0;
1199 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_3;
1202 case LWS_RXPS_07_COLLECT_FRAME_KEY_3:
1203 wsi->u.ws.mask[2] = c;
1205 wsi->u.ws.all_zero_nonce = 0;
1206 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_4;
1209 case LWS_RXPS_07_COLLECT_FRAME_KEY_4:
1210 wsi->u.ws.mask[3] = c;
1212 wsi->u.ws.all_zero_nonce = 0;
1213 wsi->lws_rx_parse_state =
1214 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1215 wsi->u.ws.mask_idx = 0;
1216 if (wsi->u.ws.rx_packet_length == 0) {
1217 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1223 case LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED:
1224 assert(wsi->u.ws.rx_ubuf);
1226 if (wsi->u.ws.rx_ubuf_head + LWS_PRE >=
1227 wsi->u.ws.rx_ubuf_alloc) {
1228 lwsl_err("Attempted overflow \n");
1231 if (wsi->u.ws.all_zero_nonce)
1232 wsi->u.ws.rx_ubuf[LWS_PRE +
1233 (wsi->u.ws.rx_ubuf_head++)] = c;
1235 wsi->u.ws.rx_ubuf[LWS_PRE +
1236 (wsi->u.ws.rx_ubuf_head++)] =
1238 (wsi->u.ws.mask_idx++) & 3];
1240 if (--wsi->u.ws.rx_packet_length == 0) {
1241 /* spill because we have the whole frame */
1242 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1247 * if there's no protocol max frame size given, we are
1248 * supposed to default to context->pt_serv_buf_size
1251 if (!wsi->protocol->rx_buffer_size &&
1252 wsi->u.ws.rx_ubuf_head != wsi->context->pt_serv_buf_size)
1255 if (wsi->protocol->rx_buffer_size &&
1256 wsi->u.ws.rx_ubuf_head !=
1257 wsi->protocol->rx_buffer_size)
1260 /* spill because we filled our rx buffer */
1263 * is this frame a control packet we should take care of at this
1264 * layer? If so service it and hide it from the user callback
1267 lwsl_parser("spill on %s\n", wsi->protocol->name);
1269 switch (wsi->u.ws.opcode) {
1270 case LWSWSOPC_CLOSE:
1272 /* is this an acknowledgement of our close? */
1273 if (wsi->state == LWSS_AWAITING_CLOSE_ACK) {
1275 * fine he has told us he is closing too, let's
1278 lwsl_parser("seen client close ack\n");
1281 if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY)
1282 /* if he sends us 2 CLOSE, kill him */
1285 if (lws_partial_buffered(wsi)) {
1287 * if we're in the middle of something,
1288 * we can't do a normal close response and
1289 * have to just close our end.
1291 wsi->socket_is_permanently_unusable = 1;
1292 lwsl_parser("Closing on peer close due to Pending tx\n");
1296 if (user_callback_handle_rxflow(
1297 wsi->protocol->callback, wsi,
1298 LWS_CALLBACK_WS_PEER_INITIATED_CLOSE,
1300 &wsi->u.ws.rx_ubuf[LWS_PRE],
1301 wsi->u.ws.rx_ubuf_head))
1304 lwsl_parser("server sees client close packet\n");
1305 wsi->state = LWSS_RETURNED_CLOSE_ALREADY;
1306 /* deal with the close packet contents as a PONG */
1307 wsi->u.ws.payload_is_close = 1;
1308 goto process_as_ping;
1311 lwsl_info("received %d byte ping, sending pong\n",
1312 wsi->u.ws.rx_ubuf_head);
1314 if (wsi->u.ws.ping_pending_flag) {
1316 * there is already a pending ping payload
1317 * we should just log and drop
1319 lwsl_parser("DROP PING since one pending\n");
1323 /* control packets can only be < 128 bytes long */
1324 if (wsi->u.ws.rx_ubuf_head > 128 - 3) {
1325 lwsl_parser("DROP PING payload too large\n");
1329 /* stash the pong payload */
1330 memcpy(wsi->u.ws.ping_payload_buf + LWS_PRE,
1331 &wsi->u.ws.rx_ubuf[LWS_PRE],
1332 wsi->u.ws.rx_ubuf_head);
1334 wsi->u.ws.ping_payload_len = wsi->u.ws.rx_ubuf_head;
1335 wsi->u.ws.ping_pending_flag = 1;
1337 /* get it sent as soon as possible */
1338 lws_callback_on_writable(wsi);
1340 wsi->u.ws.rx_ubuf_head = 0;
1344 lwsl_info("received pong\n");
1345 lwsl_hexdump(&wsi->u.ws.rx_ubuf[LWS_PRE],
1346 wsi->u.ws.rx_ubuf_head);
1348 if (wsi->pending_timeout == PENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG) {
1349 lwsl_info("received expected PONG on wsi %p\n", wsi);
1350 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1354 callback_action = LWS_CALLBACK_RECEIVE_PONG;
1357 case LWSWSOPC_TEXT_FRAME:
1358 case LWSWSOPC_BINARY_FRAME:
1359 case LWSWSOPC_CONTINUATION:
1363 lwsl_parser("passing opc %x up to exts\n",
1366 * It's something special we can't understand here.
1367 * Pass the payload up to the extension's parsing
1371 eff_buf.token = &wsi->u.ws.rx_ubuf[LWS_PRE];
1372 eff_buf.token_len = wsi->u.ws.rx_ubuf_head;
1374 if (lws_ext_cb_active(wsi, LWS_EXT_CB_EXTENDED_PAYLOAD_RX,
1376 /* not handle or fail */
1377 lwsl_ext("ext opc opcode 0x%x unknown\n",
1380 wsi->u.ws.rx_ubuf_head = 0;
1385 * No it's real payload, pass it up to the user callback.
1386 * It's nicely buffered with the pre-padding taken care of
1387 * so it can be sent straight out again using lws_write
1390 eff_buf.token = &wsi->u.ws.rx_ubuf[LWS_PRE];
1391 eff_buf.token_len = wsi->u.ws.rx_ubuf_head;
1394 lwsl_ext("%s: passing %d to ext\n", __func__, eff_buf.token_len);
1396 if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY ||
1397 wsi->state == LWSS_AWAITING_CLOSE_ACK)
1400 n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_RX, &eff_buf, 0);
1403 * we may rely on this to get RX, just drop connection
1405 wsi->socket_is_permanently_unusable = 1;
1409 if (rx_draining_ext && eff_buf.token_len == 0)
1412 if (n && eff_buf.token_len) {
1413 /* extension had more... main loop will come back */
1414 wsi->u.ws.rx_draining_ext = 1;
1415 wsi->u.ws.rx_draining_ext_list = pt->rx_draining_ext_list;
1416 pt->rx_draining_ext_list = wsi;
1419 if (eff_buf.token_len > 0 ||
1420 callback_action == LWS_CALLBACK_RECEIVE_PONG) {
1421 eff_buf.token[eff_buf.token_len] = '\0';
1423 if (wsi->protocol->callback) {
1425 if (callback_action == LWS_CALLBACK_RECEIVE_PONG)
1426 lwsl_info("Doing pong callback\n");
1428 ret = user_callback_handle_rxflow(
1429 wsi->protocol->callback,
1431 (enum lws_callback_reasons)callback_action,
1437 lwsl_err("No callback on payload spill!\n");
1441 wsi->u.ws.rx_ubuf_head = 0;
1449 lwsl_warn("Control frame with xtended length is illegal\n");
1450 /* kill the connection */
1455 lws_remaining_packet_payload(struct lws *wsi)
1457 return wsi->u.ws.rx_packet_length;
1460 /* Once we reach LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED, we know how much
1461 * to expect in that state and can deal with it in bulk more efficiently.
1465 lws_payload_until_length_exhausted(struct lws *wsi, unsigned char **buf,
1468 unsigned char *buffer = *buf, mask[4];
1473 if (wsi->protocol->rx_buffer_size)
1474 buffer_size = wsi->protocol->rx_buffer_size;
1476 buffer_size = wsi->context->pt_serv_buf_size;
1477 avail = buffer_size - wsi->u.ws.rx_ubuf_head;
1479 /* do not consume more than we should */
1480 if (avail > wsi->u.ws.rx_packet_length)
1481 avail = wsi->u.ws.rx_packet_length;
1483 /* do not consume more than what is in the buffer */
1487 /* we want to leave 1 byte for the parser to handle properly */
1492 rx_ubuf = wsi->u.ws.rx_ubuf + LWS_PRE + wsi->u.ws.rx_ubuf_head;
1493 if (wsi->u.ws.all_zero_nonce)
1494 memcpy(rx_ubuf, buffer, avail);
1497 for (n = 0; n < 4; n++)
1498 mask[n] = wsi->u.ws.mask[(wsi->u.ws.mask_idx + n) & 3];
1500 /* deal with 4-byte chunks using unwrapped loop */
1503 *(rx_ubuf++) = *(buffer++) ^ mask[0];
1504 *(rx_ubuf++) = *(buffer++) ^ mask[1];
1505 *(rx_ubuf++) = *(buffer++) ^ mask[2];
1506 *(rx_ubuf++) = *(buffer++) ^ mask[3];
1508 /* and the remaining bytes bytewise */
1509 for (n = 0; n < (int)(avail & 3); n++)
1510 *(rx_ubuf++) = *(buffer++) ^ mask[n];
1512 wsi->u.ws.mask_idx = (wsi->u.ws.mask_idx + avail) & 3;
1516 wsi->u.ws.rx_ubuf_head += avail;
1517 wsi->u.ws.rx_packet_length -= avail;