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 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 if (wsi->u.hdr.ups == URIPS_SEEN_SLASH_DOT_DOT) {
591 * back up one dir level if possible
592 * safe against header fragmentation because
593 * the method URI can only be in 1 fragment
595 if (ah->frags[ah->nfrag].len > 2) {
597 ah->frags[ah->nfrag].len--;
600 ah->frags[ah->nfrag].len--;
601 } while (ah->frags[ah->nfrag].len > 1 &&
602 ah->data[ah->pos] != '/');
606 /* begin parsing HTTP version: */
607 if (issue_char(wsi, '\0') < 0)
609 wsi->u.hdr.parser_state = WSI_TOKEN_HTTP;
615 * special URI processing... convert %xx
618 switch (wsi->u.hdr.ues) {
621 wsi->u.hdr.ues = URIES_SEEN_PERCENT;
625 case URIES_SEEN_PERCENT:
626 if (char_to_hex(c) < 0)
627 /* illegal post-% char */
630 wsi->u.hdr.esc_stash = c;
631 wsi->u.hdr.ues = URIES_SEEN_PERCENT_H1;
634 case URIES_SEEN_PERCENT_H1:
635 if (char_to_hex(c) < 0)
636 /* illegal post-% char */
639 c = (char_to_hex(wsi->u.hdr.esc_stash) << 4) |
642 wsi->u.hdr.ues = URIES_IDLE;
648 * special URI processing...
649 * convert /.. or /... or /../ etc to /
651 * convert // or /// etc to /
652 * leave /.dir or whatever alone
655 switch (wsi->u.hdr.ups) {
659 /* genuine delimiter */
660 if ((c == '&' || c == ';') && !enc) {
661 if (issue_char(wsi, c) < 0)
663 /* swallow the terminator */
664 ah->frags[ah->nfrag].len--;
665 /* link to next fragment */
666 ah->frags[ah->nfrag].nfrag = ah->nfrag + 1;
668 if (ah->nfrag >= ARRAY_SIZE(ah->frags))
670 /* start next fragment after the & */
671 wsi->u.hdr.post_literal_equal = 0;
672 ah->frags[ah->nfrag].offset = ah->pos;
673 ah->frags[ah->nfrag].len = 0;
674 ah->frags[ah->nfrag].nfrag = 0;
677 /* uriencoded = in the name part, disallow */
678 if (c == '=' && enc && !wsi->u.hdr.post_literal_equal)
681 /* after the real =, we don't care how many = */
682 if (c == '=' && !enc)
683 wsi->u.hdr.post_literal_equal = 1;
686 if (c == '+' && !enc)
688 /* issue the first / always */
689 if (c == '/' && !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS])
690 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
692 case URIPS_SEEN_SLASH:
693 /* swallow subsequent slashes */
696 /* track and swallow the first . after / */
698 wsi->u.hdr.ups = URIPS_SEEN_SLASH_DOT;
701 wsi->u.hdr.ups = URIPS_IDLE;
703 case URIPS_SEEN_SLASH_DOT:
704 /* swallow second . */
706 wsi->u.hdr.ups = URIPS_SEEN_SLASH_DOT_DOT;
709 /* change /./ to / */
711 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
714 /* it was like /.dir ... regurgitate the . */
715 wsi->u.hdr.ups = URIPS_IDLE;
716 if (issue_char(wsi, '.') < 0)
720 case URIPS_SEEN_SLASH_DOT_DOT:
722 /* /../ or /..[End of URI] --> backup to last / */
723 if (c == '/' || c == '?') {
725 * back up one dir level if possible
726 * safe against header fragmentation because
727 * the method URI can only be in 1 fragment
729 if (ah->frags[ah->nfrag].len > 2) {
731 ah->frags[ah->nfrag].len--;
734 ah->frags[ah->nfrag].len--;
735 } while (ah->frags[ah->nfrag].len > 1 &&
736 ah->data[ah->pos] != '/');
738 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
739 if (ah->frags[ah->nfrag].len > 1)
744 /* /..[^/] ... regurgitate and allow */
746 if (issue_char(wsi, '.') < 0)
748 if (issue_char(wsi, '.') < 0)
750 wsi->u.hdr.ups = URIPS_IDLE;
754 if (c == '?' && !enc &&
755 !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS]) { /* start of URI arguments */
756 if (wsi->u.hdr.ues != URIES_IDLE)
759 /* seal off uri header */
760 if (issue_char(wsi, '\0') < 0)
763 /* move to using WSI_TOKEN_HTTP_URI_ARGS */
765 if (ah->nfrag >= ARRAY_SIZE(ah->frags))
767 ah->frags[ah->nfrag].offset = ah->pos;
768 ah->frags[ah->nfrag].len = 0;
769 ah->frags[ah->nfrag].nfrag = 0;
771 wsi->u.hdr.post_literal_equal = 0;
772 ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS] = ah->nfrag;
773 wsi->u.hdr.ups = URIPS_IDLE;
779 if (wsi->u.hdr.parser_state != WSI_TOKEN_CHALLENGE &&
781 if (wsi->u.hdr.ues != URIES_IDLE)
785 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
789 n = issue_char(wsi, c);
793 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
796 /* per-protocol end of headers management */
798 if (wsi->u.hdr.parser_state == WSI_TOKEN_CHALLENGE)
799 goto set_parsing_complete;
802 /* collecting and checking a name part */
803 case WSI_TOKEN_NAME_PART:
804 lwsl_parser("WSI_TOKEN_NAME_PART '%c' (mode=%d)\n", c, wsi->mode);
806 wsi->u.hdr.lextable_pos =
807 lextable_decode(wsi->u.hdr.lextable_pos, c);
809 * Server needs to look out for unknown methods...
811 if (wsi->u.hdr.lextable_pos < 0 &&
812 wsi->mode == LWSCM_HTTP_SERVING) {
813 /* this is not a header we know about */
814 for (m = 0; m < ARRAY_SIZE(methods); m++)
815 if (ah->frag_index[methods[m]]) {
817 * already had the method, no idea what
818 * this crap from the client is, ignore
820 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
824 * hm it's an unknown http method from a client in fact,
827 if (m == ARRAY_SIZE(methods)) {
828 lwsl_info("Unknown method - dropping\n");
834 * ...otherwise for a client, let him ignore unknown headers
835 * coming from the server
837 if (wsi->u.hdr.lextable_pos < 0) {
838 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
842 if (lextable[wsi->u.hdr.lextable_pos] < FAIL_CHAR) {
845 n = ((unsigned int)lextable[wsi->u.hdr.lextable_pos] << 8) |
846 lextable[wsi->u.hdr.lextable_pos + 1];
848 lwsl_parser("known hdr %d\n", n);
849 for (m = 0; m < ARRAY_SIZE(methods); m++)
850 if (n == methods[m] &&
851 ah->frag_index[methods[m]]) {
852 lwsl_warn("Duplicated method\n");
857 * WSORIGIN is protocol equiv to ORIGIN,
858 * JWebSocket likes to send it, map to ORIGIN
860 if (n == WSI_TOKEN_SWORIGIN)
861 n = WSI_TOKEN_ORIGIN;
863 wsi->u.hdr.parser_state = (enum lws_token_indexes)
864 (WSI_TOKEN_GET_URI + n);
866 if (context->token_limits)
867 wsi->u.hdr.current_token_limit =
868 context->token_limits->token_limit[
869 wsi->u.hdr.parser_state];
871 wsi->u.hdr.current_token_limit =
872 wsi->context->max_http_header_data;
874 if (wsi->u.hdr.parser_state == WSI_TOKEN_CHALLENGE)
875 goto set_parsing_complete;
884 if (ah->nfrag == ARRAY_SIZE(ah->frags)) {
885 lwsl_warn("More hdr frags than we can deal with\n");
889 ah->frags[ah->nfrag].offset = ah->pos;
890 ah->frags[ah->nfrag].len = 0;
891 ah->frags[ah->nfrag].nfrag = 0;
893 n = ah->frag_index[wsi->u.hdr.parser_state];
894 if (!n) { /* first fragment */
895 ah->frag_index[wsi->u.hdr.parser_state] = ah->nfrag;
899 while (ah->frags[n].nfrag)
900 n = ah->frags[n].nfrag;
901 ah->frags[n].nfrag = ah->nfrag;
903 if (issue_char(wsi, ' ') < 0)
907 /* skipping arg part of a name we didn't recognize */
908 case WSI_TOKEN_SKIPPING:
909 lwsl_parser("WSI_TOKEN_SKIPPING '%c'\n", c);
912 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
915 case WSI_TOKEN_SKIPPING_SAW_CR:
916 lwsl_parser("WSI_TOKEN_SKIPPING_SAW_CR '%c'\n", c);
917 if (wsi->u.hdr.ues != URIES_IDLE)
920 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
921 wsi->u.hdr.lextable_pos = 0;
923 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
925 /* we're done, ignore anything else */
927 case WSI_PARSING_COMPLETE:
928 lwsl_parser("WSI_PARSING_COMPLETE '%c'\n", c);
934 set_parsing_complete:
935 if (wsi->u.hdr.ues != URIES_IDLE)
937 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
938 if (lws_hdr_total_length(wsi, WSI_TOKEN_VERSION))
939 wsi->ietf_spec_revision =
940 atoi(lws_hdr_simple_ptr(wsi, WSI_TOKEN_VERSION));
942 lwsl_parser("v%02d hdrs completed\n", wsi->ietf_spec_revision);
944 wsi->u.hdr.parser_state = WSI_PARSING_COMPLETE;
945 wsi->hdr_parsing_completed = 1;
950 lwsl_notice(" forbidding on uri sanitation\n");
951 lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
957 * lws_frame_is_binary: true if the current frame was sent in binary mode
959 * @wsi: the connection we are inquiring about
961 * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
962 * it's interested to see if the frame it's dealing with was sent in binary
966 LWS_VISIBLE int lws_frame_is_binary(struct lws *wsi)
968 return wsi->u.ws.frame_is_binary;
972 lws_rx_sm(struct lws *wsi, unsigned char c)
974 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
975 int callback_action = LWS_CALLBACK_RECEIVE;
976 int ret = 0, n, rx_draining_ext = 0;
977 struct lws_tokens eff_buf;
979 if (wsi->socket_is_permanently_unusable)
982 switch (wsi->lws_rx_parse_state) {
984 if (wsi->u.ws.rx_draining_ext) {
985 struct lws **w = &pt->rx_draining_ext_list;
987 eff_buf.token = NULL;
988 eff_buf.token_len = 0;
989 wsi->u.ws.rx_draining_ext = 0;
990 /* remove us from context draining ext list */
993 *w = wsi->u.ws.rx_draining_ext_list;
996 w = &((*w)->u.ws.rx_draining_ext_list);
998 wsi->u.ws.rx_draining_ext_list = NULL;
1000 lwsl_err("%s: doing draining flow\n", __func__);
1002 goto drain_extension;
1004 switch (wsi->ietf_spec_revision) {
1007 * no prepended frame key any more
1009 wsi->u.ws.all_zero_nonce = 1;
1013 lwsl_warn("lws_rx_sm: unknown spec version %d\n",
1014 wsi->ietf_spec_revision);
1018 case LWS_RXPS_04_mask_1:
1019 wsi->u.ws.mask[1] = c;
1021 wsi->u.ws.all_zero_nonce = 0;
1022 wsi->lws_rx_parse_state = LWS_RXPS_04_mask_2;
1024 case LWS_RXPS_04_mask_2:
1025 wsi->u.ws.mask[2] = c;
1027 wsi->u.ws.all_zero_nonce = 0;
1028 wsi->lws_rx_parse_state = LWS_RXPS_04_mask_3;
1030 case LWS_RXPS_04_mask_3:
1031 wsi->u.ws.mask[3] = c;
1033 wsi->u.ws.all_zero_nonce = 0;
1036 * start from the zero'th byte in the XOR key buffer since
1037 * this is the start of a frame with a new key
1040 wsi->u.ws.mask_idx = 0;
1042 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_1;
1046 * 04 logical framing from the spec (all this is masked when incoming
1047 * and has to be unmasked)
1049 * We ignore the possibility of extension data because we don't
1050 * negotiate any extensions at the moment.
1053 * 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
1054 * +-+-+-+-+-------+-+-------------+-------------------------------+
1055 * |F|R|R|R| opcode|R| Payload len | Extended payload length |
1056 * |I|S|S|S| (4) |S| (7) | (16/63) |
1057 * |N|V|V|V| |V| | (if payload len==126/127) |
1059 * +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
1060 * | Extended payload length continued, if payload len == 127 |
1061 * + - - - - - - - - - - - - - - - +-------------------------------+
1062 * | | Extension data |
1063 * +-------------------------------+ - - - - - - - - - - - - - - - +
1065 * +---------------------------------------------------------------+
1066 * : Application data :
1067 * +---------------------------------------------------------------+
1069 * We pass payload through to userland as soon as we get it, ignoring
1070 * FIN. It's up to userland to buffer it up if it wants to see a
1071 * whole unfragmented block of the original size (which may be up to
1075 case LWS_RXPS_04_FRAME_HDR_1:
1078 wsi->u.ws.opcode = c & 0xf;
1079 wsi->u.ws.rsv = c & 0x70;
1080 wsi->u.ws.final = !!((c >> 7) & 1);
1082 switch (wsi->u.ws.opcode) {
1083 case LWSWSOPC_TEXT_FRAME:
1084 case LWSWSOPC_BINARY_FRAME:
1085 wsi->u.ws.rsv_first_msg = (c & 0x70);
1086 wsi->u.ws.frame_is_binary =
1087 wsi->u.ws.opcode == LWSWSOPC_BINARY_FRAME;
1099 lwsl_info("illegal opcode\n");
1102 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;
1105 case LWS_RXPS_04_FRAME_HDR_LEN:
1107 wsi->u.ws.this_frame_masked = !!(c & 0x80);
1111 /* control frames are not allowed to have big lengths */
1112 if (wsi->u.ws.opcode & 8)
1113 goto illegal_ctl_length;
1115 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;
1118 /* control frames are not allowed to have big lengths */
1119 if (wsi->u.ws.opcode & 8)
1120 goto illegal_ctl_length;
1122 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;
1125 wsi->u.ws.rx_packet_length = c & 0x7f;
1126 if (wsi->u.ws.this_frame_masked)
1127 wsi->lws_rx_parse_state =
1128 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
1130 if (wsi->u.ws.rx_packet_length)
1131 wsi->lws_rx_parse_state =
1132 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1134 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1141 case LWS_RXPS_04_FRAME_HDR_LEN16_2:
1142 wsi->u.ws.rx_packet_length = c << 8;
1143 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1;
1146 case LWS_RXPS_04_FRAME_HDR_LEN16_1:
1147 wsi->u.ws.rx_packet_length |= c;
1148 if (wsi->u.ws.this_frame_masked)
1149 wsi->lws_rx_parse_state =
1150 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
1152 wsi->lws_rx_parse_state =
1153 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1156 case LWS_RXPS_04_FRAME_HDR_LEN64_8:
1158 lwsl_warn("b63 of length must be zero\n");
1159 /* kill the connection */
1162 #if defined __LP64__
1163 wsi->u.ws.rx_packet_length = ((size_t)c) << 56;
1165 wsi->u.ws.rx_packet_length = 0;
1167 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;
1170 case LWS_RXPS_04_FRAME_HDR_LEN64_7:
1171 #if defined __LP64__
1172 wsi->u.ws.rx_packet_length |= ((size_t)c) << 48;
1174 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;
1177 case LWS_RXPS_04_FRAME_HDR_LEN64_6:
1178 #if defined __LP64__
1179 wsi->u.ws.rx_packet_length |= ((size_t)c) << 40;
1181 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;
1184 case LWS_RXPS_04_FRAME_HDR_LEN64_5:
1185 #if defined __LP64__
1186 wsi->u.ws.rx_packet_length |= ((size_t)c) << 32;
1188 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;
1191 case LWS_RXPS_04_FRAME_HDR_LEN64_4:
1192 wsi->u.ws.rx_packet_length |= ((size_t)c) << 24;
1193 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3;
1196 case LWS_RXPS_04_FRAME_HDR_LEN64_3:
1197 wsi->u.ws.rx_packet_length |= ((size_t)c) << 16;
1198 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2;
1201 case LWS_RXPS_04_FRAME_HDR_LEN64_2:
1202 wsi->u.ws.rx_packet_length |= ((size_t)c) << 8;
1203 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1;
1206 case LWS_RXPS_04_FRAME_HDR_LEN64_1:
1207 wsi->u.ws.rx_packet_length |= ((size_t)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_07_COLLECT_FRAME_KEY_1:
1217 wsi->u.ws.mask[0] = c;
1219 wsi->u.ws.all_zero_nonce = 0;
1220 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_2;
1223 case LWS_RXPS_07_COLLECT_FRAME_KEY_2:
1224 wsi->u.ws.mask[1] = c;
1226 wsi->u.ws.all_zero_nonce = 0;
1227 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_3;
1230 case LWS_RXPS_07_COLLECT_FRAME_KEY_3:
1231 wsi->u.ws.mask[2] = c;
1233 wsi->u.ws.all_zero_nonce = 0;
1234 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_4;
1237 case LWS_RXPS_07_COLLECT_FRAME_KEY_4:
1238 wsi->u.ws.mask[3] = c;
1240 wsi->u.ws.all_zero_nonce = 0;
1241 wsi->lws_rx_parse_state =
1242 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1243 wsi->u.ws.mask_idx = 0;
1244 if (wsi->u.ws.rx_packet_length == 0) {
1245 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1251 case LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED:
1252 assert(wsi->u.ws.rx_ubuf);
1254 if (wsi->u.ws.rx_ubuf_head + LWS_PRE >=
1255 wsi->u.ws.rx_ubuf_alloc) {
1256 lwsl_err("Attempted overflow \n");
1259 if (wsi->u.ws.all_zero_nonce)
1260 wsi->u.ws.rx_ubuf[LWS_PRE +
1261 (wsi->u.ws.rx_ubuf_head++)] = c;
1263 wsi->u.ws.rx_ubuf[LWS_PRE +
1264 (wsi->u.ws.rx_ubuf_head++)] =
1266 (wsi->u.ws.mask_idx++) & 3];
1268 if (--wsi->u.ws.rx_packet_length == 0) {
1269 /* spill because we have the whole frame */
1270 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1275 * if there's no protocol max frame size given, we are
1276 * supposed to default to LWS_MAX_SOCKET_IO_BUF
1279 if (!wsi->protocol->rx_buffer_size &&
1280 wsi->u.ws.rx_ubuf_head !=
1281 LWS_MAX_SOCKET_IO_BUF)
1284 if (wsi->protocol->rx_buffer_size &&
1285 wsi->u.ws.rx_ubuf_head !=
1286 wsi->protocol->rx_buffer_size)
1289 /* spill because we filled our rx buffer */
1292 * is this frame a control packet we should take care of at this
1293 * layer? If so service it and hide it from the user callback
1296 lwsl_parser("spill on %s\n", wsi->protocol->name);
1298 switch (wsi->u.ws.opcode) {
1299 case LWSWSOPC_CLOSE:
1301 /* is this an acknowledgement of our close? */
1302 if (wsi->state == LWSS_AWAITING_CLOSE_ACK) {
1304 * fine he has told us he is closing too, let's
1307 lwsl_parser("seen client close ack\n");
1310 if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY)
1311 /* if he sends us 2 CLOSE, kill him */
1314 if (user_callback_handle_rxflow(
1315 wsi->protocol->callback, wsi,
1316 LWS_CALLBACK_WS_PEER_INITIATED_CLOSE,
1318 &wsi->u.ws.rx_ubuf[LWS_PRE],
1319 wsi->u.ws.rx_ubuf_head))
1322 lwsl_parser("server sees client close packet\n");
1323 wsi->state = LWSS_RETURNED_CLOSE_ALREADY;
1324 /* deal with the close packet contents as a PONG */
1325 wsi->u.ws.payload_is_close = 1;
1326 goto process_as_ping;
1329 lwsl_info("received %d byte ping, sending pong\n",
1330 wsi->u.ws.rx_ubuf_head);
1332 if (wsi->u.ws.ping_pending_flag) {
1334 * there is already a pending ping payload
1335 * we should just log and drop
1337 lwsl_parser("DROP PING since one pending\n");
1341 /* control packets can only be < 128 bytes long */
1342 if (wsi->u.ws.rx_ubuf_head > 128 - 3) {
1343 lwsl_parser("DROP PING payload too large\n");
1347 /* stash the pong payload */
1348 memcpy(wsi->u.ws.ping_payload_buf + LWS_PRE,
1349 &wsi->u.ws.rx_ubuf[LWS_PRE],
1350 wsi->u.ws.rx_ubuf_head);
1352 wsi->u.ws.ping_payload_len = wsi->u.ws.rx_ubuf_head;
1353 wsi->u.ws.ping_pending_flag = 1;
1355 /* get it sent as soon as possible */
1356 lws_callback_on_writable(wsi);
1358 wsi->u.ws.rx_ubuf_head = 0;
1362 lwsl_info("received pong\n");
1363 lwsl_hexdump(&wsi->u.ws.rx_ubuf[LWS_PRE],
1364 wsi->u.ws.rx_ubuf_head);
1367 callback_action = LWS_CALLBACK_RECEIVE_PONG;
1370 case LWSWSOPC_TEXT_FRAME:
1371 case LWSWSOPC_BINARY_FRAME:
1372 case LWSWSOPC_CONTINUATION:
1376 lwsl_parser("passing opc %x up to exts\n",
1379 * It's something special we can't understand here.
1380 * Pass the payload up to the extension's parsing
1384 eff_buf.token = &wsi->u.ws.rx_ubuf[LWS_PRE];
1385 eff_buf.token_len = wsi->u.ws.rx_ubuf_head;
1387 if (lws_ext_cb_active(wsi, LWS_EXT_CB_EXTENDED_PAYLOAD_RX,
1389 /* not handle or fail */
1390 lwsl_ext("ext opc opcode 0x%x unknown\n",
1393 wsi->u.ws.rx_ubuf_head = 0;
1398 * No it's real payload, pass it up to the user callback.
1399 * It's nicely buffered with the pre-padding taken care of
1400 * so it can be sent straight out again using lws_write
1403 eff_buf.token = &wsi->u.ws.rx_ubuf[LWS_PRE];
1404 eff_buf.token_len = wsi->u.ws.rx_ubuf_head;
1407 lwsl_ext("%s: passing %d to ext\n", __func__, eff_buf.token_len);
1409 if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY ||
1410 wsi->state == LWSS_AWAITING_CLOSE_ACK)
1413 n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_RX, &eff_buf, 0);
1416 * we may rely on this to get RX, just drop connection
1418 wsi->socket_is_permanently_unusable = 1;
1422 if (rx_draining_ext && eff_buf.token_len == 0)
1425 if (n && eff_buf.token_len) {
1426 /* extension had more... main loop will come back */
1427 wsi->u.ws.rx_draining_ext = 1;
1428 wsi->u.ws.rx_draining_ext_list = pt->rx_draining_ext_list;
1429 pt->rx_draining_ext_list = wsi;
1432 if (eff_buf.token_len > 0 ||
1433 callback_action == LWS_CALLBACK_RECEIVE_PONG) {
1434 eff_buf.token[eff_buf.token_len] = '\0';
1436 if (wsi->protocol->callback) {
1438 if (callback_action == LWS_CALLBACK_RECEIVE_PONG)
1439 lwsl_info("Doing pong callback\n");
1441 ret = user_callback_handle_rxflow(
1442 wsi->protocol->callback,
1444 (enum lws_callback_reasons)callback_action,
1450 lwsl_err("No callback on payload spill!\n");
1454 wsi->u.ws.rx_ubuf_head = 0;
1462 lwsl_warn("Control frame with xtended length is illegal\n");
1463 /* kill the connection */
1469 * lws_remaining_packet_payload() - Bytes to come before "overall"
1470 * rx packet is complete
1471 * @wsi: Websocket instance (available from user callback)
1473 * This function is intended to be called from the callback if the
1474 * user code is interested in "complete packets" from the client.
1475 * libwebsockets just passes through payload as it comes and issues a buffer
1476 * additionally when it hits a built-in limit. The LWS_CALLBACK_RECEIVE
1477 * callback handler can use this API to find out if the buffer it has just
1478 * been given is the last piece of a "complete packet" from the client --
1479 * when that is the case lws_remaining_packet_payload() will return
1482 * Many protocols won't care becuse their packets are always small.
1486 lws_remaining_packet_payload(struct lws *wsi)
1488 return wsi->u.ws.rx_packet_length;
1491 /* Once we reach LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED, we know how much
1492 * to expect in that state and can deal with it in bulk more efficiently.
1496 lws_payload_until_length_exhausted(struct lws *wsi, unsigned char **buf,
1499 unsigned char *buffer = *buf, mask[4];
1504 if (wsi->protocol->rx_buffer_size)
1505 buffer_size = wsi->protocol->rx_buffer_size;
1507 buffer_size = LWS_MAX_SOCKET_IO_BUF;
1508 avail = buffer_size - wsi->u.ws.rx_ubuf_head;
1510 /* do not consume more than we should */
1511 if (avail > wsi->u.ws.rx_packet_length)
1512 avail = wsi->u.ws.rx_packet_length;
1514 /* do not consume more than what is in the buffer */
1518 /* we want to leave 1 byte for the parser to handle properly */
1523 rx_ubuf = wsi->u.ws.rx_ubuf + LWS_PRE + wsi->u.ws.rx_ubuf_head;
1524 if (wsi->u.ws.all_zero_nonce)
1525 memcpy(rx_ubuf, buffer, avail);
1528 for (n = 0; n < 4; n++)
1529 mask[n] = wsi->u.ws.mask[(wsi->u.ws.mask_idx + n) & 3];
1531 /* deal with 4-byte chunks using unwrapped loop */
1534 *(rx_ubuf++) = *(buffer++) ^ mask[0];
1535 *(rx_ubuf++) = *(buffer++) ^ mask[1];
1536 *(rx_ubuf++) = *(buffer++) ^ mask[2];
1537 *(rx_ubuf++) = *(buffer++) ^ mask[3];
1539 /* and the remaining bytes bytewise */
1540 for (n = 0; n < (int)(avail & 3); n++)
1541 *(rx_ubuf++) = *(buffer++) ^ mask[n];
1543 wsi->u.ws.mask_idx = (wsi->u.ws.mask_idx + avail) & 3;
1547 wsi->u.ws.rx_ubuf_head += avail;
1548 wsi->u.ws.rx_packet_length -= avail;