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 if (!lws_client_connect_via_info2(wsi))
191 /* our client connect has failed, the wsi
205 int lws_header_table_detach(struct lws *wsi, int autoservice)
207 struct lws_context *context = wsi->context;
208 struct allocated_headers *ah = wsi->u.hdr.ah;
209 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
210 struct lws_pollargs pa;
214 lwsl_info("%s: wsi %p: ah %p (tsi=%d, count = %d)\n", __func__,
215 (void *)wsi, (void *)wsi->u.hdr.ah, wsi->tsi,
216 pt->ah_count_in_use);
218 if (wsi->u.hdr.preamble_rx)
219 lws_free_set_NULL(wsi->u.hdr.preamble_rx);
221 /* may not be detached while he still has unprocessed rx */
222 if (ah && ah->rxpos != ah->rxlen) {
223 lwsl_err("%s: %p: rxpos:%d, rxlen:%d\n", __func__, wsi,
224 ah->rxpos, ah->rxlen);
225 assert(ah->rxpos == ah->rxlen);
230 pwsi = &pt->ah_wait_list;
231 if (!ah) { /* remove from wait list if none attached */
234 lwsl_info("%s: wsi %p, remv wait\n",
236 *pwsi = wsi->u.hdr.ah_wait_list;
237 wsi->u.hdr.ah_wait_list = NULL;
238 pt->ah_wait_list_length--;
241 pwsi = &(*pwsi)->u.hdr.ah_wait_list;
243 /* no ah, not on list... no more business here */
246 /* we did have an ah attached */
248 if (now - wsi->u.hdr.ah->assigned > 3) {
250 * we're detaching the ah, but it was held an
251 * unreasonably long time
253 lwsl_notice("%s: wsi %p: ah held %ds, "
254 "ah.rxpos %d, ah.rxlen %d, mode/state %d %d,"
255 "wsi->more_rx_waiting %d\n", __func__, wsi,
256 (int)(now - wsi->u.hdr.ah->assigned),
257 ah->rxpos, ah->rxlen, wsi->mode, wsi->state,
258 wsi->more_rx_waiting);
261 /* if we think we're detaching one, there should be one in use */
262 assert(pt->ah_count_in_use > 0);
263 /* and this specific one should have been in use */
264 assert(wsi->u.hdr.ah->in_use);
265 wsi->u.hdr.ah = NULL;
266 ah->wsi = NULL; /* no owner */
268 /* oh there is nobody on the waiting list... leave it at that then */
271 pt->ah_count_in_use--;
276 /* somebody else on same tsi is waiting, give it to oldest guy */
278 lwsl_info("pt wait list %p\n", *pwsi);
279 while ((*pwsi)->u.hdr.ah_wait_list)
280 pwsi = &(*pwsi)->u.hdr.ah_wait_list;
283 lwsl_info("last wsi in wait list %p\n", wsi);
286 ah->wsi = wsi; /* new owner */
287 lws_header_table_reset(wsi, autoservice);
288 time(&wsi->u.hdr.ah->assigned);
290 assert(wsi->position_in_fds_table != -1);
292 lwsl_info("%s: Enabling %p POLLIN\n", __func__, wsi);
294 /* he has been stuck waiting for an ah, but now his wait is over,
297 _lws_change_pollfd(wsi, 0, LWS_POLLIN, &pa);
299 /* point prev guy to next guy in list instead */
300 *pwsi = wsi->u.hdr.ah_wait_list;
301 /* the guy who got one is out of the list */
302 wsi->u.hdr.ah_wait_list = NULL;
303 pt->ah_wait_list_length--;
305 #ifndef LWS_NO_CLIENT
306 if (wsi->state == LWSS_CLIENT_UNCONNECTED)
307 if (!lws_client_connect_via_info2(wsi)) {
308 /* our client connect has failed, the wsi
317 assert(!!pt->ah_wait_list_length == !!(int)(long)pt->ah_wait_list);
325 * lws_hdr_fragment_length: report length of a single fragment of a header
326 * The returned length does not include the space for a
329 * @wsi: websocket connection
330 * @h: which header index we are interested in
331 * @frag_idx: which fragment of @h we want to get the length of
335 lws_hdr_fragment_length(struct lws *wsi, enum lws_token_indexes h, int frag_idx)
339 n = wsi->u.hdr.ah->frag_index[h];
344 return wsi->u.hdr.ah->frags[n].len;
345 n = wsi->u.hdr.ah->frags[n].nfrag;
346 } while (frag_idx-- && n);
352 * lws_hdr_total_length: report length of all fragments of a header totalled up
353 * The returned length does not include the space for a
356 * @wsi: websocket connection
357 * @h: which header index we are interested in
360 LWS_VISIBLE int lws_hdr_total_length(struct lws *wsi, enum lws_token_indexes h)
365 n = wsi->u.hdr.ah->frag_index[h];
369 len += wsi->u.hdr.ah->frags[n].len;
370 n = wsi->u.hdr.ah->frags[n].nfrag;
377 * lws_hdr_copy_fragment: copy a single fragment of the given header to a buffer
378 * The buffer length @len must include space for an additional
379 * terminating '\0', or it will fail returning -1.
380 * If the requested fragment index is not present, it fails
383 * @wsi: websocket connection
384 * @dst: destination buffer
385 * @len: length of destination buffer
386 * @h: which header index we are interested in
387 * @frag_index: which fragment of @h we want to copy
390 LWS_VISIBLE int lws_hdr_copy_fragment(struct lws *wsi, char *dst, int len,
391 enum lws_token_indexes h, int frag_idx)
394 int f = wsi->u.hdr.ah->frag_index[h];
399 while (n < frag_idx) {
400 f = wsi->u.hdr.ah->frags[f].nfrag;
406 if (wsi->u.hdr.ah->frags[f].len >= len)
409 memcpy(dst, wsi->u.hdr.ah->data + wsi->u.hdr.ah->frags[f].offset,
410 wsi->u.hdr.ah->frags[f].len);
411 dst[wsi->u.hdr.ah->frags[f].len] = '\0';
413 return wsi->u.hdr.ah->frags[f].len;
417 * lws_hdr_copy: copy a single fragment of the given header to a buffer
418 * The buffer length @len must include space for an additional
419 * terminating '\0', or it will fail returning -1.
421 * @wsi: websocket connection
422 * @dst: destination buffer
423 * @len: length of destination buffer
424 * @h: which header index we are interested in
427 LWS_VISIBLE int lws_hdr_copy(struct lws *wsi, char *dst, int len,
428 enum lws_token_indexes h)
430 int toklen = lws_hdr_total_length(wsi, h);
436 n = wsi->u.hdr.ah->frag_index[h];
441 strcpy(dst, &wsi->u.hdr.ah->data[wsi->u.hdr.ah->frags[n].offset]);
442 dst += wsi->u.hdr.ah->frags[n].len;
443 n = wsi->u.hdr.ah->frags[n].nfrag;
449 char *lws_hdr_simple_ptr(struct lws *wsi, enum lws_token_indexes h)
453 n = wsi->u.hdr.ah->frag_index[h];
457 return wsi->u.hdr.ah->data + wsi->u.hdr.ah->frags[n].offset;
460 int LWS_WARN_UNUSED_RESULT
461 lws_pos_in_bounds(struct lws *wsi)
463 if (wsi->u.hdr.ah->pos < wsi->context->max_http_header_data)
466 if (wsi->u.hdr.ah->pos == wsi->context->max_http_header_data) {
467 lwsl_err("Ran out of header data space\n");
472 * with these tests everywhere, it should never be able to exceed
473 * the limit, only meet the limit
476 lwsl_err("%s: pos %d, limit %d\n", __func__, wsi->u.hdr.ah->pos,
477 wsi->context->max_http_header_data);
483 int LWS_WARN_UNUSED_RESULT
484 lws_hdr_simple_create(struct lws *wsi, enum lws_token_indexes h, const char *s)
486 wsi->u.hdr.ah->nfrag++;
487 if (wsi->u.hdr.ah->nfrag == ARRAY_SIZE(wsi->u.hdr.ah->frags)) {
488 lwsl_warn("More hdr frags than we can deal with, dropping\n");
492 wsi->u.hdr.ah->frag_index[h] = wsi->u.hdr.ah->nfrag;
494 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].offset = wsi->u.hdr.ah->pos;
495 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len = 0;
496 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].nfrag = 0;
499 if (lws_pos_in_bounds(wsi))
502 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = *s;
504 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len++;
510 signed char char_to_hex(const char c)
512 if (c >= '0' && c <= '9')
515 if (c >= 'a' && c <= 'f')
518 if (c >= 'A' && c <= 'F')
524 static int LWS_WARN_UNUSED_RESULT
525 issue_char(struct lws *wsi, unsigned char c)
527 unsigned short frag_len;
529 if (lws_pos_in_bounds(wsi))
532 frag_len = wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len;
534 * If we haven't hit the token limit, just copy the character into
537 if (frag_len < wsi->u.hdr.current_token_limit) {
538 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = c;
540 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len++;
544 /* Insert a null character when we *hit* the limit: */
545 if (frag_len == wsi->u.hdr.current_token_limit) {
546 if (lws_pos_in_bounds(wsi))
548 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = '\0';
549 lwsl_warn("header %i exceeds limit %d\n",
550 wsi->u.hdr.parser_state,
551 wsi->u.hdr.current_token_limit);
557 int LWS_WARN_UNUSED_RESULT
558 lws_parse(struct lws *wsi, unsigned char c)
560 static const unsigned char methods[] = {
563 WSI_TOKEN_OPTIONS_URI,
566 WSI_TOKEN_DELETE_URI,
568 struct allocated_headers *ah = wsi->u.hdr.ah;
569 struct lws_context *context = wsi->context;
570 unsigned int n, m, enc = 0;
572 assert(wsi->u.hdr.ah);
574 switch (wsi->u.hdr.parser_state) {
577 lwsl_parser("WSI_TOK_(%d) '%c'\n", wsi->u.hdr.parser_state, c);
579 /* collect into malloc'd buffers */
580 /* optional initial space swallow */
581 if (!ah->frags[ah->frag_index[wsi->u.hdr.parser_state]].len &&
585 for (m = 0; m < ARRAY_SIZE(methods); m++)
586 if (wsi->u.hdr.parser_state == methods[m])
588 if (m == ARRAY_SIZE(methods))
589 /* it was not any of the methods */
592 /* special URI processing... end at space */
595 /* enforce starting with / */
596 if (!ah->frags[ah->nfrag].len)
597 if (issue_char(wsi, '/') < 0)
600 if (wsi->u.hdr.ups == URIPS_SEEN_SLASH_DOT_DOT) {
602 * back up one dir level if possible
603 * safe against header fragmentation because
604 * the method URI can only be in 1 fragment
606 if (ah->frags[ah->nfrag].len > 2) {
608 ah->frags[ah->nfrag].len--;
611 ah->frags[ah->nfrag].len--;
612 } while (ah->frags[ah->nfrag].len > 1 &&
613 ah->data[ah->pos] != '/');
617 /* begin parsing HTTP version: */
618 if (issue_char(wsi, '\0') < 0)
620 wsi->u.hdr.parser_state = WSI_TOKEN_HTTP;
626 * special URI processing... convert %xx
629 switch (wsi->u.hdr.ues) {
632 wsi->u.hdr.ues = URIES_SEEN_PERCENT;
636 case URIES_SEEN_PERCENT:
637 if (char_to_hex(c) < 0)
638 /* illegal post-% char */
641 wsi->u.hdr.esc_stash = c;
642 wsi->u.hdr.ues = URIES_SEEN_PERCENT_H1;
645 case URIES_SEEN_PERCENT_H1:
646 if (char_to_hex(c) < 0)
647 /* illegal post-% char */
650 c = (char_to_hex(wsi->u.hdr.esc_stash) << 4) |
653 wsi->u.hdr.ues = URIES_IDLE;
659 * special URI processing...
660 * convert /.. or /... or /../ etc to /
662 * convert // or /// etc to /
663 * leave /.dir or whatever alone
666 switch (wsi->u.hdr.ups) {
670 /* genuine delimiter */
671 if ((c == '&' || c == ';') && !enc) {
672 if (issue_char(wsi, c) < 0)
674 /* swallow the terminator */
675 ah->frags[ah->nfrag].len--;
676 /* link to next fragment */
677 ah->frags[ah->nfrag].nfrag = ah->nfrag + 1;
679 if (ah->nfrag >= ARRAY_SIZE(ah->frags))
681 /* start next fragment after the & */
682 wsi->u.hdr.post_literal_equal = 0;
683 ah->frags[ah->nfrag].offset = ah->pos;
684 ah->frags[ah->nfrag].len = 0;
685 ah->frags[ah->nfrag].nfrag = 0;
688 /* uriencoded = in the name part, disallow */
689 if (c == '=' && enc &&
690 ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS] &&
691 !wsi->u.hdr.post_literal_equal)
694 /* after the real =, we don't care how many = */
695 if (c == '=' && !enc)
696 wsi->u.hdr.post_literal_equal = 1;
699 if (c == '+' && !enc)
701 /* issue the first / always */
702 if (c == '/' && !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS])
703 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
705 case URIPS_SEEN_SLASH:
706 /* swallow subsequent slashes */
709 /* track and swallow the first . after / */
711 wsi->u.hdr.ups = URIPS_SEEN_SLASH_DOT;
714 wsi->u.hdr.ups = URIPS_IDLE;
716 case URIPS_SEEN_SLASH_DOT:
717 /* swallow second . */
719 wsi->u.hdr.ups = URIPS_SEEN_SLASH_DOT_DOT;
722 /* change /./ to / */
724 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
727 /* it was like /.dir ... regurgitate the . */
728 wsi->u.hdr.ups = URIPS_IDLE;
729 if (issue_char(wsi, '.') < 0)
733 case URIPS_SEEN_SLASH_DOT_DOT:
735 /* /../ or /..[End of URI] --> backup to last / */
736 if (c == '/' || c == '?') {
738 * back up one dir level if possible
739 * safe against header fragmentation because
740 * the method URI can only be in 1 fragment
742 if (ah->frags[ah->nfrag].len > 2) {
744 ah->frags[ah->nfrag].len--;
747 ah->frags[ah->nfrag].len--;
748 } while (ah->frags[ah->nfrag].len > 1 &&
749 ah->data[ah->pos] != '/');
751 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
752 if (ah->frags[ah->nfrag].len > 1)
757 /* /..[^/] ... regurgitate and allow */
759 if (issue_char(wsi, '.') < 0)
761 if (issue_char(wsi, '.') < 0)
763 wsi->u.hdr.ups = URIPS_IDLE;
767 if (c == '?' && !enc &&
768 !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS]) { /* start of URI arguments */
769 if (wsi->u.hdr.ues != URIES_IDLE)
772 /* seal off uri header */
773 if (issue_char(wsi, '\0') < 0)
776 /* move to using WSI_TOKEN_HTTP_URI_ARGS */
778 if (ah->nfrag >= ARRAY_SIZE(ah->frags))
780 ah->frags[ah->nfrag].offset = ah->pos;
781 ah->frags[ah->nfrag].len = 0;
782 ah->frags[ah->nfrag].nfrag = 0;
784 wsi->u.hdr.post_literal_equal = 0;
785 ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS] = ah->nfrag;
786 wsi->u.hdr.ups = URIPS_IDLE;
792 if (wsi->u.hdr.parser_state != WSI_TOKEN_CHALLENGE &&
794 if (wsi->u.hdr.ues != URIES_IDLE)
798 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
802 n = issue_char(wsi, c);
806 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
809 /* per-protocol end of headers management */
811 if (wsi->u.hdr.parser_state == WSI_TOKEN_CHALLENGE)
812 goto set_parsing_complete;
815 /* collecting and checking a name part */
816 case WSI_TOKEN_NAME_PART:
817 lwsl_parser("WSI_TOKEN_NAME_PART '%c' (mode=%d)\n", c, wsi->mode);
819 wsi->u.hdr.lextable_pos =
820 lextable_decode(wsi->u.hdr.lextable_pos, c);
822 * Server needs to look out for unknown methods...
824 if (wsi->u.hdr.lextable_pos < 0 &&
825 wsi->mode == LWSCM_HTTP_SERVING) {
826 /* this is not a header we know about */
827 for (m = 0; m < ARRAY_SIZE(methods); m++)
828 if (ah->frag_index[methods[m]]) {
830 * already had the method, no idea what
831 * this crap from the client is, ignore
833 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
837 * hm it's an unknown http method from a client in fact,
840 if (m == ARRAY_SIZE(methods)) {
841 lwsl_info("Unknown method - dropping\n");
847 * ...otherwise for a client, let him ignore unknown headers
848 * coming from the server
850 if (wsi->u.hdr.lextable_pos < 0) {
851 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
855 if (lextable[wsi->u.hdr.lextable_pos] < FAIL_CHAR) {
858 n = ((unsigned int)lextable[wsi->u.hdr.lextable_pos] << 8) |
859 lextable[wsi->u.hdr.lextable_pos + 1];
861 lwsl_parser("known hdr %d\n", n);
862 for (m = 0; m < ARRAY_SIZE(methods); m++)
863 if (n == methods[m] &&
864 ah->frag_index[methods[m]]) {
865 lwsl_warn("Duplicated method\n");
870 * WSORIGIN is protocol equiv to ORIGIN,
871 * JWebSocket likes to send it, map to ORIGIN
873 if (n == WSI_TOKEN_SWORIGIN)
874 n = WSI_TOKEN_ORIGIN;
876 wsi->u.hdr.parser_state = (enum lws_token_indexes)
877 (WSI_TOKEN_GET_URI + n);
879 if (context->token_limits)
880 wsi->u.hdr.current_token_limit =
881 context->token_limits->token_limit[
882 wsi->u.hdr.parser_state];
884 wsi->u.hdr.current_token_limit =
885 wsi->context->max_http_header_data;
887 if (wsi->u.hdr.parser_state == WSI_TOKEN_CHALLENGE)
888 goto set_parsing_complete;
897 if (ah->nfrag == ARRAY_SIZE(ah->frags)) {
898 lwsl_warn("More hdr frags than we can deal with\n");
902 ah->frags[ah->nfrag].offset = ah->pos;
903 ah->frags[ah->nfrag].len = 0;
904 ah->frags[ah->nfrag].nfrag = 0;
906 n = ah->frag_index[wsi->u.hdr.parser_state];
907 if (!n) { /* first fragment */
908 ah->frag_index[wsi->u.hdr.parser_state] = ah->nfrag;
912 while (ah->frags[n].nfrag)
913 n = ah->frags[n].nfrag;
914 ah->frags[n].nfrag = ah->nfrag;
916 if (issue_char(wsi, ' ') < 0)
920 /* skipping arg part of a name we didn't recognize */
921 case WSI_TOKEN_SKIPPING:
922 lwsl_parser("WSI_TOKEN_SKIPPING '%c'\n", c);
925 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
928 case WSI_TOKEN_SKIPPING_SAW_CR:
929 lwsl_parser("WSI_TOKEN_SKIPPING_SAW_CR '%c'\n", c);
930 if (wsi->u.hdr.ues != URIES_IDLE)
933 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
934 wsi->u.hdr.lextable_pos = 0;
936 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
938 /* we're done, ignore anything else */
940 case WSI_PARSING_COMPLETE:
941 lwsl_parser("WSI_PARSING_COMPLETE '%c'\n", c);
947 set_parsing_complete:
948 if (wsi->u.hdr.ues != URIES_IDLE)
950 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
951 if (lws_hdr_total_length(wsi, WSI_TOKEN_VERSION))
952 wsi->ietf_spec_revision =
953 atoi(lws_hdr_simple_ptr(wsi, WSI_TOKEN_VERSION));
955 lwsl_parser("v%02d hdrs completed\n", wsi->ietf_spec_revision);
957 wsi->u.hdr.parser_state = WSI_PARSING_COMPLETE;
958 wsi->hdr_parsing_completed = 1;
963 lwsl_notice(" forbidding on uri sanitation\n");
964 lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
970 * lws_frame_is_binary: true if the current frame was sent in binary mode
972 * @wsi: the connection we are inquiring about
974 * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
975 * it's interested to see if the frame it's dealing with was sent in binary
979 LWS_VISIBLE int lws_frame_is_binary(struct lws *wsi)
981 return wsi->u.ws.frame_is_binary;
985 lws_rx_sm(struct lws *wsi, unsigned char c)
987 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
988 int callback_action = LWS_CALLBACK_RECEIVE;
989 int ret = 0, n, rx_draining_ext = 0;
990 struct lws_tokens eff_buf;
992 if (wsi->socket_is_permanently_unusable)
995 switch (wsi->lws_rx_parse_state) {
997 if (wsi->u.ws.rx_draining_ext) {
998 struct lws **w = &pt->rx_draining_ext_list;
1000 eff_buf.token = NULL;
1001 eff_buf.token_len = 0;
1002 wsi->u.ws.rx_draining_ext = 0;
1003 /* remove us from context draining ext list */
1006 *w = wsi->u.ws.rx_draining_ext_list;
1009 w = &((*w)->u.ws.rx_draining_ext_list);
1011 wsi->u.ws.rx_draining_ext_list = NULL;
1012 rx_draining_ext = 1;
1013 lwsl_err("%s: doing draining flow\n", __func__);
1015 goto drain_extension;
1017 switch (wsi->ietf_spec_revision) {
1020 * no prepended frame key any more
1022 wsi->u.ws.all_zero_nonce = 1;
1026 lwsl_warn("lws_rx_sm: unknown spec version %d\n",
1027 wsi->ietf_spec_revision);
1031 case LWS_RXPS_04_mask_1:
1032 wsi->u.ws.mask[1] = c;
1034 wsi->u.ws.all_zero_nonce = 0;
1035 wsi->lws_rx_parse_state = LWS_RXPS_04_mask_2;
1037 case LWS_RXPS_04_mask_2:
1038 wsi->u.ws.mask[2] = c;
1040 wsi->u.ws.all_zero_nonce = 0;
1041 wsi->lws_rx_parse_state = LWS_RXPS_04_mask_3;
1043 case LWS_RXPS_04_mask_3:
1044 wsi->u.ws.mask[3] = c;
1046 wsi->u.ws.all_zero_nonce = 0;
1049 * start from the zero'th byte in the XOR key buffer since
1050 * this is the start of a frame with a new key
1053 wsi->u.ws.mask_idx = 0;
1055 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_1;
1059 * 04 logical framing from the spec (all this is masked when incoming
1060 * and has to be unmasked)
1062 * We ignore the possibility of extension data because we don't
1063 * negotiate any extensions at the moment.
1066 * 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
1067 * +-+-+-+-+-------+-+-------------+-------------------------------+
1068 * |F|R|R|R| opcode|R| Payload len | Extended payload length |
1069 * |I|S|S|S| (4) |S| (7) | (16/63) |
1070 * |N|V|V|V| |V| | (if payload len==126/127) |
1072 * +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
1073 * | Extended payload length continued, if payload len == 127 |
1074 * + - - - - - - - - - - - - - - - +-------------------------------+
1075 * | | Extension data |
1076 * +-------------------------------+ - - - - - - - - - - - - - - - +
1078 * +---------------------------------------------------------------+
1079 * : Application data :
1080 * +---------------------------------------------------------------+
1082 * We pass payload through to userland as soon as we get it, ignoring
1083 * FIN. It's up to userland to buffer it up if it wants to see a
1084 * whole unfragmented block of the original size (which may be up to
1088 case LWS_RXPS_04_FRAME_HDR_1:
1091 wsi->u.ws.opcode = c & 0xf;
1092 wsi->u.ws.rsv = c & 0x70;
1093 wsi->u.ws.final = !!((c >> 7) & 1);
1095 switch (wsi->u.ws.opcode) {
1096 case LWSWSOPC_TEXT_FRAME:
1097 case LWSWSOPC_BINARY_FRAME:
1098 wsi->u.ws.rsv_first_msg = (c & 0x70);
1099 wsi->u.ws.frame_is_binary =
1100 wsi->u.ws.opcode == LWSWSOPC_BINARY_FRAME;
1112 lwsl_info("illegal opcode\n");
1115 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;
1118 case LWS_RXPS_04_FRAME_HDR_LEN:
1120 wsi->u.ws.this_frame_masked = !!(c & 0x80);
1124 /* control frames are not allowed to have big lengths */
1125 if (wsi->u.ws.opcode & 8)
1126 goto illegal_ctl_length;
1128 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;
1131 /* control frames are not allowed to have big lengths */
1132 if (wsi->u.ws.opcode & 8)
1133 goto illegal_ctl_length;
1135 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;
1138 wsi->u.ws.rx_packet_length = c & 0x7f;
1139 if (wsi->u.ws.this_frame_masked)
1140 wsi->lws_rx_parse_state =
1141 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
1143 if (wsi->u.ws.rx_packet_length)
1144 wsi->lws_rx_parse_state =
1145 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1147 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1154 case LWS_RXPS_04_FRAME_HDR_LEN16_2:
1155 wsi->u.ws.rx_packet_length = c << 8;
1156 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1;
1159 case LWS_RXPS_04_FRAME_HDR_LEN16_1:
1160 wsi->u.ws.rx_packet_length |= c;
1161 if (wsi->u.ws.this_frame_masked)
1162 wsi->lws_rx_parse_state =
1163 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
1165 wsi->lws_rx_parse_state =
1166 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1169 case LWS_RXPS_04_FRAME_HDR_LEN64_8:
1171 lwsl_warn("b63 of length must be zero\n");
1172 /* kill the connection */
1175 #if defined __LP64__
1176 wsi->u.ws.rx_packet_length = ((size_t)c) << 56;
1178 wsi->u.ws.rx_packet_length = 0;
1180 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;
1183 case LWS_RXPS_04_FRAME_HDR_LEN64_7:
1184 #if defined __LP64__
1185 wsi->u.ws.rx_packet_length |= ((size_t)c) << 48;
1187 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;
1190 case LWS_RXPS_04_FRAME_HDR_LEN64_6:
1191 #if defined __LP64__
1192 wsi->u.ws.rx_packet_length |= ((size_t)c) << 40;
1194 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;
1197 case LWS_RXPS_04_FRAME_HDR_LEN64_5:
1198 #if defined __LP64__
1199 wsi->u.ws.rx_packet_length |= ((size_t)c) << 32;
1201 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;
1204 case LWS_RXPS_04_FRAME_HDR_LEN64_4:
1205 wsi->u.ws.rx_packet_length |= ((size_t)c) << 24;
1206 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3;
1209 case LWS_RXPS_04_FRAME_HDR_LEN64_3:
1210 wsi->u.ws.rx_packet_length |= ((size_t)c) << 16;
1211 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2;
1214 case LWS_RXPS_04_FRAME_HDR_LEN64_2:
1215 wsi->u.ws.rx_packet_length |= ((size_t)c) << 8;
1216 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1;
1219 case LWS_RXPS_04_FRAME_HDR_LEN64_1:
1220 wsi->u.ws.rx_packet_length |= ((size_t)c);
1221 if (wsi->u.ws.this_frame_masked)
1222 wsi->lws_rx_parse_state =
1223 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
1225 wsi->lws_rx_parse_state =
1226 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1229 case LWS_RXPS_07_COLLECT_FRAME_KEY_1:
1230 wsi->u.ws.mask[0] = c;
1232 wsi->u.ws.all_zero_nonce = 0;
1233 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_2;
1236 case LWS_RXPS_07_COLLECT_FRAME_KEY_2:
1237 wsi->u.ws.mask[1] = c;
1239 wsi->u.ws.all_zero_nonce = 0;
1240 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_3;
1243 case LWS_RXPS_07_COLLECT_FRAME_KEY_3:
1244 wsi->u.ws.mask[2] = c;
1246 wsi->u.ws.all_zero_nonce = 0;
1247 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_4;
1250 case LWS_RXPS_07_COLLECT_FRAME_KEY_4:
1251 wsi->u.ws.mask[3] = c;
1253 wsi->u.ws.all_zero_nonce = 0;
1254 wsi->lws_rx_parse_state =
1255 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1256 wsi->u.ws.mask_idx = 0;
1257 if (wsi->u.ws.rx_packet_length == 0) {
1258 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1264 case LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED:
1265 assert(wsi->u.ws.rx_ubuf);
1267 if (wsi->u.ws.rx_ubuf_head + LWS_PRE >=
1268 wsi->u.ws.rx_ubuf_alloc) {
1269 lwsl_err("Attempted overflow \n");
1272 if (wsi->u.ws.all_zero_nonce)
1273 wsi->u.ws.rx_ubuf[LWS_PRE +
1274 (wsi->u.ws.rx_ubuf_head++)] = c;
1276 wsi->u.ws.rx_ubuf[LWS_PRE +
1277 (wsi->u.ws.rx_ubuf_head++)] =
1279 (wsi->u.ws.mask_idx++) & 3];
1281 if (--wsi->u.ws.rx_packet_length == 0) {
1282 /* spill because we have the whole frame */
1283 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1288 * if there's no protocol max frame size given, we are
1289 * supposed to default to LWS_MAX_SOCKET_IO_BUF
1292 if (!wsi->protocol->rx_buffer_size &&
1293 wsi->u.ws.rx_ubuf_head !=
1294 LWS_MAX_SOCKET_IO_BUF)
1297 if (wsi->protocol->rx_buffer_size &&
1298 wsi->u.ws.rx_ubuf_head !=
1299 wsi->protocol->rx_buffer_size)
1302 /* spill because we filled our rx buffer */
1305 * is this frame a control packet we should take care of at this
1306 * layer? If so service it and hide it from the user callback
1309 lwsl_parser("spill on %s\n", wsi->protocol->name);
1311 switch (wsi->u.ws.opcode) {
1312 case LWSWSOPC_CLOSE:
1314 /* is this an acknowledgement of our close? */
1315 if (wsi->state == LWSS_AWAITING_CLOSE_ACK) {
1317 * fine he has told us he is closing too, let's
1320 lwsl_parser("seen client close ack\n");
1323 if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY)
1324 /* if he sends us 2 CLOSE, kill him */
1327 if (user_callback_handle_rxflow(
1328 wsi->protocol->callback, wsi,
1329 LWS_CALLBACK_WS_PEER_INITIATED_CLOSE,
1331 &wsi->u.ws.rx_ubuf[LWS_PRE],
1332 wsi->u.ws.rx_ubuf_head))
1335 lwsl_parser("server sees client close packet\n");
1336 wsi->state = LWSS_RETURNED_CLOSE_ALREADY;
1337 /* deal with the close packet contents as a PONG */
1338 wsi->u.ws.payload_is_close = 1;
1339 goto process_as_ping;
1342 lwsl_info("received %d byte ping, sending pong\n",
1343 wsi->u.ws.rx_ubuf_head);
1345 if (wsi->u.ws.ping_pending_flag) {
1347 * there is already a pending ping payload
1348 * we should just log and drop
1350 lwsl_parser("DROP PING since one pending\n");
1354 /* control packets can only be < 128 bytes long */
1355 if (wsi->u.ws.rx_ubuf_head > 128 - 3) {
1356 lwsl_parser("DROP PING payload too large\n");
1360 /* stash the pong payload */
1361 memcpy(wsi->u.ws.ping_payload_buf + LWS_PRE,
1362 &wsi->u.ws.rx_ubuf[LWS_PRE],
1363 wsi->u.ws.rx_ubuf_head);
1365 wsi->u.ws.ping_payload_len = wsi->u.ws.rx_ubuf_head;
1366 wsi->u.ws.ping_pending_flag = 1;
1368 /* get it sent as soon as possible */
1369 lws_callback_on_writable(wsi);
1371 wsi->u.ws.rx_ubuf_head = 0;
1375 lwsl_info("received pong\n");
1376 lwsl_hexdump(&wsi->u.ws.rx_ubuf[LWS_PRE],
1377 wsi->u.ws.rx_ubuf_head);
1380 callback_action = LWS_CALLBACK_RECEIVE_PONG;
1383 case LWSWSOPC_TEXT_FRAME:
1384 case LWSWSOPC_BINARY_FRAME:
1385 case LWSWSOPC_CONTINUATION:
1389 lwsl_parser("passing opc %x up to exts\n",
1392 * It's something special we can't understand here.
1393 * Pass the payload up to the extension's parsing
1397 eff_buf.token = &wsi->u.ws.rx_ubuf[LWS_PRE];
1398 eff_buf.token_len = wsi->u.ws.rx_ubuf_head;
1400 if (lws_ext_cb_active(wsi, LWS_EXT_CB_EXTENDED_PAYLOAD_RX,
1402 /* not handle or fail */
1403 lwsl_ext("ext opc opcode 0x%x unknown\n",
1406 wsi->u.ws.rx_ubuf_head = 0;
1411 * No it's real payload, pass it up to the user callback.
1412 * It's nicely buffered with the pre-padding taken care of
1413 * so it can be sent straight out again using lws_write
1416 eff_buf.token = &wsi->u.ws.rx_ubuf[LWS_PRE];
1417 eff_buf.token_len = wsi->u.ws.rx_ubuf_head;
1420 lwsl_ext("%s: passing %d to ext\n", __func__, eff_buf.token_len);
1422 if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY ||
1423 wsi->state == LWSS_AWAITING_CLOSE_ACK)
1426 n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_RX, &eff_buf, 0);
1429 * we may rely on this to get RX, just drop connection
1431 wsi->socket_is_permanently_unusable = 1;
1435 if (rx_draining_ext && eff_buf.token_len == 0)
1438 if (n && eff_buf.token_len) {
1439 /* extension had more... main loop will come back */
1440 wsi->u.ws.rx_draining_ext = 1;
1441 wsi->u.ws.rx_draining_ext_list = pt->rx_draining_ext_list;
1442 pt->rx_draining_ext_list = wsi;
1445 if (eff_buf.token_len > 0 ||
1446 callback_action == LWS_CALLBACK_RECEIVE_PONG) {
1447 eff_buf.token[eff_buf.token_len] = '\0';
1449 if (wsi->protocol->callback) {
1451 if (callback_action == LWS_CALLBACK_RECEIVE_PONG)
1452 lwsl_info("Doing pong callback\n");
1454 ret = user_callback_handle_rxflow(
1455 wsi->protocol->callback,
1457 (enum lws_callback_reasons)callback_action,
1463 lwsl_err("No callback on payload spill!\n");
1467 wsi->u.ws.rx_ubuf_head = 0;
1475 lwsl_warn("Control frame with xtended length is illegal\n");
1476 /* kill the connection */
1482 * lws_remaining_packet_payload() - Bytes to come before "overall"
1483 * rx packet is complete
1484 * @wsi: Websocket instance (available from user callback)
1486 * This function is intended to be called from the callback if the
1487 * user code is interested in "complete packets" from the client.
1488 * libwebsockets just passes through payload as it comes and issues a buffer
1489 * additionally when it hits a built-in limit. The LWS_CALLBACK_RECEIVE
1490 * callback handler can use this API to find out if the buffer it has just
1491 * been given is the last piece of a "complete packet" from the client --
1492 * when that is the case lws_remaining_packet_payload() will return
1495 * Many protocols won't care becuse their packets are always small.
1499 lws_remaining_packet_payload(struct lws *wsi)
1501 return wsi->u.ws.rx_packet_length;
1504 /* Once we reach LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED, we know how much
1505 * to expect in that state and can deal with it in bulk more efficiently.
1509 lws_payload_until_length_exhausted(struct lws *wsi, unsigned char **buf,
1512 unsigned char *buffer = *buf, mask[4];
1517 if (wsi->protocol->rx_buffer_size)
1518 buffer_size = wsi->protocol->rx_buffer_size;
1520 buffer_size = LWS_MAX_SOCKET_IO_BUF;
1521 avail = buffer_size - wsi->u.ws.rx_ubuf_head;
1523 /* do not consume more than we should */
1524 if (avail > wsi->u.ws.rx_packet_length)
1525 avail = wsi->u.ws.rx_packet_length;
1527 /* do not consume more than what is in the buffer */
1531 /* we want to leave 1 byte for the parser to handle properly */
1536 rx_ubuf = wsi->u.ws.rx_ubuf + LWS_PRE + wsi->u.ws.rx_ubuf_head;
1537 if (wsi->u.ws.all_zero_nonce)
1538 memcpy(rx_ubuf, buffer, avail);
1541 for (n = 0; n < 4; n++)
1542 mask[n] = wsi->u.ws.mask[(wsi->u.ws.mask_idx + n) & 3];
1544 /* deal with 4-byte chunks using unwrapped loop */
1547 *(rx_ubuf++) = *(buffer++) ^ mask[0];
1548 *(rx_ubuf++) = *(buffer++) ^ mask[1];
1549 *(rx_ubuf++) = *(buffer++) ^ mask[2];
1550 *(rx_ubuf++) = *(buffer++) ^ mask[3];
1552 /* and the remaining bytes bytewise */
1553 for (n = 0; n < (int)(avail & 3); n++)
1554 *(rx_ubuf++) = *(buffer++) ^ mask[n];
1556 wsi->u.ws.mask_idx = (wsi->u.ws.mask_idx + avail) & 3;
1560 wsi->u.ws.rx_ubuf_head += avail;
1561 wsi->u.ws.rx_packet_length -= avail;