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_04(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_KEY].token_len >=
252 MAX_WEBSOCKET_04_KEY_LEN) {
253 fprintf(stderr, "Client sent handshake key longer "
254 "than max supported %d\n", MAX_WEBSOCKET_04_KEY_LEN);
258 strcpy(accept_buf, wsi->utf8_token[WSI_TOKEN_KEY].token);
259 strcpy(accept_buf + wsi->utf8_token[WSI_TOKEN_KEY].token_len,
260 websocket_magic_guid_04);
262 SHA1((unsigned char *)accept_buf,
263 wsi->utf8_token[WSI_TOKEN_KEY].token_len +
264 strlen(websocket_magic_guid_04), hash);
266 accept_len = lws_b64_encode_string((char *)hash, 20, accept_buf,
268 if (accept_len < 0) {
269 fprintf(stderr, "Base64 encoded hash too long\n");
273 /* allocate the per-connection user memory (if any) */
275 if (wsi->protocol->per_session_data_size) {
276 wsi->user_space = malloc(
277 wsi->protocol->per_session_data_size);
278 if (wsi->user_space == NULL) {
279 fprintf(stderr, "Out of memory for "
280 "conn user space\n");
284 wsi->user_space = NULL;
286 /* create the response packet */
288 /* make a buffer big enough for everything */
290 response = malloc(256 +
291 wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len +
292 wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len +
293 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len);
295 fprintf(stderr, "Out of memory for response buffer\n");
300 strcpy(p, "HTTP/1.1 101 Switching Protocols\x0d\x0a"
301 "Upgrade: WebSocket\x0d\x0a");
302 p += strlen("HTTP/1.1 101 Switching Protocols\x0d\x0a"
303 "Upgrade: WebSocket\x0d\x0a");
304 strcpy(p, "Connection: Upgrade\x0d\x0a"
305 "Sec-WebSocket-Accept: ");
306 p += strlen("Connection: Upgrade\x0d\x0a"
307 "Sec-WebSocket-Accept: ");
308 strcpy(p, accept_buf);
311 strcpy(p, "\x0d\x0aSec-WebSocket-Nonce: ");
312 p += strlen("\x0d\x0aSec-WebSocket-Nonce: ");
314 /* select the nonce */
316 fd = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
318 fprintf(stderr, "Unable to open random device %s\n",
319 SYSTEM_RANDOM_FILEPATH);
321 free(wsi->user_space);
324 n = read(fd, hash, 16);
326 fprintf(stderr, "Unable to read from random device %s %d\n",
327 SYSTEM_RANDOM_FILEPATH, n);
329 free(wsi->user_space);
334 /* encode the nonce */
336 nonce_len = lws_b64_encode_string((const char *)hash, 16, nonce_buf,
339 fprintf(stderr, "Failed to base 64 encode the nonce\n");
341 free(wsi->user_space);
345 /* apply the nonce */
347 strcpy(p, nonce_buf);
350 if (wsi->utf8_token[WSI_TOKEN_PROTOCOL].token) {
351 strcpy(p, "\x0d\x0aSec-WebSocket-Protocol: ");
352 p += strlen("\x0d\x0aSec-WebSocket-Protocol: ");
353 strcpy(p, wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
354 p += wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len;
357 /* end of response packet */
359 strcpy(p, "\x0d\x0a\x0d\x0a");
360 p += strlen("\x0d\x0a\x0d\x0a");
363 * precompute the masking key the client will use from the SHA1 hash of
364 * ( base 64 client key we were sent, concatenated with the base 64
365 * nonce we sent, concatenated with a magic constant guid specified by
368 * We store the hash in the connection's wsi ready to use with
369 * undoing the masking the client has done on framed data it sends
370 * (we send our data to the client in clear).
373 strcpy(mask_summing_buf, wsi->utf8_token[WSI_TOKEN_KEY].token);
374 m += wsi->utf8_token[WSI_TOKEN_KEY].token_len;
375 strcpy(m, nonce_buf);
377 strcpy(m, websocket_magic_guid_04_masking);
378 m += strlen(websocket_magic_guid_04_masking);
380 SHA1((unsigned char *)mask_summing_buf, m - mask_summing_buf,
381 wsi->masking_key_04);
383 /* okay send the handshake response accepting the connection */
385 debug("issuing response packet %d len\n", (int)(p - response));
387 fwrite(response, 1, p - response, stderr);
389 n = libwebsocket_write(wsi, (unsigned char *)response,
390 p - response, LWS_WRITE_HTTP);
392 fprintf(stderr, "ERROR writing to socket");
396 /* alright clean up and set ourselves into established state */
399 wsi->state = WSI_STATE_ESTABLISHED;
400 wsi->lws_rx_parse_state = LWS_RXPS_NEW;
401 wsi->rx_packet_length = 0;
403 /* notify user code that we're ready to roll */
405 if (wsi->protocol->callback)
406 wsi->protocol->callback(wsi, LWS_CALLBACK_ESTABLISHED,
407 wsi->user_space, NULL, 0);
418 * -04 of the protocol (actually the 80th version) has a radically different
419 * handshake. The 04 spec gives the following idea
421 * The handshake from the client looks as follows:
424 * Host: server.example.com
426 * Connection: Upgrade
427 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
428 * Sec-WebSocket-Origin: http://example.com
429 * Sec-WebSocket-Protocol: chat, superchat
430 * Sec-WebSocket-Version: 4
432 * The handshake from the server looks as follows:
434 * HTTP/1.1 101 Switching Protocols
436 * Connection: Upgrade
437 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
438 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
439 * Sec-WebSocket-Protocol: chat
443 * We have to take care about parsing because the headers may be split
444 * into multiple fragments. They may contain unknown headers with arbitrary
445 * argument lengths. So, we parse using a single-character at a time state
446 * machine that is completely independent of packet size.
450 libwebsocket_read(struct libwebsocket *wsi, unsigned char * buf, size_t len)
454 switch (wsi->state) {
456 wsi->state = WSI_STATE_HTTP_HEADERS;
457 wsi->parser_state = WSI_TOKEN_NAME_PART;
459 case WSI_STATE_HTTP_HEADERS:
461 debug("issuing %d bytes to parser\n", (int)len);
463 fwrite(buf, 1, len, stderr);
466 if (wsi->client_mode) {
467 for (n = 0; n < len; n++)
468 libwebsocket_client_rx_sm(wsi, *buf++);
473 for (n = 0; n < len; n++)
474 libwebsocket_parse(wsi, *buf++);
476 if (wsi->parser_state != WSI_PARSING_COMPLETE)
479 debug("libwebsocket_parse sees parsing complete\n");
481 /* is this websocket protocol or normal http 1.0? */
483 if (!wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
484 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len) {
485 if (wsi->protocol->callback)
486 (wsi->protocol->callback)(wsi,
487 LWS_CALLBACK_HTTP, wsi->user_space,
488 wsi->utf8_token[WSI_TOKEN_GET_URI].token, 0);
489 wsi->state = WSI_STATE_HTTP;
496 * Make sure user side is happy about protocol
499 while (wsi->protocol->callback) {
501 if (wsi->utf8_token[WSI_TOKEN_PROTOCOL].token == NULL) {
502 if (wsi->protocol->name == NULL)
506 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
507 wsi->protocol->name) == 0)
513 /* we didn't find a protocol he wanted? */
515 if (wsi->protocol->callback == NULL) {
516 if (wsi->utf8_token[WSI_TOKEN_PROTOCOL].token == NULL)
517 fprintf(stderr, "[no protocol] "
518 "not supported (use NULL .name)\n");
520 fprintf(stderr, "Requested protocol %s "
522 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
527 * find out which spec version the client is using
528 * if this header is not given, we default to 00 (aka 76)
531 if (wsi->utf8_token[WSI_TOKEN_VERSION].token_len)
532 wsi->ietf_spec_revision =
533 atoi(wsi->utf8_token[WSI_TOKEN_VERSION].token);
537 * Perform the handshake according to the protocol version the
541 switch (wsi->ietf_spec_revision) {
542 case 0: /* applies to 76 and 00 */
543 if (handshake_00(wsi))
547 debug("libwebsocket_parse calling handshake_04\n");
548 if (handshake_04(wsi))
552 fprintf(stderr, "Unknown client spec version %d\n",
553 wsi->ietf_spec_revision);
559 case WSI_STATE_ESTABLISHED:
560 if (wsi->client_mode) {
561 for (n = 0; n < len; n++)
562 libwebsocket_client_rx_sm(wsi, *buf++);
568 if (libwebsocket_interpret_incoming_packet(wsi, buf, len) < 0)
578 libwebsocket_close_and_free_session(wsi);