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"
26 interpret_key(const char *key, unsigned long *result)
31 unsigned int spaces = 0;
32 unsigned long acc = 0;
37 if (digit_pos == sizeof(digits) - 1)
39 digits[digit_pos++] = *p;
43 digits[digit_pos] = '\0';
58 rem = (rem * 10) + ((*p++) - '0');
59 acc = (acc * 10) + (rem / spaces);
60 rem -= (rem / spaces) * spaces;
64 fprintf(stderr, "nonzero handshake remainder\n");
75 handshake_00(struct libwebsocket_context *context, struct libwebsocket *wsi)
77 unsigned long key1, key2;
78 unsigned char sum[16];
83 /* Confirm we have all the necessary pieces */
85 if (!wsi->utf8_token[WSI_TOKEN_ORIGIN].token_len ||
86 !wsi->utf8_token[WSI_TOKEN_HOST].token_len ||
87 !wsi->utf8_token[WSI_TOKEN_CHALLENGE].token_len ||
88 !wsi->utf8_token[WSI_TOKEN_KEY1].token_len ||
89 !wsi->utf8_token[WSI_TOKEN_KEY2].token_len)
90 /* completed header processing, but missing some bits */
93 /* allocate the per-connection user memory (if any) */
94 if (wsi->protocol->per_session_data_size && !libwebsocket_ensure_user_space(wsi))
97 /* create the response packet */
99 /* make a buffer big enough for everything */
101 response = malloc(256 +
102 wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len +
103 wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len +
104 wsi->utf8_token[WSI_TOKEN_HOST].token_len +
105 wsi->utf8_token[WSI_TOKEN_ORIGIN].token_len +
106 wsi->utf8_token[WSI_TOKEN_GET_URI].token_len +
107 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len);
109 fprintf(stderr, "Out of memory for response buffer\n");
114 strcpy(p, "HTTP/1.1 101 WebSocket Protocol Handshake\x0d\x0a"
115 "Upgrade: WebSocket\x0d\x0a");
116 p += strlen("HTTP/1.1 101 WebSocket Protocol Handshake\x0d\x0a"
117 "Upgrade: WebSocket\x0d\x0a");
118 strcpy(p, "Connection: Upgrade\x0d\x0a"
119 "Sec-WebSocket-Origin: ");
120 p += strlen("Connection: Upgrade\x0d\x0a"
121 "Sec-WebSocket-Origin: ");
122 strcpy(p, wsi->utf8_token[WSI_TOKEN_ORIGIN].token);
123 p += wsi->utf8_token[WSI_TOKEN_ORIGIN].token_len;
124 #ifdef LWS_OPENSSL_SUPPORT
126 strcpy(p, "\x0d\x0aSec-WebSocket-Location: wss://");
127 p += strlen("\x0d\x0aSec-WebSocket-Location: wss://");
130 strcpy(p, "\x0d\x0aSec-WebSocket-Location: ws://");
131 p += strlen("\x0d\x0aSec-WebSocket-Location: ws://");
132 #ifdef LWS_OPENSSL_SUPPORT
135 strcpy(p, wsi->utf8_token[WSI_TOKEN_HOST].token);
136 p += wsi->utf8_token[WSI_TOKEN_HOST].token_len;
137 strcpy(p, wsi->utf8_token[WSI_TOKEN_GET_URI].token);
138 p += wsi->utf8_token[WSI_TOKEN_GET_URI].token_len;
140 if (wsi->utf8_token[WSI_TOKEN_PROTOCOL].token) {
141 strcpy(p, "\x0d\x0aSec-WebSocket-Protocol: ");
142 p += strlen("\x0d\x0aSec-WebSocket-Protocol: ");
143 strcpy(p, wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
144 p += wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len;
147 strcpy(p, "\x0d\x0a\x0d\x0a");
148 p += strlen("\x0d\x0a\x0d\x0a");
150 /* convert the two keys into 32-bit integers */
152 if (interpret_key(wsi->utf8_token[WSI_TOKEN_KEY1].token, &key1))
154 if (interpret_key(wsi->utf8_token[WSI_TOKEN_KEY2].token, &key2))
157 /* lay them out in network byte order (MSB first */
168 /* follow them with the challenge token we were sent */
170 memcpy(&sum[8], wsi->utf8_token[WSI_TOKEN_CHALLENGE].token, 8);
173 * compute the md5sum of that 16-byte series and use as our
174 * payload after our headers
177 MD5(sum, 16, (unsigned char *)p);
180 /* it's complete: go ahead and send it */
182 debug("issuing response packet %d len\n", (int)(p - response));
184 fwrite(response, 1, p - response, stderr);
186 n = libwebsocket_write(wsi, (unsigned char *)response,
187 p - response, LWS_WRITE_HTTP);
189 fprintf(stderr, "ERROR writing to socket");
193 /* alright clean up and set ourselves into established state */
196 wsi->state = WSI_STATE_ESTABLISHED;
197 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
199 /* notify user code that we're ready to roll */
201 if (wsi->protocol->callback)
202 wsi->protocol->callback(wsi->protocol->owning_server,
203 wsi, LWS_CALLBACK_ESTABLISHED,
204 wsi->user_space, NULL, 0);
213 * Perform the newer BASE64-encoded handshake scheme
217 handshake_0405(struct libwebsocket_context *context, struct libwebsocket *wsi)
219 static const char *websocket_magic_guid_04 =
220 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
221 static const char *websocket_magic_guid_04_masking =
222 "61AC5F19-FBBA-4540-B96F-6561F1AB40A8";
223 char accept_buf[MAX_WEBSOCKET_04_KEY_LEN + 37];
225 char mask_summing_buf[256 + MAX_WEBSOCKET_04_KEY_LEN + 37];
226 unsigned char hash[20];
230 char *m = mask_summing_buf;
235 struct libwebsocket_extension * ext;
239 if (!wsi->utf8_token[WSI_TOKEN_HOST].token_len ||
240 !wsi->utf8_token[WSI_TOKEN_KEY].token_len) {
241 debug("handshake_04 missing pieces\n");
242 /* completed header processing, but missing some bits */
246 if (wsi->utf8_token[WSI_TOKEN_KEY].token_len >=
247 MAX_WEBSOCKET_04_KEY_LEN) {
248 fprintf(stderr, "Client sent handshake key longer "
249 "than max supported %d\n", MAX_WEBSOCKET_04_KEY_LEN);
253 strcpy(accept_buf, wsi->utf8_token[WSI_TOKEN_KEY].token);
254 strcpy(accept_buf + wsi->utf8_token[WSI_TOKEN_KEY].token_len,
255 websocket_magic_guid_04);
257 SHA1((unsigned char *)accept_buf,
258 wsi->utf8_token[WSI_TOKEN_KEY].token_len +
259 strlen(websocket_magic_guid_04), hash);
261 accept_len = lws_b64_encode_string((char *)hash, 20, accept_buf,
263 if (accept_len < 0) {
264 fprintf(stderr, "Base64 encoded hash too long\n");
268 /* allocate the per-connection user memory (if any) */
269 if (wsi->protocol->per_session_data_size && !libwebsocket_ensure_user_space(wsi))
272 /* create the response packet */
274 /* make a buffer big enough for everything */
276 response = malloc(256 +
277 wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len +
278 wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len +
279 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len);
281 fprintf(stderr, "Out of memory for response buffer\n");
286 strcpy(p, "HTTP/1.1 101 Switching Protocols\x0d\x0a"
287 "Upgrade: WebSocket\x0d\x0a");
288 p += strlen("HTTP/1.1 101 Switching Protocols\x0d\x0a"
289 "Upgrade: WebSocket\x0d\x0a");
290 strcpy(p, "Connection: Upgrade\x0d\x0a"
291 "Sec-WebSocket-Accept: ");
292 p += strlen("Connection: Upgrade\x0d\x0a"
293 "Sec-WebSocket-Accept: ");
294 strcpy(p, accept_buf);
297 if (wsi->ietf_spec_revision == 4) {
298 strcpy(p, "\x0d\x0aSec-WebSocket-Nonce: ");
299 p += strlen("\x0d\x0aSec-WebSocket-Nonce: ");
301 /* select the nonce */
303 n = libwebsockets_get_random(wsi->protocol->owning_server,
306 fprintf(stderr, "Unable to read random device %s %d\n",
307 SYSTEM_RANDOM_FILEPATH, n);
309 free(wsi->user_space);
313 /* encode the nonce */
315 nonce_len = lws_b64_encode_string((const char *)hash, 16,
316 nonce_buf, sizeof nonce_buf);
318 fprintf(stderr, "Failed to base 64 encode the nonce\n");
320 free(wsi->user_space);
324 /* apply the nonce */
326 strcpy(p, nonce_buf);
330 if (wsi->utf8_token[WSI_TOKEN_PROTOCOL].token) {
331 strcpy(p, "\x0d\x0aSec-WebSocket-Protocol: ");
332 p += strlen("\x0d\x0aSec-WebSocket-Protocol: ");
333 strcpy(p, wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
334 p += wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len;
338 * Figure out which extensions the client has that we want to
339 * enable on this connection, and give him back the list
342 if (wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token_len) {
345 * break down the list of client extensions
346 * and go through them
349 c = wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token;
350 debug("wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token = %s\n", wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token);
351 wsi->count_active_extensions = 0;
355 if (*c && (*c != ',' && *c != ' ' && *c != '\t')) {
357 if (n < sizeof(ext_name) - 1)
370 /* check a client's extension against our support */
372 ext = wsi->protocol->owning_server->extensions;
374 while (ext && ext->callback) {
376 if (strcmp(ext_name, ext->name)) {
382 * oh, we do support this one he
383 * asked for... but let's ask user
384 * code if it's OK to apply it on this
385 * particular connection + protocol
388 n = wsi->protocol->owning_server->
389 protocols[0].callback(
390 wsi->protocol->owning_server,
392 LWS_CALLBACK_CONFIRM_EXTENSION_OKAY,
393 wsi->user_space, ext_name, 0);
396 * zero return from callback means
397 * go ahead and allow the extension,
398 * it's what we get if the callback is
412 strcpy(p, "\x0d\x0aSec-WebSocket-Extensions: ");
413 p += strlen("\x0d\x0aSec-WebSocket-Extensions: ");
415 p += sprintf(p, "%s", ext_name);
418 /* instantiate the extension on this conn */
420 wsi->active_extensions_user[
421 wsi->count_active_extensions] =
422 malloc(ext->per_session_data_size);
423 memset(wsi->active_extensions_user[
424 wsi->count_active_extensions], 0,
425 ext->per_session_data_size);
427 wsi->active_extensions[
428 wsi->count_active_extensions] = ext;
430 /* allow him to construct his context */
432 ext->callback(wsi->protocol->owning_server,
434 LWS_EXT_CALLBACK_CONSTRUCT,
435 wsi->active_extensions_user[
436 wsi->count_active_extensions], NULL, 0);
438 wsi->count_active_extensions++;
439 debug("wsi->count_active_extensions <- %d",
440 wsi->count_active_extensions);
449 /* end of response packet */
451 strcpy(p, "\x0d\x0a\x0d\x0a");
452 p += strlen("\x0d\x0a\x0d\x0a");
454 if (wsi->ietf_spec_revision == 4) {
457 * precompute the masking key the client will use from the SHA1
458 * hash of ( base 64 client key we were sent, concatenated with
459 * the bse 64 nonce we sent, concatenated with a magic constant
460 * guid specified by the 04 standard )
462 * We store the hash in the connection's wsi ready to use with
463 * undoing the masking the client has done on framed data it
464 * sends (we send our data to the client in clear).
467 strcpy(mask_summing_buf, wsi->utf8_token[WSI_TOKEN_KEY].token);
468 m += wsi->utf8_token[WSI_TOKEN_KEY].token_len;
469 strcpy(m, nonce_buf);
471 strcpy(m, websocket_magic_guid_04_masking);
472 m += strlen(websocket_magic_guid_04_masking);
474 SHA1((unsigned char *)mask_summing_buf, m - mask_summing_buf,
475 wsi->masking_key_04);
478 if (!lws_any_extension_handled(context, wsi,
479 LWS_EXT_CALLBACK_HANDSHAKE_REPLY_TX,
480 response, p - response)) {
482 /* okay send the handshake response accepting the connection */
484 debug("issuing response packet %d len\n", (int)(p - response));
486 fwrite(response, 1, p - response, stderr);
488 n = libwebsocket_write(wsi, (unsigned char *)response,
489 p - response, LWS_WRITE_HTTP);
491 fprintf(stderr, "ERROR writing to socket");
497 /* alright clean up and set ourselves into established state */
500 wsi->state = WSI_STATE_ESTABLISHED;
501 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
502 wsi->rx_packet_length = 0;
504 /* notify user code that we're ready to roll */
506 if (wsi->protocol->callback)
507 wsi->protocol->callback(wsi->protocol->owning_server,
508 wsi, LWS_CALLBACK_ESTABLISHED,
509 wsi->user_space, NULL, 0);
520 * -04 of the protocol (actually the 80th version) has a radically different
521 * handshake. The 04 spec gives the following idea
523 * The handshake from the client looks as follows:
526 * Host: server.example.com
528 * Connection: Upgrade
529 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
530 * Sec-WebSocket-Origin: http://example.com
531 * Sec-WebSocket-Protocol: chat, superchat
532 * Sec-WebSocket-Version: 4
534 * The handshake from the server looks as follows:
536 * HTTP/1.1 101 Switching Protocols
538 * Connection: Upgrade
539 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
540 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
541 * Sec-WebSocket-Protocol: chat
545 * We have to take care about parsing because the headers may be split
546 * into multiple fragments. They may contain unknown headers with arbitrary
547 * argument lengths. So, we parse using a single-character at a time state
548 * machine that is completely independent of packet size.
552 libwebsocket_read(struct libwebsocket_context *context, struct libwebsocket *wsi,
553 unsigned char * buf, size_t len)
557 switch (wsi->state) {
559 wsi->state = WSI_STATE_HTTP_HEADERS;
560 wsi->parser_state = WSI_TOKEN_NAME_PART;
562 case WSI_STATE_HTTP_HEADERS:
564 debug("issuing %d bytes to parser\n", (int)len);
566 fwrite(buf, 1, len, stderr);
570 case LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY:
571 case LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE:
572 case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
573 case LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT:
574 case LWS_CONNMODE_WS_CLIENT:
575 for (n = 0; n < len; n++)
576 libwebsocket_client_rx_sm(wsi, *buf++);
583 /* LWS_CONNMODE_WS_SERVING */
585 for (n = 0; n < len; n++)
586 libwebsocket_parse(wsi, *buf++);
588 if (wsi->parser_state != WSI_PARSING_COMPLETE)
591 debug("seem to be serving, mode is %d\n", wsi->mode);
593 debug("libwebsocket_parse sees parsing complete\n");
595 /* is this websocket protocol or normal http 1.0? */
597 if (!wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
598 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len) {
599 if (wsi->protocol->callback)
600 (wsi->protocol->callback)(context, wsi,
601 LWS_CALLBACK_HTTP, wsi->user_space,
602 wsi->utf8_token[WSI_TOKEN_GET_URI].token, 0);
603 wsi->state = WSI_STATE_HTTP;
608 fprintf(stderr, "NULL protocol coming on libwebsocket_read\n");
613 * Make sure user side is happy about protocol
616 while (wsi->protocol->callback) {
618 if (wsi->utf8_token[WSI_TOKEN_PROTOCOL].token == NULL) {
619 if (wsi->protocol->name == NULL)
623 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
624 wsi->protocol->name) == 0)
630 /* we didn't find a protocol he wanted? */
632 if (wsi->protocol->callback == NULL) {
633 if (wsi->utf8_token[WSI_TOKEN_PROTOCOL].token == NULL)
634 fprintf(stderr, "[no protocol] "
635 "not supported (use NULL .name)\n");
637 fprintf(stderr, "Requested protocol %s "
639 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
644 * find out which spec version the client is using
645 * if this header is not given, we default to 00 (aka 76)
648 if (wsi->utf8_token[WSI_TOKEN_VERSION].token_len)
649 wsi->ietf_spec_revision =
650 atoi(wsi->utf8_token[WSI_TOKEN_VERSION].token);
653 * Give the user code a chance to study the request and
654 * have the opportunity to deny it
657 if ((wsi->protocol->callback)(wsi->protocol->owning_server, wsi,
658 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
659 &wsi->utf8_token[0], NULL, 0)) {
660 fprintf(stderr, "User code denied connection\n");
666 * Perform the handshake according to the protocol version the
670 switch (wsi->ietf_spec_revision) {
671 case 0: /* applies to 76 and 00 */
672 wsi->xor_mask = xor_no_mask;
673 if (handshake_00(context, wsi))
677 wsi->xor_mask = xor_mask_04;
678 debug("libwebsocket_parse calling handshake_04\n");
679 if (handshake_0405(context, wsi))
687 wsi->xor_mask = xor_mask_05;
688 debug("libwebsocket_parse calling handshake_04\n");
689 if (handshake_0405(context, wsi))
694 fprintf(stderr, "Unknown client spec version %d\n",
695 wsi->ietf_spec_revision);
699 debug("accepted v%02d connection\n",
700 wsi->ietf_spec_revision);
704 case WSI_STATE_AWAITING_CLOSE_ACK:
705 case WSI_STATE_ESTABLISHED:
707 case LWS_CONNMODE_WS_CLIENT:
708 for (n = 0; n < len; n++)
709 if (libwebsocket_client_rx_sm(wsi, *buf++) < 0)
717 /* LWS_CONNMODE_WS_SERVING */
719 if (libwebsocket_interpret_incoming_packet(wsi, buf, len) < 0)
730 libwebsocket_close_and_free_session(context, wsi,
731 LWS_CLOSE_STATUS_NOSTATUS);