ws-server: restrict returned Sec-Websocket-Protocol to the chosen name only
[platform/upstream/libwebsockets.git] / lib / client.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2014 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 int
25 lws_handshake_client(struct lws *wsi, unsigned char **buf, size_t len)
26 {
27         int m;
28
29         switch (wsi->mode) {
30         case LWSCM_WSCL_WAITING_PROXY_REPLY:
31         case LWSCM_WSCL_ISSUE_HANDSHAKE:
32         case LWSCM_WSCL_WAITING_SERVER_REPLY:
33         case LWSCM_WSCL_WAITING_EXTENSION_CONNECT:
34         case LWSCM_WS_CLIENT:
35                 while (len) {
36                         /*
37                          * we were accepting input but now we stopped doing so
38                          */
39                         if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
40                                 lwsl_debug("%s: caching %d\n", __func__, len);
41                                 lws_rxflow_cache(wsi, *buf, 0, len);
42                                 return 0;
43                         }
44                         if (wsi->u.ws.rx_draining_ext) {
45                                 m = lws_rx_sm(wsi, 0);
46                                 if (m < 0)
47                                         return -1;
48                                 continue;
49                         }
50                         /* account for what we're using in rxflow buffer */
51                         if (wsi->rxflow_buffer)
52                                 wsi->rxflow_pos++;
53
54                         if (lws_client_rx_sm(wsi, *(*buf)++)) {
55                                 lwsl_debug("client_rx_sm exited\n");
56                                 return -1;
57                         }
58                         len--;
59                 }
60                 lwsl_debug("%s: finished with %d\n", __func__, len);
61                 return 0;
62         default:
63                 break;
64         }
65
66         return 0;
67 }
68
69 int
70 lws_client_socket_service(struct lws_context *context, struct lws *wsi,
71                           struct lws_pollfd *pollfd)
72 {
73         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
74         char *p = (char *)&pt->serv_buf[0];
75         char *sb = p;
76         unsigned char c;
77         int n, len;
78
79         switch (wsi->mode) {
80
81         case LWSCM_WSCL_WAITING_CONNECT:
82
83                 /*
84                  * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE
85                  * timeout protection set in client-handshake.c
86                  */
87
88                 if (!lws_client_connect_2(wsi)) {
89                         /* closed */
90                         lwsl_client("closed\n");
91                         return -1;
92                 }
93
94                 /* either still pending connection, or changed mode */
95                 return 0;
96
97         case LWSCM_WSCL_WAITING_PROXY_REPLY:
98
99                 /* handle proxy hung up on us */
100
101                 if (pollfd->revents & LWS_POLLHUP) {
102
103                         lwsl_warn("Proxy connection %p (fd=%d) dead\n",
104                                   (void *)wsi, pollfd->fd);
105
106                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
107                         return 0;
108                 }
109
110                 n = recv(wsi->sock, sb, LWS_MAX_SOCKET_IO_BUF, 0);
111                 if (n < 0) {
112                         if (LWS_ERRNO == LWS_EAGAIN) {
113                                 lwsl_debug("Proxy read returned EAGAIN... retrying\n");
114                                 return 0;
115                         }
116
117                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
118                         lwsl_err("ERROR reading from proxy socket\n");
119                         return 0;
120                 }
121
122                 pt->serv_buf[13] = '\0';
123                 if (strcmp(sb, "HTTP/1.0 200 ") &&
124                     strcmp(sb, "HTTP/1.1 200 ")) {
125                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
126                         lwsl_err("ERROR proxy: %s\n", sb);
127                         return 0;
128                 }
129
130                 /* clear his proxy connection timeout */
131
132                 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
133
134                 /* fallthru */
135
136         case LWSCM_WSCL_ISSUE_HANDSHAKE:
137
138                 /*
139                  * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE
140                  * timeout protection set in client-handshake.c
141                  *
142                  * take care of our lws_callback_on_writable
143                  * happening at a time when there's no real connection yet
144                  */
145                 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0))
146                         return -1;
147
148 #ifdef LWS_OPENSSL_SUPPORT
149                 /* we can retry this... just cook the SSL BIO the first time */
150
151                 if (wsi->use_ssl && !wsi->ssl) {
152 #if defined(CYASSL_SNI_HOST_NAME) || defined(WOLFSSL_SNI_HOST_NAME) || defined(SSL_CTRL_SET_TLSEXT_HOSTNAME)
153                         const char *hostname = lws_hdr_simple_ptr(wsi,
154                                                 _WSI_TOKEN_CLIENT_HOST);
155 #endif
156
157                         wsi->ssl = SSL_new(context->ssl_client_ctx);
158 #ifndef USE_WOLFSSL
159                         SSL_set_mode(wsi->ssl,
160                                         SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
161 #endif
162                         /*
163                          * use server name indication (SNI), if supported,
164                          * when establishing connection
165                          */
166 #ifdef USE_WOLFSSL
167 #ifdef USE_OLD_CYASSL
168 #ifdef CYASSL_SNI_HOST_NAME
169                         CyaSSL_UseSNI(wsi->ssl, CYASSL_SNI_HOST_NAME,
170                                 hostname, strlen(hostname));
171 #endif
172 #else
173 #ifdef WOLFSSL_SNI_HOST_NAME
174                         wolfSSL_UseSNI(wsi->ssl, WOLFSSL_SNI_HOST_NAME,
175                                 hostname, strlen(hostname));
176 #endif
177 #endif
178 #else
179 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
180                         SSL_set_tlsext_host_name(wsi->ssl, hostname);
181 #endif
182 #endif
183
184 #ifdef USE_WOLFSSL
185                         /*
186                          * wolfSSL/CyaSSL does certificate verification differently
187                          * from OpenSSL.
188                          * If we should ignore the certificate, we need to set
189                          * this before SSL_new and SSL_connect is called.
190                          * Otherwise the connect will simply fail with error
191                          * code -155
192                          */
193 #ifdef USE_OLD_CYASSL
194                         if (wsi->use_ssl == 2)
195                                 CyaSSL_set_verify(wsi->ssl,
196                                                         SSL_VERIFY_NONE, NULL);
197 #else
198                         if (wsi->use_ssl == 2)
199                                 wolfSSL_set_verify(wsi->ssl,
200                                                         SSL_VERIFY_NONE, NULL);
201 #endif
202 #endif /* USE_WOLFSSL */
203
204                         wsi->client_bio =
205                                 BIO_new_socket(wsi->sock, BIO_NOCLOSE);
206                         SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
207
208 #ifdef USE_WOLFSSL
209 #ifdef USE_OLD_CYASSL
210                         CyaSSL_set_using_nonblock(wsi->ssl, 1);
211 #else
212                         wolfSSL_set_using_nonblock(wsi->ssl, 1);
213 #endif
214 #else
215                         BIO_set_nbio(wsi->client_bio, 1); /* nonblocking */
216 #endif
217
218                         SSL_set_ex_data(wsi->ssl,
219                                         openssl_websocket_private_data_index,
220                                                                        context);
221                 }
222
223                 if (wsi->use_ssl) {
224                         lws_latency_pre(context, wsi);
225                         n = SSL_connect(wsi->ssl);
226                         lws_latency(context, wsi,
227                           "SSL_connect LWSCM_WSCL_ISSUE_HANDSHAKE", n, n > 0);
228
229                         if (n < 0) {
230                                 n = SSL_get_error(wsi->ssl, n);
231
232                                 if (n == SSL_ERROR_WANT_READ)
233                                         goto some_wait;
234
235                                 if (n == SSL_ERROR_WANT_WRITE) {
236                                         /*
237                                          * wants us to retry connect due to
238                                          * state of the underlying ssl layer...
239                                          * but since it may be stalled on
240                                          * blocked write, no incoming data may
241                                          * arrive to trigger the retry.
242                                          * Force (possibly many times if the SSL
243                                          * state persists in returning the
244                                          * condition code, but other sockets
245                                          * are getting serviced inbetweentimes)
246                                          * us to get called back when writable.
247                                          */
248                                         lwsl_info("%s: WANT_WRITE... retrying\n", __func__);
249                                         lws_callback_on_writable(wsi);
250 some_wait:
251                                         wsi->mode = LWSCM_WSCL_WAITING_SSL;
252
253                                         return 0; /* no error */
254                                 }
255                                 n = -1;
256                         }
257
258                         if (n <= 0) {
259                                 /*
260                                  * retry if new data comes until we
261                                  * run into the connection timeout or win
262                                  */
263                                 n = ERR_get_error();
264                                 if (n != SSL_ERROR_NONE) {
265                                         lwsl_err("SSL connect error %lu: %s\n",
266                                                 n, ERR_error_string(n, sb));
267                                         goto bail3;
268                                 }
269                         }
270                 } else
271                         wsi->ssl = NULL;
272
273                 /* fallthru */
274
275         case LWSCM_WSCL_WAITING_SSL:
276
277                 if (wsi->use_ssl) {
278                         if (wsi->mode == LWSCM_WSCL_WAITING_SSL) {
279                                 lws_latency_pre(context, wsi);
280                                 n = SSL_connect(wsi->ssl);
281                                 lws_latency(context, wsi,
282                                             "SSL_connect LWSCM_WSCL_WAITING_SSL",
283                                             n, n > 0);
284
285                                 if (n < 0) {
286                                         n = SSL_get_error(wsi->ssl, n);
287
288                                         if (n == SSL_ERROR_WANT_READ)
289                                                 goto some_wait;
290
291                                         if (n == SSL_ERROR_WANT_WRITE) {
292                                                 /*
293                                                  * wants us to retry connect due to
294                                                  * state of the underlying ssl layer...
295                                                  * but since it may be stalled on
296                                                  * blocked write, no incoming data may
297                                                  * arrive to trigger the retry.
298                                                  * Force (possibly many times if the SSL
299                                                  * state persists in returning the
300                                                  * condition code, but other sockets
301                                                  * are getting serviced inbetweentimes)
302                                                  * us to get called back when writable.
303                                                  */
304                                                 lwsl_info("SSL_connect WANT_WRITE... retrying\n");
305                                                 lws_callback_on_writable(wsi);
306
307                                                 goto some_wait;
308                                         }
309                                         n = -1;
310                                 }
311
312                                 if (n <= 0) {
313                                         /*
314                                          * retry if new data comes until we
315                                          * run into the connection timeout or win
316                                          */
317                                         n = ERR_get_error();
318                                         if (n != SSL_ERROR_NONE) {
319                                                 lwsl_err("SSL connect error %lu: %s\n",
320                                                          n, ERR_error_string(n, sb));
321                                                 goto bail3;
322                                         }
323                                 }
324                         }
325
326                         #ifndef USE_WOLFSSL
327                         /*
328                          * See comment above about wolfSSL certificate
329                          * verification
330                          */
331                         lws_latency_pre(context, wsi);
332                         n = SSL_get_verify_result(wsi->ssl);
333                         lws_latency(context, wsi,
334                                 "SSL_get_verify_result LWS_CONNMODE..HANDSHAKE",
335                                                                       n, n > 0);
336
337                         if (n != X509_V_OK) {
338                                 if ((n == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
339                                      n == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) && wsi->use_ssl == 2) {
340                                         lwsl_notice("accepting self-signed certificate\n");
341                                 } else {
342                                         lwsl_err("server's cert didn't look good, X509_V_ERR = %d: %s\n",
343                                                  n, ERR_error_string(n, sb));
344                                         lws_close_free_wsi(wsi,
345                                                 LWS_CLOSE_STATUS_NOSTATUS);
346                                         return -1;
347                                 }
348                         }
349 #endif /* USE_WOLFSSL */
350                 } else
351                         wsi->ssl = NULL;
352 #endif
353
354                 wsi->mode = LWSCM_WSCL_ISSUE_HANDSHAKE2;
355                 lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND,
356                                 context->timeout_secs);
357
358                 /* fallthru */
359
360         case LWSCM_WSCL_ISSUE_HANDSHAKE2:
361                 p = lws_generate_client_handshake(wsi, p);
362                 if (p == NULL) {
363                         lwsl_err("Failed to generate handshake for client\n");
364                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
365                         return 0;
366                 }
367
368                 /* send our request to the server */
369
370                 lws_latency_pre(context, wsi);
371
372                 n = lws_ssl_capable_write(wsi, (unsigned char *)sb, p - sb);
373                 lws_latency(context, wsi, "send lws_issue_raw", n,
374                             n == p - sb);
375                 switch (n) {
376                 case LWS_SSL_CAPABLE_ERROR:
377                         lwsl_debug("ERROR writing to client socket\n");
378                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
379                         return 0;
380                 case LWS_SSL_CAPABLE_MORE_SERVICE:
381                         lws_callback_on_writable(wsi);
382                         break;
383                 }
384
385                 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
386                 wsi->u.hdr.lextable_pos = 0;
387                 wsi->mode = LWSCM_WSCL_WAITING_SERVER_REPLY;
388                 lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE,
389                                 context->timeout_secs);
390                 break;
391
392         case LWSCM_WSCL_WAITING_SERVER_REPLY:
393
394                 /* handle server hung up on us */
395
396                 if (pollfd->revents & LWS_POLLHUP) {
397
398                         lwsl_debug("Server connection %p (fd=%d) dead\n",
399                                 (void *)wsi, pollfd->fd);
400
401                         goto bail3;
402                 }
403
404                 if (!(pollfd->revents & LWS_POLLIN))
405                         break;
406
407                 /* interpret the server response */
408
409                 /*
410                  *  HTTP/1.1 101 Switching Protocols
411                  *  Upgrade: websocket
412                  *  Connection: Upgrade
413                  *  Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
414                  *  Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
415                  *  Sec-WebSocket-Protocol: chat
416                  */
417
418                 /*
419                  * we have to take some care here to only take from the
420                  * socket bytewise.  The browser may (and has been seen to
421                  * in the case that onopen() performs websocket traffic)
422                  * coalesce both handshake response and websocket traffic
423                  * in one packet, since at that point the connection is
424                  * definitively ready from browser pov.
425                  */
426                 len = 1;
427                 while (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE &&
428                        len > 0) {
429                         n = lws_ssl_capable_read(wsi, &c, 1);
430                         lws_latency(context, wsi, "send lws_issue_raw", n,
431                                     n == 1);
432                         switch (n) {
433                         case 0:
434                         case LWS_SSL_CAPABLE_ERROR:
435                                 goto bail3;
436                         case LWS_SSL_CAPABLE_MORE_SERVICE:
437                                 return 0;
438                         }
439
440                         if (lws_parse(wsi, c)) {
441                                 lwsl_warn("problems parsing header\n");
442                                 goto bail3;
443                         }
444                 }
445
446                 /*
447                  * hs may also be coming in multiple packets, there is a 5-sec
448                  * libwebsocket timeout still active here too, so if parsing did
449                  * not complete just wait for next packet coming in this state
450                  */
451
452                 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
453                         break;
454
455                 /*
456                  * otherwise deal with the handshake.  If there's any
457                  * packet traffic already arrived we'll trigger poll() again
458                  * right away and deal with it that way
459                  */
460
461                 return lws_client_interpret_server_handshake(wsi);
462
463 bail3:
464                 lwsl_info("closing conn at LWS_CONNMODE...SERVER_REPLY\n");
465                 wsi->context->protocols[0].callback(wsi,
466                                 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
467                                 wsi->user_space, NULL, 0);
468
469                 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
470                 return -1;
471
472         case LWSCM_WSCL_WAITING_EXTENSION_CONNECT:
473                 lwsl_ext("LWSCM_WSCL_WAITING_EXTENSION_CONNECT\n");
474                 break;
475
476         case LWSCM_WSCL_PENDING_CANDIDATE_CHILD:
477                 lwsl_ext("LWSCM_WSCL_PENDING_CANDIDATE_CHILD\n");
478                 break;
479         default:
480                 break;
481         }
482
483         return 0;
484 }
485
486 /*
487  * In-place str to lower case
488  */
489
490 static void
491 strtolower(char *s)
492 {
493         while (*s) {
494                 *s = tolower((int)*s);
495                 s++;
496         }
497 }
498
499 int
500 lws_client_interpret_server_handshake(struct lws *wsi)
501 {
502         int n, len, okay = 0, isErrorCodeReceived = 0, port = 0, ssl = 0;
503         struct lws_context *context = wsi->context;
504         int close_reason = LWS_CLOSE_STATUS_PROTOCOL_ERR;
505         const char *pc, *prot, *ads = NULL, *path;
506         char *p;
507 #ifndef LWS_NO_EXTENSIONS
508         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
509         char *sb = (char *)&pt->serv_buf[0];
510         const struct lws_ext_options *opts;
511         const struct lws_extension *ext;
512         char ext_name[128];
513         const char *c, *a;
514         char ignore;
515         int more = 1;
516         void *v;
517 #endif
518
519         /*
520          * well, what the server sent looked reasonable for syntax.
521          * Now let's confirm it sent all the necessary headers
522          */
523         p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP);
524         if (!p) {
525                 lwsl_info("no URI\n");
526                 goto bail3;
527         }
528         n = atoi(p);
529         if (n == 301 || n == 302 || n == 303 || n == 307 || n == 308) {
530                 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_LOCATION);
531                 if (!p)
532                         goto bail3;
533
534                 if (lws_parse_uri(p, &prot, &ads, &port, &path))
535                         goto bail3;
536
537                 if (!strcmp(prot, "wss://") || !strcmp(prot, "https://"))
538                         ssl = 1;
539
540                 if (lws_client_reset(wsi, ssl, ads, port, path, ads)) {
541                         lwsl_err("Redirect failed\n");
542                         goto bail3;
543                 }
544                 return 0;
545         }
546         if (lws_hdr_total_length(wsi, WSI_TOKEN_ACCEPT) == 0) {
547                 lwsl_info("no ACCEPT\n");
548                 isErrorCodeReceived = 1;
549                 goto bail3;
550         }
551
552         if (p && strncmp(p, "101", 3)) {
553                 lwsl_warn(
554                        "lws_client_handshake: got bad HTTP response '%s'\n", p);
555                 goto bail3;
556         }
557
558         p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE);
559         if (!p) {
560                 lwsl_info("no UPGRADE\n");
561                 goto bail3;
562         }
563         strtolower(p);
564         if (strcmp(p, "websocket")) {
565                 lwsl_warn(
566                       "lws_client_handshake: got bad Upgrade header '%s'\n", p);
567                 goto bail3;
568         }
569
570         p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_CONNECTION);
571         if (!p) {
572                 lwsl_info("no Connection hdr\n");
573                 goto bail3;
574         }
575         strtolower(p);
576         if (strcmp(p, "upgrade")) {
577                 lwsl_warn("lws_client_int_s_hs: bad header %s\n", p);
578                 goto bail3;
579         }
580
581         pc = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);
582         if (!pc) {
583                 lwsl_parser("lws_client_int_s_hs: no protocol list\n");
584         } else
585                 lwsl_parser("lws_client_int_s_hs: protocol list '%s'\n", pc);
586
587         /*
588          * confirm the protocol the server wants to talk was in the list
589          * of protocols we offered
590          */
591
592         len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
593         if (!len) {
594                 lwsl_info("lws_client_int_s_hs: WSI_TOKEN_PROTOCOL is null\n");
595                 /*
596                  * no protocol name to work from,
597                  * default to first protocol
598                  */
599                 wsi->protocol = &context->protocols[0];
600                 goto check_extensions;
601         }
602
603         p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL);
604         len = strlen(p);
605
606         while (pc && *pc && !okay) {
607                 if (!strncmp(pc, p, len) &&
608                     (pc[len] == ',' || pc[len] == '\0')) {
609                         okay = 1;
610                         continue;
611                 }
612                 while (*pc && *pc++ != ',')
613                         ;
614                 while (*pc && *pc == ' ')
615                         pc++;
616         }
617
618         if (!okay) {
619                 lwsl_err("lws_client_int_s_hs: got bad protocol %s\n", p);
620                 goto bail2;
621         }
622
623         /*
624          * identify the selected protocol struct and set it
625          */
626         n = 0;
627         wsi->protocol = NULL;
628         while (context->protocols[n].callback && !wsi->protocol) {
629                 if (strcmp(p, context->protocols[n].name) == 0) {
630                         wsi->protocol = &context->protocols[n];
631                         break;
632                 }
633                 n++;
634         }
635
636         if (wsi->protocol == NULL) {
637                 lwsl_err("lws_client_int_s_hs: fail protocol %s\n", p);
638                 goto bail2;
639         }
640
641
642 check_extensions:
643 #ifndef LWS_NO_EXTENSIONS
644         /* instantiate the accepted extensions */
645
646         if (!lws_hdr_total_length(wsi, WSI_TOKEN_EXTENSIONS)) {
647                 lwsl_ext("no client extensions allowed by server\n");
648                 goto check_accept;
649         }
650
651         /*
652          * break down the list of server accepted extensions
653          * and go through matching them or identifying bogons
654          */
655
656         if (lws_hdr_copy(wsi, sb, LWS_MAX_SOCKET_IO_BUF, WSI_TOKEN_EXTENSIONS) < 0) {
657                 lwsl_warn("ext list from server failed to copy\n");
658                 goto bail2;
659         }
660
661         c = sb;
662         n = 0;
663         ignore = 0;
664         a = NULL;
665         while (more) {
666
667                 if (*c && (*c != ',' && *c != '\t')) {
668                         if (*c == ';') {
669                                 ignore = 1;
670                                 if (!a)
671                                         a = c + 1;
672                         }
673                         if (ignore || *c == ' ') {
674                                 c++;
675                                 continue;
676                         }
677
678                         ext_name[n] = *c++;
679                         if (n < sizeof(ext_name) - 1)
680                                 n++;
681                         continue;
682                 }
683                 ext_name[n] = '\0';
684                 ignore = 0;
685                 if (!*c)
686                         more = 0;
687                 else {
688                         c++;
689                         if (!n)
690                                 continue;
691                 }
692
693                 /* check we actually support it */
694
695                 lwsl_notice("checking client ext %s\n", ext_name);
696
697                 n = 0;
698                 ext = lws_get_context(wsi)->extensions;
699                 while (ext && ext->callback) {
700                         if (strcmp(ext_name, ext->name)) {
701                                 ext++;
702                                 continue;
703                         }
704
705                         n = 1;
706                         lwsl_notice("instantiating client ext %s\n", ext_name);
707
708                         /* instantiate the extension on this conn */
709
710                         wsi->active_extensions[wsi->count_act_ext] = ext;
711
712                         /* allow him to construct his ext instance */
713
714                         if (ext->callback(lws_get_context(wsi), ext, wsi,
715                                       LWS_EXT_CB_CLIENT_CONSTRUCT,
716                                       (void *)&wsi->act_ext_user[wsi->count_act_ext],
717                                       (void *)&opts, 0)) {
718                                 lwsl_notice(" ext %s failed construction\n", ext_name);
719                                 ext++;
720                                 continue;
721                         }
722
723                         /*
724                          * allow the user code to override ext defaults if it
725                          * wants to
726                          */
727                         ext_name[0] = '\0';
728                         if (user_callback_handle_rxflow(wsi->protocol->callback,
729                                         wsi, LWS_CALLBACK_WS_EXT_DEFAULTS,
730                                         (char *)ext->name, ext_name,
731                                         sizeof(ext_name)))
732                                 goto bail2;
733
734                         if (ext_name[0] &&
735                             lws_ext_parse_options(ext, wsi, wsi->act_ext_user[
736                                                   wsi->count_act_ext], opts, ext_name,
737                                                   strlen(ext_name))) {
738                                 lwsl_err("%s: unable to parse user defaults '%s'",
739                                          __func__, ext_name);
740                                 goto bail2;
741                         }
742
743                         /*
744                          * give the extension the server options
745                          */
746                         if (a && lws_ext_parse_options(ext, wsi,
747                                         wsi->act_ext_user[wsi->count_act_ext],
748                                         opts, a, c - a)) {
749                                 lwsl_err("%s: unable to parse remote def '%s'",
750                                          __func__, a);
751                                 goto bail2;
752                         }
753
754                         if (ext->callback(lws_get_context(wsi), ext, wsi,
755                                         LWS_EXT_CB_OPTION_CONFIRM,
756                                       wsi->act_ext_user[wsi->count_act_ext],
757                                       NULL, 0)) {
758                                 lwsl_err("%s: ext %s rejects server options %s",
759                                          ext->name, a);
760                                 goto bail2;
761                         }
762
763                         wsi->count_act_ext++;
764
765                         ext++;
766                 }
767
768                 if (n == 0) {
769                         lwsl_warn("Unknown ext '%s'!\n", ext_name);
770                         goto bail2;
771                 }
772
773                 a = NULL;
774                 n = 0;
775         }
776
777 check_accept:
778 #endif
779
780         /*
781          * Confirm his accept token is the one we precomputed
782          */
783
784         p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_ACCEPT);
785         if (strcmp(p, wsi->u.hdr.ah->initial_handshake_hash_base64)) {
786                 lwsl_warn("lws_client_int_s_hs: accept '%s' wrong vs '%s'\n", p,
787                                   wsi->u.hdr.ah->initial_handshake_hash_base64);
788                 goto bail2;
789         }
790
791         /* allocate the per-connection user memory (if any) */
792         if (lws_ensure_user_space(wsi)) {
793                 lwsl_err("Problem allocating wsi user mem\n");
794                 goto bail2;
795         }
796
797         /*
798          * we seem to be good to go, give client last chance to check
799          * headers and OK it
800          */
801         if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH,
802                                     wsi->user_space, NULL, 0))
803                 goto bail2;
804
805         /* clear his proxy connection timeout */
806         lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
807
808         /* free up his parsing allocations */
809         lws_header_table_detach(wsi);
810
811         lws_union_transition(wsi, LWSCM_WS_CLIENT);
812         wsi->state = LWSS_ESTABLISHED;
813
814         wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
815
816         /*
817          * create the frame buffer for this connection according to the
818          * size mentioned in the protocol definition.  If 0 there, then
819          * use a big default for compatibility
820          */
821         n = wsi->protocol->rx_buffer_size;
822         if (!n)
823                 n = LWS_MAX_SOCKET_IO_BUF;
824         n += LWS_PRE;
825         wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
826         if (!wsi->u.ws.rx_ubuf) {
827                 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
828                 goto bail2;
829         }
830        wsi->u.ws.rx_ubuf_alloc = n;
831         lwsl_info("Allocating client RX buffer %d\n", n);
832
833         if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF, (const char *)&n,
834                        sizeof n)) {
835                 lwsl_warn("Failed to set SNDBUF to %d", n);
836                 goto bail3;
837         }
838
839         lwsl_debug("handshake OK for protocol %s\n", wsi->protocol->name);
840
841         /* call him back to inform him he is up */
842
843         if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_ESTABLISHED,
844                                     wsi->user_space, NULL, 0))
845                 goto bail3;
846 #ifndef LWS_NO_EXTENSIONS
847         /*
848          * inform all extensions, not just active ones since they
849          * already know
850          */
851         ext = context->extensions;
852
853         while (ext && ext->callback) {
854                 v = NULL;
855                 for (n = 0; n < wsi->count_act_ext; n++)
856                         if (wsi->active_extensions[n] == ext)
857                                 v = wsi->act_ext_user[n];
858
859                 ext->callback(context, ext, wsi,
860                           LWS_EXT_CB_ANY_WSI_ESTABLISHED, v, NULL, 0);
861                 ext++;
862         }
863 #endif
864
865         return 0;
866
867 bail3:
868         close_reason = LWS_CLOSE_STATUS_NOSTATUS;
869
870 bail2:
871         if (wsi->protocol && wsi->state == LWSS_ESTABLISHED) {
872                 if (isErrorCodeReceived && p) {
873                         wsi->protocol->callback(wsi,
874                                 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
875                                                 wsi->user_space, p,
876                                                 (unsigned int)strlen(p));
877                 } else {
878                         wsi->protocol->callback(wsi,
879                                 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
880                                                 wsi->user_space, NULL, 0);
881                 }
882         }
883
884         lwsl_info("closing connection due to bail2 connection error\n");
885
886         /* closing will free up his parsing allocations */
887         lws_close_free_wsi(wsi, close_reason);
888
889         return 1;
890 }
891
892
893 char *
894 lws_generate_client_handshake(struct lws *wsi, char *pkt)
895 {
896         char buf[128], hash[20], key_b64[40], *p = pkt;
897         struct lws_context *context = wsi->context;
898         int n;
899 #ifndef LWS_NO_EXTENSIONS
900         const struct lws_extension *ext;
901         int ext_count = 0;
902 #endif
903
904         /*
905          * create the random key
906          */
907         n = lws_get_random(context, hash, 16);
908         if (n != 16) {
909                 lwsl_err("Unable to read from random dev %s\n",
910                          SYSTEM_RANDOM_FILEPATH);
911                 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
912                 return NULL;
913         }
914
915         lws_b64_encode_string(hash, 16, key_b64, sizeof(key_b64));
916
917         /*
918          * 00 example client handshake
919          *
920          * GET /socket.io/websocket HTTP/1.1
921          * Upgrade: WebSocket
922          * Connection: Upgrade
923          * Host: 127.0.0.1:9999
924          * Origin: http://127.0.0.1
925          * Sec-WebSocket-Key1: 1 0 2#0W 9 89 7  92 ^
926          * Sec-WebSocket-Key2: 7 7Y 4328 B2v[8(z1
927          * Cookie: socketio=websocket
928          *
929          * (Á®Ä0¶†≥
930          *
931          * 04 example client handshake
932          *
933          * GET /chat HTTP/1.1
934          * Host: server.example.com
935          * Upgrade: websocket
936          * Connection: Upgrade
937          * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
938          * Sec-WebSocket-Origin: http://example.com
939          * Sec-WebSocket-Protocol: chat, superchat
940          * Sec-WebSocket-Version: 4
941          */
942
943         p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a",
944                      lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_URI));
945
946         p += sprintf(p, "Pragma: no-cache\x0d\x0a"
947                         "Cache-Control: no-cache\x0d\x0a");
948
949         p += sprintf(p, "Host: %s\x0d\x0a",
950                      lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_HOST));
951         p += sprintf(p, "Upgrade: websocket\x0d\x0a"
952                         "Connection: Upgrade\x0d\x0a"
953                         "Sec-WebSocket-Key: ");
954         strcpy(p, key_b64);
955         p += strlen(key_b64);
956         p += sprintf(p, "\x0d\x0a");
957         if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN))
958                 p += sprintf(p, "Origin: http://%s\x0d\x0a",
959                              lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN));
960
961         if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS))
962                 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
963                      lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS));
964
965         /* tell the server what extensions we could support */
966
967 #ifndef LWS_NO_EXTENSIONS
968         ext = context->extensions;
969         while (ext && ext->callback) {
970                 n = lws_ext_cb_all_exts(context, wsi,
971                            LWS_EXT_CB_CHECK_OK_TO_PROPOSE_EXTENSION,
972                            (char *)ext->name, 0);
973                 if (n) { /* an extension vetos us */
974                         lwsl_ext("ext %s vetoed\n", (char *)ext->name);
975                         ext++;
976                         continue;
977                 }
978                 n = context->protocols[0].callback(wsi,
979                         LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
980                                 wsi->user_space, (char *)ext->name, 0);
981
982                 /*
983                  * zero return from callback means
984                  * go ahead and allow the extension,
985                  * it's what we get if the callback is
986                  * unhandled
987                  */
988
989                 if (n) {
990                         ext++;
991                         continue;
992                 }
993
994                 /* apply it */
995
996                 if (ext_count)
997                         *p++ = ',';
998                 else
999                         p += sprintf(p, "Sec-WebSocket-Extensions: ");
1000
1001                 p += sprintf(p, "%s", ext->client_offer);
1002                 ext_count++;
1003
1004                 ext++;
1005         }
1006         if (ext_count)
1007                 p += sprintf(p, "\x0d\x0a");
1008 #endif
1009
1010         if (wsi->ietf_spec_revision)
1011                 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
1012                              wsi->ietf_spec_revision);
1013
1014         /* give userland a chance to append, eg, cookies */
1015
1016         context->protocols[0].callback(wsi, LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
1017                                 wsi->user_space, &p, (pkt + LWS_MAX_SOCKET_IO_BUF) - p - 12);
1018
1019         p += sprintf(p, "\x0d\x0a");
1020
1021         /* prepare the expected server accept response */
1022
1023         key_b64[39] = '\0'; /* enforce composed length below buf sizeof */
1024         n = sprintf(buf, "%s258EAFA5-E914-47DA-95CA-C5AB0DC85B11", key_b64);
1025
1026         lws_SHA1((unsigned char *)buf, n, (unsigned char *)hash);
1027
1028         lws_b64_encode_string(hash, 20,
1029                               wsi->u.hdr.ah->initial_handshake_hash_base64,
1030                               sizeof(wsi->u.hdr.ah->initial_handshake_hash_base64));
1031
1032         return p;
1033 }
1034