client: always set port even if sockfd already created
[platform/upstream/libwebsockets.git] / lib / client-handshake.c
1 #include "private-libwebsockets.h"
2
3 static int
4 lws_getaddrinfo46(struct lws *wsi, const char *ads, struct addrinfo **result)
5 {
6         struct addrinfo hints;
7
8         memset(&hints, 0, sizeof(hints));
9         *result = NULL;
10
11 #ifdef LWS_USE_IPV6
12         if (wsi->ipv6) {
13
14 #if !defined(__ANDROID__)
15                 hints.ai_family = AF_INET6;
16                 hints.ai_flags = AI_V4MAPPED;
17 #endif
18         } else
19 #endif
20         {
21                 hints.ai_family = PF_UNSPEC;
22                 hints.ai_socktype = SOCK_STREAM;
23                 hints.ai_flags = AI_CANONNAME;
24         }
25
26         return getaddrinfo(ads, NULL, &hints, result);
27 }
28
29 struct lws *
30 lws_client_connect_2(struct lws *wsi)
31 {
32         sockaddr46 sa46;
33         struct addrinfo *result;
34         struct lws_context *context = wsi->context;
35         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
36         struct lws_pollfd pfd;
37         const char *cce = "", *iface;
38         int n, plen = 0, port;
39         const char *ads;
40 #ifdef LWS_USE_IPV6
41         char ipv6only = lws_check_opt(wsi->vhost->options,
42                         LWS_SERVER_OPTION_IPV6_V6ONLY_MODIFY |
43                         LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE);
44
45 #if defined(__ANDROID__)
46         ipv6only = 0;
47 #endif
48 #endif
49
50         lwsl_client("%s\n", __func__);
51
52         if (!wsi->u.hdr.ah) {
53                 cce = "ah was NULL at cc2";
54                 lwsl_err("%s\n", cce);
55                 goto oom4;
56         }
57
58         /*
59          * start off allowing ipv6 on connection if vhost allows it
60          */
61         wsi->ipv6 = LWS_IPV6_ENABLED(wsi->vhost);
62
63         /* Decide what it is we need to connect to:
64          *
65          * Priority 1: connect to http proxy */
66
67         if (wsi->vhost->http_proxy_port) {
68                 plen = sprintf((char *)pt->serv_buf,
69                         "CONNECT %s:%u HTTP/1.0\x0d\x0a"
70                         "User-agent: libwebsockets\x0d\x0a",
71                         lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS),
72                         wsi->c_port);
73
74                 if (wsi->vhost->proxy_basic_auth_token[0])
75                         plen += sprintf((char *)pt->serv_buf + plen,
76                                         "Proxy-authorization: basic %s\x0d\x0a",
77                                         wsi->vhost->proxy_basic_auth_token);
78
79                 plen += sprintf((char *)pt->serv_buf + plen, "\x0d\x0a");
80                 ads = wsi->vhost->http_proxy_address;
81                 port = wsi->vhost->http_proxy_port;
82
83 #if defined(LWS_WITH_SOCKS5)
84
85         /* Priority 2: Connect to SOCK5 Proxy */
86
87         } else if (wsi->vhost->socks_proxy_port) {
88                 socks_generate_msg(wsi, SOCKS_MSG_GREETING, (size_t *)&plen);
89                 lwsl_client("%s\n", "Sending SOCKS Greeting.");
90
91                 ads = wsi->vhost->socks_proxy_address;
92                 port = wsi->vhost->socks_proxy_port;
93 #endif
94         } else {
95
96                 /* Priority 3: Connect directly */
97
98                 ads = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS);
99                 port = wsi->c_port;
100         }
101
102         /*
103          * prepare the actual connection
104          * to whatever we decided to connect to
105          */
106
107        lwsl_notice("%s: %p: address %s\n", __func__, wsi, ads);
108
109        n = lws_getaddrinfo46(wsi, ads, &result);
110
111 #ifdef LWS_USE_IPV6
112         if (wsi->ipv6) {
113
114                 memset(&sa46, 0, sizeof(sa46));
115
116                 sa46.sa6.sin6_family = AF_INET6;
117                 switch (result->ai_family) {
118                 case AF_INET:
119                         if (ipv6only)
120                                 break;
121                         /* map IPv4 to IPv6 */
122                         bzero((char *)&sa46.sa6.sin6_addr,
123                                                 sizeof(sa46.sa6.sin6_addr));
124                         sa46.sa6.sin6_addr.s6_addr[10] = 0xff;
125                         sa46.sa6.sin6_addr.s6_addr[11] = 0xff;
126                         memcpy(&sa46.sa6.sin6_addr.s6_addr[12],
127                                 &((struct sockaddr_in *)result->ai_addr)->sin_addr,
128                                                         sizeof(struct in_addr));
129                         lwsl_notice("uplevelling AF_INET to AF_INET6\n");
130                         break;
131
132                 case AF_INET6:
133                         memcpy(&sa46.sa6.sin6_addr,
134                           &((struct sockaddr_in6 *)result->ai_addr)->sin6_addr,
135                                                 sizeof(struct in6_addr));
136                         sa46.sa6.sin6_scope_id = ((struct sockaddr_in6 *)result->ai_addr)->sin6_scope_id;
137                         sa46.sa6.sin6_flowinfo = ((struct sockaddr_in6 *)result->ai_addr)->sin6_flowinfo;
138                         break;
139                 default:
140                         lwsl_err("Unknown address family\n");
141                         freeaddrinfo(result);
142                         cce = "unknown address family";
143                         goto oom4;
144                 }
145         } else
146 #endif /* use ipv6 */
147
148         /* use ipv4 */
149         {
150                 void *p = NULL;
151
152                 if (!n) {
153                         struct addrinfo *res = result;
154
155                         /* pick the first AF_INET (IPv4) result */
156
157                         while (!p && res) {
158                                 switch (res->ai_family) {
159                                 case AF_INET:
160                                         p = &((struct sockaddr_in *)res->ai_addr)->sin_addr;
161                                         break;
162                                 }
163
164                                 res = res->ai_next;
165                         }
166 #if defined(LWS_FALLBACK_GETHOSTBYNAME)
167                 } else if (n == EAI_SYSTEM) {
168                         struct hostent *host;
169
170                         lwsl_info("getaddrinfo (ipv4) failed, trying gethostbyname\n");
171                         host = gethostbyname(ads);
172                         if (host) {
173                                 p = host->h_addr;
174                         } else {
175                                 lwsl_err("gethostbyname failed\n");
176                                 cce = "gethostbyname (ipv4) failed";
177                                 goto oom4;
178                         }
179 #endif
180                 } else {
181                         lwsl_err("getaddrinfo failed\n");
182                         cce = "getaddrinfo failed";
183                         goto oom4;
184                 }
185
186                 if (!p) {
187                         if (result)
188                                 freeaddrinfo(result);
189                         lwsl_err("Couldn't identify address\n");
190                         cce = "unable to lookup address";
191                         goto oom4;
192                 }
193
194                 sa46.sa4.sin_family = AF_INET;
195                 sa46.sa4.sin_addr = *((struct in_addr *)p);
196                 bzero(&sa46.sa4.sin_zero, 8);
197         }
198
199         if (result)
200                 freeaddrinfo(result);
201
202         /* now we decided on ipv4 or ipv6, set the port */
203
204         if (!lws_socket_is_valid(wsi->desc.sockfd)) {
205
206 #if defined(LWS_USE_LIBUV)
207                 if (LWS_LIBUV_ENABLED(context))
208                         if (lws_libuv_check_watcher_active(wsi)) {
209                                 lwsl_warn("Waiting for libuv watcher to close\n");
210                                 cce = "waiting for libuv watcher to close";
211                                 goto oom4;
212                         }
213 #endif
214
215 #ifdef LWS_USE_IPV6
216                 if (wsi->ipv6)
217                         wsi->desc.sockfd = socket(AF_INET6, SOCK_STREAM, 0);
218                 else
219 #endif
220                         wsi->desc.sockfd = socket(AF_INET, SOCK_STREAM, 0);
221
222                 if (!lws_socket_is_valid(wsi->desc.sockfd)) {
223                         lwsl_warn("Unable to open socket\n");
224                         cce = "unable to open socket";
225                         goto oom4;
226                 }
227
228                 if (lws_plat_set_socket_options(wsi->vhost, wsi->desc.sockfd)) {
229                         lwsl_err("Failed to set wsi socket options\n");
230                         compatible_close(wsi->desc.sockfd);
231                         cce = "set socket opts failed";
232                         goto oom4;
233                 }
234
235                 wsi->mode = LWSCM_WSCL_WAITING_CONNECT;
236
237                 lws_libev_accept(wsi, wsi->desc);
238                 lws_libuv_accept(wsi, wsi->desc);
239                 lws_libevent_accept(wsi, wsi->desc);
240
241                 if (insert_wsi_socket_into_fds(context, wsi)) {
242                         compatible_close(wsi->desc.sockfd);
243                         cce = "insert wsi failed";
244                         goto oom4;
245                 }
246
247                 lws_change_pollfd(wsi, 0, LWS_POLLIN);
248
249                 /*
250                  * past here, we can't simply free the structs as error
251                  * handling as oom4 does.  We have to run the whole close flow.
252                  */
253
254                 if (!wsi->protocol)
255                         wsi->protocol = &wsi->vhost->protocols[0];
256
257                 wsi->protocol->callback(wsi, LWS_CALLBACK_WSI_CREATE,
258                                         wsi->user_space, NULL, 0);
259
260                 lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_CONNECT_RESPONSE,
261                                 AWAITING_TIMEOUT);
262
263                 iface = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_IFACE);
264
265                 if (iface) {
266                         n = lws_socket_bind(wsi->vhost, wsi->desc.sockfd, 0, iface);
267                         if (n < 0) {
268                                 cce = "unable to bind socket";
269                                 goto failed;
270                         }
271                 }
272         }
273
274 #ifdef LWS_USE_IPV6
275         if (wsi->ipv6) {
276                 sa46.sa6.sin6_port = htons(port);
277                 n = sizeof(struct sockaddr_in6);
278         } else
279 #endif
280         {
281                 sa46.sa4.sin_port = htons(port);
282                 n = sizeof(struct sockaddr);
283         }
284
285         if (connect(wsi->desc.sockfd, (const struct sockaddr *)&sa46, n) == -1 ||
286             LWS_ERRNO == LWS_EISCONN) {
287                 if (LWS_ERRNO == LWS_EALREADY ||
288                     LWS_ERRNO == LWS_EINPROGRESS ||
289                     LWS_ERRNO == LWS_EWOULDBLOCK
290 #ifdef _WIN32
291                         || LWS_ERRNO == WSAEINVAL
292 #endif
293                 ) {
294                         lwsl_client("nonblocking connect retry (errno = %d)\n",
295                                     LWS_ERRNO);
296
297                         if (lws_plat_check_connection_error(wsi)) {
298                                 cce = "socket connect failed";
299                                 goto failed;
300                         }
301
302                         /*
303                          * must do specifically a POLLOUT poll to hear
304                          * about the connect completion
305                          */
306                         if (lws_change_pollfd(wsi, 0, LWS_POLLOUT)) {
307                                 cce = "POLLOUT set failed";
308                                 goto failed;
309                         }
310
311                         return wsi;
312                 }
313
314                 if (LWS_ERRNO != LWS_EISCONN) {
315                         lwsl_notice("Connect failed errno=%d\n", LWS_ERRNO);
316                         cce = "connect failed";
317                         goto failed;
318                 }
319         }
320
321         lwsl_client("connected\n");
322
323         /* we are connected to server, or proxy */
324
325         /* http proxy */
326         if (wsi->vhost->http_proxy_port) {
327
328                 /*
329                  * OK from now on we talk via the proxy, so connect to that
330                  *
331                  * (will overwrite existing pointer,
332                  * leaving old string/frag there but unreferenced)
333                  */
334                 if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS,
335                                           wsi->vhost->http_proxy_address))
336                         goto failed;
337                 wsi->c_port = wsi->vhost->http_proxy_port;
338
339                 n = send(wsi->desc.sockfd, (char *)pt->serv_buf, plen,
340                          MSG_NOSIGNAL);
341                 if (n < 0) {
342                         lwsl_debug("ERROR writing to proxy socket\n");
343                         cce = "proxy write failed";
344                         goto failed;
345                 }
346
347                 lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_PROXY_RESPONSE,
348                                 AWAITING_TIMEOUT);
349
350                 wsi->mode = LWSCM_WSCL_WAITING_PROXY_REPLY;
351
352                 return wsi;
353         }
354 #if defined(LWS_WITH_SOCKS5)
355         /* socks proxy */
356         else if (wsi->vhost->socks_proxy_port) {
357                 n = send(wsi->desc.sockfd, (char *)pt->serv_buf, plen,
358                          MSG_NOSIGNAL);
359                 if (n < 0) {
360                         lwsl_debug("ERROR writing greeting to socks proxy"
361                                 "socket.\n");
362                         cce = "socks write failed";
363                         goto failed;
364                 }
365
366                 lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_SOCKS_GREETING_REPLY,
367                                 AWAITING_TIMEOUT);
368
369                 wsi->mode = LWSCM_WSCL_WAITING_SOCKS_GREETING_REPLY;
370
371                 return wsi;
372         }
373 #endif
374
375         /*
376          * provoke service to issue the handshake directly
377          * we need to do it this way because in the proxy case, this is the
378          * next state and executed only if and when we get a good proxy
379          * response inside the state machine... but notice in SSL case this
380          * may not have sent anything yet with 0 return, and won't until some
381          * many retries from main loop.  To stop that becoming endless,
382          * cover with a timeout.
383          */
384
385         lws_set_timeout(wsi, PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE,
386                         AWAITING_TIMEOUT);
387
388         wsi->mode = LWSCM_WSCL_ISSUE_HANDSHAKE;
389         pfd.fd = wsi->desc.sockfd;
390         pfd.events = LWS_POLLIN;
391         pfd.revents = LWS_POLLIN;
392
393         n = lws_service_fd(context, &pfd);
394         if (n < 0) {
395                 cce = "first service failed";
396                 goto failed;
397         }
398         if (n) /* returns 1 on failure after closing wsi */
399                 return NULL;
400
401         return wsi;
402
403 oom4:
404         /* we're closing, losing some rx is OK */
405         lws_header_table_force_to_detachable_state(wsi);
406
407         if (wsi->mode == LWSCM_HTTP_CLIENT ||
408             wsi->mode == LWSCM_HTTP_CLIENT_ACCEPTED ||
409             wsi->mode == LWSCM_WSCL_WAITING_CONNECT) {
410                 wsi->vhost->protocols[0].callback(wsi,
411                         LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
412                         wsi->user_space, (void *)cce, strlen(cce));
413                 wsi->already_did_cce = 1;
414         }
415         /* take care that we might be inserted in fds already */
416         if (wsi->position_in_fds_table != -1)
417                 goto failed1;
418         lws_remove_from_timeout_list(wsi);
419         lws_header_table_detach(wsi, 0);
420         lws_free(wsi);
421
422         return NULL;
423
424 failed:
425         wsi->vhost->protocols[0].callback(wsi,
426                 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
427                 wsi->user_space, (void *)cce, strlen(cce));
428         wsi->already_did_cce = 1;
429 failed1:
430         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
431
432         return NULL;
433 }
434
435 /**
436  * lws_client_reset() - retarget a connected wsi to start over with a new connection (ie, redirect)
437  *                      this only works if still in HTTP, ie, not upgraded yet
438  * wsi:         connection to reset
439  * address:     network address of the new server
440  * port:        port to connect to
441  * path:        uri path to connect to on the new server
442  * host:        host header to send to the new server
443  */
444 LWS_VISIBLE struct lws *
445 lws_client_reset(struct lws **pwsi, int ssl, const char *address, int port,
446                  const char *path, const char *host)
447 {
448         char origin[300] = "", protocol[300] = "", method[32] = "", iface[16] = "", *p;
449         struct lws *wsi = *pwsi;
450
451         if (wsi->redirects == 3) {
452                 lwsl_err("%s: Too many redirects\n", __func__);
453                 return NULL;
454         }
455         wsi->redirects++;
456
457         p = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN);
458         if (p)
459                 strncpy(origin, p, sizeof(origin) - 1);
460
461         p = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);
462         if (p)
463                 strncpy(protocol, p, sizeof(protocol) - 1);
464
465         p = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_METHOD);
466         if (p)
467                 strncpy(method, p, sizeof(method) - 1);
468
469         p = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_IFACE);
470         if (p)
471                 strncpy(method, p, sizeof(iface) - 1);
472
473         lwsl_notice("redirect ads='%s', port=%d, path='%s', ssl = %d\n",
474                    address, port, path, ssl);
475
476         /* close the connection by hand */
477
478 #ifdef LWS_OPENSSL_SUPPORT
479         lws_ssl_close(wsi);
480 #endif
481
482 #ifdef LWS_USE_LIBUV
483         if (LWS_LIBUV_ENABLED(wsi->context)) {
484                 lwsl_debug("%s: lws_libuv_closehandle: wsi %p\n", __func__, wsi);
485                 /*
486                  * libuv has to do his own close handle processing asynchronously
487                  * but once it starts we can do everything else synchronously,
488                  * including trash wsi->desc.sockfd since it took a copy.
489                  *
490                  * When it completes it will call compatible_close()
491                  */
492                 lws_libuv_closehandle_manually(wsi);
493         } else
494 #else
495         compatible_close(wsi->desc.sockfd);
496 #endif
497
498         remove_wsi_socket_from_fds(wsi);
499
500 #ifdef LWS_OPENSSL_SUPPORT
501         wsi->use_ssl = ssl;
502 #else
503         if (ssl) {
504                 lwsl_err("%s: not configured for ssl\n", __func__);
505                 return NULL;
506         }
507 #endif
508
509         wsi->desc.sockfd = LWS_SOCK_INVALID;
510         wsi->state = LWSS_CLIENT_UNCONNECTED;
511         wsi->protocol = NULL;
512         wsi->pending_timeout = NO_PENDING_TIMEOUT;
513         wsi->c_port = port;
514         wsi->hdr_parsing_completed = 0;
515         _lws_header_table_reset(wsi->u.hdr.ah);
516
517         if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS, address))
518                 return NULL;
519
520         if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_HOST, host))
521                 return NULL;
522
523         if (origin[0])
524                 if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_ORIGIN,
525                                           origin))
526                         return NULL;
527         if (protocol[0])
528                 if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS,
529                                           protocol))
530                         return NULL;
531         if (method[0])
532                 if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_METHOD,
533                                           method))
534                         return NULL;
535
536         if (iface[0])
537                 if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_IFACE,
538                                           iface))
539                         return NULL;
540
541         origin[0] = '/';
542         strncpy(&origin[1], path, sizeof(origin) - 2);
543         if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_URI, origin))
544                 return NULL;
545
546         *pwsi = lws_client_connect_2(wsi);
547
548         return *pwsi;
549 }
550
551 #ifdef LWS_WITH_HTTP_PROXY
552 static hubbub_error
553 html_parser_cb(const hubbub_token *token, void *pw)
554 {
555         struct lws_rewrite *r = (struct lws_rewrite *)pw;
556         char buf[1024], *start = buf + LWS_PRE, *p = start,
557              *end = &buf[sizeof(buf) - 1];
558         size_t i;
559
560         switch (token->type) {
561         case HUBBUB_TOKEN_DOCTYPE:
562
563                 p += lws_snprintf(p, end - p, "<!DOCTYPE %.*s %s ",
564                                 (int) token->data.doctype.name.len,
565                                 token->data.doctype.name.ptr,
566                                 token->data.doctype.force_quirks ?
567                                                 "(force-quirks) " : "");
568
569                 if (token->data.doctype.public_missing)
570                         lwsl_debug("\tpublic: missing\n");
571                 else
572                         p += lws_snprintf(p, end - p, "PUBLIC \"%.*s\"\n",
573                                 (int) token->data.doctype.public_id.len,
574                                 token->data.doctype.public_id.ptr);
575
576                 if (token->data.doctype.system_missing)
577                         lwsl_debug("\tsystem: missing\n");
578                 else
579                         p += lws_snprintf(p, end - p, " \"%.*s\">\n",
580                                 (int) token->data.doctype.system_id.len,
581                                 token->data.doctype.system_id.ptr);
582
583                 break;
584         case HUBBUB_TOKEN_START_TAG:
585                 p += lws_snprintf(p, end - p, "<%.*s", (int)token->data.tag.name.len,
586                                 token->data.tag.name.ptr);
587
588 /*                              (token->data.tag.self_closing) ?
589                                                 "(self-closing) " : "",
590                                 (token->data.tag.n_attributes > 0) ?
591                                                 "attributes:" : "");
592 */
593                 for (i = 0; i < token->data.tag.n_attributes; i++) {
594                         if (!hstrcmp(&token->data.tag.attributes[i].name, "href", 4) ||
595                             !hstrcmp(&token->data.tag.attributes[i].name, "action", 6) ||
596                             !hstrcmp(&token->data.tag.attributes[i].name, "src", 3)) {
597                                 const char *pp = (const char *)token->data.tag.attributes[i].value.ptr;
598                                 int plen = (int) token->data.tag.attributes[i].value.len;
599
600                                 if (strncmp(pp, "http:", 5) && strncmp(pp, "https:", 6)) {
601
602                                         if (!hstrcmp(&token->data.tag.attributes[i].value,
603                                                      r->from, r->from_len)) {
604                                                 pp += r->from_len;
605                                                 plen -= r->from_len;
606                                         }
607                                         p += lws_snprintf(p, end - p, " %.*s=\"%s/%.*s\"",
608                                                (int) token->data.tag.attributes[i].name.len,
609                                                token->data.tag.attributes[i].name.ptr,
610                                                r->to, plen, pp);
611                                         continue;
612                                 }
613                         }
614
615                         p += lws_snprintf(p, end - p, " %.*s=\"%.*s\"",
616                                 (int) token->data.tag.attributes[i].name.len,
617                                 token->data.tag.attributes[i].name.ptr,
618                                 (int) token->data.tag.attributes[i].value.len,
619                                 token->data.tag.attributes[i].value.ptr);
620                 }
621                 p += lws_snprintf(p, end - p, ">");
622                 break;
623         case HUBBUB_TOKEN_END_TAG:
624                 p += lws_snprintf(p, end - p, "</%.*s", (int) token->data.tag.name.len,
625                                 token->data.tag.name.ptr);
626 /*
627                                 (token->data.tag.self_closing) ?
628                                                 "(self-closing) " : "",
629                                 (token->data.tag.n_attributes > 0) ?
630                                                 "attributes:" : "");
631 */
632                 for (i = 0; i < token->data.tag.n_attributes; i++) {
633                         p += lws_snprintf(p, end - p, " %.*s='%.*s'\n",
634                                 (int) token->data.tag.attributes[i].name.len,
635                                 token->data.tag.attributes[i].name.ptr,
636                                 (int) token->data.tag.attributes[i].value.len,
637                                 token->data.tag.attributes[i].value.ptr);
638                 }
639                 p += lws_snprintf(p, end - p, ">");
640                 break;
641         case HUBBUB_TOKEN_COMMENT:
642                 p += lws_snprintf(p, end - p, "<!-- %.*s -->\n",
643                                 (int) token->data.comment.len,
644                                 token->data.comment.ptr);
645                 break;
646         case HUBBUB_TOKEN_CHARACTER:
647                 if (token->data.character.len == 1) {
648                         if (*token->data.character.ptr == '<') {
649                                 p += lws_snprintf(p, end - p, "&lt;");
650                                 break;
651                         }
652                         if (*token->data.character.ptr == '>') {
653                                 p += lws_snprintf(p, end - p, "&gt;");
654                                 break;
655                         }
656                         if (*token->data.character.ptr == '&') {
657                                 p += lws_snprintf(p, end - p, "&amp;");
658                                 break;
659                         }
660                 }
661
662                 p += lws_snprintf(p, end - p, "%.*s", (int) token->data.character.len,
663                                 token->data.character.ptr);
664                 break;
665         case HUBBUB_TOKEN_EOF:
666                 p += lws_snprintf(p, end - p, "\n");
667                 break;
668         }
669
670         if (user_callback_handle_rxflow(r->wsi->protocol->callback,
671                         r->wsi, LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ,
672                         r->wsi->user_space, start, p - start))
673                 return -1;
674
675         return HUBBUB_OK;
676 }
677 #endif
678
679 LWS_VISIBLE struct lws *
680 lws_client_connect_via_info(struct lws_client_connect_info *i)
681 {
682         struct lws *wsi;
683         int v = SPEC_LATEST_SUPPORTED;
684         const struct lws_protocols *p;
685
686         if (i->context->requested_kill)
687                 return NULL;
688
689         if (!i->context->protocol_init_done)
690                 lws_protocol_init(i->context);
691
692         wsi = lws_zalloc(sizeof(struct lws));
693         if (wsi == NULL)
694                 goto bail;
695
696         wsi->context = i->context;
697         /* assert the mode and union status (hdr) clearly */
698         lws_union_transition(wsi, LWSCM_HTTP_CLIENT);
699         wsi->desc.sockfd = LWS_SOCK_INVALID;
700
701         /* 1) fill up the wsi with stuff from the connect_info as far as it
702          * can go.  It's because not only is our connection async, we might
703          * not even be able to get ahold of an ah at this point.
704          */
705
706         /* -1 means just use latest supported */
707         if (i->ietf_version_or_minus_one != -1 && i->ietf_version_or_minus_one)
708                 v = i->ietf_version_or_minus_one;
709
710         wsi->ietf_spec_revision = v;
711         wsi->user_space = NULL;
712         wsi->state = LWSS_CLIENT_UNCONNECTED;
713         wsi->pending_timeout = NO_PENDING_TIMEOUT;
714         wsi->position_in_fds_table = -1;
715         wsi->c_port = i->port;
716         wsi->vhost = i->vhost;
717         if (!wsi->vhost)
718                 wsi->vhost = i->context->vhost_list;
719
720         wsi->protocol = &wsi->vhost->protocols[0];
721
722         /* for http[s] connection, allow protocol selection by name */
723
724         if (i->method && i->vhost && i->protocol) {
725                 p = lws_vhost_name_to_protocol(i->vhost, i->protocol);
726                 if (p)
727                         wsi->protocol = p;
728         }
729
730         if (wsi && !wsi->user_space && i->userdata) {
731                 wsi->user_space_externally_allocated = 1;
732                 wsi->user_space = i->userdata;
733         } else
734                 /* if we stay in http, we can assign the user space now,
735                  * otherwise do it after the protocol negotiated
736                  */
737                 if (i->method)
738                         if (lws_ensure_user_space(wsi))
739                                 goto bail;
740
741 #ifdef LWS_OPENSSL_SUPPORT
742         wsi->use_ssl = i->ssl_connection;
743 #else
744         if (i->ssl_connection) {
745                 lwsl_err("libwebsockets not configured for ssl\n");
746                 goto bail;
747         }
748 #endif
749
750         /* 2) stash the things from connect_info that we can't process without
751          * an ah.  Because if no ah, we will go on the ah waiting list and
752          * process those things later (after the connect_info and maybe the
753          * things pointed to have gone out of scope.
754          */
755
756         wsi->u.hdr.stash = lws_malloc(sizeof(*wsi->u.hdr.stash));
757         if (!wsi->u.hdr.stash) {
758                 lwsl_err("%s: OOM\n", __func__);
759                 goto bail;
760         }
761
762         wsi->u.hdr.stash->origin[0] = '\0';
763         wsi->u.hdr.stash->protocol[0] = '\0';
764         wsi->u.hdr.stash->method[0] = '\0';
765         wsi->u.hdr.stash->iface[0] = '\0';
766
767         strncpy(wsi->u.hdr.stash->address, i->address,
768                 sizeof(wsi->u.hdr.stash->address) - 1);
769         strncpy(wsi->u.hdr.stash->path, i->path,
770                 sizeof(wsi->u.hdr.stash->path) - 1);
771         strncpy(wsi->u.hdr.stash->host, i->host,
772                 sizeof(wsi->u.hdr.stash->host) - 1);
773         if (i->origin)
774                 strncpy(wsi->u.hdr.stash->origin, i->origin,
775                         sizeof(wsi->u.hdr.stash->origin) - 1);
776         if (i->protocol)
777                 strncpy(wsi->u.hdr.stash->protocol, i->protocol,
778                         sizeof(wsi->u.hdr.stash->protocol) - 1);
779         if (i->method)
780                 strncpy(wsi->u.hdr.stash->method, i->method,
781                         sizeof(wsi->u.hdr.stash->method) - 1);
782         if (i->iface)
783                 strncpy(wsi->u.hdr.stash->iface, i->iface,
784                         sizeof(wsi->u.hdr.stash->iface) - 1);
785
786         wsi->u.hdr.stash->address[sizeof(wsi->u.hdr.stash->address) - 1] = '\0';
787         wsi->u.hdr.stash->path[sizeof(wsi->u.hdr.stash->path) - 1] = '\0';
788         wsi->u.hdr.stash->host[sizeof(wsi->u.hdr.stash->host) - 1] = '\0';
789         wsi->u.hdr.stash->origin[sizeof(wsi->u.hdr.stash->origin) - 1] = '\0';
790         wsi->u.hdr.stash->protocol[sizeof(wsi->u.hdr.stash->protocol) - 1] = '\0';
791         wsi->u.hdr.stash->method[sizeof(wsi->u.hdr.stash->method) - 1] = '\0';
792         wsi->u.hdr.stash->iface[sizeof(wsi->u.hdr.stash->iface) - 1] = '\0';
793
794         if (i->pwsi)
795                 *i->pwsi = wsi;
796
797         /* if we went on the waiting list, no probs just return the wsi
798          * when we get the ah, now or later, he will call
799          * lws_client_connect_via_info2() below.
800          */
801         if (lws_header_table_attach(wsi, 0) < 0) {
802                 /*
803                  * if we failed here, the connection is already closed
804                  * and freed.
805                  */
806                 goto bail1;
807         }
808
809         if (i->parent_wsi) {
810                 lwsl_info("%s: created child %p of parent %p\n", __func__,
811                                 wsi, i->parent_wsi);
812                 wsi->parent = i->parent_wsi;
813                 wsi->sibling_list = i->parent_wsi->child_list;
814                 i->parent_wsi->child_list = wsi;
815         }
816 #ifdef LWS_WITH_HTTP_PROXY
817         if (i->uri_replace_to)
818                 wsi->rw = lws_rewrite_create(wsi, html_parser_cb,
819                                              i->uri_replace_from,
820                                              i->uri_replace_to);
821 #endif
822
823         return wsi;
824
825 bail:
826         lws_free(wsi);
827
828 bail1:
829         if (i->pwsi)
830                 *i->pwsi = NULL;
831
832         return NULL;
833 }
834
835 struct lws *
836 lws_client_connect_via_info2(struct lws *wsi)
837 {
838         struct client_info_stash *stash = wsi->u.hdr.stash;
839
840         if (!stash)
841                 return wsi;
842
843         /*
844          * we're not necessarily in a position to action these right away,
845          * stash them... we only need during connect phase so u.hdr is fine
846          */
847         if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS,
848                                   stash->address))
849                 goto bail1;
850
851         /* these only need u.hdr lifetime as well */
852
853         if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_URI, stash->path))
854                 goto bail1;
855
856         if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_HOST, stash->host))
857                 goto bail1;
858
859         if (stash->origin[0])
860                 if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_ORIGIN,
861                                           stash->origin))
862                         goto bail1;
863         /*
864          * this is a list of protocols we tell the server we're okay with
865          * stash it for later when we compare server response with it
866          */
867         if (stash->protocol[0])
868                 if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS,
869                                           stash->protocol))
870                         goto bail1;
871         if (stash->method[0])
872                 if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_METHOD,
873                                           stash->method))
874                         goto bail1;
875         if (stash->iface[0])
876                 if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_IFACE,
877                                           stash->iface))
878                         goto bail1;
879
880 #if defined(LWS_WITH_SOCKS5)
881         if (!wsi->vhost->socks_proxy_port)
882                 lws_free_set_NULL(wsi->u.hdr.stash);
883 #endif
884
885         /*
886          * Check with each extension if it is able to route and proxy this
887          * connection for us.  For example, an extension like x-google-mux
888          * can handle this and then we don't need an actual socket for this
889          * connection.
890          */
891
892         if (lws_ext_cb_all_exts(wsi->context, wsi,
893                                 LWS_EXT_CB_CAN_PROXY_CLIENT_CONNECTION,
894                                 (void *)stash->address,
895                                 wsi->c_port) > 0) {
896                 lwsl_client("lws_client_connect: ext handling conn\n");
897
898                 lws_set_timeout(wsi,
899                         PENDING_TIMEOUT_AWAITING_EXTENSION_CONNECT_RESPONSE,
900                                 AWAITING_TIMEOUT);
901
902                 wsi->mode = LWSCM_WSCL_WAITING_EXTENSION_CONNECT;
903                 return wsi;
904         }
905         lwsl_client("lws_client_connect: direct conn\n");
906         wsi->context->count_wsi_allocated++;
907
908         return lws_client_connect_2(wsi);
909
910 bail1:
911 #if defined(LWS_WITH_SOCKS5)
912         if (!wsi->vhost->socks_proxy_port)
913                 lws_free_set_NULL(wsi->u.hdr.stash);
914 #endif
915
916         return NULL;
917 }
918
919 LWS_VISIBLE struct lws *
920 lws_client_connect_extended(struct lws_context *context, const char *address,
921                             int port, int ssl_connection, const char *path,
922                             const char *host, const char *origin,
923                             const char *protocol, int ietf_version_or_minus_one,
924                             void *userdata)
925 {
926         struct lws_client_connect_info i;
927
928         memset(&i, 0, sizeof(i));
929
930         i.context = context;
931         i.address = address;
932         i.port = port;
933         i.ssl_connection = ssl_connection;
934         i.path = path;
935         i.host = host;
936         i.origin = origin;
937         i.protocol = protocol;
938         i.ietf_version_or_minus_one = ietf_version_or_minus_one;
939         i.userdata = userdata;
940
941         return lws_client_connect_via_info(&i);
942 }
943
944 LWS_VISIBLE struct lws *
945 lws_client_connect(struct lws_context *context, const char *address,
946                             int port, int ssl_connection, const char *path,
947                             const char *host, const char *origin,
948                             const char *protocol, int ietf_version_or_minus_one)
949 {
950         struct lws_client_connect_info i;
951
952         memset(&i, 0, sizeof(i));
953
954         i.context = context;
955         i.address = address;
956         i.port = port;
957         i.ssl_connection = ssl_connection;
958         i.path = path;
959         i.host = host;
960         i.origin = origin;
961         i.protocol = protocol;
962         i.ietf_version_or_minus_one = ietf_version_or_minus_one;
963         i.userdata = NULL;
964
965         return lws_client_connect_via_info(&i);
966 }
967
968 #if defined(LWS_WITH_SOCKS5)
969 void socks_generate_msg(struct lws *wsi, enum socks_msg_type type,
970                         size_t *msg_len)
971 {
972         struct lws_context *context = wsi->context;
973         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
974         size_t len = 0;
975
976         if (type == SOCKS_MSG_GREETING) {
977                 /* socks version, version 5 only */
978                 pt->serv_buf[len++] = SOCKS_VERSION_5;
979                 /* number of methods */
980                 pt->serv_buf[len++] = 2;
981                 /* username password method */
982                 pt->serv_buf[len++] = SOCKS_AUTH_USERNAME_PASSWORD;
983                 /* no authentication method */
984                 pt->serv_buf[len++] = SOCKS_AUTH_NO_AUTH;
985         }
986         else if (type == SOCKS_MSG_USERNAME_PASSWORD) {
987                 size_t user_len = 0;
988                 size_t passwd_len = 0;
989
990                 user_len = strlen(wsi->vhost->socks_user);
991                 passwd_len = strlen(wsi->vhost->socks_password);
992
993                 /* the subnegotiation version */
994                 pt->serv_buf[len++] = SOCKS_SUBNEGOTIATION_VERSION_1;
995                 /* length of the user name */
996                 pt->serv_buf[len++] = user_len;
997                 /* user name */
998                 strncpy((char *)&pt->serv_buf[len], wsi->vhost->socks_user,
999                         context->pt_serv_buf_size - len);
1000                 len += user_len;
1001                 /* length of the password */
1002                 pt->serv_buf[len++] = passwd_len;
1003                 /* password */
1004                 strncpy((char *)&pt->serv_buf[len], wsi->vhost->socks_password,
1005                         context->pt_serv_buf_size - len);
1006                 len += passwd_len;
1007         }
1008         else if (type == SOCKS_MSG_CONNECT) {
1009                 size_t len_index = 0;
1010                 short net_num = 0;
1011                 char *net_buf = (char*)&net_num;
1012
1013                 /* socks version */
1014                 pt->serv_buf[len++] = SOCKS_VERSION_5;
1015                 /* socks command */
1016                 pt->serv_buf[len++] = SOCKS_COMMAND_CONNECT;
1017                 /* reserved */
1018                 pt->serv_buf[len++] = 0;
1019                 /* address type */
1020                 pt->serv_buf[len++] = SOCKS_ATYP_DOMAINNAME;
1021                 len_index = len;
1022                 len++;
1023                 /* the address we tell SOCKS proxy to connect to */
1024                 strncpy((char *)&(pt->serv_buf[len]), wsi->u.hdr.stash->address,
1025                         context->pt_serv_buf_size - len);
1026                 len += strlen(wsi->u.hdr.stash->address);
1027                 net_num = htons((short)wsi->c_port);
1028                 /* the port we tell SOCKS proxy to connect to */
1029                 pt->serv_buf[len++] = net_buf[0];
1030                 pt->serv_buf[len++] = net_buf[1];
1031                 /* the length of the address, excluding port */
1032                 pt->serv_buf[len_index] = strlen(wsi->u.hdr.stash->address);
1033         }
1034
1035         *msg_len = len;
1036 }
1037 #endif