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 *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) */
95 if (wsi->protocol->per_session_data_size) {
96 wsi->user_space = malloc(
97 wsi->protocol->per_session_data_size);
98 if (wsi->user_space == NULL) {
99 fprintf(stderr, "Out of memory for "
100 "conn user space\n");
104 wsi->user_space = NULL;
106 /* create the response packet */
108 /* make a buffer big enough for everything */
110 response = malloc(256 +
111 wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len +
112 wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len +
113 wsi->utf8_token[WSI_TOKEN_HOST].token_len +
114 wsi->utf8_token[WSI_TOKEN_ORIGIN].token_len +
115 wsi->utf8_token[WSI_TOKEN_GET_URI].token_len +
116 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len);
118 fprintf(stderr, "Out of memory for response buffer\n");
123 strcpy(p, "HTTP/1.1 101 WebSocket Protocol Handshake\x0d\x0a"
124 "Upgrade: WebSocket\x0d\x0a");
125 p += strlen("HTTP/1.1 101 WebSocket Protocol Handshake\x0d\x0a"
126 "Upgrade: WebSocket\x0d\x0a");
127 strcpy(p, "Connection: Upgrade\x0d\x0a"
128 "Sec-WebSocket-Origin: ");
129 p += strlen("Connection: Upgrade\x0d\x0a"
130 "Sec-WebSocket-Origin: ");
131 strcpy(p, wsi->utf8_token[WSI_TOKEN_ORIGIN].token);
132 p += wsi->utf8_token[WSI_TOKEN_ORIGIN].token_len;
133 #ifdef LWS_OPENSSL_SUPPORT
135 strcpy(p, "\x0d\x0aSec-WebSocket-Location: wss://");
136 p += strlen("\x0d\x0aSec-WebSocket-Location: wss://");
139 strcpy(p, "\x0d\x0aSec-WebSocket-Location: ws://");
140 p += strlen("\x0d\x0aSec-WebSocket-Location: ws://");
141 #ifdef LWS_OPENSSL_SUPPORT
144 strcpy(p, wsi->utf8_token[WSI_TOKEN_HOST].token);
145 p += wsi->utf8_token[WSI_TOKEN_HOST].token_len;
146 strcpy(p, wsi->utf8_token[WSI_TOKEN_GET_URI].token);
147 p += wsi->utf8_token[WSI_TOKEN_GET_URI].token_len;
149 if (wsi->utf8_token[WSI_TOKEN_PROTOCOL].token) {
150 strcpy(p, "\x0d\x0aSec-WebSocket-Protocol: ");
151 p += strlen("\x0d\x0aSec-WebSocket-Protocol: ");
152 strcpy(p, wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
153 p += wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len;
156 strcpy(p, "\x0d\x0a\x0d\x0a");
157 p += strlen("\x0d\x0a\x0d\x0a");
159 /* convert the two keys into 32-bit integers */
161 if (interpret_key(wsi->utf8_token[WSI_TOKEN_KEY1].token, &key1))
163 if (interpret_key(wsi->utf8_token[WSI_TOKEN_KEY2].token, &key2))
166 /* lay them out in network byte order (MSB first */
177 /* follow them with the challenge token we were sent */
179 memcpy(&sum[8], wsi->utf8_token[WSI_TOKEN_CHALLENGE].token, 8);
182 * compute the md5sum of that 16-byte series and use as our
183 * payload after our headers
186 MD5(sum, 16, (unsigned char *)p);
189 /* it's complete: go ahead and send it */
191 debug("issuing response packet %d len\n", (int)(p - response));
193 fwrite(response, 1, p - response, stderr);
195 n = libwebsocket_write(wsi, (unsigned char *)response,
196 p - response, LWS_WRITE_HTTP);
198 fprintf(stderr, "ERROR writing to socket");
202 /* alright clean up and set ourselves into established state */
205 wsi->state = WSI_STATE_ESTABLISHED;
206 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
208 /* notify user code that we're ready to roll */
210 if (wsi->protocol->callback)
211 wsi->protocol->callback(wsi, LWS_CALLBACK_ESTABLISHED,
212 wsi->user_space, NULL, 0);
221 * Perform the newer BASE64-encoded handshake scheme
225 handshake_0405(struct libwebsocket *wsi)
227 static const char *websocket_magic_guid_04 =
228 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
229 static const char *websocket_magic_guid_04_masking =
230 "61AC5F19-FBBA-4540-B96F-6561F1AB40A8";
231 char accept_buf[MAX_WEBSOCKET_04_KEY_LEN + 37];
233 char mask_summing_buf[256 + MAX_WEBSOCKET_04_KEY_LEN + 37];
234 unsigned char hash[20];
238 char *m = mask_summing_buf;
243 if (!wsi->utf8_token[WSI_TOKEN_SWORIGIN].token_len ||
244 !wsi->utf8_token[WSI_TOKEN_HOST].token_len ||
245 !wsi->utf8_token[WSI_TOKEN_KEY].token_len) {
246 debug("handshake_04 missing pieces\n");
247 /* completed header processing, but missing some bits */
251 if (wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token_len) {
252 fprintf(stderr, "extensions not supported\n");
256 if (wsi->utf8_token[WSI_TOKEN_KEY].token_len >=
257 MAX_WEBSOCKET_04_KEY_LEN) {
258 fprintf(stderr, "Client sent handshake key longer "
259 "than max supported %d\n", MAX_WEBSOCKET_04_KEY_LEN);
263 strcpy(accept_buf, wsi->utf8_token[WSI_TOKEN_KEY].token);
264 strcpy(accept_buf + wsi->utf8_token[WSI_TOKEN_KEY].token_len,
265 websocket_magic_guid_04);
267 SHA1((unsigned char *)accept_buf,
268 wsi->utf8_token[WSI_TOKEN_KEY].token_len +
269 strlen(websocket_magic_guid_04), hash);
271 accept_len = lws_b64_encode_string((char *)hash, 20, accept_buf,
273 if (accept_len < 0) {
274 fprintf(stderr, "Base64 encoded hash too long\n");
278 /* allocate the per-connection user memory (if any) */
280 if (wsi->protocol->per_session_data_size) {
281 wsi->user_space = malloc(
282 wsi->protocol->per_session_data_size);
283 if (wsi->user_space == NULL) {
284 fprintf(stderr, "Out of memory for "
285 "conn user space\n");
289 wsi->user_space = NULL;
291 /* create the response packet */
293 /* make a buffer big enough for everything */
295 response = malloc(256 +
296 wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len +
297 wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len +
298 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len);
300 fprintf(stderr, "Out of memory for response buffer\n");
305 strcpy(p, "HTTP/1.1 101 Switching Protocols\x0d\x0a"
306 "Upgrade: WebSocket\x0d\x0a");
307 p += strlen("HTTP/1.1 101 Switching Protocols\x0d\x0a"
308 "Upgrade: WebSocket\x0d\x0a");
309 strcpy(p, "Connection: Upgrade\x0d\x0a"
310 "Sec-WebSocket-Accept: ");
311 p += strlen("Connection: Upgrade\x0d\x0a"
312 "Sec-WebSocket-Accept: ");
313 strcpy(p, accept_buf);
316 strcpy(p, "\x0d\x0aSec-WebSocket-Nonce: ");
317 p += strlen("\x0d\x0aSec-WebSocket-Nonce: ");
319 /* select the nonce */
321 fd = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
323 fprintf(stderr, "Unable to open random device %s\n",
324 SYSTEM_RANDOM_FILEPATH);
326 free(wsi->user_space);
329 n = read(fd, hash, 16);
331 fprintf(stderr, "Unable to read from random device %s %d\n",
332 SYSTEM_RANDOM_FILEPATH, n);
334 free(wsi->user_space);
339 /* encode the nonce */
341 nonce_len = lws_b64_encode_string((const char *)hash, 16, nonce_buf,
344 fprintf(stderr, "Failed to base 64 encode the nonce\n");
346 free(wsi->user_space);
350 /* apply the nonce */
352 strcpy(p, nonce_buf);
355 if (wsi->utf8_token[WSI_TOKEN_PROTOCOL].token) {
356 strcpy(p, "\x0d\x0aSec-WebSocket-Protocol: ");
357 p += strlen("\x0d\x0aSec-WebSocket-Protocol: ");
358 strcpy(p, wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
359 p += wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len;
362 /* end of response packet */
364 strcpy(p, "\x0d\x0a\x0d\x0a");
365 p += strlen("\x0d\x0a\x0d\x0a");
368 * precompute the masking key the client will use from the SHA1 hash of
369 * ( base 64 client key we were sent, concatenated with the base 64
370 * nonce we sent, concatenated with a magic constant guid specified by
373 * We store the hash in the connection's wsi ready to use with
374 * undoing the masking the client has done on framed data it sends
375 * (we send our data to the client in clear).
378 strcpy(mask_summing_buf, wsi->utf8_token[WSI_TOKEN_KEY].token);
379 m += wsi->utf8_token[WSI_TOKEN_KEY].token_len;
380 strcpy(m, nonce_buf);
382 strcpy(m, websocket_magic_guid_04_masking);
383 m += strlen(websocket_magic_guid_04_masking);
385 SHA1((unsigned char *)mask_summing_buf, m - mask_summing_buf,
386 wsi->masking_key_04);
388 /* okay send the handshake response accepting the connection */
390 debug("issuing response packet %d len\n", (int)(p - response));
392 fwrite(response, 1, p - response, stderr);
394 n = libwebsocket_write(wsi, (unsigned char *)response,
395 p - response, LWS_WRITE_HTTP);
397 fprintf(stderr, "ERROR writing to socket");
401 /* alright clean up and set ourselves into established state */
404 wsi->state = WSI_STATE_ESTABLISHED;
405 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
406 wsi->rx_packet_length = 0;
408 /* notify user code that we're ready to roll */
410 if (wsi->protocol->callback)
411 wsi->protocol->callback(wsi, LWS_CALLBACK_ESTABLISHED,
412 wsi->user_space, NULL, 0);
423 * -04 of the protocol (actually the 80th version) has a radically different
424 * handshake. The 04 spec gives the following idea
426 * The handshake from the client looks as follows:
429 * Host: server.example.com
431 * Connection: Upgrade
432 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
433 * Sec-WebSocket-Origin: http://example.com
434 * Sec-WebSocket-Protocol: chat, superchat
435 * Sec-WebSocket-Version: 4
437 * The handshake from the server looks as follows:
439 * HTTP/1.1 101 Switching Protocols
441 * Connection: Upgrade
442 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
443 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
444 * Sec-WebSocket-Protocol: chat
448 * We have to take care about parsing because the headers may be split
449 * into multiple fragments. They may contain unknown headers with arbitrary
450 * argument lengths. So, we parse using a single-character at a time state
451 * machine that is completely independent of packet size.
455 libwebsocket_read(struct libwebsocket *wsi, unsigned char * buf, size_t len)
459 switch (wsi->state) {
461 wsi->state = WSI_STATE_HTTP_HEADERS;
462 wsi->parser_state = WSI_TOKEN_NAME_PART;
464 case WSI_STATE_HTTP_HEADERS:
466 debug("issuing %d bytes to parser\n", (int)len);
468 fwrite(buf, 1, len, stderr);
472 case LWS_CONNMODE_WS_CLIENT:
473 for (n = 0; n < len; n++)
474 libwebsocket_client_rx_sm(wsi, *buf++);
481 /* LWS_CONNMODE_WS_SERVING */
483 for (n = 0; n < len; n++)
484 libwebsocket_parse(wsi, *buf++);
486 if (wsi->parser_state != WSI_PARSING_COMPLETE)
489 debug("libwebsocket_parse sees parsing complete\n");
491 /* is this websocket protocol or normal http 1.0? */
493 if (!wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
494 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len) {
495 if (wsi->protocol->callback)
496 (wsi->protocol->callback)(wsi,
497 LWS_CALLBACK_HTTP, wsi->user_space,
498 wsi->utf8_token[WSI_TOKEN_GET_URI].token, 0);
499 wsi->state = WSI_STATE_HTTP;
506 * Make sure user side is happy about protocol
509 while (wsi->protocol->callback) {
511 if (wsi->utf8_token[WSI_TOKEN_PROTOCOL].token == NULL) {
512 if (wsi->protocol->name == NULL)
516 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
517 wsi->protocol->name) == 0)
523 /* we didn't find a protocol he wanted? */
525 if (wsi->protocol->callback == NULL) {
526 if (wsi->utf8_token[WSI_TOKEN_PROTOCOL].token == NULL)
527 fprintf(stderr, "[no protocol] "
528 "not supported (use NULL .name)\n");
530 fprintf(stderr, "Requested protocol %s "
532 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
537 * find out which spec version the client is using
538 * if this header is not given, we default to 00 (aka 76)
541 if (wsi->utf8_token[WSI_TOKEN_VERSION].token_len)
542 wsi->ietf_spec_revision =
543 atoi(wsi->utf8_token[WSI_TOKEN_VERSION].token);
546 * Perform the handshake according to the protocol version the
550 switch (wsi->ietf_spec_revision) {
551 case 0: /* applies to 76 and 00 */
552 wsi->xor_mask = xor_no_mask;
553 if (handshake_00(wsi))
557 wsi->xor_mask = xor_mask_04;
558 debug("libwebsocket_parse calling handshake_04\n");
559 if (handshake_0405(wsi))
563 wsi->xor_mask = xor_mask_05;
564 debug("libwebsocket_parse calling handshake_04\n");
565 if (handshake_0405(wsi))
570 fprintf(stderr, "Unknown client spec version %d\n",
571 wsi->ietf_spec_revision);
575 fprintf(stderr, "accepted v%02d connection\n",
576 wsi->ietf_spec_revision);
580 case WSI_STATE_ESTABLISHED:
582 case LWS_CONNMODE_WS_CLIENT:
583 for (n = 0; n < len; n++)
584 libwebsocket_client_rx_sm(wsi, *buf++);
591 /* LWS_CONNMODE_WS_SERVING */
593 if (libwebsocket_interpret_incoming_packet(wsi, buf, len) < 0)
604 libwebsocket_close_and_free_session(wsi);