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)
66 struct allocated_headers *ah = wsi->u.hdr.ah;
68 /* if we have the idea we're resetting 'our' ah, must be bound to one */
70 /* ah also concurs with ownership */
71 assert(ah->wsi == wsi);
73 /* init the ah to reflect no headers or data have appeared yet */
74 memset(ah->frag_index, 0, sizeof(ah->frag_index));
78 /* and reset the rx state */
82 /* since we will restart the ah, our new headers are not completed */
83 wsi->hdr_parsing_completed = 0;
86 int LWS_WARN_UNUSED_RESULT
87 lws_header_table_attach(struct lws *wsi)
89 struct lws_context *context = wsi->context;
90 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
91 struct lws_pollargs pa;
95 lwsl_info("%s: wsi %p: ah %p (tsi %d)\n", __func__, (void *)wsi,
96 (void *)wsi->u.hdr.ah, wsi->tsi);
98 /* if we are already bound to one, just clear it down */
100 lwsl_err("cleardown\n");
105 pwsi = &pt->ah_wait_list;
108 /* if already waiting on list, if no new ah just ret */
109 if (pt->ah_count_in_use ==
110 context->max_http_header_pool) {
111 lwsl_err("ah wl denied\n");
114 /* new ah.... remove ourselves from waiting list */
115 *pwsi = wsi->u.hdr.ah_wait_list;
116 wsi->u.hdr.ah_wait_list = NULL;
117 pt->ah_wait_list_length--;
120 pwsi = &(*pwsi)->u.hdr.ah_wait_list;
123 * pool is all busy... add us to waiting list and return that we
124 * weren't able to deliver it right now
126 if (pt->ah_count_in_use == context->max_http_header_pool) {
127 lwsl_info("%s: adding %p to ah waiting list\n", __func__, wsi);
128 wsi->u.hdr.ah_wait_list = pt->ah_wait_list;
129 pt->ah_wait_list = wsi;
130 pt->ah_wait_list_length++;
132 /* we cannot accept input then */
134 _lws_change_pollfd(wsi, LWS_POLLIN, 0, &pa);
138 for (n = 0; n < context->max_http_header_pool; n++)
139 if (!pt->ah_pool[n].in_use)
142 /* if the count of in use said something free... */
143 assert(n != context->max_http_header_pool);
145 wsi->u.hdr.ah = &pt->ah_pool[n];
146 wsi->u.hdr.ah->in_use = 1;
147 pt->ah_pool[n].wsi = wsi; /* mark our owner */
148 pt->ah_count_in_use++;
150 _lws_change_pollfd(wsi, 0, LWS_POLLIN, &pa);
152 lwsl_info("%s: wsi %p: ah %p: count %d (on exit)\n", __func__,
153 (void *)wsi, (void *)wsi->u.hdr.ah, pt->ah_count_in_use);
158 lws_header_table_reset(wsi);
159 time(&wsi->u.hdr.ah->assigned);
169 int lws_header_table_detach(struct lws *wsi)
171 struct lws_context *context = wsi->context;
172 struct allocated_headers *ah = wsi->u.hdr.ah;
173 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
174 struct lws_pollargs pa;
178 lwsl_info("%s: wsi %p: ah %p (tsi=%d, count = %d)\n", __func__,
179 (void *)wsi, (void *)wsi->u.hdr.ah, wsi->tsi,
180 pt->ah_count_in_use);
182 /* may not be detached while he still has unprocessed rx */
183 if (ah && ah->rxpos != ah->rxlen) {
184 lwsl_err("%s: %p: rxpos:%d, rxlen:%d\n", __func__, wsi,
185 ah->rxpos, ah->rxlen);
186 assert(ah->rxpos == ah->rxlen);
191 pwsi = &pt->ah_wait_list;
192 if (!ah) { /* remove from wait list if that's all */
193 if (wsi->socket_is_permanently_unusable)
196 lwsl_info("%s: wsi %p, remv wait\n",
198 *pwsi = wsi->u.hdr.ah_wait_list;
199 wsi->u.hdr.ah_wait_list = NULL;
200 pt->ah_wait_list_length--;
203 pwsi = &(*pwsi)->u.hdr.ah_wait_list;
209 if (now - wsi->u.hdr.ah->assigned > 3)
210 lwsl_err("header assign - free time %d\n",
211 (int)(now - wsi->u.hdr.ah->assigned));
213 /* if we think we're detaching one, there should be one in use */
214 assert(pt->ah_count_in_use > 0);
215 /* and this specific one should have been in use */
216 assert(wsi->u.hdr.ah->in_use);
217 wsi->u.hdr.ah = NULL;
218 ah->wsi = NULL; /* no owner */
222 pt->ah_count_in_use--;
227 /* somebody else on same tsi is waiting, give it to him */
229 lwsl_info("pt wait list %p\n", *pwsi);
230 while ((*pwsi)->u.hdr.ah_wait_list)
231 pwsi = &(*pwsi)->u.hdr.ah_wait_list;
234 lwsl_info("last wsi in wait list %p\n", wsi);
237 ah->wsi = wsi; /* new owner */
238 lws_header_table_reset(wsi);
239 time(&wsi->u.hdr.ah->assigned);
241 assert(wsi->position_in_fds_table != -1);
243 lwsl_info("%s: Enabling %p POLLIN\n", __func__, wsi);
245 /* he has been stuck waiting for an ah, but now his wait is over,
248 _lws_change_pollfd(wsi, 0, LWS_POLLIN, &pa);
250 /* point prev guy to next guy in list instead */
251 *pwsi = wsi->u.hdr.ah_wait_list;
252 wsi->u.hdr.ah_wait_list = NULL;
253 pt->ah_wait_list_length--;
255 assert(!!pt->ah_wait_list_length == !!(int)(long)pt->ah_wait_list);
263 * lws_hdr_fragment_length: report length of a single fragment of a header
264 * The returned length does not include the space for a
267 * @wsi: websocket connection
268 * @h: which header index we are interested in
269 * @frag_idx: which fragment of @h we want to get the length of
273 lws_hdr_fragment_length(struct lws *wsi, enum lws_token_indexes h, int frag_idx)
277 n = wsi->u.hdr.ah->frag_index[h];
282 return wsi->u.hdr.ah->frags[n].len;
283 n = wsi->u.hdr.ah->frags[n].nfrag;
284 } while (frag_idx-- && n);
290 * lws_hdr_total_length: report length of all fragments of a header totalled up
291 * The returned length does not include the space for a
294 * @wsi: websocket connection
295 * @h: which header index we are interested in
298 LWS_VISIBLE int lws_hdr_total_length(struct lws *wsi, enum lws_token_indexes h)
303 n = wsi->u.hdr.ah->frag_index[h];
307 len += wsi->u.hdr.ah->frags[n].len;
308 n = wsi->u.hdr.ah->frags[n].nfrag;
315 * lws_hdr_copy_fragment: copy a single fragment of the given header to a buffer
316 * The buffer length @len must include space for an additional
317 * terminating '\0', or it will fail returning -1.
318 * If the requested fragment index is not present, it fails
321 * @wsi: websocket connection
322 * @dst: destination buffer
323 * @len: length of destination buffer
324 * @h: which header index we are interested in
325 * @frag_index: which fragment of @h we want to copy
328 LWS_VISIBLE int lws_hdr_copy_fragment(struct lws *wsi, char *dst, int len,
329 enum lws_token_indexes h, int frag_idx)
332 int f = wsi->u.hdr.ah->frag_index[h];
337 while (n < frag_idx) {
338 f = wsi->u.hdr.ah->frags[f].nfrag;
344 if (wsi->u.hdr.ah->frags[f].len >= len)
347 memcpy(dst, wsi->u.hdr.ah->data + wsi->u.hdr.ah->frags[f].offset,
348 wsi->u.hdr.ah->frags[f].len);
349 dst[wsi->u.hdr.ah->frags[f].len] = '\0';
351 return wsi->u.hdr.ah->frags[f].len;
355 * lws_hdr_copy: copy a single fragment of the given header to a buffer
356 * The buffer length @len must include space for an additional
357 * terminating '\0', or it will fail returning -1.
359 * @wsi: websocket connection
360 * @dst: destination buffer
361 * @len: length of destination buffer
362 * @h: which header index we are interested in
365 LWS_VISIBLE int lws_hdr_copy(struct lws *wsi, char *dst, int len,
366 enum lws_token_indexes h)
368 int toklen = lws_hdr_total_length(wsi, h);
374 n = wsi->u.hdr.ah->frag_index[h];
379 strcpy(dst, &wsi->u.hdr.ah->data[wsi->u.hdr.ah->frags[n].offset]);
380 dst += wsi->u.hdr.ah->frags[n].len;
381 n = wsi->u.hdr.ah->frags[n].nfrag;
387 char *lws_hdr_simple_ptr(struct lws *wsi, enum lws_token_indexes h)
391 n = wsi->u.hdr.ah->frag_index[h];
395 return wsi->u.hdr.ah->data + wsi->u.hdr.ah->frags[n].offset;
398 int LWS_WARN_UNUSED_RESULT
399 lws_pos_in_bounds(struct lws *wsi)
401 if (wsi->u.hdr.ah->pos < wsi->context->max_http_header_data)
404 if (wsi->u.hdr.ah->pos == wsi->context->max_http_header_data) {
405 lwsl_err("Ran out of header data space\n");
410 * with these tests everywhere, it should never be able to exceed
411 * the limit, only meet the limit
414 lwsl_err("%s: pos %d, limit %d\n", __func__, wsi->u.hdr.ah->pos,
415 wsi->context->max_http_header_data);
421 int LWS_WARN_UNUSED_RESULT
422 lws_hdr_simple_create(struct lws *wsi, enum lws_token_indexes h, const char *s)
424 wsi->u.hdr.ah->nfrag++;
425 if (wsi->u.hdr.ah->nfrag == ARRAY_SIZE(wsi->u.hdr.ah->frags)) {
426 lwsl_warn("More hdr frags than we can deal with, dropping\n");
430 wsi->u.hdr.ah->frag_index[h] = wsi->u.hdr.ah->nfrag;
432 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].offset = wsi->u.hdr.ah->pos;
433 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len = 0;
434 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].nfrag = 0;
437 if (lws_pos_in_bounds(wsi))
440 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = *s;
442 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len++;
448 static signed char char_to_hex(const char c)
450 if (c >= '0' && c <= '9')
453 if (c >= 'a' && c <= 'f')
456 if (c >= 'A' && c <= 'F')
462 static int LWS_WARN_UNUSED_RESULT
463 issue_char(struct lws *wsi, unsigned char c)
465 unsigned short frag_len;
467 if (lws_pos_in_bounds(wsi))
470 frag_len = wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len;
472 * If we haven't hit the token limit, just copy the character into
475 if (frag_len < wsi->u.hdr.current_token_limit) {
476 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = c;
478 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->nfrag].len++;
482 /* Insert a null character when we *hit* the limit: */
483 if (frag_len == wsi->u.hdr.current_token_limit) {
484 if (lws_pos_in_bounds(wsi))
486 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = '\0';
487 lwsl_warn("header %i exceeds limit %d\n",
488 wsi->u.hdr.parser_state,
489 wsi->u.hdr.current_token_limit);
495 int LWS_WARN_UNUSED_RESULT
496 lws_parse(struct lws *wsi, unsigned char c)
498 static const unsigned char methods[] = {
501 WSI_TOKEN_OPTIONS_URI,
504 WSI_TOKEN_DELETE_URI,
506 struct allocated_headers *ah = wsi->u.hdr.ah;
507 struct lws_context *context = wsi->context;
508 unsigned int n, m, enc = 0;
510 assert(wsi->u.hdr.ah);
512 switch (wsi->u.hdr.parser_state) {
515 lwsl_parser("WSI_TOK_(%d) '%c'\n", wsi->u.hdr.parser_state, c);
517 /* collect into malloc'd buffers */
518 /* optional initial space swallow */
519 if (!ah->frags[ah->frag_index[wsi->u.hdr.parser_state]].len &&
523 for (m = 0; m < ARRAY_SIZE(methods); m++)
524 if (wsi->u.hdr.parser_state == methods[m])
526 if (m == ARRAY_SIZE(methods))
527 /* it was not any of the methods */
530 /* special URI processing... end at space */
533 /* enforce starting with / */
534 if (!ah->frags[ah->nfrag].len)
535 if (issue_char(wsi, '/') < 0)
538 /* begin parsing HTTP version: */
539 if (issue_char(wsi, '\0') < 0)
541 wsi->u.hdr.parser_state = WSI_TOKEN_HTTP;
545 /* special URI processing... convert %xx */
547 switch (wsi->u.hdr.ues) {
550 wsi->u.hdr.ues = URIES_SEEN_PERCENT;
554 case URIES_SEEN_PERCENT:
555 if (char_to_hex(c) < 0) {
557 if (issue_char(wsi, '%') < 0)
559 wsi->u.hdr.ues = URIES_IDLE;
560 /* continue on to assess c */
563 wsi->u.hdr.esc_stash = c;
564 wsi->u.hdr.ues = URIES_SEEN_PERCENT_H1;
567 case URIES_SEEN_PERCENT_H1:
568 if (char_to_hex(c) < 0) {
570 if (issue_char(wsi, '%') < 0)
572 wsi->u.hdr.ues = URIES_IDLE;
573 /* regurgitate + assess */
574 if (lws_parse(wsi, wsi->u.hdr.esc_stash) < 0)
576 /* continue on to assess c */
579 c = (char_to_hex(wsi->u.hdr.esc_stash) << 4) |
582 wsi->u.hdr.ues = URIES_IDLE;
587 * special URI processing...
588 * convert /.. or /... or /../ etc to /
590 * convert // or /// etc to /
591 * leave /.dir or whatever alone
594 switch (wsi->u.hdr.ups) {
598 /* genuine delimiter */
599 if ((c == '&' || c == ';') && !enc) {
600 if (issue_char(wsi, c) < 0)
602 /* swallow the terminator */
603 ah->frags[ah->nfrag].len--;
604 /* link to next fragment */
605 ah->frags[ah->nfrag].nfrag = ah->nfrag + 1;
607 if (ah->nfrag >= ARRAY_SIZE(ah->frags))
609 /* start next fragment after the & */
610 wsi->u.hdr.post_literal_equal = 0;
611 ah->frags[ah->nfrag].offset = ah->pos;
612 ah->frags[ah->nfrag].len = 0;
613 ah->frags[ah->nfrag].nfrag = 0;
616 /* uriencoded = in the name part, disallow */
617 if (c == '=' && enc && !wsi->u.hdr.post_literal_equal)
620 /* after the real =, we don't care how many = */
621 if (c == '=' && !enc)
622 wsi->u.hdr.post_literal_equal = 1;
625 if (c == '+' && !enc)
627 /* issue the first / always */
628 if (c == '/' && !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS])
629 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
631 case URIPS_SEEN_SLASH:
632 /* swallow subsequent slashes */
635 /* track and swallow the first . after / */
637 wsi->u.hdr.ups = URIPS_SEEN_SLASH_DOT;
640 wsi->u.hdr.ups = URIPS_IDLE;
642 case URIPS_SEEN_SLASH_DOT:
643 /* swallow second . */
646 * back up one dir level if possible
647 * safe against header fragmentation because
648 * the method URI can only be in 1 fragment
650 if (ah->frags[ah->nfrag].len > 2) {
652 ah->frags[ah->nfrag].len--;
655 ah->frags[ah->nfrag].len--;
656 } while (ah->frags[ah->nfrag].len > 1 &&
657 ah->data[ah->pos] != '/');
659 wsi->u.hdr.ups = URIPS_SEEN_SLASH_DOT_DOT;
662 /* change /./ to / */
664 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
667 /* it was like /.dir ... regurgitate the . */
668 wsi->u.hdr.ups = URIPS_IDLE;
669 if (issue_char(wsi, '.') < 0)
673 case URIPS_SEEN_SLASH_DOT_DOT:
674 /* swallow prior .. chars and any subsequent . */
677 /* last issued was /, so another / == // */
680 /* last we issued was / so SEEN_SLASH */
681 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
685 if (c == '?' && !enc &&
686 !ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS]) { /* start of URI arguments */
687 /* seal off uri header */
688 if (issue_char(wsi, '\0') < 0)
691 /* move to using WSI_TOKEN_HTTP_URI_ARGS */
693 if (ah->nfrag >= ARRAY_SIZE(ah->frags))
695 ah->frags[ah->nfrag].offset = ah->pos;
696 ah->frags[ah->nfrag].len = 0;
697 ah->frags[ah->nfrag].nfrag = 0;
699 wsi->u.hdr.post_literal_equal = 0;
700 ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS] = ah->nfrag;
701 wsi->u.hdr.ups = URIPS_IDLE;
708 if (wsi->u.hdr.parser_state != WSI_TOKEN_CHALLENGE &&
711 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
715 n = issue_char(wsi, c);
719 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
722 /* per-protocol end of headers management */
724 if (wsi->u.hdr.parser_state == WSI_TOKEN_CHALLENGE)
725 goto set_parsing_complete;
728 /* collecting and checking a name part */
729 case WSI_TOKEN_NAME_PART:
730 lwsl_parser("WSI_TOKEN_NAME_PART '%c' (mode=%d)\n", c, wsi->mode);
732 wsi->u.hdr.lextable_pos =
733 lextable_decode(wsi->u.hdr.lextable_pos, c);
735 * Server needs to look out for unknown methods...
737 if (wsi->u.hdr.lextable_pos < 0 &&
738 wsi->mode == LWSCM_HTTP_SERVING) {
739 /* this is not a header we know about */
740 for (m = 0; m < ARRAY_SIZE(methods); m++)
741 if (ah->frag_index[methods[m]]) {
743 * already had the method, no idea what
744 * this crap from the client is, ignore
746 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
750 * hm it's an unknown http method from a client in fact,
753 if (m == ARRAY_SIZE(methods)) {
754 lwsl_info("Unknown method - dropping\n");
760 * ...otherwise for a client, let him ignore unknown headers
761 * coming from the server
763 if (wsi->u.hdr.lextable_pos < 0) {
764 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
768 if (lextable[wsi->u.hdr.lextable_pos] < FAIL_CHAR) {
771 n = ((unsigned int)lextable[wsi->u.hdr.lextable_pos] << 8) |
772 lextable[wsi->u.hdr.lextable_pos + 1];
774 lwsl_parser("known hdr %d\n", n);
775 for (m = 0; m < ARRAY_SIZE(methods); m++)
776 if (n == methods[m] &&
777 ah->frag_index[methods[m]]) {
778 lwsl_warn("Duplicated method\n");
783 * WSORIGIN is protocol equiv to ORIGIN,
784 * JWebSocket likes to send it, map to ORIGIN
786 if (n == WSI_TOKEN_SWORIGIN)
787 n = WSI_TOKEN_ORIGIN;
789 wsi->u.hdr.parser_state = (enum lws_token_indexes)
790 (WSI_TOKEN_GET_URI + n);
792 if (context->token_limits)
793 wsi->u.hdr.current_token_limit =
794 context->token_limits->token_limit[
795 wsi->u.hdr.parser_state];
797 wsi->u.hdr.current_token_limit =
798 wsi->context->max_http_header_data;
800 if (wsi->u.hdr.parser_state == WSI_TOKEN_CHALLENGE)
801 goto set_parsing_complete;
810 if (ah->nfrag == ARRAY_SIZE(ah->frags)) {
811 lwsl_warn("More hdr frags than we can deal with\n");
815 ah->frags[ah->nfrag].offset = ah->pos;
816 ah->frags[ah->nfrag].len = 0;
817 ah->frags[ah->nfrag].nfrag = 0;
819 n = ah->frag_index[wsi->u.hdr.parser_state];
820 if (!n) { /* first fragment */
821 ah->frag_index[wsi->u.hdr.parser_state] = ah->nfrag;
825 while (ah->frags[n].nfrag)
826 n = ah->frags[n].nfrag;
827 ah->frags[n].nfrag = ah->nfrag;
829 if (issue_char(wsi, ' ') < 0)
833 /* skipping arg part of a name we didn't recognize */
834 case WSI_TOKEN_SKIPPING:
835 lwsl_parser("WSI_TOKEN_SKIPPING '%c'\n", c);
838 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
841 case WSI_TOKEN_SKIPPING_SAW_CR:
842 lwsl_parser("WSI_TOKEN_SKIPPING_SAW_CR '%c'\n", c);
844 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
845 wsi->u.hdr.lextable_pos = 0;
847 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
849 /* we're done, ignore anything else */
851 case WSI_PARSING_COMPLETE:
852 lwsl_parser("WSI_PARSING_COMPLETE '%c'\n", c);
858 set_parsing_complete:
860 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
861 if (lws_hdr_total_length(wsi, WSI_TOKEN_VERSION))
862 wsi->ietf_spec_revision =
863 atoi(lws_hdr_simple_ptr(wsi, WSI_TOKEN_VERSION));
865 lwsl_parser("v%02d hdrs completed\n", wsi->ietf_spec_revision);
867 wsi->u.hdr.parser_state = WSI_PARSING_COMPLETE;
868 wsi->hdr_parsing_completed = 1;
875 * lws_frame_is_binary: true if the current frame was sent in binary mode
877 * @wsi: the connection we are inquiring about
879 * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
880 * it's interested to see if the frame it's dealing with was sent in binary
884 LWS_VISIBLE int lws_frame_is_binary(struct lws *wsi)
886 return wsi->u.ws.frame_is_binary;
890 lws_rx_sm(struct lws *wsi, unsigned char c)
892 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
893 int callback_action = LWS_CALLBACK_RECEIVE;
894 int ret = 0, n, rx_draining_ext = 0;
895 struct lws_tokens eff_buf;
897 if (wsi->socket_is_permanently_unusable)
900 switch (wsi->lws_rx_parse_state) {
902 if (wsi->u.ws.rx_draining_ext) {
903 struct lws **w = &pt->rx_draining_ext_list;
905 eff_buf.token = NULL;
906 eff_buf.token_len = 0;
907 wsi->u.ws.rx_draining_ext = 0;
908 /* remove us from context draining ext list */
911 *w = wsi->u.ws.rx_draining_ext_list;
914 w = &((*w)->u.ws.rx_draining_ext_list);
916 wsi->u.ws.rx_draining_ext_list = NULL;
918 lwsl_err("%s: doing draining flow\n", __func__);
920 goto drain_extension;
922 switch (wsi->ietf_spec_revision) {
925 * no prepended frame key any more
927 wsi->u.ws.all_zero_nonce = 1;
931 lwsl_warn("lws_rx_sm: unknown spec version %d\n",
932 wsi->ietf_spec_revision);
936 case LWS_RXPS_04_mask_1:
937 wsi->u.ws.mask[1] = c;
939 wsi->u.ws.all_zero_nonce = 0;
940 wsi->lws_rx_parse_state = LWS_RXPS_04_mask_2;
942 case LWS_RXPS_04_mask_2:
943 wsi->u.ws.mask[2] = c;
945 wsi->u.ws.all_zero_nonce = 0;
946 wsi->lws_rx_parse_state = LWS_RXPS_04_mask_3;
948 case LWS_RXPS_04_mask_3:
949 wsi->u.ws.mask[3] = c;
951 wsi->u.ws.all_zero_nonce = 0;
954 * start from the zero'th byte in the XOR key buffer since
955 * this is the start of a frame with a new key
958 wsi->u.ws.mask_idx = 0;
960 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_1;
964 * 04 logical framing from the spec (all this is masked when incoming
965 * and has to be unmasked)
967 * We ignore the possibility of extension data because we don't
968 * negotiate any extensions at the moment.
971 * 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
972 * +-+-+-+-+-------+-+-------------+-------------------------------+
973 * |F|R|R|R| opcode|R| Payload len | Extended payload length |
974 * |I|S|S|S| (4) |S| (7) | (16/63) |
975 * |N|V|V|V| |V| | (if payload len==126/127) |
977 * +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
978 * | Extended payload length continued, if payload len == 127 |
979 * + - - - - - - - - - - - - - - - +-------------------------------+
980 * | | Extension data |
981 * +-------------------------------+ - - - - - - - - - - - - - - - +
983 * +---------------------------------------------------------------+
984 * : Application data :
985 * +---------------------------------------------------------------+
987 * We pass payload through to userland as soon as we get it, ignoring
988 * FIN. It's up to userland to buffer it up if it wants to see a
989 * whole unfragmented block of the original size (which may be up to
993 case LWS_RXPS_04_FRAME_HDR_1:
996 wsi->u.ws.opcode = c & 0xf;
997 wsi->u.ws.rsv = c & 0x70;
998 wsi->u.ws.final = !!((c >> 7) & 1);
1000 switch (wsi->u.ws.opcode) {
1001 case LWSWSOPC_TEXT_FRAME:
1002 case LWSWSOPC_BINARY_FRAME:
1003 wsi->u.ws.rsv_first_msg = (c & 0x70);
1004 wsi->u.ws.frame_is_binary =
1005 wsi->u.ws.opcode == LWSWSOPC_BINARY_FRAME;
1017 lwsl_info("illegal opcode\n");
1020 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;
1023 case LWS_RXPS_04_FRAME_HDR_LEN:
1025 wsi->u.ws.this_frame_masked = !!(c & 0x80);
1029 /* control frames are not allowed to have big lengths */
1030 if (wsi->u.ws.opcode & 8)
1031 goto illegal_ctl_length;
1033 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;
1036 /* control frames are not allowed to have big lengths */
1037 if (wsi->u.ws.opcode & 8)
1038 goto illegal_ctl_length;
1040 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;
1043 wsi->u.ws.rx_packet_length = c & 0x7f;
1044 if (wsi->u.ws.this_frame_masked)
1045 wsi->lws_rx_parse_state =
1046 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
1048 if (wsi->u.ws.rx_packet_length)
1049 wsi->lws_rx_parse_state =
1050 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1052 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1059 case LWS_RXPS_04_FRAME_HDR_LEN16_2:
1060 wsi->u.ws.rx_packet_length = c << 8;
1061 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1;
1064 case LWS_RXPS_04_FRAME_HDR_LEN16_1:
1065 wsi->u.ws.rx_packet_length |= c;
1066 if (wsi->u.ws.this_frame_masked)
1067 wsi->lws_rx_parse_state =
1068 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
1070 wsi->lws_rx_parse_state =
1071 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1074 case LWS_RXPS_04_FRAME_HDR_LEN64_8:
1076 lwsl_warn("b63 of length must be zero\n");
1077 /* kill the connection */
1080 #if defined __LP64__
1081 wsi->u.ws.rx_packet_length = ((size_t)c) << 56;
1083 wsi->u.ws.rx_packet_length = 0;
1085 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;
1088 case LWS_RXPS_04_FRAME_HDR_LEN64_7:
1089 #if defined __LP64__
1090 wsi->u.ws.rx_packet_length |= ((size_t)c) << 48;
1092 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;
1095 case LWS_RXPS_04_FRAME_HDR_LEN64_6:
1096 #if defined __LP64__
1097 wsi->u.ws.rx_packet_length |= ((size_t)c) << 40;
1099 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;
1102 case LWS_RXPS_04_FRAME_HDR_LEN64_5:
1103 #if defined __LP64__
1104 wsi->u.ws.rx_packet_length |= ((size_t)c) << 32;
1106 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;
1109 case LWS_RXPS_04_FRAME_HDR_LEN64_4:
1110 wsi->u.ws.rx_packet_length |= ((size_t)c) << 24;
1111 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3;
1114 case LWS_RXPS_04_FRAME_HDR_LEN64_3:
1115 wsi->u.ws.rx_packet_length |= ((size_t)c) << 16;
1116 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2;
1119 case LWS_RXPS_04_FRAME_HDR_LEN64_2:
1120 wsi->u.ws.rx_packet_length |= ((size_t)c) << 8;
1121 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1;
1124 case LWS_RXPS_04_FRAME_HDR_LEN64_1:
1125 wsi->u.ws.rx_packet_length |= ((size_t)c);
1126 if (wsi->u.ws.this_frame_masked)
1127 wsi->lws_rx_parse_state =
1128 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
1130 wsi->lws_rx_parse_state =
1131 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1134 case LWS_RXPS_07_COLLECT_FRAME_KEY_1:
1135 wsi->u.ws.mask[0] = c;
1137 wsi->u.ws.all_zero_nonce = 0;
1138 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_2;
1141 case LWS_RXPS_07_COLLECT_FRAME_KEY_2:
1142 wsi->u.ws.mask[1] = c;
1144 wsi->u.ws.all_zero_nonce = 0;
1145 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_3;
1148 case LWS_RXPS_07_COLLECT_FRAME_KEY_3:
1149 wsi->u.ws.mask[2] = c;
1151 wsi->u.ws.all_zero_nonce = 0;
1152 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_4;
1155 case LWS_RXPS_07_COLLECT_FRAME_KEY_4:
1156 wsi->u.ws.mask[3] = c;
1158 wsi->u.ws.all_zero_nonce = 0;
1159 wsi->lws_rx_parse_state =
1160 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
1161 wsi->u.ws.mask_idx = 0;
1162 if (wsi->u.ws.rx_packet_length == 0) {
1163 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1169 case LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED:
1170 assert(wsi->u.ws.rx_ubuf);
1172 if (wsi->u.ws.rx_ubuf_head + LWS_PRE >=
1173 wsi->u.ws.rx_ubuf_alloc) {
1174 lwsl_err("Attempted overflow \n");
1177 if (wsi->u.ws.all_zero_nonce)
1178 wsi->u.ws.rx_ubuf[LWS_PRE +
1179 (wsi->u.ws.rx_ubuf_head++)] = c;
1181 wsi->u.ws.rx_ubuf[LWS_PRE +
1182 (wsi->u.ws.rx_ubuf_head++)] =
1184 (wsi->u.ws.mask_idx++) & 3];
1186 if (--wsi->u.ws.rx_packet_length == 0) {
1187 /* spill because we have the whole frame */
1188 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
1193 * if there's no protocol max frame size given, we are
1194 * supposed to default to LWS_MAX_SOCKET_IO_BUF
1197 if (!wsi->protocol->rx_buffer_size &&
1198 wsi->u.ws.rx_ubuf_head !=
1199 LWS_MAX_SOCKET_IO_BUF)
1202 if (wsi->protocol->rx_buffer_size &&
1203 wsi->u.ws.rx_ubuf_head !=
1204 wsi->protocol->rx_buffer_size)
1207 /* spill because we filled our rx buffer */
1210 * is this frame a control packet we should take care of at this
1211 * layer? If so service it and hide it from the user callback
1214 lwsl_parser("spill on %s\n", wsi->protocol->name);
1216 switch (wsi->u.ws.opcode) {
1217 case LWSWSOPC_CLOSE:
1219 /* is this an acknowledgement of our close? */
1220 if (wsi->state == LWSS_AWAITING_CLOSE_ACK) {
1222 * fine he has told us he is closing too, let's
1225 lwsl_parser("seen client close ack\n");
1228 if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY)
1229 /* if he sends us 2 CLOSE, kill him */
1232 if (user_callback_handle_rxflow(
1233 wsi->protocol->callback, wsi,
1234 LWS_CALLBACK_WS_PEER_INITIATED_CLOSE,
1236 &wsi->u.ws.rx_ubuf[LWS_PRE],
1237 wsi->u.ws.rx_ubuf_head))
1240 lwsl_parser("server sees client close packet\n");
1241 wsi->state = LWSS_RETURNED_CLOSE_ALREADY;
1242 /* deal with the close packet contents as a PONG */
1243 wsi->u.ws.payload_is_close = 1;
1244 goto process_as_ping;
1247 lwsl_info("received %d byte ping, sending pong\n",
1248 wsi->u.ws.rx_ubuf_head);
1250 if (wsi->u.ws.ping_pending_flag) {
1252 * there is already a pending ping payload
1253 * we should just log and drop
1255 lwsl_parser("DROP PING since one pending\n");
1259 /* control packets can only be < 128 bytes long */
1260 if (wsi->u.ws.rx_ubuf_head > 128 - 3) {
1261 lwsl_parser("DROP PING payload too large\n");
1265 /* stash the pong payload */
1266 memcpy(wsi->u.ws.ping_payload_buf + LWS_PRE,
1267 &wsi->u.ws.rx_ubuf[LWS_PRE],
1268 wsi->u.ws.rx_ubuf_head);
1270 wsi->u.ws.ping_payload_len = wsi->u.ws.rx_ubuf_head;
1271 wsi->u.ws.ping_pending_flag = 1;
1273 /* get it sent as soon as possible */
1274 lws_callback_on_writable(wsi);
1276 wsi->u.ws.rx_ubuf_head = 0;
1280 lwsl_info("received pong\n");
1281 lwsl_hexdump(&wsi->u.ws.rx_ubuf[LWS_PRE],
1282 wsi->u.ws.rx_ubuf_head);
1285 callback_action = LWS_CALLBACK_RECEIVE_PONG;
1288 case LWSWSOPC_TEXT_FRAME:
1289 case LWSWSOPC_BINARY_FRAME:
1290 case LWSWSOPC_CONTINUATION:
1294 lwsl_parser("passing opc %x up to exts\n",
1297 * It's something special we can't understand here.
1298 * Pass the payload up to the extension's parsing
1302 eff_buf.token = &wsi->u.ws.rx_ubuf[LWS_PRE];
1303 eff_buf.token_len = wsi->u.ws.rx_ubuf_head;
1305 if (lws_ext_cb_active(wsi, LWS_EXT_CB_EXTENDED_PAYLOAD_RX,
1306 &eff_buf, 0) <= 0) /* not handle or fail */
1307 lwsl_ext("ext opc opcode 0x%x unknown\n",
1310 wsi->u.ws.rx_ubuf_head = 0;
1315 * No it's real payload, pass it up to the user callback.
1316 * It's nicely buffered with the pre-padding taken care of
1317 * so it can be sent straight out again using lws_write
1320 eff_buf.token = &wsi->u.ws.rx_ubuf[LWS_PRE];
1321 eff_buf.token_len = wsi->u.ws.rx_ubuf_head;
1324 lwsl_ext("%s: passing %d to ext\n", __func__, eff_buf.token_len);
1326 if (wsi->state == LWSS_RETURNED_CLOSE_ALREADY ||
1327 wsi->state == LWSS_AWAITING_CLOSE_ACK)
1330 n = lws_ext_cb_active(wsi, LWS_EXT_CB_PAYLOAD_RX, &eff_buf, 0);
1333 * we may rely on this to get RX, just drop connection
1335 wsi->socket_is_permanently_unusable = 1;
1339 if (rx_draining_ext && eff_buf.token_len == 0)
1342 if (n && eff_buf.token_len) {
1343 /* extension had more... main loop will come back */
1344 wsi->u.ws.rx_draining_ext = 1;
1345 wsi->u.ws.rx_draining_ext_list = pt->rx_draining_ext_list;
1346 pt->rx_draining_ext_list = wsi;
1349 if (eff_buf.token_len > 0 ||
1350 callback_action == LWS_CALLBACK_RECEIVE_PONG) {
1351 eff_buf.token[eff_buf.token_len] = '\0';
1353 if (wsi->protocol->callback) {
1355 if (callback_action == LWS_CALLBACK_RECEIVE_PONG)
1356 lwsl_info("Doing pong callback\n");
1358 ret = user_callback_handle_rxflow(
1359 wsi->protocol->callback,
1361 (enum lws_callback_reasons)callback_action,
1367 lwsl_err("No callback on payload spill!\n");
1371 wsi->u.ws.rx_ubuf_head = 0;
1379 lwsl_warn("Control frame with xtended length is illegal\n");
1380 /* kill the connection */
1386 * lws_remaining_packet_payload() - Bytes to come before "overall"
1387 * rx packet is complete
1388 * @wsi: Websocket instance (available from user callback)
1390 * This function is intended to be called from the callback if the
1391 * user code is interested in "complete packets" from the client.
1392 * libwebsockets just passes through payload as it comes and issues a buffer
1393 * additionally when it hits a built-in limit. The LWS_CALLBACK_RECEIVE
1394 * callback handler can use this API to find out if the buffer it has just
1395 * been given is the last piece of a "complete packet" from the client --
1396 * when that is the case lws_remaining_packet_payload() will return
1399 * Many protocols won't care becuse their packets are always small.
1403 lws_remaining_packet_payload(struct lws *wsi)
1405 return wsi->u.ws.rx_packet_length;