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