roubustness handle problems in read loop better
[profile/ivi/libwebsockets.git] / lib / client.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2013 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 #ifdef WIN32
25 #include <tchar.h>
26 #include <io.h>
27 #else
28 #ifdef LWS_BUILTIN_GETIFADDRS
29 #include <getifaddrs.h>
30 #else
31 #include <ifaddrs.h>
32 #endif
33 #include <sys/un.h>
34 #include <sys/socket.h>
35 #include <netdb.h>
36 #endif
37
38 #ifdef LWS_OPENSSL_SUPPORT
39 extern int openssl_websocket_private_data_index;
40 #endif                            
41
42 int lws_client_socket_service(struct libwebsocket_context *context, struct libwebsocket *wsi, struct pollfd *pollfd)
43 {
44         int n;
45         char pkt[1024];
46         char *p = &pkt[0];
47         int len;
48         char c;
49 #ifdef LWS_OPENSSL_SUPPORT
50         char ssl_err_buf[512];
51 #endif
52
53         switch (wsi->mode) {
54
55         case LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY:
56
57                 /* handle proxy hung up on us */
58
59                 if (pollfd->revents & (POLLERR | POLLHUP)) {
60
61                         lwsl_warn("Proxy connection %p (fd=%d) dead\n",
62                                 (void *)wsi, pollfd->fd);
63
64                         libwebsocket_close_and_free_session(context, wsi,
65                                                      LWS_CLOSE_STATUS_NOSTATUS);
66                         return 0;
67                 }
68
69                 n = recv(wsi->sock, pkt, sizeof pkt, 0);
70                 if (n < 0) {
71                         libwebsocket_close_and_free_session(context, wsi,
72                                                      LWS_CLOSE_STATUS_NOSTATUS);
73                         lwsl_err("ERROR reading from proxy socket\n");
74                         return 0;
75                 }
76
77                 pkt[13] = '\0';
78                 if (strcmp(pkt, "HTTP/1.0 200 ") != 0) {
79                         libwebsocket_close_and_free_session(context, wsi,
80                                                      LWS_CLOSE_STATUS_NOSTATUS);
81                         lwsl_err("ERROR from proxy: %s\n", pkt);
82                         return 0;
83                 }
84
85                 /* clear his proxy connection timeout */
86
87                 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
88
89                 /* fallthru */
90
91         case LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE:
92
93                 /*
94                  * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE
95                  * timeout protection set in client-handshake.c
96                  */
97
98         #ifdef LWS_OPENSSL_SUPPORT
99
100                 /*
101                  * take care of our libwebsocket_callback_on_writable
102                  * happening at a time when there's no real connection yet
103                  */
104
105                 pollfd->events &= ~POLLOUT;
106
107                 /* external POLL support via protocol 0 */
108                 context->protocols[0].callback(context, wsi,
109                         LWS_CALLBACK_CLEAR_MODE_POLL_FD,
110                         (void *)(long)wsi->sock, NULL, POLLOUT);
111
112                 /* we can retry this... so just cook the SSL BIO the first time */
113
114                 if (wsi->use_ssl && !wsi->ssl) {
115
116                         wsi->ssl = SSL_new(context->ssl_client_ctx);
117                         wsi->client_bio = BIO_new_socket(wsi->sock,
118                                                                    BIO_NOCLOSE);
119
120                         SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
121
122                         BIO_set_nbio(wsi->client_bio, 1); /* nonblocking */
123
124                         SSL_set_ex_data(wsi->ssl,
125                                         openssl_websocket_private_data_index,
126                                                                        context);
127                 }               
128
129                 if (wsi->use_ssl) {
130                         lws_latency_pre(context, wsi);
131                         n = SSL_connect(wsi->ssl);
132                         lws_latency(context, wsi, "SSL_connect LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE", n, n > 0);
133
134                         if (n < 0) {
135                                 n = SSL_get_error(wsi->ssl, n);
136
137                                 if (n == SSL_ERROR_WANT_READ ||
138                                         n == SSL_ERROR_WANT_WRITE) {
139                                         /*
140                                          * wants us to retry connect due to state of the
141                                          * underlying ssl layer... but since it may be
142                                          * stalled on blocked write, no incoming data may
143                                          * arrive to trigger the retry.  Force (possibly
144                                          * many if the SSL state persists in returning the
145                                          * condition code, but other sockets are getting
146                                          * serviced inbetweentimes) us to get called back
147                                          * when writable.
148                                          */
149
150                                         lwsl_info("SSL_connect -> SSL_ERROR_WANT_... retrying\n");
151                                         libwebsocket_callback_on_writable(context, wsi);
152
153                                         return 0; /* no error */
154                                 }
155                                 n = -1;
156                         }
157
158                         if (n <= 0) {
159                                 /*
160                                  * retry if new data comes until we
161                                  * run into the connection timeout or win
162                                  */
163
164                                 lwsl_err("SSL connect error %s\n",
165                                         ERR_error_string(ERR_get_error(),
166                                                                   ssl_err_buf));
167                                 return 0;
168                         }
169
170                         lws_latency_pre(context, wsi);
171                         n = SSL_get_verify_result(wsi->ssl);
172                         lws_latency(context, wsi, "SSL_get_verify_result LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE", n, n > 0);
173                         if ((n != X509_V_OK) && (
174                                 n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
175                                                            wsi->use_ssl != 2)) {
176
177                                 lwsl_err("server's cert didn't "
178                                                            "look good %d\n", n);
179                                 libwebsocket_close_and_free_session(context,
180                                                 wsi, LWS_CLOSE_STATUS_NOSTATUS);
181                                 return 0;
182                         }
183                 } else
184                         wsi->ssl = NULL;
185         #endif
186
187                 p = libwebsockets_generate_client_handshake(context, wsi, p);
188                 if (p == NULL) {
189                         lwsl_err("Failed to generate handshake for client, closing it\n");
190                         libwebsocket_close_and_free_session(context, wsi,
191                                                      LWS_CLOSE_STATUS_NOSTATUS);
192                         return 0;
193                 }
194
195                 /* send our request to the server */
196
197                 lws_latency_pre(context, wsi);
198         #ifdef LWS_OPENSSL_SUPPORT
199                 if (wsi->use_ssl)
200                         n = SSL_write(wsi->ssl, pkt, p - pkt);
201                 else
202         #endif
203                         n = send(wsi->sock, pkt, p - pkt, 0);
204                 lws_latency(context, wsi, "send or SSL_write LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE", n, n >= 0);
205
206                 if (n < 0) {
207                         lwsl_debug("ERROR writing to client socket\n");
208                         libwebsocket_close_and_free_session(context, wsi,
209                                                      LWS_CLOSE_STATUS_NOSTATUS);
210                         return 0;
211                 }
212
213                 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
214                 wsi->u.hdr.lextable_pos = 0;
215                 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY;
216                 libwebsocket_set_timeout(wsi,
217                                 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, AWAITING_TIMEOUT);
218
219                 break;
220
221         case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
222
223                 /* handle server hung up on us */
224
225                 if (pollfd->revents & (POLLERR | POLLHUP)) {
226
227                         lwsl_debug("Server connection %p (fd=%d) dead\n",
228                                 (void *)wsi, pollfd->fd);
229
230                         goto bail3;
231                 }
232
233                 if (!(pollfd->revents & POLLIN))
234                         goto bail3;
235
236                 /* interpret the server response */
237
238                 /*
239                  *  HTTP/1.1 101 Switching Protocols
240                  *  Upgrade: websocket
241                  *  Connection: Upgrade
242                  *  Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
243                  *  Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
244                  *  Sec-WebSocket-Protocol: chat
245                  */
246
247                 /*
248                  * we have to take some care here to only take from the
249                  * socket bytewise.  The browser may (and has been seen to
250                  * in the case that onopen() performs websocket traffic)
251                  * coalesce both handshake response and websocket traffic
252                  * in one packet, since at that point the connection is
253                  * definitively ready from browser pov.
254                  */
255
256                 len = 1;
257                 while (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE && len > 0) {
258 #ifdef LWS_OPENSSL_SUPPORT
259                         if (wsi->use_ssl) {
260                                 len = SSL_read(wsi->ssl, &c, 1);
261                                 if (len < 0) {
262                                         n = SSL_get_error(wsi->ssl, len);
263                                         if (n ==  SSL_ERROR_WANT_READ ||
264                                                         n ==  SSL_ERROR_WANT_WRITE)
265                                                 return 0;
266                                 }
267                         } else
268 #endif
269                                 len = recv(wsi->sock, &c, 1, 0);
270
271                         if (len < 0)
272                                 goto bail3;
273
274                         libwebsocket_parse(wsi, c);
275                 }
276
277                 /*
278                  * hs may also be coming in multiple packets, there is a 5-sec
279                  * libwebsocket timeout still active here too, so if parsing did
280                  * not complete just wait for next packet coming in this state
281                  */
282
283                 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
284                         break;
285
286                 /*
287                  * otherwise deal with the handshake.  If there's any
288                  * packet traffic already arrived we'll trigger poll() again
289                  * right away and deal with it that way
290                  */
291
292                 return lws_client_interpret_server_handshake(context, wsi);
293
294 bail3:
295                 if (wsi->c_protocol)
296                         free(wsi->c_protocol);
297                 lwsl_info("closing connection at LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY\n");
298                 libwebsocket_close_and_free_session(context, wsi,
299                                                     LWS_CLOSE_STATUS_NOSTATUS);
300                 return 0;
301
302         case LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT:
303                 lwsl_ext("LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT\n");
304                 break;
305
306         case LWS_CONNMODE_WS_CLIENT_PENDING_CANDIDATE_CHILD:
307                 lwsl_ext("LWS_CONNMODE_WS_CLIENT_PENDING_CANDIDATE_CHILD\n");
308                 break;
309         default:
310                 break;
311         }
312
313         return 0;
314 }
315
316
317 /*
318  * In-place str to lower case
319  */
320
321 static void
322 strtolower(char *s)
323 {
324         while (*s) {
325                 *s = tolower(*s);
326                 s++;
327         }
328 }
329
330 int
331 lws_client_interpret_server_handshake(struct libwebsocket_context *context,
332                 struct libwebsocket *wsi)
333 {
334         const char *pc;
335         int okay = 0;
336 #ifndef LWS_NO_EXTENSIONS
337         char ext_name[128];
338         struct libwebsocket_extension *ext;
339         void *v;
340         int more = 1;
341         const char *c;
342 #endif
343         int n;
344
345         /*
346          * well, what the server sent looked reasonable for syntax.
347          * Now let's confirm it sent all the necessary headers
348          */
349 #if 0
350         lwsl_parser("WSI_TOKEN_HTTP: %d\n",
351                                     wsi->utf8_token[WSI_TOKEN_HTTP].token_len);
352         lwsl_parser("WSI_TOKEN_UPGRADE: %d\n",
353                                  wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len);
354         lwsl_parser("WSI_TOKEN_CONNECTION: %d\n",
355                               wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len);
356         lwsl_parser("WSI_TOKEN_ACCEPT: %d\n",
357                                   wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len);
358         lwsl_parser("WSI_TOKEN_NONCE: %d\n",
359                                    wsi->utf8_token[WSI_TOKEN_NONCE].token_len);
360         lwsl_parser("WSI_TOKEN_PROTOCOL: %d\n",
361                                 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len);
362 #endif
363
364         strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
365         if (strncmp(wsi->utf8_token[WSI_TOKEN_HTTP].token, "101", 3)) {
366                 lwsl_warn("libwebsocket_client_handshake "
367                                 "server sent bad HTTP response '%s'\n",
368                                  wsi->utf8_token[WSI_TOKEN_HTTP].token);
369                 goto bail3;
370         }
371
372         strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
373         if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token,
374                                                          "websocket")) {
375                 lwsl_warn("libwebsocket_client_handshake server "
376                                 "sent bad Upgrade header '%s'\n",
377                                   wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
378                 goto bail3;
379         }
380
381         strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
382         if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token,
383                                                            "upgrade")) {
384                 lwsl_warn("libwebsocket_client_handshake server "
385                                 "sent bad Connection hdr '%s'\n",
386                            wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
387                 goto bail3;
388         }
389
390         pc = wsi->c_protocol;
391         if (pc == NULL)
392                 lwsl_parser("lws_client_interpret_server_handshake: "
393                                                           "NULL c_protocol\n");
394         else
395                 lwsl_parser("lws_client_interpret_server_handshake: "
396                                                       "cPprotocol='%s'\n", pc);
397
398         /*
399          * confirm the protocol the server wants to talk was in the list
400          * of protocols we offered
401          */
402
403         if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
404
405                 lwsl_info("lws_client_interpret_server_handshake "
406                                                "WSI_TOKEN_PROTOCOL is null\n");
407                 /*
408                  * no protocol name to work from,
409                  * default to first protocol
410                  */
411                 wsi->protocol = &context->protocols[0];
412                 wsi->c_callback = wsi->protocol->callback;
413                 free(wsi->c_protocol);
414
415                 goto check_extensions;
416         }
417
418         while (*pc && !okay) {
419                 if ((!strncmp(pc, wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
420                  wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len)) &&
421                  (pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == ',' ||
422                   pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == '\0')) {
423                         okay = 1;
424                         continue;
425                 }
426                 while (*pc && *pc != ',')
427                         pc++;
428                 while (*pc && *pc != ' ')
429                         pc++;
430         }
431
432         /* done with him now */
433
434         if (wsi->c_protocol)
435                 free(wsi->c_protocol);
436
437         if (!okay) {
438                 lwsl_err("libwebsocket_client_handshake server "
439                                         "sent bad protocol '%s'\n",
440                                  wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
441                 goto bail2;
442         }
443
444         /*
445          * identify the selected protocol struct and set it
446          */
447         n = 0;
448         wsi->protocol = NULL;
449         while (context->protocols[n].callback && !wsi->protocol) {  /* Stop after finding first one?? */
450                 if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
451                                            context->protocols[n].name) == 0) {
452                         wsi->protocol = &context->protocols[n];
453                         wsi->c_callback = wsi->protocol->callback;
454                 }
455                 n++;
456         }
457
458         if (wsi->protocol == NULL) {
459                 lwsl_err("libwebsocket_client_handshake server "
460                                 "requested protocol '%s', which we "
461                                 "said we supported but we don't!\n",
462                                  wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
463                 goto bail2;
464         }
465
466
467 check_extensions:
468 #ifndef LWS_NO_EXTENSIONS
469         /* instantiate the accepted extensions */
470
471         if (!wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token_len) {
472                 lwsl_ext("no client extenstions allowed by server\n");
473                 goto check_accept;
474         }
475
476         /*
477          * break down the list of server accepted extensions
478          * and go through matching them or identifying bogons
479          */
480
481         c = wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token;
482         n = 0;
483         while (more) {
484
485                 if (*c && (*c != ',' && *c != ' ' && *c != '\t')) {
486                         ext_name[n] = *c++;
487                         if (n < sizeof(ext_name) - 1)
488                                 n++;
489                         continue;
490                 }
491                 ext_name[n] = '\0';
492                 if (!*c)
493                         more = 0;
494                 else {
495                         c++;
496                         if (!n)
497                                 continue;
498                 }
499
500                 /* check we actually support it */
501
502                 lwsl_ext("checking client ext %s\n", ext_name);
503
504                 n = 0;
505                 ext = wsi->protocol->owning_server->extensions;
506                 while (ext && ext->callback) {
507
508                         if (strcmp(ext_name, ext->name)) {
509                                 ext++;
510                                 continue;
511                         }
512
513                         n = 1;
514
515                         lwsl_ext("instantiating client ext %s\n", ext_name);
516
517                         /* instantiate the extension on this conn */
518
519                         wsi->active_extensions_user[
520                                 wsi->count_active_extensions] =
521                                          malloc(ext->per_session_data_size);
522                         if (wsi->active_extensions_user[
523                                 wsi->count_active_extensions] == NULL) {
524                                 lwsl_err("Out of mem\n");
525                                 goto bail2;
526                         }
527                         memset(wsi->active_extensions_user[
528                                 wsi->count_active_extensions], 0,
529                                                     ext->per_session_data_size);
530                         wsi->active_extensions[
531                                   wsi->count_active_extensions] = ext;
532
533                         /* allow him to construct his context */
534
535                         ext->callback(wsi->protocol->owning_server,
536                                 ext, wsi,
537                                    LWS_EXT_CALLBACK_CLIENT_CONSTRUCT,
538                                         wsi->active_extensions_user[
539                                          wsi->count_active_extensions],
540                                                                    NULL, 0);
541
542                         wsi->count_active_extensions++;
543
544                         ext++;
545                 }
546
547                 if (n == 0) {
548                         lwsl_warn("Server said we should use"
549                                   "an unknown extension '%s'!\n", ext_name);
550                         goto bail2;
551                 }
552
553                 n = 0;
554         }
555
556 check_accept:
557 #endif
558
559         /*
560          * Confirm his accept token is the one we precomputed
561          */
562
563         if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
564                                   wsi->u.hdr.initial_handshake_hash_base64)) {
565                 lwsl_warn("libwebsocket_client_handshake server "
566                         "sent bad ACCEPT '%s' vs computed '%s'\n",
567                         wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
568                                         wsi->u.hdr.initial_handshake_hash_base64);
569                 goto bail2;
570         }
571
572         /* allocate the per-connection user memory (if any) */
573         if (wsi->protocol->per_session_data_size &&
574                                           !libwebsocket_ensure_user_space(wsi))
575                 goto bail2;
576
577         /* clear his proxy connection timeout */
578
579         libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
580
581         /* mark him as being alive */
582
583         wsi->state = WSI_STATE_ESTABLISHED;
584         wsi->mode = LWS_CONNMODE_WS_CLIENT;
585
586         /* union transition */
587         memset(&wsi->u, 0, sizeof wsi->u);
588
589         lwsl_debug("handshake OK for protocol %s\n", wsi->protocol->name);
590
591         /* call him back to inform him he is up */
592
593         wsi->protocol->callback(context, wsi,
594                                 LWS_CALLBACK_CLIENT_ESTABLISHED,
595                                                      wsi->user_space, NULL, 0);
596 #ifndef LWS_NO_EXTENSIONS
597         /*
598          * inform all extensions, not just active ones since they
599          * already know
600          */
601
602         ext = context->extensions;
603
604         while (ext && ext->callback) {
605                 v = NULL;
606                 for (n = 0; n < wsi->count_active_extensions; n++)
607                         if (wsi->active_extensions[n] == ext)
608                                 v = wsi->active_extensions_user[n];
609
610                 ext->callback(context, ext, wsi,
611                           LWS_EXT_CALLBACK_ANY_WSI_ESTABLISHED, v, NULL, 0);
612                 ext++;
613         }
614 #endif
615
616         return 0;
617
618 bail3:
619         if (wsi->c_protocol)
620                 free(wsi->c_protocol);
621
622 bail2:
623         if (wsi->c_callback) wsi->c_callback(context, wsi,
624        LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
625                          wsi->user_space,
626                          NULL, 0);
627         lwsl_info("closing connection due to bail2 connection error\n");
628         libwebsocket_close_and_free_session(context, wsi,
629                                                  LWS_CLOSE_STATUS_PROTOCOL_ERR);
630
631         return 1;
632 }
633
634
635 char *
636 libwebsockets_generate_client_handshake(struct libwebsocket_context *context,
637                 struct libwebsocket *wsi, char *pkt)
638 {
639         char hash[20];
640         char key_b64[40];
641         char *p = pkt;
642         int n;
643 #ifndef LWS_NO_EXTENSIONS
644         struct libwebsocket_extension *ext;
645         struct libwebsocket_extension *ext1;
646         int ext_count = 0;
647 #endif
648         unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 +
649                          MAX_USER_RX_BUFFER + LWS_SEND_BUFFER_POST_PADDING];
650         static const char magic_websocket_guid[] =
651                                          "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
652
653         /*
654          * create the random key
655          */
656
657         n = libwebsockets_get_random(context, hash, 16);
658         if (n != 16) {
659                 lwsl_err("Unable to read from random dev %s\n",
660                                                 SYSTEM_RANDOM_FILEPATH);
661                 free(wsi->c_path);
662                 free(wsi->c_host);
663                 if (wsi->c_origin)
664                         free(wsi->c_origin);
665                 if (wsi->c_protocol)
666                         free(wsi->c_protocol);
667                 libwebsocket_close_and_free_session(context, wsi,
668                                              LWS_CLOSE_STATUS_NOSTATUS);
669                 return NULL;
670         }
671
672         lws_b64_encode_string(hash, 16, key_b64, sizeof key_b64);
673
674         /*
675          * 00 example client handshake
676          *
677          * GET /socket.io/websocket HTTP/1.1
678          * Upgrade: WebSocket
679          * Connection: Upgrade
680          * Host: 127.0.0.1:9999
681          * Origin: http://127.0.0.1
682          * Sec-WebSocket-Key1: 1 0 2#0W 9 89 7  92 ^
683          * Sec-WebSocket-Key2: 7 7Y 4328 B2v[8(z1
684          * Cookie: socketio=websocket
685          *
686          * (Á®Ä0¶†≥
687          *
688          * 04 example client handshake
689          *
690          * GET /chat HTTP/1.1
691          * Host: server.example.com
692          * Upgrade: websocket
693          * Connection: Upgrade
694          * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
695          * Sec-WebSocket-Origin: http://example.com
696          * Sec-WebSocket-Protocol: chat, superchat
697          * Sec-WebSocket-Version: 4
698          */
699
700         p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", wsi->c_path);
701
702         p += sprintf(p, "Pragma: no-cache\x0d\x0a"
703                                         "Cache-Control: no-cache\x0d\x0a");
704
705         p += sprintf(p, "Host: %s\x0d\x0a", wsi->c_host);
706         p += sprintf(p, "Upgrade: websocket\x0d\x0a"
707                                         "Connection: Upgrade\x0d\x0a"
708                                         "Sec-WebSocket-Key: ");
709         strcpy(p, key_b64);
710         p += strlen(key_b64);
711         p += sprintf(p, "\x0d\x0a");
712         if (wsi->c_origin) {
713                 if (wsi->ietf_spec_revision == 13)
714                         p += sprintf(p, "Origin: %s\x0d\x0a", wsi->c_origin);
715                 else
716                         p += sprintf(p, "Sec-WebSocket-Origin: %s\x0d\x0a",
717                                                          wsi->c_origin);
718         }
719         if (wsi->c_protocol)
720                 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
721                                                        wsi->c_protocol);
722
723         /* tell the server what extensions we could support */
724
725         p += sprintf(p, "Sec-WebSocket-Extensions: ");
726 #ifndef LWS_NO_EXTENSIONS
727         ext = context->extensions;
728         while (ext && ext->callback) {
729
730                 n = 0;
731                 ext1 = context->extensions;
732
733                 while (ext1 && ext1->callback) {
734                         n |= ext1->callback(context, ext1, wsi,
735                                 LWS_EXT_CALLBACK_CHECK_OK_TO_PROPOSE_EXTENSION,
736                                         NULL, (char *)ext->name, 0);
737
738                         ext1++;
739                 }
740
741                 if (n) { /* an extension vetos us */
742                         lwsl_ext("ext %s vetoed\n", (char *)ext->name);
743                         ext++;
744                         continue;
745                 }
746
747                 n = context->protocols[0].callback(context, wsi,
748                         LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
749                                 wsi->user_space, (char *)ext->name, 0);
750
751                 /*
752                  * zero return from callback means
753                  * go ahead and allow the extension,
754                  * it's what we get if the callback is
755                  * unhandled
756                  */
757
758                 if (n) {
759                         ext++;
760                         continue;
761                 }
762
763                 /* apply it */
764
765                 if (ext_count)
766                         *p++ = ',';
767                 p += sprintf(p, "%s", ext->name);
768                 ext_count++;
769
770                 ext++;
771         }
772 #endif
773         p += sprintf(p, "\x0d\x0a");
774
775         if (wsi->ietf_spec_revision)
776                 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
777                                                wsi->ietf_spec_revision);
778
779         /* give userland a chance to append, eg, cookies */
780
781         context->protocols[0].callback(context, wsi,
782                 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
783                 NULL, &p, (pkt + sizeof(pkt)) - p - 12);
784
785         p += sprintf(p, "\x0d\x0a");
786
787         /* prepare the expected server accept response */
788
789         strcpy((char *)buf, key_b64);
790         strcpy((char *)&buf[strlen((char *)buf)], magic_websocket_guid);
791
792         SHA1(buf, strlen((char *)buf), (unsigned char *)hash);
793
794         lws_b64_encode_string(hash, 20,
795                         wsi->u.hdr.initial_handshake_hash_base64,
796                              sizeof wsi->u.hdr.initial_handshake_hash_base64);
797
798         /* done with these now */
799
800         free(wsi->c_path);
801         free(wsi->c_host);
802         if (wsi->c_origin)
803                 free(wsi->c_origin);
804
805         return p;
806 }
807