e4f17a40289506deabb4118386bd24b4dafbccfd
[profile/ivi/libwebsockets.git] / lib / parsers.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010 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 const struct lws_tokens lws_tokens[WSI_TOKEN_COUNT] = {
25
26         /* win32 can't do C99 */
27
28 /*      [WSI_TOKEN_GET_URI]     =       */{ "GET ",                      4 },
29 /*      [WSI_TOKEN_HOST]        =       */{ "Host:",                     5 },
30 /*      [WSI_TOKEN_CONNECTION]  =       */{ "Connection:",              11 },
31 /*      [WSI_TOKEN_KEY1]        =       */{ "Sec-WebSocket-Key1:",      19 },
32 /*      [WSI_TOKEN_KEY2]        =       */{ "Sec-WebSocket-Key2:",      19 },
33 /*      [WSI_TOKEN_PROTOCOL]    =       */{ "Sec-WebSocket-Protocol:",  23 },
34 /*      [WSI_TOKEN_UPGRADE]     =       */{ "Upgrade:",                  8 },
35 /*      [WSI_TOKEN_ORIGIN]      =       */{ "Origin:",                   7 },
36 /*      [WSI_TOKEN_DRAFT]       =       */{ "Sec-WebSocket-Draft:",     20 },
37 /*      [WSI_TOKEN_CHALLENGE]   =       */{ "\x0d\x0a",                  2 },
38
39 /*      [WSI_TOKEN_KEY]         =       */{ "Sec-WebSocket-Key:",       18 },
40 /*      [WSI_TOKEN_VERSION]     =       */{ "Sec-WebSocket-Version:",   22 },
41 /*      [WSI_TOKEN_SWORIGIN]=           */{ "Sec-WebSocket-Origin:",    21 },
42
43 /*      [WSI_TOKEN_EXTENSIONS]  =       */{ "Sec-WebSocket-Extensions:", 25 },
44
45 /*      [WSI_TOKEN_ACCEPT]      =       */{ "Sec-WebSocket-Accept:",    21 },
46 /*      [WSI_TOKEN_NONCE]       =       */{ "Sec-WebSocket-Nonce:",     20 },
47 /*      [WSI_TOKEN_HTTP]        =       */{ "HTTP/1.1 ",                 9 },
48
49 };
50
51 int libwebsocket_parse(struct libwebsocket *wsi, unsigned char c)
52 {
53         int n;
54
55         switch (wsi->parser_state) {
56         case WSI_TOKEN_GET_URI:
57         case WSI_TOKEN_HOST:
58         case WSI_TOKEN_CONNECTION:
59         case WSI_TOKEN_KEY1:
60         case WSI_TOKEN_KEY2:
61         case WSI_TOKEN_PROTOCOL:
62         case WSI_TOKEN_UPGRADE:
63         case WSI_TOKEN_ORIGIN:
64         case WSI_TOKEN_SWORIGIN:
65         case WSI_TOKEN_DRAFT:
66         case WSI_TOKEN_CHALLENGE:
67         case WSI_TOKEN_KEY:
68         case WSI_TOKEN_VERSION:
69         case WSI_TOKEN_ACCEPT:
70         case WSI_TOKEN_NONCE:
71         case WSI_TOKEN_EXTENSIONS:
72         case WSI_TOKEN_HTTP:
73                 debug("WSI_TOKEN_(%d) '%c'\n", wsi->parser_state, c);
74
75                 /* collect into malloc'd buffers */
76                 /* optional space swallow */
77                 if (!wsi->utf8_token[wsi->parser_state].token_len && c == ' ')
78                         break;
79
80                 /* special case space terminator for get-uri */
81                 if (wsi->parser_state == WSI_TOKEN_GET_URI && c == ' ') {
82                         wsi->utf8_token[wsi->parser_state].token[
83                            wsi->utf8_token[wsi->parser_state].token_len] = '\0';
84                         wsi->parser_state = WSI_TOKEN_SKIPPING;
85                         break;
86                 }
87
88                 /* allocate appropriate memory */
89                 if (wsi->utf8_token[wsi->parser_state].token_len ==
90                                                    wsi->current_alloc_len - 1) {
91                         /* need to extend */
92                         wsi->current_alloc_len += LWS_ADDITIONAL_HDR_ALLOC;
93                         if (wsi->current_alloc_len >= LWS_MAX_HEADER_LEN) {
94                                 /* it's waaay to much payload, fail it */
95                                 strcpy(wsi->utf8_token[wsi->parser_state].token,
96                                    "!!! Length exceeded maximum supported !!!");
97                                 wsi->parser_state = WSI_TOKEN_SKIPPING;
98                                 break;
99                         }
100                         wsi->utf8_token[wsi->parser_state].token =
101                                realloc(wsi->utf8_token[wsi->parser_state].token,
102                                                         wsi->current_alloc_len);
103                 }
104
105                 /* bail at EOL */
106                 if (wsi->parser_state != WSI_TOKEN_CHALLENGE && c == '\x0d') {
107                         wsi->utf8_token[wsi->parser_state].token[
108                            wsi->utf8_token[wsi->parser_state].token_len] = '\0';
109                         wsi->parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
110                         break;
111                 }
112
113                 wsi->utf8_token[wsi->parser_state].token[
114                             wsi->utf8_token[wsi->parser_state].token_len++] = c;
115
116                 /* per-protocol end of headers management */
117
118                 if (wsi->parser_state != WSI_TOKEN_CHALLENGE)
119                         break;
120
121                 /* -76 has no version header ... server */
122                 if (!wsi->utf8_token[WSI_TOKEN_VERSION].token_len &&
123                    wsi->mode != LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY &&
124                               wsi->utf8_token[wsi->parser_state].token_len != 8)
125                         break;
126
127                 /* -76 has no version header ... client */
128                 if (!wsi->utf8_token[WSI_TOKEN_VERSION].token_len &&
129                    wsi->mode == LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY &&
130                         wsi->utf8_token[wsi->parser_state].token_len != 16)
131                         break;
132
133                 /* <= 03 has old handshake with version header needs 8 bytes */
134                 if (wsi->utf8_token[WSI_TOKEN_VERSION].token_len &&
135                          atoi(wsi->utf8_token[WSI_TOKEN_VERSION].token) < 4 &&
136                               wsi->utf8_token[wsi->parser_state].token_len != 8)
137                         break;
138
139                 /* no payload challenge in 01 + */
140
141                 if (wsi->utf8_token[WSI_TOKEN_VERSION].token_len &&
142                            atoi(wsi->utf8_token[WSI_TOKEN_VERSION].token) > 0) {
143                         wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len = 0;
144                         free(wsi->utf8_token[WSI_TOKEN_CHALLENGE].token);
145                         wsi->utf8_token[WSI_TOKEN_CHALLENGE].token = NULL;
146                 }
147
148                 /* For any supported protocol we have enough payload */
149
150                 debug("Setting WSI_PARSING_COMPLETE\n");
151                 wsi->parser_state = WSI_PARSING_COMPLETE;
152                 break;
153
154                 /* collecting and checking a name part */
155         case WSI_TOKEN_NAME_PART:
156                 debug("WSI_TOKEN_NAME_PART '%c'\n", c);
157
158                 if (wsi->name_buffer_pos == sizeof(wsi->name_buffer) - 1) {
159                         /* name bigger than we can handle, skip until next */
160                         wsi->parser_state = WSI_TOKEN_SKIPPING;
161                         break;
162                 }
163                 wsi->name_buffer[wsi->name_buffer_pos++] = c;
164                 wsi->name_buffer[wsi->name_buffer_pos] = '\0';
165
166                 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
167                         if (wsi->name_buffer_pos != lws_tokens[n].token_len)
168                                 continue;
169                         if (strcmp(lws_tokens[n].token, wsi->name_buffer))
170                                 continue;
171                         debug("known hdr '%s'\n", wsi->name_buffer);
172                         wsi->parser_state = WSI_TOKEN_GET_URI + n;
173                         wsi->current_alloc_len = LWS_INITIAL_HDR_ALLOC;
174
175                         wsi->utf8_token[wsi->parser_state].token =
176                                                  malloc(wsi->current_alloc_len);
177                         wsi->utf8_token[wsi->parser_state].token_len = 0;
178                         n = WSI_TOKEN_COUNT;
179                 }
180
181                 /* colon delimiter means we just don't know this name */
182
183                 if (wsi->parser_state == WSI_TOKEN_NAME_PART && c == ':') {
184                         debug("skipping unknown header '%s'\n",
185                                                               wsi->name_buffer);
186                         wsi->parser_state = WSI_TOKEN_SKIPPING;
187                         break;
188                 }
189
190                 if (wsi->parser_state != WSI_TOKEN_CHALLENGE)
191                         break;
192
193                 /* don't look for payload when it can just be http headers */
194
195                 if (!wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len) {
196                         /* they're HTTP headers, not websocket upgrade! */
197                         debug("Setting WSI_PARSING_COMPLETE "
198                                                          "from http headers\n");
199                         wsi->parser_state = WSI_PARSING_COMPLETE;
200                 }
201
202                 /* 04 version has no packet content after end of hdrs */
203
204                 if (wsi->utf8_token[WSI_TOKEN_VERSION].token_len &&
205                          atoi(wsi->utf8_token[WSI_TOKEN_VERSION].token) >= 4) {
206                         debug("04 header completed\n");
207                         wsi->parser_state = WSI_PARSING_COMPLETE;
208                         wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len = 0;
209                         free(wsi->utf8_token[WSI_TOKEN_CHALLENGE].token);
210                         wsi->utf8_token[WSI_TOKEN_CHALLENGE].token = NULL;
211                 }
212
213                 /* client parser? */
214
215                 if (wsi->ietf_spec_revision >= 4) {
216                         debug("04 header completed\n");
217                         wsi->parser_state = WSI_PARSING_COMPLETE;
218                 }
219
220                 break;
221
222                 /* skipping arg part of a name we didn't recognize */
223         case WSI_TOKEN_SKIPPING:
224                 debug("WSI_TOKEN_SKIPPING '%c'\n", c);
225                 if (c == '\x0d')
226                         wsi->parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
227                 break;
228         case WSI_TOKEN_SKIPPING_SAW_CR:
229                 debug("WSI_TOKEN_SKIPPING_SAW_CR '%c'\n", c);
230                 if (c == '\x0a')
231                         wsi->parser_state = WSI_TOKEN_NAME_PART;
232                 else
233                         wsi->parser_state = WSI_TOKEN_SKIPPING;
234                 wsi->name_buffer_pos = 0;
235                 break;
236                 /* we're done, ignore anything else */
237         case WSI_PARSING_COMPLETE:
238                 debug("WSI_PARSING_COMPLETE '%c'\n", c);
239                 break;
240
241         default:        /* keep gcc happy */
242                 break;
243         }
244
245         return 0;
246 }
247
248 unsigned char
249 xor_no_mask(struct libwebsocket *wsi, unsigned char c)
250 {
251         return c;
252 }
253
254 unsigned char
255 xor_mask_04(struct libwebsocket *wsi, unsigned char c)
256 {
257         c ^= wsi->masking_key_04[wsi->frame_mask_index++];
258         if (wsi->frame_mask_index == 20)
259                 wsi->frame_mask_index = 0;
260
261         return c;
262 }
263
264 unsigned char
265 xor_mask_05(struct libwebsocket *wsi, unsigned char c)
266 {
267         return c ^ wsi->frame_masking_nonce_04[(wsi->frame_mask_index++) & 3];
268 }
269
270
271
272 static int libwebsocket_rx_sm(struct libwebsocket *wsi, unsigned char c)
273 {
274         int n;
275         unsigned char buf[20 + 4];
276
277         switch (wsi->lws_rx_parse_state) {
278         case LWS_RXPS_NEW:
279
280                 switch (wsi->ietf_spec_revision) {
281                 /* Firefox 4.0b6 likes this as of 30 Oct */
282                 case 0:
283                         if (c == 0xff)
284                                 wsi->lws_rx_parse_state = LWS_RXPS_SEEN_76_FF;
285                         if (c == 0) {
286                                 wsi->lws_rx_parse_state =
287                                                        LWS_RXPS_EAT_UNTIL_76_FF;
288                                 wsi->rx_user_buffer_head = 0;
289                         }
290                         break;
291                 case 4:
292                 case 5:
293                 case 6:
294                         wsi->all_zero_nonce = 1;
295                         wsi->frame_masking_nonce_04[0] = c;
296                         if (c)
297                                 wsi->all_zero_nonce = 0;
298                         wsi->lws_rx_parse_state = LWS_RXPS_04_MASK_NONCE_1;
299                         break;
300                 default:
301                         fprintf(stderr, "libwebsocket_rx_sm doesn't know "
302                             "about spec version %d\n", wsi->ietf_spec_revision);
303                         break;
304                 }
305                 break;
306         case LWS_RXPS_04_MASK_NONCE_1:
307                 wsi->frame_masking_nonce_04[1] = c;
308                 if (c)
309                         wsi->all_zero_nonce = 0;
310                 wsi->lws_rx_parse_state = LWS_RXPS_04_MASK_NONCE_2;
311                 break;
312         case LWS_RXPS_04_MASK_NONCE_2:
313                 wsi->frame_masking_nonce_04[2] = c;
314                 if (c)
315                         wsi->all_zero_nonce = 0;
316                 wsi->lws_rx_parse_state = LWS_RXPS_04_MASK_NONCE_3;
317                 break;
318         case LWS_RXPS_04_MASK_NONCE_3:
319                 wsi->frame_masking_nonce_04[3] = c;
320                 if (c)
321                         wsi->all_zero_nonce = 0;
322
323                 if (wsi->protocol->owning_server->options &
324                                            LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK)
325                         goto post_mask;
326
327                 if (wsi->ietf_spec_revision > 4)
328                         goto post_sha1;
329
330                 /*
331                  * we are able to compute the frame key now
332                  * it's a SHA1 of ( frame nonce we were just sent, concatenated
333                  * with the connection masking key we computed at handshake
334                  * time ) -- yeah every frame from the client invokes a SHA1
335                  * for no real reason so much for lightweight.
336                  */
337
338                 buf[0] = wsi->frame_masking_nonce_04[0];
339                 buf[1] = wsi->frame_masking_nonce_04[1];
340                 buf[2] = wsi->frame_masking_nonce_04[2];
341                 buf[3] = wsi->frame_masking_nonce_04[3];
342
343                 memcpy(buf + 4, wsi->masking_key_04, 20);
344
345                 /*
346                  * wsi->frame_mask_04 will be our recirculating 20-byte XOR key
347                  * for this frame
348                  */
349
350                 SHA1((unsigned char *)buf, 4 + 20, wsi->frame_mask_04);
351
352 post_sha1:
353
354                 /*
355                  * start from the zero'th byte in the XOR key buffer since
356                  * this is the start of a frame with a new key
357                  */
358
359                 wsi->frame_mask_index = 0;
360
361 post_mask:
362                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_1;
363                 break;
364
365         /*
366          *  04 logical framing from the spec (all this is masked when incoming
367          *  and has to be unmasked)
368          *
369          * We ignore the possibility of extension data because we don't
370          * negotiate any extensions at the moment.
371          *
372          *    0                   1                   2                   3
373          *    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
374          *   +-+-+-+-+-------+-+-------------+-------------------------------+
375          *   |F|R|R|R| opcode|R| Payload len |    Extended payload length    |
376          *   |I|S|S|S|  (4)  |S|     (7)     |             (16/63)           |
377          *   |N|V|V|V|       |V|             |   (if payload len==126/127)   |
378          *   | |1|2|3|       |4|             |                               |
379          *   +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
380          *   |     Extended payload length continued, if payload len == 127  |
381          *   + - - - - - - - - - - - - - - - +-------------------------------+
382          *   |                               |         Extension data        |
383          *   +-------------------------------+ - - - - - - - - - - - - - - - +
384          *   :                                                               :
385          *   +---------------------------------------------------------------+
386          *   :                       Application data                        :
387          *   +---------------------------------------------------------------+
388          *
389          *  We pass payload through to userland as soon as we get it, ignoring
390          *  FIN.  It's up to userland to buffer it up if it wants to see a
391          *  whole unfragmented block of the original size (which may be up to
392          *  2^63 long!)
393          */
394
395         case LWS_RXPS_04_FRAME_HDR_1:
396                 /*
397                  * 04 spec defines the opcode like this: (1, 2, and 3 are
398                  * "control frame" opcodes which may not be fragmented or
399                  * have size larger than 126)
400                  *
401                  *       frame-opcode           =
402                  *             %x0 ; continuation frame
403                  *              / %x1 ; connection close
404                  *              / %x2 ; ping
405                  *              / %x3 ; pong
406                  *              / %x4 ; text frame
407                  *              / %x5 ; binary frame
408                  *              / %x6-F ; reserved
409                  *
410                  *              FIN (b7)
411                  */
412
413                 c = wsi->xor_mask(wsi, c);
414
415                 if (c & 0x70) {
416                         fprintf(stderr,
417                                       "Frame has extensions set illegally 1\n");
418                         /* kill the connection */
419                         return -1;
420                 }
421
422                 wsi->opcode = c & 0xf;
423                 wsi->final = !!((c >> 7) & 1);
424
425                 if (wsi->final &&
426                         wsi->opcode == LWS_WS_OPCODE_04__CONTINUATION &&
427                                                    wsi->rx_packet_length == 0) {
428                         fprintf(stderr,
429                                       "Frame starts with final continuation\n");
430                         /* kill the connection */
431                         return -1;
432                 }
433
434                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;
435                 break;
436
437         case LWS_RXPS_04_FRAME_HDR_LEN:
438                 c = wsi->xor_mask(wsi, c);
439
440                 if (c & 0x80) {
441                         fprintf(stderr, "Frame has extensions "
442                                                            "set illegally 2\n");
443                         /* kill the connection */
444                         return -1;
445                 }
446
447                 switch (c) {
448                 case 126:
449                         /* control frames are not allowed to have big lengths */
450                         switch (wsi->opcode) {
451                         case LWS_WS_OPCODE_04__CLOSE:
452                         case LWS_WS_OPCODE_04__PING:
453                         case LWS_WS_OPCODE_04__PONG:
454                                 fprintf(stderr, "Control frame asking for "
455                                                 "extended length is illegal\n");
456                                 /* kill the connection */
457                                 return -1;
458                         default:
459                                 break;
460                         }
461                         wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;
462                         break;
463                 case 127:
464                         /* control frames are not allowed to have big lengths */
465                         switch (wsi->opcode) {
466                         case LWS_WS_OPCODE_04__CLOSE:
467                         case LWS_WS_OPCODE_04__PING:
468                         case LWS_WS_OPCODE_04__PONG:
469                                 fprintf(stderr, "Control frame asking for "
470                                                 "extended length is illegal\n");
471                                 /* kill the connection */
472                                 return -1;
473                         default:
474                                 break;
475                         }
476                         wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;
477                         break;
478                 default:
479                         wsi->rx_packet_length = c;
480                         wsi->lws_rx_parse_state =
481                                         LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
482                         break;
483                 }
484                 break;
485
486         case LWS_RXPS_04_FRAME_HDR_LEN16_2:
487                 c = wsi->xor_mask(wsi, c);
488
489                 wsi->rx_packet_length = c << 8;
490                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1;
491                 break;
492
493         case LWS_RXPS_04_FRAME_HDR_LEN16_1:
494                 c = wsi->xor_mask(wsi, c);
495
496                 wsi->rx_packet_length |= c;
497                 wsi->lws_rx_parse_state =
498                                         LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
499                 break;
500
501         case LWS_RXPS_04_FRAME_HDR_LEN64_8:
502                 c = wsi->xor_mask(wsi, c);
503                 if (c & 0x80) {
504                         fprintf(stderr, "b63 of length must be zero\n");
505                         /* kill the connection */
506                         return -1;
507                 }
508 #if defined __LP64__
509                 wsi->rx_packet_length = ((size_t)c) << 56;
510 #else
511                 wsi->rx_packet_length = 0;
512 #endif
513                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;
514                 break;
515
516         case LWS_RXPS_04_FRAME_HDR_LEN64_7:
517 #if defined __LP64__
518                 wsi->rx_packet_length |= ((size_t)wsi->xor_mask(wsi, c)) << 48;
519 #endif
520                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;
521                 break;
522
523         case LWS_RXPS_04_FRAME_HDR_LEN64_6:
524 #if defined __LP64__
525                 wsi->rx_packet_length |= ((size_t)wsi->xor_mask(wsi, c)) << 40;
526 #endif
527                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;
528                 break;
529
530         case LWS_RXPS_04_FRAME_HDR_LEN64_5:
531 #if defined __LP64__
532                 wsi->rx_packet_length |= ((size_t)wsi->xor_mask(wsi, c)) << 32;
533 #endif
534                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;
535                 break;
536
537         case LWS_RXPS_04_FRAME_HDR_LEN64_4:
538                 wsi->rx_packet_length |= ((size_t)wsi->xor_mask(wsi, c)) << 24;
539                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3;
540                 break;
541
542         case LWS_RXPS_04_FRAME_HDR_LEN64_3:
543                 wsi->rx_packet_length |= ((size_t)wsi->xor_mask(wsi, c)) << 16;
544                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2;
545                 break;
546
547         case LWS_RXPS_04_FRAME_HDR_LEN64_2:
548                 wsi->rx_packet_length |= ((size_t)wsi->xor_mask(wsi, c)) << 8;
549                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1;
550                 break;
551
552         case LWS_RXPS_04_FRAME_HDR_LEN64_1:
553                 wsi->rx_packet_length |= ((size_t)wsi->xor_mask(wsi, c));
554                 wsi->lws_rx_parse_state =
555                                         LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
556                 break;
557
558         case LWS_RXPS_EAT_UNTIL_76_FF:
559                 if (c == 0xff) {
560                         wsi->lws_rx_parse_state = LWS_RXPS_NEW;
561                         goto issue;
562                 }
563                 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
564                                               (wsi->rx_user_buffer_head++)] = c;
565
566                 if (wsi->rx_user_buffer_head != MAX_USER_RX_BUFFER)
567                         break;
568 issue:
569                 if (wsi->protocol->callback)
570                         wsi->protocol->callback(wsi->protocol->owning_server,
571                           wsi, LWS_CALLBACK_RECEIVE,
572                           wsi->user_space,
573                           &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
574                           wsi->rx_user_buffer_head);
575                 wsi->rx_user_buffer_head = 0;
576                 break;
577         case LWS_RXPS_SEEN_76_FF:
578                 if (c)
579                         break;
580
581                 debug("Seen that client is requesting "
582                                 "a v76 close, sending ack\n");
583                 buf[0] = 0xff;
584                 buf[1] = 0;
585                 n = libwebsocket_write(wsi, buf, 2, LWS_WRITE_HTTP);
586                 if (n < 0) {
587                         fprintf(stderr, "ERROR writing to socket");
588                         return -1;
589                 }
590                 debug("  v76 close ack sent, server closing skt\n");
591                 /* returning < 0 will get it closed in parent */
592                 return -1;
593
594         case LWS_RXPS_PULLING_76_LENGTH:
595                 break;
596
597         case LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED:
598                 if (wsi->all_zero_nonce && wsi->ietf_spec_revision >= 5)
599                         wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
600                                (wsi->rx_user_buffer_head++)] = c;
601                 else
602                         wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
603                                (wsi->rx_user_buffer_head++)] =
604                                                           wsi->xor_mask(wsi, c);
605
606                 if (--wsi->rx_packet_length == 0) {
607                         wsi->lws_rx_parse_state = LWS_RXPS_NEW;
608                         goto spill;
609                 }
610                 if (wsi->rx_user_buffer_head != MAX_USER_RX_BUFFER)
611                         break;
612 spill:
613                 /*
614                  * is this frame a control packet we should take care of at this
615                  * layer?  If so service it and hide it from the user callback
616                  */
617
618                 switch (wsi->opcode) {
619                 case LWS_WS_OPCODE_04__CLOSE:
620                         /* parrot the close packet payload back */
621                         n = libwebsocket_write(wsi, (unsigned char *)
622                            &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
623                                      wsi->rx_user_buffer_head, LWS_WRITE_CLOSE);
624                         wsi->state = WSI_STATE_RETURNED_CLOSE_ALREADY;
625                         /* close the connection */
626                         return -1;
627
628                 case LWS_WS_OPCODE_04__PING:
629                         /* parrot the ping packet payload back as a pong */
630                         n = libwebsocket_write(wsi, (unsigned char *)
631                             &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
632                                     wsi->rx_user_buffer_head, LWS_WRITE_PONG);
633                         /* ... then just drop it */
634                         wsi->rx_user_buffer_head = 0;
635                         return 0;
636
637                 case LWS_WS_OPCODE_04__PONG:
638                         /* keep the statistics... */
639                         wsi->pings_vs_pongs--;
640                         /* ... then just drop it */
641                         wsi->rx_user_buffer_head = 0;
642                         return 0;
643
644                 default:
645                         break;
646                 }
647
648                 /*
649                  * No it's real payload, pass it up to the user callback.
650                  * It's nicely buffered with the pre-padding taken care of
651                  * so it can be sent straight out again using libwebsocket_write
652                  */
653
654                 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
655                                                wsi->rx_user_buffer_head] = '\0';
656
657                 if (wsi->protocol->callback)
658                         wsi->protocol->callback(wsi->protocol->owning_server,
659                                                 wsi, LWS_CALLBACK_RECEIVE,
660                                                 wsi->user_space,
661                           &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
662                                                       wsi->rx_user_buffer_head);
663                 wsi->rx_user_buffer_head = 0;
664                 break;
665         }
666
667         return 0;
668 }
669
670
671 int libwebsocket_client_rx_sm(struct libwebsocket *wsi, unsigned char c)
672 {
673         int n;
674         unsigned char buf[20 + 4];
675         int callback_action = LWS_CALLBACK_CLIENT_RECEIVE;
676
677         switch (wsi->lws_rx_parse_state) {
678         case LWS_RXPS_NEW:
679
680                 switch (wsi->ietf_spec_revision) {
681                 /* Firefox 4.0b6 likes this as of 30 Oct */
682                 case 0:
683                         if (c == 0xff)
684                                 wsi->lws_rx_parse_state = LWS_RXPS_SEEN_76_FF;
685                         if (c == 0) {
686                                 wsi->lws_rx_parse_state =
687                                                        LWS_RXPS_EAT_UNTIL_76_FF;
688                                 wsi->rx_user_buffer_head = 0;
689                         }
690                         break;
691                 case 4:
692                 case 5:
693                 case 6:
694         /*
695          *  04 logical framing from the spec (all this is masked when
696          *  incoming and has to be unmasked)
697          *
698          * We ignore the possibility of extension data because we don't
699          * negotiate any extensions at the moment.
700          *
701          *    0                   1                   2                   3
702          *    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
703          *   +-+-+-+-+-------+-+-------------+-------------------------------+
704          *   |F|R|R|R| opcode|R| Payload len |    Extended payload length    |
705          *   |I|S|S|S|  (4)  |S|     (7)     |             (16/63)           |
706          *   |N|V|V|V|       |V|             |   (if payload len==126/127)   |
707          *   | |1|2|3|       |4|             |                               |
708          *   +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
709          *   |     Extended payload length continued, if payload len == 127  |
710          *   + - - - - - - - - - - - - - - - +-------------------------------+
711          *   |                               |         Extension data        |
712          *   +-------------------------------+ - - - - - - - - - - - - - - - +
713          *   :                                                               :
714          *   +---------------------------------------------------------------+
715          *   :                       Application data                        :
716          *   +---------------------------------------------------------------+
717          *
718          *  We pass payload through to userland as soon as we get it, ignoring
719          *  FIN.  It's up to userland to buffer it up if it wants to see a
720          *  whole unfragmented block of the original size (which may be up to
721          *  2^63 long!)
722          */
723
724                 /*
725                  * 04 spec defines the opcode like this: (1, 2, and 3 are
726                  * "control frame" opcodes which may not be fragmented or
727                  * have size larger than 126)
728                  *
729                  *       frame-opcode           =
730                  *                %x0 ; continuation frame
731                  *              / %x1 ; connection close
732                  *              / %x2 ; ping
733                  *              / %x3 ; pong
734                  *              / %x4 ; text frame
735                  *              / %x5 ; binary frame
736                  *              / %x6-F ; reserved
737                  *
738                  *              FIN (b7)
739                  */
740
741                         if (c & 0x70) {
742                                 fprintf(stderr, "Frame has extensions set "
743                                    "illegally on first framing byte %02X\n", c);
744                                 /* kill the connection */
745                                 return -1;
746                         }
747
748                         wsi->opcode = c & 0xf;
749                         wsi->final = !!((c >> 7) & 1);
750
751                         if (wsi->final &&
752                             wsi->opcode == LWS_WS_OPCODE_04__CONTINUATION &&
753                                                    wsi->rx_packet_length == 0) {
754                                 fprintf(stderr,
755                                       "Frame starts with final continuation\n");
756                                 /* kill the connection */
757                                 return -1;
758                         }
759
760                         wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;
761                         break;
762                 default:
763                         fprintf(stderr, "client_rx_sm doesn't know how "
764                                 "to handle spec version %02d\n",
765                                                        wsi->ietf_spec_revision);
766                         break;
767                 }
768                 break;
769
770
771         case LWS_RXPS_04_FRAME_HDR_LEN:
772
773                 if (c & 0x80) {
774                         fprintf(stderr,
775                                       "Frame has extensions set illegally 4\n");
776                         /* kill the connection */
777                         return -1;
778                 }
779
780                 switch (c) {
781                 case 126:
782                         /* control frames are not allowed to have big lengths */
783                         switch (wsi->opcode) {
784                         case LWS_WS_OPCODE_04__CLOSE:
785                         case LWS_WS_OPCODE_04__PING:
786                         case LWS_WS_OPCODE_04__PONG:
787                                 fprintf(stderr, "Control frame asking for "
788                                                 "extended length is illegal\n");
789                                 /* kill the connection */
790                                 return -1;
791                         default:
792                                 break;
793                         }
794                         wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;
795                         break;
796                 case 127:
797                         /* control frames are not allowed to have big lengths */
798                         switch (wsi->opcode) {
799                         case LWS_WS_OPCODE_04__CLOSE:
800                         case LWS_WS_OPCODE_04__PING:
801                         case LWS_WS_OPCODE_04__PONG:
802                                 fprintf(stderr, "Control frame asking for "
803                                                 "extended length is illegal\n");
804                                 /* kill the connection */
805                                 return -1;
806                         default:
807                                 break;
808                         }
809                         wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;
810                         break;
811                 default:
812                         wsi->rx_packet_length = c;
813                         wsi->lws_rx_parse_state =
814                                         LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
815                         break;
816                 }
817                 break;
818
819         case LWS_RXPS_04_FRAME_HDR_LEN16_2:
820                 wsi->rx_packet_length = c << 8;
821                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1;
822                 break;
823
824         case LWS_RXPS_04_FRAME_HDR_LEN16_1:
825                 wsi->rx_packet_length |= c;
826                 wsi->lws_rx_parse_state =
827                                         LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
828                 break;
829
830         case LWS_RXPS_04_FRAME_HDR_LEN64_8:
831                 if (c & 0x80) {
832                         fprintf(stderr, "b63 of length must be zero\n");
833                         /* kill the connection */
834                         return -1;
835                 }
836 #if defined __LP64__
837                 wsi->rx_packet_length = ((size_t)c) << 56;
838 #else
839                 wsi->rx_packet_length = 0;
840 #endif
841                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;
842                 break;
843
844         case LWS_RXPS_04_FRAME_HDR_LEN64_7:
845 #if defined __LP64__
846                 wsi->rx_packet_length |= ((size_t)c) << 48;
847 #endif
848                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;
849                 break;
850
851         case LWS_RXPS_04_FRAME_HDR_LEN64_6:
852 #if defined __LP64__
853                 wsi->rx_packet_length |= ((size_t)c) << 40;
854 #endif
855                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;
856                 break;
857
858         case LWS_RXPS_04_FRAME_HDR_LEN64_5:
859 #if defined __LP64__
860                 wsi->rx_packet_length |= ((size_t)c) << 32;
861 #endif
862                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;
863                 break;
864
865         case LWS_RXPS_04_FRAME_HDR_LEN64_4:
866                 wsi->rx_packet_length |= ((size_t)c) << 24;
867                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3;
868                 break;
869
870         case LWS_RXPS_04_FRAME_HDR_LEN64_3:
871                 wsi->rx_packet_length |= ((size_t)c) << 16;
872                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2;
873                 break;
874
875         case LWS_RXPS_04_FRAME_HDR_LEN64_2:
876                 wsi->rx_packet_length |= ((size_t)c) << 8;
877                 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1;
878                 break;
879
880         case LWS_RXPS_04_FRAME_HDR_LEN64_1:
881                 wsi->rx_packet_length |= (size_t)c;
882                 wsi->lws_rx_parse_state =
883                                         LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
884                 break;
885
886         case LWS_RXPS_EAT_UNTIL_76_FF:
887                 if (c == 0xff) {
888                         wsi->lws_rx_parse_state = LWS_RXPS_NEW;
889                         goto issue;
890                 }
891                 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
892                                               (wsi->rx_user_buffer_head++)] = c;
893
894                 if (wsi->rx_user_buffer_head != MAX_USER_RX_BUFFER)
895                         break;
896 issue:
897                 if (wsi->protocol->callback)
898                         wsi->protocol->callback(wsi->protocol->owning_server,
899                                                 wsi,
900                                                 LWS_CALLBACK_CLIENT_RECEIVE,
901                                                 wsi->user_space,
902                           &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
903                                                       wsi->rx_user_buffer_head);
904                 wsi->rx_user_buffer_head = 0;
905                 break;
906         case LWS_RXPS_SEEN_76_FF:
907                 if (c)
908                         break;
909
910                 debug("Seen that client is requesting "
911                                 "a v76 close, sending ack\n");
912                 buf[0] = 0xff;
913                 buf[1] = 0;
914                 n = libwebsocket_write(wsi, buf, 2, LWS_WRITE_HTTP);
915                 if (n < 0) {
916                         fprintf(stderr, "ERROR writing to socket");
917                         return -1;
918                 }
919                 debug("  v76 close ack sent, server closing skt\n");
920                 /* returning < 0 will get it closed in parent */
921                 return -1;
922
923         case LWS_RXPS_PULLING_76_LENGTH:
924                 break;
925
926         case LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED:
927                 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
928                                  (wsi->rx_user_buffer_head++)] = c;
929                 if (--wsi->rx_packet_length == 0) {
930                         wsi->lws_rx_parse_state = LWS_RXPS_NEW;
931                         goto spill;
932                 }
933                 if (wsi->rx_user_buffer_head != MAX_USER_RX_BUFFER)
934                         break;
935 spill:
936                 /*
937                  * is this frame a control packet we should take care of at this
938                  * layer?  If so service it and hide it from the user callback
939                  */
940
941                 switch (wsi->opcode) {
942                 case LWS_WS_OPCODE_04__CLOSE:
943                         /* parrot the close packet payload back */
944                         n = libwebsocket_write(wsi, (unsigned char *)
945                            &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
946                                      wsi->rx_user_buffer_head, LWS_WRITE_CLOSE);
947                         wsi->state = WSI_STATE_RETURNED_CLOSE_ALREADY;
948                         /* close the connection */
949                         return -1;
950
951                 case LWS_WS_OPCODE_04__PING:
952                         /* parrot the ping packet payload back as a pong*/
953                         n = libwebsocket_write(wsi, (unsigned char *)
954                             &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
955                                     wsi->rx_user_buffer_head, LWS_WRITE_PONG);
956                         break;
957
958                 case LWS_WS_OPCODE_04__PONG:
959                         /* keep the statistics... */
960                         wsi->pings_vs_pongs--;
961
962                         /* issue it */
963                         callback_action = LWS_CALLBACK_CLIENT_RECEIVE_PONG;
964                         break;
965
966                 default:
967                         break;
968                 }
969
970                 /*
971                  * No it's real payload, pass it up to the user callback.
972                  * It's nicely buffered with the pre-padding taken care of
973                  * so it can be sent straight out again using libwebsocket_write
974                  */
975
976                 if (wsi->protocol->callback)
977                         wsi->protocol->callback(wsi->protocol->owning_server,
978                                                 wsi, callback_action,
979                                                 wsi->user_space,
980                           &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
981                                                       wsi->rx_user_buffer_head);
982                 wsi->rx_user_buffer_head = 0;
983                 break;
984         default:
985                 fprintf(stderr, "client rx illegal state\n");
986                 return 1;
987         }
988
989         return 0;
990 }
991
992
993
994 int libwebsocket_interpret_incoming_packet(struct libwebsocket *wsi,
995                                                  unsigned char *buf, size_t len)
996 {
997         int n;
998
999 #ifdef DEBUG
1000         fprintf(stderr, "received %d byte packet\n", (int)len);
1001         for (n = 0; n < len; n++)
1002                 fprintf(stderr, "%02X ", buf[n]);
1003         fprintf(stderr, "\n");
1004 #endif
1005
1006         /* let the rx protocol state machine have as much as it needs */
1007
1008         n = 0;
1009         while (n < len)
1010                 if (libwebsocket_rx_sm(wsi, buf[n++]) < 0)
1011                         return -1;
1012
1013         return 0;
1014 }
1015
1016
1017 static int
1018 libwebsocket_0405_frame_mask_generate(struct libwebsocket *wsi)
1019 {
1020         char buf[4 + 20];
1021         int n;
1022
1023         /* fetch the per-frame nonce */
1024
1025         n = libwebsockets_get_random(wsi->protocol->owning_server,
1026                                                 wsi->frame_masking_nonce_04, 4);
1027         if (n != 4) {
1028                 fprintf(stderr, "Unable to read from random device %s %d\n",
1029                                                      SYSTEM_RANDOM_FILEPATH, n);
1030                 return 1;
1031         }
1032
1033         /* start masking from first byte of masking key buffer */
1034         wsi->frame_mask_index = 0;
1035
1036         if (wsi->ietf_spec_revision != 4)
1037                 return 0;
1038
1039         /* 04 only does SHA-1 more complex key */
1040
1041         /*
1042          * the frame key is the frame nonce (4 bytes) followed by the
1043          * connection masking key, hashed by SHA1
1044          */
1045
1046         memcpy(buf, wsi->frame_masking_nonce_04, 4);
1047         
1048         memcpy(buf + 4, wsi->masking_key_04, 20);
1049
1050         /* concatenate the nonce with the connection key then hash it */
1051
1052         SHA1((unsigned char *)buf, 4 + 20, wsi->frame_mask_04);
1053
1054         return 0;
1055 }
1056
1057 int lws_issue_raw(struct libwebsocket *wsi, unsigned char *buf, size_t len)
1058 {
1059         int n;
1060
1061 #ifdef LWS_OPENSSL_SUPPORT
1062         if (wsi->ssl) {
1063                 n = SSL_write(wsi->ssl, buf, len);
1064                 if (n < 0) {
1065                         fprintf(stderr,
1066                                    "ERROR writing to socket\n");
1067                         return -1;
1068                 }
1069         } else {
1070 #endif
1071                 n = send(wsi->sock, buf, len, MSG_NOSIGNAL);
1072                 if (n < 0) {
1073                         fprintf(stderr,
1074                                    "ERROR writing to socket\n");
1075                         return -1;
1076                 }
1077 #ifdef LWS_OPENSSL_SUPPORT
1078         }
1079 #endif
1080         return 0;
1081 }
1082
1083 /**
1084  * libwebsocket_write() - Apply protocol then write data to client
1085  * @wsi:        Websocket instance (available from user callback)
1086  * @buf:        The data to send.  For data being sent on a websocket
1087  *              connection (ie, not default http), this buffer MUST have
1088  *              LWS_SEND_BUFFER_PRE_PADDING bytes valid BEFORE the pointer
1089  *              and an additional LWS_SEND_BUFFER_POST_PADDING bytes valid
1090  *              in the buffer after (buf + len).  This is so the protocol
1091  *              header and trailer data can be added in-situ.
1092  * @len:        Count of the data bytes in the payload starting from buf
1093  * @protocol:   Use LWS_WRITE_HTTP to reply to an http connection, and one
1094  *              of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
1095  *              data on a websockets connection.  Remember to allow the extra
1096  *              bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
1097  *              are used.
1098  *
1099  *      This function provides the way to issue data back to the client
1100  *      for both http and websocket protocols.
1101  *
1102  *      In the case of sending using websocket protocol, be sure to allocate
1103  *      valid storage before and after buf as explained above.  This scheme
1104  *      allows maximum efficiency of sending data and protocol in a single
1105  *      packet while not burdening the user code with any protocol knowledge.
1106  */
1107
1108 int libwebsocket_write(struct libwebsocket *wsi, unsigned char *buf,
1109                           size_t len, enum libwebsocket_write_protocol protocol)
1110 {
1111         int n;
1112         int m;
1113         int pre = 0;
1114         int post = 0;
1115         unsigned int shift = 7;
1116         struct lws_tokens eff_buf;
1117         int ret;
1118
1119         if (len == 0 && protocol != LWS_WRITE_CLOSE) {
1120                 fprintf(stderr, "zero length libwebsocket_write attempt\n");
1121                 return 0;
1122         }
1123
1124         if (protocol == LWS_WRITE_HTTP)
1125                 goto send_raw;
1126
1127         /* websocket protocol, either binary or text */
1128
1129         if (wsi->state != WSI_STATE_ESTABLISHED)
1130                 return -1;
1131
1132         switch (wsi->ietf_spec_revision) {
1133         /* chrome likes this as of 30 Oct */
1134         /* Firefox 4.0b6 likes this as of 30 Oct */
1135         case 0:
1136                 if ((protocol & 0xf) == LWS_WRITE_BINARY) {
1137                         /* in binary mode we send 7-bit used length blocks */
1138                         pre = 1;
1139                         while (len & (127 << shift)) {
1140                                 pre++;
1141                                 shift += 7;
1142                         }
1143                         n = 0;
1144                         shift -= 7;
1145                         while (shift >= 0) {
1146                                 if (shift)
1147                                         buf[0 - pre + n] =
1148                                                   ((len >> shift) & 127) | 0x80;
1149                                 else
1150                                         buf[0 - pre + n] =
1151                                                   ((len >> shift) & 127);
1152                                 n++;
1153                                 shift -= 7;
1154                         }
1155                         break;
1156                 }
1157
1158                 /* frame type = text, length-free spam mode */
1159
1160                 buf[-1] = 0;
1161                 buf[len] = 0xff; /* EOT marker */
1162                 pre = 1;
1163                 post = 1;
1164                 break;
1165
1166         case 4:
1167         case 5:
1168         case 6:
1169                 switch (protocol & 0xf) {
1170                 case LWS_WRITE_TEXT:
1171                         n = LWS_WS_OPCODE_04__TEXT_FRAME;
1172                         break;
1173                 case LWS_WRITE_BINARY:
1174                         n = LWS_WS_OPCODE_04__BINARY_FRAME;
1175                         break;
1176                 case LWS_WRITE_CLOSE:
1177                         n = LWS_WS_OPCODE_04__CLOSE;
1178
1179                         /*
1180                          * v5 mandates the first byte of close packet
1181                          * in both client and server directions
1182                          */
1183                         
1184                         switch (wsi->ietf_spec_revision) {
1185                         case 0:
1186                         case 4:
1187                                 break;
1188                         case 5:
1189                                 /* we can do this because we demand post-buf */
1190
1191                                 if (len < 1)
1192                                         len = 1;
1193                                 
1194                                 switch (wsi->mode) {
1195                                 case LWS_CONNMODE_WS_SERVING:
1196                                         /*
1197                                         fprintf(stderr, "LWS_WRITE_CLOSE S\n");
1198                                         */
1199                                         buf[0] = 'S';
1200                                         break;
1201                                 case LWS_CONNMODE_WS_CLIENT:
1202                                         /*
1203                                         fprintf(stderr, "LWS_WRITE_CLOSE C\n");
1204                                         */
1205                                         buf[0] = 'C';
1206                                         break;
1207                                 default:
1208                                         break;
1209                                 }
1210                                 break;
1211                         default:
1212                                 /*
1213                                  * 06 has a 2-byte status code in network order
1214                                  * we can do this because we demand post-buf
1215                                  */
1216
1217                                 if (wsi->close_reason) {
1218                                         buf[pre - 2] = wsi->close_reason >> 8;
1219                                         buf[pre - 1] = wsi->close_reason;
1220                                         pre += 2;
1221                                 }
1222                                 break;
1223                         }
1224                         break;
1225                 case LWS_WRITE_PING:
1226                         n = LWS_WS_OPCODE_04__PING;
1227                         wsi->pings_vs_pongs++;
1228                         break;
1229                 case LWS_WRITE_PONG:
1230                         n = LWS_WS_OPCODE_04__PONG;
1231                         break;
1232                 default:
1233                         fprintf(stderr, "libwebsocket_write: unknown write "
1234                                                          "opcode / protocol\n");
1235                         return -1;
1236                 }
1237
1238                 if (!(protocol & LWS_WRITE_NO_FIN))
1239                         n |= 1 << 7;
1240
1241                 if (len < 126) {
1242                         buf[pre - 2] = n;
1243                         buf[pre - 1] = len;
1244                         pre += 2;
1245                 } else {
1246                         if (len < 65536) {
1247                                 buf[pre - 4] = n;
1248                                 buf[pre - 3] = 126;
1249                                 buf[pre - 2] = len >> 8;
1250                                 buf[pre - 1] = len;
1251                                 pre += 4;
1252                         } else {
1253                                 buf[pre - 10] = n;
1254                                 buf[pre - 9] = 127;
1255 #if defined __LP64__
1256                                         buf[pre - 8] = (len >> 56) & 0x7f;
1257                                         buf[pre - 7] = len >> 48;
1258                                         buf[pre - 6] = len >> 40;
1259                                         buf[pre - 5] = len >> 32;
1260 #else
1261                                         buf[pre - 8] = 0;
1262                                         buf[pre - 7] = 0;
1263                                         buf[pre - 6] = 0;
1264                                         buf[pre - 5] = 0;
1265 #endif
1266                                 buf[pre - 4] = len >> 24;
1267                                 buf[pre - 3] = len >> 16;
1268                                 buf[pre - 2] = len >> 8;
1269                                 buf[pre - 1] = len;
1270                                 pre += 10;
1271                         }
1272                 }
1273                 break;
1274         }
1275
1276 #if 0
1277         for (n = 0; n < (len + pre + post); n++)
1278                 fprintf(stderr, "%02X ", buf[n - pre]);
1279
1280         fprintf(stderr, "\n");
1281 #endif
1282
1283         /*
1284          * Deal with masking if we are in client -> server direction and
1285          * the protocol demands it
1286          */
1287
1288         if (wsi->mode == LWS_CONNMODE_WS_CLIENT &&
1289                                                  wsi->ietf_spec_revision >= 4) {
1290
1291                 /*
1292                  * this is only useful for security tests where it's required
1293                  * to control the raw packet payload content
1294                  */
1295
1296                 if (!(protocol & LWS_WRITE_CLIENT_IGNORE_XOR_MASK)) {
1297
1298                         if (libwebsocket_0405_frame_mask_generate(wsi)) {
1299                                 fprintf(stderr, "libwebsocket_write: "
1300                                               "frame mask generation failed\n");
1301                                 return 1;
1302                         }
1303
1304                         /*
1305                          * use the XOR masking against everything we send
1306                          * past the frame nonce
1307                          */
1308
1309                         for (n = 0; n < (len + pre + post); n++)
1310                                 buf[n - pre] = wsi->xor_mask(wsi, buf[n - pre]);
1311
1312
1313                         /* make space for the frame nonce in clear */
1314                         pre += 4;
1315
1316                         /* copy the frame nonce into place */
1317                         memcpy(&buf[0 - pre], wsi->frame_masking_nonce_04, 4);
1318                 } else {
1319                         /* make space for the frame nonce in clear */
1320                         pre += 4;
1321
1322                         buf[0 - pre] = 0;
1323                         buf[1 - pre] = 0;
1324                         buf[2 - pre] = 0;
1325                         buf[3 - pre] = 0;
1326                 }
1327
1328         }
1329
1330 send_raw:
1331
1332         if (protocol == LWS_WRITE_HTTP) {
1333                 if (lws_issue_raw(wsi, (unsigned char *)buf - pre,
1334                                                               len + pre + post))
1335                         return -1;
1336
1337                 return 0;
1338         }
1339
1340         /*
1341          * give any active extensions a chance to munge the buffer
1342          * before send.  We pass in a pointer to an lws_tokens struct
1343          * prepared with the default buffer and content length that's in
1344          * there.  Rather than rewrite the default buffer, extensions
1345          * that expect to grow the buffer can adapt .token to
1346          * point to their own per-connection buffer in the extension
1347          * user allocation.  By default with no extensions or no
1348          * extension callback handling, just the normal input buffer is
1349          * used then so it is efficient.
1350          *
1351          * callback returns 1 in case it wants to spill more buffers
1352          */
1353
1354         eff_buf.token = (char *)buf - pre;
1355         eff_buf.token_len = len + pre + post;
1356
1357         /*
1358          * while we have original buf to spill ourselves, or extensions report
1359          * more in their pipeline
1360          */
1361
1362         ret = 1;
1363         while (ret == 1) {
1364
1365                 /* default to nobody has more to spill */
1366
1367                 ret = 0;
1368
1369                 /* show every extension the new incoming data */
1370
1371                 for (n = 0; n < wsi->count_active_extensions; n++) {
1372                         m = wsi->active_extensions[n]->callback(
1373                                 wsi->protocol->owning_server, wsi,
1374                                         LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
1375                                    wsi->active_extensions_user[n], &eff_buf, 0);
1376                         if (m < 0) {
1377                                 fprintf(stderr, "Extension reports fatal error\n");
1378                                 return -1;
1379                         }
1380                         if (m)
1381                                 /*
1382                                  * at least one extension told us he has more
1383                                  * to spill, so we will go around again after
1384                                  */
1385                                 ret = 1;
1386                 }
1387
1388                 /* assuming they left us something to send, send it */
1389
1390                 if (eff_buf.token_len)
1391                         if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
1392                                                              eff_buf.token_len))
1393                                 return -1;
1394
1395                 /* we used up what we had */
1396
1397                 eff_buf.token = NULL;
1398                 eff_buf.token_len = 0;
1399
1400                 /*
1401                  * Did that leave the pipe choked?
1402                  */
1403
1404                 if (!lws_send_pipe_choked(wsi))
1405                         /* no we could add more */
1406                         continue;
1407
1408                 fprintf(stderr, "choked\n");
1409
1410                 /*
1411                  * Yes, he's choked.  Don't spill the rest now get a callback
1412                  * when he is ready to send and take care of it there
1413                  */
1414                 libwebsocket_callback_on_writable(
1415                                              wsi->protocol->owning_server, wsi);
1416                 wsi->extension_data_pending = 1;
1417                 ret = 0;
1418         }
1419
1420         debug("written %d bytes to client\n", eff_buf.token_len);
1421
1422         return 0;
1423 }
1424
1425
1426 /**
1427  * libwebsockets_serve_http_file() - Send a file back to the client using http
1428  * @wsi:                Websocket instance (available from user callback)
1429  * @file:               The file to issue over http
1430  * @content_type:       The http content type, eg, text/html
1431  *
1432  *      This function is intended to be called from the callback in response
1433  *      to http requests from the client.  It allows the callback to issue
1434  *      local files down the http link in a single step.
1435  */
1436
1437 int libwebsockets_serve_http_file(struct libwebsocket *wsi, const char *file,
1438                                                        const char *content_type)
1439 {
1440         int fd;
1441         struct stat stat_buf;
1442         char buf[512];
1443         char *p = buf;
1444         int n;
1445
1446         fd = open(file, O_RDONLY);
1447         if (fd < 1) {
1448                 p += sprintf(p, "HTTP/1.0 400 Bad\x0d\x0a"
1449                         "Server: libwebsockets\x0d\x0a"
1450                         "\x0d\x0a"
1451                 );
1452                 libwebsocket_write(wsi, (unsigned char *)buf, p - buf,
1453                                                                 LWS_WRITE_HTTP);
1454
1455                 return -1;
1456         }
1457
1458         fstat(fd, &stat_buf);
1459         p += sprintf(p, "HTTP/1.0 200 OK\x0d\x0a"
1460                         "Server: libwebsockets\x0d\x0a"
1461                         "Content-Type: %s\x0d\x0a"
1462                         "Content-Length: %u\x0d\x0a"
1463                         "\x0d\x0a", content_type, (unsigned int)stat_buf.st_size);
1464
1465         libwebsocket_write(wsi, (unsigned char *)buf, p - buf, LWS_WRITE_HTTP);
1466
1467         n = 1;
1468         while (n > 0) {
1469                 n = read(fd, buf, 512);
1470                 if (n <= 0)
1471                         continue;
1472                 libwebsocket_write(wsi, (unsigned char *)buf, n,
1473                                                                 LWS_WRITE_HTTP);
1474         }
1475
1476         close(fd);
1477
1478         return 0;
1479 }
1480
1481
1482 /**
1483  * libwebsockets_remaining_packet_payload() - Bytes to come before "overall"
1484  *                                            rx packet is complete
1485  * @wsi:                Websocket instance (available from user callback)
1486  *
1487  *      This function is intended to be called from the callback if the
1488  *  user code is interested in "complete packets" from the client.
1489  *  libwebsockets just passes through payload as it comes and issues a buffer
1490  *  additionally when it hits a built-in limit.  The LWS_CALLBACK_RECEIVE
1491  *  callback handler can use this API to find out if the buffer it has just
1492  *  been given is the last piece of a "complete packet" from the client --
1493  *  when that is the case libwebsockets_remaining_packet_payload() will return
1494  *  0.
1495  *
1496  *  Many protocols won't care becuse their packets are always small.
1497  */
1498
1499 size_t
1500 libwebsockets_remaining_packet_payload(struct libwebsocket *wsi)
1501 {
1502         return wsi->rx_packet_length;
1503 }