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