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