C89 tweaks as per #348.
[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
46                 if (lextable[pos] == FAIL_CHAR)
47                         return -1;
48
49                 /* b7 = 0, end or 3-byte */
50                 if (lextable[pos] < FAIL_CHAR) /* terminal marker */
51                         return pos;
52
53                 if (lextable[pos] == c) /* goto */
54                         return pos + (lextable[pos + 1]) +
55                                                 (lextable[pos + 2] << 8);
56                 /* fall thru goto */
57                 pos += 3;
58                 /* continue */
59         }
60 }
61
62 int lws_allocate_header_table(struct libwebsocket *wsi)
63 {
64         /* Be sure to free any existing header data to avoid mem leak: */
65         lws_free_header_table(wsi);
66         wsi->u.hdr.ah = lws_malloc(sizeof(*wsi->u.hdr.ah));
67         if (wsi->u.hdr.ah == NULL) {
68                 lwsl_err("Out of memory\n");
69                 return -1;
70         }
71         memset(wsi->u.hdr.ah->frag_index, 0, sizeof(wsi->u.hdr.ah->frag_index));
72         wsi->u.hdr.ah->next_frag_index = 0;
73         wsi->u.hdr.ah->pos = 0;
74
75         return 0;
76 }
77
78 int lws_free_header_table(struct libwebsocket *wsi)
79 {
80         lws_free2(wsi->u.hdr.ah);
81         wsi->u.hdr.ah = NULL;
82         return 0;
83 };
84
85 LWS_VISIBLE int lws_hdr_total_length(struct libwebsocket *wsi, enum lws_token_indexes h)
86 {
87         int n;
88         int len = 0;
89
90         n = wsi->u.hdr.ah->frag_index[h];
91         if (!n)
92                 return 0;
93         do {
94                 len += wsi->u.hdr.ah->frags[n].len;
95                 n = wsi->u.hdr.ah->frags[n].next_frag_index;
96         } while (n);
97
98         return len;
99 }
100
101 LWS_VISIBLE int lws_hdr_copy(struct libwebsocket *wsi, char *dest, int len,
102                                                 enum lws_token_indexes h)
103 {
104         int toklen = lws_hdr_total_length(wsi, h);
105         int n;
106
107         if (toklen >= len)
108                 return -1;
109
110         n = wsi->u.hdr.ah->frag_index[h];
111         if (!n)
112                 return 0;
113
114         do {
115                 strcpy(dest,
116                         &wsi->u.hdr.ah->data[wsi->u.hdr.ah->frags[n].offset]);
117                 dest += wsi->u.hdr.ah->frags[n].len;
118                 n = wsi->u.hdr.ah->frags[n].next_frag_index;
119         } while (n);
120
121         return toklen;
122 }
123
124 char *lws_hdr_simple_ptr(struct libwebsocket *wsi, enum lws_token_indexes h)
125 {
126         int n;
127
128         n = wsi->u.hdr.ah->frag_index[h];
129         if (!n)
130                 return NULL;
131
132         return &wsi->u.hdr.ah->data[wsi->u.hdr.ah->frags[n].offset];
133 }
134
135 int lws_hdr_simple_create(struct libwebsocket *wsi,
136                                 enum lws_token_indexes h, const char *s)
137 {
138         wsi->u.hdr.ah->next_frag_index++;
139         if (wsi->u.hdr.ah->next_frag_index ==
140                sizeof(wsi->u.hdr.ah->frags) / sizeof(wsi->u.hdr.ah->frags[0])) {
141                 lwsl_warn("More hdr frags than we can deal with, dropping\n");
142                 return -1;
143         }
144
145         wsi->u.hdr.ah->frag_index[h] = wsi->u.hdr.ah->next_frag_index;
146
147         wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].offset =
148                                                              wsi->u.hdr.ah->pos;
149         wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len = 0;
150         wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].next_frag_index =
151                                                                               0;
152
153         do {
154                 if (wsi->u.hdr.ah->pos == sizeof(wsi->u.hdr.ah->data)) {
155                         lwsl_err("Ran out of header data space\n");
156                         return -1;
157                 }
158                 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = *s;
159                 if (*s)
160                         wsi->u.hdr.ah->frags[
161                                         wsi->u.hdr.ah->next_frag_index].len++;
162         } while (*s++);
163
164         return 0;
165 }
166
167 static signed char char_to_hex(const char c)
168 {
169         if (c >= '0' && c <= '9')
170                 return c - '0';
171
172         if (c >= 'a' && c <= 'f')
173                 return c - 'a' + 10;
174
175         if (c >= 'A' && c <= 'F')
176                 return c - 'A' + 10;
177
178         return -1;
179 }
180
181 static int issue_char(struct libwebsocket *wsi, unsigned char c)
182 {
183         unsigned short frag_len;
184         if (wsi->u.hdr.ah->pos == sizeof(wsi->u.hdr.ah->data)) {
185                 lwsl_warn("excessive header content\n");
186                 return -1;
187         }
188
189         frag_len = \
190                 wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len;
191         /* If we haven't hit the token limit, just copy the character into
192          * the header: */
193         if( frag_len < wsi->u.hdr.current_token_limit ) {
194                 wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = c;
195                 if (c)
196                         wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len++;
197                 return 0;
198         }
199         else {
200                 /* Insert a null character when we *hit* the limit: */
201                 if( frag_len == wsi->u.hdr.current_token_limit ) {
202                         wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = '\0';
203                         lwsl_warn("header %i exceeds limit\n", wsi->u.hdr.parser_state);
204                 };
205         };
206         return 1;
207 }
208
209 int libwebsocket_parse(
210                 struct libwebsocket_context *context,
211                 struct libwebsocket *wsi, unsigned char c)
212 {
213         static const unsigned char methods[] = {
214                 WSI_TOKEN_GET_URI,
215                 WSI_TOKEN_POST_URI,
216                 WSI_TOKEN_OPTIONS_URI,
217                 WSI_TOKEN_PUT_URI,
218                 WSI_TOKEN_PATCH_URI,
219                 WSI_TOKEN_DELETE_URI,
220         };
221         unsigned int n, m;
222
223         switch (wsi->u.hdr.parser_state) {
224         default:
225
226                 lwsl_parser("WSI_TOK_(%d) '%c'\n", wsi->u.hdr.parser_state, c);
227
228                 /* collect into malloc'd buffers */
229                 /* optional initial space swallow */
230                 if (!wsi->u.hdr.ah->frags[wsi->u.hdr.ah->frag_index[
231                                       wsi->u.hdr.parser_state]].len && c == ' ')
232                         break;
233
234                 for (m = 0; m < ARRAY_SIZE(methods); m++)
235                         if (wsi->u.hdr.parser_state == methods[m])
236                                 break;
237                 if (m == ARRAY_SIZE(methods))
238                         /* it was not any of the methods */
239                         goto check_eol;
240
241                 /* special URI processing... end at space */
242
243                 if (c == ' ') {
244                         /* enforce starting with / */
245                         if (!wsi->u.hdr.ah->frags[wsi->u.hdr.ah->next_frag_index].len)
246                                 if (issue_char(wsi, '/') < 0)
247                                         return -1;
248
249                         /* begin parsing HTTP version: */
250                         if (issue_char(wsi, '\0') < 0)
251                                 return -1;
252                         wsi->u.hdr.parser_state = WSI_TOKEN_HTTP;
253                         goto start_fragment;
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                         }
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                         /* 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                 if (c == '?') { /* start of URI arguments */
366                         /* seal off uri header */
367                         wsi->u.hdr.ah->data[wsi->u.hdr.ah->pos++] = '\0';
368
369                         /* move to using WSI_TOKEN_HTTP_URI_ARGS */
370                         wsi->u.hdr.ah->next_frag_index++;
371                         wsi->u.hdr.ah->frags[
372                                 wsi->u.hdr.ah->next_frag_index].offset =
373                                                              wsi->u.hdr.ah->pos;
374                         wsi->u.hdr.ah->frags[
375                                         wsi->u.hdr.ah->next_frag_index].len = 0;
376                         wsi->u.hdr.ah->frags[
377                             wsi->u.hdr.ah->next_frag_index].next_frag_index = 0;
378
379                         wsi->u.hdr.ah->frag_index[WSI_TOKEN_HTTP_URI_ARGS] =
380                                                  wsi->u.hdr.ah->next_frag_index;
381
382                         /* defeat normal uri path processing */
383                         wsi->u.hdr.ups = URIPS_ARGUMENTS;
384                         goto swallow;
385                 }
386
387 check_eol:
388
389                 /* bail at EOL */
390                 if (wsi->u.hdr.parser_state != WSI_TOKEN_CHALLENGE &&
391                                                                   c == '\x0d') {
392                         c = '\0';
393                         wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
394                         lwsl_parser("*\n");
395                 }
396
397                 n = issue_char(wsi, c);
398                 if ((int)n < 0)
399                         return -1;
400                 if (n > 0)
401                         wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
402
403 swallow:
404                 /* per-protocol end of headers management */
405
406                 if (wsi->u.hdr.parser_state == WSI_TOKEN_CHALLENGE)
407                         goto set_parsing_complete;
408                 break;
409
410                 /* collecting and checking a name part */
411         case WSI_TOKEN_NAME_PART:
412                 lwsl_parser("WSI_TOKEN_NAME_PART '%c' (mode=%d)\n", c, wsi->mode);
413
414                 wsi->u.hdr.lextable_pos =
415                                 lextable_decode(wsi->u.hdr.lextable_pos, c);
416                 /*
417                  * Server needs to look out for unknown methods...
418                  */
419                 if (wsi->u.hdr.lextable_pos < 0 &&
420                     wsi->mode == LWS_CONNMODE_HTTP_SERVING) {
421                         /* this is not a header we know about */
422                         for (m = 0; m < ARRAY_SIZE(methods); m++)
423                                 if (wsi->u.hdr.ah->frag_index[methods[m]]) {
424                                         /*
425                                          * already had the method, no idea what
426                                          * this crap from the client is, ignore
427                                          */
428                                         wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
429                                         break;
430                                 }
431                         /*
432                          * hm it's an unknown http method from a client in fact,
433                          * treat as dangerous
434                          */
435                         if (m == ARRAY_SIZE(methods)) {
436                                 lwsl_info("Unknown method - dropping\n");
437                                 return -1;
438                         }
439                         break;
440                 }
441                 /*
442                  * ...otherwise for a client, let him ignore unknown headers
443                  * coming from the server
444                  */
445                 if (wsi->u.hdr.lextable_pos < 0) {
446                         wsi->u.hdr.parser_state = WSI_TOKEN_SKIPPING;
447                         break;
448                 }
449
450                 if (lextable[wsi->u.hdr.lextable_pos] < FAIL_CHAR) {
451                         /* terminal state */
452
453                         n = ((unsigned int)lextable[wsi->u.hdr.lextable_pos] << 8) |
454                                         lextable[wsi->u.hdr.lextable_pos + 1];
455
456                         lwsl_parser("known hdr %d\n", n);
457                         for (m = 0; m < ARRAY_SIZE(methods); m++)
458                                 if (n == methods[m] &&
459                                                 wsi->u.hdr.ah->frag_index[
460                                                         methods[m]]) {
461                                         lwsl_warn("Duplicated method\n");
462                                         return -1;
463                                 }
464
465                         /*
466                          * WSORIGIN is protocol equiv to ORIGIN,
467                          * JWebSocket likes to send it, map to ORIGIN
468                          */
469                         if (n == WSI_TOKEN_SWORIGIN)
470                                 n = WSI_TOKEN_ORIGIN;
471
472                         wsi->u.hdr.parser_state = (enum lws_token_indexes)
473                                                         (WSI_TOKEN_GET_URI + n);
474
475                         if (context->token_limits)
476                                 wsi->u.hdr.current_token_limit =
477                                         context->token_limits->token_limit[wsi->u.hdr.parser_state];
478                         else
479                                 wsi->u.hdr.current_token_limit = sizeof(wsi->u.hdr.ah->data);
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
547         return 0;
548
549 set_parsing_complete:
550
551         if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
552                 if (lws_hdr_total_length(wsi, WSI_TOKEN_VERSION))
553                         wsi->ietf_spec_revision =
554                                atoi(lws_hdr_simple_ptr(wsi, WSI_TOKEN_VERSION));
555
556                 lwsl_parser("v%02d hdrs completed\n", wsi->ietf_spec_revision);
557         }
558         wsi->u.hdr.parser_state = WSI_PARSING_COMPLETE;
559         wsi->hdr_parsing_completed = 1;
560
561         return 0;
562 }
563
564
565 /**
566  * lws_frame_is_binary: true if the current frame was sent in binary mode
567  *
568  * @wsi: the connection we are inquiring about
569  *
570  * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
571  * it's interested to see if the frame it's dealing with was sent in binary
572  * mode.
573  */
574
575 LWS_VISIBLE int lws_frame_is_binary(struct libwebsocket *wsi)
576 {
577         return wsi->u.ws.frame_is_binary;
578 }
579
580 int
581 libwebsocket_rx_sm(struct libwebsocket *wsi, unsigned char c)
582 {
583         struct lws_tokens eff_buf;
584         int ret = 0;
585         int callback_action = LWS_CALLBACK_RECEIVE;
586
587         switch (wsi->lws_rx_parse_state) {
588         case LWS_RXPS_NEW:
589
590                 switch (wsi->ietf_spec_revision) {
591                 case 13:
592                         /*
593                          * no prepended frame key any more
594                          */
595                         wsi->u.ws.all_zero_nonce = 1;
596                         goto handle_first;
597
598                 default:
599                         lwsl_warn("lws_rx_sm: unknown spec version %d\n",
600                                                        wsi->ietf_spec_revision);
601                         break;
602                 }
603                 break;
604         case LWS_RXPS_04_MASK_NONCE_1:
605                 wsi->u.ws.frame_masking_nonce_04[1] = c;
606                 if (c)
607                         wsi->u.ws.all_zero_nonce = 0;
608                 wsi->lws_rx_parse_state = LWS_RXPS_04_MASK_NONCE_2;
609                 break;
610         case LWS_RXPS_04_MASK_NONCE_2:
611                 wsi->u.ws.frame_masking_nonce_04[2] = c;
612                 if (c)
613                         wsi->u.ws.all_zero_nonce = 0;
614                 wsi->lws_rx_parse_state = LWS_RXPS_04_MASK_NONCE_3;
615                 break;
616         case LWS_RXPS_04_MASK_NONCE_3:
617                 wsi->u.ws.frame_masking_nonce_04[3] = c;
618                 if (c)
619                         wsi->u.ws.all_zero_nonce = 0;
620
621                 /*
622                  * start from the zero'th byte in the XOR key buffer since
623                  * this is the start of a frame with a new key
624                  */
625
626                 wsi->u.ws.frame_mask_index = 0;
627
628                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_1;
629                 break;
630
631         /*
632          *  04 logical framing from the spec (all this is masked when incoming
633          *  and has to be unmasked)
634          *
635          * We ignore the possibility of extension data because we don't
636          * negotiate any extensions at the moment.
637          *
638          *    0                   1                   2                   3
639          *    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
640          *   +-+-+-+-+-------+-+-------------+-------------------------------+
641          *   |F|R|R|R| opcode|R| Payload len |    Extended payload length    |
642          *   |I|S|S|S|  (4)  |S|     (7)     |             (16/63)           |
643          *   |N|V|V|V|       |V|             |   (if payload len==126/127)   |
644          *   | |1|2|3|       |4|             |                               |
645          *   +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
646          *   |     Extended payload length continued, if payload len == 127  |
647          *   + - - - - - - - - - - - - - - - +-------------------------------+
648          *   |                               |         Extension data        |
649          *   +-------------------------------+ - - - - - - - - - - - - - - - +
650          *   :                                                               :
651          *   +---------------------------------------------------------------+
652          *   :                       Application data                        :
653          *   +---------------------------------------------------------------+
654          *
655          *  We pass payload through to userland as soon as we get it, ignoring
656          *  FIN.  It's up to userland to buffer it up if it wants to see a
657          *  whole unfragmented block of the original size (which may be up to
658          *  2^63 long!)
659          */
660
661         case LWS_RXPS_04_FRAME_HDR_1:
662 handle_first:
663
664                 wsi->u.ws.opcode = c & 0xf;
665                 wsi->u.ws.rsv = c & 0x70;
666                 wsi->u.ws.final = !!((c >> 7) & 1);
667
668                 switch (wsi->u.ws.opcode) {
669                 case LWS_WS_OPCODE_07__TEXT_FRAME:
670                 case LWS_WS_OPCODE_07__BINARY_FRAME:
671                         wsi->u.ws.frame_is_binary =
672                              wsi->u.ws.opcode == LWS_WS_OPCODE_07__BINARY_FRAME;
673                         break;
674                 }
675                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;
676                 break;
677
678         case LWS_RXPS_04_FRAME_HDR_LEN:
679
680                 wsi->u.ws.this_frame_masked = !!(c & 0x80);
681
682                 switch (c & 0x7f) {
683                 case 126:
684                         /* control frames are not allowed to have big lengths */
685                         if (wsi->u.ws.opcode & 8)
686                                 goto illegal_ctl_length;
687
688                         wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;
689                         break;
690                 case 127:
691                         /* control frames are not allowed to have big lengths */
692                         if (wsi->u.ws.opcode & 8)
693                                 goto illegal_ctl_length;
694
695                         wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;
696                         break;
697                 default:
698                         wsi->u.ws.rx_packet_length = c & 0x7f;
699                         if (wsi->u.ws.this_frame_masked)
700                                 wsi->lws_rx_parse_state =
701                                                 LWS_RXPS_07_COLLECT_FRAME_KEY_1;
702                         else
703                                 if (wsi->u.ws.rx_packet_length)
704                                         wsi->lws_rx_parse_state =
705                                         LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
706                                 else {
707                                         wsi->lws_rx_parse_state = LWS_RXPS_NEW;
708                                         goto spill;
709                                 }
710                         break;
711                 }
712                 break;
713
714         case LWS_RXPS_04_FRAME_HDR_LEN16_2:
715                 wsi->u.ws.rx_packet_length = c << 8;
716                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1;
717                 break;
718
719         case LWS_RXPS_04_FRAME_HDR_LEN16_1:
720                 wsi->u.ws.rx_packet_length |= c;
721                 if (wsi->u.ws.this_frame_masked)
722                         wsi->lws_rx_parse_state =
723                                         LWS_RXPS_07_COLLECT_FRAME_KEY_1;
724                 else
725                         wsi->lws_rx_parse_state =
726                                 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
727                 break;
728
729         case LWS_RXPS_04_FRAME_HDR_LEN64_8:
730                 if (c & 0x80) {
731                         lwsl_warn("b63 of length must be zero\n");
732                         /* kill the connection */
733                         return -1;
734                 }
735 #if defined __LP64__
736                 wsi->u.ws.rx_packet_length = ((size_t)c) << 56;
737 #else
738                 wsi->u.ws.rx_packet_length = 0;
739 #endif
740                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;
741                 break;
742
743         case LWS_RXPS_04_FRAME_HDR_LEN64_7:
744 #if defined __LP64__
745                 wsi->u.ws.rx_packet_length |= ((size_t)c) << 48;
746 #endif
747                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;
748                 break;
749
750         case LWS_RXPS_04_FRAME_HDR_LEN64_6:
751 #if defined __LP64__
752                 wsi->u.ws.rx_packet_length |= ((size_t)c) << 40;
753 #endif
754                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;
755                 break;
756
757         case LWS_RXPS_04_FRAME_HDR_LEN64_5:
758 #if defined __LP64__
759                 wsi->u.ws.rx_packet_length |= ((size_t)c) << 32;
760 #endif
761                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;
762                 break;
763
764         case LWS_RXPS_04_FRAME_HDR_LEN64_4:
765                 wsi->u.ws.rx_packet_length |= ((size_t)c) << 24;
766                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3;
767                 break;
768
769         case LWS_RXPS_04_FRAME_HDR_LEN64_3:
770                 wsi->u.ws.rx_packet_length |= ((size_t)c) << 16;
771                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2;
772                 break;
773
774         case LWS_RXPS_04_FRAME_HDR_LEN64_2:
775                 wsi->u.ws.rx_packet_length |= ((size_t)c) << 8;
776                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1;
777                 break;
778
779         case LWS_RXPS_04_FRAME_HDR_LEN64_1:
780                 wsi->u.ws.rx_packet_length |= ((size_t)c);
781                 if (wsi->u.ws.this_frame_masked)
782                         wsi->lws_rx_parse_state =
783                                         LWS_RXPS_07_COLLECT_FRAME_KEY_1;
784                 else
785                         wsi->lws_rx_parse_state =
786                                 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
787                 break;
788
789         case LWS_RXPS_07_COLLECT_FRAME_KEY_1:
790                 wsi->u.ws.frame_masking_nonce_04[0] = c;
791                 if (c)
792                         wsi->u.ws.all_zero_nonce = 0;
793                 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_2;
794                 break;
795
796         case LWS_RXPS_07_COLLECT_FRAME_KEY_2:
797                 wsi->u.ws.frame_masking_nonce_04[1] = c;
798                 if (c)
799                         wsi->u.ws.all_zero_nonce = 0;
800                 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_3;
801                 break;
802
803         case LWS_RXPS_07_COLLECT_FRAME_KEY_3:
804                 wsi->u.ws.frame_masking_nonce_04[2] = c;
805                 if (c)
806                         wsi->u.ws.all_zero_nonce = 0;
807                 wsi->lws_rx_parse_state = LWS_RXPS_07_COLLECT_FRAME_KEY_4;
808                 break;
809
810         case LWS_RXPS_07_COLLECT_FRAME_KEY_4:
811                 wsi->u.ws.frame_masking_nonce_04[3] = c;
812                 if (c)
813                         wsi->u.ws.all_zero_nonce = 0;
814                 wsi->lws_rx_parse_state =
815                                         LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
816                 wsi->u.ws.frame_mask_index = 0;
817                 if (wsi->u.ws.rx_packet_length == 0) {
818                         wsi->lws_rx_parse_state = LWS_RXPS_NEW;
819                         goto spill;
820                 }
821                 break;
822
823
824         case LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED:
825
826                 if (!wsi->u.ws.rx_user_buffer) {
827                         lwsl_err("NULL user buffer...\n");
828                         return 1;
829                 }
830
831                 if (wsi->u.ws.all_zero_nonce)
832                         wsi->u.ws.rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
833                                (wsi->u.ws.rx_user_buffer_head++)] = c;
834                 else
835                         wsi->u.ws.rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
836                                (wsi->u.ws.rx_user_buffer_head++)] =
837                                    c ^ wsi->u.ws.frame_masking_nonce_04[
838                                             (wsi->u.ws.frame_mask_index++) & 3];
839
840                 if (--wsi->u.ws.rx_packet_length == 0) {
841                         /* spill because we have the whole frame */
842                         wsi->lws_rx_parse_state = LWS_RXPS_NEW;
843                         goto spill;
844                 }
845
846                 /*
847                  * if there's no protocol max frame size given, we are
848                  * supposed to default to LWS_MAX_SOCKET_IO_BUF
849                  */
850
851                 if (!wsi->protocol->rx_buffer_size &&
852                                         wsi->u.ws.rx_user_buffer_head !=
853                                                           LWS_MAX_SOCKET_IO_BUF)
854                         break;
855                 else
856                         if (wsi->protocol->rx_buffer_size &&
857                                         wsi->u.ws.rx_user_buffer_head !=
858                                                   wsi->protocol->rx_buffer_size)
859                         break;
860
861                 /* spill because we filled our rx buffer */
862 spill:
863                 /*
864                  * is this frame a control packet we should take care of at this
865                  * layer?  If so service it and hide it from the user callback
866                  */
867
868                 lwsl_parser("spill on %s\n", wsi->protocol->name);
869
870                 switch (wsi->u.ws.opcode) {
871                 case LWS_WS_OPCODE_07__CLOSE:
872                         /* is this an acknowledgement of our close? */
873                         if (wsi->state == WSI_STATE_AWAITING_CLOSE_ACK) {
874                                 /*
875                                  * fine he has told us he is closing too, let's
876                                  * finish our close
877                                  */
878                                 lwsl_parser("seen client close ack\n");
879                                 return -1;
880                         }
881                         if (wsi->state == WSI_STATE_RETURNED_CLOSE_ALREADY)
882                                 /* if he sends us 2 CLOSE, kill him */
883                                 return -1;
884
885                         lwsl_parser("server sees client close packet\n");
886                         wsi->state = WSI_STATE_RETURNED_CLOSE_ALREADY;
887                         /* deal with the close packet contents as a PONG */
888                         wsi->u.ws.payload_is_close = 1;
889                         goto process_as_ping;
890
891                 case LWS_WS_OPCODE_07__PING:
892                         lwsl_info("received %d byte ping, sending pong\n",
893                                                  wsi->u.ws.rx_user_buffer_head);
894
895                         if (wsi->u.ws.ping_pending_flag) {
896                                 /* 
897                                  * there is already a pending ping payload
898                                  * we should just log and drop
899                                  */
900                                 lwsl_parser("DROP PING since one pending\n");
901                                 goto ping_drop;
902                         }
903 process_as_ping:
904                         /* control packets can only be < 128 bytes long */
905                         if (wsi->u.ws.rx_user_buffer_head > 128 - 4) {
906                                 lwsl_parser("DROP PING payload too large\n");
907                                 goto ping_drop;
908                         }
909                         
910                         /* if existing buffer is too small, drop it */
911                         if (wsi->u.ws.ping_payload_buf &&
912                             wsi->u.ws.ping_payload_alloc < wsi->u.ws.rx_user_buffer_head) {
913                                 lws_free2(wsi->u.ws.ping_payload_buf);
914                         }
915
916                         /* if no buffer, allocate it */
917                         if (!wsi->u.ws.ping_payload_buf) {
918                                 wsi->u.ws.ping_payload_buf = lws_malloc(wsi->u.ws.rx_user_buffer_head
919                                                                         + LWS_SEND_BUFFER_PRE_PADDING);
920                                 wsi->u.ws.ping_payload_alloc = wsi->u.ws.rx_user_buffer_head;
921                         }
922                         
923                         /* stash the pong payload */
924                         memcpy(wsi->u.ws.ping_payload_buf + LWS_SEND_BUFFER_PRE_PADDING,
925                                &wsi->u.ws.rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
926                                 wsi->u.ws.rx_user_buffer_head);
927                         
928                         wsi->u.ws.ping_payload_len = wsi->u.ws.rx_user_buffer_head;
929                         wsi->u.ws.ping_pending_flag = 1;
930                         
931                         /* get it sent as soon as possible */
932                         libwebsocket_callback_on_writable(wsi->protocol->owning_server, wsi);
933 ping_drop:
934                         wsi->u.ws.rx_user_buffer_head = 0;
935                         return 0;
936
937                 case LWS_WS_OPCODE_07__PONG:
938                         lwsl_info("received pong\n");
939                         lwsl_hexdump(&wsi->u.ws.rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
940                                      wsi->u.ws.rx_user_buffer_head);
941
942                         /* issue it */
943                         callback_action = LWS_CALLBACK_RECEIVE_PONG;
944                         break;
945
946                 case LWS_WS_OPCODE_07__TEXT_FRAME:
947                 case LWS_WS_OPCODE_07__BINARY_FRAME:
948                 case LWS_WS_OPCODE_07__CONTINUATION:
949                         break;
950
951                 default:
952                         lwsl_parser("passing opc %x up to exts\n",
953                                                         wsi->u.ws.opcode);
954                         /*
955                          * It's something special we can't understand here.
956                          * Pass the payload up to the extension's parsing
957                          * state machine.
958                          */
959
960                         eff_buf.token = &wsi->u.ws.rx_user_buffer[
961                                                    LWS_SEND_BUFFER_PRE_PADDING];
962                         eff_buf.token_len = wsi->u.ws.rx_user_buffer_head;
963
964                         if (lws_ext_callback_for_each_active(wsi,
965                                 LWS_EXT_CALLBACK_EXTENDED_PAYLOAD_RX,
966                                         &eff_buf, 0) <= 0) /* not handle or fail */
967                                 lwsl_ext("ext opc opcode 0x%x unknown\n",
968                                                               wsi->u.ws.opcode);
969
970                         wsi->u.ws.rx_user_buffer_head = 0;
971                         return 0;
972                 }
973
974                 /*
975                  * No it's real payload, pass it up to the user callback.
976                  * It's nicely buffered with the pre-padding taken care of
977                  * so it can be sent straight out again using libwebsocket_write
978                  */
979
980                 eff_buf.token = &wsi->u.ws.rx_user_buffer[
981                                                 LWS_SEND_BUFFER_PRE_PADDING];
982                 eff_buf.token_len = wsi->u.ws.rx_user_buffer_head;
983                 
984                 if (lws_ext_callback_for_each_active(wsi,
985                                 LWS_EXT_CALLBACK_PAYLOAD_RX, &eff_buf, 0) < 0)
986                         return -1;
987
988                 if (eff_buf.token_len > 0) {
989                         eff_buf.token[eff_buf.token_len] = '\0';
990
991                         if (wsi->protocol->callback) {
992
993                                 if (callback_action == LWS_CALLBACK_RECEIVE_PONG)
994                                     lwsl_info("Doing pong callback\n");
995
996                                 ret = user_callback_handle_rxflow(
997                                                 wsi->protocol->callback,
998                                                 wsi->protocol->owning_server,
999                                                 wsi,
1000                                                 (enum libwebsocket_callback_reasons)callback_action,
1001                                                 wsi->user_space,
1002                                                 eff_buf.token,
1003                                                 eff_buf.token_len);
1004                         }
1005                         else
1006                                 lwsl_err("No callback on payload spill!\n");
1007                 }
1008
1009                 wsi->u.ws.rx_user_buffer_head = 0;
1010                 break;
1011         }
1012
1013         return ret;
1014
1015 illegal_ctl_length:
1016
1017         lwsl_warn("Control frame with xtended length is illegal\n");
1018         /* kill the connection */
1019         return -1;
1020 }
1021
1022
1023 /**
1024  * libwebsockets_remaining_packet_payload() - Bytes to come before "overall"
1025  *                                            rx packet is complete
1026  * @wsi:                Websocket instance (available from user callback)
1027  *
1028  *      This function is intended to be called from the callback if the
1029  *  user code is interested in "complete packets" from the client.
1030  *  libwebsockets just passes through payload as it comes and issues a buffer
1031  *  additionally when it hits a built-in limit.  The LWS_CALLBACK_RECEIVE
1032  *  callback handler can use this API to find out if the buffer it has just
1033  *  been given is the last piece of a "complete packet" from the client --
1034  *  when that is the case libwebsockets_remaining_packet_payload() will return
1035  *  0.
1036  *
1037  *  Many protocols won't care becuse their packets are always small.
1038  */
1039
1040 LWS_VISIBLE size_t
1041 libwebsockets_remaining_packet_payload(struct libwebsocket *wsi)
1042 {
1043         return wsi->u.ws.rx_packet_length;
1044 }