documentation convert to doxygen
[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, context->pt_serv_buf_size, 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                         lws_ssl_client_bio_create(wsi);
153
154                 if (wsi->use_ssl) {
155                         n = lws_ssl_client_connect1(wsi);
156                         if (!n)
157                                 return 0;
158                         if (n < 0)
159                                 goto bail3;
160                 } else
161                         wsi->ssl = NULL;
162
163                 /* fallthru */
164
165         case LWSCM_WSCL_WAITING_SSL:
166
167                 if (wsi->use_ssl) {
168                         n = lws_ssl_client_connect2(wsi);
169                         if (!n)
170                                 return 0;
171                         if (n < 0)
172                                 goto bail3;
173                 } else
174                         wsi->ssl = NULL;
175 #endif
176
177                 wsi->mode = LWSCM_WSCL_ISSUE_HANDSHAKE2;
178                 lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND,
179                                 context->timeout_secs);
180
181                 /* fallthru */
182
183         case LWSCM_WSCL_ISSUE_HANDSHAKE2:
184                 p = lws_generate_client_handshake(wsi, p);
185                 if (p == NULL) {
186                         lwsl_err("Failed to generate handshake for client\n");
187                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
188                         return 0;
189                 }
190
191                 /* send our request to the server */
192
193                 lws_latency_pre(context, wsi);
194
195                 n = lws_ssl_capable_write(wsi, (unsigned char *)sb, p - sb);
196                 lws_latency(context, wsi, "send lws_issue_raw", n,
197                             n == p - sb);
198                 switch (n) {
199                 case LWS_SSL_CAPABLE_ERROR:
200                         lwsl_debug("ERROR writing to client socket\n");
201                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
202                         return 0;
203                 case LWS_SSL_CAPABLE_MORE_SERVICE:
204                         lws_callback_on_writable(wsi);
205                         break;
206                 }
207
208                 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
209                 wsi->u.hdr.lextable_pos = 0;
210                 wsi->mode = LWSCM_WSCL_WAITING_SERVER_REPLY;
211                 lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE,
212                                 context->timeout_secs);
213                 break;
214
215         case LWSCM_WSCL_WAITING_SERVER_REPLY:
216
217                 /* handle server hung up on us */
218
219                 if (pollfd->revents & LWS_POLLHUP) {
220
221                         lwsl_debug("Server connection %p (fd=%d) dead\n",
222                                 (void *)wsi, pollfd->fd);
223
224                         goto bail3;
225                 }
226
227                 if (!(pollfd->revents & LWS_POLLIN))
228                         break;
229
230                 /* interpret the server response */
231
232                 /*
233                  *  HTTP/1.1 101 Switching Protocols
234                  *  Upgrade: websocket
235                  *  Connection: Upgrade
236                  *  Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
237                  *  Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
238                  *  Sec-WebSocket-Protocol: chat
239                  */
240
241                 /*
242                  * we have to take some care here to only take from the
243                  * socket bytewise.  The browser may (and has been seen to
244                  * in the case that onopen() performs websocket traffic)
245                  * coalesce both handshake response and websocket traffic
246                  * in one packet, since at that point the connection is
247                  * definitively ready from browser pov.
248                  */
249                 len = 1;
250                 while (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE &&
251                        len > 0) {
252                         n = lws_ssl_capable_read(wsi, &c, 1);
253                         lws_latency(context, wsi, "send lws_issue_raw", n,
254                                     n == 1);
255                         switch (n) {
256                         case 0:
257                         case LWS_SSL_CAPABLE_ERROR:
258                                 goto bail3;
259                         case LWS_SSL_CAPABLE_MORE_SERVICE:
260                                 return 0;
261                         }
262
263                         if (lws_parse(wsi, c)) {
264                                 lwsl_warn("problems parsing header\n");
265                                 goto bail3;
266                         }
267                 }
268
269                 /*
270                  * hs may also be coming in multiple packets, there is a 5-sec
271                  * libwebsocket timeout still active here too, so if parsing did
272                  * not complete just wait for next packet coming in this state
273                  */
274
275                 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
276                         break;
277
278                 /*
279                  * otherwise deal with the handshake.  If there's any
280                  * packet traffic already arrived we'll trigger poll() again
281                  * right away and deal with it that way
282                  */
283
284                 return lws_client_interpret_server_handshake(wsi);
285
286 bail3:
287                 lwsl_info("closing conn at LWS_CONNMODE...SERVER_REPLY\n");
288                 wsi->vhost->protocols[0].callback(wsi,
289                         LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
290                                         wsi->user_space, NULL, 0);
291                 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
292                 return -1;
293
294         case LWSCM_WSCL_WAITING_EXTENSION_CONNECT:
295                 lwsl_ext("LWSCM_WSCL_WAITING_EXTENSION_CONNECT\n");
296                 break;
297
298         case LWSCM_WSCL_PENDING_CANDIDATE_CHILD:
299                 lwsl_ext("LWSCM_WSCL_PENDING_CANDIDATE_CHILD\n");
300                 break;
301         default:
302                 break;
303         }
304
305         return 0;
306 }
307
308 /*
309  * In-place str to lower case
310  */
311
312 static void
313 strtolower(char *s)
314 {
315         while (*s) {
316                 *s = tolower((int)*s);
317                 s++;
318         }
319 }
320
321 int LWS_WARN_UNUSED_RESULT
322 lws_http_transaction_completed_client(struct lws *wsi)
323 {
324         lwsl_debug("%s: wsi %p\n", __func__, wsi);
325         /* if we can't go back to accept new headers, drop the connection */
326         if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
327                 lwsl_info("%s: %p: close connection\n", __func__, wsi);
328                 return 1;
329         }
330
331         /* otherwise set ourselves up ready to go again */
332         wsi->state = LWSS_CLIENT_HTTP_ESTABLISHED;
333         wsi->mode = LWSCM_HTTP_CLIENT_ACCEPTED;
334         wsi->u.http.content_length = 0;
335         wsi->hdr_parsing_completed = 0;
336
337         /* He asked for it to stay alive indefinitely */
338         lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
339
340         /*
341          * As client, nothing new is going to come until we ask for it
342          * we can drop the ah, if any
343          */
344         if (wsi->u.hdr.ah) {
345                 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
346                 lws_header_table_detach(wsi, 0);
347         }
348
349         /* If we're (re)starting on headers, need other implied init */
350         wsi->u.hdr.ues = URIES_IDLE;
351
352         lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
353
354         return 0;
355 }
356
357 int
358 lws_client_interpret_server_handshake(struct lws *wsi)
359 {
360         int n, len, okay = 0, isErrorCodeReceived = 0, port = 0, ssl = 0;
361         int close_reason = LWS_CLOSE_STATUS_PROTOCOL_ERR;
362         struct lws_context *context = wsi->context;
363         const char *pc, *prot, *ads = NULL, *path;
364         struct allocated_headers *ah;
365         char *p;
366 #ifndef LWS_NO_EXTENSIONS
367         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
368         char *sb = (char *)&pt->serv_buf[0];
369         const struct lws_ext_options *opts;
370         const struct lws_extension *ext;
371         char ext_name[128];
372         const char *c, *a;
373         char ignore;
374         int more = 1;
375         void *v;
376 #endif
377
378         if (!wsi->do_ws) {
379                 /* we are being an http client...
380                  */
381                 ah = wsi->u.hdr.ah;
382                 lws_union_transition(wsi, LWSCM_HTTP_CLIENT_ACCEPTED);
383                 wsi->state = LWSS_CLIENT_HTTP_ESTABLISHED;
384                 wsi->u.http.ah = ah;
385         }
386
387         /*
388          * well, what the server sent looked reasonable for syntax.
389          * Now let's confirm it sent all the necessary headers
390          *
391          * http (non-ws) client will expect something like this
392          *
393          * HTTP/1.0.200
394          * server:.libwebsockets
395          * content-type:.text/html
396          * content-length:.17703
397          * set-cookie:.test=LWS_1456736240_336776_COOKIE;Max-Age=360000
398          *
399          *
400          *
401          */
402
403         wsi->u.http.connection_type = HTTP_CONNECTION_KEEP_ALIVE;
404         p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP);
405         if (wsi->do_ws && !p) {
406                 lwsl_info("no URI\n");
407                 goto bail3;
408         }
409         if (!p) {
410                 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP1_0);
411                 wsi->u.http.connection_type = HTTP_CONNECTION_CLOSE;
412         }
413         if (!p) {
414                 lwsl_info("no URI\n");
415                 goto bail3;
416         }
417         n = atoi(p);
418         if (n == 301 || n == 302 || n == 303 || n == 307 || n == 308) {
419                 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_LOCATION);
420                 if (!p)
421                         goto bail3;
422
423                 if (lws_parse_uri(p, &prot, &ads, &port, &path))
424                         goto bail3;
425
426                 if (!strcmp(prot, "wss://") || !strcmp(prot, "https://"))
427                         ssl = 1;
428
429                 if (lws_client_reset(wsi, ssl, ads, port, path, ads)) {
430                         lwsl_err("Redirect failed\n");
431                         goto bail3;
432                 }
433                 return 0;
434         }
435
436         if (!wsi->do_ws) {
437                 if (n != 200) {
438                         lwsl_notice("Connection failed with code %d", n);
439                         goto bail2;
440                 }
441
442 #ifdef LWS_WITH_HTTP_PROXY
443                 wsi->perform_rewrite = 0;
444                 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
445                         if (!strncmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE),
446                                      "text/html", 9))
447                                 wsi->perform_rewrite = 1;
448                 }
449 #endif
450
451                 /* allocate the per-connection user memory (if any) */
452                 if (lws_ensure_user_space(wsi)) {
453                         lwsl_err("Problem allocating wsi user mem\n");
454                         goto bail2;
455                 }
456
457                 /* he may choose to send us stuff in chunked transfer-coding */
458                 wsi->chunked = 0;
459                 wsi->chunk_remaining = 0; /* ie, next thing is chunk size */
460                 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_TRANSFER_ENCODING)) {
461                         wsi->chunked = !strcmp(lws_hdr_simple_ptr(wsi,
462                                                WSI_TOKEN_HTTP_TRANSFER_ENCODING),
463                                         "chunked");
464                         /* first thing is hex, after payload there is crlf */
465                         wsi->chunk_parser = ELCP_HEX;
466                 }
467
468                 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
469                         wsi->u.http.content_length =
470                                         atoi(lws_hdr_simple_ptr(wsi,
471                                                 WSI_TOKEN_HTTP_CONTENT_LENGTH));
472                         lwsl_notice("%s: incoming content length %d\n", __func__,
473                                         wsi->u.http.content_length);
474                         wsi->u.http.content_remain = wsi->u.http.content_length;
475                 } else /* can't do 1.1 without a content length or chunked */
476                         if (!wsi->chunked)
477                                 wsi->u.http.connection_type = HTTP_CONNECTION_CLOSE;
478
479                 /*
480                  * we seem to be good to go, give client last chance to check
481                  * headers and OK it
482                  */
483                 if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH,
484                                             wsi->user_space, NULL, 0))
485                         goto bail2;
486
487                 /* clear his proxy connection timeout */
488                 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
489
490                 wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
491
492                 /* call him back to inform him he is up */
493                 if (wsi->protocol->callback(wsi,
494                                             LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP,
495                                             wsi->user_space, NULL, 0))
496                         goto bail3;
497
498                 /* free up his parsing allocations */
499                 lws_header_table_detach(wsi, 0);
500
501                 lwsl_notice("%s: client connection up\n", __func__);
502
503                 return 0;
504         }
505
506         if (lws_hdr_total_length(wsi, WSI_TOKEN_ACCEPT) == 0) {
507                 lwsl_info("no ACCEPT\n");
508                 isErrorCodeReceived = 1;
509                 goto bail3;
510         }
511
512         if (p && strncmp(p, "101", 3)) {
513                 lwsl_warn(
514                        "lws_client_handshake: got bad HTTP response '%s'\n", p);
515                 goto bail3;
516         }
517
518         p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE);
519         if (!p) {
520                 lwsl_info("no UPGRADE\n");
521                 goto bail3;
522         }
523         strtolower(p);
524         if (strcmp(p, "websocket")) {
525                 lwsl_warn(
526                       "lws_client_handshake: got bad Upgrade header '%s'\n", p);
527                 goto bail3;
528         }
529
530         p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_CONNECTION);
531         if (!p) {
532                 lwsl_info("no Connection hdr\n");
533                 goto bail3;
534         }
535         strtolower(p);
536         if (strcmp(p, "upgrade")) {
537                 lwsl_warn("lws_client_int_s_hs: bad header %s\n", p);
538                 goto bail3;
539         }
540
541         pc = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);
542         if (!pc) {
543                 lwsl_parser("lws_client_int_s_hs: no protocol list\n");
544         } else
545                 lwsl_parser("lws_client_int_s_hs: protocol list '%s'\n", pc);
546
547         /*
548          * confirm the protocol the server wants to talk was in the list
549          * of protocols we offered
550          */
551
552         len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
553         if (!len) {
554                 lwsl_info("lws_client_int_s_hs: WSI_TOKEN_PROTOCOL is null\n");
555                 /*
556                  * no protocol name to work from,
557                  * default to first protocol
558                  */
559                 wsi->protocol = &wsi->vhost->protocols[0];
560                 goto check_extensions;
561         }
562
563         p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL);
564         len = strlen(p);
565
566         while (pc && *pc && !okay) {
567                 if (!strncmp(pc, p, len) &&
568                     (pc[len] == ',' || pc[len] == '\0')) {
569                         okay = 1;
570                         continue;
571                 }
572                 while (*pc && *pc++ != ',')
573                         ;
574                 while (*pc && *pc == ' ')
575                         pc++;
576         }
577
578         if (!okay) {
579                 lwsl_err("lws_client_int_s_hs: got bad protocol %s\n", p);
580                 goto bail2;
581         }
582
583         /*
584          * identify the selected protocol struct and set it
585          */
586         n = 0;
587         wsi->protocol = NULL;
588         while (wsi->vhost->protocols[n].callback && !wsi->protocol) {
589                 if (strcmp(p, wsi->vhost->protocols[n].name) == 0) {
590                         wsi->protocol = &wsi->vhost->protocols[n];
591                         break;
592                 }
593                 n++;
594         }
595
596         if (wsi->protocol == NULL) {
597                 lwsl_err("lws_client_int_s_hs: fail protocol %s\n", p);
598                 goto bail2;
599         }
600
601
602 check_extensions:
603 #ifndef LWS_NO_EXTENSIONS
604         /* instantiate the accepted extensions */
605
606         if (!lws_hdr_total_length(wsi, WSI_TOKEN_EXTENSIONS)) {
607                 lwsl_ext("no client extensions allowed by server\n");
608                 goto check_accept;
609         }
610
611         /*
612          * break down the list of server accepted extensions
613          * and go through matching them or identifying bogons
614          */
615
616         if (lws_hdr_copy(wsi, sb, context->pt_serv_buf_size, WSI_TOKEN_EXTENSIONS) < 0) {
617                 lwsl_warn("ext list from server failed to copy\n");
618                 goto bail2;
619         }
620
621         c = sb;
622         n = 0;
623         ignore = 0;
624         a = NULL;
625         while (more) {
626
627                 if (*c && (*c != ',' && *c != '\t')) {
628                         if (*c == ';') {
629                                 ignore = 1;
630                                 if (!a)
631                                         a = c + 1;
632                         }
633                         if (ignore || *c == ' ') {
634                                 c++;
635                                 continue;
636                         }
637
638                         ext_name[n] = *c++;
639                         if (n < sizeof(ext_name) - 1)
640                                 n++;
641                         continue;
642                 }
643                 ext_name[n] = '\0';
644                 ignore = 0;
645                 if (!*c)
646                         more = 0;
647                 else {
648                         c++;
649                         if (!n)
650                                 continue;
651                 }
652
653                 /* check we actually support it */
654
655                 lwsl_notice("checking client ext %s\n", ext_name);
656
657                 n = 0;
658                 ext = wsi->vhost->extensions;
659                 while (ext && ext->callback) {
660                         if (strcmp(ext_name, ext->name)) {
661                                 ext++;
662                                 continue;
663                         }
664
665                         n = 1;
666                         lwsl_notice("instantiating client ext %s\n", ext_name);
667
668                         /* instantiate the extension on this conn */
669
670                         wsi->active_extensions[wsi->count_act_ext] = ext;
671
672                         /* allow him to construct his ext instance */
673
674                         if (ext->callback(lws_get_context(wsi), ext, wsi,
675                                       LWS_EXT_CB_CLIENT_CONSTRUCT,
676                                       (void *)&wsi->act_ext_user[wsi->count_act_ext],
677                                       (void *)&opts, 0)) {
678                                 lwsl_notice(" ext %s failed construction\n", ext_name);
679                                 ext++;
680                                 continue;
681                         }
682
683                         /*
684                          * allow the user code to override ext defaults if it
685                          * wants to
686                          */
687                         ext_name[0] = '\0';
688                         if (user_callback_handle_rxflow(wsi->protocol->callback,
689                                         wsi, LWS_CALLBACK_WS_EXT_DEFAULTS,
690                                         (char *)ext->name, ext_name,
691                                         sizeof(ext_name)))
692                                 goto bail2;
693
694                         if (ext_name[0] &&
695                             lws_ext_parse_options(ext, wsi, wsi->act_ext_user[
696                                                   wsi->count_act_ext], opts, ext_name,
697                                                   strlen(ext_name))) {
698                                 lwsl_err("%s: unable to parse user defaults '%s'",
699                                          __func__, ext_name);
700                                 goto bail2;
701                         }
702
703                         /*
704                          * give the extension the server options
705                          */
706                         if (a && lws_ext_parse_options(ext, wsi,
707                                         wsi->act_ext_user[wsi->count_act_ext],
708                                         opts, a, c - a)) {
709                                 lwsl_err("%s: unable to parse remote def '%s'",
710                                          __func__, a);
711                                 goto bail2;
712                         }
713
714                         if (ext->callback(lws_get_context(wsi), ext, wsi,
715                                         LWS_EXT_CB_OPTION_CONFIRM,
716                                       wsi->act_ext_user[wsi->count_act_ext],
717                                       NULL, 0)) {
718                                 lwsl_err("%s: ext %s rejects server options %s",
719                                          ext->name, a);
720                                 goto bail2;
721                         }
722
723                         wsi->count_act_ext++;
724
725                         ext++;
726                 }
727
728                 if (n == 0) {
729                         lwsl_warn("Unknown ext '%s'!\n", ext_name);
730                         goto bail2;
731                 }
732
733                 a = NULL;
734                 n = 0;
735         }
736
737 check_accept:
738 #endif
739
740         /*
741          * Confirm his accept token is the one we precomputed
742          */
743
744         p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_ACCEPT);
745         if (strcmp(p, wsi->u.hdr.ah->initial_handshake_hash_base64)) {
746                 lwsl_warn("lws_client_int_s_hs: accept '%s' wrong vs '%s'\n", p,
747                                   wsi->u.hdr.ah->initial_handshake_hash_base64);
748                 goto bail2;
749         }
750
751         /* allocate the per-connection user memory (if any) */
752         if (lws_ensure_user_space(wsi)) {
753                 lwsl_err("Problem allocating wsi user mem\n");
754                 goto bail2;
755         }
756
757         /*
758          * we seem to be good to go, give client last chance to check
759          * headers and OK it
760          */
761         if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH,
762                                     wsi->user_space, NULL, 0))
763                 goto bail2;
764
765         /* clear his proxy connection timeout */
766         lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
767
768         /* free up his parsing allocations */
769         lws_header_table_detach(wsi, 0);
770
771         lws_union_transition(wsi, LWSCM_WS_CLIENT);
772         wsi->state = LWSS_ESTABLISHED;
773
774         wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
775
776         /*
777          * create the frame buffer for this connection according to the
778          * size mentioned in the protocol definition.  If 0 there, then
779          * use a big default for compatibility
780          */
781         n = wsi->protocol->rx_buffer_size;
782         if (!n)
783                 n = context->pt_serv_buf_size;
784         n += LWS_PRE;
785         wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
786         if (!wsi->u.ws.rx_ubuf) {
787                 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
788                 goto bail2;
789         }
790        wsi->u.ws.rx_ubuf_alloc = n;
791         lwsl_info("Allocating client RX buffer %d\n", n);
792
793         if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF, (const char *)&n,
794                        sizeof n)) {
795                 lwsl_warn("Failed to set SNDBUF to %d", n);
796                 goto bail3;
797         }
798
799         lwsl_debug("handshake OK for protocol %s\n", wsi->protocol->name);
800
801         /* call him back to inform him he is up */
802
803         if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_ESTABLISHED,
804                                     wsi->user_space, NULL, 0))
805                 goto bail3;
806 #ifndef LWS_NO_EXTENSIONS
807         /*
808          * inform all extensions, not just active ones since they
809          * already know
810          */
811         ext = wsi->vhost->extensions;
812
813         while (ext && ext->callback) {
814                 v = NULL;
815                 for (n = 0; n < wsi->count_act_ext; n++)
816                         if (wsi->active_extensions[n] == ext)
817                                 v = wsi->act_ext_user[n];
818
819                 ext->callback(context, ext, wsi,
820                           LWS_EXT_CB_ANY_WSI_ESTABLISHED, v, NULL, 0);
821                 ext++;
822         }
823 #endif
824
825         return 0;
826
827 bail3:
828         close_reason = LWS_CLOSE_STATUS_NOSTATUS;
829
830 bail2:
831         if (wsi->protocol && wsi->state == LWSS_ESTABLISHED) {
832                 if (isErrorCodeReceived && p) {
833                         wsi->protocol->callback(wsi,
834                                 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
835                                                 wsi->user_space, p,
836                                                 (unsigned int)strlen(p));
837                 } else {
838                         wsi->protocol->callback(wsi,
839                                 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
840                                                 wsi->user_space, NULL, 0);
841                 }
842         }
843
844         lwsl_info("closing connection due to bail2 connection error\n");
845
846         /* closing will free up his parsing allocations */
847         lws_close_free_wsi(wsi, close_reason);
848
849         return 1;
850 }
851
852
853 char *
854 lws_generate_client_handshake(struct lws *wsi, char *pkt)
855 {
856         char buf[128], hash[20], key_b64[40], *p = pkt;
857         struct lws_context *context = wsi->context;
858         const char *meth;
859         int n;
860 #ifndef LWS_NO_EXTENSIONS
861         const struct lws_extension *ext;
862         int ext_count = 0;
863 #endif
864
865         meth = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_METHOD);
866         if (!meth) {
867                 meth = "GET";
868                 wsi->do_ws = 1;
869         } else
870                 wsi->do_ws = 0;
871
872         if (wsi->do_ws) {
873                 /*
874                  * create the random key
875                  */
876                 n = lws_get_random(context, hash, 16);
877                 if (n != 16) {
878                         lwsl_err("Unable to read from random dev %s\n",
879                                  SYSTEM_RANDOM_FILEPATH);
880                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
881                         return NULL;
882                 }
883
884                 lws_b64_encode_string(hash, 16, key_b64, sizeof(key_b64));
885         }
886
887         /*
888          * 04 example client handshake
889          *
890          * GET /chat HTTP/1.1
891          * Host: server.example.com
892          * Upgrade: websocket
893          * Connection: Upgrade
894          * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
895          * Sec-WebSocket-Origin: http://example.com
896          * Sec-WebSocket-Protocol: chat, superchat
897          * Sec-WebSocket-Version: 4
898          */
899
900         p += sprintf(p, "%s %s HTTP/1.1\x0d\x0a", meth,
901                      lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_URI));
902
903         p += sprintf(p, "Pragma: no-cache\x0d\x0a"
904                         "Cache-Control: no-cache\x0d\x0a");
905
906         p += sprintf(p, "Host: %s\x0d\x0a",
907                      lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_HOST));
908
909         if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN))
910                 p += sprintf(p, "Origin: http://%s\x0d\x0a",
911                              lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN));
912
913         if (wsi->do_ws) {
914                 p += sprintf(p, "Upgrade: websocket\x0d\x0a"
915                                 "Connection: Upgrade\x0d\x0a"
916                                 "Sec-WebSocket-Key: ");
917                 strcpy(p, key_b64);
918                 p += strlen(key_b64);
919                 p += sprintf(p, "\x0d\x0a");
920                 if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS))
921                         p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
922                              lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS));
923
924                 /* tell the server what extensions we could support */
925
926 #ifndef LWS_NO_EXTENSIONS
927                 ext = wsi->vhost->extensions;
928                 while (ext && ext->callback) {
929                         n = lws_ext_cb_all_exts(context, wsi,
930                                    LWS_EXT_CB_CHECK_OK_TO_PROPOSE_EXTENSION,
931                                    (char *)ext->name, 0);
932                         if (n) { /* an extension vetos us */
933                                 lwsl_ext("ext %s vetoed\n", (char *)ext->name);
934                                 ext++;
935                                 continue;
936                         }
937                         n = wsi->vhost->protocols[0].callback(wsi,
938                                 LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
939                                         wsi->user_space, (char *)ext->name, 0);
940
941                         /*
942                          * zero return from callback means
943                          * go ahead and allow the extension,
944                          * it's what we get if the callback is
945                          * unhandled
946                          */
947
948                         if (n) {
949                                 ext++;
950                                 continue;
951                         }
952
953                         /* apply it */
954
955                         if (ext_count)
956                                 *p++ = ',';
957                         else
958                                 p += sprintf(p, "Sec-WebSocket-Extensions: ");
959                         p += sprintf(p, "%s", ext->client_offer);
960                         ext_count++;
961
962                         ext++;
963                 }
964                 if (ext_count)
965                         p += sprintf(p, "\x0d\x0a");
966 #endif
967
968                 if (wsi->ietf_spec_revision)
969                         p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
970                                      wsi->ietf_spec_revision);
971
972                 /* prepare the expected server accept response */
973
974                 key_b64[39] = '\0'; /* enforce composed length below buf sizeof */
975                 n = sprintf(buf, "%s258EAFA5-E914-47DA-95CA-C5AB0DC85B11", key_b64);
976
977                 lws_SHA1((unsigned char *)buf, n, (unsigned char *)hash);
978
979                 lws_b64_encode_string(hash, 20,
980                                       wsi->u.hdr.ah->initial_handshake_hash_base64,
981                                       sizeof(wsi->u.hdr.ah->initial_handshake_hash_base64));
982         }
983
984         /* give userland a chance to append, eg, cookies */
985
986         wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
987                                 wsi->user_space, &p, (pkt + context->pt_serv_buf_size) - p - 12);
988
989         p += sprintf(p, "\x0d\x0a");
990
991         return p;
992 }
993