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_EXTENSIONS] = { "Sec-WebSocket-Extensions:", 25 },
33 [WSI_TOKEN_ORIGIN] = { "Origin:", 7 },
34 [WSI_TOKEN_DRAFT] = { "Sec-WebSocket-Draft:", 20 },
35 [WSI_TOKEN_CHALLENGE] = { "\x0d\x0a", 2 },
37 [WSI_TOKEN_KEY] = { "Sec-WebSocket-Key:", 18 },
38 [WSI_TOKEN_VERSION] = { "Sec-WebSocket-Version:", 22 },
40 [WSI_TOKEN_ACCEPT] = { "Sec-WebSocket-Accept:", 21 },
41 [WSI_TOKEN_NONCE] = { "Sec-WebSocket-Nonce:", 20 },
42 [WSI_TOKEN_HTTP] = { "HTTP/1.1 ", 9 },
43 [WSI_TOKEN_SWORIGIN] = { "Sec-WebSocket-Origin:", 21 },
47 int libwebsocket_parse(struct libwebsocket *wsi, unsigned char c)
51 switch (wsi->parser_state) {
52 case WSI_TOKEN_GET_URI:
54 case WSI_TOKEN_CONNECTION:
57 case WSI_TOKEN_PROTOCOL:
58 case WSI_TOKEN_UPGRADE:
59 case WSI_TOKEN_ORIGIN:
60 case WSI_TOKEN_SWORIGIN:
62 case WSI_TOKEN_CHALLENGE:
64 case WSI_TOKEN_VERSION:
65 case WSI_TOKEN_ACCEPT:
67 case WSI_TOKEN_EXTENSIONS:
69 debug("WSI_TOKEN_(%d) '%c'\n", wsi->parser_state, c);
71 /* collect into malloc'd buffers */
72 /* optional space swallow */
73 if (!wsi->utf8_token[wsi->parser_state].token_len && c == ' ')
76 /* special case space terminator for get-uri */
77 if (wsi->parser_state == WSI_TOKEN_GET_URI && c == ' ') {
78 wsi->utf8_token[wsi->parser_state].token[
79 wsi->utf8_token[wsi->parser_state].token_len] = '\0';
80 wsi->parser_state = WSI_TOKEN_SKIPPING;
84 /* allocate appropriate memory */
85 if (wsi->utf8_token[wsi->parser_state].token_len ==
86 wsi->current_alloc_len - 1) {
88 wsi->current_alloc_len += LWS_ADDITIONAL_HDR_ALLOC;
89 if (wsi->current_alloc_len >= LWS_MAX_HEADER_LEN) {
90 /* it's waaay to much payload, fail it */
91 strcpy(wsi->utf8_token[wsi->parser_state].token,
92 "!!! Length exceeded maximum supported !!!");
93 wsi->parser_state = WSI_TOKEN_SKIPPING;
96 wsi->utf8_token[wsi->parser_state].token =
97 realloc(wsi->utf8_token[wsi->parser_state].token,
98 wsi->current_alloc_len);
102 if (wsi->parser_state != WSI_TOKEN_CHALLENGE && c == '\x0d') {
103 wsi->utf8_token[wsi->parser_state].token[
104 wsi->utf8_token[wsi->parser_state].token_len] = '\0';
105 wsi->parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
109 wsi->utf8_token[wsi->parser_state].token[
110 wsi->utf8_token[wsi->parser_state].token_len++] = c;
112 /* per-protocol end of headers management */
114 if (wsi->parser_state != WSI_TOKEN_CHALLENGE)
117 /* -76 has no version header */
118 if (!wsi->utf8_token[WSI_TOKEN_VERSION].token_len &&
119 wsi->utf8_token[wsi->parser_state].token_len != 8)
122 /* <= 03 has old handshake with version header */
123 if (wsi->utf8_token[WSI_TOKEN_VERSION].token_len &&
124 atoi(wsi->utf8_token[WSI_TOKEN_VERSION].token) < 4 &&
125 wsi->utf8_token[wsi->parser_state].token_len != 8)
128 /* For any supported protocol we have enough payload */
130 debug("Setting WSI_PARSING_COMPLETE\n");
131 wsi->parser_state = WSI_PARSING_COMPLETE;
134 /* collecting and checking a name part */
135 case WSI_TOKEN_NAME_PART:
136 debug("WSI_TOKEN_NAME_PART '%c'\n", c);
138 if (wsi->name_buffer_pos == sizeof(wsi->name_buffer) - 1) {
139 /* name bigger than we can handle, skip until next */
140 wsi->parser_state = WSI_TOKEN_SKIPPING;
143 wsi->name_buffer[wsi->name_buffer_pos++] = c;
144 wsi->name_buffer[wsi->name_buffer_pos] = '\0';
146 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
147 if (wsi->name_buffer_pos != lws_tokens[n].token_len)
149 if (strcmp(lws_tokens[n].token, wsi->name_buffer))
151 debug("known hdr '%s'\n", wsi->name_buffer);
152 wsi->parser_state = WSI_TOKEN_GET_URI + n;
153 wsi->current_alloc_len = LWS_INITIAL_HDR_ALLOC;
155 wsi->utf8_token[wsi->parser_state].token =
156 malloc(wsi->current_alloc_len);
157 wsi->utf8_token[wsi->parser_state].token_len = 0;
161 /* colon delimiter means we just don't know this name */
163 if (wsi->parser_state == WSI_TOKEN_NAME_PART && c == ':') {
164 debug("skipping unknown header '%s'\n",
166 wsi->parser_state = WSI_TOKEN_SKIPPING;
170 if (wsi->parser_state != WSI_TOKEN_CHALLENGE)
173 /* don't look for payload when it can just be http headers */
175 if (!wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len) {
176 /* they're HTTP headers, not websocket upgrade! */
177 debug("Setting WSI_PARSING_COMPLETE "
178 "from http headers\n");
179 wsi->parser_state = WSI_PARSING_COMPLETE;
182 /* 04 version has no packet content after end of hdrs */
184 if (wsi->utf8_token[WSI_TOKEN_VERSION].token_len &&
185 atoi(wsi->utf8_token[WSI_TOKEN_VERSION].token) >= 4) {
186 debug("04 header completed\n");
187 wsi->parser_state = WSI_PARSING_COMPLETE;
192 if (wsi->ietf_spec_revision >= 4) {
193 debug("04 header completed\n");
194 wsi->parser_state = WSI_PARSING_COMPLETE;
199 /* skipping arg part of a name we didn't recognize */
200 case WSI_TOKEN_SKIPPING:
201 debug("WSI_TOKEN_SKIPPING '%c'\n", c);
203 wsi->parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
205 case WSI_TOKEN_SKIPPING_SAW_CR:
206 debug("WSI_TOKEN_SKIPPING_SAW_CR '%c'\n", c);
208 wsi->parser_state = WSI_TOKEN_NAME_PART;
210 wsi->parser_state = WSI_TOKEN_SKIPPING;
211 wsi->name_buffer_pos = 0;
213 /* we're done, ignore anything else */
214 case WSI_PARSING_COMPLETE:
215 debug("WSI_PARSING_COMPLETE '%c'\n", c);
218 default: /* keep gcc happy */
226 xor_no_mask(struct libwebsocket *wsi, unsigned char c)
232 xor_mask_04(struct libwebsocket *wsi, unsigned char c)
234 c ^= wsi->masking_key_04[wsi->frame_mask_index++];
235 if (wsi->frame_mask_index == 20)
236 wsi->frame_mask_index = 0;
242 xor_mask_05(struct libwebsocket *wsi, unsigned char c)
244 return c ^ wsi->frame_masking_nonce_04[(wsi->frame_mask_index++) & 3];
249 static int libwebsocket_rx_sm(struct libwebsocket *wsi, unsigned char c)
252 unsigned char buf[20 + 4];
254 switch (wsi->lws_rx_parse_state) {
257 switch (wsi->ietf_spec_revision) {
258 /* Firefox 4.0b6 likes this as of 30 Oct */
261 wsi->lws_rx_parse_state = LWS_RXPS_SEEN_76_FF;
263 wsi->lws_rx_parse_state =
264 LWS_RXPS_EAT_UNTIL_76_FF;
265 wsi->rx_user_buffer_head = 0;
270 wsi->all_zero_nonce = 1;
271 wsi->frame_masking_nonce_04[0] = c;
273 wsi->all_zero_nonce = 0;
274 wsi->lws_rx_parse_state = LWS_RXPS_04_MASK_NONCE_1;
277 fprintf(stderr, "libwebsocket_rx_sm doesn't know "
278 "about spec version %d\n", wsi->ietf_spec_revision);
282 case LWS_RXPS_04_MASK_NONCE_1:
283 wsi->frame_masking_nonce_04[1] = c;
285 wsi->all_zero_nonce = 0;
286 wsi->lws_rx_parse_state = LWS_RXPS_04_MASK_NONCE_2;
288 case LWS_RXPS_04_MASK_NONCE_2:
289 wsi->frame_masking_nonce_04[2] = c;
291 wsi->all_zero_nonce = 0;
292 wsi->lws_rx_parse_state = LWS_RXPS_04_MASK_NONCE_3;
294 case LWS_RXPS_04_MASK_NONCE_3:
295 wsi->frame_masking_nonce_04[3] = c;
297 wsi->all_zero_nonce = 0;
299 if (wsi->protocol->owning_server->options &
300 LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK)
303 if (wsi->ietf_spec_revision > 4)
307 * we are able to compute the frame key now
308 * it's a SHA1 of ( frame nonce we were just sent, concatenated
309 * with the connection masking key we computed at handshake
310 * time ) -- yeah every frame from the client invokes a SHA1
311 * for no real reason so much for lightweight.
314 buf[0] = wsi->frame_masking_nonce_04[0];
315 buf[1] = wsi->frame_masking_nonce_04[1];
316 buf[2] = wsi->frame_masking_nonce_04[2];
317 buf[3] = wsi->frame_masking_nonce_04[3];
319 memcpy(buf + 4, wsi->masking_key_04, 20);
322 * wsi->frame_mask_04 will be our recirculating 20-byte XOR key
326 SHA1((unsigned char *)buf, 4 + 20, wsi->frame_mask_04);
331 * start from the zero'th byte in the XOR key buffer since
332 * this is the start of a frame with a new key
335 wsi->frame_mask_index = 0;
338 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_1;
342 * 04 logical framing from the spec (all this is masked when incoming
343 * and has to be unmasked)
345 * We ignore the possibility of extension data because we don't
346 * negotiate any extensions at the moment.
349 * 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
350 * +-+-+-+-+-------+-+-------------+-------------------------------+
351 * |F|R|R|R| opcode|R| Payload len | Extended payload length |
352 * |I|S|S|S| (4) |S| (7) | (16/63) |
353 * |N|V|V|V| |V| | (if payload len==126/127) |
355 * +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
356 * | Extended payload length continued, if payload len == 127 |
357 * + - - - - - - - - - - - - - - - +-------------------------------+
358 * | | Extension data |
359 * +-------------------------------+ - - - - - - - - - - - - - - - +
361 * +---------------------------------------------------------------+
362 * : Application data :
363 * +---------------------------------------------------------------+
365 * We pass payload through to userland as soon as we get it, ignoring
366 * FIN. It's up to userland to buffer it up if it wants to see a
367 * whole unfragmented block of the original size (which may be up to
371 case LWS_RXPS_04_FRAME_HDR_1:
373 * 04 spec defines the opcode like this: (1, 2, and 3 are
374 * "control frame" opcodes which may not be fragmented or
375 * have size larger than 126)
378 * %x0 ; continuation frame
379 * / %x1 ; connection close
383 * / %x5 ; binary frame
389 c = wsi->xor_mask(wsi, c);
393 "Frame has extensions set illegally 1\n");
394 /* kill the connection */
398 wsi->opcode = c & 0xf;
399 wsi->final = !!((c >> 7) & 1);
402 wsi->opcode == LWS_WS_OPCODE_04__CONTINUATION &&
403 wsi->rx_packet_length == 0) {
405 "Frame starts with final continuation\n");
406 /* kill the connection */
410 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;
413 case LWS_RXPS_04_FRAME_HDR_LEN:
414 c = wsi->xor_mask(wsi, c);
417 fprintf(stderr, "Frame has extensions "
418 "set illegally 2\n");
419 /* kill the connection */
425 /* control frames are not allowed to have big lengths */
426 switch (wsi->opcode) {
427 case LWS_WS_OPCODE_04__CLOSE:
428 case LWS_WS_OPCODE_04__PING:
429 case LWS_WS_OPCODE_04__PONG:
430 fprintf(stderr, "Control frame asking for "
431 "extended length is illegal\n");
432 /* kill the connection */
437 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;
440 /* control frames are not allowed to have big lengths */
441 switch (wsi->opcode) {
442 case LWS_WS_OPCODE_04__CLOSE:
443 case LWS_WS_OPCODE_04__PING:
444 case LWS_WS_OPCODE_04__PONG:
445 fprintf(stderr, "Control frame asking for "
446 "extended length is illegal\n");
447 /* kill the connection */
452 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;
455 wsi->rx_packet_length = c;
456 wsi->lws_rx_parse_state =
457 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
462 case LWS_RXPS_04_FRAME_HDR_LEN16_2:
463 c = wsi->xor_mask(wsi, c);
465 wsi->rx_packet_length = c << 8;
466 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1;
469 case LWS_RXPS_04_FRAME_HDR_LEN16_1:
470 c = wsi->xor_mask(wsi, c);
472 wsi->rx_packet_length |= c;
473 wsi->lws_rx_parse_state =
474 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
477 case LWS_RXPS_04_FRAME_HDR_LEN64_8:
478 c = wsi->xor_mask(wsi, c);
480 fprintf(stderr, "b63 of length must be zero\n");
481 /* kill the connection */
485 wsi->rx_packet_length = ((size_t)c) << 56;
487 wsi->rx_packet_length = 0;
489 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;
492 case LWS_RXPS_04_FRAME_HDR_LEN64_7:
494 wsi->rx_packet_length |= ((size_t)wsi->xor_mask(wsi, c)) << 48;
496 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;
499 case LWS_RXPS_04_FRAME_HDR_LEN64_6:
501 wsi->rx_packet_length |= ((size_t)wsi->xor_mask(wsi, c)) << 40;
503 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;
506 case LWS_RXPS_04_FRAME_HDR_LEN64_5:
508 wsi->rx_packet_length |= ((size_t)wsi->xor_mask(wsi, c)) << 32;
510 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;
513 case LWS_RXPS_04_FRAME_HDR_LEN64_4:
514 wsi->rx_packet_length |= ((size_t)wsi->xor_mask(wsi, c)) << 24;
515 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3;
518 case LWS_RXPS_04_FRAME_HDR_LEN64_3:
519 wsi->rx_packet_length |= ((size_t)wsi->xor_mask(wsi, c)) << 16;
520 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2;
523 case LWS_RXPS_04_FRAME_HDR_LEN64_2:
524 wsi->rx_packet_length |= ((size_t)wsi->xor_mask(wsi, c)) << 8;
525 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1;
528 case LWS_RXPS_04_FRAME_HDR_LEN64_1:
529 wsi->rx_packet_length |= ((size_t)wsi->xor_mask(wsi, c));
530 wsi->lws_rx_parse_state =
531 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
534 case LWS_RXPS_EAT_UNTIL_76_FF:
536 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
539 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
540 (wsi->rx_user_buffer_head++)] = c;
542 if (wsi->rx_user_buffer_head != MAX_USER_RX_BUFFER)
545 if (wsi->protocol->callback)
546 wsi->protocol->callback(wsi, LWS_CALLBACK_RECEIVE,
548 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
549 wsi->rx_user_buffer_head);
550 wsi->rx_user_buffer_head = 0;
552 case LWS_RXPS_SEEN_76_FF:
556 debug("Seen that client is requesting "
557 "a v76 close, sending ack\n");
560 n = libwebsocket_write(wsi, buf, 2, LWS_WRITE_HTTP);
562 fprintf(stderr, "ERROR writing to socket");
565 debug(" v76 close ack sent, server closing skt\n");
566 /* returning < 0 will get it closed in parent */
569 case LWS_RXPS_PULLING_76_LENGTH:
572 case LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED:
573 if (wsi->all_zero_nonce && wsi->ietf_spec_revision >= 5)
574 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
575 (wsi->rx_user_buffer_head++)] = c;
577 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
578 (wsi->rx_user_buffer_head++)] =
579 wsi->xor_mask(wsi, c);
581 if (--wsi->rx_packet_length == 0) {
582 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
585 if (wsi->rx_user_buffer_head != MAX_USER_RX_BUFFER)
589 * is this frame a control packet we should take care of at this
590 * layer? If so service it and hide it from the user callback
593 switch (wsi->opcode) {
594 case LWS_WS_OPCODE_04__CLOSE:
595 /* parrot the close packet payload back */
596 n = libwebsocket_write(wsi, (unsigned char *)
597 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
598 wsi->rx_user_buffer_head, LWS_WRITE_CLOSE);
599 wsi->state = WSI_STATE_RETURNED_CLOSE_ALREADY;
600 /* close the connection */
603 case LWS_WS_OPCODE_04__PING:
604 /* parrot the ping packet payload back as a pong */
605 n = libwebsocket_write(wsi, (unsigned char *)
606 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
607 wsi->rx_user_buffer_head, LWS_WRITE_PONG);
608 /* ... then just drop it */
609 wsi->rx_user_buffer_head = 0;
612 case LWS_WS_OPCODE_04__PONG:
613 /* keep the statistics... */
614 wsi->pings_vs_pongs--;
615 /* ... then just drop it */
616 wsi->rx_user_buffer_head = 0;
624 * No it's real payload, pass it up to the user callback.
625 * It's nicely buffered with the pre-padding taken care of
626 * so it can be sent straight out again using libwebsocket_write
629 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
630 wsi->rx_user_buffer_head] = '\0';
632 if (wsi->protocol->callback)
633 wsi->protocol->callback(wsi, LWS_CALLBACK_RECEIVE,
635 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
636 wsi->rx_user_buffer_head);
637 wsi->rx_user_buffer_head = 0;
645 int libwebsocket_client_rx_sm(struct libwebsocket *wsi, unsigned char c)
648 unsigned char buf[20 + 4];
649 int callback_action = LWS_CALLBACK_CLIENT_RECEIVE;
651 switch (wsi->lws_rx_parse_state) {
654 switch (wsi->ietf_spec_revision) {
655 /* Firefox 4.0b6 likes this as of 30 Oct */
658 wsi->lws_rx_parse_state = LWS_RXPS_SEEN_76_FF;
660 wsi->lws_rx_parse_state =
661 LWS_RXPS_EAT_UNTIL_76_FF;
662 wsi->rx_user_buffer_head = 0;
668 * 04 logical framing from the spec (all this is masked when
669 * incoming and has to be unmasked)
671 * We ignore the possibility of extension data because we don't
672 * negotiate any extensions at the moment.
675 * 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
676 * +-+-+-+-+-------+-+-------------+-------------------------------+
677 * |F|R|R|R| opcode|R| Payload len | Extended payload length |
678 * |I|S|S|S| (4) |S| (7) | (16/63) |
679 * |N|V|V|V| |V| | (if payload len==126/127) |
681 * +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
682 * | Extended payload length continued, if payload len == 127 |
683 * + - - - - - - - - - - - - - - - +-------------------------------+
684 * | | Extension data |
685 * +-------------------------------+ - - - - - - - - - - - - - - - +
687 * +---------------------------------------------------------------+
688 * : Application data :
689 * +---------------------------------------------------------------+
691 * We pass payload through to userland as soon as we get it, ignoring
692 * FIN. It's up to userland to buffer it up if it wants to see a
693 * whole unfragmented block of the original size (which may be up to
698 * 04 spec defines the opcode like this: (1, 2, and 3 are
699 * "control frame" opcodes which may not be fragmented or
700 * have size larger than 126)
703 * %x0 ; continuation frame
704 * / %x1 ; connection close
708 * / %x5 ; binary frame
715 fprintf(stderr, "Frame has extensions set "
716 "illegally on first framing byte %02X\n", c);
717 /* kill the connection */
721 wsi->opcode = c & 0xf;
722 wsi->final = !!((c >> 7) & 1);
725 wsi->opcode == LWS_WS_OPCODE_04__CONTINUATION &&
726 wsi->rx_packet_length == 0) {
728 "Frame starts with final continuation\n");
729 /* kill the connection */
733 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;
736 fprintf(stderr, "client_rx_sm doesn't know how "
737 "to handle spec version %02d\n",
738 wsi->ietf_spec_revision);
744 case LWS_RXPS_04_FRAME_HDR_LEN:
748 "Frame has extensions set illegally 4\n");
749 /* kill the connection */
755 /* control frames are not allowed to have big lengths */
756 switch (wsi->opcode) {
757 case LWS_WS_OPCODE_04__CLOSE:
758 case LWS_WS_OPCODE_04__PING:
759 case LWS_WS_OPCODE_04__PONG:
760 fprintf(stderr, "Control frame asking for "
761 "extended length is illegal\n");
762 /* kill the connection */
767 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;
770 /* control frames are not allowed to have big lengths */
771 switch (wsi->opcode) {
772 case LWS_WS_OPCODE_04__CLOSE:
773 case LWS_WS_OPCODE_04__PING:
774 case LWS_WS_OPCODE_04__PONG:
775 fprintf(stderr, "Control frame asking for "
776 "extended length is illegal\n");
777 /* kill the connection */
782 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;
785 wsi->rx_packet_length = c;
786 wsi->lws_rx_parse_state =
787 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
792 case LWS_RXPS_04_FRAME_HDR_LEN16_2:
793 wsi->rx_packet_length = c << 8;
794 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1;
797 case LWS_RXPS_04_FRAME_HDR_LEN16_1:
798 wsi->rx_packet_length |= c;
799 wsi->lws_rx_parse_state =
800 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
803 case LWS_RXPS_04_FRAME_HDR_LEN64_8:
805 fprintf(stderr, "b63 of length must be zero\n");
806 /* kill the connection */
810 wsi->rx_packet_length = ((size_t)c) << 56;
812 wsi->rx_packet_length = 0;
814 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;
817 case LWS_RXPS_04_FRAME_HDR_LEN64_7:
819 wsi->rx_packet_length |= ((size_t)c) << 48;
821 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;
824 case LWS_RXPS_04_FRAME_HDR_LEN64_6:
826 wsi->rx_packet_length |= ((size_t)c) << 40;
828 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;
831 case LWS_RXPS_04_FRAME_HDR_LEN64_5:
833 wsi->rx_packet_length |= ((size_t)c) << 32;
835 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;
838 case LWS_RXPS_04_FRAME_HDR_LEN64_4:
839 wsi->rx_packet_length |= ((size_t)c) << 24;
840 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_3;
843 case LWS_RXPS_04_FRAME_HDR_LEN64_3:
844 wsi->rx_packet_length |= ((size_t)c) << 16;
845 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_2;
848 case LWS_RXPS_04_FRAME_HDR_LEN64_2:
849 wsi->rx_packet_length |= ((size_t)c) << 8;
850 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_1;
853 case LWS_RXPS_04_FRAME_HDR_LEN64_1:
854 wsi->rx_packet_length |= (size_t)c;
855 wsi->lws_rx_parse_state =
856 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
859 case LWS_RXPS_EAT_UNTIL_76_FF:
861 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
864 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
865 (wsi->rx_user_buffer_head++)] = c;
867 if (wsi->rx_user_buffer_head != MAX_USER_RX_BUFFER)
870 if (wsi->protocol->callback)
871 wsi->protocol->callback(wsi,
872 LWS_CALLBACK_CLIENT_RECEIVE,
874 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
875 wsi->rx_user_buffer_head);
876 wsi->rx_user_buffer_head = 0;
878 case LWS_RXPS_SEEN_76_FF:
882 debug("Seen that client is requesting "
883 "a v76 close, sending ack\n");
886 n = libwebsocket_write(wsi, buf, 2, LWS_WRITE_HTTP);
888 fprintf(stderr, "ERROR writing to socket");
891 debug(" v76 close ack sent, server closing skt\n");
892 /* returning < 0 will get it closed in parent */
895 case LWS_RXPS_PULLING_76_LENGTH:
898 case LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED:
899 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
900 (wsi->rx_user_buffer_head++)] = c;
901 if (--wsi->rx_packet_length == 0) {
902 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
905 if (wsi->rx_user_buffer_head != MAX_USER_RX_BUFFER)
909 * is this frame a control packet we should take care of at this
910 * layer? If so service it and hide it from the user callback
913 switch (wsi->opcode) {
914 case LWS_WS_OPCODE_04__CLOSE:
915 /* parrot the close packet payload back */
916 n = libwebsocket_write(wsi, (unsigned char *)
917 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
918 wsi->rx_user_buffer_head, LWS_WRITE_CLOSE);
919 wsi->state = WSI_STATE_RETURNED_CLOSE_ALREADY;
920 /* close the connection */
923 case LWS_WS_OPCODE_04__PING:
924 /* parrot the ping packet payload back as a pong*/
925 n = libwebsocket_write(wsi, (unsigned char *)
926 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
927 wsi->rx_user_buffer_head, LWS_WRITE_PONG);
930 case LWS_WS_OPCODE_04__PONG:
931 /* keep the statistics... */
932 wsi->pings_vs_pongs--;
935 callback_action = LWS_CALLBACK_CLIENT_RECEIVE_PONG;
943 * No it's real payload, pass it up to the user callback.
944 * It's nicely buffered with the pre-padding taken care of
945 * so it can be sent straight out again using libwebsocket_write
948 if (wsi->protocol->callback)
949 wsi->protocol->callback(wsi, callback_action,
951 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
952 wsi->rx_user_buffer_head);
953 wsi->rx_user_buffer_head = 0;
956 fprintf(stderr, "client rx illegal state\n");
965 int libwebsocket_interpret_incoming_packet(struct libwebsocket *wsi,
966 unsigned char *buf, size_t len)
971 fprintf(stderr, "received %d byte packet\n", (int)len);
972 for (n = 0; n < len; n++)
973 fprintf(stderr, "%02X ", buf[n]);
974 fprintf(stderr, "\n");
977 /* let the rx protocol state machine have as much as it needs */
981 if (libwebsocket_rx_sm(wsi, buf[n++]) < 0)
989 libwebsocket_0405_frame_mask_generate(struct libwebsocket *wsi)
994 /* fetch the per-frame nonce */
996 n = read(wsi->protocol->owning_server->fd_random,
997 wsi->frame_masking_nonce_04, 4);
999 fprintf(stderr, "Unable to read from random device %s %d\n",
1000 SYSTEM_RANDOM_FILEPATH, n);
1004 /* start masking from first byte of masking key buffer */
1005 wsi->frame_mask_index = 0;
1007 if (wsi->ietf_spec_revision != 4)
1010 /* 04 only does SHA-1 more complex key */
1013 * the frame key is the frame nonce (4 bytes) followed by the
1014 * connection masking key, hashed by SHA1
1017 memcpy(buf, wsi->frame_masking_nonce_04, 4);
1019 memcpy(buf + 4, wsi->masking_key_04, 20);
1021 /* concatenate the nonce with the connection key then hash it */
1023 SHA1((unsigned char *)buf, 4 + 20, wsi->frame_mask_04);
1030 * libwebsocket_write() - Apply protocol then write data to client
1031 * @wsi: Websocket instance (available from user callback)
1032 * @buf: The data to send. For data being sent on a websocket
1033 * connection (ie, not default http), this buffer MUST have
1034 * LWS_SEND_BUFFER_PRE_PADDING bytes valid BEFORE the pointer
1035 * and an additional LWS_SEND_BUFFER_POST_PADDING bytes valid
1036 * in the buffer after (buf + len). This is so the protocol
1037 * header and trailer data can be added in-situ.
1038 * @len: Count of the data bytes in the payload starting from buf
1039 * @protocol: Use LWS_WRITE_HTTP to reply to an http connection, and one
1040 * of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
1041 * data on a websockets connection. Remember to allow the extra
1042 * bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
1045 * This function provides the way to issue data back to the client
1046 * for both http and websocket protocols.
1048 * In the case of sending using websocket protocol, be sure to allocate
1049 * valid storage before and after buf as explained above. This scheme
1050 * allows maximum efficiency of sending data and protocol in a single
1051 * packet while not burdening the user code with any protocol knowledge.
1054 int libwebsocket_write(struct libwebsocket *wsi, unsigned char *buf,
1055 size_t len, enum libwebsocket_write_protocol protocol)
1060 unsigned int shift = 7;
1062 if (len == 0 && protocol != LWS_WRITE_CLOSE) {
1063 fprintf(stderr, "zero length libwebsocket_write attempt\n");
1067 if (protocol == LWS_WRITE_HTTP)
1070 /* websocket protocol, either binary or text */
1072 if (wsi->state != WSI_STATE_ESTABLISHED)
1075 switch (wsi->ietf_spec_revision) {
1076 /* chrome likes this as of 30 Oct */
1077 /* Firefox 4.0b6 likes this as of 30 Oct */
1079 if ((protocol & 0xf) == LWS_WRITE_BINARY) {
1080 /* in binary mode we send 7-bit used length blocks */
1082 while (len & (127 << shift)) {
1088 while (shift >= 0) {
1091 ((len >> shift) & 127) | 0x80;
1094 ((len >> shift) & 127);
1101 /* frame type = text, length-free spam mode */
1104 buf[len] = 0xff; /* EOT marker */
1111 switch (protocol & 0xf) {
1112 case LWS_WRITE_TEXT:
1113 n = LWS_WS_OPCODE_04__TEXT_FRAME;
1115 case LWS_WRITE_BINARY:
1116 n = LWS_WS_OPCODE_04__BINARY_FRAME;
1118 case LWS_WRITE_CLOSE:
1119 n = LWS_WS_OPCODE_04__CLOSE;
1122 * v5 mandates the first byte of close packet
1123 * in both client and server directions
1126 if (wsi->ietf_spec_revision >= 5) {
1128 /* we can do this because we demand post-buf */
1133 switch (wsi->mode) {
1134 case LWS_CONNMODE_WS_SERVING:
1136 fprintf(stderr, "LWS_WRITE_CLOSE S\n");
1140 case LWS_CONNMODE_WS_CLIENT:
1142 fprintf(stderr, "LWS_WRITE_CLOSE C\n");
1149 case LWS_WRITE_PING:
1150 n = LWS_WS_OPCODE_04__PING;
1151 wsi->pings_vs_pongs++;
1153 case LWS_WRITE_PONG:
1154 n = LWS_WS_OPCODE_04__PONG;
1157 fprintf(stderr, "libwebsocket_write: unknown write "
1158 "opcode / protocol\n");
1162 if (!(protocol & LWS_WRITE_NO_FIN))
1179 #if defined __LP64__
1180 buf[-8] = (len >> 56) & 0x7f;
1181 buf[-7] = len >> 48;
1182 buf[-6] = len >> 40;
1183 buf[-5] = len >> 32;
1190 buf[-4] = len >> 24;
1191 buf[-3] = len >> 16;
1201 for (n = 0; n < (len + pre + post); n++)
1202 fprintf(stderr, "%02X ", buf[n - pre]);
1204 fprintf(stderr, "\n");
1208 * Deal with masking if we are in client -> server direction and
1209 * the protocol demands it
1212 if (wsi->mode == LWS_CONNMODE_WS_CLIENT &&
1213 wsi->ietf_spec_revision >= 4) {
1216 * this is only useful for security tests where it's required
1217 * to control the raw packet payload content
1220 if (!(protocol & LWS_WRITE_CLIENT_IGNORE_XOR_MASK)) {
1222 if (libwebsocket_0405_frame_mask_generate(wsi)) {
1223 fprintf(stderr, "libwebsocket_write: "
1224 "frame mask generation failed\n");
1229 * use the XOR masking against everything we send
1230 * past the frame nonce
1233 for (n = 0; n < (len + pre + post); n++)
1234 buf[n - pre] = wsi->xor_mask(wsi, buf[n - pre]);
1237 /* make space for the frame nonce in clear */
1240 /* copy the frame nonce into place */
1241 memcpy(&buf[0 - pre], wsi->frame_masking_nonce_04, 4);
1243 /* make space for the frame nonce in clear */
1255 #ifdef LWS_OPENSSL_SUPPORT
1257 n = SSL_write(wsi->ssl, buf - pre, len + pre + post);
1259 fprintf(stderr, "ERROR writing to socket\n");
1264 n = send(wsi->sock, buf - pre, len + pre + post, MSG_NOSIGNAL);
1266 fprintf(stderr, "ERROR writing to socket\n");
1269 #ifdef LWS_OPENSSL_SUPPORT
1273 debug("written %d bytes to client\n", (int)len);
1280 * libwebsockets_serve_http_file() - Send a file back to the client using http
1281 * @wsi: Websocket instance (available from user callback)
1282 * @file: The file to issue over http
1283 * @content_type: The http content type, eg, text/html
1285 * This function is intended to be called from the callback in response
1286 * to http requests from the client. It allows the callback to issue
1287 * local files down the http link in a single step.
1290 int libwebsockets_serve_http_file(struct libwebsocket *wsi, const char *file,
1291 const char *content_type)
1299 fd = open(file, O_RDONLY);
1301 p += sprintf(p, "HTTP/1.0 400 Bad\x0d\x0a"
1302 "Server: libwebsockets\x0d\x0a"
1305 libwebsocket_write(wsi, (unsigned char *)buf, p - buf,
1312 p += sprintf(p, "HTTP/1.0 200 OK\x0d\x0a"
1313 "Server: libwebsockets\x0d\x0a"
1314 "Content-Type: %s\x0d\x0a"
1315 "Content-Length: %u\x0d\x0a"
1316 "\x0d\x0a", content_type, (unsigned int)stat.st_size);
1318 libwebsocket_write(wsi, (unsigned char *)buf, p - buf, LWS_WRITE_HTTP);
1322 n = read(fd, buf, 512);
1325 libwebsocket_write(wsi, (unsigned char *)buf, n,
1336 * libwebsockets_remaining_packet_payload() - Bytes to come before "overall"
1337 * rx packet is complete
1338 * @wsi: Websocket instance (available from user callback)
1340 * This function is intended to be called from the callback if the
1341 * user code is interested in "complete packets" from the client.
1342 * libwebsockets just passes through payload as it comes and issues a buffer
1343 * additionally when it hits a built-in limit. The LWS_CALLBACK_RECEIVE
1344 * callback handler can use this API to find out if the buffer it has just
1345 * been given is the last piece of a "complete packet" from the client --
1346 * when that is the case libwebsockets_remaining_packet_payload() will return
1349 * Many protocols won't care becuse their packets are always small.
1353 libwebsockets_remaining_packet_payload(struct libwebsocket *wsi)
1355 return wsi->rx_packet_length;