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] = {
26 /* win32 can't do C99 */
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 },
39 /* [WSI_TOKEN_KEY] = */{ "Sec-WebSocket-Key:", 18 },
40 /* [WSI_TOKEN_VERSION] = */{ "Sec-WebSocket-Version:", 22 },
41 /* [WSI_TOKEN_SWORIGIN]= */{ "Sec-WebSocket-Origin:", 21 },
43 /* [WSI_TOKEN_EXTENSIONS] = */{ "Sec-WebSocket-Extensions:", 25 },
45 /* [WSI_TOKEN_ACCEPT] = */{ "Sec-WebSocket-Accept:", 21 },
46 /* [WSI_TOKEN_NONCE] = */{ "Sec-WebSocket-Nonce:", 20 },
47 /* [WSI_TOKEN_HTTP] = */{ "HTTP/1.1 ", 9 },
51 int libwebsocket_parse(struct libwebsocket *wsi, unsigned char c)
55 switch (wsi->parser_state) {
56 case WSI_TOKEN_GET_URI:
58 case WSI_TOKEN_CONNECTION:
61 case WSI_TOKEN_PROTOCOL:
62 case WSI_TOKEN_UPGRADE:
63 case WSI_TOKEN_ORIGIN:
64 case WSI_TOKEN_SWORIGIN:
66 case WSI_TOKEN_CHALLENGE:
68 case WSI_TOKEN_VERSION:
69 case WSI_TOKEN_ACCEPT:
71 case WSI_TOKEN_EXTENSIONS:
73 debug("WSI_TOKEN_(%d) '%c'\n", wsi->parser_state, c);
75 /* collect into malloc'd buffers */
76 /* optional space swallow */
77 if (!wsi->utf8_token[wsi->parser_state].token_len && c == ' ')
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;
88 /* allocate appropriate memory */
89 if (wsi->utf8_token[wsi->parser_state].token_len ==
90 wsi->current_alloc_len - 1) {
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;
100 wsi->utf8_token[wsi->parser_state].token =
101 realloc(wsi->utf8_token[wsi->parser_state].token,
102 wsi->current_alloc_len);
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;
113 wsi->utf8_token[wsi->parser_state].token[
114 wsi->utf8_token[wsi->parser_state].token_len++] = c;
116 /* per-protocol end of headers management */
118 if (wsi->parser_state != WSI_TOKEN_CHALLENGE)
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)
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)
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)
139 /* no payload challenge in 01 + */
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;
148 /* For any supported protocol we have enough payload */
150 debug("Setting WSI_PARSING_COMPLETE\n");
151 wsi->parser_state = WSI_PARSING_COMPLETE;
154 /* collecting and checking a name part */
155 case WSI_TOKEN_NAME_PART:
156 debug("WSI_TOKEN_NAME_PART '%c'\n", c);
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;
163 wsi->name_buffer[wsi->name_buffer_pos++] = c;
164 wsi->name_buffer[wsi->name_buffer_pos] = '\0';
166 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
167 if (wsi->name_buffer_pos != lws_tokens[n].token_len)
169 if (strcmp(lws_tokens[n].token, wsi->name_buffer))
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;
175 wsi->utf8_token[wsi->parser_state].token =
176 malloc(wsi->current_alloc_len);
177 wsi->utf8_token[wsi->parser_state].token_len = 0;
181 /* colon delimiter means we just don't know this name */
183 if (wsi->parser_state == WSI_TOKEN_NAME_PART && c == ':') {
184 debug("skipping unknown header '%s'\n",
186 wsi->parser_state = WSI_TOKEN_SKIPPING;
190 if (wsi->parser_state != WSI_TOKEN_CHALLENGE)
193 /* don't look for payload when it can just be http headers */
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;
202 /* 04 version has no packet content after end of hdrs */
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;
215 if (wsi->ietf_spec_revision >= 4) {
216 debug("04 header completed\n");
217 wsi->parser_state = WSI_PARSING_COMPLETE;
222 /* skipping arg part of a name we didn't recognize */
223 case WSI_TOKEN_SKIPPING:
224 debug("WSI_TOKEN_SKIPPING '%c'\n", c);
226 wsi->parser_state = WSI_TOKEN_SKIPPING_SAW_CR;
228 case WSI_TOKEN_SKIPPING_SAW_CR:
229 debug("WSI_TOKEN_SKIPPING_SAW_CR '%c'\n", c);
231 wsi->parser_state = WSI_TOKEN_NAME_PART;
233 wsi->parser_state = WSI_TOKEN_SKIPPING;
234 wsi->name_buffer_pos = 0;
236 /* we're done, ignore anything else */
237 case WSI_PARSING_COMPLETE:
238 debug("WSI_PARSING_COMPLETE '%c'\n", c);
241 default: /* keep gcc happy */
249 xor_no_mask(struct libwebsocket *wsi, unsigned char c)
255 xor_mask_04(struct libwebsocket *wsi, unsigned char c)
257 c ^= wsi->masking_key_04[wsi->frame_mask_index++];
258 if (wsi->frame_mask_index == 20)
259 wsi->frame_mask_index = 0;
265 xor_mask_05(struct libwebsocket *wsi, unsigned char c)
267 return c ^ wsi->frame_masking_nonce_04[(wsi->frame_mask_index++) & 3];
272 static int libwebsocket_rx_sm(struct libwebsocket *wsi, unsigned char c)
275 unsigned char buf[20 + 4];
277 switch (wsi->lws_rx_parse_state) {
280 switch (wsi->ietf_spec_revision) {
281 /* Firefox 4.0b6 likes this as of 30 Oct */
284 wsi->lws_rx_parse_state = LWS_RXPS_SEEN_76_FF;
286 wsi->lws_rx_parse_state =
287 LWS_RXPS_EAT_UNTIL_76_FF;
288 wsi->rx_user_buffer_head = 0;
294 wsi->all_zero_nonce = 1;
295 wsi->frame_masking_nonce_04[0] = c;
297 wsi->all_zero_nonce = 0;
298 wsi->lws_rx_parse_state = LWS_RXPS_04_MASK_NONCE_1;
301 fprintf(stderr, "libwebsocket_rx_sm doesn't know "
302 "about spec version %d\n", wsi->ietf_spec_revision);
306 case LWS_RXPS_04_MASK_NONCE_1:
307 wsi->frame_masking_nonce_04[1] = c;
309 wsi->all_zero_nonce = 0;
310 wsi->lws_rx_parse_state = LWS_RXPS_04_MASK_NONCE_2;
312 case LWS_RXPS_04_MASK_NONCE_2:
313 wsi->frame_masking_nonce_04[2] = c;
315 wsi->all_zero_nonce = 0;
316 wsi->lws_rx_parse_state = LWS_RXPS_04_MASK_NONCE_3;
318 case LWS_RXPS_04_MASK_NONCE_3:
319 wsi->frame_masking_nonce_04[3] = c;
321 wsi->all_zero_nonce = 0;
323 if (wsi->protocol->owning_server->options &
324 LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK)
327 if (wsi->ietf_spec_revision > 4)
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.
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];
343 memcpy(buf + 4, wsi->masking_key_04, 20);
346 * wsi->frame_mask_04 will be our recirculating 20-byte XOR key
350 SHA1((unsigned char *)buf, 4 + 20, wsi->frame_mask_04);
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
359 wsi->frame_mask_index = 0;
362 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_1;
366 * 04 logical framing from the spec (all this is masked when incoming
367 * and has to be unmasked)
369 * We ignore the possibility of extension data because we don't
370 * negotiate any extensions at the moment.
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) |
379 * +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
380 * | Extended payload length continued, if payload len == 127 |
381 * + - - - - - - - - - - - - - - - +-------------------------------+
382 * | | Extension data |
383 * +-------------------------------+ - - - - - - - - - - - - - - - +
385 * +---------------------------------------------------------------+
386 * : Application data :
387 * +---------------------------------------------------------------+
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
395 case LWS_RXPS_04_FRAME_HDR_1:
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)
402 * %x0 ; continuation frame
403 * / %x1 ; connection close
407 * / %x5 ; binary frame
413 c = wsi->xor_mask(wsi, c);
417 "Frame has extensions set illegally 1\n");
418 /* kill the connection */
422 wsi->opcode = c & 0xf;
423 wsi->final = !!((c >> 7) & 1);
426 wsi->opcode == LWS_WS_OPCODE_04__CONTINUATION &&
427 wsi->rx_packet_length == 0) {
429 "Frame starts with final continuation\n");
430 /* kill the connection */
434 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;
437 case LWS_RXPS_04_FRAME_HDR_LEN:
438 c = wsi->xor_mask(wsi, c);
441 fprintf(stderr, "Frame has extensions "
442 "set illegally 2\n");
443 /* kill the connection */
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 */
461 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;
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 */
476 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;
479 wsi->rx_packet_length = c;
480 wsi->lws_rx_parse_state =
481 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
486 case LWS_RXPS_04_FRAME_HDR_LEN16_2:
487 c = wsi->xor_mask(wsi, c);
489 wsi->rx_packet_length = c << 8;
490 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_1;
493 case LWS_RXPS_04_FRAME_HDR_LEN16_1:
494 c = wsi->xor_mask(wsi, c);
496 wsi->rx_packet_length |= c;
497 wsi->lws_rx_parse_state =
498 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
501 case LWS_RXPS_04_FRAME_HDR_LEN64_8:
502 c = wsi->xor_mask(wsi, c);
504 fprintf(stderr, "b63 of length must be zero\n");
505 /* kill the connection */
509 wsi->rx_packet_length = ((size_t)c) << 56;
511 wsi->rx_packet_length = 0;
513 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;
516 case LWS_RXPS_04_FRAME_HDR_LEN64_7:
518 wsi->rx_packet_length |= ((size_t)wsi->xor_mask(wsi, c)) << 48;
520 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;
523 case LWS_RXPS_04_FRAME_HDR_LEN64_6:
525 wsi->rx_packet_length |= ((size_t)wsi->xor_mask(wsi, c)) << 40;
527 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;
530 case LWS_RXPS_04_FRAME_HDR_LEN64_5:
532 wsi->rx_packet_length |= ((size_t)wsi->xor_mask(wsi, c)) << 32;
534 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;
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;
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;
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;
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;
558 case LWS_RXPS_EAT_UNTIL_76_FF:
560 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
563 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
564 (wsi->rx_user_buffer_head++)] = c;
566 if (wsi->rx_user_buffer_head != MAX_USER_RX_BUFFER)
569 if (wsi->protocol->callback)
570 wsi->protocol->callback(wsi->protocol->owning_server,
571 wsi, LWS_CALLBACK_RECEIVE,
573 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
574 wsi->rx_user_buffer_head);
575 wsi->rx_user_buffer_head = 0;
577 case LWS_RXPS_SEEN_76_FF:
581 debug("Seen that client is requesting "
582 "a v76 close, sending ack\n");
585 n = libwebsocket_write(wsi, buf, 2, LWS_WRITE_HTTP);
587 fprintf(stderr, "ERROR writing to socket");
590 debug(" v76 close ack sent, server closing skt\n");
591 /* returning < 0 will get it closed in parent */
594 case LWS_RXPS_PULLING_76_LENGTH:
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;
602 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
603 (wsi->rx_user_buffer_head++)] =
604 wsi->xor_mask(wsi, c);
606 if (--wsi->rx_packet_length == 0) {
607 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
610 if (wsi->rx_user_buffer_head != MAX_USER_RX_BUFFER)
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
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 */
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;
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;
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
654 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
655 wsi->rx_user_buffer_head] = '\0';
657 if (wsi->protocol->callback)
658 wsi->protocol->callback(wsi->protocol->owning_server,
659 wsi, LWS_CALLBACK_RECEIVE,
661 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
662 wsi->rx_user_buffer_head);
663 wsi->rx_user_buffer_head = 0;
671 int libwebsocket_client_rx_sm(struct libwebsocket *wsi, unsigned char c)
674 unsigned char buf[20 + 4];
675 int callback_action = LWS_CALLBACK_CLIENT_RECEIVE;
677 switch (wsi->lws_rx_parse_state) {
680 switch (wsi->ietf_spec_revision) {
681 /* Firefox 4.0b6 likes this as of 30 Oct */
684 wsi->lws_rx_parse_state = LWS_RXPS_SEEN_76_FF;
686 wsi->lws_rx_parse_state =
687 LWS_RXPS_EAT_UNTIL_76_FF;
688 wsi->rx_user_buffer_head = 0;
695 * 04 logical framing from the spec (all this is masked when
696 * incoming and has to be unmasked)
698 * We ignore the possibility of extension data because we don't
699 * negotiate any extensions at the moment.
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) |
708 * +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
709 * | Extended payload length continued, if payload len == 127 |
710 * + - - - - - - - - - - - - - - - +-------------------------------+
711 * | | Extension data |
712 * +-------------------------------+ - - - - - - - - - - - - - - - +
714 * +---------------------------------------------------------------+
715 * : Application data :
716 * +---------------------------------------------------------------+
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
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)
730 * %x0 ; continuation frame
731 * / %x1 ; connection close
735 * / %x5 ; binary frame
742 fprintf(stderr, "Frame has extensions set "
743 "illegally on first framing byte %02X\n", c);
744 /* kill the connection */
748 wsi->opcode = c & 0xf;
749 wsi->final = !!((c >> 7) & 1);
752 wsi->opcode == LWS_WS_OPCODE_04__CONTINUATION &&
753 wsi->rx_packet_length == 0) {
755 "Frame starts with final continuation\n");
756 /* kill the connection */
760 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN;
763 fprintf(stderr, "client_rx_sm doesn't know how "
764 "to handle spec version %02d\n",
765 wsi->ietf_spec_revision);
771 case LWS_RXPS_04_FRAME_HDR_LEN:
775 "Frame has extensions set illegally 4\n");
776 /* kill the connection */
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 */
794 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN16_2;
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 */
809 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_8;
812 wsi->rx_packet_length = c;
813 wsi->lws_rx_parse_state =
814 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED;
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;
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;
830 case LWS_RXPS_04_FRAME_HDR_LEN64_8:
832 fprintf(stderr, "b63 of length must be zero\n");
833 /* kill the connection */
837 wsi->rx_packet_length = ((size_t)c) << 56;
839 wsi->rx_packet_length = 0;
841 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_7;
844 case LWS_RXPS_04_FRAME_HDR_LEN64_7:
846 wsi->rx_packet_length |= ((size_t)c) << 48;
848 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_6;
851 case LWS_RXPS_04_FRAME_HDR_LEN64_6:
853 wsi->rx_packet_length |= ((size_t)c) << 40;
855 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_5;
858 case LWS_RXPS_04_FRAME_HDR_LEN64_5:
860 wsi->rx_packet_length |= ((size_t)c) << 32;
862 wsi->lws_rx_parse_state = LWS_RXPS_04_FRAME_HDR_LEN64_4;
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;
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;
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;
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;
886 case LWS_RXPS_EAT_UNTIL_76_FF:
888 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
891 wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING +
892 (wsi->rx_user_buffer_head++)] = c;
894 if (wsi->rx_user_buffer_head != MAX_USER_RX_BUFFER)
897 if (wsi->protocol->callback)
898 wsi->protocol->callback(wsi->protocol->owning_server,
900 LWS_CALLBACK_CLIENT_RECEIVE,
902 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
903 wsi->rx_user_buffer_head);
904 wsi->rx_user_buffer_head = 0;
906 case LWS_RXPS_SEEN_76_FF:
910 debug("Seen that client is requesting "
911 "a v76 close, sending ack\n");
914 n = libwebsocket_write(wsi, buf, 2, LWS_WRITE_HTTP);
916 fprintf(stderr, "ERROR writing to socket");
919 debug(" v76 close ack sent, server closing skt\n");
920 /* returning < 0 will get it closed in parent */
923 case LWS_RXPS_PULLING_76_LENGTH:
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;
933 if (wsi->rx_user_buffer_head != MAX_USER_RX_BUFFER)
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
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 */
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);
958 case LWS_WS_OPCODE_04__PONG:
959 /* keep the statistics... */
960 wsi->pings_vs_pongs--;
963 callback_action = LWS_CALLBACK_CLIENT_RECEIVE_PONG;
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
976 if (wsi->protocol->callback)
977 wsi->protocol->callback(wsi->protocol->owning_server,
978 wsi, callback_action,
980 &wsi->rx_user_buffer[LWS_SEND_BUFFER_PRE_PADDING],
981 wsi->rx_user_buffer_head);
982 wsi->rx_user_buffer_head = 0;
985 fprintf(stderr, "client rx illegal state\n");
994 int libwebsocket_interpret_incoming_packet(struct libwebsocket *wsi,
995 unsigned char *buf, size_t len)
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");
1006 /* let the rx protocol state machine have as much as it needs */
1010 if (libwebsocket_rx_sm(wsi, buf[n++]) < 0)
1018 libwebsocket_0405_frame_mask_generate(struct libwebsocket *wsi)
1023 /* fetch the per-frame nonce */
1025 n = libwebsockets_get_random(wsi->protocol->owning_server,
1026 wsi->frame_masking_nonce_04, 4);
1028 fprintf(stderr, "Unable to read from random device %s %d\n",
1029 SYSTEM_RANDOM_FILEPATH, n);
1033 /* start masking from first byte of masking key buffer */
1034 wsi->frame_mask_index = 0;
1036 if (wsi->ietf_spec_revision != 4)
1039 /* 04 only does SHA-1 more complex key */
1042 * the frame key is the frame nonce (4 bytes) followed by the
1043 * connection masking key, hashed by SHA1
1046 memcpy(buf, wsi->frame_masking_nonce_04, 4);
1048 memcpy(buf + 4, wsi->masking_key_04, 20);
1050 /* concatenate the nonce with the connection key then hash it */
1052 SHA1((unsigned char *)buf, 4 + 20, wsi->frame_mask_04);
1057 int lws_issue_raw(struct libwebsocket *wsi, unsigned char *buf, size_t len)
1061 #ifdef LWS_OPENSSL_SUPPORT
1063 n = SSL_write(wsi->ssl, buf, len);
1066 "ERROR writing to socket\n");
1071 n = send(wsi->sock, buf, len, MSG_NOSIGNAL);
1074 "ERROR writing to socket\n");
1077 #ifdef LWS_OPENSSL_SUPPORT
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
1099 * This function provides the way to issue data back to the client
1100 * for both http and websocket protocols.
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.
1108 int libwebsocket_write(struct libwebsocket *wsi, unsigned char *buf,
1109 size_t len, enum libwebsocket_write_protocol protocol)
1115 unsigned int shift = 7;
1116 struct lws_tokens eff_buf;
1119 if (len == 0 && protocol != LWS_WRITE_CLOSE) {
1120 fprintf(stderr, "zero length libwebsocket_write attempt\n");
1124 if (protocol == LWS_WRITE_HTTP)
1127 /* websocket protocol, either binary or text */
1129 if (wsi->state != WSI_STATE_ESTABLISHED)
1132 switch (wsi->ietf_spec_revision) {
1133 /* chrome likes this as of 30 Oct */
1134 /* Firefox 4.0b6 likes this as of 30 Oct */
1136 if ((protocol & 0xf) == LWS_WRITE_BINARY) {
1137 /* in binary mode we send 7-bit used length blocks */
1139 while (len & (127 << shift)) {
1145 while (shift >= 0) {
1148 ((len >> shift) & 127) | 0x80;
1151 ((len >> shift) & 127);
1158 /* frame type = text, length-free spam mode */
1161 buf[len] = 0xff; /* EOT marker */
1169 switch (protocol & 0xf) {
1170 case LWS_WRITE_TEXT:
1171 n = LWS_WS_OPCODE_04__TEXT_FRAME;
1173 case LWS_WRITE_BINARY:
1174 n = LWS_WS_OPCODE_04__BINARY_FRAME;
1176 case LWS_WRITE_CLOSE:
1177 n = LWS_WS_OPCODE_04__CLOSE;
1180 * v5 mandates the first byte of close packet
1181 * in both client and server directions
1184 switch (wsi->ietf_spec_revision) {
1189 /* we can do this because we demand post-buf */
1194 switch (wsi->mode) {
1195 case LWS_CONNMODE_WS_SERVING:
1197 fprintf(stderr, "LWS_WRITE_CLOSE S\n");
1201 case LWS_CONNMODE_WS_CLIENT:
1203 fprintf(stderr, "LWS_WRITE_CLOSE C\n");
1213 * 06 has a 2-byte status code in network order
1214 * we can do this because we demand post-buf
1217 if (wsi->close_reason) {
1218 /* reason codes count as data bytes */
1220 buf[0] = wsi->close_reason >> 8;
1221 buf[1] = wsi->close_reason;
1227 case LWS_WRITE_PING:
1228 n = LWS_WS_OPCODE_04__PING;
1229 wsi->pings_vs_pongs++;
1231 case LWS_WRITE_PONG:
1232 n = LWS_WS_OPCODE_04__PONG;
1235 fprintf(stderr, "libwebsocket_write: unknown write "
1236 "opcode / protocol\n");
1240 if (!(protocol & LWS_WRITE_NO_FIN))
1251 buf[pre - 2] = len >> 8;
1257 #if defined __LP64__
1258 buf[pre - 8] = (len >> 56) & 0x7f;
1259 buf[pre - 7] = len >> 48;
1260 buf[pre - 6] = len >> 40;
1261 buf[pre - 5] = len >> 32;
1268 buf[pre - 4] = len >> 24;
1269 buf[pre - 3] = len >> 16;
1270 buf[pre - 2] = len >> 8;
1279 for (n = 0; n < (len + pre + post); n++)
1280 fprintf(stderr, "%02X ", buf[n - pre]);
1282 fprintf(stderr, "\n");
1286 * Deal with masking if we are in client -> server direction and
1287 * the protocol demands it
1290 if (wsi->mode == LWS_CONNMODE_WS_CLIENT &&
1291 wsi->ietf_spec_revision >= 4) {
1294 * this is only useful for security tests where it's required
1295 * to control the raw packet payload content
1298 if (!(protocol & LWS_WRITE_CLIENT_IGNORE_XOR_MASK)) {
1300 if (libwebsocket_0405_frame_mask_generate(wsi)) {
1301 fprintf(stderr, "libwebsocket_write: "
1302 "frame mask generation failed\n");
1307 * use the XOR masking against everything we send
1308 * past the frame nonce
1311 for (n = 0; n < (len + pre + post); n++)
1312 buf[n - pre] = wsi->xor_mask(wsi, buf[n - pre]);
1315 /* make space for the frame nonce in clear */
1318 /* copy the frame nonce into place */
1319 memcpy(&buf[0 - pre], wsi->frame_masking_nonce_04, 4);
1321 /* make space for the frame nonce in clear */
1334 if (protocol == LWS_WRITE_HTTP) {
1335 if (lws_issue_raw(wsi, (unsigned char *)buf - pre,
1343 * give any active extensions a chance to munge the buffer
1344 * before send. We pass in a pointer to an lws_tokens struct
1345 * prepared with the default buffer and content length that's in
1346 * there. Rather than rewrite the default buffer, extensions
1347 * that expect to grow the buffer can adapt .token to
1348 * point to their own per-connection buffer in the extension
1349 * user allocation. By default with no extensions or no
1350 * extension callback handling, just the normal input buffer is
1351 * used then so it is efficient.
1353 * callback returns 1 in case it wants to spill more buffers
1356 eff_buf.token = (char *)buf - pre;
1357 eff_buf.token_len = len + pre + post;
1360 * while we have original buf to spill ourselves, or extensions report
1361 * more in their pipeline
1367 /* default to nobody has more to spill */
1371 /* show every extension the new incoming data */
1373 for (n = 0; n < wsi->count_active_extensions; n++) {
1374 m = wsi->active_extensions[n]->callback(
1375 wsi->protocol->owning_server, wsi,
1376 LWS_EXT_CALLBACK_PACKET_TX_PRESEND,
1377 wsi->active_extensions_user[n], &eff_buf, 0);
1379 fprintf(stderr, "Extension reports fatal error\n");
1384 * at least one extension told us he has more
1385 * to spill, so we will go around again after
1390 /* assuming they left us something to send, send it */
1392 if (eff_buf.token_len)
1393 if (lws_issue_raw(wsi, (unsigned char *)eff_buf.token,
1397 /* we used up what we had */
1399 eff_buf.token = NULL;
1400 eff_buf.token_len = 0;
1403 * Did that leave the pipe choked?
1406 if (!lws_send_pipe_choked(wsi))
1407 /* no we could add more */
1410 fprintf(stderr, "choked\n");
1413 * Yes, he's choked. Don't spill the rest now get a callback
1414 * when he is ready to send and take care of it there
1416 libwebsocket_callback_on_writable(
1417 wsi->protocol->owning_server, wsi);
1418 wsi->extension_data_pending = 1;
1422 debug("written %d bytes to client\n", eff_buf.token_len);
1429 * libwebsockets_serve_http_file() - Send a file back to the client using http
1430 * @wsi: Websocket instance (available from user callback)
1431 * @file: The file to issue over http
1432 * @content_type: The http content type, eg, text/html
1434 * This function is intended to be called from the callback in response
1435 * to http requests from the client. It allows the callback to issue
1436 * local files down the http link in a single step.
1439 int libwebsockets_serve_http_file(struct libwebsocket *wsi, const char *file,
1440 const char *content_type)
1443 struct stat stat_buf;
1448 fd = open(file, O_RDONLY);
1450 p += sprintf(p, "HTTP/1.0 400 Bad\x0d\x0a"
1451 "Server: libwebsockets\x0d\x0a"
1454 libwebsocket_write(wsi, (unsigned char *)buf, p - buf,
1460 fstat(fd, &stat_buf);
1461 p += sprintf(p, "HTTP/1.0 200 OK\x0d\x0a"
1462 "Server: libwebsockets\x0d\x0a"
1463 "Content-Type: %s\x0d\x0a"
1464 "Content-Length: %u\x0d\x0a"
1465 "\x0d\x0a", content_type, (unsigned int)stat_buf.st_size);
1467 libwebsocket_write(wsi, (unsigned char *)buf, p - buf, LWS_WRITE_HTTP);
1471 n = read(fd, buf, 512);
1474 libwebsocket_write(wsi, (unsigned char *)buf, n,
1485 * libwebsockets_remaining_packet_payload() - Bytes to come before "overall"
1486 * rx packet is complete
1487 * @wsi: Websocket instance (available from user callback)
1489 * This function is intended to be called from the callback if the
1490 * user code is interested in "complete packets" from the client.
1491 * libwebsockets just passes through payload as it comes and issues a buffer
1492 * additionally when it hits a built-in limit. The LWS_CALLBACK_RECEIVE
1493 * callback handler can use this API to find out if the buffer it has just
1494 * been given is the last piece of a "complete packet" from the client --
1495 * when that is the case libwebsockets_remaining_packet_payload() will return
1498 * Many protocols won't care becuse their packets are always small.
1502 libwebsockets_remaining_packet_payload(struct libwebsocket *wsi)
1504 return wsi->rx_packet_length;