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, int autoservice)
66 struct allocated_headers *ah = wsi->u.hdr.ah;
67 struct lws_context_per_thread *pt;
68 struct lws_pollfd *pfd;
70 /* if we have the idea we're resetting 'our' ah, must be bound to one */
72 /* ah also concurs with ownership */
73 assert(ah->wsi == wsi);
75 /* init the ah to reflect no headers or data have appeared yet */
76 memset(ah->frag_index, 0, sizeof(ah->frag_index));
80 /* and reset the rx state */
84 /* since we will restart the ah, our new headers are not completed */
85 wsi->hdr_parsing_completed = 0;
88 * if we inherited pending rx (from socket adoption deferred
89 * processing), apply and free it.
91 if (wsi->u.hdr.preamble_rx) {
92 memcpy(ah->rx, wsi->u.hdr.preamble_rx,
93 wsi->u.hdr.preamble_rx_len);
94 ah->rxlen = wsi->u.hdr.preamble_rx_len;
95 lws_free_set_NULL(wsi->u.hdr.preamble_rx);
98 lwsl_notice("%s: calling service on readbuf ah\n", __func__);
100 pt = &wsi->context->pt[(int)wsi->tsi];
102 /* unlike a normal connect, we have the headers already
103 * (or the first part of them anyway)
105 pfd = &pt->fds[wsi->position_in_fds_table];
106 pfd->revents |= LWS_POLLIN;
107 lwsl_err("%s: calling service\n", __func__);
108 lws_service_fd_tsi(wsi->context, pfd, wsi->tsi);
113 int LWS_WARN_UNUSED_RESULT
114 lws_header_table_attach(struct lws *wsi, int autoservice)
116 struct lws_context *context = wsi->context;
117 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
118 struct lws_pollargs pa;
122 lwsl_info("%s: wsi %p: ah %p (tsi %d)\n", __func__, (void *)wsi,
123 (void *)wsi->u.hdr.ah, wsi->tsi);
125 /* if we are already bound to one, just clear it down */
127 lwsl_info("cleardown\n");
132 pwsi = &pt->ah_wait_list;
135 /* if already waiting on list, if no new ah just ret */
136 if (pt->ah_count_in_use ==
137 context->max_http_header_pool) {
138 lwsl_err("ah wl denied\n");
141 /* new ah.... remove ourselves from waiting list */
142 *pwsi = wsi->u.hdr.ah_wait_list; /* set our prev to our next */
143 wsi->u.hdr.ah_wait_list = NULL; /* no next any more */
144 pt->ah_wait_list_length--;
147 pwsi = &(*pwsi)->u.hdr.ah_wait_list;
150 * pool is all busy... add us to waiting list and return that we
151 * weren't able to deliver it right now
153 if (pt->ah_count_in_use == context->max_http_header_pool) {
154 lwsl_info("%s: adding %p to ah waiting list\n", __func__, wsi);
155 wsi->u.hdr.ah_wait_list = pt->ah_wait_list;
156 pt->ah_wait_list = wsi;
157 pt->ah_wait_list_length++;
159 /* we cannot accept input then */
161 _lws_change_pollfd(wsi, LWS_POLLIN, 0, &pa);
165 for (n = 0; n < context->max_http_header_pool; n++)
166 if (!pt->ah_pool[n].in_use)
169 /* if the count of in use said something free... */
170 assert(n != context->max_http_header_pool);
172 wsi->u.hdr.ah = &pt->ah_pool[n];
173 wsi->u.hdr.ah->in_use = 1;
174 pt->ah_pool[n].wsi = wsi; /* mark our owner */
175 pt->ah_count_in_use++;
177 _lws_change_pollfd(wsi, 0, LWS_POLLIN, &pa);
179 lwsl_info("%s: wsi %p: ah %p: count %d (on exit)\n", __func__,
180 (void *)wsi, (void *)wsi->u.hdr.ah, pt->ah_count_in_use);
185 lws_header_table_reset(wsi, autoservice);
186 time(&wsi->u.hdr.ah->assigned);
188 #ifndef LWS_NO_CLIENT
189 if (wsi->state == LWSS_CLIENT_UNCONNECTED)
190 lws_client_connect_via_info2(wsi);
201 int lws_header_table_detach(struct lws *wsi, int autoservice)
203 struct lws_context *context = wsi->context;
204 struct allocated_headers *ah = wsi->u.hdr.ah;
205 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
206 struct lws_pollargs pa;
210 lwsl_info("%s: wsi %p: ah %p (tsi=%d, count = %d)\n", __func__,
211 (void *)wsi, (void *)wsi->u.hdr.ah, wsi->tsi,
212 pt->ah_count_in_use);
214 if (wsi->u.hdr.preamble_rx)
215 lws_free_set_NULL(wsi->u.hdr.preamble_rx);
217 /* may not be detached while he still has unprocessed rx */
218 if (ah && ah->rxpos != ah->rxlen) {
219 lwsl_err("%s: %p: rxpos:%d, rxlen:%d\n", __func__, wsi,
220 ah->rxpos, ah->rxlen);
221 assert(ah->rxpos == ah->rxlen);
226 pwsi = &pt->ah_wait_list;
227 if (!ah) { /* remove from wait list if none attached */
230 lwsl_info("%s: wsi %p, remv wait\n",
232 *pwsi = wsi->u.hdr.ah_wait_list;
233 wsi->u.hdr.ah_wait_list = NULL;
234 pt->ah_wait_list_length--;
237 pwsi = &(*pwsi)->u.hdr.ah_wait_list;
239 /* no ah, not on list... no more business here */
242 /* we did have an ah attached */
244 if (now - wsi->u.hdr.ah->assigned > 3) {
246 * we're detaching the ah, but it was held an
247 * unreasonably long time
249 lwsl_notice("%s: wsi %p: ah held %ds, "
250 "ah.rxpos %d, ah.rxlen %d, mode/state %d %d,"
251 "wsi->more_rx_waiting %d\n", __func__, wsi,
252 (int)(now - wsi->u.hdr.ah->assigned),
253 ah->rxpos, ah->rxlen, wsi->mode, wsi->state,
254 wsi->more_rx_waiting);
257 /* if we think we're detaching one, there should be one in use */
258 assert(pt->ah_count_in_use > 0);
259 /* and this specific one should have been in use */
260 assert(wsi->u.hdr.ah->in_use);
261 wsi->u.hdr.ah = NULL;
262 ah->wsi = NULL; /* no owner */
264 /* oh there is nobody on the waiting list... leave it at that then */
267 pt->ah_count_in_use--;
272 /* somebody else on same tsi is waiting, give it to oldest guy */
274 lwsl_info("pt wait list %p\n", *pwsi);
275 while ((*pwsi)->u.hdr.ah_wait_list)
276 pwsi = &(*pwsi)->u.hdr.ah_wait_list;
279 lwsl_info("last wsi in wait list %p\n", wsi);
282 ah->wsi = wsi; /* new owner */
283 lws_header_table_reset(wsi, autoservice);
284 time(&wsi->u.hdr.ah->assigned);
286 assert(wsi->position_in_fds_table != -1);
288 lwsl_info("%s: Enabling %p POLLIN\n", __func__, wsi);
290 /* he has been stuck waiting for an ah, but now his wait is over,
293 _lws_change_pollfd(wsi, 0, LWS_POLLIN, &pa);
295 /* point prev guy to next guy in list instead */
296 *pwsi = wsi->u.hdr.ah_wait_list;
297 /* the guy who got one is out of the list */
298 wsi->u.hdr.ah_wait_list = NULL;
299 pt->ah_wait_list_length--;
301 #ifndef LWS_NO_CLIENT
302 if (wsi->state == LWSS_CLIENT_UNCONNECTED)
303 lws_client_connect_via_info2(wsi);
306 assert(!!pt->ah_wait_list_length == !!(int)(long)pt->ah_wait_list);
314 * lws_hdr_fragment_length: report length of a single fragment of a header
315 * The returned length does not include the space for a
318 * @wsi: websocket connection
319 * @h: which header index we are interested in
320 * @frag_idx: which fragment of @h we want to get the length of
324 lws_hdr_fragment_length(struct lws *wsi, enum lws_token_indexes h, int frag_idx)
328 n = wsi->u.hdr.ah->frag_index[h];
333 return wsi->u.hdr.ah->frags[n].len;
334 n = wsi->u.hdr.ah->frags[n].nfrag;
335 } while (frag_idx-- && n);
341 * lws_hdr_total_length: report length of all fragments of a header totalled up
342 * The returned length does not include the space for a
345 * @wsi: websocket connection
346 * @h: which header index we are interested in
349 LWS_VISIBLE int lws_hdr_total_length(struct lws *wsi, enum lws_token_indexes h)
354 n = wsi->u.hdr.ah->frag_index[h];
358 len += wsi->u.hdr.ah->frags[n].len;
359 n = wsi->u.hdr.ah->frags[n].nfrag;
366 * lws_hdr_copy_fragment: copy a single fragment of the given header to a buffer
367 * The buffer length @len must include space for an additional
368 * terminating '\0', or it will fail returning -1.
369 * If the requested fragment index is not present, it fails
372 * @wsi: websocket connection
373 * @dst: destination buffer
374 * @len: length of destination buffer
375 * @h: which header index we are interested in
376 * @frag_index: which fragment of @h we want to copy
379 LWS_VISIBLE int lws_hdr_copy_fragment(struct lws *wsi, char *dst, int len,
380 enum lws_token_indexes h, int frag_idx)
383 int f = wsi->u.hdr.ah->frag_index[h];
388 while (n < frag_idx) {
389 f = wsi->u.hdr.ah->frags[f].nfrag;
395 if (wsi->u.hdr.ah->frags[f].len >= len)
398 memcpy(dst, wsi->u.hdr.ah->data + wsi->u.hdr.ah->frags[f].offset,
399 wsi->u.hdr.ah->frags[f].len);
400 dst[wsi->u.hdr.ah->frags[f].len] = '\0';
402 return wsi->u.hdr.ah->frags[f].len;
406 * lws_hdr_copy: copy a single fragment of the given header to a buffer
407 * The buffer length @len must include space for an additional
408 * terminating '\0', or it will fail returning -1.
410 * @wsi: websocket connection
411 * @dst: destination buffer
412 * @len: length of destination buffer
413 * @h: which header index we are interested in
416 LWS_VISIBLE int lws_hdr_copy(struct lws *wsi, char *dst, int len,
417 enum lws_token_indexes h)
419 int toklen = lws_hdr_total_length(wsi, h);
425 n = wsi->u.hdr.ah->frag_index[h];
430 strcpy(dst, &wsi->u.hdr.ah->data[wsi->u.hdr.ah->frags[n].offset]);
431 dst += wsi->u.hdr.ah->frags[n].len;
432 n = wsi->u.hdr.ah->frags[n].nfrag;
438 char *lws_hdr_simple_ptr(struct lws *wsi, enum lws_token_indexes h)
442 n = wsi->u.hdr.ah->frag_index[h];
446 return wsi->u.hdr.ah->data + wsi->u.hdr.ah->frags[n].offset;
449 int LWS_WARN_UNUSED_RESULT
450 lws_pos_in_bounds(struct lws *wsi)
452 if (wsi->u.hdr.ah->pos < wsi->context->max_http_header_data)
455 if (wsi->u.hdr.ah->pos == wsi->context->max_http_header_data) {
456 lwsl_err("Ran out of header data space\n");
461 * with these tests everywhere, it should never be able to exceed
462 * the limit, only meet the limit
465 lwsl_err("%s: pos %d, limit %d\n", __func__, wsi->u.hdr.ah->pos,
466 wsi->context->max_http_header_data);
472 int LWS_WARN_UNUSED_RESULT
473 lws_hdr_simple_create(struct lws *wsi, enum lws_token_indexes h, const char *s)
475 wsi->u.hdr.ah->nfrag++;
476 if (wsi->u.hdr.ah->nfrag == ARRAY_SIZE(wsi->u.hdr.ah->frags)) {
477 lwsl_warn("More hdr frags than we can deal with, dropping\n");
481 wsi->u.hdr.ah->frag_index[h] = wsi->u.hdr.ah->nfrag;
483 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].offset = wsi->u.hdr.ah->pos;
484 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len = 0;
485 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].nfrag = 0;
488 if (lws_pos_in_bounds(wsi))
491 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = *s;
493 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len++;
499 static signed char char_to_hex(const char c)
501 if (c >= '0' && c <= '9')
504 if (c >= 'a' && c <= 'f')
507 if (c >= 'A' && c <= 'F')
513 static int LWS_WARN_UNUSED_RESULT
514 issue_char(struct lws *wsi, unsigned char c)
516 unsigned short frag_len;
518 if (lws_pos_in_bounds(wsi))
521 frag_len = wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len;
523 * If we haven't hit the token limit, just copy the character into
526 if (frag_len < wsi->u.hdr.current_token_limit) {
527 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = c;
529 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len++;
533 /* Insert a null character when we *hit* the limit: */
534 if (frag_len == wsi->u.hdr.current_token_limit) {
535 if (lws_pos_in_bounds(wsi))
537 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = '\0';
538 lwsl_warn("header %i exceeds limit %d\n",
539 wsi->u.hdr.parser_state,
540 wsi->u.hdr.current_token_limit);
546 int LWS_WARN_UNUSED_RESULT
547 lws_parse(struct lws *wsi, unsigned char c)
549 static const unsigned char methods[] = {
552 WSI_TOKEN_OPTIONS_URI,
555 WSI_TOKEN_DELETE_URI,
557 struct allocated_headers *ah = wsi->u.hdr.ah;
558 struct lws_context *context = wsi->context;
559 unsigned int n, m, enc = 0;
561 assert(wsi->u.hdr.ah);
563 switch (wsi->u.hdr.parser_state) {
566 lwsl_parser("WSI_TOK_(%d) '%c'\n", wsi->u.hdr.parser_state, c);
568 /* collect into malloc'd buffers */
569 /* optional initial space swallow */
570 if (!ah->frags[ah->frag_index[wsi->u.hdr.parser_state]].len &&
574 for (m = 0; m < ARRAY_SIZE(methods); m++)
575 if (wsi->u.hdr.parser_state == methods[m])
577 if (m == ARRAY_SIZE(methods))
578 /* it was not any of the methods */
581 /* special URI processing... end at space */
584 /* enforce starting with / */
585 if (!ah->frags[ah->nfrag].len)
586 if (issue_char(wsi, '/') < 0)
589 /* begin parsing HTTP version: */
590 if (issue_char(wsi, '\0') < 0)
592 wsi->u.hdr.parser_state = WSI_TOKEN_HTTP;
596 /* special URI processing... convert %xx */
598 switch (wsi->u.hdr.ues) {
601 wsi->u.hdr.ues = URIES_SEEN_PERCENT;
605 case URIES_SEEN_PERCENT:
606 if (char_to_hex(c) < 0) {
608 if (issue_char(wsi, '%') < 0)
610 wsi->u.hdr.ues = URIES_IDLE;
611 /* continue on to assess c */
614 wsi->u.hdr.esc_stash = c;
615 wsi->u.hdr.ues = URIES_SEEN_PERCENT_H1;
618 case URIES_SEEN_PERCENT_H1:
619 if (char_to_hex(c) < 0) {
621 if (issue_char(wsi, '%') < 0)
623 wsi->u.hdr.ues = URIES_IDLE;
624 /* regurgitate + assess */
625 if (lws_parse(wsi, wsi->u.hdr.esc_stash) < 0)
627 /* continue on to assess c */
630 c = (char_to_hex(wsi->u.hdr.esc_stash) << 4) |
633 wsi->u.hdr.ues = URIES_IDLE;
638 * special URI processing...
639 * convert /.. or /... or /../ etc to /
641 * convert // or /// etc to /
642 * leave /.dir or whatever alone
645 switch (wsi->u.hdr.ups) {
649 /* genuine delimiter */
650 if ((c == '&' || c == ';') && !enc) {
651 if (issue_char(wsi, c) < 0)
653 /* swallow the terminator */
654 ah->frags[ah->nfrag].len--;
655 /* link to next fragment */
656 ah->frags[ah->nfrag].nfrag = ah->nfrag + 1;
658 if (ah->nfrag >= ARRAY_SIZE(ah->frags))
660 /* start next fragment after the & */
661 wsi->u.hdr.post_literal_equal = 0;
662 ah->frags[ah->nfrag].offset = ah->pos;
663 ah->frags[ah->nfrag].len = 0;
664 ah->frags[ah->nfrag].nfrag = 0;
667 /* uriencoded = in the name part, disallow */
668 if (c == '=' && enc && !wsi->u.hdr.post_literal_equal)
671 /* after the real =, we don't care how many = */
672 if (c == '=' && !enc)
673 wsi->u.hdr.post_literal_equal = 1;
676 if (c == '+' && !enc)
678 /* issue the first / always */
679 if (c == '/' && !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS])
680 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
682 case URIPS_SEEN_SLASH:
683 /* swallow subsequent slashes */
686 /* track and swallow the first . after / */
688 wsi->u.hdr.ups = URIPS_SEEN_SLASH_DOT;
691 wsi->u.hdr.ups = URIPS_IDLE;
693 case URIPS_SEEN_SLASH_DOT:
694 /* swallow second . */
697 * back up one dir level if possible
698 * safe against header fragmentation because
699 * the method URI can only be in 1 fragment
701 if (ah->frags[ah->nfrag].len > 2) {
703 ah->frags[ah->nfrag].len--;
706 ah->frags[ah->nfrag].len--;
707 } while (ah->frags[ah->nfrag].len > 1 &&
708 ah->data[ah->pos] != '/');
710 wsi->u.hdr.ups = URIPS_SEEN_SLASH_DOT_DOT;
713 /* change /./ to / */
715 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
718 /* it was like /.dir ... regurgitate the . */
719 wsi->u.hdr.ups = URIPS_IDLE;
720 if (issue_char(wsi, '.') < 0)
724 case URIPS_SEEN_SLASH_DOT_DOT:
725 /* swallow prior .. chars and any subsequent . */
728 /* last issued was /, so another / == // */
731 /* last we issued was / so SEEN_SLASH */
732 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
736 if (c == '?' && !enc &&
737 !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS]) { /* start of URI arguments */
738 /* seal off uri header */
739 if (issue_char(wsi, '\0') < 0)
742 /* move to using WSI_TOKEN_HTTP_URI_ARGS */
744 if (ah->nfrag >= ARRAY_SIZE(ah->frags))
746 ah->frags[ah->nfrag].offset = ah->pos;
747 ah->frags[ah->nfrag].len = 0;
748 ah->frags[ah->nfrag].nfrag = 0;
750 wsi->u.hdr.post_literal_equal = 0;
751 ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS] = ah->nfrag;
752 wsi->u.hdr.ups = URIPS_IDLE;
759 if (wsi->u.hdr.parser_state != WSI_TOKEN_CHALLENGE &&
762 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
766 n = issue_char(wsi, c);
770 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
773 /* per-protocol end of headers management */
775 if (wsi->u.hdr.parser_state == WSI_TOKEN_CHALLENGE)
776 goto set_parsing_complete;
779 /* collecting and checking a name part */
780 case WSI_TOKEN_NAME_PART:
781 lwsl_parser("WSI_TOKEN_NAME_PART '%c' (mode=%d)\n", c, wsi->mode);
783 wsi->u.hdr.lextable_pos =
784 lextable_decode(wsi->u.hdr.lextable_pos, c);
786 * Server needs to look out for unknown methods...
788 if (wsi->u.hdr.lextable_pos < 0 &&
789 wsi->mode == LWSCM_HTTP_SERVING) {
790 /* this is not a header we know about */
791 for (m = 0; m < ARRAY_SIZE(methods); m++)
792 if (ah->frag_index[methods[m]]) {
794 * already had the method, no idea what
795 * this crap from the client is, ignore
797 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
801 * hm it's an unknown http method from a client in fact,
804 if (m == ARRAY_SIZE(methods)) {
805 lwsl_info("Unknown method - dropping\n");
811 * ...otherwise for a client, let him ignore unknown headers
812 * coming from the server
814 if (wsi->u.hdr.lextable_pos < 0) {
815 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
819 if (lextable[wsi->u.hdr.lextable_pos] < FAIL_CHAR) {
822 n = ((unsigned int)lextable[wsi->u.hdr.lextable_pos] << 8) |
823 lextable[wsi->u.hdr.lextable_pos + 1];
825 lwsl_parser("known hdr %d\n", n);
826 for (m = 0; m < ARRAY_SIZE(methods); m++)
827 if (n == methods[m] &&
828 ah->frag_index[methods[m]]) {
829 lwsl_warn("Duplicated method\n");
834 * WSORIGIN is protocol equiv to ORIGIN,
835 * JWebSocket likes to send it, map to ORIGIN
837 if (n == WSI_TOKEN_SWORIGIN)
838 n = WSI_TOKEN_ORIGIN;
840 wsi->u.hdr.parser_state = (enum lws_token_indexes)
841 (WSI_TOKEN_GET_URI + n);
843 if (context->token_limits)
844 wsi->u.hdr.current_token_limit =
845 context->token_limits->token_limit[
846 wsi->u.hdr.parser_state];
848 wsi->u.hdr.current_token_limit =
849 wsi->context->max_http_header_data;
851 if (wsi->u.hdr.parser_state == WSI_TOKEN_CHALLENGE)
852 goto set_parsing_complete;
861 if (ah->nfrag == ARRAY_SIZE(ah->frags)) {
862 lwsl_warn("More hdr frags than we can deal with\n");
866 ah->frags[ah->nfrag].offset = ah->pos;
867 ah->frags[ah->nfrag].len = 0;
868 ah->frags[ah->nfrag].nfrag = 0;
870 n = ah->frag_index[wsi->u.hdr.parser_state];
871 if (!n) { /* first fragment */
872 ah->frag_index[wsi->u.hdr.parser_state] = ah->nfrag;
876 while (ah->frags[n].nfrag)
877 n = ah->frags[n].nfrag;
878 ah->frags[n].nfrag = ah->nfrag;
880 if (issue_char(wsi, ' ') < 0)
884 /* skipping arg part of a name we didn't recognize */
885 case WSI_TOKEN_SKIPPING:
886 lwsl_parser("WSI_TOKEN_SKIPPING '%c'\n", c);
889 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
892 case WSI_TOKEN_SKIPPING_SAW_CR:
893 lwsl_parser("WSI_TOKEN_SKIPPING_SAW_CR '%c'\n", c);
895 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
896 wsi->u.hdr.lextable_pos = 0;
898 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
900 /* we're done, ignore anything else */
902 case WSI_PARSING_COMPLETE:
903 lwsl_parser("WSI_PARSING_COMPLETE '%c'\n", c);
909 set_parsing_complete:
911 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
912 if (lws_hdr_total_length(wsi, WSI_TOKEN_VERSION))
913 wsi->ietf_spec_revision =
914 atoi(lws_hdr_simple_ptr(wsi, WSI_TOKEN_VERSION));
916 lwsl_parser("v%02d hdrs completed\n", wsi->ietf_spec_revision);
918 wsi->u.hdr.parser_state = WSI_PARSING_COMPLETE;
919 wsi->hdr_parsing_completed = 1;
926 * lws_frame_is_binary: true if the current frame was sent in binary mode
928 * @wsi: the connection we are inquiring about
930 * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
931 * it's interested to see if the frame it's dealing with was sent in binary
935 LWS_VISIBLE int lws_frame_is_binary(struct lws *wsi)
937 return wsi->u.ws.frame_is_binary;
941 lws_rx_sm(struct lws *wsi, unsigned char c)
943 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
944 int callback_action = LWS_CALLBACK_RECEIVE;
945 int ret = 0, n, rx_draining_ext = 0;
946 struct lws_tokens eff_buf;
948 if (wsi->socket_is_permanently_unusable)
951 switch (wsi->lws_rx_parse_state) {
953 if (wsi->u.ws.rx_draining_ext) {
954 struct lws **w = &pt->rx_draining_ext_list;
956 eff_buf.token = NULL;
957 eff_buf.token_len = 0;
958 wsi->u.ws.rx_draining_ext = 0;
959 /* remove us from context draining ext list */
962 *w = wsi->u.ws.rx_draining_ext_list;
965 w = &((*w)->u.ws.rx_draining_ext_list);
967 wsi->u.ws.rx_draining_ext_list = NULL;
969 lwsl_err("%s: doing draining flow\n", __func__);
971 goto drain_extension;
973 switch (wsi->ietf_spec_revision) {
976 * no prepended frame key any more
978 wsi->u.ws.all_zero_nonce = 1;
982 lwsl_warn("lws_rx_sm: unknown spec version %d\n",
983 wsi->ietf_spec_revision);
987 case LWS_RXPS_04_mask_1:
988 wsi->u.ws.mask[1] = c;
990 wsi->u.ws.all_zero_nonce = 0;
991 wsi->lws_rx_parse_state = LWS_RXPS_04_mask_2;
993 case LWS_RXPS_04_mask_2:
994 wsi->u.ws.mask[2] = c;
996 wsi->u.ws.all_zero_nonce = 0;
997 wsi->lws_rx_parse_state = LWS_RXPS_04_mask_3;
999 case LWS_RXPS_04_mask_3:
1000 wsi->u.ws.mask[3] = c;
1002 wsi->u.ws.all_zero_nonce = 0;
1005 * start from the zero'th byte in the XOR key buffer since
1006 * this is the start of a frame with a new key
1009 wsi->u.ws.mask_idx = 0;
1011 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_1;
1015 * 04 logical framing from the spec (all this is masked when incoming
1016 * and has to be unmasked)
1018 * We ignore the possibility of extension data because we don't
1019 * negotiate any extensions at the moment.
1022 * 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
1023 * +-+-+-+-+-------+-+-------------+-------------------------------+
1024 * |F|R|R|R| opcode|R| Payload len | Extended payload length |
1025 * |I|S|S|S| (4) |S| (7) | (16/63) |
1026 * |N|V|V|V| |V| | (if payload len==126/127) |
1028 * +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
1029 * | Extended payload length continued, if payload len == 127 |
1030 * + - - - - - - - - - - - - - - - +-------------------------------+
1031 * | | Extension data |
1032 * +-------------------------------+ - - - - - - - - - - - - - - - +
1034 * +---------------------------------------------------------------+
1035 * : Application data :
1036 * +---------------------------------------------------------------+
1038 * We pass payload through to userland as soon as we get it, ignoring
1039 * FIN. It's up to userland to buffer it up if it wants to see a
1040 * whole unfragmented block of the original size (which may be up to
1044 case LWS_RXPS_04_FRAME_HDR_1:
1047 wsi->u.ws.opcode = c & 0xf;
1048 wsi->u.ws.rsv = c & 0x70;
1049 wsi->u.ws.final = !!((c >> 7) & 1);
1051 switch (wsi->u.ws.opcode) {
1052 case LWSWSOPC_TEXT_FRAME:
1053 case LWSWSOPC_BINARY_FRAME:
1054 wsi->u.ws.rsv_first_msg = (c & 0x70);
1055 wsi->u.ws.frame_is_binary =
1056 wsi->u.ws.opcode == LWSWSOPC_BINARY_FRAME;
1068 lwsl_info("illegal opcode\n");
1071 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;
1074 case LWS_RXPS_04_FRAME_HDR_LEN:
1076 wsi->u.ws.this_frame_masked = !!(c & 0x80);
1080 /* control frames are not allowed to have big lengths */
1081 if (wsi->u.ws.opcode & 8)
1082 goto illegal_ctl_length;
1084 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;
1087 /* control frames are not allowed to have big lengths */
1088 if (wsi->u.ws.opcode & 8)
1089 goto illegal_ctl_length;
1091 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;
1094 wsi->u.ws.rx_packet_length = c & 0x7f;
1095 if (wsi->u.ws.this_frame_masked)
1096 wsi->lws_rx_parse_state =
1097 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
1099 if (wsi->u.ws.rx_packet_length)
1100 wsi->lws_rx_parse_state =
1101 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1103 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1110 case LWS_RXPS_04_FRAME_HDR_LEN16_2:
1111 wsi->u.ws.rx_packet_length = c << 8;
1112 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1;
1115 case LWS_RXPS_04_FRAME_HDR_LEN16_1:
1116 wsi->u.ws.rx_packet_length |= c;
1117 if (wsi->u.ws.this_frame_masked)
1118 wsi->lws_rx_parse_state =
1119 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
1121 wsi->lws_rx_parse_state =
1122 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1125 case LWS_RXPS_04_FRAME_HDR_LEN64_8:
1127 lwsl_warn("b63 of length must be zero\n");
1128 /* kill the connection */
1131 #if defined __LP64__
1132 wsi->u.ws.rx_packet_length = ((size_t)c) << 56;
1134 wsi->u.ws.rx_packet_length = 0;
1136 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;
1139 case LWS_RXPS_04_FRAME_HDR_LEN64_7:
1140 #if defined __LP64__
1141 wsi->u.ws.rx_packet_length |= ((size_t)c) << 48;
1143 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;
1146 case LWS_RXPS_04_FRAME_HDR_LEN64_6:
1147 #if defined __LP64__
1148 wsi->u.ws.rx_packet_length |= ((size_t)c) << 40;
1150 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;
1153 case LWS_RXPS_04_FRAME_HDR_LEN64_5:
1154 #if defined __LP64__
1155 wsi->u.ws.rx_packet_length |= ((size_t)c) << 32;
1157 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;
1160 case LWS_RXPS_04_FRAME_HDR_LEN64_4:
1161 wsi->u.ws.rx_packet_length |= ((size_t)c) << 24;
1162 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3;
1165 case LWS_RXPS_04_FRAME_HDR_LEN64_3:
1166 wsi->u.ws.rx_packet_length |= ((size_t)c) << 16;
1167 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2;
1170 case LWS_RXPS_04_FRAME_HDR_LEN64_2:
1171 wsi->u.ws.rx_packet_length |= ((size_t)c) << 8;
1172 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1;
1175 case LWS_RXPS_04_FRAME_HDR_LEN64_1:
1176 wsi->u.ws.rx_packet_length |= ((size_t)c);
1177 if (wsi->u.ws.this_frame_masked)
1178 wsi->lws_rx_parse_state =
1179 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
1181 wsi->lws_rx_parse_state =
1182 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1185 case LWS_RXPS_07_COLLECT_FRAME_KEY_1:
1186 wsi->u.ws.mask[0] = c;
1188 wsi->u.ws.all_zero_nonce = 0;
1189 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_2;
1192 case LWS_RXPS_07_COLLECT_FRAME_KEY_2:
1193 wsi->u.ws.mask[1] = c;
1195 wsi->u.ws.all_zero_nonce = 0;
1196 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_3;
1199 case LWS_RXPS_07_COLLECT_FRAME_KEY_3:
1200 wsi->u.ws.mask[2] = c;
1202 wsi->u.ws.all_zero_nonce = 0;
1203 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_4;
1206 case LWS_RXPS_07_COLLECT_FRAME_KEY_4:
1207 wsi->u.ws.mask[3] = c;
1209 wsi->u.ws.all_zero_nonce = 0;
1210 wsi->lws_rx_parse_state =
1211 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1212 wsi->u.ws.mask_idx = 0;
1213 if (wsi->u.ws.rx_packet_length == 0) {
1214 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1220 case LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED:
1221 assert(wsi->u.ws.rx_ubuf);
1223 if (wsi->u.ws.rx_ubuf_head + LWS_PRE >=
1224 wsi->u.ws.rx_ubuf_alloc) {
1225 lwsl_err("Attempted overflow \n");
1228 if (wsi->u.ws.all_zero_nonce)
1229 wsi->u.ws.rx_ubuf[LWS_PRE +
1230 (wsi->u.ws.rx_ubuf_head++)] = c;
1232 wsi->u.ws.rx_ubuf[LWS_PRE +
1233 (wsi->u.ws.rx_ubuf_head++)] =
1235 (wsi->u.ws.mask_idx++) & 3];
1237 if (--wsi->u.ws.rx_packet_length == 0) {
1238 /* spill because we have the whole frame */
1239 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1244 * if there's no protocol max frame size given, we are
1245 * supposed to default to LWS_MAX_SOCKET_IO_BUF
1248 if (!wsi->protocol->rx_buffer_size &&
1249 wsi->u.ws.rx_ubuf_head !=
1250 LWS_MAX_SOCKET_IO_BUF)
1253 if (wsi->protocol->rx_buffer_size &&
1254 wsi->u.ws.rx_ubuf_head !=
1255 wsi->protocol->rx_buffer_size)
1258 /* spill because we filled our rx buffer */
1261 * is this frame a control packet we should take care of at this
1262 * layer? If so service it and hide it from the user callback
1265 lwsl_parser("spill on %s\n", wsi->protocol->name);
1267 switch (wsi->u.ws.opcode) {
1268 case LWSWSOPC_CLOSE:
1270 /* is this an acknowledgement of our close? */
1271 if (wsi->state == LWSS_AWAITING_CLOSE_ACK) {
1273 * fine he has told us he is closing too, let's
1276 lwsl_parser("seen client close ack\n");
1279 if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY)
1280 /* if he sends us 2 CLOSE, kill him */
1283 if (user_callback_handle_rxflow(
1284 wsi->protocol->callback, wsi,
1285 LWS_CALLBACK_WS_PEER_INITIATED_CLOSE,
1287 &wsi->u.ws.rx_ubuf[LWS_PRE],
1288 wsi->u.ws.rx_ubuf_head))
1291 lwsl_parser("server sees client close packet\n");
1292 wsi->state = LWSS_RETURNED_CLOSE_ALREADY;
1293 /* deal with the close packet contents as a PONG */
1294 wsi->u.ws.payload_is_close = 1;
1295 goto process_as_ping;
1298 lwsl_info("received %d byte ping, sending pong\n",
1299 wsi->u.ws.rx_ubuf_head);
1301 if (wsi->u.ws.ping_pending_flag) {
1303 * there is already a pending ping payload
1304 * we should just log and drop
1306 lwsl_parser("DROP PING since one pending\n");
1310 /* control packets can only be < 128 bytes long */
1311 if (wsi->u.ws.rx_ubuf_head > 128 - 3) {
1312 lwsl_parser("DROP PING payload too large\n");
1316 /* stash the pong payload */
1317 memcpy(wsi->u.ws.ping_payload_buf + LWS_PRE,
1318 &wsi->u.ws.rx_ubuf[LWS_PRE],
1319 wsi->u.ws.rx_ubuf_head);
1321 wsi->u.ws.ping_payload_len = wsi->u.ws.rx_ubuf_head;
1322 wsi->u.ws.ping_pending_flag = 1;
1324 /* get it sent as soon as possible */
1325 lws_callback_on_writable(wsi);
1327 wsi->u.ws.rx_ubuf_head = 0;
1331 lwsl_info("received pong\n");
1332 lwsl_hexdump(&wsi->u.ws.rx_ubuf[LWS_PRE],
1333 wsi->u.ws.rx_ubuf_head);
1336 callback_action = LWS_CALLBACK_RECEIVE_PONG;
1339 case LWSWSOPC_TEXT_FRAME:
1340 case LWSWSOPC_BINARY_FRAME:
1341 case LWSWSOPC_CONTINUATION:
1345 lwsl_parser("passing opc %x up to exts\n",
1348 * It's something special we can't understand here.
1349 * Pass the payload up to the extension's parsing
1353 eff_buf.token = &wsi->u.ws.rx_ubuf[LWS_PRE];
1354 eff_buf.token_len = wsi->u.ws.rx_ubuf_head;
1356 if (lws_ext_cb_active(wsi, LWS_EXT_CB_EXTENDED_PAYLOAD_RX,
1358 /* not handle or fail */
1359 lwsl_ext("ext opc opcode 0x%x unknown\n",
1362 wsi->u.ws.rx_ubuf_head = 0;
1367 * No it's real payload, pass it up to the user callback.
1368 * It's nicely buffered with the pre-padding taken care of
1369 * so it can be sent straight out again using lws_write
1372 eff_buf.token = &wsi->u.ws.rx_ubuf[LWS_PRE];
1373 eff_buf.token_len = wsi->u.ws.rx_ubuf_head;
1376 lwsl_ext("%s: passing %d to ext\n", __func__, eff_buf.token_len);
1378 if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY ||
1379 wsi->state == LWSS_AWAITING_CLOSE_ACK)
1382 n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_RX, &eff_buf, 0);
1385 * we may rely on this to get RX, just drop connection
1387 wsi->socket_is_permanently_unusable = 1;
1391 if (rx_draining_ext && eff_buf.token_len == 0)
1394 if (n && eff_buf.token_len) {
1395 /* extension had more... main loop will come back */
1396 wsi->u.ws.rx_draining_ext = 1;
1397 wsi->u.ws.rx_draining_ext_list = pt->rx_draining_ext_list;
1398 pt->rx_draining_ext_list = wsi;
1401 if (eff_buf.token_len > 0 ||
1402 callback_action == LWS_CALLBACK_RECEIVE_PONG) {
1403 eff_buf.token[eff_buf.token_len] = '\0';
1405 if (wsi->protocol->callback) {
1407 if (callback_action == LWS_CALLBACK_RECEIVE_PONG)
1408 lwsl_info("Doing pong callback\n");
1410 ret = user_callback_handle_rxflow(
1411 wsi->protocol->callback,
1413 (enum lws_callback_reasons)callback_action,
1419 lwsl_err("No callback on payload spill!\n");
1423 wsi->u.ws.rx_ubuf_head = 0;
1431 lwsl_warn("Control frame with xtended length is illegal\n");
1432 /* kill the connection */
1438 * lws_remaining_packet_payload() - Bytes to come before "overall"
1439 * rx packet is complete
1440 * @wsi: Websocket instance (available from user callback)
1442 * This function is intended to be called from the callback if the
1443 * user code is interested in "complete packets" from the client.
1444 * libwebsockets just passes through payload as it comes and issues a buffer
1445 * additionally when it hits a built-in limit. The LWS_CALLBACK_RECEIVE
1446 * callback handler can use this API to find out if the buffer it has just
1447 * been given is the last piece of a "complete packet" from the client --
1448 * when that is the case lws_remaining_packet_payload() will return
1451 * Many protocols won't care becuse their packets are always small.
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 = LWS_MAX_SOCKET_IO_BUF;
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;