Added HTTP OPTIONS support:
[platform/upstream/libwebsockets.git] / lib / parsers.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2013 Andy Green <andy@warmcat.com>
5  *
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.
10  *
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.
15  *
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,
19  *  MA  02110-1301  USA
20  */
21
22 #include "private-libwebsockets.h"
23
24 unsigned char lextable[] = {
25         #include "lextable.h"
26 };
27
28 #define FAIL_CHAR 0x08
29
30 int lextable_decode(int pos, char c)
31 {
32
33         c = tolower(c);
34
35         while (1) {
36                 if (lextable[pos] & (1 << 7)) { /* 1-byte, fail on mismatch */
37                         if ((lextable[pos] & 0x7f) != c)
38                                 return -1;
39                         /* fall thru */
40                         pos++;
41                         if (lextable[pos] == FAIL_CHAR)
42                                 return -1;
43                         return pos;
44                 }
45                 /* b7 = 0, end or 3-byte */
46                 if (lextable[pos] < FAIL_CHAR) /* terminal marker */
47                         return pos;
48
49                 if (lextable[pos] == c) /* goto */
50                         return pos + (lextable[pos + 1]) +
51                                                 (lextable[pos + 2] << 8);
52                 /* fall thru goto */
53                 pos += 3;
54                 /* continue */
55         }
56 }
57
58 int lws_allocate_header_table(struct libwebsocket *wsi)
59 {
60         wsi->u.hdr.ah = malloc(sizeof(*wsi->u.hdr.ah));
61         if (wsi->u.hdr.ah == NULL) {
62                 lwsl_err("Out of memory\n");
63                 return -1;
64         }
65         memset(wsi->u.hdr.ah->frag_index, 0, sizeof(wsi->u.hdr.ah->frag_index));
66         wsi->u.hdr.ah->next_frag_index = 0;
67         wsi->u.hdr.ah->pos = 0;
68
69         return 0;
70 }
71
72 LWS_VISIBLE int lws_hdr_total_length(struct libwebsocket *wsi, enum lws_token_indexes h)
73 {
74         int n;
75         int len = 0;
76
77         n = wsi->u.hdr.ah->frag_index[h];
78         if (!n)
79                 return 0;
80         do {
81                 len += wsi->u.hdr.ah->frags[n].len;
82                 n = wsi->u.hdr.ah->frags[n].next_frag_index;
83         } while (n);
84
85         return len;
86 }
87
88 LWS_VISIBLE int lws_hdr_copy(struct libwebsocket *wsi, char *dest, int len,
89                                                 enum lws_token_indexes h)
90 {
91         int toklen = lws_hdr_total_length(wsi, h);
92         int n;
93
94         if (toklen >= len)
95                 return -1;
96
97         n = wsi->u.hdr.ah->frag_index[h];
98         if (!n)
99                 return 0;
100
101         do {
102                 strcpy(dest,
103                         &wsi->u.hdr.ah->data[wsi->u.hdr.ah->frags[n].offset]);
104                 dest += wsi->u.hdr.ah->frags[n].len;
105                 n = wsi->u.hdr.ah->frags[n].next_frag_index;
106         } while (n);
107
108         return toklen;
109 }
110
111 char *lws_hdr_simple_ptr(struct libwebsocket *wsi, enum lws_token_indexes h)
112 {
113         int n;
114
115         n = wsi->u.hdr.ah->frag_index[h];
116         if (!n)
117                 return NULL;
118
119         return &wsi->u.hdr.ah->data[wsi->u.hdr.ah->frags[n].offset];
120 }
121
122 int lws_hdr_simple_create(struct libwebsocket *wsi,
123                                 enum lws_token_indexes h, const char *s)
124 {
125         wsi->u.hdr.ah->next_frag_index++;
126         if (wsi->u.hdr.ah->next_frag_index ==
127                sizeof(wsi->u.hdr.ah->frags) / sizeof(wsi->u.hdr.ah->frags[0])) {
128                 lwsl_warn("More hdr frags than we can deal with, dropping\n");
129                 return -1;
130         }
131
132         wsi->u.hdr.ah->frag_index[h] = wsi->u.hdr.ah->next_frag_index;
133
134         wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].offset =
135                                                              wsi->u.hdr.ah->pos;
136         wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len = 0;
137         wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].next_frag_index =
138                                                                               0;
139
140         do {
141                 if (wsi->u.hdr.ah->pos == sizeof(wsi->u.hdr.ah->data)) {
142                         lwsl_err("Ran out of header data space\n");
143                         return -1;
144                 }
145                 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = *s;
146                 if (*s)
147                         wsi->u.hdr.ah->frags[
148                                         wsi->u.hdr.ah->next_frag_index].len++;
149         } while (*s++);
150
151         return 0;
152 }
153
154 static char char_to_hex(const char c)
155 {
156         if (c >= '0' && c <= '9')
157                 return c - '0';
158
159         if (c >= 'a' && c <= 'f')
160                 return c - 'a' + 10;
161
162         if (c >= 'A' && c <= 'F')
163                 return c - 'A' + 10;
164
165         return -1;
166 }
167
168 static int issue_char(struct libwebsocket *wsi, unsigned char c)
169 {
170         if (wsi->u.hdr.ah->pos == sizeof(wsi->u.hdr.ah->data)) {
171                 lwsl_warn("excessive header content\n");
172                 return -1;
173         }
174
175         if( wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len >= 
176                 wsi->u.hdr.current_token_limit) {
177                 lwsl_warn("header %i exceeds limit\n", wsi->u.hdr.parser_state);
178                 return 1;
179         };
180
181         wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = c;
182         if (c)
183                 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len++;
184
185         return 0;
186 }
187
188 int libwebsocket_parse(
189                 struct libwebsocket_context *context,
190                 struct libwebsocket *wsi, unsigned char c)
191 {
192         int n;
193
194         switch (wsi->u.hdr.parser_state) {
195         case WSI_TOKEN_GET_URI:
196         case WSI_TOKEN_POST_URI:
197         case WSI_TOKEN_OPTIONS_URI:
198         case WSI_TOKEN_HOST:
199         case WSI_TOKEN_CONNECTION:
200         case WSI_TOKEN_KEY1:
201         case WSI_TOKEN_KEY2:
202         case WSI_TOKEN_PROTOCOL:
203         case WSI_TOKEN_UPGRADE:
204         case WSI_TOKEN_ORIGIN:
205         case WSI_TOKEN_SWORIGIN:
206         case WSI_TOKEN_DRAFT:
207         case WSI_TOKEN_CHALLENGE:
208         case WSI_TOKEN_KEY:
209         case WSI_TOKEN_VERSION:
210         case WSI_TOKEN_ACCEPT:
211         case WSI_TOKEN_NONCE:
212         case WSI_TOKEN_EXTENSIONS:
213         case WSI_TOKEN_HTTP:
214         case WSI_TOKEN_HTTP_ACCEPT:
215         case WSI_TOKEN_HTTP_AC_REQUEST_HEADERS:
216         case WSI_TOKEN_HTTP_IF_MODIFIED_SINCE:
217         case WSI_TOKEN_HTTP_IF_NONE_MATCH:
218         case WSI_TOKEN_HTTP_ACCEPT_ENCODING:
219         case WSI_TOKEN_HTTP_ACCEPT_LANGUAGE:
220         case WSI_TOKEN_HTTP_PRAGMA:
221         case WSI_TOKEN_HTTP_CACHE_CONTROL:
222         case WSI_TOKEN_HTTP_AUTHORIZATION:
223         case WSI_TOKEN_HTTP_COOKIE:
224         case WSI_TOKEN_HTTP_CONTENT_LENGTH:
225         case WSI_TOKEN_HTTP_CONTENT_TYPE:
226         case WSI_TOKEN_HTTP_DATE:
227         case WSI_TOKEN_HTTP_RANGE:
228         case WSI_TOKEN_HTTP_REFERER:
229
230
231                 lwsl_parser("WSI_TOK_(%d) '%c'\n", wsi->u.hdr.parser_state, c);
232
233                 /* collect into malloc'd buffers */
234                 /* optional initial space swallow */
235                 if (!wsi->u.hdr.ah->frags[wsi->u.hdr.ah->frag_index[
236                                       wsi->u.hdr.parser_state]].len && c == ' ')
237                         break;
238
239                 if ((wsi->u.hdr.parser_state != WSI_TOKEN_GET_URI) &&
240                         (wsi->u.hdr.parser_state != WSI_TOKEN_POST_URI) &&
241                         (wsi->u.hdr.parser_state != WSI_TOKEN_OPTIONS_URI))
242                         goto check_eol;
243
244                 /* special URI processing... end at space */
245
246                 if (c == ' ') {
247                         /* enforce starting with / */
248                         if (!wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len)
249                                 if (issue_char(wsi, '/') < 0)
250                                         return -1;
251                         c = '\0';
252                         wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
253                         goto spill;
254                 }
255
256                 /* special URI processing... convert %xx */
257
258                 switch (wsi->u.hdr.ues) {
259                 case URIES_IDLE:
260                         if (c == '%') {
261                                 wsi->u.hdr.ues = URIES_SEEN_PERCENT;
262                                 goto swallow;
263                         }
264                         break;
265                 case URIES_SEEN_PERCENT:
266                         if (char_to_hex(c) < 0) {
267                                 /* regurgitate */
268                                 if (issue_char(wsi, '%') < 0)
269                                         return -1;
270                                 wsi->u.hdr.ues = URIES_IDLE;
271                                 /* continue on to assess c */
272                                 break;
273                         }
274                         wsi->u.hdr.esc_stash = c;
275                         wsi->u.hdr.ues = URIES_SEEN_PERCENT_H1;
276                         goto swallow;
277                         
278                 case URIES_SEEN_PERCENT_H1:
279                         if (char_to_hex(c) < 0) {
280                                 /* regurgitate */
281                                 issue_char(wsi, '%');
282                                 wsi->u.hdr.ues = URIES_IDLE;
283                                 /* regurgitate + assess */
284                                 if (libwebsocket_parse(context, wsi, wsi->u.hdr.esc_stash) < 0)
285                                         return -1;
286                                 /* continue on to assess c */
287                                 break;
288                         }
289                         c = (char_to_hex(wsi->u.hdr.esc_stash) << 4) |
290                                         char_to_hex(c);
291                         wsi->u.hdr.ues = URIES_IDLE;
292                         break;
293                 }
294
295                 /*
296                  * special URI processing... 
297                  *  convert /.. or /... or /../ etc to /
298                  *  convert /./ to /
299                  *  convert // or /// etc to /
300                  *  leave /.dir or whatever alone
301                  */
302
303                 switch (wsi->u.hdr.ups) {
304                 case URIPS_IDLE:
305                         /* issue the first / always */
306                         if (c == '/')
307                                 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
308                         break;
309                 case URIPS_SEEN_SLASH:
310                         /* swallow subsequent slashes */
311                         if (c == '/')
312                                 goto swallow;
313                         /* track and swallow the first . after / */
314                         if (c == '.') {
315                                 wsi->u.hdr.ups = URIPS_SEEN_SLASH_DOT;
316                                 goto swallow;
317                         } else
318                                 wsi->u.hdr.ups = URIPS_IDLE;
319                         break;
320                 case URIPS_SEEN_SLASH_DOT:
321                         /* swallow second . */
322                         if (c == '.') {
323                                 /* 
324                                  * back up one dir level if possible
325                                  * safe against header fragmentation because
326                                  * the method URI can only be in 1 fragment
327                                  */
328                                 if (wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len > 2) {
329                                         wsi->u.hdr.ah->pos--;
330                                         wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len--;
331                                         do {
332                                                 wsi->u.hdr.ah->pos--;
333                                                 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len--;
334                                         } while (wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len > 1 &&
335                                                         wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos] != '/');
336                                 }
337                                 wsi->u.hdr.ups = URIPS_SEEN_SLASH_DOT_DOT;
338                                 goto swallow;
339                         }
340                         /* change /./ to / */
341                         if (c == '/') {
342                                 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
343                                 goto swallow;
344                         }
345                         /* it was like /.dir ... regurgitate the . */
346                         wsi->u.hdr.ups = URIPS_IDLE;
347                         issue_char(wsi, '.');
348                         break;
349                         
350                 case URIPS_SEEN_SLASH_DOT_DOT:
351                         /* swallow prior .. chars and any subsequent . */
352                         if (c == '.')
353                                 goto swallow;
354                         /* last issued was /, so another / == // */
355                         if (c == '/')
356                                 goto swallow;
357                         else /* last we issued was / so SEEN_SLASH */
358                                 wsi->u.hdr.ups = URIPS_SEEN_SLASH;
359                         break;
360                 case URIPS_ARGUMENTS:
361                         /* leave them alone */
362                         break;
363                 }
364
365 check_eol:
366
367                 /* bail at EOL */
368                 if (wsi->u.hdr.parser_state != WSI_TOKEN_CHALLENGE &&
369                                                                   c == '\x0d') {
370                         c = '\0';
371                         wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
372                         lwsl_parser("*\n");
373                 }
374
375                 if (c == '?') { /* start of URI arguments */
376                         /* seal off uri header */
377                         wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = '\0';
378
379                         /* move to using WSI_TOKEN_HTTP_URI_ARGS */
380                         wsi->u.hdr.ah->next_frag_index++;
381                         wsi->u.hdr.ah->frags[
382                                 wsi->u.hdr.ah->next_frag_index].offset =
383                                                              wsi->u.hdr.ah->pos;
384                         wsi->u.hdr.ah->frags[
385                                         wsi->u.hdr.ah->next_frag_index].len = 0;
386                         wsi->u.hdr.ah->frags[
387                             wsi->u.hdr.ah->next_frag_index].next_frag_index = 0;
388
389                         wsi->u.hdr.ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS] =
390                                                  wsi->u.hdr.ah->next_frag_index;
391
392                         /* defeat normal uri path processing */
393                         wsi->u.hdr.ups = URIPS_ARGUMENTS;
394                         goto swallow;
395                 }
396
397 spill:
398                 {
399                         int issue_result = issue_char(wsi, c);
400                         if (issue_result < 0) {
401                                 return -1;
402                         }
403                         else if(issue_result > 0) {
404                                 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
405                         };
406                 };
407 swallow:
408                 /* per-protocol end of headers management */
409
410                 if (wsi->u.hdr.parser_state == WSI_TOKEN_CHALLENGE)
411                         goto set_parsing_complete;
412                 break;
413
414                 /* collecting and checking a name part */
415         case WSI_TOKEN_NAME_PART:
416                 lwsl_parser("WSI_TOKEN_NAME_PART '%c'\n", c);
417
418                 wsi->u.hdr.lextable_pos =
419                                 lextable_decode(wsi->u.hdr.lextable_pos, c);
420
421                 if (wsi->u.hdr.lextable_pos < 0) {
422                         /* this is not a header we know about */
423                         if (wsi->u.hdr.ah->frag_index[WSI_TOKEN_GET_URI] ||
424                                 wsi->u.hdr.ah->frag_index[WSI_TOKEN_POST_URI] ||
425                                 wsi->u.hdr.ah->frag_index[WSI_TOKEN_OPTIONS_URI] ||
426                                 wsi->u.hdr.ah->frag_index[WSI_TOKEN_HTTP]) {
427                                 /*
428                                  * altready had the method, no idea what
429                                  * this crap is, ignore
430                                  */
431                                 wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
432                                 break;
433                         }
434                         /*
435                          * hm it's an unknown http method in fact,
436                          * treat as dangerous
437                          */
438
439                         lwsl_info("Unknown method - dropping\n");
440                         return -1;
441                 }
442                 if (lextable[wsi->u.hdr.lextable_pos] < FAIL_CHAR) {
443
444                         /* terminal state */
445
446                         n = (lextable[wsi->u.hdr.lextable_pos] << 8) | lextable[wsi->u.hdr.lextable_pos + 1];
447
448                         lwsl_parser("known hdr %d\n", n);
449                         if (n == WSI_TOKEN_GET_URI &&
450                                 wsi->u.hdr.ah->frag_index[WSI_TOKEN_GET_URI]) {
451                                 lwsl_warn("Duplicated GET\n");
452                                 return -1;
453                         } else if (n == WSI_TOKEN_POST_URI &&
454                                 wsi->u.hdr.ah->frag_index[WSI_TOKEN_POST_URI]) {
455                                 lwsl_warn("Duplicated POST\n");
456                                 return -1;
457                         } else if (n == WSI_TOKEN_OPTIONS_URI &&
458                                 wsi->u.hdr.ah->frag_index[WSI_TOKEN_OPTIONS_URI]) {
459                                 lwsl_warn("Duplicated OPTIONS\n");
460                                 return -1;
461                         }
462
463                         /*
464                          * WSORIGIN is protocol equiv to ORIGIN,
465                          * JWebSocket likes to send it, map to ORIGIN
466                          */
467                         if (n == WSI_TOKEN_SWORIGIN)
468                                 n = WSI_TOKEN_ORIGIN;
469
470                         wsi->u.hdr.parser_state = (enum lws_token_indexes)
471                                                         (WSI_TOKEN_GET_URI + n);
472
473                         if( context->token_limits ) {
474                                 wsi->u.hdr.current_token_limit = \
475                                         context->token_limits->token_limit[wsi->u.hdr.parser_state];
476                         }
477                         else {
478                                 wsi->u.hdr.current_token_limit = sizeof(wsi->u.hdr.ah->data);
479                         };
480
481                         if (wsi->u.hdr.parser_state == WSI_TOKEN_CHALLENGE)
482                                 goto set_parsing_complete;
483
484                         goto start_fragment;
485                 }
486                 break;
487
488 start_fragment:
489                 wsi->u.hdr.ah->next_frag_index++;
490                 if (wsi->u.hdr.ah->next_frag_index ==
491                                 sizeof(wsi->u.hdr.ah->frags) /
492                                               sizeof(wsi->u.hdr.ah->frags[0])) {
493                         lwsl_warn("More hdr frags than we can deal with\n");
494                         return -1;
495                 }
496
497                 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].offset =
498                                                              wsi->u.hdr.ah->pos;
499                 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len = 0;
500                 wsi->u.hdr.ah->frags[
501                             wsi->u.hdr.ah->next_frag_index].next_frag_index = 0;
502
503                 n = wsi->u.hdr.ah->frag_index[wsi->u.hdr.parser_state];
504                 if (!n) { /* first fragment */
505                         wsi->u.hdr.ah->frag_index[wsi->u.hdr.parser_state] =
506                                                  wsi->u.hdr.ah->next_frag_index;
507                         break;
508                 }
509                 /* continuation */
510                 while (wsi->u.hdr.ah->frags[n].next_frag_index)
511                                 n = wsi->u.hdr.ah->frags[n].next_frag_index;
512                 wsi->u.hdr.ah->frags[n].next_frag_index =
513                                                  wsi->u.hdr.ah->next_frag_index;
514
515                 if (wsi->u.hdr.ah->pos == sizeof(wsi->u.hdr.ah->data)) {
516                         lwsl_warn("excessive header content\n");
517                         return -1;
518                 }
519
520                 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = ' ';
521                 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len++;
522                 break;
523
524                 /* skipping arg part of a name we didn't recognize */
525         case WSI_TOKEN_SKIPPING:
526                 lwsl_parser("WSI_TOKEN_SKIPPING '%c'\n", c);
527
528                 if (c == '\x0d')
529                         wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
530                 break;
531
532         case WSI_TOKEN_SKIPPING_SAW_CR:
533                 lwsl_parser("WSI_TOKEN_SKIPPING_SAW_CR '%c'\n", c);
534                 if (c == '\x0a') {
535                         wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
536                         wsi->u.hdr.lextable_pos = 0;
537                 } else
538                         wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
539                 break;
540                 /* we're done, ignore anything else */
541
542         case WSI_PARSING_COMPLETE:
543                 lwsl_parser("WSI_PARSING_COMPLETE '%c'\n", c);
544                 break;
545
546         default:        /* keep gcc happy */
547                 break;
548         }
549
550         return 0;
551
552 set_parsing_complete:
553
554         if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
555                 if (lws_hdr_total_length(wsi, WSI_TOKEN_VERSION))
556                         wsi->ietf_spec_revision =
557                                atoi(lws_hdr_simple_ptr(wsi, WSI_TOKEN_VERSION));
558
559                 lwsl_parser("v%02d hdrs completed\n", wsi->ietf_spec_revision);
560         }
561         wsi->u.hdr.parser_state = WSI_PARSING_COMPLETE;
562         wsi->hdr_parsing_completed = 1;
563
564         return 0;
565 }
566
567
568 /**
569  * lws_frame_is_binary: true if the current frame was sent in binary mode
570  *
571  * @wsi: the connection we are inquiring about
572  *
573  * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
574  * it's interested to see if the frame it's dealing with was sent in binary
575  * mode.
576  */
577
578 LWS_VISIBLE int lws_frame_is_binary(struct libwebsocket *wsi)
579 {
580         return wsi->u.ws.frame_is_binary;
581 }
582
583 int
584 libwebsocket_rx_sm(struct libwebsocket *wsi, unsigned char c)
585 {
586         int n;
587         struct lws_tokens eff_buf;
588         int ret = 0;
589
590         switch (wsi->lws_rx_parse_state) {
591         case LWS_RXPS_NEW:
592
593                 switch (wsi->ietf_spec_revision) {
594                 case 13:
595                         /*
596                          * no prepended frame key any more
597                          */
598                         wsi->u.ws.all_zero_nonce = 1;
599                         goto handle_first;
600
601                 default:
602                         lwsl_warn("lws_rx_sm: unknown spec version %d\n",
603                                                        wsi->ietf_spec_revision);
604                         break;
605                 }
606                 break;
607         case LWS_RXPS_04_MASK_NONCE_1:
608                 wsi->u.ws.frame_masking_nonce_04[1] = c;
609                 if (c)
610                         wsi->u.ws.all_zero_nonce = 0;
611                 wsi->lws_rx_parse_state = LWS_RXPS_04_MASK_NONCE_2;
612                 break;
613         case LWS_RXPS_04_MASK_NONCE_2:
614                 wsi->u.ws.frame_masking_nonce_04[2] = c;
615                 if (c)
616                         wsi->u.ws.all_zero_nonce = 0;
617                 wsi->lws_rx_parse_state = LWS_RXPS_04_MASK_NONCE_3;
618                 break;
619         case LWS_RXPS_04_MASK_NONCE_3:
620                 wsi->u.ws.frame_masking_nonce_04[3] = c;
621                 if (c)
622                         wsi->u.ws.all_zero_nonce = 0;
623
624                 /*
625                  * start from the zero'th byte in the XOR key buffer since
626                  * this is the start of a frame with a new key
627                  */
628
629                 wsi->u.ws.frame_mask_index = 0;
630
631                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_1;
632                 break;
633
634         /*
635          *  04 logical framing from the spec (all this is masked when incoming
636          *  and has to be unmasked)
637          *
638          * We ignore the possibility of extension data because we don't
639          * negotiate any extensions at the moment.
640          *
641          *    0                   1                   2                   3
642          *    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
643          *   +-+-+-+-+-------+-+-------------+-------------------------------+
644          *   |F|R|R|R| opcode|R| Payload len |    Extended payload length    |
645          *   |I|S|S|S|  (4)  |S|     (7)     |             (16/63)           |
646          *   |N|V|V|V|       |V|             |   (if payload len==126/127)   |
647          *   | |1|2|3|       |4|             |                               |
648          *   +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
649          *   |     Extended payload length continued, if payload len == 127  |
650          *   + - - - - - - - - - - - - - - - +-------------------------------+
651          *   |                               |         Extension data        |
652          *   +-------------------------------+ - - - - - - - - - - - - - - - +
653          *   :                                                               :
654          *   +---------------------------------------------------------------+
655          *   :                       Application data                        :
656          *   +---------------------------------------------------------------+
657          *
658          *  We pass payload through to userland as soon as we get it, ignoring
659          *  FIN.  It's up to userland to buffer it up if it wants to see a
660          *  whole unfragmented block of the original size (which may be up to
661          *  2^63 long!)
662          */
663
664         case LWS_RXPS_04_FRAME_HDR_1:
665 handle_first:
666
667                 wsi->u.ws.opcode = c & 0xf;
668                 wsi->u.ws.rsv = c & 0x70;
669                 wsi->u.ws.final = !!((c >> 7) & 1);
670
671                 switch (wsi->u.ws.opcode) {
672                 case LWS_WS_OPCODE_07__TEXT_FRAME:
673                 case LWS_WS_OPCODE_07__BINARY_FRAME:
674                         wsi->u.ws.frame_is_binary =
675                              wsi->u.ws.opcode == LWS_WS_OPCODE_07__BINARY_FRAME;
676                         break;
677                 }
678                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;
679                 break;
680
681         case LWS_RXPS_04_FRAME_HDR_LEN:
682
683                 wsi->u.ws.this_frame_masked = !!(c & 0x80);
684
685                 switch (c & 0x7f) {
686                 case 126:
687                         /* control frames are not allowed to have big lengths */
688                         if (wsi->u.ws.opcode & 8)
689                                 goto illegal_ctl_length;
690
691                         wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;
692                         break;
693                 case 127:
694                         /* control frames are not allowed to have big lengths */
695                         if (wsi->u.ws.opcode & 8)
696                                 goto illegal_ctl_length;
697
698                         wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;
699                         break;
700                 default:
701                         wsi->u.ws.rx_packet_length = c & 0x7f;
702                         if (wsi->u.ws.this_frame_masked)
703                                 wsi->lws_rx_parse_state =
704                                                 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
705                         else
706                                 if (wsi->u.ws.rx_packet_length)
707                                         wsi->lws_rx_parse_state =
708                                         LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
709                                 else {
710                                         wsi->lws_rx_parse_state = LWS_RXPS_NEW;
711                                         goto spill;
712                                 }
713                         break;
714                 }
715                 break;
716
717         case LWS_RXPS_04_FRAME_HDR_LEN16_2:
718                 wsi->u.ws.rx_packet_length = c << 8;
719                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1;
720                 break;
721
722         case LWS_RXPS_04_FRAME_HDR_LEN16_1:
723                 wsi->u.ws.rx_packet_length |= c;
724                 if (wsi->u.ws.this_frame_masked)
725                         wsi->lws_rx_parse_state =
726                                         LWS_RXPS_07_COLLECT_FRAME_KEY_1;
727                 else
728                         wsi->lws_rx_parse_state =
729                                 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
730                 break;
731
732         case LWS_RXPS_04_FRAME_HDR_LEN64_8:
733                 if (c & 0x80) {
734                         lwsl_warn("b63 of length must be zero\n");
735                         /* kill the connection */
736                         return -1;
737                 }
738 #if defined __LP64__
739                 wsi->u.ws.rx_packet_length = ((size_t)c) << 56;
740 #else
741                 wsi->u.ws.rx_packet_length = 0;
742 #endif
743                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;
744                 break;
745
746         case LWS_RXPS_04_FRAME_HDR_LEN64_7:
747 #if defined __LP64__
748                 wsi->u.ws.rx_packet_length |= ((size_t)c) << 48;
749 #endif
750                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;
751                 break;
752
753         case LWS_RXPS_04_FRAME_HDR_LEN64_6:
754 #if defined __LP64__
755                 wsi->u.ws.rx_packet_length |= ((size_t)c) << 40;
756 #endif
757                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;
758                 break;
759
760         case LWS_RXPS_04_FRAME_HDR_LEN64_5:
761 #if defined __LP64__
762                 wsi->u.ws.rx_packet_length |= ((size_t)c) << 32;
763 #endif
764                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;
765                 break;
766
767         case LWS_RXPS_04_FRAME_HDR_LEN64_4:
768                 wsi->u.ws.rx_packet_length |= ((size_t)c) << 24;
769                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3;
770                 break;
771
772         case LWS_RXPS_04_FRAME_HDR_LEN64_3:
773                 wsi->u.ws.rx_packet_length |= ((size_t)c) << 16;
774                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2;
775                 break;
776
777         case LWS_RXPS_04_FRAME_HDR_LEN64_2:
778                 wsi->u.ws.rx_packet_length |= ((size_t)c) << 8;
779                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1;
780                 break;
781
782         case LWS_RXPS_04_FRAME_HDR_LEN64_1:
783                 wsi->u.ws.rx_packet_length |= ((size_t)c);
784                 if (wsi->u.ws.this_frame_masked)
785                         wsi->lws_rx_parse_state =
786                                         LWS_RXPS_07_COLLECT_FRAME_KEY_1;
787                 else
788                         wsi->lws_rx_parse_state =
789                                 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
790                 break;
791
792         case LWS_RXPS_07_COLLECT_FRAME_KEY_1:
793                 wsi->u.ws.frame_masking_nonce_04[0] = c;
794                 if (c)
795                         wsi->u.ws.all_zero_nonce = 0;
796                 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_2;
797                 break;
798
799         case LWS_RXPS_07_COLLECT_FRAME_KEY_2:
800                 wsi->u.ws.frame_masking_nonce_04[1] = c;
801                 if (c)
802                         wsi->u.ws.all_zero_nonce = 0;
803                 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_3;
804                 break;
805
806         case LWS_RXPS_07_COLLECT_FRAME_KEY_3:
807                 wsi->u.ws.frame_masking_nonce_04[2] = c;
808                 if (c)
809                         wsi->u.ws.all_zero_nonce = 0;
810                 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_4;
811                 break;
812
813         case LWS_RXPS_07_COLLECT_FRAME_KEY_4:
814                 wsi->u.ws.frame_masking_nonce_04[3] = c;
815                 if (c)
816                         wsi->u.ws.all_zero_nonce = 0;
817                 wsi->lws_rx_parse_state =
818                                         LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
819                 wsi->u.ws.frame_mask_index = 0;
820                 if (wsi->u.ws.rx_packet_length == 0) {
821                         wsi->lws_rx_parse_state = LWS_RXPS_NEW;
822                         goto spill;
823                 }
824                 break;
825
826
827         case LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED:
828
829                 if (!wsi->u.ws.rx_user_buffer)
830                         lwsl_err("NULL user buffer...\n");
831
832                 if (wsi->u.ws.all_zero_nonce)
833                         wsi->u.ws.rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
834                                (wsi->u.ws.rx_user_buffer_head++)] = c;
835                 else
836                         wsi->u.ws.rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
837                                (wsi->u.ws.rx_user_buffer_head++)] =
838                                    c ^ wsi->u.ws.frame_masking_nonce_04[
839                                             (wsi->u.ws.frame_mask_index++) & 3];
840
841                 if (--wsi->u.ws.rx_packet_length == 0) {
842                         /* spill because we have the whole frame */
843                         wsi->lws_rx_parse_state = LWS_RXPS_NEW;
844                         goto spill;
845                 }
846
847                 /*
848                  * if there's no protocol max frame size given, we are
849                  * supposed to default to LWS_MAX_SOCKET_IO_BUF
850                  */
851
852                 if (!wsi->protocol->rx_buffer_size &&
853                                         wsi->u.ws.rx_user_buffer_head !=
854                                                           LWS_MAX_SOCKET_IO_BUF)
855                         break;
856                 else
857                         if (wsi->protocol->rx_buffer_size &&
858                                         wsi->u.ws.rx_user_buffer_head !=
859                                                   wsi->protocol->rx_buffer_size)
860                         break;
861
862                 /* spill because we filled our rx buffer */
863 spill:
864                 /*
865                  * is this frame a control packet we should take care of at this
866                  * layer?  If so service it and hide it from the user callback
867                  */
868
869                 lwsl_parser("spill on %s\n", wsi->protocol->name);
870
871                 switch (wsi->u.ws.opcode) {
872                 case LWS_WS_OPCODE_07__CLOSE:
873                         /* is this an acknowledgement of our close? */
874                         if (wsi->state == WSI_STATE_AWAITING_CLOSE_ACK) {
875                                 /*
876                                  * fine he has told us he is closing too, let's
877                                  * finish our close
878                                  */
879                                 lwsl_parser("seen client close ack\n");
880                                 return -1;
881                         }
882                         lwsl_parser("server sees client close packet\n");
883                         /* parrot the close packet payload back */
884                         n = libwebsocket_write(wsi, (unsigned char *)
885                                 &wsi->u.ws.rx_user_buffer[
886                                         LWS_SEND_BUFFER_PRE_PADDING],
887                                         wsi->u.ws.rx_user_buffer_head,
888                                                                LWS_WRITE_CLOSE);
889                         if (n < 0)
890                                 lwsl_info("write of close ack failed %d\n", n);
891                         wsi->state = WSI_STATE_RETURNED_CLOSE_ALREADY;
892                         /* close the connection */
893                         return -1;
894
895                 case LWS_WS_OPCODE_07__PING:
896                         lwsl_info("received %d byte ping, sending pong\n",
897                                                  wsi->u.ws.rx_user_buffer_head);
898                         lwsl_hexdump(&wsi->u.ws.rx_user_buffer[
899                                         LWS_SEND_BUFFER_PRE_PADDING],
900                                                  wsi->u.ws.rx_user_buffer_head);
901                         /* parrot the ping packet payload back as a pong */
902                         n = libwebsocket_write(wsi, (unsigned char *)
903                         &wsi->u.ws.rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
904                                  wsi->u.ws.rx_user_buffer_head, LWS_WRITE_PONG);
905                         if (n < 0)
906                                 return -1;
907                         /* ... then just drop it */
908                         wsi->u.ws.rx_user_buffer_head = 0;
909                         return 0;
910
911                 case LWS_WS_OPCODE_07__PONG:
912                         /* ... then just drop it */
913                         wsi->u.ws.rx_user_buffer_head = 0;
914                         return 0;
915
916                 case LWS_WS_OPCODE_07__TEXT_FRAME:
917                 case LWS_WS_OPCODE_07__BINARY_FRAME:
918                 case LWS_WS_OPCODE_07__CONTINUATION:
919                         break;
920
921                 default:
922                         lwsl_parser("passing opc %x up to exts\n",
923                                                         wsi->u.ws.opcode);
924                         /*
925                          * It's something special we can't understand here.
926                          * Pass the payload up to the extension's parsing
927                          * state machine.
928                          */
929
930                         eff_buf.token = &wsi->u.ws.rx_user_buffer[
931                                                    LWS_SEND_BUFFER_PRE_PADDING];
932                         eff_buf.token_len = wsi->u.ws.rx_user_buffer_head;
933
934                         if (lws_ext_callback_for_each_active(wsi,
935                                 LWS_EXT_CALLBACK_EXTENDED_PAYLOAD_RX,
936                                         &eff_buf, 0) <= 0) /* not handle or fail */
937                                 lwsl_ext("ext opc opcode 0x%x unknown\n",
938                                                               wsi->u.ws.opcode);
939
940                         wsi->u.ws.rx_user_buffer_head = 0;
941                         return 0;
942                 }
943
944                 /*
945                  * No it's real payload, pass it up to the user callback.
946                  * It's nicely buffered with the pre-padding taken care of
947                  * so it can be sent straight out again using libwebsocket_write
948                  */
949
950                 eff_buf.token = &wsi->u.ws.rx_user_buffer[
951                                                 LWS_SEND_BUFFER_PRE_PADDING];
952                 eff_buf.token_len = wsi->u.ws.rx_user_buffer_head;
953                 
954                 if (lws_ext_callback_for_each_active(wsi,
955                                 LWS_EXT_CALLBACK_PAYLOAD_RX, &eff_buf, 0) < 0)
956                         return -1;
957
958                 if (eff_buf.token_len > 0) {
959                         eff_buf.token[eff_buf.token_len] = '\0';
960
961                         if (wsi->protocol->callback)
962                                 ret = user_callback_handle_rxflow(
963                                                 wsi->protocol->callback,
964                                                 wsi->protocol->owning_server,
965                                                 wsi, LWS_CALLBACK_RECEIVE,
966                                                 wsi->user_space,
967                                                 eff_buf.token,
968                                                 eff_buf.token_len);
969                     else
970                             lwsl_err("No callback on payload spill!\n");
971                 }
972
973                 wsi->u.ws.rx_user_buffer_head = 0;
974                 break;
975         }
976
977         return ret;
978
979 illegal_ctl_length:
980
981         lwsl_warn("Control frame with xtended length is illegal\n");
982         /* kill the connection */
983         return -1;
984 }
985
986
987 /**
988  * libwebsockets_remaining_packet_payload() - Bytes to come before "overall"
989  *                                            rx packet is complete
990  * @wsi:                Websocket instance (available from user callback)
991  *
992  *      This function is intended to be called from the callback if the
993  *  user code is interested in "complete packets" from the client.
994  *  libwebsockets just passes through payload as it comes and issues a buffer
995  *  additionally when it hits a built-in limit.  The LWS_CALLBACK_RECEIVE
996  *  callback handler can use this API to find out if the buffer it has just
997  *  been given is the last piece of a "complete packet" from the client --
998  *  when that is the case libwebsockets_remaining_packet_payload() will return
999  *  0.
1000  *
1001  *  Many protocols won't care becuse their packets are always small.
1002  */
1003
1004 LWS_VISIBLE size_t
1005 libwebsockets_remaining_packet_payload(struct libwebsocket *wsi)
1006 {
1007         return wsi->u.ws.rx_packet_length;
1008 }