2 * libwebsockets - small server side websockets and web server implementation
4 * Copyright (C) 2010 Andy Green <andy@warmcat.com>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation:
9 * version 2.1 of the License.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22 #include "private-libwebsockets.h"
24 const struct lws_tokens lws_tokens[WSI_TOKEN_COUNT] = {
25 [WSI_TOKEN_GET_URI] = { "GET ", 4 },
26 [WSI_TOKEN_HOST] = { "Host:", 5 },
27 [WSI_TOKEN_CONNECTION] = { "Connection:", 11 },
28 [WSI_TOKEN_KEY1] = { "Sec-WebSocket-Key1:", 19 },
29 [WSI_TOKEN_KEY2] = { "Sec-WebSocket-Key2:", 19 },
30 [WSI_TOKEN_PROTOCOL] = { "Sec-WebSocket-Protocol:", 23 },
31 [WSI_TOKEN_UPGRADE] = { "Upgrade:", 8 },
32 [WSI_TOKEN_ORIGIN] = { "Origin:", 7 },
33 [WSI_TOKEN_DRAFT] = { "Sec-WebSocket-Draft:", 20 },
34 [WSI_TOKEN_CHALLENGE] = { "\x0d\x0a", 2 },
36 [WSI_TOKEN_KEY] = { "Sec-WebSocket-Key:", 18 },
37 [WSI_TOKEN_VERSION] = { "Sec-WebSocket-Version:", 22 },
39 [WSI_TOKEN_ACCEPT] = { "Sec-WebSocket-Accept:", 21 },
40 [WSI_TOKEN_NONCE] = { "Sec-WebSocket-Nonce:", 20 },
41 [WSI_TOKEN_HTTP] = { "HTTP/1.1 ", 9 },
42 [WSI_TOKEN_SWORIGIN] = { "Sec-WebSocket-Origin:", 21 },
46 int libwebsocket_parse(struct libwebsocket *wsi, unsigned char c)
50 switch (wsi->parser_state) {
51 case WSI_TOKEN_GET_URI:
53 case WSI_TOKEN_CONNECTION:
56 case WSI_TOKEN_PROTOCOL:
57 case WSI_TOKEN_UPGRADE:
58 case WSI_TOKEN_ORIGIN:
59 case WSI_TOKEN_SWORIGIN:
61 case WSI_TOKEN_CHALLENGE:
63 case WSI_TOKEN_VERSION:
64 case WSI_TOKEN_ACCEPT:
67 debug("WSI_TOKEN_(%d) '%c'\n", wsi->parser_state, c);
69 /* collect into malloc'd buffers */
70 /* optional space swallow */
71 if (!wsi->utf8_token[wsi->parser_state].token_len && c == ' ')
74 /* special case space terminator for get-uri */
75 if (wsi->parser_state == WSI_TOKEN_GET_URI && c == ' ') {
76 wsi->utf8_token[wsi->parser_state].token[
77 wsi->utf8_token[wsi->parser_state].token_len] = '\0';
78 wsi->parser_state = WSI_TOKEN_SKIPPING;
82 /* allocate appropriate memory */
83 if (wsi->utf8_token[wsi->parser_state].token_len ==
84 wsi->current_alloc_len - 1) {
86 wsi->current_alloc_len += LWS_ADDITIONAL_HDR_ALLOC;
87 if (wsi->current_alloc_len >= LWS_MAX_HEADER_LEN) {
88 /* it's waaay to much payload, fail it */
89 strcpy(wsi->utf8_token[wsi->parser_state].token,
90 "!!! Length exceeded maximum supported !!!");
91 wsi->parser_state = WSI_TOKEN_SKIPPING;
94 wsi->utf8_token[wsi->parser_state].token =
95 realloc(wsi->utf8_token[wsi->parser_state].token,
96 wsi->current_alloc_len);
100 if (wsi->parser_state != WSI_TOKEN_CHALLENGE && c == '\x0d') {
101 wsi->utf8_token[wsi->parser_state].token[
102 wsi->utf8_token[wsi->parser_state].token_len] = '\0';
103 wsi->parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
107 wsi->utf8_token[wsi->parser_state].token[
108 wsi->utf8_token[wsi->parser_state].token_len++] = c;
110 /* per-protocol end of headers management */
112 if (wsi->parser_state != WSI_TOKEN_CHALLENGE)
115 /* -76 has no version header */
116 if (!wsi->utf8_token[WSI_TOKEN_VERSION].token_len &&
117 wsi->utf8_token[wsi->parser_state].token_len != 8)
120 /* <= 03 has old handshake with version header */
121 if (wsi->utf8_token[WSI_TOKEN_VERSION].token_len &&
122 atoi(wsi->utf8_token[WSI_TOKEN_VERSION].token) < 4 &&
123 wsi->utf8_token[wsi->parser_state].token_len != 8)
126 /* For any supported protocol we have enough payload */
128 debug("Setting WSI_PARSING_COMPLETE\n");
129 wsi->parser_state = WSI_PARSING_COMPLETE;
132 /* collecting and checking a name part */
133 case WSI_TOKEN_NAME_PART:
134 debug("WSI_TOKEN_NAME_PART '%c'\n", c);
136 if (wsi->name_buffer_pos == sizeof(wsi->name_buffer) - 1) {
137 /* name bigger than we can handle, skip until next */
138 wsi->parser_state = WSI_TOKEN_SKIPPING;
141 wsi->name_buffer[wsi->name_buffer_pos++] = c;
142 wsi->name_buffer[wsi->name_buffer_pos] = '\0';
144 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
145 if (wsi->name_buffer_pos != lws_tokens[n].token_len)
147 if (strcmp(lws_tokens[n].token, wsi->name_buffer))
149 debug("known hdr '%s'\n", wsi->name_buffer);
150 wsi->parser_state = WSI_TOKEN_GET_URI + n;
151 wsi->current_alloc_len = LWS_INITIAL_HDR_ALLOC;
153 wsi->utf8_token[wsi->parser_state].token =
154 malloc(wsi->current_alloc_len);
155 wsi->utf8_token[wsi->parser_state].token_len = 0;
159 /* colon delimiter means we just don't know this name */
161 if (wsi->parser_state == WSI_TOKEN_NAME_PART && c == ':') {
162 debug("skipping unknown header '%s'\n",
164 wsi->parser_state = WSI_TOKEN_SKIPPING;
168 if (wsi->parser_state != WSI_TOKEN_CHALLENGE)
171 /* don't look for payload when it can just be http headers */
173 if (!wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len) {
174 /* they're HTTP headers, not websocket upgrade! */
175 debug("Setting WSI_PARSING_COMPLETE "
176 "from http headers\n");
177 wsi->parser_state = WSI_PARSING_COMPLETE;
180 /* 04 version has no packet content after end of hdrs */
182 if (wsi->utf8_token[WSI_TOKEN_VERSION].token_len &&
183 atoi(wsi->utf8_token[WSI_TOKEN_VERSION].token) >= 4) {
184 debug("04 header completed\n");
185 wsi->parser_state = WSI_PARSING_COMPLETE;
190 if (wsi->ietf_spec_revision >= 4) {
191 debug("04 header completed\n");
192 wsi->parser_state = WSI_PARSING_COMPLETE;
197 /* skipping arg part of a name we didn't recognize */
198 case WSI_TOKEN_SKIPPING:
199 debug("WSI_TOKEN_SKIPPING '%c'\n", c);
201 wsi->parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
203 case WSI_TOKEN_SKIPPING_SAW_CR:
204 debug("WSI_TOKEN_SKIPPING_SAW_CR '%c'\n", c);
206 wsi->parser_state = WSI_TOKEN_NAME_PART;
208 wsi->parser_state = WSI_TOKEN_SKIPPING;
209 wsi->name_buffer_pos = 0;
211 /* we're done, ignore anything else */
212 case WSI_PARSING_COMPLETE:
213 debug("WSI_PARSING_COMPLETE '%c'\n", c);
216 default: /* keep gcc happy */
223 static inline unsigned char
224 xor_mask(struct libwebsocket *wsi, unsigned char c)
226 c ^= wsi->masking_key_04[wsi->frame_mask_index++];
227 if (wsi->frame_mask_index == 20)
228 wsi->frame_mask_index = 0;
234 static int libwebsocket_rx_sm(struct libwebsocket *wsi, unsigned char c)
237 unsigned char buf[20 + 4];
239 switch (wsi->lws_rx_parse_state) {
242 switch (wsi->ietf_spec_revision) {
243 /* Firefox 4.0b6 likes this as of 30 Oct */
246 wsi->lws_rx_parse_state = LWS_RXPS_SEEN_76_FF;
248 wsi->lws_rx_parse_state =
249 LWS_RXPS_EAT_UNTIL_76_FF;
250 wsi->rx_user_buffer_head = 0;
254 wsi->frame_masking_nonce_04[0] = c;
255 wsi->lws_rx_parse_state = LWS_RXPS_04_MASK_NONCE_1;
259 case LWS_RXPS_04_MASK_NONCE_1:
260 wsi->frame_masking_nonce_04[1] = c;
261 wsi->lws_rx_parse_state = LWS_RXPS_04_MASK_NONCE_2;
263 case LWS_RXPS_04_MASK_NONCE_2:
264 wsi->frame_masking_nonce_04[2] = c;
265 wsi->lws_rx_parse_state = LWS_RXPS_04_MASK_NONCE_3;
267 case LWS_RXPS_04_MASK_NONCE_3:
268 wsi->frame_masking_nonce_04[3] = c;
271 * we are able to compute the frame key now
272 * it's a SHA1 of ( frame nonce we were just sent, concatenated
273 * with the connection masking key we computed at handshake
274 * time ) -- yeah every frame from the client invokes a SHA1
275 * for no real reason so much for lightweight.
278 buf[0] = wsi->frame_masking_nonce_04[0];
279 buf[1] = wsi->frame_masking_nonce_04[1];
280 buf[2] = wsi->frame_masking_nonce_04[2];
281 buf[3] = wsi->frame_masking_nonce_04[3];
283 memcpy(buf + 4, wsi->masking_key_04, 20);
286 * wsi->frame_mask_04 will be our recirculating 20-byte XOR key
290 SHA1((unsigned char *)buf, 4 + 20, wsi->frame_mask_04);
293 * start from the zero'th byte in the XOR key buffer since
294 * this is the start of a frame with a new key
297 wsi->frame_mask_index = 0;
299 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_1;
303 * 04 logical framing from the spec (all this is masked when incoming
304 * and has to be unmasked)
306 * We ignore the possibility of extension data because we don't
307 * negotiate any extensions at the moment.
310 * 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
311 * +-+-+-+-+-------+-+-------------+-------------------------------+
312 * |F|R|R|R| opcode|R| Payload len | Extended payload length |
313 * |I|S|S|S| (4) |S| (7) | (16/63) |
314 * |N|V|V|V| |V| | (if payload len==126/127) |
316 * +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
317 * | Extended payload length continued, if payload len == 127 |
318 * + - - - - - - - - - - - - - - - +-------------------------------+
319 * | | Extension data |
320 * +-------------------------------+ - - - - - - - - - - - - - - - +
322 * +---------------------------------------------------------------+
323 * : Application data :
324 * +---------------------------------------------------------------+
326 * We pass payload through to userland as soon as we get it, ignoring
327 * FIN. It's up to userland to buffer it up if it wants to see a
328 * whole unfragmented block of the original size (which may be up to
332 case LWS_RXPS_04_FRAME_HDR_1:
334 * 04 spec defines the opcode like this: (1, 2, and 3 are
335 * "control frame" opcodes which may not be fragmented or
336 * have size larger than 126)
339 * %x0 ; continuation frame
340 * / %x1 ; connection close
344 * / %x5 ; binary frame
350 c = xor_mask(wsi, c);
354 "Frame has extensions set illegally 1\n");
355 /* kill the connection */
359 wsi->opcode = c & 0xf;
360 wsi->final = !!((c >> 7) & 1);
363 wsi->opcode == LWS_WS_OPCODE_04__CONTINUATION &&
364 wsi->rx_packet_length == 0) {
366 "Frame starts with final continuation\n");
367 /* kill the connection */
371 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;
374 case LWS_RXPS_04_FRAME_HDR_LEN:
375 c = xor_mask(wsi, c);
378 fprintf(stderr, "Frame has extensions "
379 "set illegally 2\n");
380 /* kill the connection */
386 /* control frames are not allowed to have big lengths */
387 switch (wsi->opcode) {
388 case LWS_WS_OPCODE_04__CLOSE:
389 case LWS_WS_OPCODE_04__PING:
390 case LWS_WS_OPCODE_04__PONG:
391 fprintf(stderr, "Control frame asking for "
392 "extended length is illegal\n");
393 /* kill the connection */
398 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;
401 /* control frames are not allowed to have big lengths */
402 switch (wsi->opcode) {
403 case LWS_WS_OPCODE_04__CLOSE:
404 case LWS_WS_OPCODE_04__PING:
405 case LWS_WS_OPCODE_04__PONG:
406 fprintf(stderr, "Control frame asking for "
407 "extended length is illegal\n");
408 /* kill the connection */
413 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;
416 wsi->rx_packet_length = c;
417 wsi->lws_rx_parse_state =
418 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
423 case LWS_RXPS_04_FRAME_HDR_LEN16_2:
424 c = xor_mask(wsi, c);
426 wsi->rx_packet_length = c << 8;
427 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1;
430 case LWS_RXPS_04_FRAME_HDR_LEN16_1:
431 c = xor_mask(wsi, c);
433 wsi->rx_packet_length |= c;
434 wsi->lws_rx_parse_state =
435 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
438 case LWS_RXPS_04_FRAME_HDR_LEN64_8:
439 c = xor_mask(wsi, c);
441 fprintf(stderr, "b63 of length must be zero\n");
442 /* kill the connection */
446 wsi->rx_packet_length = ((size_t)c) << 56;
448 wsi->rx_packet_length = 0;
450 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;
453 case LWS_RXPS_04_FRAME_HDR_LEN64_7:
455 wsi->rx_packet_length |= ((size_t)xor_mask(wsi, c)) << 48;
457 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;
460 case LWS_RXPS_04_FRAME_HDR_LEN64_6:
462 wsi->rx_packet_length |= ((size_t)xor_mask(wsi, c)) << 40;
464 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;
467 case LWS_RXPS_04_FRAME_HDR_LEN64_5:
469 wsi->rx_packet_length |= ((size_t)xor_mask(wsi, c)) << 32;
471 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;
474 case LWS_RXPS_04_FRAME_HDR_LEN64_4:
475 wsi->rx_packet_length |= ((size_t)xor_mask(wsi, c)) << 24;
476 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3;
479 case LWS_RXPS_04_FRAME_HDR_LEN64_3:
480 wsi->rx_packet_length |= ((size_t)xor_mask(wsi, c)) << 16;
481 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2;
484 case LWS_RXPS_04_FRAME_HDR_LEN64_2:
485 wsi->rx_packet_length |= ((size_t)xor_mask(wsi, c)) << 8;
486 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1;
489 case LWS_RXPS_04_FRAME_HDR_LEN64_1:
490 wsi->rx_packet_length |= ((size_t)xor_mask(wsi, c));
491 wsi->lws_rx_parse_state =
492 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
495 case LWS_RXPS_EAT_UNTIL_76_FF:
497 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
500 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
501 (wsi->rx_user_buffer_head++)] = c;
503 if (wsi->rx_user_buffer_head != MAX_USER_RX_BUFFER)
506 if (wsi->protocol->callback)
507 wsi->protocol->callback(wsi, LWS_CALLBACK_RECEIVE,
509 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
510 wsi->rx_user_buffer_head);
511 wsi->rx_user_buffer_head = 0;
513 case LWS_RXPS_SEEN_76_FF:
517 debug("Seen that client is requesting "
518 "a v76 close, sending ack\n");
521 n = libwebsocket_write(wsi, buf, 2, LWS_WRITE_HTTP);
523 fprintf(stderr, "ERROR writing to socket");
526 debug(" v76 close ack sent, server closing skt\n");
527 /* returning < 0 will get it closed in parent */
530 case LWS_RXPS_PULLING_76_LENGTH:
533 case LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED:
534 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
535 (wsi->rx_user_buffer_head++)] = xor_mask(wsi, c);
537 if (--wsi->rx_packet_length == 0) {
538 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
541 if (wsi->rx_user_buffer_head != MAX_USER_RX_BUFFER)
545 * is this frame a control packet we should take care of at this
546 * layer? If so service it and hide it from the user callback
549 switch (wsi->opcode) {
550 case LWS_WS_OPCODE_04__CLOSE:
551 /* parrot the close packet payload back */
552 n = libwebsocket_write(wsi, (unsigned char *)
553 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
554 wsi->rx_user_buffer_head, LWS_WRITE_CLOSE);
555 /* close the connection */
558 case LWS_WS_OPCODE_04__PING:
559 /* parrot the ping packet payload back as a pong*/
560 n = libwebsocket_write(wsi, (unsigned char *)
561 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
562 wsi->rx_user_buffer_head, LWS_WRITE_PONG);
565 case LWS_WS_OPCODE_04__PONG:
566 /* keep the statistics... */
567 wsi->pings_vs_pongs--;
568 /* ... then just drop it */
569 wsi->rx_user_buffer_head = 0;
577 * No it's real payload, pass it up to the user callback.
578 * It's nicely buffered with the pre-padding taken care of
579 * so it can be sent straight out again using libwebsocket_write
582 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
583 wsi->rx_user_buffer_head] = '\0';
585 if (wsi->protocol->callback)
586 wsi->protocol->callback(wsi, LWS_CALLBACK_RECEIVE,
588 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
589 wsi->rx_user_buffer_head);
590 wsi->rx_user_buffer_head = 0;
598 int libwebsocket_client_rx_sm(struct libwebsocket *wsi, unsigned char c)
601 unsigned char buf[20 + 4];
603 switch (wsi->lws_rx_parse_state) {
606 switch (wsi->ietf_spec_revision) {
607 /* Firefox 4.0b6 likes this as of 30 Oct */
610 wsi->lws_rx_parse_state = LWS_RXPS_SEEN_76_FF;
612 wsi->lws_rx_parse_state =
613 LWS_RXPS_EAT_UNTIL_76_FF;
614 wsi->rx_user_buffer_head = 0;
619 * 04 logical framing from the spec (all this is masked when
620 * incoming and has to be unmasked)
622 * We ignore the possibility of extension data because we don't
623 * negotiate any extensions at the moment.
626 * 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
627 * +-+-+-+-+-------+-+-------------+-------------------------------+
628 * |F|R|R|R| opcode|R| Payload len | Extended payload length |
629 * |I|S|S|S| (4) |S| (7) | (16/63) |
630 * |N|V|V|V| |V| | (if payload len==126/127) |
632 * +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
633 * | Extended payload length continued, if payload len == 127 |
634 * + - - - - - - - - - - - - - - - +-------------------------------+
635 * | | Extension data |
636 * +-------------------------------+ - - - - - - - - - - - - - - - +
638 * +---------------------------------------------------------------+
639 * : Application data :
640 * +---------------------------------------------------------------+
642 * We pass payload through to userland as soon as we get it, ignoring
643 * FIN. It's up to userland to buffer it up if it wants to see a
644 * whole unfragmented block of the original size (which may be up to
649 * 04 spec defines the opcode like this: (1, 2, and 3 are
650 * "control frame" opcodes which may not be fragmented or
651 * have size larger than 126)
654 * %x0 ; continuation frame
655 * / %x1 ; connection close
659 * / %x5 ; binary frame
666 fprintf(stderr, "Frame has extensions set "
667 "illegally on first framing byte %02X\n", c);
668 /* kill the connection */
672 wsi->opcode = c & 0xf;
673 wsi->final = !!((c >> 7) & 1);
676 wsi->opcode == LWS_WS_OPCODE_04__CONTINUATION &&
677 wsi->rx_packet_length == 0) {
679 "Frame starts with final continuation\n");
680 /* kill the connection */
684 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;
690 case LWS_RXPS_04_FRAME_HDR_LEN:
694 "Frame has extensions set illegally 4\n");
695 /* kill the connection */
701 /* control frames are not allowed to have big lengths */
702 switch (wsi->opcode) {
703 case LWS_WS_OPCODE_04__CLOSE:
704 case LWS_WS_OPCODE_04__PING:
705 case LWS_WS_OPCODE_04__PONG:
706 fprintf(stderr, "Control frame asking for "
707 "extended length is illegal\n");
708 /* kill the connection */
713 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;
716 /* control frames are not allowed to have big lengths */
717 switch (wsi->opcode) {
718 case LWS_WS_OPCODE_04__CLOSE:
719 case LWS_WS_OPCODE_04__PING:
720 case LWS_WS_OPCODE_04__PONG:
721 fprintf(stderr, "Control frame asking for "
722 "extended length is illegal\n");
723 /* kill the connection */
728 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;
731 wsi->rx_packet_length = c;
732 wsi->lws_rx_parse_state =
733 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
738 case LWS_RXPS_04_FRAME_HDR_LEN16_2:
739 wsi->rx_packet_length = c << 8;
740 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1;
743 case LWS_RXPS_04_FRAME_HDR_LEN16_1:
744 wsi->rx_packet_length |= c;
745 wsi->lws_rx_parse_state =
746 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
749 case LWS_RXPS_04_FRAME_HDR_LEN64_8:
751 fprintf(stderr, "b63 of length must be zero\n");
752 /* kill the connection */
756 wsi->rx_packet_length = ((size_t)c) << 56;
758 wsi->rx_packet_length =0;
760 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;
763 case LWS_RXPS_04_FRAME_HDR_LEN64_7:
765 wsi->rx_packet_length |= ((size_t)c) << 48;
767 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;
770 case LWS_RXPS_04_FRAME_HDR_LEN64_6:
772 wsi->rx_packet_length |= ((size_t)c) << 40;
774 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;
777 case LWS_RXPS_04_FRAME_HDR_LEN64_5:
779 wsi->rx_packet_length |= ((size_t)c) << 32;
781 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;
784 case LWS_RXPS_04_FRAME_HDR_LEN64_4:
785 wsi->rx_packet_length |= ((size_t)c) << 24;
786 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3;
789 case LWS_RXPS_04_FRAME_HDR_LEN64_3:
790 wsi->rx_packet_length |= ((size_t)c) << 16;
791 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2;
794 case LWS_RXPS_04_FRAME_HDR_LEN64_2:
795 wsi->rx_packet_length |= ((size_t)c) << 8;
796 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1;
799 case LWS_RXPS_04_FRAME_HDR_LEN64_1:
800 wsi->rx_packet_length |= (size_t)c;
801 wsi->lws_rx_parse_state =
802 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
805 case LWS_RXPS_EAT_UNTIL_76_FF:
807 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
810 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
811 (wsi->rx_user_buffer_head++)] = c;
813 if (wsi->rx_user_buffer_head != MAX_USER_RX_BUFFER)
816 if (wsi->protocol->callback)
817 wsi->protocol->callback(wsi,
818 LWS_CALLBACK_CLIENT_RECEIVE,
820 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
821 wsi->rx_user_buffer_head);
822 wsi->rx_user_buffer_head = 0;
824 case LWS_RXPS_SEEN_76_FF:
828 debug("Seen that client is requesting "
829 "a v76 close, sending ack\n");
832 n = libwebsocket_write(wsi, buf, 2, LWS_WRITE_HTTP);
834 fprintf(stderr, "ERROR writing to socket");
837 debug(" v76 close ack sent, server closing skt\n");
838 /* returning < 0 will get it closed in parent */
841 case LWS_RXPS_PULLING_76_LENGTH:
844 case LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED:
845 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
846 (wsi->rx_user_buffer_head++)] = c;
847 if (--wsi->rx_packet_length == 0) {
848 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
851 if (wsi->rx_user_buffer_head != MAX_USER_RX_BUFFER)
855 * is this frame a control packet we should take care of at this
856 * layer? If so service it and hide it from the user callback
859 switch (wsi->opcode) {
860 case LWS_WS_OPCODE_04__CLOSE:
861 /* parrot the close packet payload back */
862 n = libwebsocket_write(wsi, (unsigned char *)
863 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
864 wsi->rx_user_buffer_head, LWS_WRITE_CLOSE);
865 /* close the connection */
868 case LWS_WS_OPCODE_04__PING:
869 /* parrot the ping packet payload back as a pong*/
870 n = libwebsocket_write(wsi, (unsigned char *)
871 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
872 wsi->rx_user_buffer_head, LWS_WRITE_PONG);
875 case LWS_WS_OPCODE_04__PONG:
876 /* keep the statistics... */
877 wsi->pings_vs_pongs--;
878 /* ... then just drop it */
879 wsi->rx_user_buffer_head = 0;
887 * No it's real payload, pass it up to the user callback.
888 * It's nicely buffered with the pre-padding taken care of
889 * so it can be sent straight out again using libwebsocket_write
892 if (wsi->protocol->callback)
893 wsi->protocol->callback(wsi,
894 LWS_CALLBACK_CLIENT_RECEIVE,
896 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
897 wsi->rx_user_buffer_head);
898 wsi->rx_user_buffer_head = 0;
901 fprintf(stderr, "client rx illegal state\n");
910 int libwebsocket_interpret_incoming_packet(struct libwebsocket *wsi,
911 unsigned char *buf, size_t len)
916 fprintf(stderr, "received %d byte packet\n", (int)len);
917 for (n = 0; n < len; n++)
918 fprintf(stderr, "%02X ", buf[n]);
919 fprintf(stderr, "\n");
922 /* let the rx protocol state machine have as much as it needs */
926 if (libwebsocket_rx_sm(wsi, buf[n++]) < 0)
934 libwebsocket_04_frame_mask_generate(struct libwebsocket *wsi)
940 /* fetch the per-frame nonce */
942 fd = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
944 fprintf(stderr, "Unable to open random device %s\n",
945 SYSTEM_RANDOM_FILEPATH);
948 n = read(fd, wsi->frame_masking_nonce_04, 4);
950 fprintf(stderr, "Unable to read from random device %s %d\n",
951 SYSTEM_RANDOM_FILEPATH, n);
957 * the frame key is the frame nonce (4 bytes) followed by the
958 * connection masking key, hashed by SHA1
961 memcpy(buf, wsi->frame_masking_nonce_04, 4);
962 memcpy(buf + 4, wsi->masking_key_04, 20);
964 /* concatenate the nonce with the connection key then hash it */
966 SHA1((unsigned char *)buf, 4 + 20, wsi->frame_mask_04);
968 /* start masking from first byte of masking key buffer */
969 wsi->frame_mask_index = 0;
976 * libwebsocket_write() - Apply protocol then write data to client
977 * @wsi: Websocket instance (available from user callback)
978 * @buf: The data to send. For data being sent on a websocket
979 * connection (ie, not default http), this buffer MUST have
980 * LWS_SEND_BUFFER_PRE_PADDING bytes valid BEFORE the pointer
981 * and an additional LWS_SEND_BUFFER_POST_PADDING bytes valid
982 * in the buffer after (buf + len). This is so the protocol
983 * header and trailer data can be added in-situ.
984 * @len: Count of the data bytes in the payload starting from buf
985 * @protocol: Use LWS_WRITE_HTTP to reply to an http connection, and one
986 * of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
987 * data on a websockets connection. Remember to allow the extra
988 * bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
991 * This function provides the way to issue data back to the client
992 * for both http and websocket protocols.
994 * In the case of sending using websocket protocol, be sure to allocate
995 * valid storage before and after buf as explained above. This scheme
996 * allows maximum efficiency of sending data and protocol in a single
997 * packet while not burdening the user code with any protocol knowledge.
1000 int libwebsocket_write(struct libwebsocket *wsi, unsigned char *buf,
1001 size_t len, enum libwebsocket_write_protocol protocol)
1006 unsigned int shift = 7;
1009 fprintf(stderr, "zero length libwebsocket_write attempt\n");
1013 if (protocol == LWS_WRITE_HTTP)
1016 /* websocket protocol, either binary or text */
1018 if (wsi->state != WSI_STATE_ESTABLISHED)
1021 switch (wsi->ietf_spec_revision) {
1022 /* chrome likes this as of 30 Oct */
1023 /* Firefox 4.0b6 likes this as of 30 Oct */
1025 if ((protocol & 0xf) == LWS_WRITE_BINARY) {
1026 /* in binary mode we send 7-bit used length blocks */
1028 while (len & (127 << shift)) {
1034 while (shift >= 0) {
1037 ((len >> shift) & 127) | 0x80;
1040 ((len >> shift) & 127);
1047 /* frame type = text, length-free spam mode */
1050 buf[len] = 0xff; /* EOT marker */
1057 switch (protocol & 0xf) {
1058 case LWS_WRITE_TEXT:
1059 n = LWS_WS_OPCODE_04__TEXT_FRAME;
1061 case LWS_WRITE_BINARY:
1062 n = LWS_WS_OPCODE_04__BINARY_FRAME;
1064 case LWS_WRITE_CLOSE:
1065 n = LWS_WS_OPCODE_04__CLOSE;
1067 case LWS_WRITE_PING:
1068 n = LWS_WS_OPCODE_04__PING;
1069 wsi->pings_vs_pongs++;
1071 case LWS_WRITE_PONG:
1072 n = LWS_WS_OPCODE_04__PONG;
1075 fprintf(stderr, "libwebsocket_write: unknown write "
1076 "opcode / protocol\n");
1080 if (!(protocol & LWS_WRITE_NO_FIN))
1097 #if defined __LP64__
1098 buf[-8] = (len >> 56) & 0x7f;
1099 buf[-7] = len >> 48;
1100 buf[-6] = len >> 40;
1101 buf[-5] = len >> 32;
1108 buf[-4] = len >> 24;
1109 buf[-3] = len >> 16;
1119 for (n = 0; n < (len + pre + post); n++)
1120 fprintf(stderr, "%02X ", buf[n - pre]);
1122 fprintf(stderr, "\n");
1126 * Deal with masking if appropriate
1129 if (wsi->client_mode && wsi->ietf_spec_revision == 4) {
1131 if (libwebsocket_04_frame_mask_generate(wsi)) {
1132 fprintf(stderr, "libwebsocket_write: "
1133 "frame mask generation failed\n");
1138 * use the XOR masking against everything we send
1139 * past the frame nonce
1142 for (n = 0; n < (len + pre + post); n++)
1143 buf[n - pre] = xor_mask(wsi, buf[n - pre]);
1145 /* make space for the frame nonce in clear */
1148 /* copy the frame nonce into place */
1149 memcpy(&buf[0 - pre], wsi->frame_masking_nonce_04, 4);
1153 #ifdef LWS_OPENSSL_SUPPORT
1155 n = SSL_write(wsi->ssl, buf - pre, len + pre + post);
1157 fprintf(stderr, "ERROR writing to socket\n");
1162 n = send(wsi->sock, buf - pre, len + pre + post, MSG_NOSIGNAL);
1164 fprintf(stderr, "ERROR writing to socket\n");
1167 #ifdef LWS_OPENSSL_SUPPORT
1171 debug("written %d bytes to client\n", (int)len);
1178 * libwebsockets_serve_http_file() - Send a file back to the client using http
1179 * @wsi: Websocket instance (available from user callback)
1180 * @file: The file to issue over http
1181 * @content_type: The http content type, eg, text/html
1183 * This function is intended to be called from the callback in response
1184 * to http requests from the client. It allows the callback to issue
1185 * local files down the http link in a single step.
1188 int libwebsockets_serve_http_file(struct libwebsocket *wsi, const char *file,
1189 const char *content_type)
1197 fd = open(file, O_RDONLY);
1199 p += sprintf(p, "HTTP/1.0 400 Bad\x0d\x0a"
1200 "Server: libwebsockets\x0d\x0a"
1203 libwebsocket_write(wsi, (unsigned char *)buf, p - buf,
1210 p += sprintf(p, "HTTP/1.0 200 OK\x0d\x0a"
1211 "Server: libwebsockets\x0d\x0a"
1212 "Content-Type: %s\x0d\x0a"
1213 "Content-Length: %u\x0d\x0a"
1214 "\x0d\x0a", content_type, (unsigned int)stat.st_size);
1216 libwebsocket_write(wsi, (unsigned char *)buf, p - buf, LWS_WRITE_HTTP);
1220 n = read(fd, buf, 512);
1223 libwebsocket_write(wsi, (unsigned char *)buf, n,
1234 * libwebsockets_remaining_packet_payload() - Bytes to come before "overall"
1235 * rx packet is complete
1236 * @wsi: Websocket instance (available from user callback)
1238 * This function is intended to be called from the callback if the
1239 * user code is interested in "complete packets" from the client.
1240 * libwebsockets just passes through payload as it comes and issues a buffer
1241 * additionally when it hits a built-in limit. The LWS_CALLBACK_RECEIVE
1242 * callback handler can use this API to find out if the buffer it has just
1243 * been given is the last piece of a "complete packet" from the client --
1244 * when that is the case libwebsockets_remaining_packet_payload() will return
1247 * Many protocols won't care becuse their packets are always small.
1251 libwebsockets_remaining_packet_payload(struct libwebsocket *wsi)
1253 return wsi->rx_packet_length;