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