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