coverity 181576: remove dead code to keep coverity happy
[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 %ld\n", __func__, (long)len);
41                                 lws_rxflow_cache(wsi, *buf, 0, len);
42                                 return 0;
43                         }
44                         if (wsi->u.ws.rx_draining_ext) {
45 #if !defined(LWS_NO_CLIENT)
46                                 if (wsi->mode == LWSCM_WS_CLIENT)
47                                         m = lws_client_rx_sm(wsi, 0);
48                                 else
49 #endif
50                                         m = lws_rx_sm(wsi, 0);
51                                 if (m < 0)
52                                         return -1;
53                                 continue;
54                         }
55                         /* account for what we're using in rxflow buffer */
56                         if (wsi->rxflow_buffer)
57                                 wsi->rxflow_pos++;
58
59                         if (lws_client_rx_sm(wsi, *(*buf)++)) {
60                                 lwsl_debug("client_rx_sm exited\n");
61                                 return -1;
62                         }
63                         len--;
64                 }
65                 lwsl_debug("%s: finished with %ld\n", __func__, (long)len);
66                 return 0;
67         default:
68                 break;
69         }
70
71         return 0;
72 }
73
74 LWS_VISIBLE LWS_EXTERN void
75 lws_client_http_body_pending(struct lws *wsi, int something_left_to_send)
76 {
77         wsi->client_http_body_pending = !!something_left_to_send;
78 }
79
80 int
81 lws_client_socket_service(struct lws_context *context, struct lws *wsi,
82                           struct lws_pollfd *pollfd)
83 {
84         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
85         char *p = (char *)&pt->serv_buf[0];
86         const char *cce = NULL;
87         unsigned char c;
88         char *sb = p;
89         int n = 0, len = 0;
90 #if defined(LWS_WITH_SOCKS5)
91         char conn_mode = 0, pending_timeout = 0;
92 #endif
93
94         switch (wsi->mode) {
95
96         case LWSCM_WSCL_WAITING_CONNECT:
97
98                 /*
99                  * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE
100                  * timeout protection set in client-handshake.c
101                  */
102
103                 if (!lws_client_connect_2(wsi)) {
104                         /* closed */
105                         lwsl_client("closed\n");
106                         return -1;
107                 }
108
109                 /* either still pending connection, or changed mode */
110                 return 0;
111
112 #if defined(LWS_WITH_SOCKS5)
113         /* SOCKS Greeting Reply */
114         case LWSCM_WSCL_WAITING_SOCKS_GREETING_REPLY:
115
116                 /* handle proxy hung up on us */
117
118                 if (pollfd->revents & LWS_POLLHUP) {
119
120                         lwsl_warn("SOCKS connection %p (fd=%d) dead\n",
121                                   (void *)wsi, pollfd->fd);
122
123                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
124                         return 0;
125                 }
126
127                 n = recv(wsi->desc.sockfd, sb, context->pt_serv_buf_size, 0);
128                 if (n < 0) {
129                         if (LWS_ERRNO == LWS_EAGAIN) {
130                                 lwsl_debug("SOCKS read returned EAGAIN..."
131                                         "retrying\n");
132                                 return 0;
133                         }
134
135                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
136                         lwsl_err("ERROR reading from SOCKS socket\n");
137                         return 0;
138                 }
139
140                 /* processing greeting reply */
141                 if (pt->serv_buf[0] == SOCKS_VERSION_5
142                         && pt->serv_buf[1] == SOCKS_AUTH_NO_AUTH)
143                 {
144                         lwsl_client("%s\n", "SOCKS greeting reply received "
145                                 "- No Authentication Method");
146                         socks_generate_msg(wsi, SOCKS_MSG_CONNECT, (size_t *)&len);
147
148                         conn_mode = LWSCM_WSCL_WAITING_SOCKS_CONNECT_REPLY;
149                         pending_timeout = PENDING_TIMEOUT_AWAITING_SOCKS_CONNECT_REPLY;
150                         lwsl_client("%s\n", "Sending SOCKS connect command");
151                 }
152                 else if (pt->serv_buf[0] == SOCKS_VERSION_5
153                                 && pt->serv_buf[1] == SOCKS_AUTH_USERNAME_PASSWORD)
154                 {
155                         lwsl_client("%s\n", "SOCKS greeting reply received "
156                                 "- User Name Password Method");
157                         socks_generate_msg(wsi, SOCKS_MSG_USERNAME_PASSWORD,
158                                 (size_t *)&len);
159
160                         conn_mode = LWSCM_WSCL_WAITING_SOCKS_AUTH_REPLY;
161                         pending_timeout = PENDING_TIMEOUT_AWAITING_SOCKS_AUTH_REPLY;
162                         lwsl_client("%s\n", "Sending SOCKS user/password");
163                 }
164                 else
165                 {
166                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
167                         lwsl_err("ERROR SOCKS greeting reply failed, method "
168                                 "code: %d\n", pt->serv_buf[1]);
169                         return 0;
170                 }
171
172                 n = send(wsi->desc.sockfd, (char *)pt->serv_buf, len,
173                          MSG_NOSIGNAL);
174                 if (n < 0) {
175                         lwsl_debug("ERROR writing socks command to socks proxy "
176                                 "socket\n");
177                         return 0;
178                 }
179
180                 lws_set_timeout(wsi, pending_timeout, AWAITING_TIMEOUT);
181                 wsi->mode = conn_mode;
182
183                 break;
184         /* SOCKS auth Reply */
185         case LWSCM_WSCL_WAITING_SOCKS_AUTH_REPLY:
186
187                 /* handle proxy hung up on us */
188
189                 if (pollfd->revents & LWS_POLLHUP) {
190
191                         lwsl_warn("SOCKS connection %p (fd=%d) dead\n",
192                                   (void *)wsi, pollfd->fd);
193
194                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
195                         return 0;
196                 }
197
198                 n = recv(wsi->desc.sockfd, sb, context->pt_serv_buf_size, 0);
199                 if (n < 0) {
200                         if (LWS_ERRNO == LWS_EAGAIN) {
201                                 lwsl_debug("SOCKS read returned EAGAIN... "
202                                         "retrying\n");
203                                 return 0;
204                         }
205
206                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
207                         lwsl_err("ERROR reading from socks socket\n");
208                         return 0;
209                 }
210
211                 /* processing auth reply */
212                 if (pt->serv_buf[0] == SOCKS_SUBNEGOTIATION_VERSION_1
213                         && pt->serv_buf[1] == SOCKS_SUBNEGOTIATION_STATUS_SUCCESS)
214                 {
215                         lwsl_client("%s\n", "SOCKS password reply recieved - "
216                                 "successful");
217                         socks_generate_msg(wsi, SOCKS_MSG_CONNECT, (size_t *)&len);
218
219                         conn_mode = LWSCM_WSCL_WAITING_SOCKS_CONNECT_REPLY;
220                         pending_timeout =
221                                 PENDING_TIMEOUT_AWAITING_SOCKS_CONNECT_REPLY;
222                         lwsl_client("%s\n", "Sending SOCKS connect command");
223                 }
224                 else
225                 {
226                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
227                         lwsl_err("ERROR : SOCKS user/password reply failed, "
228                                 "error code: %d\n", pt->serv_buf[1]);
229                         return 0;
230                 }
231
232                 n = send(wsi->desc.sockfd, (char *)pt->serv_buf, len,
233                          MSG_NOSIGNAL);
234                 if (n < 0) {
235                         lwsl_debug("ERROR writing connect command to SOCKS "
236                                 "socket\n");
237                         return 0;
238                 }
239
240                 lws_set_timeout(wsi, pending_timeout, AWAITING_TIMEOUT);
241                 wsi->mode = conn_mode;
242
243                 break;
244
245         /* SOCKS connect command Reply */
246         case LWSCM_WSCL_WAITING_SOCKS_CONNECT_REPLY:
247
248                 /* handle proxy hung up on us */
249
250                 if (pollfd->revents & LWS_POLLHUP) {
251
252                         lwsl_warn("SOCKS connection %p (fd=%d) dead\n",
253                                   (void *)wsi, pollfd->fd);
254
255                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
256                         return 0;
257                 }
258
259                 n = recv(wsi->desc.sockfd, sb, context->pt_serv_buf_size, 0);
260                 if (n < 0) {
261                         if (LWS_ERRNO == LWS_EAGAIN) {
262                                 lwsl_debug("SOCKS read returned EAGAIN... "
263                                         "retrying\n");
264                                 return 0;
265                         }
266
267                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
268                         lwsl_err("ERROR reading from socks socket\n");
269                         return 0;
270                 }
271
272                 /* processing connect reply */
273                 if (pt->serv_buf[0] == SOCKS_VERSION_5
274                         && pt->serv_buf[1] == SOCKS_REQUEST_REPLY_SUCCESS)
275                 {
276                         lwsl_client("%s\n", "SOCKS connect reply recieved - "
277                                 "successful");
278                 }
279                 else
280                 {
281                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
282                         lwsl_err("ERROR SOCKS connect reply failed, error "
283                                 "code: %d\n", pt->serv_buf[1]);
284                         return 0;
285                 }
286
287                 /* free stash since we are done with it */
288                 lws_free_set_NULL(wsi->u.hdr.stash);
289
290                 if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS,
291                         wsi->vhost->socks_proxy_address))
292                         goto bail3;
293                 wsi->c_port = wsi->vhost->socks_proxy_port;
294
295                 /* clear his proxy connection timeout */
296
297                 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
298
299                 goto start_ws_hanshake;
300 #endif
301         case LWSCM_WSCL_WAITING_PROXY_REPLY:
302
303                 /* handle proxy hung up on us */
304
305                 if (pollfd->revents & LWS_POLLHUP) {
306
307                         lwsl_warn("Proxy connection %p (fd=%d) dead\n",
308                                   (void *)wsi, pollfd->fd);
309
310                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
311                         return 0;
312                 }
313
314                 n = recv(wsi->desc.sockfd, sb, context->pt_serv_buf_size, 0);
315                 if (n < 0) {
316                         if (LWS_ERRNO == LWS_EAGAIN) {
317                                 lwsl_debug("Proxy read returned EAGAIN... retrying\n");
318                                 return 0;
319                         }
320
321                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
322                         lwsl_err("ERROR reading from proxy socket\n");
323                         return 0;
324                 }
325
326                 pt->serv_buf[13] = '\0';
327                 if (strcmp(sb, "HTTP/1.0 200 ") &&
328                     strcmp(sb, "HTTP/1.1 200 ")) {
329                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
330                         lwsl_err("ERROR proxy: %s\n", sb);
331                         return 0;
332                 }
333
334                 /* clear his proxy connection timeout */
335
336                 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
337
338                 /* fallthru */
339
340         case LWSCM_WSCL_ISSUE_HANDSHAKE:
341
342                 /*
343                  * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE
344                  * timeout protection set in client-handshake.c
345                  *
346                  * take care of our lws_callback_on_writable
347                  * happening at a time when there's no real connection yet
348                  */
349 #if defined(LWS_WITH_SOCKS5)
350 start_ws_hanshake:
351 #endif
352                 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0))
353                         return -1;
354
355 #ifdef LWS_OPENSSL_SUPPORT
356                 /* we can retry this... just cook the SSL BIO the first time */
357
358                 if (wsi->use_ssl && !wsi->ssl) {
359                         if (lws_ssl_client_bio_create(wsi))
360                                 return -1;
361                 }
362
363                 if (wsi->use_ssl) {
364                         n = lws_ssl_client_connect1(wsi);
365                         if (!n)
366                                 return 0;
367                         if (n < 0) {
368                                 cce = "lws_ssl_client_connect1 failed";
369                                 goto bail3;
370                         }
371                 } else
372                         wsi->ssl = NULL;
373
374                 /* fallthru */
375
376         case LWSCM_WSCL_WAITING_SSL:
377
378                 if (wsi->use_ssl) {
379                         n = lws_ssl_client_connect2(wsi);
380                         if (!n)
381                                 return 0;
382                         if (n < 0) {
383                                 cce = "lws_ssl_client_connect2 failed";
384                                 goto bail3;
385                         }
386                 } else
387                         wsi->ssl = NULL;
388 #endif
389
390                 wsi->mode = LWSCM_WSCL_ISSUE_HANDSHAKE2;
391                 lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND,
392                                 context->timeout_secs);
393
394                 /* fallthru */
395
396         case LWSCM_WSCL_ISSUE_HANDSHAKE2:
397                 p = lws_generate_client_handshake(wsi, p);
398                 if (p == NULL) {
399                         if (wsi->mode == LWSCM_RAW)
400                                 return 0;
401
402                         lwsl_err("Failed to generate handshake for client\n");
403                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
404                         return 0;
405                 }
406
407                 /* send our request to the server */
408
409                 lws_latency_pre(context, wsi);
410
411                 n = lws_ssl_capable_write(wsi, (unsigned char *)sb, p - sb);
412                 lws_latency(context, wsi, "send lws_issue_raw", n,
413                             n == p - sb);
414                 switch (n) {
415                 case LWS_SSL_CAPABLE_ERROR:
416                         lwsl_debug("ERROR writing to client socket\n");
417                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
418                         return 0;
419                 case LWS_SSL_CAPABLE_MORE_SERVICE:
420                         lws_callback_on_writable(wsi);
421                         break;
422                 }
423
424                 if (wsi->client_http_body_pending) {
425                         wsi->mode = LWSCM_WSCL_ISSUE_HTTP_BODY;
426                         lws_set_timeout(wsi, PENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD,
427                                         context->timeout_secs);
428                         /* user code must ask for writable callback */
429                         break;
430                 }
431
432                 goto client_http_body_sent;
433
434         case LWSCM_WSCL_ISSUE_HTTP_BODY:
435                 if (wsi->client_http_body_pending) {
436                         lws_set_timeout(wsi, PENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD,
437                                         context->timeout_secs);
438                         /* user code must ask for writable callback */
439                         break;
440                 }
441 client_http_body_sent:
442                 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
443                 wsi->u.hdr.lextable_pos = 0;
444                 wsi->mode = LWSCM_WSCL_WAITING_SERVER_REPLY;
445                 lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE,
446                                 context->timeout_secs);
447                 break;
448
449         case LWSCM_WSCL_WAITING_SERVER_REPLY:
450
451                 /* handle server hung up on us */
452
453                 if (pollfd->revents & LWS_POLLHUP) {
454
455                         lwsl_debug("Server connection %p (fd=%d) dead\n",
456                                 (void *)wsi, pollfd->fd);
457                         cce = "Peer hung up";
458                         goto bail3;
459                 }
460
461                 if (!(pollfd->revents & LWS_POLLIN))
462                         break;
463
464                 /* interpret the server response */
465
466                 /*
467                  *  HTTP/1.1 101 Switching Protocols
468                  *  Upgrade: websocket
469                  *  Connection: Upgrade
470                  *  Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
471                  *  Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
472                  *  Sec-WebSocket-Protocol: chat
473                  */
474
475                 /*
476                  * we have to take some care here to only take from the
477                  * socket bytewise.  The browser may (and has been seen to
478                  * in the case that onopen() performs websocket traffic)
479                  * coalesce both handshake response and websocket traffic
480                  * in one packet, since at that point the connection is
481                  * definitively ready from browser pov.
482                  */
483                 len = 1;
484                 while (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE &&
485                        len > 0) {
486                         n = lws_ssl_capable_read(wsi, &c, 1);
487                         lws_latency(context, wsi, "send lws_issue_raw", n,
488                                     n == 1);
489                         switch (n) {
490                         case 0:
491                         case LWS_SSL_CAPABLE_ERROR:
492                                 cce = "read failed";
493                                 goto bail3;
494                         case LWS_SSL_CAPABLE_MORE_SERVICE:
495                                 return 0;
496                         }
497
498                         if (lws_parse(wsi, c)) {
499                                 lwsl_warn("problems parsing header\n");
500                                 goto bail3;
501                         }
502                 }
503
504                 /*
505                  * hs may also be coming in multiple packets, there is a 5-sec
506                  * libwebsocket timeout still active here too, so if parsing did
507                  * not complete just wait for next packet coming in this state
508                  */
509
510                 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
511                         break;
512
513                 /*
514                  * otherwise deal with the handshake.  If there's any
515                  * packet traffic already arrived we'll trigger poll() again
516                  * right away and deal with it that way
517                  */
518
519                 return lws_client_interpret_server_handshake(wsi);
520
521 bail3:
522                 lwsl_info("closing conn at LWS_CONNMODE...SERVER_REPLY\n");
523                 if (cce)
524                         lwsl_info("reason: %s\n", cce);
525                 wsi->protocol->callback(wsi,
526                         LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
527                         wsi->user_space, (void *)cce, cce ? strlen(cce) : 0);
528                 wsi->already_did_cce = 1;
529                 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
530                 return -1;
531
532         case LWSCM_WSCL_WAITING_EXTENSION_CONNECT:
533                 lwsl_ext("LWSCM_WSCL_WAITING_EXTENSION_CONNECT\n");
534                 break;
535
536         case LWSCM_WSCL_PENDING_CANDIDATE_CHILD:
537                 lwsl_ext("LWSCM_WSCL_PENDING_CANDIDATE_CHILD\n");
538                 break;
539         default:
540                 break;
541         }
542
543         return 0;
544 }
545
546 /*
547  * In-place str to lower case
548  */
549
550 static void
551 strtolower(char *s)
552 {
553         while (*s) {
554 #ifdef LWS_PLAT_OPTEE
555                 int tolower_optee(int c);
556                 *s = tolower_optee((int)*s);
557 #else
558                 *s = tolower((int)*s);
559 #endif
560                 s++;
561         }
562 }
563
564 int LWS_WARN_UNUSED_RESULT
565 lws_http_transaction_completed_client(struct lws *wsi)
566 {
567         lwsl_debug("%s: wsi %p\n", __func__, wsi);
568         /* if we can't go back to accept new headers, drop the connection */
569         if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
570                 lwsl_info("%s: %p: close connection\n", __func__, wsi);
571                 return 1;
572         }
573
574         /* we don't support chained client connections yet */
575         return 1;
576 #if 0
577         /* otherwise set ourselves up ready to go again */
578         wsi->state = LWSS_CLIENT_HTTP_ESTABLISHED;
579         wsi->mode = LWSCM_HTTP_CLIENT_ACCEPTED;
580         wsi->u.http.content_length = 0;
581         wsi->hdr_parsing_completed = 0;
582
583         /* He asked for it to stay alive indefinitely */
584         lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
585
586         /*
587          * As client, nothing new is going to come until we ask for it
588          * we can drop the ah, if any
589          */
590         if (wsi->u.hdr.ah) {
591                 lws_header_table_force_to_detachable_state(wsi);
592                 lws_header_table_detach(wsi, 0);
593         }
594
595         /* If we're (re)starting on headers, need other implied init */
596         wsi->u.hdr.ues = URIES_IDLE;
597
598         lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
599
600         return 0;
601 #endif
602 }
603
604 LWS_VISIBLE LWS_EXTERN unsigned int
605 lws_http_client_http_response(struct lws *wsi)
606 {
607         if (!wsi->u.http.ah)
608                 return 0;
609
610         return wsi->u.http.ah->http_response;
611 }
612
613 int
614 lws_client_interpret_server_handshake(struct lws *wsi)
615 {
616         int n, len, okay = 0, port = 0, ssl = 0;
617         int close_reason = LWS_CLOSE_STATUS_PROTOCOL_ERR;
618         struct lws_context *context = wsi->context;
619         const char *pc, *prot, *ads = NULL, *path, *cce = NULL;
620         struct allocated_headers *ah = NULL;
621         char *p, *q;
622         char new_path[300];
623 #ifndef LWS_NO_EXTENSIONS
624         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
625         char *sb = (char *)&pt->serv_buf[0];
626         const struct lws_ext_options *opts;
627         const struct lws_extension *ext;
628         char ext_name[128];
629         const char *c, *a;
630         char ignore;
631         int more = 1;
632         void *v;
633 #endif
634
635         ah = wsi->u.hdr.ah;
636         if (!wsi->do_ws) {
637                 /* we are being an http client...
638                  */
639                 lws_union_transition(wsi, LWSCM_HTTP_CLIENT_ACCEPTED);
640                 wsi->state = LWSS_CLIENT_HTTP_ESTABLISHED;
641                 wsi->u.http.ah = ah;
642                 ah->http_response = 0;
643         }
644
645         /*
646          * well, what the server sent looked reasonable for syntax.
647          * Now let's confirm it sent all the necessary headers
648          *
649          * http (non-ws) client will expect something like this
650          *
651          * HTTP/1.0.200
652          * server:.libwebsockets
653          * content-type:.text/html
654          * content-length:.17703
655          * set-cookie:.test=LWS_1456736240_336776_COOKIE;Max-Age=360000
656          *
657          *
658          *
659          */
660
661         wsi->u.http.connection_type = HTTP_CONNECTION_KEEP_ALIVE;
662         p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP);
663         if (wsi->do_ws && !p) {
664                 lwsl_info("no URI\n");
665                 cce = "HS: URI missing";
666                 goto bail3;
667         }
668         if (!p) {
669                 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP1_0);
670                 wsi->u.http.connection_type = HTTP_CONNECTION_CLOSE;
671         }
672         if (!p) {
673                 cce = "HS: URI missing";
674                 lwsl_info("no URI\n");
675                 goto bail3;
676         }
677         n = atoi(p);
678         if (ah)
679                 ah->http_response = n;
680
681         if (n == 301 || n == 302 || n == 303 || n == 307 || n == 308) {
682                 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_LOCATION);
683                 if (!p) {
684                         cce = "HS: Redirect code but no Location";
685                         goto bail3;
686                 }
687
688                 /* Relative reference absolute path */
689                 if (p[0] == '/')
690                 {
691 #ifdef LWS_OPENSSL_SUPPORT
692                         ssl = wsi->use_ssl;
693 #endif
694                         ads = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS);
695                         port = wsi->c_port;
696                         path = p + 1; /* +1 as lws_client_reset expects leading / to be omitted */
697                 }
698                 /* Absolute (Full) URI */
699                 else if (strchr(p, ':'))
700                 {
701                         if (lws_parse_uri(p, &prot, &ads, &port, &path)) {
702                                 cce = "HS: URI did not parse";
703                                 goto bail3;
704                         }
705
706                         if (!strcmp(prot, "wss") || !strcmp(prot, "https"))
707                                 ssl = 1;
708                 }
709                 /* Relative reference relative path */
710                 else
711                 {
712                         /* This doesn't try to calculate an absolute path, that will be left to the server */
713 #ifdef LWS_OPENSSL_SUPPORT
714                         ssl = wsi->use_ssl;
715 #endif
716                         ads = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS);
717                         port = wsi->c_port;
718                         path = new_path + 1; /* +1 as lws_client_reset expects leading / to be omitted */
719                         strncpy(new_path, lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_URI), sizeof(new_path));
720                         new_path[sizeof(new_path) - 1] = '\0';
721                         q = strrchr(new_path, '/');
722                         if (q)
723                         {
724                                 strncpy(q + 1, p, sizeof(new_path) - (q - new_path) - 1);
725                                 new_path[sizeof(new_path) - 1] = '\0';
726                         }
727                         else
728                         {
729                                 path = p;
730                         }
731                 }
732
733 #ifdef LWS_OPENSSL_SUPPORT
734                 if (wsi->use_ssl && !ssl) {
735                         cce = "HS: Redirect attempted SSL downgrade";
736                         goto bail3;
737                 }
738 #endif
739
740                 if (!lws_client_reset(&wsi, ssl, ads, port, path, ads)) {
741                         /* there are two ways to fail out with NULL return...
742                          * simple, early problem where the wsi is intact, or
743                          * we went through with the reconnect attempt and the
744                          * wsi is already closed.  In the latter case, the wsi
745                          * has beet set to NULL additionally.
746                          */
747                         lwsl_err("Redirect failed\n");
748                         cce = "HS: Redirect failed";
749                         if (wsi)
750                                 goto bail3;
751
752                         return 1;
753                 }
754                 return 0;
755         }
756
757         if (!wsi->do_ws) {
758                 if (n != 200 && n != 201 && n != 304 && n != 401) {
759                         lwsl_notice("Connection failed with code %d\n", n);
760                         cce = "HS: Server unrecognized response code";
761                         goto bail2;
762                 }
763
764 #ifdef LWS_WITH_HTTP_PROXY
765                 wsi->perform_rewrite = 0;
766                 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
767                         if (!strncmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE),
768                                      "text/html", 9))
769                                 wsi->perform_rewrite = 1;
770                 }
771 #endif
772
773                 /* allocate the per-connection user memory (if any) */
774                 if (lws_ensure_user_space(wsi)) {
775                         lwsl_err("Problem allocating wsi user mem\n");
776                         cce = "HS: OOM";
777                         goto bail2;
778                 }
779
780                 /* he may choose to send us stuff in chunked transfer-coding */
781                 wsi->chunked = 0;
782                 wsi->chunk_remaining = 0; /* ie, next thing is chunk size */
783                 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_TRANSFER_ENCODING)) {
784                         wsi->chunked = !strcmp(lws_hdr_simple_ptr(wsi,
785                                                WSI_TOKEN_HTTP_TRANSFER_ENCODING),
786                                         "chunked");
787                         /* first thing is hex, after payload there is crlf */
788                         wsi->chunk_parser = ELCP_HEX;
789                 }
790
791                 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
792                         wsi->u.http.content_length =
793                                         atoll(lws_hdr_simple_ptr(wsi,
794                                                 WSI_TOKEN_HTTP_CONTENT_LENGTH));
795                         lwsl_notice("%s: incoming content length %llu\n", __func__,
796                                         (unsigned long long)wsi->u.http.content_length);
797                         wsi->u.http.content_remain = wsi->u.http.content_length;
798                 } else /* can't do 1.1 without a content length or chunked */
799                         if (!wsi->chunked)
800                                 wsi->u.http.connection_type = HTTP_CONNECTION_CLOSE;
801
802                 /*
803                  * we seem to be good to go, give client last chance to check
804                  * headers and OK it
805                  */
806                 if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH,
807                                             wsi->user_space, NULL, 0)) {
808
809                         cce = "HS: disallowed by client filter";
810                         goto bail2;
811                 }
812
813                 /* clear his proxy connection timeout */
814                 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
815
816                 wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
817
818                 /* call him back to inform him he is up */
819                 if (wsi->protocol->callback(wsi,
820                                             LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP,
821                                             wsi->user_space, NULL, 0)) {
822                         cce = "HS: disallowed at ESTABLISHED";
823                         goto bail3;
824                 }
825
826                 /* free up his parsing allocations */
827                 lws_header_table_detach(wsi, 0);
828
829                 lwsl_notice("%s: client connection up\n", __func__);
830
831                 return 0;
832         }
833
834         if (lws_hdr_total_length(wsi, WSI_TOKEN_ACCEPT) == 0) {
835                 lwsl_info("no ACCEPT\n");
836                 cce = "HS: ACCEPT missing";
837                 goto bail3;
838         }
839
840         if (p && strncmp(p, "101", 3)) {
841                 lwsl_warn(
842                        "lws_client_handshake: got bad HTTP response '%s'\n", p);
843                 cce = "HS: ws upgrade response not 101";
844                 goto bail3;
845         }
846
847         p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE);
848         if (!p) {
849                 lwsl_info("no UPGRADE\n");
850                 cce = "HS: UPGRADE missing";
851                 goto bail3;
852         }
853         strtolower(p);
854         if (strcmp(p, "websocket")) {
855                 lwsl_warn(
856                       "lws_client_handshake: got bad Upgrade header '%s'\n", p);
857                 cce = "HS: Upgrade to something other than websocket";
858                 goto bail3;
859         }
860
861         p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_CONNECTION);
862         if (!p) {
863                 lwsl_info("no Connection hdr\n");
864                 cce = "HS: CONNECTION missing";
865                 goto bail3;
866         }
867         strtolower(p);
868         if (strcmp(p, "upgrade")) {
869                 lwsl_warn("lws_client_int_s_hs: bad header %s\n", p);
870                 cce = "HS: UPGRADE malformed";
871                 goto bail3;
872         }
873
874         pc = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);
875         if (!pc) {
876                 lwsl_parser("lws_client_int_s_hs: no protocol list\n");
877         } else
878                 lwsl_parser("lws_client_int_s_hs: protocol list '%s'\n", pc);
879
880         /*
881          * confirm the protocol the server wants to talk was in the list
882          * of protocols we offered
883          */
884
885         len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
886         if (!len) {
887                 lwsl_info("lws_client_int_s_hs: WSI_TOKEN_PROTOCOL is null\n");
888                 /*
889                  * no protocol name to work from,
890                  * default to first protocol
891                  */
892                 n = 0;
893                 wsi->protocol = &wsi->vhost->protocols[0];
894                 goto check_extensions;
895         }
896
897         p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL);
898         len = strlen(p);
899
900         while (pc && *pc && !okay) {
901                 if (!strncmp(pc, p, len) &&
902                     (pc[len] == ',' || pc[len] == '\0')) {
903                         okay = 1;
904                         continue;
905                 }
906                 while (*pc && *pc++ != ',')
907                         ;
908                 while (*pc && *pc == ' ')
909                         pc++;
910         }
911
912         if (!okay) {
913                 lwsl_err("lws_client_int_s_hs: got bad protocol %s\n", p);
914                 cce = "HS: PROTOCOL malformed";
915                 goto bail2;
916         }
917
918         /*
919          * identify the selected protocol struct and set it
920          */
921         n = 0;
922         wsi->protocol = NULL;
923         while (wsi->vhost->protocols[n].callback && !wsi->protocol) {
924                 if (strcmp(p, wsi->vhost->protocols[n].name) == 0) {
925                         wsi->protocol = &wsi->vhost->protocols[n];
926                         break;
927                 }
928                 n++;
929         }
930
931         if (wsi->protocol == NULL) {
932                 lwsl_err("lws_client_int_s_hs: fail protocol %s\n", p);
933                 cce = "HS: Cannot match protocol";
934                 goto bail2;
935         }
936
937 check_extensions:
938         /*
939          * stitch protocol choice into the vh protocol linked list
940          * We always insert ourselves at the start of the list
941          *
942          * X <-> B
943          * X <-> pAn <-> pB
944          */
945         //lwsl_err("%s: pre insert vhost start wsi %p, that wsi prev == %p\n",
946         //              __func__,
947         //              wsi->vhost->same_vh_protocol_list[n],
948         //              wsi->same_vh_protocol_prev);
949         wsi->same_vh_protocol_prev = /* guy who points to us */
950                 &wsi->vhost->same_vh_protocol_list[n];
951         wsi->same_vh_protocol_next = /* old first guy is our next */
952                         wsi->vhost->same_vh_protocol_list[n];
953         /* we become the new first guy */
954         wsi->vhost->same_vh_protocol_list[n] = wsi;
955
956         if (wsi->same_vh_protocol_next)
957                 /* old first guy points back to us now */
958                 wsi->same_vh_protocol_next->same_vh_protocol_prev =
959                                 &wsi->same_vh_protocol_next;
960
961 #ifndef LWS_NO_EXTENSIONS
962         /* instantiate the accepted extensions */
963
964         if (!lws_hdr_total_length(wsi, WSI_TOKEN_EXTENSIONS)) {
965                 lwsl_ext("no client extensions allowed by server\n");
966                 goto check_accept;
967         }
968
969         /*
970          * break down the list of server accepted extensions
971          * and go through matching them or identifying bogons
972          */
973
974         if (lws_hdr_copy(wsi, sb, context->pt_serv_buf_size, WSI_TOKEN_EXTENSIONS) < 0) {
975                 lwsl_warn("ext list from server failed to copy\n");
976                 cce = "HS: EXT: list too big";
977                 goto bail2;
978         }
979
980         c = sb;
981         n = 0;
982         ignore = 0;
983         a = NULL;
984         while (more) {
985
986                 if (*c && (*c != ',' && *c != '\t')) {
987                         if (*c == ';') {
988                                 ignore = 1;
989                                 if (!a)
990                                         a = c + 1;
991                         }
992                         if (ignore || *c == ' ') {
993                                 c++;
994                                 continue;
995                         }
996
997                         ext_name[n] = *c++;
998                         if (n < sizeof(ext_name) - 1)
999                                 n++;
1000                         continue;
1001                 }
1002                 ext_name[n] = '\0';
1003                 ignore = 0;
1004                 if (!*c)
1005                         more = 0;
1006                 else {
1007                         c++;
1008                         if (!n)
1009                                 continue;
1010                 }
1011
1012                 /* check we actually support it */
1013
1014                 lwsl_notice("checking client ext %s\n", ext_name);
1015
1016                 n = 0;
1017                 ext = wsi->vhost->extensions;
1018                 while (ext && ext->callback) {
1019                         if (strcmp(ext_name, ext->name)) {
1020                                 ext++;
1021                                 continue;
1022                         }
1023
1024                         n = 1;
1025                         lwsl_notice("instantiating client ext %s\n", ext_name);
1026
1027                         /* instantiate the extension on this conn */
1028
1029                         wsi->active_extensions[wsi->count_act_ext] = ext;
1030
1031                         /* allow him to construct his ext instance */
1032
1033                         if (ext->callback(lws_get_context(wsi), ext, wsi,
1034                                       LWS_EXT_CB_CLIENT_CONSTRUCT,
1035                                       (void *)&wsi->act_ext_user[wsi->count_act_ext],
1036                                       (void *)&opts, 0)) {
1037                                 lwsl_notice(" ext %s failed construction\n", ext_name);
1038                                 ext++;
1039                                 continue;
1040                         }
1041
1042                         /*
1043                          * allow the user code to override ext defaults if it
1044                          * wants to
1045                          */
1046                         ext_name[0] = '\0';
1047                         if (user_callback_handle_rxflow(wsi->protocol->callback,
1048                                         wsi, LWS_CALLBACK_WS_EXT_DEFAULTS,
1049                                         (char *)ext->name, ext_name,
1050                                         sizeof(ext_name))) {
1051                                 cce = "HS: EXT: failed setting defaults";
1052                                 goto bail2;
1053                         }
1054
1055                         if (ext_name[0] &&
1056                             lws_ext_parse_options(ext, wsi, wsi->act_ext_user[
1057                                                   wsi->count_act_ext], opts, ext_name,
1058                                                   strlen(ext_name))) {
1059                                 lwsl_err("%s: unable to parse user defaults '%s'",
1060                                          __func__, ext_name);
1061                                 cce = "HS: EXT: failed parsing defaults";
1062                                 goto bail2;
1063                         }
1064
1065                         /*
1066                          * give the extension the server options
1067                          */
1068                         if (a && lws_ext_parse_options(ext, wsi,
1069                                         wsi->act_ext_user[wsi->count_act_ext],
1070                                         opts, a, c - a)) {
1071                                 lwsl_err("%s: unable to parse remote def '%s'",
1072                                          __func__, a);
1073                                 cce = "HS: EXT: failed parsing options";
1074                                 goto bail2;
1075                         }
1076
1077                         if (ext->callback(lws_get_context(wsi), ext, wsi,
1078                                         LWS_EXT_CB_OPTION_CONFIRM,
1079                                       wsi->act_ext_user[wsi->count_act_ext],
1080                                       NULL, 0)) {
1081                                 lwsl_err("%s: ext %s rejects server options %s",
1082                                          __func__, ext->name, a);
1083                                 cce = "HS: EXT: Rejects server options";
1084                                 goto bail2;
1085                         }
1086
1087                         wsi->count_act_ext++;
1088
1089                         ext++;
1090                 }
1091
1092                 if (n == 0) {
1093                         lwsl_warn("Unknown ext '%s'!\n", ext_name);
1094                         cce = "HS: EXT: unknown ext";
1095                         goto bail2;
1096                 }
1097
1098                 a = NULL;
1099                 n = 0;
1100         }
1101
1102 check_accept:
1103 #endif
1104
1105         /*
1106          * Confirm his accept token is the one we precomputed
1107          */
1108
1109         p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_ACCEPT);
1110         if (strcmp(p, wsi->u.hdr.ah->initial_handshake_hash_base64)) {
1111                 lwsl_warn("lws_client_int_s_hs: accept '%s' wrong vs '%s'\n", p,
1112                                   wsi->u.hdr.ah->initial_handshake_hash_base64);
1113                 cce = "HS: Accept hash wrong";
1114                 goto bail2;
1115         }
1116
1117         /* allocate the per-connection user memory (if any) */
1118         if (lws_ensure_user_space(wsi)) {
1119                 lwsl_err("Problem allocating wsi user mem\n");
1120                 cce = "HS: OOM";
1121                 goto bail2;
1122         }
1123
1124         /*
1125          * we seem to be good to go, give client last chance to check
1126          * headers and OK it
1127          */
1128         if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH,
1129                                     wsi->user_space, NULL, 0)) {
1130                 cce = "HS: Rejected by filter cb";
1131                 goto bail2;
1132         }
1133
1134         /* clear his proxy connection timeout */
1135         lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1136
1137         /* free up his parsing allocations */
1138         lws_header_table_detach(wsi, 0);
1139
1140         lws_union_transition(wsi, LWSCM_WS_CLIENT);
1141         wsi->state = LWSS_ESTABLISHED;
1142         lws_restart_ws_ping_pong_timer(wsi);
1143
1144         wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1145
1146         /*
1147          * create the frame buffer for this connection according to the
1148          * size mentioned in the protocol definition.  If 0 there, then
1149          * use a big default for compatibility
1150          */
1151         n = wsi->protocol->rx_buffer_size;
1152         if (!n)
1153                 n = context->pt_serv_buf_size;
1154         n += LWS_PRE;
1155         wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
1156         if (!wsi->u.ws.rx_ubuf) {
1157                 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
1158                 cce = "HS: OOM";
1159                 goto bail2;
1160         }
1161        wsi->u.ws.rx_ubuf_alloc = n;
1162         lwsl_info("Allocating client RX buffer %d\n", n);
1163
1164 #if !defined(LWS_WITH_ESP32)
1165         if (setsockopt(wsi->desc.sockfd, SOL_SOCKET, SO_SNDBUF, (const char *)&n,
1166                        sizeof n)) {
1167                 lwsl_warn("Failed to set SNDBUF to %d", n);
1168                 cce = "HS: SO_SNDBUF failed";
1169                 goto bail3;
1170         }
1171 #endif
1172
1173         lwsl_debug("handshake OK for protocol %s\n", wsi->protocol->name);
1174
1175         /* call him back to inform him he is up */
1176
1177         if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_ESTABLISHED,
1178                                     wsi->user_space, NULL, 0)) {
1179                 cce = "HS: Rejected at CLIENT_ESTABLISHED";
1180                 goto bail3;
1181         }
1182 #ifndef LWS_NO_EXTENSIONS
1183         /*
1184          * inform all extensions, not just active ones since they
1185          * already know
1186          */
1187         ext = wsi->vhost->extensions;
1188
1189         while (ext && ext->callback) {
1190                 v = NULL;
1191                 for (n = 0; n < wsi->count_act_ext; n++)
1192                         if (wsi->active_extensions[n] == ext)
1193                                 v = wsi->act_ext_user[n];
1194
1195                 ext->callback(context, ext, wsi,
1196                           LWS_EXT_CB_ANY_WSI_ESTABLISHED, v, NULL, 0);
1197                 ext++;
1198         }
1199 #endif
1200
1201         return 0;
1202
1203 bail3:
1204         close_reason = LWS_CLOSE_STATUS_NOSTATUS;
1205
1206 bail2:
1207         if (wsi->protocol)
1208                 wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
1209                                 wsi->user_space, (void *)cce,
1210                                 (unsigned int)strlen(cce));
1211         wsi->already_did_cce = 1;
1212
1213         lwsl_info("closing connection due to bail2 connection error\n");
1214
1215         /* closing will free up his parsing allocations */
1216         lws_close_free_wsi(wsi, close_reason);
1217
1218         return 1;
1219 }
1220
1221
1222 char *
1223 lws_generate_client_handshake(struct lws *wsi, char *pkt)
1224 {
1225         char buf[128], hash[20], key_b64[40], *p = pkt;
1226         struct lws_context *context = wsi->context;
1227         const char *meth;
1228         int n;
1229 #ifndef LWS_NO_EXTENSIONS
1230         const struct lws_extension *ext;
1231         int ext_count = 0;
1232 #endif
1233         const char *pp = lws_hdr_simple_ptr(wsi,
1234                                 _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);
1235
1236         meth = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_METHOD);
1237         if (!meth) {
1238                 meth = "GET";
1239                 wsi->do_ws = 1;
1240         } else {
1241                 wsi->do_ws = 0;
1242         }
1243
1244         if (!strcmp(meth, "RAW")) {
1245                 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1246                 lwsl_notice("client transition to raw\n");
1247
1248                 if (pp) {
1249                         const struct lws_protocols *pr;
1250
1251                         pr = lws_vhost_name_to_protocol(wsi->vhost, pp);
1252
1253                         if (!pr) {
1254                                 lwsl_err("protocol %s not enabled on vhost\n",
1255                                          pp);
1256                                 return NULL;
1257                         }
1258
1259                         lws_bind_protocol(wsi, pr);
1260                 }
1261
1262                 if ((wsi->protocol->callback)(wsi,
1263                                 LWS_CALLBACK_RAW_ADOPT,
1264                                 wsi->user_space, NULL, 0))
1265                         return NULL;
1266
1267                 lws_header_table_force_to_detachable_state(wsi);
1268                 lws_union_transition(wsi, LWSCM_RAW);
1269                 lws_header_table_detach(wsi, 1);
1270
1271                 return NULL;
1272         }
1273
1274         if (wsi->do_ws) {
1275                 /*
1276                  * create the random key
1277                  */
1278                 n = lws_get_random(context, hash, 16);
1279                 if (n != 16) {
1280                         lwsl_err("Unable to read from random dev %s\n",
1281                                  SYSTEM_RANDOM_FILEPATH);
1282                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1283                         return NULL;
1284                 }
1285
1286                 lws_b64_encode_string(hash, 16, key_b64, sizeof(key_b64));
1287         }
1288
1289         /*
1290          * 04 example client handshake
1291          *
1292          * GET /chat HTTP/1.1
1293          * Host: server.example.com
1294          * Upgrade: websocket
1295          * Connection: Upgrade
1296          * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
1297          * Sec-WebSocket-Origin: http://example.com
1298          * Sec-WebSocket-Protocol: chat, superchat
1299          * Sec-WebSocket-Version: 4
1300          */
1301
1302         p += sprintf(p, "%s %s HTTP/1.1\x0d\x0a", meth,
1303                      lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_URI));
1304
1305         p += sprintf(p, "Pragma: no-cache\x0d\x0a"
1306                         "Cache-Control: no-cache\x0d\x0a");
1307
1308         p += sprintf(p, "Host: %s\x0d\x0a",
1309                      lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_HOST));
1310
1311         if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN)) {
1312                 if (lws_check_opt(context->options, LWS_SERVER_OPTION_JUST_USE_RAW_ORIGIN))
1313                         p += sprintf(p, "Origin: %s\x0d\x0a",
1314                                      lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN));
1315                 else
1316                         p += sprintf(p, "Origin: http://%s\x0d\x0a",
1317                                      lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN));
1318         }
1319
1320         if (wsi->do_ws) {
1321                 p += sprintf(p, "Upgrade: websocket\x0d\x0a"
1322                                 "Connection: Upgrade\x0d\x0a"
1323                                 "Sec-WebSocket-Key: ");
1324                 strcpy(p, key_b64);
1325                 p += strlen(key_b64);
1326                 p += sprintf(p, "\x0d\x0a");
1327                 if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS))
1328                         p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
1329                              lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS));
1330
1331                 /* tell the server what extensions we could support */
1332
1333 #ifndef LWS_NO_EXTENSIONS
1334                 ext = wsi->vhost->extensions;
1335                 while (ext && ext->callback) {
1336                         n = lws_ext_cb_all_exts(context, wsi,
1337                                    LWS_EXT_CB_CHECK_OK_TO_PROPOSE_EXTENSION,
1338                                    (char *)ext->name, 0);
1339                         if (n) { /* an extension vetos us */
1340                                 lwsl_ext("ext %s vetoed\n", (char *)ext->name);
1341                                 ext++;
1342                                 continue;
1343                         }
1344                         n = wsi->vhost->protocols[0].callback(wsi,
1345                                 LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
1346                                         wsi->user_space, (char *)ext->name, 0);
1347
1348                         /*
1349                          * zero return from callback means
1350                          * go ahead and allow the extension,
1351                          * it's what we get if the callback is
1352                          * unhandled
1353                          */
1354
1355                         if (n) {
1356                                 ext++;
1357                                 continue;
1358                         }
1359
1360                         /* apply it */
1361
1362                         if (ext_count)
1363                                 *p++ = ',';
1364                         else
1365                                 p += sprintf(p, "Sec-WebSocket-Extensions: ");
1366                         p += sprintf(p, "%s", ext->client_offer);
1367                         ext_count++;
1368
1369                         ext++;
1370                 }
1371                 if (ext_count)
1372                         p += sprintf(p, "\x0d\x0a");
1373 #endif
1374
1375                 if (wsi->ietf_spec_revision)
1376                         p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
1377                                      wsi->ietf_spec_revision);
1378
1379                 /* prepare the expected server accept response */
1380
1381                 key_b64[39] = '\0'; /* enforce composed length below buf sizeof */
1382                 n = sprintf(buf, "%s258EAFA5-E914-47DA-95CA-C5AB0DC85B11", key_b64);
1383
1384                 lws_SHA1((unsigned char *)buf, n, (unsigned char *)hash);
1385
1386                 lws_b64_encode_string(hash, 20,
1387                                       wsi->u.hdr.ah->initial_handshake_hash_base64,
1388                                       sizeof(wsi->u.hdr.ah->initial_handshake_hash_base64));
1389         }
1390
1391         /* give userland a chance to append, eg, cookies */
1392
1393         wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
1394                                 wsi->user_space, &p, (pkt + context->pt_serv_buf_size) - p - 12);
1395
1396         p += sprintf(p, "\x0d\x0a");
1397
1398         return p;
1399 }
1400