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