introduce-client-support.patch
[profile/ivi/libwebsockets.git] / lib / handshake.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010 Andy Green <andy@warmcat.com>
5  *
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.
10  *
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.
15  *
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,
19  *  MA  02110-1301  USA
20  */
21
22 #include "private-libwebsockets.h"
23
24
25 static int
26 interpret_key(const char *key, unsigned long *result)
27 {
28         char digits[20];
29         int digit_pos = 0;
30         const char *p = key;
31         unsigned int spaces = 0;
32         unsigned long acc = 0;
33         int rem = 0;
34
35         while (*p) {
36                 if (isdigit(*p)) {
37                         if (digit_pos == sizeof(digits) - 1)
38                                 return -1;
39                         digits[digit_pos++] = *p;
40                 }
41                 p++;
42         }
43         digits[digit_pos] = '\0';
44         if (!digit_pos)
45                 return -2;
46
47         while (*key) {
48                 if (*key == ' ')
49                         spaces++;
50                 key++;
51         }
52
53         if (!spaces)
54                 return -3;
55
56         p = &digits[0];
57         while (*p) {
58                 rem = (rem * 10) + ((*p++) - '0');
59                 acc = (acc * 10) + (rem / spaces);
60                 rem -= (rem / spaces) * spaces;
61         }
62
63         if (rem) {
64                 fprintf(stderr, "nonzero handshake remainder\n");
65                 return -1;
66         }
67
68         *result = acc;
69
70         return 0;
71 }
72
73
74 static int
75 handshake_00(struct libwebsocket *wsi)
76 {
77         unsigned long key1, key2;
78         unsigned char sum[16];
79         char *response;
80         char *p;
81         int n;
82
83         /* Confirm we have all the necessary pieces */
84
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 */
91                 goto bail;
92
93         /* allocate the per-connection user memory (if any) */
94
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");
101                         goto bail;
102                 }
103         } else
104                 wsi->user_space = NULL;
105
106         /* create the response packet */
107
108         /* make a buffer big enough for everything */
109
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);
117         if (!response) {
118                 fprintf(stderr, "Out of memory for response buffer\n");
119                 goto bail;
120         }
121
122         p = response;
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
134         if (use_ssl) {
135                 strcpy(p,   "\x0d\x0aSec-WebSocket-Location: wss://");
136                 p += strlen("\x0d\x0aSec-WebSocket-Location: wss://");
137         } else {
138 #endif
139                 strcpy(p,   "\x0d\x0aSec-WebSocket-Location: ws://");
140                 p += strlen("\x0d\x0aSec-WebSocket-Location: ws://");
141 #ifdef LWS_OPENSSL_SUPPORT
142         }
143 #endif
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;
148
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;
154         }
155
156         strcpy(p,   "\x0d\x0a\x0d\x0a");
157         p += strlen("\x0d\x0a\x0d\x0a");
158
159         /* convert the two keys into 32-bit integers */
160
161         if (interpret_key(wsi->utf8_token[WSI_TOKEN_KEY1].token, &key1))
162                 goto bail;
163         if (interpret_key(wsi->utf8_token[WSI_TOKEN_KEY2].token, &key2))
164                 goto bail;
165
166         /* lay them out in network byte order (MSB first */
167
168         sum[0] = key1 >> 24;
169         sum[1] = key1 >> 16;
170         sum[2] = key1 >> 8;
171         sum[3] = key1;
172         sum[4] = key2 >> 24;
173         sum[5] = key2 >> 16;
174         sum[6] = key2 >> 8;
175         sum[7] = key2;
176
177         /* follow them with the challenge token we were sent */
178
179         memcpy(&sum[8], wsi->utf8_token[WSI_TOKEN_CHALLENGE].token, 8);
180
181         /*
182          * compute the md5sum of that 16-byte series and use as our
183          * payload after our headers
184          */
185
186         MD5(sum, 16, (unsigned char *)p);
187         p += 16;
188
189         /* it's complete: go ahead and send it */
190
191         debug("issuing response packet %d len\n", (int)(p - response));
192 #ifdef DEBUG
193         fwrite(response, 1,  p - response, stderr);
194 #endif
195         n = libwebsocket_write(wsi, (unsigned char *)response,
196                                           p - response, LWS_WRITE_HTTP);
197         if (n < 0) {
198                 fprintf(stderr, "ERROR writing to socket");
199                 goto bail;
200         }
201
202         /* alright clean up and set ourselves into established state */
203
204         free(response);
205         wsi->state = WSI_STATE_ESTABLISHED;
206         wsi->lws_rx_parse_state = LWS_RXPS_NEW;
207
208         /* notify user code that we're ready to roll */
209
210         if (wsi->protocol->callback)
211                 wsi->protocol->callback(wsi, LWS_CALLBACK_ESTABLISHED,
212                                           wsi->user_space, NULL, 0);
213
214         return 0;
215
216 bail:
217         return -1;
218 }
219
220 /*
221  * Perform the newer BASE64-encoded handshake scheme
222  */
223
224 static int
225 handshake_04(struct libwebsocket *wsi)
226 {
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];
232         char nonce_buf[256];
233         char mask_summing_buf[256 + MAX_WEBSOCKET_04_KEY_LEN + 37];
234         unsigned char hash[20];
235         int n;
236         char *response;
237         char *p;
238         char *m = mask_summing_buf;
239         int fd;
240         int nonce_len;
241         int accept_len;
242
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 */
248                 goto bail;
249         }
250
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);
255                 goto bail;
256         }
257
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);
261
262         SHA1((unsigned char *)accept_buf,
263                         wsi->utf8_token[WSI_TOKEN_KEY].token_len +
264                                          strlen(websocket_magic_guid_04), hash);
265
266         accept_len = lws_b64_encode_string((char *)hash, 20, accept_buf,
267                                                              sizeof accept_buf);
268         if (accept_len < 0) {
269                 fprintf(stderr, "Base64 encoded hash too long\n");
270                 goto bail;
271         }
272
273         /* allocate the per-connection user memory (if any) */
274
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");
281                         goto bail;
282                 }
283         } else
284                 wsi->user_space = NULL;
285
286         /* create the response packet */
287
288         /* make a buffer big enough for everything */
289
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);
294         if (!response) {
295                 fprintf(stderr, "Out of memory for response buffer\n");
296                 goto bail;
297         }
298
299         p = response;
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);
309         p += accept_len;
310
311         strcpy(p,   "\x0d\x0aSec-WebSocket-Nonce: ");
312         p += strlen("\x0d\x0aSec-WebSocket-Nonce: ");
313
314         /* select the nonce */
315
316         fd = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
317         if (fd < 1) {
318                 fprintf(stderr, "Unable to open random device %s\n",
319                                                         SYSTEM_RANDOM_FILEPATH);
320                 if (wsi->user_space)
321                         free(wsi->user_space);
322                 goto bail;
323         }
324         n = read(fd, hash, 16);
325         if (n != 16) {
326                 fprintf(stderr, "Unable to read from random device %s %d\n",
327                                                      SYSTEM_RANDOM_FILEPATH, n);
328                 if (wsi->user_space)
329                         free(wsi->user_space);
330                 goto bail;
331         }
332         close(fd);
333
334         /* encode the nonce */
335
336         nonce_len = lws_b64_encode_string((const char *)hash, 16, nonce_buf,
337                                                               sizeof nonce_buf);
338         if (nonce_len < 0) {
339                 fprintf(stderr, "Failed to base 64 encode the nonce\n");
340                 if (wsi->user_space)
341                         free(wsi->user_space);
342                 goto bail;
343         }
344
345         /* apply the nonce */
346
347         strcpy(p, nonce_buf);
348         p += nonce_len;
349
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;
355         }
356
357         /* end of response packet */
358
359         strcpy(p,   "\x0d\x0a\x0d\x0a");
360         p += strlen("\x0d\x0a\x0d\x0a");
361
362         /*
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
366          * the 04 standard )
367          *
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).
371          */
372
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);
376         m += nonce_len;
377         strcpy(m, websocket_magic_guid_04_masking);
378         m += strlen(websocket_magic_guid_04_masking);
379         
380         SHA1((unsigned char *)mask_summing_buf, m - mask_summing_buf,
381                                                            wsi->masking_key_04);
382
383         /* okay send the handshake response accepting the connection */
384
385         debug("issuing response packet %d len\n", (int)(p - response));
386 #ifdef DEBUG
387         fwrite(response, 1,  p - response, stderr);
388 #endif
389         n = libwebsocket_write(wsi, (unsigned char *)response,
390                                           p - response, LWS_WRITE_HTTP);
391         if (n < 0) {
392                 fprintf(stderr, "ERROR writing to socket");
393                 goto bail;
394         }
395
396         /* alright clean up and set ourselves into established state */
397
398         free(response);
399         wsi->state = WSI_STATE_ESTABLISHED;
400         wsi->lws_rx_parse_state = LWS_RXPS_NEW;
401         wsi->rx_packet_length = 0;
402
403         /* notify user code that we're ready to roll */
404
405         if (wsi->protocol->callback)
406                 wsi->protocol->callback(wsi, LWS_CALLBACK_ESTABLISHED,
407                                           wsi->user_space, NULL, 0);
408
409         return 0;
410
411
412 bail:
413         return -1;
414 }
415
416
417 /*
418  * -04 of the protocol (actually the 80th version) has a radically different
419  * handshake.  The 04 spec gives the following idea
420  *
421  *    The handshake from the client looks as follows:
422  *
423  *      GET /chat HTTP/1.1
424  *      Host: server.example.com
425  *      Upgrade: websocket
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
431  *
432  *  The handshake from the server looks as follows:
433  *
434  *       HTTP/1.1 101 Switching Protocols
435  *       Upgrade: websocket
436  *       Connection: Upgrade
437  *       Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
438  *       Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
439  *       Sec-WebSocket-Protocol: chat
440  */
441
442 /*
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.
447  */
448
449 int
450 libwebsocket_read(struct libwebsocket *wsi, unsigned char * buf, size_t len)
451 {
452         size_t n;
453
454         switch (wsi->state) {
455         case WSI_STATE_HTTP:
456                 wsi->state = WSI_STATE_HTTP_HEADERS;
457                 wsi->parser_state = WSI_TOKEN_NAME_PART;
458                 /* fallthru */
459         case WSI_STATE_HTTP_HEADERS:
460
461                 debug("issuing %d bytes to parser\n", (int)len);
462 #ifdef DEBUG
463                 fwrite(buf, 1, len, stderr);
464 #endif
465
466                 if (wsi->client_mode) {
467                         for (n = 0; n < len; n++)
468                                 libwebsocket_client_rx_sm(wsi, *buf++);
469
470                         return 0;
471                 }
472
473                 for (n = 0; n < len; n++)
474                         libwebsocket_parse(wsi, *buf++);
475
476                 if (wsi->parser_state != WSI_PARSING_COMPLETE)
477                         break;
478
479                 debug("libwebsocket_parse sees parsing complete\n");
480
481                 /* is this websocket protocol or normal http 1.0? */
482
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;
490                         return 0;
491                 }
492
493                 /*
494                  * It's websocket
495                  *
496                  * Make sure user side is happy about protocol
497                  */
498
499                 while (wsi->protocol->callback) {
500
501                         if (wsi->utf8_token[WSI_TOKEN_PROTOCOL].token == NULL) {
502                                 if (wsi->protocol->name == NULL)
503                                         break;
504                         } else
505                                 if (strcmp(
506                                      wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
507                                                       wsi->protocol->name) == 0)
508                                         break;
509
510                         wsi->protocol++;
511                 }
512
513                 /* we didn't find a protocol he wanted? */
514
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");
519                         else
520                                 fprintf(stderr, "Requested protocol %s "
521                                                 "not supported\n",
522                                      wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
523                         goto bail;
524                 }
525
526                 /*
527                  * find out which spec version the client is using
528                  * if this header is not given, we default to 00 (aka 76)
529                  */
530
531                 if (wsi->utf8_token[WSI_TOKEN_VERSION].token_len)
532                         wsi->ietf_spec_revision =
533                                  atoi(wsi->utf8_token[WSI_TOKEN_VERSION].token);
534
535
536                 /*
537                  * Perform the handshake according to the protocol version the
538                  * client announced
539                  */
540
541                 switch (wsi->ietf_spec_revision) {
542                 case 0: /* applies to 76 and 00 */
543                         if (handshake_00(wsi))
544                                 goto bail;
545                         break;
546                 case 4: /* 04 */
547                         debug("libwebsocket_parse calling handshake_04\n");
548                         if (handshake_04(wsi))
549                                 goto bail;
550                         break;
551                 default:
552                         fprintf(stderr, "Unknown client spec version %d\n",
553                                                        wsi->ietf_spec_revision);
554                         goto bail;
555                 }
556
557                 break;
558
559         case WSI_STATE_ESTABLISHED:
560                 if (wsi->client_mode) {
561                         for (n = 0; n < len; n++)
562                                 libwebsocket_client_rx_sm(wsi, *buf++);
563
564                         return 0;
565                 }
566
567
568                 if (libwebsocket_interpret_incoming_packet(wsi, buf, len) < 0)
569                         goto bail;
570                 break;
571         default:
572                 break;
573         }
574
575         return 0;
576
577 bail:
578         libwebsocket_close_and_free_session(wsi);
579         return -1;
580 }