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);
64 _lws_header_table_reset(struct allocated_headers *ah)
66 /* init the ah to reflect no headers or data have appeared yet */
67 memset(ah->frag_index, 0, sizeof(ah->frag_index));
70 ah->http_response = 0;
73 // doesn't scrub the ah rxbuffer by default, parent must do if needed
76 lws_header_table_reset(struct lws *wsi, int autoservice)
78 struct allocated_headers *ah = wsi->u.hdr.ah;
79 struct lws_context_per_thread *pt;
80 struct lws_pollfd *pfd;
82 /* if we have the idea we're resetting 'our' ah, must be bound to one */
84 /* ah also concurs with ownership */
85 assert(ah->wsi == wsi);
87 _lws_header_table_reset(ah);
89 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
90 wsi->u.hdr.lextable_pos = 0;
92 /* since we will restart the ah, our new headers are not completed */
93 wsi->hdr_parsing_completed = 0;
96 * if we inherited pending rx (from socket adoption deferred
97 * processing), apply and free it.
99 if (wsi->u.hdr.preamble_rx) {
100 memcpy(ah->rx, wsi->u.hdr.preamble_rx,
101 wsi->u.hdr.preamble_rx_len);
102 ah->rxlen = wsi->u.hdr.preamble_rx_len;
103 lws_free_set_NULL(wsi->u.hdr.preamble_rx);
106 lwsl_notice("%s: calling service on readbuf ah\n", __func__);
108 pt = &wsi->context->pt[(int)wsi->tsi];
110 /* unlike a normal connect, we have the headers already
111 * (or the first part of them anyway)
113 pfd = &pt->fds[wsi->position_in_fds_table];
114 pfd->revents |= LWS_POLLIN;
115 lwsl_err("%s: calling service\n", __func__);
116 lws_service_fd_tsi(wsi->context, pfd, wsi->tsi);
121 int LWS_WARN_UNUSED_RESULT
122 lws_header_table_attach(struct lws *wsi, int autoservice)
124 struct lws_context *context = wsi->context;
125 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
126 struct lws_pollargs pa;
130 lwsl_info("%s: wsi %p: ah %p (tsi %d, count = %d) in\n", __func__, (void *)wsi,
131 (void *)wsi->u.hdr.ah, wsi->tsi, pt->ah_count_in_use);
133 /* if we are already bound to one, just clear it down */
135 lwsl_info("cleardown\n");
140 pwsi = &pt->ah_wait_list;
143 /* if already waiting on list, if no new ah just ret */
144 if (pt->ah_count_in_use ==
145 context->max_http_header_pool) {
146 lwsl_notice("%s: no free ah to attach\n", __func__);
149 /* new ah.... remove ourselves from waiting list */
150 *pwsi = wsi->u.hdr.ah_wait_list; /* set our prev to our next */
151 wsi->u.hdr.ah_wait_list = NULL; /* no next any more */
152 pt->ah_wait_list_length--;
155 pwsi = &(*pwsi)->u.hdr.ah_wait_list;
158 * pool is all busy... add us to waiting list and return that we
159 * weren't able to deliver it right now
161 if (pt->ah_count_in_use == context->max_http_header_pool) {
162 lwsl_info("%s: adding %p to ah waiting list\n", __func__, wsi);
163 wsi->u.hdr.ah_wait_list = pt->ah_wait_list;
164 pt->ah_wait_list = wsi;
165 pt->ah_wait_list_length++;
167 /* we cannot accept input then */
169 _lws_change_pollfd(wsi, LWS_POLLIN, 0, &pa);
173 for (n = 0; n < context->max_http_header_pool; n++)
174 if (!pt->ah_pool[n].in_use)
177 /* if the count of in use said something free... */
178 assert(n != context->max_http_header_pool);
180 wsi->u.hdr.ah = &pt->ah_pool[n];
181 wsi->u.hdr.ah->in_use = 1;
182 pt->ah_pool[n].wsi = wsi; /* mark our owner */
183 pt->ah_count_in_use++;
185 _lws_change_pollfd(wsi, 0, LWS_POLLIN, &pa);
187 lwsl_info("%s: did attach wsi %p: ah %p: count %d (on exit)\n", __func__,
188 (void *)wsi, (void *)wsi->u.hdr.ah, pt->ah_count_in_use);
194 /* and reset the rx state */
195 wsi->u.hdr.ah->rxpos = 0;
196 wsi->u.hdr.ah->rxlen = 0;
198 lws_header_table_reset(wsi, autoservice);
199 time(&wsi->u.hdr.ah->assigned);
201 #ifndef LWS_NO_CLIENT
202 if (wsi->state == LWSS_CLIENT_UNCONNECTED)
203 if (!lws_client_connect_via_info2(wsi))
204 /* our client connect has failed, the wsi
219 lws_header_table_force_to_detachable_state(struct lws *wsi)
222 wsi->u.hdr.ah->rxpos = -1;
223 wsi->u.hdr.ah->rxlen = -1;
224 wsi->hdr_parsing_completed = 1;
229 lws_header_table_is_in_detachable_state(struct lws *wsi)
231 struct allocated_headers *ah = wsi->u.hdr.ah;
233 return ah && ah->rxpos == ah->rxlen && wsi->hdr_parsing_completed;
236 int lws_header_table_detach(struct lws *wsi, int autoservice)
238 struct lws_context *context = wsi->context;
239 struct allocated_headers *ah = wsi->u.hdr.ah;
240 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
241 struct lws_pollargs pa;
248 lwsl_info("%s: wsi %p: ah %p (tsi=%d, count = %d)\n", __func__,
249 (void *)wsi, (void *)ah, wsi->tsi,
250 pt->ah_count_in_use);
252 if (wsi->u.hdr.preamble_rx)
253 lws_free_set_NULL(wsi->u.hdr.preamble_rx);
255 /* may not be detached while he still has unprocessed rx */
256 if (!lws_header_table_is_in_detachable_state(wsi)) {
257 lwsl_err("%s: %p: CANNOT DETACH rxpos:%d, rxlen:%d, wsi->hdr_parsing_completed = %d\n", __func__, wsi,
258 ah->rxpos, ah->rxlen, wsi->hdr_parsing_completed);
264 pwsi = &pt->ah_wait_list;
265 if (!ah) { /* remove from wait list if none attached */
268 lwsl_info("%s: wsi %p, remv wait\n",
270 *pwsi = wsi->u.hdr.ah_wait_list;
271 wsi->u.hdr.ah_wait_list = NULL;
272 pt->ah_wait_list_length--;
275 pwsi = &(*pwsi)->u.hdr.ah_wait_list;
277 /* no ah, not on list... no more business here */
280 /* we did have an ah attached */
282 if (ah->assigned && now - ah->assigned > 3) {
284 * we're detaching the ah, but it was held an
285 * unreasonably long time
287 lwsl_notice("%s: wsi %p: ah held %ds, "
288 "ah.rxpos %d, ah.rxlen %d, mode/state %d %d,"
289 "wsi->more_rx_waiting %d\n", __func__, wsi,
290 (int)(now - ah->assigned),
291 ah->rxpos, ah->rxlen, wsi->mode, wsi->state,
292 wsi->more_rx_waiting);
297 /* if we think we're detaching one, there should be one in use */
298 assert(pt->ah_count_in_use > 0);
299 /* and this specific one should have been in use */
301 wsi->u.hdr.ah = NULL;
302 ah->wsi = NULL; /* no owner */
304 /* oh there is nobody on the waiting list... leave it at that then */
307 pt->ah_count_in_use--;
312 /* somebody else on same tsi is waiting, give it to oldest guy */
314 lwsl_info("pt wait list %p\n", *pwsi);
315 while ((*pwsi)->u.hdr.ah_wait_list)
316 pwsi = &(*pwsi)->u.hdr.ah_wait_list;
319 lwsl_info("last wsi in wait list %p\n", wsi);
322 ah->wsi = wsi; /* new owner */
323 /* and reset the rx state */
326 lws_header_table_reset(wsi, autoservice);
327 time(&wsi->u.hdr.ah->assigned);
329 /* clients acquire the ah and then insert themselves in fds table... */
330 if (wsi->position_in_fds_table != -1) {
331 lwsl_info("%s: Enabling %p POLLIN\n", __func__, wsi);
333 /* he has been stuck waiting for an ah, but now his wait is over,
336 _lws_change_pollfd(wsi, 0, LWS_POLLIN, &pa);
339 /* point prev guy to next guy in list instead */
340 *pwsi = wsi->u.hdr.ah_wait_list;
341 /* the guy who got one is out of the list */
342 wsi->u.hdr.ah_wait_list = NULL;
343 pt->ah_wait_list_length--;
345 #ifndef LWS_NO_CLIENT
346 if (wsi->state == LWSS_CLIENT_UNCONNECTED) {
349 if (!lws_client_connect_via_info2(wsi)) {
350 /* our client connect has failed, the wsi
360 assert(!!pt->ah_wait_list_length == !!(lws_intptr_t)pt->ah_wait_list);
362 lwsl_info("%s: wsi %p: ah %p (tsi=%d, count = %d)\n", __func__,
363 (void *)wsi, (void *)ah, wsi->tsi,
364 pt->ah_count_in_use);
371 lws_hdr_fragment_length(struct lws *wsi, enum lws_token_indexes h, int frag_idx)
375 n = wsi->u.hdr.ah->frag_index[h];
380 return wsi->u.hdr.ah->frags[n].len;
381 n = wsi->u.hdr.ah->frags[n].nfrag;
382 } while (frag_idx-- && n);
387 LWS_VISIBLE int lws_hdr_total_length(struct lws *wsi, enum lws_token_indexes h)
392 n = wsi->u.hdr.ah->frag_index[h];
396 len += wsi->u.hdr.ah->frags[n].len;
397 n = wsi->u.hdr.ah->frags[n].nfrag;
403 LWS_VISIBLE int lws_hdr_copy_fragment(struct lws *wsi, char *dst, int len,
404 enum lws_token_indexes h, int frag_idx)
407 int f = wsi->u.hdr.ah->frag_index[h];
412 while (n < frag_idx) {
413 f = wsi->u.hdr.ah->frags[f].nfrag;
419 if (wsi->u.hdr.ah->frags[f].len >= len)
422 memcpy(dst, wsi->u.hdr.ah->data + wsi->u.hdr.ah->frags[f].offset,
423 wsi->u.hdr.ah->frags[f].len);
424 dst[wsi->u.hdr.ah->frags[f].len] = '\0';
426 return wsi->u.hdr.ah->frags[f].len;
429 LWS_VISIBLE int lws_hdr_copy(struct lws *wsi, char *dst, int len,
430 enum lws_token_indexes h)
432 int toklen = lws_hdr_total_length(wsi, h);
438 n = wsi->u.hdr.ah->frag_index[h];
443 strcpy(dst, &wsi->u.hdr.ah->data[wsi->u.hdr.ah->frags[n].offset]);
444 dst += wsi->u.hdr.ah->frags[n].len;
445 n = wsi->u.hdr.ah->frags[n].nfrag;
451 char *lws_hdr_simple_ptr(struct lws *wsi, enum lws_token_indexes h)
455 n = wsi->u.hdr.ah->frag_index[h];
459 return wsi->u.hdr.ah->data + wsi->u.hdr.ah->frags[n].offset;
462 int LWS_WARN_UNUSED_RESULT
463 lws_pos_in_bounds(struct lws *wsi)
465 if (wsi->u.hdr.ah->pos < (unsigned int)wsi->context->max_http_header_data)
468 if (wsi->u.hdr.ah->pos == wsi->context->max_http_header_data) {
469 lwsl_err("Ran out of header data space\n");
474 * with these tests everywhere, it should never be able to exceed
475 * the limit, only meet the limit
478 lwsl_err("%s: pos %d, limit %d\n", __func__, wsi->u.hdr.ah->pos,
479 wsi->context->max_http_header_data);
485 int LWS_WARN_UNUSED_RESULT
486 lws_hdr_simple_create(struct lws *wsi, enum lws_token_indexes h, const char *s)
488 wsi->u.hdr.ah->nfrag++;
489 if (wsi->u.hdr.ah->nfrag == ARRAY_SIZE(wsi->u.hdr.ah->frags)) {
490 lwsl_warn("More hdr frags than we can deal with, dropping\n");
494 wsi->u.hdr.ah->frag_index[h] = wsi->u.hdr.ah->nfrag;
496 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].offset = wsi->u.hdr.ah->pos;
497 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len = 0;
498 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].nfrag = 0;
501 if (lws_pos_in_bounds(wsi))
504 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = *s;
506 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len++;
512 signed char char_to_hex(const char c)
514 if (c >= '0' && c <= '9')
517 if (c >= 'a' && c <= 'f')
520 if (c >= 'A' && c <= 'F')
526 static int LWS_WARN_UNUSED_RESULT
527 issue_char(struct lws *wsi, unsigned char c)
529 unsigned short frag_len;
531 if (lws_pos_in_bounds(wsi))
534 frag_len = wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len;
536 * If we haven't hit the token limit, just copy the character into
539 if (frag_len < wsi->u.hdr.current_token_limit) {
540 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = c;
542 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len++;
546 /* Insert a null character when we *hit* the limit: */
547 if (frag_len == wsi->u.hdr.current_token_limit) {
548 if (lws_pos_in_bounds(wsi))
550 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = '\0';
551 lwsl_warn("header %i exceeds limit %d\n",
552 wsi->u.hdr.parser_state,
553 wsi->u.hdr.current_token_limit);
559 int LWS_WARN_UNUSED_RESULT
560 lws_parse(struct lws *wsi, unsigned char c)
562 static const unsigned char methods[] = {
565 WSI_TOKEN_OPTIONS_URI,
568 WSI_TOKEN_DELETE_URI,
571 struct allocated_headers *ah = wsi->u.hdr.ah;
572 struct lws_context *context = wsi->context;
573 unsigned int n, m, enc = 0;
575 assert(wsi->u.hdr.ah);
577 switch (wsi->u.hdr.parser_state) {
580 lwsl_parser("WSI_TOK_(%d) '%c'\n", wsi->u.hdr.parser_state, c);
582 /* collect into malloc'd buffers */
583 /* optional initial space swallow */
584 if (!ah->frags[ah->frag_index[wsi->u.hdr.parser_state]].len &&
588 for (m = 0; m < ARRAY_SIZE(methods); m++)
589 if (wsi->u.hdr.parser_state == methods[m])
591 if (m == ARRAY_SIZE(methods))
592 /* it was not any of the methods */
595 /* special URI processing... end at space */
598 /* enforce starting with / */
599 if (!ah->frags[ah->nfrag].len)
600 if (issue_char(wsi, '/') < 0)
603 if (wsi->u.hdr.ups == URIPS_SEEN_SLASH_DOT_DOT) {
605 * back up one dir level if possible
606 * safe against header fragmentation because
607 * the method URI can only be in 1 fragment
609 if (ah->frags[ah->nfrag].len > 2) {
611 ah->frags[ah->nfrag].len--;
614 ah->frags[ah->nfrag].len--;
615 } while (ah->frags[ah->nfrag].len > 1 &&
616 ah->data[ah->pos] != '/');
620 /* begin parsing HTTP version: */
621 if (issue_char(wsi, '\0') < 0)
623 wsi->u.hdr.parser_state = WSI_TOKEN_HTTP;
629 * special URI processing... convert %xx
632 switch (wsi->u.hdr.ues) {
635 wsi->u.hdr.ues = URIES_SEEN_PERCENT;
639 case URIES_SEEN_PERCENT:
640 if (char_to_hex(c) < 0)
641 /* illegal post-% char */
644 wsi->u.hdr.esc_stash = c;
645 wsi->u.hdr.ues = URIES_SEEN_PERCENT_H1;
648 case URIES_SEEN_PERCENT_H1:
649 if (char_to_hex(c) < 0)
650 /* illegal post-% char */
653 c = (char_to_hex(wsi->u.hdr.esc_stash) << 4) |
656 wsi->u.hdr.ues = URIES_IDLE;
662 * special URI processing...
663 * convert /.. or /... or /../ etc to /
665 * convert // or /// etc to /
666 * leave /.dir or whatever alone
669 switch (wsi->u.hdr.ups) {
673 /* genuine delimiter */
674 if ((c == '&' || c == ';') && !enc) {
675 if (issue_char(wsi, c) < 0)
677 /* swallow the terminator */
678 ah->frags[ah->nfrag].len--;
679 /* link to next fragment */
680 ah->frags[ah->nfrag].nfrag = ah->nfrag + 1;
682 if (ah->nfrag >= ARRAY_SIZE(ah->frags))
684 /* start next fragment after the & */
685 wsi->u.hdr.post_literal_equal = 0;
686 ah->frags[ah->nfrag].offset = ah->pos;
687 ah->frags[ah->nfrag].len = 0;
688 ah->frags[ah->nfrag].nfrag = 0;
691 /* uriencoded = in the name part, disallow */
692 if (c == '=' && enc &&
693 ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS] &&
694 !wsi->u.hdr.post_literal_equal)
697 /* after the real =, we don't care how many = */
698 if (c == '=' && !enc)
699 wsi->u.hdr.post_literal_equal = 1;
702 if (c == '+' && !enc)
704 /* issue the first / always */
705 if (c == '/' && !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS])
706 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
708 case URIPS_SEEN_SLASH:
709 /* swallow subsequent slashes */
712 /* track and swallow the first . after / */
714 wsi->u.hdr.ups = URIPS_SEEN_SLASH_DOT;
717 wsi->u.hdr.ups = URIPS_IDLE;
719 case URIPS_SEEN_SLASH_DOT:
720 /* swallow second . */
722 wsi->u.hdr.ups = URIPS_SEEN_SLASH_DOT_DOT;
725 /* change /./ to / */
727 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
730 /* it was like /.dir ... regurgitate the . */
731 wsi->u.hdr.ups = URIPS_IDLE;
732 if (issue_char(wsi, '.') < 0)
736 case URIPS_SEEN_SLASH_DOT_DOT:
738 /* /../ or /..[End of URI] --> backup to last / */
739 if (c == '/' || c == '?') {
741 * back up one dir level if possible
742 * safe against header fragmentation because
743 * the method URI can only be in 1 fragment
745 if (ah->frags[ah->nfrag].len > 2) {
747 ah->frags[ah->nfrag].len--;
750 ah->frags[ah->nfrag].len--;
751 } while (ah->frags[ah->nfrag].len > 1 &&
752 ah->data[ah->pos] != '/');
754 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
755 if (ah->frags[ah->nfrag].len > 1)
760 /* /..[^/] ... regurgitate and allow */
762 if (issue_char(wsi, '.') < 0)
764 if (issue_char(wsi, '.') < 0)
766 wsi->u.hdr.ups = URIPS_IDLE;
770 if (c == '?' && !enc &&
771 !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS]) { /* start of URI arguments */
772 if (wsi->u.hdr.ues != URIES_IDLE)
775 /* seal off uri header */
776 if (issue_char(wsi, '\0') < 0)
779 /* move to using WSI_TOKEN_HTTP_URI_ARGS */
781 if (ah->nfrag >= ARRAY_SIZE(ah->frags))
783 ah->frags[ah->nfrag].offset = ah->pos;
784 ah->frags[ah->nfrag].len = 0;
785 ah->frags[ah->nfrag].nfrag = 0;
787 wsi->u.hdr.post_literal_equal = 0;
788 ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS] = ah->nfrag;
789 wsi->u.hdr.ups = URIPS_IDLE;
795 if (wsi->u.hdr.parser_state != WSI_TOKEN_CHALLENGE &&
797 if (wsi->u.hdr.ues != URIES_IDLE)
801 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
805 n = issue_char(wsi, c);
809 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
812 /* per-protocol end of headers management */
814 if (wsi->u.hdr.parser_state == WSI_TOKEN_CHALLENGE)
815 goto set_parsing_complete;
818 /* collecting and checking a name part */
819 case WSI_TOKEN_NAME_PART:
820 lwsl_parser("WSI_TOKEN_NAME_PART '%c' (mode=%d)\n", c, wsi->mode);
822 wsi->u.hdr.lextable_pos =
823 lextable_decode(wsi->u.hdr.lextable_pos, c);
825 * Server needs to look out for unknown methods...
827 if (wsi->u.hdr.lextable_pos < 0 &&
828 wsi->mode == LWSCM_HTTP_SERVING) {
829 /* this is not a header we know about */
830 for (m = 0; m < ARRAY_SIZE(methods); m++)
831 if (ah->frag_index[methods[m]]) {
833 * already had the method, no idea what
834 * this crap from the client is, ignore
836 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
840 * hm it's an unknown http method from a client in fact,
841 * it cannot be valid http
843 if (m == ARRAY_SIZE(methods)) {
845 * are we set up to accept raw in these cases?
847 if (lws_check_opt(wsi->vhost->options,
848 LWS_SERVER_OPTION_FALLBACK_TO_RAW))
849 return 2; /* transition to raw */
851 lwsl_info("Unknown method - dropping\n");
857 * ...otherwise for a client, let him ignore unknown headers
858 * coming from the server
860 if (wsi->u.hdr.lextable_pos < 0) {
861 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
865 if (lextable[wsi->u.hdr.lextable_pos] < FAIL_CHAR) {
868 n = ((unsigned int)lextable[wsi->u.hdr.lextable_pos] << 8) |
869 lextable[wsi->u.hdr.lextable_pos + 1];
871 lwsl_parser("known hdr %d\n", n);
872 for (m = 0; m < ARRAY_SIZE(methods); m++)
873 if (n == methods[m] &&
874 ah->frag_index[methods[m]]) {
875 lwsl_warn("Duplicated method\n");
880 * WSORIGIN is protocol equiv to ORIGIN,
881 * JWebSocket likes to send it, map to ORIGIN
883 if (n == WSI_TOKEN_SWORIGIN)
884 n = WSI_TOKEN_ORIGIN;
886 wsi->u.hdr.parser_state = (enum lws_token_indexes)
887 (WSI_TOKEN_GET_URI + n);
889 if (context->token_limits)
890 wsi->u.hdr.current_token_limit =
891 context->token_limits->token_limit[
892 wsi->u.hdr.parser_state];
894 wsi->u.hdr.current_token_limit =
895 wsi->context->max_http_header_data;
897 if (wsi->u.hdr.parser_state == WSI_TOKEN_CHALLENGE)
898 goto set_parsing_complete;
907 if (ah->nfrag == ARRAY_SIZE(ah->frags)) {
908 lwsl_warn("More hdr frags than we can deal with\n");
912 ah->frags[ah->nfrag].offset = ah->pos;
913 ah->frags[ah->nfrag].len = 0;
914 ah->frags[ah->nfrag].nfrag = 0;
916 n = ah->frag_index[wsi->u.hdr.parser_state];
917 if (!n) { /* first fragment */
918 ah->frag_index[wsi->u.hdr.parser_state] = ah->nfrag;
922 while (ah->frags[n].nfrag)
923 n = ah->frags[n].nfrag;
924 ah->frags[n].nfrag = ah->nfrag;
926 if (issue_char(wsi, ' ') < 0)
930 /* skipping arg part of a name we didn't recognize */
931 case WSI_TOKEN_SKIPPING:
932 lwsl_parser("WSI_TOKEN_SKIPPING '%c'\n", c);
935 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
938 case WSI_TOKEN_SKIPPING_SAW_CR:
939 lwsl_parser("WSI_TOKEN_SKIPPING_SAW_CR '%c'\n", c);
940 if (wsi->u.hdr.ues != URIES_IDLE)
943 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
944 wsi->u.hdr.lextable_pos = 0;
946 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
948 /* we're done, ignore anything else */
950 case WSI_PARSING_COMPLETE:
951 lwsl_parser("WSI_PARSING_COMPLETE '%c'\n", c);
957 set_parsing_complete:
958 if (wsi->u.hdr.ues != URIES_IDLE)
960 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
961 if (lws_hdr_total_length(wsi, WSI_TOKEN_VERSION))
962 wsi->ietf_spec_revision =
963 atoi(lws_hdr_simple_ptr(wsi, WSI_TOKEN_VERSION));
965 lwsl_parser("v%02d hdrs completed\n", wsi->ietf_spec_revision);
967 wsi->u.hdr.parser_state = WSI_PARSING_COMPLETE;
968 wsi->hdr_parsing_completed = 1;
973 lwsl_notice(" forbidding on uri sanitation\n");
974 lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
978 LWS_VISIBLE int lws_frame_is_binary(struct lws *wsi)
980 return wsi->u.ws.frame_is_binary;
984 lws_add_wsi_to_draining_ext_list(struct lws *wsi)
986 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
988 if (wsi->u.ws.rx_draining_ext)
991 lwsl_ext("%s: RX EXT DRAINING: Adding to list\n", __func__);
993 wsi->u.ws.rx_draining_ext = 1;
994 wsi->u.ws.rx_draining_ext_list = pt->rx_draining_ext_list;
995 pt->rx_draining_ext_list = wsi;
999 lws_remove_wsi_from_draining_ext_list(struct lws *wsi)
1001 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
1002 struct lws **w = &pt->rx_draining_ext_list;
1004 if (!wsi->u.ws.rx_draining_ext)
1007 lwsl_ext("%s: RX EXT DRAINING: Removing from list\n", __func__);
1009 wsi->u.ws.rx_draining_ext = 0;
1011 /* remove us from context draining ext list */
1014 /* if us, point it instead to who we were pointing to */
1015 *w = wsi->u.ws.rx_draining_ext_list;
1018 w = &((*w)->u.ws.rx_draining_ext_list);
1020 wsi->u.ws.rx_draining_ext_list = NULL;
1024 * client-parser.c: lws_client_rx_sm() needs to be roughly kept in
1025 * sync with changes here, esp related to ext draining
1029 lws_rx_sm(struct lws *wsi, unsigned char c)
1031 int callback_action = LWS_CALLBACK_RECEIVE;
1032 int ret = 0, n, rx_draining_ext = 0;
1033 struct lws_tokens eff_buf;
1035 eff_buf.token = NULL;
1036 eff_buf.token_len = 0;
1037 if (wsi->socket_is_permanently_unusable)
1040 switch (wsi->lws_rx_parse_state) {
1042 if (wsi->u.ws.rx_draining_ext) {
1043 eff_buf.token = NULL;
1044 eff_buf.token_len = 0;
1045 lws_remove_wsi_from_draining_ext_list(wsi);
1046 rx_draining_ext = 1;
1047 lwsl_debug("%s: doing draining flow\n", __func__);
1049 goto drain_extension;
1051 switch (wsi->ietf_spec_revision) {
1054 * no prepended frame key any more
1056 wsi->u.ws.all_zero_nonce = 1;
1060 lwsl_warn("lws_rx_sm: unknown spec version %d\n",
1061 wsi->ietf_spec_revision);
1065 case LWS_RXPS_04_mask_1:
1066 wsi->u.ws.mask[1] = c;
1068 wsi->u.ws.all_zero_nonce = 0;
1069 wsi->lws_rx_parse_state = LWS_RXPS_04_mask_2;
1071 case LWS_RXPS_04_mask_2:
1072 wsi->u.ws.mask[2] = c;
1074 wsi->u.ws.all_zero_nonce = 0;
1075 wsi->lws_rx_parse_state = LWS_RXPS_04_mask_3;
1077 case LWS_RXPS_04_mask_3:
1078 wsi->u.ws.mask[3] = c;
1080 wsi->u.ws.all_zero_nonce = 0;
1083 * start from the zero'th byte in the XOR key buffer since
1084 * this is the start of a frame with a new key
1087 wsi->u.ws.mask_idx = 0;
1089 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_1;
1093 * 04 logical framing from the spec (all this is masked when incoming
1094 * and has to be unmasked)
1096 * We ignore the possibility of extension data because we don't
1097 * negotiate any extensions at the moment.
1100 * 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
1101 * +-+-+-+-+-------+-+-------------+-------------------------------+
1102 * |F|R|R|R| opcode|R| Payload len | Extended payload length |
1103 * |I|S|S|S| (4) |S| (7) | (16/63) |
1104 * |N|V|V|V| |V| | (if payload len==126/127) |
1106 * +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
1107 * | Extended payload length continued, if payload len == 127 |
1108 * + - - - - - - - - - - - - - - - +-------------------------------+
1109 * | | Extension data |
1110 * +-------------------------------+ - - - - - - - - - - - - - - - +
1112 * +---------------------------------------------------------------+
1113 * : Application data :
1114 * +---------------------------------------------------------------+
1116 * We pass payload through to userland as soon as we get it, ignoring
1117 * FIN. It's up to userland to buffer it up if it wants to see a
1118 * whole unfragmented block of the original size (which may be up to
1122 case LWS_RXPS_04_FRAME_HDR_1:
1125 wsi->u.ws.opcode = c & 0xf;
1126 wsi->u.ws.rsv = c & 0x70;
1127 wsi->u.ws.final = !!((c >> 7) & 1);
1129 switch (wsi->u.ws.opcode) {
1130 case LWSWSOPC_TEXT_FRAME:
1131 case LWSWSOPC_BINARY_FRAME:
1132 wsi->u.ws.rsv_first_msg = (c & 0x70);
1133 wsi->u.ws.frame_is_binary =
1134 wsi->u.ws.opcode == LWSWSOPC_BINARY_FRAME;
1146 lwsl_info("illegal opcode\n");
1149 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;
1152 case LWS_RXPS_04_FRAME_HDR_LEN:
1154 wsi->u.ws.this_frame_masked = !!(c & 0x80);
1158 /* control frames are not allowed to have big lengths */
1159 if (wsi->u.ws.opcode & 8)
1160 goto illegal_ctl_length;
1162 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;
1165 /* control frames are not allowed to have big lengths */
1166 if (wsi->u.ws.opcode & 8)
1167 goto illegal_ctl_length;
1169 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;
1172 wsi->u.ws.rx_packet_length = c & 0x7f;
1173 if (wsi->u.ws.this_frame_masked)
1174 wsi->lws_rx_parse_state =
1175 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
1177 if (wsi->u.ws.rx_packet_length)
1178 wsi->lws_rx_parse_state =
1179 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1181 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1188 case LWS_RXPS_04_FRAME_HDR_LEN16_2:
1189 wsi->u.ws.rx_packet_length = c << 8;
1190 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1;
1193 case LWS_RXPS_04_FRAME_HDR_LEN16_1:
1194 wsi->u.ws.rx_packet_length |= c;
1195 if (wsi->u.ws.this_frame_masked)
1196 wsi->lws_rx_parse_state =
1197 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
1199 wsi->lws_rx_parse_state =
1200 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1203 case LWS_RXPS_04_FRAME_HDR_LEN64_8:
1205 lwsl_warn("b63 of length must be zero\n");
1206 /* kill the connection */
1209 #if defined __LP64__
1210 wsi->u.ws.rx_packet_length = ((size_t)c) << 56;
1212 wsi->u.ws.rx_packet_length = 0;
1214 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;
1217 case LWS_RXPS_04_FRAME_HDR_LEN64_7:
1218 #if defined __LP64__
1219 wsi->u.ws.rx_packet_length |= ((size_t)c) << 48;
1221 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;
1224 case LWS_RXPS_04_FRAME_HDR_LEN64_6:
1225 #if defined __LP64__
1226 wsi->u.ws.rx_packet_length |= ((size_t)c) << 40;
1228 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;
1231 case LWS_RXPS_04_FRAME_HDR_LEN64_5:
1232 #if defined __LP64__
1233 wsi->u.ws.rx_packet_length |= ((size_t)c) << 32;
1235 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;
1238 case LWS_RXPS_04_FRAME_HDR_LEN64_4:
1239 wsi->u.ws.rx_packet_length |= ((size_t)c) << 24;
1240 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3;
1243 case LWS_RXPS_04_FRAME_HDR_LEN64_3:
1244 wsi->u.ws.rx_packet_length |= ((size_t)c) << 16;
1245 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2;
1248 case LWS_RXPS_04_FRAME_HDR_LEN64_2:
1249 wsi->u.ws.rx_packet_length |= ((size_t)c) << 8;
1250 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1;
1253 case LWS_RXPS_04_FRAME_HDR_LEN64_1:
1254 wsi->u.ws.rx_packet_length |= ((size_t)c);
1255 if (wsi->u.ws.this_frame_masked)
1256 wsi->lws_rx_parse_state =
1257 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
1259 wsi->lws_rx_parse_state =
1260 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1263 case LWS_RXPS_07_COLLECT_FRAME_KEY_1:
1264 wsi->u.ws.mask[0] = c;
1266 wsi->u.ws.all_zero_nonce = 0;
1267 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_2;
1270 case LWS_RXPS_07_COLLECT_FRAME_KEY_2:
1271 wsi->u.ws.mask[1] = c;
1273 wsi->u.ws.all_zero_nonce = 0;
1274 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_3;
1277 case LWS_RXPS_07_COLLECT_FRAME_KEY_3:
1278 wsi->u.ws.mask[2] = c;
1280 wsi->u.ws.all_zero_nonce = 0;
1281 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_4;
1284 case LWS_RXPS_07_COLLECT_FRAME_KEY_4:
1285 wsi->u.ws.mask[3] = c;
1287 wsi->u.ws.all_zero_nonce = 0;
1288 wsi->lws_rx_parse_state =
1289 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1290 wsi->u.ws.mask_idx = 0;
1291 if (wsi->u.ws.rx_packet_length == 0) {
1292 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1298 case LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED:
1299 assert(wsi->u.ws.rx_ubuf);
1301 if (wsi->u.ws.rx_draining_ext)
1302 goto drain_extension;
1304 if (wsi->u.ws.rx_ubuf_head + LWS_PRE >=
1305 wsi->u.ws.rx_ubuf_alloc) {
1306 lwsl_err("Attempted overflow \n");
1309 if (wsi->u.ws.all_zero_nonce)
1310 wsi->u.ws.rx_ubuf[LWS_PRE +
1311 (wsi->u.ws.rx_ubuf_head++)] = c;
1313 wsi->u.ws.rx_ubuf[LWS_PRE +
1314 (wsi->u.ws.rx_ubuf_head++)] =
1316 (wsi->u.ws.mask_idx++) & 3];
1318 if (--wsi->u.ws.rx_packet_length == 0) {
1319 /* spill because we have the whole frame */
1320 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1325 * if there's no protocol max frame size given, we are
1326 * supposed to default to context->pt_serv_buf_size
1329 if (!wsi->protocol->rx_buffer_size &&
1330 wsi->u.ws.rx_ubuf_head != wsi->context->pt_serv_buf_size)
1333 if (wsi->protocol->rx_buffer_size &&
1334 wsi->u.ws.rx_ubuf_head !=
1335 wsi->protocol->rx_buffer_size)
1338 /* spill because we filled our rx buffer */
1341 * is this frame a control packet we should take care of at this
1342 * layer? If so service it and hide it from the user callback
1345 lwsl_parser("spill on %s\n", wsi->protocol->name);
1347 switch (wsi->u.ws.opcode) {
1348 case LWSWSOPC_CLOSE:
1350 /* is this an acknowledgement of our close? */
1351 if (wsi->state == LWSS_AWAITING_CLOSE_ACK) {
1353 * fine he has told us he is closing too, let's
1356 lwsl_parser("seen client close ack\n");
1359 if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY)
1360 /* if he sends us 2 CLOSE, kill him */
1363 if (lws_partial_buffered(wsi)) {
1365 * if we're in the middle of something,
1366 * we can't do a normal close response and
1367 * have to just close our end.
1369 wsi->socket_is_permanently_unusable = 1;
1370 lwsl_parser("Closing on peer close due to Pending tx\n");
1374 if (user_callback_handle_rxflow(
1375 wsi->protocol->callback, wsi,
1376 LWS_CALLBACK_WS_PEER_INITIATED_CLOSE,
1378 &wsi->u.ws.rx_ubuf[LWS_PRE],
1379 wsi->u.ws.rx_ubuf_head))
1382 lwsl_parser("server sees client close packet\n");
1383 wsi->state = LWSS_RETURNED_CLOSE_ALREADY;
1384 /* deal with the close packet contents as a PONG */
1385 wsi->u.ws.payload_is_close = 1;
1386 goto process_as_ping;
1389 lwsl_info("received %d byte ping, sending pong\n",
1390 wsi->u.ws.rx_ubuf_head);
1392 if (wsi->u.ws.ping_pending_flag) {
1394 * there is already a pending ping payload
1395 * we should just log and drop
1397 lwsl_parser("DROP PING since one pending\n");
1401 /* control packets can only be < 128 bytes long */
1402 if (wsi->u.ws.rx_ubuf_head > 128 - 3) {
1403 lwsl_parser("DROP PING payload too large\n");
1407 /* stash the pong payload */
1408 memcpy(wsi->u.ws.ping_payload_buf + LWS_PRE,
1409 &wsi->u.ws.rx_ubuf[LWS_PRE],
1410 wsi->u.ws.rx_ubuf_head);
1412 wsi->u.ws.ping_payload_len = wsi->u.ws.rx_ubuf_head;
1413 wsi->u.ws.ping_pending_flag = 1;
1415 /* get it sent as soon as possible */
1416 lws_callback_on_writable(wsi);
1418 wsi->u.ws.rx_ubuf_head = 0;
1422 lwsl_info("received pong\n");
1423 lwsl_hexdump(&wsi->u.ws.rx_ubuf[LWS_PRE],
1424 wsi->u.ws.rx_ubuf_head);
1426 if (wsi->pending_timeout == PENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG) {
1427 lwsl_info("received expected PONG on wsi %p\n", wsi);
1428 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1432 callback_action = LWS_CALLBACK_RECEIVE_PONG;
1435 case LWSWSOPC_TEXT_FRAME:
1436 case LWSWSOPC_BINARY_FRAME:
1437 case LWSWSOPC_CONTINUATION:
1441 lwsl_parser("passing opc %x up to exts\n",
1444 * It's something special we can't understand here.
1445 * Pass the payload up to the extension's parsing
1449 eff_buf.token = &wsi->u.ws.rx_ubuf[LWS_PRE];
1450 eff_buf.token_len = wsi->u.ws.rx_ubuf_head;
1452 if (lws_ext_cb_active(wsi, LWS_EXT_CB_EXTENDED_PAYLOAD_RX,
1454 /* not handle or fail */
1455 lwsl_ext("ext opc opcode 0x%x unknown\n",
1458 wsi->u.ws.rx_ubuf_head = 0;
1463 * No it's real payload, pass it up to the user callback.
1464 * It's nicely buffered with the pre-padding taken care of
1465 * so it can be sent straight out again using lws_write
1468 eff_buf.token = &wsi->u.ws.rx_ubuf[LWS_PRE];
1469 eff_buf.token_len = wsi->u.ws.rx_ubuf_head;
1472 lwsl_ext("%s: passing %d to ext\n", __func__, eff_buf.token_len);
1474 if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY ||
1475 wsi->state == LWSS_AWAITING_CLOSE_ACK)
1478 n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_RX, &eff_buf, 0);
1479 /* eff_buf may be pointing somewhere completely different now,
1484 * we may rely on this to get RX, just drop connection
1486 wsi->socket_is_permanently_unusable = 1;
1490 if (rx_draining_ext && eff_buf.token_len == 0)
1493 if (n && eff_buf.token_len) {
1494 /* extension had more... main loop will come back */
1495 lws_add_wsi_to_draining_ext_list(wsi);
1497 lws_remove_wsi_from_draining_ext_list(wsi);
1499 if (eff_buf.token_len > 0 ||
1500 callback_action == LWS_CALLBACK_RECEIVE_PONG) {
1501 eff_buf.token[eff_buf.token_len] = '\0';
1503 if (wsi->protocol->callback) {
1505 if (callback_action == LWS_CALLBACK_RECEIVE_PONG)
1506 lwsl_info("Doing pong callback\n");
1508 ret = user_callback_handle_rxflow(
1509 wsi->protocol->callback,
1511 (enum lws_callback_reasons)callback_action,
1517 lwsl_err("No callback on payload spill!\n");
1521 wsi->u.ws.rx_ubuf_head = 0;
1529 lwsl_warn("Control frame with xtended length is illegal\n");
1530 /* kill the connection */
1535 lws_remaining_packet_payload(struct lws *wsi)
1537 return wsi->u.ws.rx_packet_length;
1540 /* Once we reach LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED, we know how much
1541 * to expect in that state and can deal with it in bulk more efficiently.
1545 lws_payload_until_length_exhausted(struct lws *wsi, unsigned char **buf,
1548 unsigned char *buffer = *buf, mask[4];
1553 if (wsi->protocol->rx_buffer_size)
1554 buffer_size = wsi->protocol->rx_buffer_size;
1556 buffer_size = wsi->context->pt_serv_buf_size;
1557 avail = buffer_size - wsi->u.ws.rx_ubuf_head;
1559 /* do not consume more than we should */
1560 if (avail > wsi->u.ws.rx_packet_length)
1561 avail = wsi->u.ws.rx_packet_length;
1563 /* do not consume more than what is in the buffer */
1567 /* we want to leave 1 byte for the parser to handle properly */
1572 rx_ubuf = wsi->u.ws.rx_ubuf + LWS_PRE + wsi->u.ws.rx_ubuf_head;
1573 if (wsi->u.ws.all_zero_nonce)
1574 memcpy(rx_ubuf, buffer, avail);
1577 for (n = 0; n < 4; n++)
1578 mask[n] = wsi->u.ws.mask[(wsi->u.ws.mask_idx + n) & 3];
1580 /* deal with 4-byte chunks using unwrapped loop */
1583 *(rx_ubuf++) = *(buffer++) ^ mask[0];
1584 *(rx_ubuf++) = *(buffer++) ^ mask[1];
1585 *(rx_ubuf++) = *(buffer++) ^ mask[2];
1586 *(rx_ubuf++) = *(buffer++) ^ mask[3];
1588 /* and the remaining bytes bytewise */
1589 for (n = 0; n < (int)(avail & 3); n++)
1590 *(rx_ubuf++) = *(buffer++) ^ mask[n];
1592 wsi->u.ws.mask_idx = (wsi->u.ws.mask_idx + avail) & 3;
1596 wsi->u.ws.rx_ubuf_head += avail;
1597 wsi->u.ws.rx_packet_length -= avail;