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 if (wsi->protocol->owning_server->options &
227 LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK)
230 c ^= wsi->masking_key_04[wsi->frame_mask_index++];
231 if (wsi->frame_mask_index == 20)
232 wsi->frame_mask_index = 0;
238 static int libwebsocket_rx_sm(struct libwebsocket *wsi, unsigned char c)
241 unsigned char buf[20 + 4];
243 switch (wsi->lws_rx_parse_state) {
246 switch (wsi->ietf_spec_revision) {
247 /* Firefox 4.0b6 likes this as of 30 Oct */
250 wsi->lws_rx_parse_state = LWS_RXPS_SEEN_76_FF;
252 wsi->lws_rx_parse_state =
253 LWS_RXPS_EAT_UNTIL_76_FF;
254 wsi->rx_user_buffer_head = 0;
258 wsi->frame_masking_nonce_04[0] = c;
259 wsi->lws_rx_parse_state = LWS_RXPS_04_MASK_NONCE_1;
263 case LWS_RXPS_04_MASK_NONCE_1:
264 wsi->frame_masking_nonce_04[1] = c;
265 wsi->lws_rx_parse_state = LWS_RXPS_04_MASK_NONCE_2;
267 case LWS_RXPS_04_MASK_NONCE_2:
268 wsi->frame_masking_nonce_04[2] = c;
269 wsi->lws_rx_parse_state = LWS_RXPS_04_MASK_NONCE_3;
271 case LWS_RXPS_04_MASK_NONCE_3:
272 wsi->frame_masking_nonce_04[3] = c;
274 if (wsi->protocol->owning_server->options &
275 LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK)
279 * we are able to compute the frame key now
280 * it's a SHA1 of ( frame nonce we were just sent, concatenated
281 * with the connection masking key we computed at handshake
282 * time ) -- yeah every frame from the client invokes a SHA1
283 * for no real reason so much for lightweight.
286 buf[0] = wsi->frame_masking_nonce_04[0];
287 buf[1] = wsi->frame_masking_nonce_04[1];
288 buf[2] = wsi->frame_masking_nonce_04[2];
289 buf[3] = wsi->frame_masking_nonce_04[3];
291 memcpy(buf + 4, wsi->masking_key_04, 20);
294 * wsi->frame_mask_04 will be our recirculating 20-byte XOR key
298 SHA1((unsigned char *)buf, 4 + 20, wsi->frame_mask_04);
301 * start from the zero'th byte in the XOR key buffer since
302 * this is the start of a frame with a new key
305 wsi->frame_mask_index = 0;
308 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_1;
312 * 04 logical framing from the spec (all this is masked when incoming
313 * and has to be unmasked)
315 * We ignore the possibility of extension data because we don't
316 * negotiate any extensions at the moment.
319 * 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
320 * +-+-+-+-+-------+-+-------------+-------------------------------+
321 * |F|R|R|R| opcode|R| Payload len | Extended payload length |
322 * |I|S|S|S| (4) |S| (7) | (16/63) |
323 * |N|V|V|V| |V| | (if payload len==126/127) |
325 * +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
326 * | Extended payload length continued, if payload len == 127 |
327 * + - - - - - - - - - - - - - - - +-------------------------------+
328 * | | Extension data |
329 * +-------------------------------+ - - - - - - - - - - - - - - - +
331 * +---------------------------------------------------------------+
332 * : Application data :
333 * +---------------------------------------------------------------+
335 * We pass payload through to userland as soon as we get it, ignoring
336 * FIN. It's up to userland to buffer it up if it wants to see a
337 * whole unfragmented block of the original size (which may be up to
341 case LWS_RXPS_04_FRAME_HDR_1:
343 * 04 spec defines the opcode like this: (1, 2, and 3 are
344 * "control frame" opcodes which may not be fragmented or
345 * have size larger than 126)
348 * %x0 ; continuation frame
349 * / %x1 ; connection close
353 * / %x5 ; binary frame
359 c = xor_mask(wsi, c);
363 "Frame has extensions set illegally 1\n");
364 /* kill the connection */
368 wsi->opcode = c & 0xf;
369 wsi->final = !!((c >> 7) & 1);
372 wsi->opcode == LWS_WS_OPCODE_04__CONTINUATION &&
373 wsi->rx_packet_length == 0) {
375 "Frame starts with final continuation\n");
376 /* kill the connection */
380 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;
383 case LWS_RXPS_04_FRAME_HDR_LEN:
384 c = xor_mask(wsi, c);
387 fprintf(stderr, "Frame has extensions "
388 "set illegally 2\n");
389 /* kill the connection */
395 /* control frames are not allowed to have big lengths */
396 switch (wsi->opcode) {
397 case LWS_WS_OPCODE_04__CLOSE:
398 case LWS_WS_OPCODE_04__PING:
399 case LWS_WS_OPCODE_04__PONG:
400 fprintf(stderr, "Control frame asking for "
401 "extended length is illegal\n");
402 /* kill the connection */
407 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;
410 /* control frames are not allowed to have big lengths */
411 switch (wsi->opcode) {
412 case LWS_WS_OPCODE_04__CLOSE:
413 case LWS_WS_OPCODE_04__PING:
414 case LWS_WS_OPCODE_04__PONG:
415 fprintf(stderr, "Control frame asking for "
416 "extended length is illegal\n");
417 /* kill the connection */
422 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;
425 wsi->rx_packet_length = c;
426 wsi->lws_rx_parse_state =
427 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
432 case LWS_RXPS_04_FRAME_HDR_LEN16_2:
433 c = xor_mask(wsi, c);
435 wsi->rx_packet_length = c << 8;
436 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1;
439 case LWS_RXPS_04_FRAME_HDR_LEN16_1:
440 c = xor_mask(wsi, c);
442 wsi->rx_packet_length |= c;
443 wsi->lws_rx_parse_state =
444 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
447 case LWS_RXPS_04_FRAME_HDR_LEN64_8:
448 c = xor_mask(wsi, c);
450 fprintf(stderr, "b63 of length must be zero\n");
451 /* kill the connection */
455 wsi->rx_packet_length = ((size_t)c) << 56;
457 wsi->rx_packet_length = 0;
459 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;
462 case LWS_RXPS_04_FRAME_HDR_LEN64_7:
464 wsi->rx_packet_length |= ((size_t)xor_mask(wsi, c)) << 48;
466 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;
469 case LWS_RXPS_04_FRAME_HDR_LEN64_6:
471 wsi->rx_packet_length |= ((size_t)xor_mask(wsi, c)) << 40;
473 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;
476 case LWS_RXPS_04_FRAME_HDR_LEN64_5:
478 wsi->rx_packet_length |= ((size_t)xor_mask(wsi, c)) << 32;
480 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;
483 case LWS_RXPS_04_FRAME_HDR_LEN64_4:
484 wsi->rx_packet_length |= ((size_t)xor_mask(wsi, c)) << 24;
485 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3;
488 case LWS_RXPS_04_FRAME_HDR_LEN64_3:
489 wsi->rx_packet_length |= ((size_t)xor_mask(wsi, c)) << 16;
490 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2;
493 case LWS_RXPS_04_FRAME_HDR_LEN64_2:
494 wsi->rx_packet_length |= ((size_t)xor_mask(wsi, c)) << 8;
495 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1;
498 case LWS_RXPS_04_FRAME_HDR_LEN64_1:
499 wsi->rx_packet_length |= ((size_t)xor_mask(wsi, c));
500 wsi->lws_rx_parse_state =
501 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
504 case LWS_RXPS_EAT_UNTIL_76_FF:
506 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
509 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
510 (wsi->rx_user_buffer_head++)] = c;
512 if (wsi->rx_user_buffer_head != MAX_USER_RX_BUFFER)
515 if (wsi->protocol->callback)
516 wsi->protocol->callback(wsi, LWS_CALLBACK_RECEIVE,
518 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
519 wsi->rx_user_buffer_head);
520 wsi->rx_user_buffer_head = 0;
522 case LWS_RXPS_SEEN_76_FF:
526 debug("Seen that client is requesting "
527 "a v76 close, sending ack\n");
530 n = libwebsocket_write(wsi, buf, 2, LWS_WRITE_HTTP);
532 fprintf(stderr, "ERROR writing to socket");
535 debug(" v76 close ack sent, server closing skt\n");
536 /* returning < 0 will get it closed in parent */
539 case LWS_RXPS_PULLING_76_LENGTH:
542 case LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED:
543 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
544 (wsi->rx_user_buffer_head++)] = xor_mask(wsi, c);
546 if (--wsi->rx_packet_length == 0) {
547 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
550 if (wsi->rx_user_buffer_head != MAX_USER_RX_BUFFER)
554 * is this frame a control packet we should take care of at this
555 * layer? If so service it and hide it from the user callback
558 switch (wsi->opcode) {
559 case LWS_WS_OPCODE_04__CLOSE:
560 /* parrot the close packet payload back */
561 n = libwebsocket_write(wsi, (unsigned char *)
562 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
563 wsi->rx_user_buffer_head, LWS_WRITE_CLOSE);
564 /* close the connection */
567 case LWS_WS_OPCODE_04__PING:
568 /* parrot the ping packet payload back as a pong*/
569 n = libwebsocket_write(wsi, (unsigned char *)
570 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
571 wsi->rx_user_buffer_head, LWS_WRITE_PONG);
572 /* ... then just drop it */
573 wsi->rx_user_buffer_head = 0;
576 case LWS_WS_OPCODE_04__PONG:
577 /* keep the statistics... */
578 wsi->pings_vs_pongs--;
579 /* ... then just drop it */
580 wsi->rx_user_buffer_head = 0;
588 * No it's real payload, pass it up to the user callback.
589 * It's nicely buffered with the pre-padding taken care of
590 * so it can be sent straight out again using libwebsocket_write
593 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
594 wsi->rx_user_buffer_head] = '\0';
596 if (wsi->protocol->callback)
597 wsi->protocol->callback(wsi, LWS_CALLBACK_RECEIVE,
599 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
600 wsi->rx_user_buffer_head);
601 wsi->rx_user_buffer_head = 0;
609 int libwebsocket_client_rx_sm(struct libwebsocket *wsi, unsigned char c)
612 unsigned char buf[20 + 4];
613 int callback_action = LWS_CALLBACK_CLIENT_RECEIVE;
615 switch (wsi->lws_rx_parse_state) {
618 switch (wsi->ietf_spec_revision) {
619 /* Firefox 4.0b6 likes this as of 30 Oct */
622 wsi->lws_rx_parse_state = LWS_RXPS_SEEN_76_FF;
624 wsi->lws_rx_parse_state =
625 LWS_RXPS_EAT_UNTIL_76_FF;
626 wsi->rx_user_buffer_head = 0;
631 * 04 logical framing from the spec (all this is masked when
632 * incoming and has to be unmasked)
634 * We ignore the possibility of extension data because we don't
635 * negotiate any extensions at the moment.
638 * 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
639 * +-+-+-+-+-------+-+-------------+-------------------------------+
640 * |F|R|R|R| opcode|R| Payload len | Extended payload length |
641 * |I|S|S|S| (4) |S| (7) | (16/63) |
642 * |N|V|V|V| |V| | (if payload len==126/127) |
644 * +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
645 * | Extended payload length continued, if payload len == 127 |
646 * + - - - - - - - - - - - - - - - +-------------------------------+
647 * | | Extension data |
648 * +-------------------------------+ - - - - - - - - - - - - - - - +
650 * +---------------------------------------------------------------+
651 * : Application data :
652 * +---------------------------------------------------------------+
654 * We pass payload through to userland as soon as we get it, ignoring
655 * FIN. It's up to userland to buffer it up if it wants to see a
656 * whole unfragmented block of the original size (which may be up to
661 * 04 spec defines the opcode like this: (1, 2, and 3 are
662 * "control frame" opcodes which may not be fragmented or
663 * have size larger than 126)
666 * %x0 ; continuation frame
667 * / %x1 ; connection close
671 * / %x5 ; binary frame
678 fprintf(stderr, "Frame has extensions set "
679 "illegally on first framing byte %02X\n", c);
680 /* kill the connection */
684 wsi->opcode = c & 0xf;
685 wsi->final = !!((c >> 7) & 1);
688 wsi->opcode == LWS_WS_OPCODE_04__CONTINUATION &&
689 wsi->rx_packet_length == 0) {
691 "Frame starts with final continuation\n");
692 /* kill the connection */
696 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;
702 case LWS_RXPS_04_FRAME_HDR_LEN:
706 "Frame has extensions set illegally 4\n");
707 /* kill the connection */
713 /* control frames are not allowed to have big lengths */
714 switch (wsi->opcode) {
715 case LWS_WS_OPCODE_04__CLOSE:
716 case LWS_WS_OPCODE_04__PING:
717 case LWS_WS_OPCODE_04__PONG:
718 fprintf(stderr, "Control frame asking for "
719 "extended length is illegal\n");
720 /* kill the connection */
725 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;
728 /* control frames are not allowed to have big lengths */
729 switch (wsi->opcode) {
730 case LWS_WS_OPCODE_04__CLOSE:
731 case LWS_WS_OPCODE_04__PING:
732 case LWS_WS_OPCODE_04__PONG:
733 fprintf(stderr, "Control frame asking for "
734 "extended length is illegal\n");
735 /* kill the connection */
740 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;
743 wsi->rx_packet_length = c;
744 wsi->lws_rx_parse_state =
745 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
750 case LWS_RXPS_04_FRAME_HDR_LEN16_2:
751 wsi->rx_packet_length = c << 8;
752 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1;
755 case LWS_RXPS_04_FRAME_HDR_LEN16_1:
756 wsi->rx_packet_length |= c;
757 wsi->lws_rx_parse_state =
758 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
761 case LWS_RXPS_04_FRAME_HDR_LEN64_8:
763 fprintf(stderr, "b63 of length must be zero\n");
764 /* kill the connection */
768 wsi->rx_packet_length = ((size_t)c) << 56;
770 wsi->rx_packet_length = 0;
772 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;
775 case LWS_RXPS_04_FRAME_HDR_LEN64_7:
777 wsi->rx_packet_length |= ((size_t)c) << 48;
779 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;
782 case LWS_RXPS_04_FRAME_HDR_LEN64_6:
784 wsi->rx_packet_length |= ((size_t)c) << 40;
786 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;
789 case LWS_RXPS_04_FRAME_HDR_LEN64_5:
791 wsi->rx_packet_length |= ((size_t)c) << 32;
793 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;
796 case LWS_RXPS_04_FRAME_HDR_LEN64_4:
797 wsi->rx_packet_length |= ((size_t)c) << 24;
798 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3;
801 case LWS_RXPS_04_FRAME_HDR_LEN64_3:
802 wsi->rx_packet_length |= ((size_t)c) << 16;
803 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2;
806 case LWS_RXPS_04_FRAME_HDR_LEN64_2:
807 wsi->rx_packet_length |= ((size_t)c) << 8;
808 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1;
811 case LWS_RXPS_04_FRAME_HDR_LEN64_1:
812 wsi->rx_packet_length |= (size_t)c;
813 wsi->lws_rx_parse_state =
814 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
817 case LWS_RXPS_EAT_UNTIL_76_FF:
819 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
822 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
823 (wsi->rx_user_buffer_head++)] = c;
825 if (wsi->rx_user_buffer_head != MAX_USER_RX_BUFFER)
828 if (wsi->protocol->callback)
829 wsi->protocol->callback(wsi,
830 LWS_CALLBACK_CLIENT_RECEIVE,
832 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
833 wsi->rx_user_buffer_head);
834 wsi->rx_user_buffer_head = 0;
836 case LWS_RXPS_SEEN_76_FF:
840 debug("Seen that client is requesting "
841 "a v76 close, sending ack\n");
844 n = libwebsocket_write(wsi, buf, 2, LWS_WRITE_HTTP);
846 fprintf(stderr, "ERROR writing to socket");
849 debug(" v76 close ack sent, server closing skt\n");
850 /* returning < 0 will get it closed in parent */
853 case LWS_RXPS_PULLING_76_LENGTH:
856 case LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED:
857 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
858 (wsi->rx_user_buffer_head++)] = c;
859 if (--wsi->rx_packet_length == 0) {
860 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
863 if (wsi->rx_user_buffer_head != MAX_USER_RX_BUFFER)
867 * is this frame a control packet we should take care of at this
868 * layer? If so service it and hide it from the user callback
871 switch (wsi->opcode) {
872 case LWS_WS_OPCODE_04__CLOSE:
873 /* parrot the close packet payload back */
874 n = libwebsocket_write(wsi, (unsigned char *)
875 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
876 wsi->rx_user_buffer_head, LWS_WRITE_CLOSE);
877 /* close the connection */
880 case LWS_WS_OPCODE_04__PING:
881 /* parrot the ping packet payload back as a pong*/
882 n = libwebsocket_write(wsi, (unsigned char *)
883 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
884 wsi->rx_user_buffer_head, LWS_WRITE_PONG);
887 case LWS_WS_OPCODE_04__PONG:
888 /* keep the statistics... */
889 wsi->pings_vs_pongs--;
892 callback_action = LWS_CALLBACK_CLIENT_RECEIVE_PONG;
900 * No it's real payload, pass it up to the user callback.
901 * It's nicely buffered with the pre-padding taken care of
902 * so it can be sent straight out again using libwebsocket_write
905 if (wsi->protocol->callback)
906 wsi->protocol->callback(wsi, callback_action,
908 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
909 wsi->rx_user_buffer_head);
910 wsi->rx_user_buffer_head = 0;
913 fprintf(stderr, "client rx illegal state\n");
922 int libwebsocket_interpret_incoming_packet(struct libwebsocket *wsi,
923 unsigned char *buf, size_t len)
928 fprintf(stderr, "received %d byte packet\n", (int)len);
929 for (n = 0; n < len; n++)
930 fprintf(stderr, "%02X ", buf[n]);
931 fprintf(stderr, "\n");
934 /* let the rx protocol state machine have as much as it needs */
938 if (libwebsocket_rx_sm(wsi, buf[n++]) < 0)
946 libwebsocket_04_frame_mask_generate(struct libwebsocket *wsi)
952 /* fetch the per-frame nonce */
954 fd = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
956 fprintf(stderr, "Unable to open random device %s\n",
957 SYSTEM_RANDOM_FILEPATH);
960 n = read(fd, wsi->frame_masking_nonce_04, 4);
962 fprintf(stderr, "Unable to read from random device %s %d\n",
963 SYSTEM_RANDOM_FILEPATH, n);
969 * the frame key is the frame nonce (4 bytes) followed by the
970 * connection masking key, hashed by SHA1
973 memcpy(buf, wsi->frame_masking_nonce_04, 4);
974 memcpy(buf + 4, wsi->masking_key_04, 20);
976 /* concatenate the nonce with the connection key then hash it */
978 SHA1((unsigned char *)buf, 4 + 20, wsi->frame_mask_04);
980 /* start masking from first byte of masking key buffer */
981 wsi->frame_mask_index = 0;
988 * libwebsocket_write() - Apply protocol then write data to client
989 * @wsi: Websocket instance (available from user callback)
990 * @buf: The data to send. For data being sent on a websocket
991 * connection (ie, not default http), this buffer MUST have
992 * LWS_SEND_BUFFER_PRE_PADDING bytes valid BEFORE the pointer
993 * and an additional LWS_SEND_BUFFER_POST_PADDING bytes valid
994 * in the buffer after (buf + len). This is so the protocol
995 * header and trailer data can be added in-situ.
996 * @len: Count of the data bytes in the payload starting from buf
997 * @protocol: Use LWS_WRITE_HTTP to reply to an http connection, and one
998 * of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
999 * data on a websockets connection. Remember to allow the extra
1000 * bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
1003 * This function provides the way to issue data back to the client
1004 * for both http and websocket protocols.
1006 * In the case of sending using websocket protocol, be sure to allocate
1007 * valid storage before and after buf as explained above. This scheme
1008 * allows maximum efficiency of sending data and protocol in a single
1009 * packet while not burdening the user code with any protocol knowledge.
1012 int libwebsocket_write(struct libwebsocket *wsi, unsigned char *buf,
1013 size_t len, enum libwebsocket_write_protocol protocol)
1018 unsigned int shift = 7;
1021 fprintf(stderr, "zero length libwebsocket_write attempt\n");
1025 if (protocol == LWS_WRITE_HTTP)
1028 /* websocket protocol, either binary or text */
1030 if (wsi->state != WSI_STATE_ESTABLISHED)
1033 switch (wsi->ietf_spec_revision) {
1034 /* chrome likes this as of 30 Oct */
1035 /* Firefox 4.0b6 likes this as of 30 Oct */
1037 if ((protocol & 0xf) == LWS_WRITE_BINARY) {
1038 /* in binary mode we send 7-bit used length blocks */
1040 while (len & (127 << shift)) {
1046 while (shift >= 0) {
1049 ((len >> shift) & 127) | 0x80;
1052 ((len >> shift) & 127);
1059 /* frame type = text, length-free spam mode */
1062 buf[len] = 0xff; /* EOT marker */
1069 switch (protocol & 0xf) {
1070 case LWS_WRITE_TEXT:
1071 n = LWS_WS_OPCODE_04__TEXT_FRAME;
1073 case LWS_WRITE_BINARY:
1074 n = LWS_WS_OPCODE_04__BINARY_FRAME;
1076 case LWS_WRITE_CLOSE:
1077 n = LWS_WS_OPCODE_04__CLOSE;
1079 case LWS_WRITE_PING:
1080 n = LWS_WS_OPCODE_04__PING;
1081 wsi->pings_vs_pongs++;
1083 case LWS_WRITE_PONG:
1084 n = LWS_WS_OPCODE_04__PONG;
1087 fprintf(stderr, "libwebsocket_write: unknown write "
1088 "opcode / protocol\n");
1092 if (!(protocol & LWS_WRITE_NO_FIN))
1109 #if defined __LP64__
1110 buf[-8] = (len >> 56) & 0x7f;
1111 buf[-7] = len >> 48;
1112 buf[-6] = len >> 40;
1113 buf[-5] = len >> 32;
1120 buf[-4] = len >> 24;
1121 buf[-3] = len >> 16;
1131 for (n = 0; n < (len + pre + post); n++)
1132 fprintf(stderr, "%02X ", buf[n - pre]);
1134 fprintf(stderr, "\n");
1138 * Deal with masking if appropriate
1141 if (wsi->mode == LWS_CONNMODE_WS_CLIENT &&
1142 wsi->ietf_spec_revision == 4) {
1145 * this is only useful for security tests where it's required
1146 * to control the raw packet payload content
1149 if (!(protocol & LWS_WRITE_CLIENT_IGNORE_XOR_MASK)) {
1151 if (libwebsocket_04_frame_mask_generate(wsi)) {
1152 fprintf(stderr, "libwebsocket_write: "
1153 "frame mask generation failed\n");
1158 * use the XOR masking against everything we send
1159 * past the frame nonce
1162 for (n = 0; n < (len + pre + post); n++)
1163 buf[n - pre] = xor_mask(wsi, buf[n - pre]);
1166 /* make space for the frame nonce in clear */
1169 /* copy the frame nonce into place */
1170 memcpy(&buf[0 - pre], wsi->frame_masking_nonce_04, 4);
1174 #ifdef LWS_OPENSSL_SUPPORT
1176 n = SSL_write(wsi->ssl, buf - pre, len + pre + post);
1178 fprintf(stderr, "ERROR writing to socket\n");
1183 n = send(wsi->sock, buf - pre, len + pre + post, MSG_NOSIGNAL);
1185 fprintf(stderr, "ERROR writing to socket\n");
1188 #ifdef LWS_OPENSSL_SUPPORT
1192 debug("written %d bytes to client\n", (int)len);
1199 * libwebsockets_serve_http_file() - Send a file back to the client using http
1200 * @wsi: Websocket instance (available from user callback)
1201 * @file: The file to issue over http
1202 * @content_type: The http content type, eg, text/html
1204 * This function is intended to be called from the callback in response
1205 * to http requests from the client. It allows the callback to issue
1206 * local files down the http link in a single step.
1209 int libwebsockets_serve_http_file(struct libwebsocket *wsi, const char *file,
1210 const char *content_type)
1218 fd = open(file, O_RDONLY);
1220 p += sprintf(p, "HTTP/1.0 400 Bad\x0d\x0a"
1221 "Server: libwebsockets\x0d\x0a"
1224 libwebsocket_write(wsi, (unsigned char *)buf, p - buf,
1231 p += sprintf(p, "HTTP/1.0 200 OK\x0d\x0a"
1232 "Server: libwebsockets\x0d\x0a"
1233 "Content-Type: %s\x0d\x0a"
1234 "Content-Length: %u\x0d\x0a"
1235 "\x0d\x0a", content_type, (unsigned int)stat.st_size);
1237 libwebsocket_write(wsi, (unsigned char *)buf, p - buf, LWS_WRITE_HTTP);
1241 n = read(fd, buf, 512);
1244 libwebsocket_write(wsi, (unsigned char *)buf, n,
1255 * libwebsockets_remaining_packet_payload() - Bytes to come before "overall"
1256 * rx packet is complete
1257 * @wsi: Websocket instance (available from user callback)
1259 * This function is intended to be called from the callback if the
1260 * user code is interested in "complete packets" from the client.
1261 * libwebsockets just passes through payload as it comes and issues a buffer
1262 * additionally when it hits a built-in limit. The LWS_CALLBACK_RECEIVE
1263 * callback handler can use this API to find out if the buffer it has just
1264 * been given is the last piece of a "complete packet" from the client --
1265 * when that is the case libwebsockets_remaining_packet_payload() will return
1268 * Many protocols won't care becuse their packets are always small.
1272 libwebsockets_remaining_packet_payload(struct libwebsocket *wsi)
1274 return wsi->rx_packet_length;