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 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);
64 lws_header_table_reset(struct lws *wsi)
66 struct allocated_headers *ah = wsi->u.hdr.ah;
68 /* if we have the idea we're resetting 'our' ah, must be bound to one */
70 /* ah also concurs with ownership */
71 assert(ah->wsi == wsi);
73 /* init the ah to reflect no headers or data have appeared yet */
74 memset(ah->frag_index, 0, sizeof(ah->frag_index));
78 /* and reset the rx state */
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, wsi->u.hdr.preamble_rx_len);
91 ah->rxlen = wsi->u.hdr.preamble_rx_len;
92 lws_free_set_NULL(wsi->u.hdr.preamble_rx);
96 int LWS_WARN_UNUSED_RESULT
97 lws_header_table_attach(struct lws *wsi)
99 struct lws_context *context = wsi->context;
100 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
101 struct lws_pollargs pa;
105 lwsl_info("%s: wsi %p: ah %p (tsi %d)\n", __func__, (void *)wsi,
106 (void *)wsi->u.hdr.ah, wsi->tsi);
108 /* if we are already bound to one, just clear it down */
110 lwsl_info("cleardown\n");
115 pwsi = &pt->ah_wait_list;
118 /* if already waiting on list, if no new ah just ret */
119 if (pt->ah_count_in_use ==
120 context->max_http_header_pool) {
121 lwsl_err("ah wl denied\n");
124 /* new ah.... remove ourselves from waiting list */
125 *pwsi = wsi->u.hdr.ah_wait_list; /* set our prev to our next */
126 wsi->u.hdr.ah_wait_list = NULL; /* no next any more */
127 pt->ah_wait_list_length--;
130 pwsi = &(*pwsi)->u.hdr.ah_wait_list;
133 * pool is all busy... add us to waiting list and return that we
134 * weren't able to deliver it right now
136 if (pt->ah_count_in_use == context->max_http_header_pool) {
137 lwsl_info("%s: adding %p to ah waiting list\n", __func__, wsi);
138 wsi->u.hdr.ah_wait_list = pt->ah_wait_list;
139 pt->ah_wait_list = wsi;
140 pt->ah_wait_list_length++;
142 /* we cannot accept input then */
144 _lws_change_pollfd(wsi, LWS_POLLIN, 0, &pa);
148 for (n = 0; n < context->max_http_header_pool; n++)
149 if (!pt->ah_pool[n].in_use)
152 /* if the count of in use said something free... */
153 assert(n != context->max_http_header_pool);
155 wsi->u.hdr.ah = &pt->ah_pool[n];
156 wsi->u.hdr.ah->in_use = 1;
157 pt->ah_pool[n].wsi = wsi; /* mark our owner */
158 pt->ah_count_in_use++;
160 _lws_change_pollfd(wsi, 0, LWS_POLLIN, &pa);
162 lwsl_info("%s: wsi %p: ah %p: count %d (on exit)\n", __func__,
163 (void *)wsi, (void *)wsi->u.hdr.ah, pt->ah_count_in_use);
168 lws_header_table_reset(wsi);
169 time(&wsi->u.hdr.ah->assigned);
179 int lws_header_table_detach(struct lws *wsi)
181 struct lws_context *context = wsi->context;
182 struct allocated_headers *ah = wsi->u.hdr.ah;
183 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
184 struct lws_pollargs pa;
188 lwsl_info("%s: wsi %p: ah %p (tsi=%d, count = %d)\n", __func__,
189 (void *)wsi, (void *)wsi->u.hdr.ah, wsi->tsi,
190 pt->ah_count_in_use);
192 if (wsi->u.hdr.preamble_rx)
193 lws_free_set_NULL(wsi->u.hdr.preamble_rx);
195 /* may not be detached while he still has unprocessed rx */
196 if (ah && ah->rxpos != ah->rxlen) {
197 lwsl_err("%s: %p: rxpos:%d, rxlen:%d\n", __func__, wsi,
198 ah->rxpos, ah->rxlen);
199 assert(ah->rxpos == ah->rxlen);
204 pwsi = &pt->ah_wait_list;
205 if (!ah) { /* remove from wait list if none attached */
206 // if (wsi->socket_is_permanently_unusable)
209 lwsl_info("%s: wsi %p, remv wait\n",
211 *pwsi = wsi->u.hdr.ah_wait_list;
212 wsi->u.hdr.ah_wait_list = NULL;
213 pt->ah_wait_list_length--;
216 pwsi = &(*pwsi)->u.hdr.ah_wait_list;
221 /* we did have an ah attached */
223 if (now - wsi->u.hdr.ah->assigned > 3) {
225 * we're detaching the ah, but it was held an
226 * unreasonably long time
228 lwsl_notice("%s: wsi %p: ah held %ds, "
229 "ah.rxpos %d, ah.rxlen %d, mode/state %d %d,"
230 "wsi->more_rx_waiting %d\n", __func__, wsi,
231 (int)(now - wsi->u.hdr.ah->assigned),
232 ah->rxpos, ah->rxlen, wsi->mode, wsi->state,
233 wsi->u.hdr.more_rx_waiting);
236 /* if we think we're detaching one, there should be one in use */
237 assert(pt->ah_count_in_use > 0);
238 /* and this specific one should have been in use */
239 assert(wsi->u.hdr.ah->in_use);
240 wsi->u.hdr.ah = NULL;
241 ah->wsi = NULL; /* no owner */
243 /* oh there is nobody on the waiting list... leave it at that then */
246 pt->ah_count_in_use--;
251 /* somebody else on same tsi is waiting, give it to oldest guy */
253 lwsl_info("pt wait list %p\n", *pwsi);
254 while ((*pwsi)->u.hdr.ah_wait_list)
255 pwsi = &(*pwsi)->u.hdr.ah_wait_list;
258 lwsl_info("last wsi in wait list %p\n", wsi);
261 ah->wsi = wsi; /* new owner */
262 lws_header_table_reset(wsi);
263 time(&wsi->u.hdr.ah->assigned);
265 assert(wsi->position_in_fds_table != -1);
267 lwsl_info("%s: Enabling %p POLLIN\n", __func__, wsi);
269 /* he has been stuck waiting for an ah, but now his wait is over,
272 _lws_change_pollfd(wsi, 0, LWS_POLLIN, &pa);
274 /* point prev guy to next guy in list instead */
275 *pwsi = wsi->u.hdr.ah_wait_list;
276 /* the guy who got one is out of the list */
277 wsi->u.hdr.ah_wait_list = NULL;
278 pt->ah_wait_list_length--;
280 assert(!!pt->ah_wait_list_length == !!(int)(long)pt->ah_wait_list);
288 * lws_hdr_fragment_length: report length of a single fragment of a header
289 * The returned length does not include the space for a
292 * @wsi: websocket connection
293 * @h: which header index we are interested in
294 * @frag_idx: which fragment of @h we want to get the length of
298 lws_hdr_fragment_length(struct lws *wsi, enum lws_token_indexes h, int frag_idx)
302 n = wsi->u.hdr.ah->frag_index[h];
307 return wsi->u.hdr.ah->frags[n].len;
308 n = wsi->u.hdr.ah->frags[n].nfrag;
309 } while (frag_idx-- && n);
315 * lws_hdr_total_length: report length of all fragments of a header totalled up
316 * The returned length does not include the space for a
319 * @wsi: websocket connection
320 * @h: which header index we are interested in
323 LWS_VISIBLE int lws_hdr_total_length(struct lws *wsi, enum lws_token_indexes h)
328 n = wsi->u.hdr.ah->frag_index[h];
332 len += wsi->u.hdr.ah->frags[n].len;
333 n = wsi->u.hdr.ah->frags[n].nfrag;
340 * lws_hdr_copy_fragment: copy a single fragment of the given header to a buffer
341 * The buffer length @len must include space for an additional
342 * terminating '\0', or it will fail returning -1.
343 * If the requested fragment index is not present, it fails
346 * @wsi: websocket connection
347 * @dst: destination buffer
348 * @len: length of destination buffer
349 * @h: which header index we are interested in
350 * @frag_index: which fragment of @h we want to copy
353 LWS_VISIBLE int lws_hdr_copy_fragment(struct lws *wsi, char *dst, int len,
354 enum lws_token_indexes h, int frag_idx)
357 int f = wsi->u.hdr.ah->frag_index[h];
362 while (n < frag_idx) {
363 f = wsi->u.hdr.ah->frags[f].nfrag;
369 if (wsi->u.hdr.ah->frags[f].len >= len)
372 memcpy(dst, wsi->u.hdr.ah->data + wsi->u.hdr.ah->frags[f].offset,
373 wsi->u.hdr.ah->frags[f].len);
374 dst[wsi->u.hdr.ah->frags[f].len] = '\0';
376 return wsi->u.hdr.ah->frags[f].len;
380 * lws_hdr_copy: copy a single fragment of the given header to a buffer
381 * The buffer length @len must include space for an additional
382 * terminating '\0', or it will fail returning -1.
384 * @wsi: websocket connection
385 * @dst: destination buffer
386 * @len: length of destination buffer
387 * @h: which header index we are interested in
390 LWS_VISIBLE int lws_hdr_copy(struct lws *wsi, char *dst, int len,
391 enum lws_token_indexes h)
393 int toklen = lws_hdr_total_length(wsi, h);
399 n = wsi->u.hdr.ah->frag_index[h];
404 strcpy(dst, &wsi->u.hdr.ah->data[wsi->u.hdr.ah->frags[n].offset]);
405 dst += wsi->u.hdr.ah->frags[n].len;
406 n = wsi->u.hdr.ah->frags[n].nfrag;
412 char *lws_hdr_simple_ptr(struct lws *wsi, enum lws_token_indexes h)
416 n = wsi->u.hdr.ah->frag_index[h];
420 return wsi->u.hdr.ah->data + wsi->u.hdr.ah->frags[n].offset;
423 int LWS_WARN_UNUSED_RESULT
424 lws_pos_in_bounds(struct lws *wsi)
426 if (wsi->u.hdr.ah->pos < wsi->context->max_http_header_data)
429 if (wsi->u.hdr.ah->pos == wsi->context->max_http_header_data) {
430 lwsl_err("Ran out of header data space\n");
435 * with these tests everywhere, it should never be able to exceed
436 * the limit, only meet the limit
439 lwsl_err("%s: pos %d, limit %d\n", __func__, wsi->u.hdr.ah->pos,
440 wsi->context->max_http_header_data);
446 int LWS_WARN_UNUSED_RESULT
447 lws_hdr_simple_create(struct lws *wsi, enum lws_token_indexes h, const char *s)
449 wsi->u.hdr.ah->nfrag++;
450 if (wsi->u.hdr.ah->nfrag == ARRAY_SIZE(wsi->u.hdr.ah->frags)) {
451 lwsl_warn("More hdr frags than we can deal with, dropping\n");
455 wsi->u.hdr.ah->frag_index[h] = wsi->u.hdr.ah->nfrag;
457 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].offset = wsi->u.hdr.ah->pos;
458 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len = 0;
459 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].nfrag = 0;
462 if (lws_pos_in_bounds(wsi))
465 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = *s;
467 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len++;
473 static signed char char_to_hex(const char c)
475 if (c >= '0' && c <= '9')
478 if (c >= 'a' && c <= 'f')
481 if (c >= 'A' && c <= 'F')
487 static int LWS_WARN_UNUSED_RESULT
488 issue_char(struct lws *wsi, unsigned char c)
490 unsigned short frag_len;
492 if (lws_pos_in_bounds(wsi))
495 frag_len = wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len;
497 * If we haven't hit the token limit, just copy the character into
500 if (frag_len < wsi->u.hdr.current_token_limit) {
501 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = c;
503 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len++;
507 /* Insert a null character when we *hit* the limit: */
508 if (frag_len == wsi->u.hdr.current_token_limit) {
509 if (lws_pos_in_bounds(wsi))
511 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = '\0';
512 lwsl_warn("header %i exceeds limit %d\n",
513 wsi->u.hdr.parser_state,
514 wsi->u.hdr.current_token_limit);
520 int LWS_WARN_UNUSED_RESULT
521 lws_parse(struct lws *wsi, unsigned char c)
523 static const unsigned char methods[] = {
526 WSI_TOKEN_OPTIONS_URI,
529 WSI_TOKEN_DELETE_URI,
531 struct allocated_headers *ah = wsi->u.hdr.ah;
532 struct lws_context *context = wsi->context;
533 unsigned int n, m, enc = 0;
535 assert(wsi->u.hdr.ah);
537 switch (wsi->u.hdr.parser_state) {
540 lwsl_parser("WSI_TOK_(%d) '%c'\n", wsi->u.hdr.parser_state, c);
542 /* collect into malloc'd buffers */
543 /* optional initial space swallow */
544 if (!ah->frags[ah->frag_index[wsi->u.hdr.parser_state]].len &&
548 for (m = 0; m < ARRAY_SIZE(methods); m++)
549 if (wsi->u.hdr.parser_state == methods[m])
551 if (m == ARRAY_SIZE(methods))
552 /* it was not any of the methods */
555 /* special URI processing... end at space */
558 /* enforce starting with / */
559 if (!ah->frags[ah->nfrag].len)
560 if (issue_char(wsi, '/') < 0)
563 /* begin parsing HTTP version: */
564 if (issue_char(wsi, '\0') < 0)
566 wsi->u.hdr.parser_state = WSI_TOKEN_HTTP;
570 /* special URI processing... convert %xx */
572 switch (wsi->u.hdr.ues) {
575 wsi->u.hdr.ues = URIES_SEEN_PERCENT;
579 case URIES_SEEN_PERCENT:
580 if (char_to_hex(c) < 0) {
582 if (issue_char(wsi, '%') < 0)
584 wsi->u.hdr.ues = URIES_IDLE;
585 /* continue on to assess c */
588 wsi->u.hdr.esc_stash = c;
589 wsi->u.hdr.ues = URIES_SEEN_PERCENT_H1;
592 case URIES_SEEN_PERCENT_H1:
593 if (char_to_hex(c) < 0) {
595 if (issue_char(wsi, '%') < 0)
597 wsi->u.hdr.ues = URIES_IDLE;
598 /* regurgitate + assess */
599 if (lws_parse(wsi, wsi->u.hdr.esc_stash) < 0)
601 /* continue on to assess c */
604 c = (char_to_hex(wsi->u.hdr.esc_stash) << 4) |
607 wsi->u.hdr.ues = URIES_IDLE;
612 * special URI processing...
613 * convert /.. or /... or /../ etc to /
615 * convert // or /// etc to /
616 * leave /.dir or whatever alone
619 switch (wsi->u.hdr.ups) {
623 /* genuine delimiter */
624 if ((c == '&' || c == ';') && !enc) {
625 if (issue_char(wsi, c) < 0)
627 /* swallow the terminator */
628 ah->frags[ah->nfrag].len--;
629 /* link to next fragment */
630 ah->frags[ah->nfrag].nfrag = ah->nfrag + 1;
632 if (ah->nfrag >= ARRAY_SIZE(ah->frags))
634 /* start next fragment after the & */
635 wsi->u.hdr.post_literal_equal = 0;
636 ah->frags[ah->nfrag].offset = ah->pos;
637 ah->frags[ah->nfrag].len = 0;
638 ah->frags[ah->nfrag].nfrag = 0;
641 /* uriencoded = in the name part, disallow */
642 if (c == '=' && enc && !wsi->u.hdr.post_literal_equal)
645 /* after the real =, we don't care how many = */
646 if (c == '=' && !enc)
647 wsi->u.hdr.post_literal_equal = 1;
650 if (c == '+' && !enc)
652 /* issue the first / always */
653 if (c == '/' && !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS])
654 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
656 case URIPS_SEEN_SLASH:
657 /* swallow subsequent slashes */
660 /* track and swallow the first . after / */
662 wsi->u.hdr.ups = URIPS_SEEN_SLASH_DOT;
665 wsi->u.hdr.ups = URIPS_IDLE;
667 case URIPS_SEEN_SLASH_DOT:
668 /* swallow second . */
671 * back up one dir level if possible
672 * safe against header fragmentation because
673 * the method URI can only be in 1 fragment
675 if (ah->frags[ah->nfrag].len > 2) {
677 ah->frags[ah->nfrag].len--;
680 ah->frags[ah->nfrag].len--;
681 } while (ah->frags[ah->nfrag].len > 1 &&
682 ah->data[ah->pos] != '/');
684 wsi->u.hdr.ups = URIPS_SEEN_SLASH_DOT_DOT;
687 /* change /./ to / */
689 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
692 /* it was like /.dir ... regurgitate the . */
693 wsi->u.hdr.ups = URIPS_IDLE;
694 if (issue_char(wsi, '.') < 0)
698 case URIPS_SEEN_SLASH_DOT_DOT:
699 /* swallow prior .. chars and any subsequent . */
702 /* last issued was /, so another / == // */
705 /* last we issued was / so SEEN_SLASH */
706 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
710 if (c == '?' && !enc &&
711 !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS]) { /* start of URI arguments */
712 /* seal off uri header */
713 if (issue_char(wsi, '\0') < 0)
716 /* move to using WSI_TOKEN_HTTP_URI_ARGS */
718 if (ah->nfrag >= ARRAY_SIZE(ah->frags))
720 ah->frags[ah->nfrag].offset = ah->pos;
721 ah->frags[ah->nfrag].len = 0;
722 ah->frags[ah->nfrag].nfrag = 0;
724 wsi->u.hdr.post_literal_equal = 0;
725 ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS] = ah->nfrag;
726 wsi->u.hdr.ups = URIPS_IDLE;
733 if (wsi->u.hdr.parser_state != WSI_TOKEN_CHALLENGE &&
736 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
740 n = issue_char(wsi, c);
744 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
747 /* per-protocol end of headers management */
749 if (wsi->u.hdr.parser_state == WSI_TOKEN_CHALLENGE)
750 goto set_parsing_complete;
753 /* collecting and checking a name part */
754 case WSI_TOKEN_NAME_PART:
755 lwsl_parser("WSI_TOKEN_NAME_PART '%c' (mode=%d)\n", c, wsi->mode);
757 wsi->u.hdr.lextable_pos =
758 lextable_decode(wsi->u.hdr.lextable_pos, c);
760 * Server needs to look out for unknown methods...
762 if (wsi->u.hdr.lextable_pos < 0 &&
763 wsi->mode == LWSCM_HTTP_SERVING) {
764 /* this is not a header we know about */
765 for (m = 0; m < ARRAY_SIZE(methods); m++)
766 if (ah->frag_index[methods[m]]) {
768 * already had the method, no idea what
769 * this crap from the client is, ignore
771 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
775 * hm it's an unknown http method from a client in fact,
778 if (m == ARRAY_SIZE(methods)) {
779 lwsl_info("Unknown method - dropping\n");
785 * ...otherwise for a client, let him ignore unknown headers
786 * coming from the server
788 if (wsi->u.hdr.lextable_pos < 0) {
789 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
793 if (lextable[wsi->u.hdr.lextable_pos] < FAIL_CHAR) {
796 n = ((unsigned int)lextable[wsi->u.hdr.lextable_pos] << 8) |
797 lextable[wsi->u.hdr.lextable_pos + 1];
799 lwsl_parser("known hdr %d\n", n);
800 for (m = 0; m < ARRAY_SIZE(methods); m++)
801 if (n == methods[m] &&
802 ah->frag_index[methods[m]]) {
803 lwsl_warn("Duplicated method\n");
808 * WSORIGIN is protocol equiv to ORIGIN,
809 * JWebSocket likes to send it, map to ORIGIN
811 if (n == WSI_TOKEN_SWORIGIN)
812 n = WSI_TOKEN_ORIGIN;
814 wsi->u.hdr.parser_state = (enum lws_token_indexes)
815 (WSI_TOKEN_GET_URI + n);
817 if (context->token_limits)
818 wsi->u.hdr.current_token_limit =
819 context->token_limits->token_limit[
820 wsi->u.hdr.parser_state];
822 wsi->u.hdr.current_token_limit =
823 wsi->context->max_http_header_data;
825 if (wsi->u.hdr.parser_state == WSI_TOKEN_CHALLENGE)
826 goto set_parsing_complete;
835 if (ah->nfrag == ARRAY_SIZE(ah->frags)) {
836 lwsl_warn("More hdr frags than we can deal with\n");
840 ah->frags[ah->nfrag].offset = ah->pos;
841 ah->frags[ah->nfrag].len = 0;
842 ah->frags[ah->nfrag].nfrag = 0;
844 n = ah->frag_index[wsi->u.hdr.parser_state];
845 if (!n) { /* first fragment */
846 ah->frag_index[wsi->u.hdr.parser_state] = ah->nfrag;
850 while (ah->frags[n].nfrag)
851 n = ah->frags[n].nfrag;
852 ah->frags[n].nfrag = ah->nfrag;
854 if (issue_char(wsi, ' ') < 0)
858 /* skipping arg part of a name we didn't recognize */
859 case WSI_TOKEN_SKIPPING:
860 lwsl_parser("WSI_TOKEN_SKIPPING '%c'\n", c);
863 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
866 case WSI_TOKEN_SKIPPING_SAW_CR:
867 lwsl_parser("WSI_TOKEN_SKIPPING_SAW_CR '%c'\n", c);
869 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
870 wsi->u.hdr.lextable_pos = 0;
872 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
874 /* we're done, ignore anything else */
876 case WSI_PARSING_COMPLETE:
877 lwsl_parser("WSI_PARSING_COMPLETE '%c'\n", c);
883 set_parsing_complete:
885 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
886 if (lws_hdr_total_length(wsi, WSI_TOKEN_VERSION))
887 wsi->ietf_spec_revision =
888 atoi(lws_hdr_simple_ptr(wsi, WSI_TOKEN_VERSION));
890 lwsl_parser("v%02d hdrs completed\n", wsi->ietf_spec_revision);
892 wsi->u.hdr.parser_state = WSI_PARSING_COMPLETE;
893 wsi->hdr_parsing_completed = 1;
900 * lws_frame_is_binary: true if the current frame was sent in binary mode
902 * @wsi: the connection we are inquiring about
904 * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
905 * it's interested to see if the frame it's dealing with was sent in binary
909 LWS_VISIBLE int lws_frame_is_binary(struct lws *wsi)
911 return wsi->u.ws.frame_is_binary;
915 lws_rx_sm(struct lws *wsi, unsigned char c)
917 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
918 int callback_action = LWS_CALLBACK_RECEIVE;
919 int ret = 0, n, rx_draining_ext = 0;
920 struct lws_tokens eff_buf;
922 if (wsi->socket_is_permanently_unusable)
925 switch (wsi->lws_rx_parse_state) {
927 if (wsi->u.ws.rx_draining_ext) {
928 struct lws **w = &pt->rx_draining_ext_list;
930 eff_buf.token = NULL;
931 eff_buf.token_len = 0;
932 wsi->u.ws.rx_draining_ext = 0;
933 /* remove us from context draining ext list */
936 *w = wsi->u.ws.rx_draining_ext_list;
939 w = &((*w)->u.ws.rx_draining_ext_list);
941 wsi->u.ws.rx_draining_ext_list = NULL;
943 lwsl_err("%s: doing draining flow\n", __func__);
945 goto drain_extension;
947 switch (wsi->ietf_spec_revision) {
950 * no prepended frame key any more
952 wsi->u.ws.all_zero_nonce = 1;
956 lwsl_warn("lws_rx_sm: unknown spec version %d\n",
957 wsi->ietf_spec_revision);
961 case LWS_RXPS_04_mask_1:
962 wsi->u.ws.mask[1] = c;
964 wsi->u.ws.all_zero_nonce = 0;
965 wsi->lws_rx_parse_state = LWS_RXPS_04_mask_2;
967 case LWS_RXPS_04_mask_2:
968 wsi->u.ws.mask[2] = c;
970 wsi->u.ws.all_zero_nonce = 0;
971 wsi->lws_rx_parse_state = LWS_RXPS_04_mask_3;
973 case LWS_RXPS_04_mask_3:
974 wsi->u.ws.mask[3] = c;
976 wsi->u.ws.all_zero_nonce = 0;
979 * start from the zero'th byte in the XOR key buffer since
980 * this is the start of a frame with a new key
983 wsi->u.ws.mask_idx = 0;
985 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_1;
989 * 04 logical framing from the spec (all this is masked when incoming
990 * and has to be unmasked)
992 * We ignore the possibility of extension data because we don't
993 * negotiate any extensions at the moment.
996 * 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
997 * +-+-+-+-+-------+-+-------------+-------------------------------+
998 * |F|R|R|R| opcode|R| Payload len | Extended payload length |
999 * |I|S|S|S| (4) |S| (7) | (16/63) |
1000 * |N|V|V|V| |V| | (if payload len==126/127) |
1002 * +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
1003 * | Extended payload length continued, if payload len == 127 |
1004 * + - - - - - - - - - - - - - - - +-------------------------------+
1005 * | | Extension data |
1006 * +-------------------------------+ - - - - - - - - - - - - - - - +
1008 * +---------------------------------------------------------------+
1009 * : Application data :
1010 * +---------------------------------------------------------------+
1012 * We pass payload through to userland as soon as we get it, ignoring
1013 * FIN. It's up to userland to buffer it up if it wants to see a
1014 * whole unfragmented block of the original size (which may be up to
1018 case LWS_RXPS_04_FRAME_HDR_1:
1021 wsi->u.ws.opcode = c & 0xf;
1022 wsi->u.ws.rsv = c & 0x70;
1023 wsi->u.ws.final = !!((c >> 7) & 1);
1025 switch (wsi->u.ws.opcode) {
1026 case LWSWSOPC_TEXT_FRAME:
1027 case LWSWSOPC_BINARY_FRAME:
1028 wsi->u.ws.rsv_first_msg = (c & 0x70);
1029 wsi->u.ws.frame_is_binary =
1030 wsi->u.ws.opcode == LWSWSOPC_BINARY_FRAME;
1042 lwsl_info("illegal opcode\n");
1045 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;
1048 case LWS_RXPS_04_FRAME_HDR_LEN:
1050 wsi->u.ws.this_frame_masked = !!(c & 0x80);
1054 /* control frames are not allowed to have big lengths */
1055 if (wsi->u.ws.opcode & 8)
1056 goto illegal_ctl_length;
1058 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;
1061 /* control frames are not allowed to have big lengths */
1062 if (wsi->u.ws.opcode & 8)
1063 goto illegal_ctl_length;
1065 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;
1068 wsi->u.ws.rx_packet_length = c & 0x7f;
1069 if (wsi->u.ws.this_frame_masked)
1070 wsi->lws_rx_parse_state =
1071 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
1073 if (wsi->u.ws.rx_packet_length)
1074 wsi->lws_rx_parse_state =
1075 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1077 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1084 case LWS_RXPS_04_FRAME_HDR_LEN16_2:
1085 wsi->u.ws.rx_packet_length = c << 8;
1086 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1;
1089 case LWS_RXPS_04_FRAME_HDR_LEN16_1:
1090 wsi->u.ws.rx_packet_length |= c;
1091 if (wsi->u.ws.this_frame_masked)
1092 wsi->lws_rx_parse_state =
1093 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
1095 wsi->lws_rx_parse_state =
1096 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1099 case LWS_RXPS_04_FRAME_HDR_LEN64_8:
1101 lwsl_warn("b63 of length must be zero\n");
1102 /* kill the connection */
1105 #if defined __LP64__
1106 wsi->u.ws.rx_packet_length = ((size_t)c) << 56;
1108 wsi->u.ws.rx_packet_length = 0;
1110 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;
1113 case LWS_RXPS_04_FRAME_HDR_LEN64_7:
1114 #if defined __LP64__
1115 wsi->u.ws.rx_packet_length |= ((size_t)c) << 48;
1117 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;
1120 case LWS_RXPS_04_FRAME_HDR_LEN64_6:
1121 #if defined __LP64__
1122 wsi->u.ws.rx_packet_length |= ((size_t)c) << 40;
1124 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;
1127 case LWS_RXPS_04_FRAME_HDR_LEN64_5:
1128 #if defined __LP64__
1129 wsi->u.ws.rx_packet_length |= ((size_t)c) << 32;
1131 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;
1134 case LWS_RXPS_04_FRAME_HDR_LEN64_4:
1135 wsi->u.ws.rx_packet_length |= ((size_t)c) << 24;
1136 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3;
1139 case LWS_RXPS_04_FRAME_HDR_LEN64_3:
1140 wsi->u.ws.rx_packet_length |= ((size_t)c) << 16;
1141 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2;
1144 case LWS_RXPS_04_FRAME_HDR_LEN64_2:
1145 wsi->u.ws.rx_packet_length |= ((size_t)c) << 8;
1146 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1;
1149 case LWS_RXPS_04_FRAME_HDR_LEN64_1:
1150 wsi->u.ws.rx_packet_length |= ((size_t)c);
1151 if (wsi->u.ws.this_frame_masked)
1152 wsi->lws_rx_parse_state =
1153 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
1155 wsi->lws_rx_parse_state =
1156 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1159 case LWS_RXPS_07_COLLECT_FRAME_KEY_1:
1160 wsi->u.ws.mask[0] = c;
1162 wsi->u.ws.all_zero_nonce = 0;
1163 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_2;
1166 case LWS_RXPS_07_COLLECT_FRAME_KEY_2:
1167 wsi->u.ws.mask[1] = c;
1169 wsi->u.ws.all_zero_nonce = 0;
1170 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_3;
1173 case LWS_RXPS_07_COLLECT_FRAME_KEY_3:
1174 wsi->u.ws.mask[2] = c;
1176 wsi->u.ws.all_zero_nonce = 0;
1177 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_4;
1180 case LWS_RXPS_07_COLLECT_FRAME_KEY_4:
1181 wsi->u.ws.mask[3] = c;
1183 wsi->u.ws.all_zero_nonce = 0;
1184 wsi->lws_rx_parse_state =
1185 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1186 wsi->u.ws.mask_idx = 0;
1187 if (wsi->u.ws.rx_packet_length == 0) {
1188 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1194 case LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED:
1195 assert(wsi->u.ws.rx_ubuf);
1197 if (wsi->u.ws.rx_ubuf_head + LWS_PRE >=
1198 wsi->u.ws.rx_ubuf_alloc) {
1199 lwsl_err("Attempted overflow \n");
1202 if (wsi->u.ws.all_zero_nonce)
1203 wsi->u.ws.rx_ubuf[LWS_PRE +
1204 (wsi->u.ws.rx_ubuf_head++)] = c;
1206 wsi->u.ws.rx_ubuf[LWS_PRE +
1207 (wsi->u.ws.rx_ubuf_head++)] =
1209 (wsi->u.ws.mask_idx++) & 3];
1211 if (--wsi->u.ws.rx_packet_length == 0) {
1212 /* spill because we have the whole frame */
1213 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1218 * if there's no protocol max frame size given, we are
1219 * supposed to default to LWS_MAX_SOCKET_IO_BUF
1222 if (!wsi->protocol->rx_buffer_size &&
1223 wsi->u.ws.rx_ubuf_head !=
1224 LWS_MAX_SOCKET_IO_BUF)
1227 if (wsi->protocol->rx_buffer_size &&
1228 wsi->u.ws.rx_ubuf_head !=
1229 wsi->protocol->rx_buffer_size)
1232 /* spill because we filled our rx buffer */
1235 * is this frame a control packet we should take care of at this
1236 * layer? If so service it and hide it from the user callback
1239 lwsl_parser("spill on %s\n", wsi->protocol->name);
1241 switch (wsi->u.ws.opcode) {
1242 case LWSWSOPC_CLOSE:
1244 /* is this an acknowledgement of our close? */
1245 if (wsi->state == LWSS_AWAITING_CLOSE_ACK) {
1247 * fine he has told us he is closing too, let's
1250 lwsl_parser("seen client close ack\n");
1253 if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY)
1254 /* if he sends us 2 CLOSE, kill him */
1257 if (user_callback_handle_rxflow(
1258 wsi->protocol->callback, wsi,
1259 LWS_CALLBACK_WS_PEER_INITIATED_CLOSE,
1261 &wsi->u.ws.rx_ubuf[LWS_PRE],
1262 wsi->u.ws.rx_ubuf_head))
1265 lwsl_parser("server sees client close packet\n");
1266 wsi->state = LWSS_RETURNED_CLOSE_ALREADY;
1267 /* deal with the close packet contents as a PONG */
1268 wsi->u.ws.payload_is_close = 1;
1269 goto process_as_ping;
1272 lwsl_info("received %d byte ping, sending pong\n",
1273 wsi->u.ws.rx_ubuf_head);
1275 if (wsi->u.ws.ping_pending_flag) {
1277 * there is already a pending ping payload
1278 * we should just log and drop
1280 lwsl_parser("DROP PING since one pending\n");
1284 /* control packets can only be < 128 bytes long */
1285 if (wsi->u.ws.rx_ubuf_head > 128 - 3) {
1286 lwsl_parser("DROP PING payload too large\n");
1290 /* stash the pong payload */
1291 memcpy(wsi->u.ws.ping_payload_buf + LWS_PRE,
1292 &wsi->u.ws.rx_ubuf[LWS_PRE],
1293 wsi->u.ws.rx_ubuf_head);
1295 wsi->u.ws.ping_payload_len = wsi->u.ws.rx_ubuf_head;
1296 wsi->u.ws.ping_pending_flag = 1;
1298 /* get it sent as soon as possible */
1299 lws_callback_on_writable(wsi);
1301 wsi->u.ws.rx_ubuf_head = 0;
1305 lwsl_info("received pong\n");
1306 lwsl_hexdump(&wsi->u.ws.rx_ubuf[LWS_PRE],
1307 wsi->u.ws.rx_ubuf_head);
1310 callback_action = LWS_CALLBACK_RECEIVE_PONG;
1313 case LWSWSOPC_TEXT_FRAME:
1314 case LWSWSOPC_BINARY_FRAME:
1315 case LWSWSOPC_CONTINUATION:
1319 lwsl_parser("passing opc %x up to exts\n",
1322 * It's something special we can't understand here.
1323 * Pass the payload up to the extension's parsing
1327 eff_buf.token = &wsi->u.ws.rx_ubuf[LWS_PRE];
1328 eff_buf.token_len = wsi->u.ws.rx_ubuf_head;
1330 if (lws_ext_cb_active(wsi, LWS_EXT_CB_EXTENDED_PAYLOAD_RX,
1331 &eff_buf, 0) <= 0) /* not handle or fail */
1332 lwsl_ext("ext opc opcode 0x%x unknown\n",
1335 wsi->u.ws.rx_ubuf_head = 0;
1340 * No it's real payload, pass it up to the user callback.
1341 * It's nicely buffered with the pre-padding taken care of
1342 * so it can be sent straight out again using lws_write
1345 eff_buf.token = &wsi->u.ws.rx_ubuf[LWS_PRE];
1346 eff_buf.token_len = wsi->u.ws.rx_ubuf_head;
1349 lwsl_ext("%s: passing %d to ext\n", __func__, eff_buf.token_len);
1351 if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY ||
1352 wsi->state == LWSS_AWAITING_CLOSE_ACK)
1355 n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_RX, &eff_buf, 0);
1358 * we may rely on this to get RX, just drop connection
1360 wsi->socket_is_permanently_unusable = 1;
1364 if (rx_draining_ext && eff_buf.token_len == 0)
1367 if (n && eff_buf.token_len) {
1368 /* extension had more... main loop will come back */
1369 wsi->u.ws.rx_draining_ext = 1;
1370 wsi->u.ws.rx_draining_ext_list = pt->rx_draining_ext_list;
1371 pt->rx_draining_ext_list = wsi;
1374 if (eff_buf.token_len > 0 ||
1375 callback_action == LWS_CALLBACK_RECEIVE_PONG) {
1376 eff_buf.token[eff_buf.token_len] = '\0';
1378 if (wsi->protocol->callback) {
1380 if (callback_action == LWS_CALLBACK_RECEIVE_PONG)
1381 lwsl_info("Doing pong callback\n");
1383 ret = user_callback_handle_rxflow(
1384 wsi->protocol->callback,
1386 (enum lws_callback_reasons)callback_action,
1392 lwsl_err("No callback on payload spill!\n");
1396 wsi->u.ws.rx_ubuf_head = 0;
1404 lwsl_warn("Control frame with xtended length is illegal\n");
1405 /* kill the connection */
1411 * lws_remaining_packet_payload() - Bytes to come before "overall"
1412 * rx packet is complete
1413 * @wsi: Websocket instance (available from user callback)
1415 * This function is intended to be called from the callback if the
1416 * user code is interested in "complete packets" from the client.
1417 * libwebsockets just passes through payload as it comes and issues a buffer
1418 * additionally when it hits a built-in limit. The LWS_CALLBACK_RECEIVE
1419 * callback handler can use this API to find out if the buffer it has just
1420 * been given is the last piece of a "complete packet" from the client --
1421 * when that is the case lws_remaining_packet_payload() will return
1424 * Many protocols won't care becuse their packets are always small.
1428 lws_remaining_packet_payload(struct lws *wsi)
1430 return wsi->u.ws.rx_packet_length;