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