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;
237 __lws_remove_from_ah_waiting_list(struct lws *wsi)
239 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
240 struct lws **pwsi =&pt->ah_wait_list;
247 lwsl_info("%s: wsi %p, remv wait\n",
249 *pwsi = wsi->u.hdr.ah_wait_list;
250 wsi->u.hdr.ah_wait_list = NULL;
251 pt->ah_wait_list_length--;
254 pwsi = &(*pwsi)->u.hdr.ah_wait_list;
259 int lws_header_table_detach(struct lws *wsi, int autoservice)
261 struct lws_context *context = wsi->context;
262 struct allocated_headers *ah = wsi->u.hdr.ah;
263 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
264 struct lws_pollargs pa;
269 __lws_remove_from_ah_waiting_list(wsi);
275 lwsl_info("%s: wsi %p: ah %p (tsi=%d, count = %d)\n", __func__,
276 (void *)wsi, (void *)ah, wsi->tsi,
277 pt->ah_count_in_use);
279 if (wsi->u.hdr.preamble_rx)
280 lws_free_set_NULL(wsi->u.hdr.preamble_rx);
282 /* may not be detached while he still has unprocessed rx */
283 if (!lws_header_table_is_in_detachable_state(wsi)) {
284 lwsl_err("%s: %p: CANNOT DETACH rxpos:%d, rxlen:%d, wsi->hdr_parsing_completed = %d\n", __func__, wsi,
285 ah->rxpos, ah->rxlen, wsi->hdr_parsing_completed);
291 /* we did have an ah attached */
293 if (ah->assigned && now - ah->assigned > 3) {
295 * we're detaching the ah, but it was held an
296 * unreasonably long time
298 lwsl_notice("%s: wsi %p: ah held %ds, "
299 "ah.rxpos %d, ah.rxlen %d, mode/state %d %d,"
300 "wsi->more_rx_waiting %d\n", __func__, wsi,
301 (int)(now - ah->assigned),
302 ah->rxpos, ah->rxlen, wsi->mode, wsi->state,
303 wsi->more_rx_waiting);
308 /* if we think we're detaching one, there should be one in use */
309 assert(pt->ah_count_in_use > 0);
310 /* and this specific one should have been in use */
312 wsi->u.hdr.ah = NULL;
313 ah->wsi = NULL; /* no owner */
315 pwsi = &pt->ah_wait_list;
317 /* oh there is nobody on the waiting list... leave it at that then */
320 pt->ah_count_in_use--;
325 /* somebody else on same tsi is waiting, give it to oldest guy */
327 lwsl_info("pt wait list %p\n", *pwsi);
328 while ((*pwsi)->u.hdr.ah_wait_list)
329 pwsi = &(*pwsi)->u.hdr.ah_wait_list;
332 lwsl_info("last wsi in wait list %p\n", wsi);
335 ah->wsi = wsi; /* new owner */
336 /* and reset the rx state */
339 lws_header_table_reset(wsi, autoservice);
340 time(&wsi->u.hdr.ah->assigned);
342 /* clients acquire the ah and then insert themselves in fds table... */
343 if (wsi->position_in_fds_table != -1) {
344 lwsl_info("%s: Enabling %p POLLIN\n", __func__, wsi);
346 /* he has been stuck waiting for an ah, but now his wait is over,
349 _lws_change_pollfd(wsi, 0, LWS_POLLIN, &pa);
352 /* point prev guy to next guy in list instead */
353 *pwsi = wsi->u.hdr.ah_wait_list;
354 /* the guy who got one is out of the list */
355 wsi->u.hdr.ah_wait_list = NULL;
356 pt->ah_wait_list_length--;
358 #ifndef LWS_NO_CLIENT
359 if (wsi->state == LWSS_CLIENT_UNCONNECTED) {
362 if (!lws_client_connect_via_info2(wsi)) {
363 /* our client connect has failed, the wsi
373 assert(!!pt->ah_wait_list_length == !!(lws_intptr_t)pt->ah_wait_list);
375 lwsl_info("%s: wsi %p: ah %p (tsi=%d, count = %d)\n", __func__,
376 (void *)wsi, (void *)ah, wsi->tsi,
377 pt->ah_count_in_use);
384 lws_hdr_fragment_length(struct lws *wsi, enum lws_token_indexes h, int frag_idx)
388 n = wsi->u.hdr.ah->frag_index[h];
393 return wsi->u.hdr.ah->frags[n].len;
394 n = wsi->u.hdr.ah->frags[n].nfrag;
395 } while (frag_idx-- && n);
400 LWS_VISIBLE int lws_hdr_total_length(struct lws *wsi, enum lws_token_indexes h)
405 n = wsi->u.hdr.ah->frag_index[h];
409 len += wsi->u.hdr.ah->frags[n].len;
410 n = wsi->u.hdr.ah->frags[n].nfrag;
416 LWS_VISIBLE int lws_hdr_copy_fragment(struct lws *wsi, char *dst, int len,
417 enum lws_token_indexes h, int frag_idx)
420 int f = wsi->u.hdr.ah->frag_index[h];
425 while (n < frag_idx) {
426 f = wsi->u.hdr.ah->frags[f].nfrag;
432 if (wsi->u.hdr.ah->frags[f].len >= len)
435 memcpy(dst, wsi->u.hdr.ah->data + wsi->u.hdr.ah->frags[f].offset,
436 wsi->u.hdr.ah->frags[f].len);
437 dst[wsi->u.hdr.ah->frags[f].len] = '\0';
439 return wsi->u.hdr.ah->frags[f].len;
442 LWS_VISIBLE int lws_hdr_copy(struct lws *wsi, char *dst, int len,
443 enum lws_token_indexes h)
445 int toklen = lws_hdr_total_length(wsi, h);
451 n = wsi->u.hdr.ah->frag_index[h];
456 strcpy(dst, &wsi->u.hdr.ah->data[wsi->u.hdr.ah->frags[n].offset]);
457 dst += wsi->u.hdr.ah->frags[n].len;
458 n = wsi->u.hdr.ah->frags[n].nfrag;
464 char *lws_hdr_simple_ptr(struct lws *wsi, enum lws_token_indexes h)
468 n = wsi->u.hdr.ah->frag_index[h];
472 return wsi->u.hdr.ah->data + wsi->u.hdr.ah->frags[n].offset;
475 int LWS_WARN_UNUSED_RESULT
476 lws_pos_in_bounds(struct lws *wsi)
478 if (wsi->u.hdr.ah->pos < (unsigned int)wsi->context->max_http_header_data)
481 if (wsi->u.hdr.ah->pos == wsi->context->max_http_header_data) {
482 lwsl_err("Ran out of header data space\n");
487 * with these tests everywhere, it should never be able to exceed
488 * the limit, only meet the limit
491 lwsl_err("%s: pos %d, limit %d\n", __func__, wsi->u.hdr.ah->pos,
492 wsi->context->max_http_header_data);
498 int LWS_WARN_UNUSED_RESULT
499 lws_hdr_simple_create(struct lws *wsi, enum lws_token_indexes h, const char *s)
501 wsi->u.hdr.ah->nfrag++;
502 if (wsi->u.hdr.ah->nfrag == ARRAY_SIZE(wsi->u.hdr.ah->frags)) {
503 lwsl_warn("More hdr frags than we can deal with, dropping\n");
507 wsi->u.hdr.ah->frag_index[h] = wsi->u.hdr.ah->nfrag;
509 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].offset = wsi->u.hdr.ah->pos;
510 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len = 0;
511 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].nfrag = 0;
514 if (lws_pos_in_bounds(wsi))
517 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = *s;
519 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len++;
525 signed char char_to_hex(const char c)
527 if (c >= '0' && c <= '9')
530 if (c >= 'a' && c <= 'f')
533 if (c >= 'A' && c <= 'F')
539 static int LWS_WARN_UNUSED_RESULT
540 issue_char(struct lws *wsi, unsigned char c)
542 unsigned short frag_len;
544 if (lws_pos_in_bounds(wsi))
547 frag_len = wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len;
549 * If we haven't hit the token limit, just copy the character into
552 if (frag_len < wsi->u.hdr.current_token_limit) {
553 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = c;
555 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len++;
559 /* Insert a null character when we *hit* the limit: */
560 if (frag_len == wsi->u.hdr.current_token_limit) {
561 if (lws_pos_in_bounds(wsi))
563 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = '\0';
564 lwsl_warn("header %i exceeds limit %d\n",
565 wsi->u.hdr.parser_state,
566 wsi->u.hdr.current_token_limit);
572 int LWS_WARN_UNUSED_RESULT
573 lws_parse(struct lws *wsi, unsigned char c)
575 static const unsigned char methods[] = {
578 WSI_TOKEN_OPTIONS_URI,
581 WSI_TOKEN_DELETE_URI,
584 struct allocated_headers *ah = wsi->u.hdr.ah;
585 struct lws_context *context = wsi->context;
586 unsigned int n, m, enc = 0;
588 assert(wsi->u.hdr.ah);
590 switch (wsi->u.hdr.parser_state) {
593 lwsl_parser("WSI_TOK_(%d) '%c'\n", wsi->u.hdr.parser_state, c);
595 /* collect into malloc'd buffers */
596 /* optional initial space swallow */
597 if (!ah->frags[ah->frag_index[wsi->u.hdr.parser_state]].len &&
601 for (m = 0; m < ARRAY_SIZE(methods); m++)
602 if (wsi->u.hdr.parser_state == methods[m])
604 if (m == ARRAY_SIZE(methods))
605 /* it was not any of the methods */
608 /* special URI processing... end at space */
611 /* enforce starting with / */
612 if (!ah->frags[ah->nfrag].len)
613 if (issue_char(wsi, '/') < 0)
616 if (wsi->u.hdr.ups == URIPS_SEEN_SLASH_DOT_DOT) {
618 * back up one dir level if possible
619 * safe against header fragmentation because
620 * the method URI can only be in 1 fragment
622 if (ah->frags[ah->nfrag].len > 2) {
624 ah->frags[ah->nfrag].len--;
627 ah->frags[ah->nfrag].len--;
628 } while (ah->frags[ah->nfrag].len > 1 &&
629 ah->data[ah->pos] != '/');
633 /* begin parsing HTTP version: */
634 if (issue_char(wsi, '\0') < 0)
636 wsi->u.hdr.parser_state = WSI_TOKEN_HTTP;
642 * special URI processing... convert %xx
645 switch (wsi->u.hdr.ues) {
648 wsi->u.hdr.ues = URIES_SEEN_PERCENT;
652 case URIES_SEEN_PERCENT:
653 if (char_to_hex(c) < 0)
654 /* illegal post-% char */
657 wsi->u.hdr.esc_stash = c;
658 wsi->u.hdr.ues = URIES_SEEN_PERCENT_H1;
661 case URIES_SEEN_PERCENT_H1:
662 if (char_to_hex(c) < 0)
663 /* illegal post-% char */
666 c = (char_to_hex(wsi->u.hdr.esc_stash) << 4) |
669 wsi->u.hdr.ues = URIES_IDLE;
675 * special URI processing...
676 * convert /.. or /... or /../ etc to /
678 * convert // or /// etc to /
679 * leave /.dir or whatever alone
682 switch (wsi->u.hdr.ups) {
686 /* genuine delimiter */
687 if ((c == '&' || c == ';') && !enc) {
688 if (issue_char(wsi, c) < 0)
690 /* swallow the terminator */
691 ah->frags[ah->nfrag].len--;
692 /* link to next fragment */
693 ah->frags[ah->nfrag].nfrag = ah->nfrag + 1;
695 if (ah->nfrag >= ARRAY_SIZE(ah->frags))
697 /* start next fragment after the & */
698 wsi->u.hdr.post_literal_equal = 0;
699 ah->frags[ah->nfrag].offset = ah->pos;
700 ah->frags[ah->nfrag].len = 0;
701 ah->frags[ah->nfrag].nfrag = 0;
704 /* uriencoded = in the name part, disallow */
705 if (c == '=' && enc &&
706 ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS] &&
707 !wsi->u.hdr.post_literal_equal)
710 /* after the real =, we don't care how many = */
711 if (c == '=' && !enc)
712 wsi->u.hdr.post_literal_equal = 1;
715 if (c == '+' && !enc)
717 /* issue the first / always */
718 if (c == '/' && !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS])
719 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
721 case URIPS_SEEN_SLASH:
722 /* swallow subsequent slashes */
725 /* track and swallow the first . after / */
727 wsi->u.hdr.ups = URIPS_SEEN_SLASH_DOT;
730 wsi->u.hdr.ups = URIPS_IDLE;
732 case URIPS_SEEN_SLASH_DOT:
733 /* swallow second . */
735 wsi->u.hdr.ups = URIPS_SEEN_SLASH_DOT_DOT;
738 /* change /./ to / */
740 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
743 /* it was like /.dir ... regurgitate the . */
744 wsi->u.hdr.ups = URIPS_IDLE;
745 if (issue_char(wsi, '.') < 0)
749 case URIPS_SEEN_SLASH_DOT_DOT:
751 /* /../ or /..[End of URI] --> backup to last / */
752 if (c == '/' || c == '?') {
754 * back up one dir level if possible
755 * safe against header fragmentation because
756 * the method URI can only be in 1 fragment
758 if (ah->frags[ah->nfrag].len > 2) {
760 ah->frags[ah->nfrag].len--;
763 ah->frags[ah->nfrag].len--;
764 } while (ah->frags[ah->nfrag].len > 1 &&
765 ah->data[ah->pos] != '/');
767 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
768 if (ah->frags[ah->nfrag].len > 1)
773 /* /..[^/] ... regurgitate and allow */
775 if (issue_char(wsi, '.') < 0)
777 if (issue_char(wsi, '.') < 0)
779 wsi->u.hdr.ups = URIPS_IDLE;
783 if (c == '?' && !enc &&
784 !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS]) { /* start of URI arguments */
785 if (wsi->u.hdr.ues != URIES_IDLE)
788 /* seal off uri header */
789 if (issue_char(wsi, '\0') < 0)
792 /* move to using WSI_TOKEN_HTTP_URI_ARGS */
794 if (ah->nfrag >= ARRAY_SIZE(ah->frags))
796 ah->frags[ah->nfrag].offset = ah->pos;
797 ah->frags[ah->nfrag].len = 0;
798 ah->frags[ah->nfrag].nfrag = 0;
800 wsi->u.hdr.post_literal_equal = 0;
801 ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS] = ah->nfrag;
802 wsi->u.hdr.ups = URIPS_IDLE;
808 if (wsi->u.hdr.parser_state != WSI_TOKEN_CHALLENGE &&
810 if (wsi->u.hdr.ues != URIES_IDLE)
814 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
818 n = issue_char(wsi, c);
822 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
825 /* per-protocol end of headers management */
827 if (wsi->u.hdr.parser_state == WSI_TOKEN_CHALLENGE)
828 goto set_parsing_complete;
831 /* collecting and checking a name part */
832 case WSI_TOKEN_NAME_PART:
833 lwsl_parser("WSI_TOKEN_NAME_PART '%c' (mode=%d)\n", c, wsi->mode);
835 wsi->u.hdr.lextable_pos =
836 lextable_decode(wsi->u.hdr.lextable_pos, c);
838 * Server needs to look out for unknown methods...
840 if (wsi->u.hdr.lextable_pos < 0 &&
841 wsi->mode == LWSCM_HTTP_SERVING) {
842 /* this is not a header we know about */
843 for (m = 0; m < ARRAY_SIZE(methods); m++)
844 if (ah->frag_index[methods[m]]) {
846 * already had the method, no idea what
847 * this crap from the client is, ignore
849 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
853 * hm it's an unknown http method from a client in fact,
854 * it cannot be valid http
856 if (m == ARRAY_SIZE(methods)) {
858 * are we set up to accept raw in these cases?
860 if (lws_check_opt(wsi->vhost->options,
861 LWS_SERVER_OPTION_FALLBACK_TO_RAW))
862 return 2; /* transition to raw */
864 lwsl_info("Unknown method - dropping\n");
870 * ...otherwise for a client, let him ignore unknown headers
871 * coming from the server
873 if (wsi->u.hdr.lextable_pos < 0) {
874 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
878 if (lextable[wsi->u.hdr.lextable_pos] < FAIL_CHAR) {
881 n = ((unsigned int)lextable[wsi->u.hdr.lextable_pos] << 8) |
882 lextable[wsi->u.hdr.lextable_pos + 1];
884 lwsl_parser("known hdr %d\n", n);
885 for (m = 0; m < ARRAY_SIZE(methods); m++)
886 if (n == methods[m] &&
887 ah->frag_index[methods[m]]) {
888 lwsl_warn("Duplicated method\n");
893 * WSORIGIN is protocol equiv to ORIGIN,
894 * JWebSocket likes to send it, map to ORIGIN
896 if (n == WSI_TOKEN_SWORIGIN)
897 n = WSI_TOKEN_ORIGIN;
899 wsi->u.hdr.parser_state = (enum lws_token_indexes)
900 (WSI_TOKEN_GET_URI + n);
902 if (context->token_limits)
903 wsi->u.hdr.current_token_limit =
904 context->token_limits->token_limit[
905 wsi->u.hdr.parser_state];
907 wsi->u.hdr.current_token_limit =
908 wsi->context->max_http_header_data;
910 if (wsi->u.hdr.parser_state == WSI_TOKEN_CHALLENGE)
911 goto set_parsing_complete;
920 if (ah->nfrag == ARRAY_SIZE(ah->frags)) {
921 lwsl_warn("More hdr frags than we can deal with\n");
925 ah->frags[ah->nfrag].offset = ah->pos;
926 ah->frags[ah->nfrag].len = 0;
927 ah->frags[ah->nfrag].nfrag = 0;
929 n = ah->frag_index[wsi->u.hdr.parser_state];
930 if (!n) { /* first fragment */
931 ah->frag_index[wsi->u.hdr.parser_state] = ah->nfrag;
935 while (ah->frags[n].nfrag)
936 n = ah->frags[n].nfrag;
937 ah->frags[n].nfrag = ah->nfrag;
939 if (issue_char(wsi, ' ') < 0)
943 /* skipping arg part of a name we didn't recognize */
944 case WSI_TOKEN_SKIPPING:
945 lwsl_parser("WSI_TOKEN_SKIPPING '%c'\n", c);
948 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
951 case WSI_TOKEN_SKIPPING_SAW_CR:
952 lwsl_parser("WSI_TOKEN_SKIPPING_SAW_CR '%c'\n", c);
953 if (wsi->u.hdr.ues != URIES_IDLE)
956 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
957 wsi->u.hdr.lextable_pos = 0;
959 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
961 /* we're done, ignore anything else */
963 case WSI_PARSING_COMPLETE:
964 lwsl_parser("WSI_PARSING_COMPLETE '%c'\n", c);
970 set_parsing_complete:
971 if (wsi->u.hdr.ues != URIES_IDLE)
973 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
974 if (lws_hdr_total_length(wsi, WSI_TOKEN_VERSION))
975 wsi->ietf_spec_revision =
976 atoi(lws_hdr_simple_ptr(wsi, WSI_TOKEN_VERSION));
978 lwsl_parser("v%02d hdrs completed\n", wsi->ietf_spec_revision);
980 wsi->u.hdr.parser_state = WSI_PARSING_COMPLETE;
981 wsi->hdr_parsing_completed = 1;
986 lwsl_notice(" forbidding on uri sanitation\n");
987 lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
991 LWS_VISIBLE int lws_frame_is_binary(struct lws *wsi)
993 return wsi->u.ws.frame_is_binary;
997 lws_add_wsi_to_draining_ext_list(struct lws *wsi)
999 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
1001 if (wsi->u.ws.rx_draining_ext)
1004 lwsl_ext("%s: RX EXT DRAINING: Adding to list\n", __func__);
1006 wsi->u.ws.rx_draining_ext = 1;
1007 wsi->u.ws.rx_draining_ext_list = pt->rx_draining_ext_list;
1008 pt->rx_draining_ext_list = wsi;
1012 lws_remove_wsi_from_draining_ext_list(struct lws *wsi)
1014 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
1015 struct lws **w = &pt->rx_draining_ext_list;
1017 if (!wsi->u.ws.rx_draining_ext)
1020 lwsl_ext("%s: RX EXT DRAINING: Removing from list\n", __func__);
1022 wsi->u.ws.rx_draining_ext = 0;
1024 /* remove us from context draining ext list */
1027 /* if us, point it instead to who we were pointing to */
1028 *w = wsi->u.ws.rx_draining_ext_list;
1031 w = &((*w)->u.ws.rx_draining_ext_list);
1033 wsi->u.ws.rx_draining_ext_list = NULL;
1037 * client-parser.c: lws_client_rx_sm() needs to be roughly kept in
1038 * sync with changes here, esp related to ext draining
1042 lws_rx_sm(struct lws *wsi, unsigned char c)
1044 int callback_action = LWS_CALLBACK_RECEIVE;
1045 int ret = 0, n, rx_draining_ext = 0;
1046 struct lws_tokens eff_buf;
1048 eff_buf.token = NULL;
1049 eff_buf.token_len = 0;
1050 if (wsi->socket_is_permanently_unusable)
1053 switch (wsi->lws_rx_parse_state) {
1055 if (wsi->u.ws.rx_draining_ext) {
1056 eff_buf.token = NULL;
1057 eff_buf.token_len = 0;
1058 lws_remove_wsi_from_draining_ext_list(wsi);
1059 rx_draining_ext = 1;
1060 lwsl_debug("%s: doing draining flow\n", __func__);
1062 goto drain_extension;
1064 switch (wsi->ietf_spec_revision) {
1067 * no prepended frame key any more
1069 wsi->u.ws.all_zero_nonce = 1;
1073 lwsl_warn("lws_rx_sm: unknown spec version %d\n",
1074 wsi->ietf_spec_revision);
1078 case LWS_RXPS_04_mask_1:
1079 wsi->u.ws.mask[1] = c;
1081 wsi->u.ws.all_zero_nonce = 0;
1082 wsi->lws_rx_parse_state = LWS_RXPS_04_mask_2;
1084 case LWS_RXPS_04_mask_2:
1085 wsi->u.ws.mask[2] = c;
1087 wsi->u.ws.all_zero_nonce = 0;
1088 wsi->lws_rx_parse_state = LWS_RXPS_04_mask_3;
1090 case LWS_RXPS_04_mask_3:
1091 wsi->u.ws.mask[3] = c;
1093 wsi->u.ws.all_zero_nonce = 0;
1096 * start from the zero'th byte in the XOR key buffer since
1097 * this is the start of a frame with a new key
1100 wsi->u.ws.mask_idx = 0;
1102 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_1;
1106 * 04 logical framing from the spec (all this is masked when incoming
1107 * and has to be unmasked)
1109 * We ignore the possibility of extension data because we don't
1110 * negotiate any extensions at the moment.
1113 * 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
1114 * +-+-+-+-+-------+-+-------------+-------------------------------+
1115 * |F|R|R|R| opcode|R| Payload len | Extended payload length |
1116 * |I|S|S|S| (4) |S| (7) | (16/63) |
1117 * |N|V|V|V| |V| | (if payload len==126/127) |
1119 * +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
1120 * | Extended payload length continued, if payload len == 127 |
1121 * + - - - - - - - - - - - - - - - +-------------------------------+
1122 * | | Extension data |
1123 * +-------------------------------+ - - - - - - - - - - - - - - - +
1125 * +---------------------------------------------------------------+
1126 * : Application data :
1127 * +---------------------------------------------------------------+
1129 * We pass payload through to userland as soon as we get it, ignoring
1130 * FIN. It's up to userland to buffer it up if it wants to see a
1131 * whole unfragmented block of the original size (which may be up to
1135 case LWS_RXPS_04_FRAME_HDR_1:
1138 wsi->u.ws.opcode = c & 0xf;
1139 wsi->u.ws.rsv = c & 0x70;
1140 wsi->u.ws.final = !!((c >> 7) & 1);
1142 switch (wsi->u.ws.opcode) {
1143 case LWSWSOPC_TEXT_FRAME:
1144 case LWSWSOPC_BINARY_FRAME:
1145 wsi->u.ws.rsv_first_msg = (c & 0x70);
1146 wsi->u.ws.frame_is_binary =
1147 wsi->u.ws.opcode == LWSWSOPC_BINARY_FRAME;
1159 lwsl_info("illegal opcode\n");
1162 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;
1165 case LWS_RXPS_04_FRAME_HDR_LEN:
1167 wsi->u.ws.this_frame_masked = !!(c & 0x80);
1171 /* control frames are not allowed to have big lengths */
1172 if (wsi->u.ws.opcode & 8)
1173 goto illegal_ctl_length;
1175 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;
1178 /* control frames are not allowed to have big lengths */
1179 if (wsi->u.ws.opcode & 8)
1180 goto illegal_ctl_length;
1182 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;
1185 wsi->u.ws.rx_packet_length = c & 0x7f;
1186 if (wsi->u.ws.this_frame_masked)
1187 wsi->lws_rx_parse_state =
1188 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
1190 if (wsi->u.ws.rx_packet_length)
1191 wsi->lws_rx_parse_state =
1192 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1194 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1201 case LWS_RXPS_04_FRAME_HDR_LEN16_2:
1202 wsi->u.ws.rx_packet_length = c << 8;
1203 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1;
1206 case LWS_RXPS_04_FRAME_HDR_LEN16_1:
1207 wsi->u.ws.rx_packet_length |= c;
1208 if (wsi->u.ws.this_frame_masked)
1209 wsi->lws_rx_parse_state =
1210 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
1212 wsi->lws_rx_parse_state =
1213 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1216 case LWS_RXPS_04_FRAME_HDR_LEN64_8:
1218 lwsl_warn("b63 of length must be zero\n");
1219 /* kill the connection */
1222 #if defined __LP64__
1223 wsi->u.ws.rx_packet_length = ((size_t)c) << 56;
1225 wsi->u.ws.rx_packet_length = 0;
1227 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;
1230 case LWS_RXPS_04_FRAME_HDR_LEN64_7:
1231 #if defined __LP64__
1232 wsi->u.ws.rx_packet_length |= ((size_t)c) << 48;
1234 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;
1237 case LWS_RXPS_04_FRAME_HDR_LEN64_6:
1238 #if defined __LP64__
1239 wsi->u.ws.rx_packet_length |= ((size_t)c) << 40;
1241 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;
1244 case LWS_RXPS_04_FRAME_HDR_LEN64_5:
1245 #if defined __LP64__
1246 wsi->u.ws.rx_packet_length |= ((size_t)c) << 32;
1248 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;
1251 case LWS_RXPS_04_FRAME_HDR_LEN64_4:
1252 wsi->u.ws.rx_packet_length |= ((size_t)c) << 24;
1253 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3;
1256 case LWS_RXPS_04_FRAME_HDR_LEN64_3:
1257 wsi->u.ws.rx_packet_length |= ((size_t)c) << 16;
1258 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2;
1261 case LWS_RXPS_04_FRAME_HDR_LEN64_2:
1262 wsi->u.ws.rx_packet_length |= ((size_t)c) << 8;
1263 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1;
1266 case LWS_RXPS_04_FRAME_HDR_LEN64_1:
1267 wsi->u.ws.rx_packet_length |= ((size_t)c);
1268 if (wsi->u.ws.this_frame_masked)
1269 wsi->lws_rx_parse_state =
1270 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
1272 wsi->lws_rx_parse_state =
1273 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1276 case LWS_RXPS_07_COLLECT_FRAME_KEY_1:
1277 wsi->u.ws.mask[0] = c;
1279 wsi->u.ws.all_zero_nonce = 0;
1280 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_2;
1283 case LWS_RXPS_07_COLLECT_FRAME_KEY_2:
1284 wsi->u.ws.mask[1] = c;
1286 wsi->u.ws.all_zero_nonce = 0;
1287 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_3;
1290 case LWS_RXPS_07_COLLECT_FRAME_KEY_3:
1291 wsi->u.ws.mask[2] = c;
1293 wsi->u.ws.all_zero_nonce = 0;
1294 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_4;
1297 case LWS_RXPS_07_COLLECT_FRAME_KEY_4:
1298 wsi->u.ws.mask[3] = c;
1300 wsi->u.ws.all_zero_nonce = 0;
1301 wsi->lws_rx_parse_state =
1302 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1303 wsi->u.ws.mask_idx = 0;
1304 if (wsi->u.ws.rx_packet_length == 0) {
1305 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1311 case LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED:
1312 assert(wsi->u.ws.rx_ubuf);
1314 if (wsi->u.ws.rx_draining_ext)
1315 goto drain_extension;
1317 if (wsi->u.ws.rx_ubuf_head + LWS_PRE >=
1318 wsi->u.ws.rx_ubuf_alloc) {
1319 lwsl_err("Attempted overflow \n");
1322 if (wsi->u.ws.all_zero_nonce)
1323 wsi->u.ws.rx_ubuf[LWS_PRE +
1324 (wsi->u.ws.rx_ubuf_head++)] = c;
1326 wsi->u.ws.rx_ubuf[LWS_PRE +
1327 (wsi->u.ws.rx_ubuf_head++)] =
1329 (wsi->u.ws.mask_idx++) & 3];
1331 if (--wsi->u.ws.rx_packet_length == 0) {
1332 /* spill because we have the whole frame */
1333 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1338 * if there's no protocol max frame size given, we are
1339 * supposed to default to context->pt_serv_buf_size
1342 if (!wsi->protocol->rx_buffer_size &&
1343 wsi->u.ws.rx_ubuf_head != wsi->context->pt_serv_buf_size)
1346 if (wsi->protocol->rx_buffer_size &&
1347 wsi->u.ws.rx_ubuf_head !=
1348 wsi->protocol->rx_buffer_size)
1351 /* spill because we filled our rx buffer */
1354 * is this frame a control packet we should take care of at this
1355 * layer? If so service it and hide it from the user callback
1358 lwsl_parser("spill on %s\n", wsi->protocol->name);
1360 switch (wsi->u.ws.opcode) {
1361 case LWSWSOPC_CLOSE:
1363 /* is this an acknowledgement of our close? */
1364 if (wsi->state == LWSS_AWAITING_CLOSE_ACK) {
1366 * fine he has told us he is closing too, let's
1369 lwsl_parser("seen client close ack\n");
1372 if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY)
1373 /* if he sends us 2 CLOSE, kill him */
1376 if (lws_partial_buffered(wsi)) {
1378 * if we're in the middle of something,
1379 * we can't do a normal close response and
1380 * have to just close our end.
1382 wsi->socket_is_permanently_unusable = 1;
1383 lwsl_parser("Closing on peer close due to Pending tx\n");
1387 if (user_callback_handle_rxflow(
1388 wsi->protocol->callback, wsi,
1389 LWS_CALLBACK_WS_PEER_INITIATED_CLOSE,
1391 &wsi->u.ws.rx_ubuf[LWS_PRE],
1392 wsi->u.ws.rx_ubuf_head))
1395 lwsl_parser("server sees client close packet\n");
1396 wsi->state = LWSS_RETURNED_CLOSE_ALREADY;
1397 /* deal with the close packet contents as a PONG */
1398 wsi->u.ws.payload_is_close = 1;
1399 goto process_as_ping;
1402 lwsl_info("received %d byte ping, sending pong\n",
1403 wsi->u.ws.rx_ubuf_head);
1405 if (wsi->u.ws.ping_pending_flag) {
1407 * there is already a pending ping payload
1408 * we should just log and drop
1410 lwsl_parser("DROP PING since one pending\n");
1414 /* control packets can only be < 128 bytes long */
1415 if (wsi->u.ws.rx_ubuf_head > 128 - 3) {
1416 lwsl_parser("DROP PING payload too large\n");
1420 /* stash the pong payload */
1421 memcpy(wsi->u.ws.ping_payload_buf + LWS_PRE,
1422 &wsi->u.ws.rx_ubuf[LWS_PRE],
1423 wsi->u.ws.rx_ubuf_head);
1425 wsi->u.ws.ping_payload_len = wsi->u.ws.rx_ubuf_head;
1426 wsi->u.ws.ping_pending_flag = 1;
1428 /* get it sent as soon as possible */
1429 lws_callback_on_writable(wsi);
1431 wsi->u.ws.rx_ubuf_head = 0;
1435 lwsl_info("received pong\n");
1436 lwsl_hexdump(&wsi->u.ws.rx_ubuf[LWS_PRE],
1437 wsi->u.ws.rx_ubuf_head);
1439 if (wsi->pending_timeout == PENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG) {
1440 lwsl_info("received expected PONG on wsi %p\n", wsi);
1441 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1445 callback_action = LWS_CALLBACK_RECEIVE_PONG;
1448 case LWSWSOPC_TEXT_FRAME:
1449 case LWSWSOPC_BINARY_FRAME:
1450 case LWSWSOPC_CONTINUATION:
1454 lwsl_parser("passing opc %x up to exts\n",
1457 * It's something special we can't understand here.
1458 * Pass the payload up to the extension's parsing
1462 eff_buf.token = &wsi->u.ws.rx_ubuf[LWS_PRE];
1463 eff_buf.token_len = wsi->u.ws.rx_ubuf_head;
1465 if (lws_ext_cb_active(wsi, LWS_EXT_CB_EXTENDED_PAYLOAD_RX,
1467 /* not handle or fail */
1468 lwsl_ext("ext opc opcode 0x%x unknown\n",
1471 wsi->u.ws.rx_ubuf_head = 0;
1476 * No it's real payload, pass it up to the user callback.
1477 * It's nicely buffered with the pre-padding taken care of
1478 * so it can be sent straight out again using lws_write
1481 eff_buf.token = &wsi->u.ws.rx_ubuf[LWS_PRE];
1482 eff_buf.token_len = wsi->u.ws.rx_ubuf_head;
1485 lwsl_ext("%s: passing %d to ext\n", __func__, eff_buf.token_len);
1487 if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY ||
1488 wsi->state == LWSS_AWAITING_CLOSE_ACK)
1491 n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_RX, &eff_buf, 0);
1492 /* eff_buf may be pointing somewhere completely different now,
1497 * we may rely on this to get RX, just drop connection
1499 wsi->socket_is_permanently_unusable = 1;
1503 if (rx_draining_ext && eff_buf.token_len == 0)
1506 if (n && eff_buf.token_len) {
1507 /* extension had more... main loop will come back */
1508 lws_add_wsi_to_draining_ext_list(wsi);
1510 lws_remove_wsi_from_draining_ext_list(wsi);
1512 if (eff_buf.token_len > 0 ||
1513 callback_action == LWS_CALLBACK_RECEIVE_PONG) {
1514 eff_buf.token[eff_buf.token_len] = '\0';
1516 if (wsi->protocol->callback) {
1518 if (callback_action == LWS_CALLBACK_RECEIVE_PONG)
1519 lwsl_info("Doing pong callback\n");
1521 ret = user_callback_handle_rxflow(
1522 wsi->protocol->callback,
1524 (enum lws_callback_reasons)callback_action,
1530 lwsl_err("No callback on payload spill!\n");
1534 wsi->u.ws.rx_ubuf_head = 0;
1542 lwsl_warn("Control frame with xtended length is illegal\n");
1543 /* kill the connection */
1548 lws_remaining_packet_payload(struct lws *wsi)
1550 return wsi->u.ws.rx_packet_length;
1553 /* Once we reach LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED, we know how much
1554 * to expect in that state and can deal with it in bulk more efficiently.
1558 lws_payload_until_length_exhausted(struct lws *wsi, unsigned char **buf,
1561 unsigned char *buffer = *buf, mask[4];
1566 if (wsi->protocol->rx_buffer_size)
1567 buffer_size = wsi->protocol->rx_buffer_size;
1569 buffer_size = wsi->context->pt_serv_buf_size;
1570 avail = buffer_size - wsi->u.ws.rx_ubuf_head;
1572 /* do not consume more than we should */
1573 if (avail > wsi->u.ws.rx_packet_length)
1574 avail = wsi->u.ws.rx_packet_length;
1576 /* do not consume more than what is in the buffer */
1580 /* we want to leave 1 byte for the parser to handle properly */
1585 rx_ubuf = wsi->u.ws.rx_ubuf + LWS_PRE + wsi->u.ws.rx_ubuf_head;
1586 if (wsi->u.ws.all_zero_nonce)
1587 memcpy(rx_ubuf, buffer, avail);
1590 for (n = 0; n < 4; n++)
1591 mask[n] = wsi->u.ws.mask[(wsi->u.ws.mask_idx + n) & 3];
1593 /* deal with 4-byte chunks using unwrapped loop */
1596 *(rx_ubuf++) = *(buffer++) ^ mask[0];
1597 *(rx_ubuf++) = *(buffer++) ^ mask[1];
1598 *(rx_ubuf++) = *(buffer++) ^ mask[2];
1599 *(rx_ubuf++) = *(buffer++) ^ mask[3];
1601 /* and the remaining bytes bytewise */
1602 for (n = 0; n < (int)(avail & 3); n++)
1603 *(rx_ubuf++) = *(buffer++) ^ mask[n];
1605 wsi->u.ws.mask_idx = (wsi->u.ws.mask_idx + avail) & 3;
1609 wsi->u.ws.rx_ubuf_head += avail;
1610 wsi->u.ws.rx_packet_length -= avail;