refactor out most NO_EXTENSIONS
[platform/upstream/libwebsockets.git] / lib / client-handshake.c
1 #include "private-libwebsockets.h"
2
3 struct libwebsocket *libwebsocket_client_connect_2(
4         struct libwebsocket_context *context,
5         struct libwebsocket *wsi
6 ) {
7         struct libwebsocket_pollfd pfd;
8 #ifdef LWS_USE_IPV6
9         struct sockaddr_in6 server_addr6;
10         struct sockaddr_in6 client_addr6;
11         struct addrinfo hints, *result;
12 #endif
13         struct sockaddr_in server_addr4;
14         struct sockaddr_in client_addr4;
15         struct hostent *server_hostent;
16
17         struct sockaddr *v;
18         int n;
19         int plen = 0;
20         const char *ads;
21
22        lwsl_client("libwebsocket_client_connect_2\n");
23
24         /*
25          * proxy?
26          */
27
28         if (context->http_proxy_port) {
29                 plen = sprintf((char *)context->service_buffer,
30                         "CONNECT %s:%u HTTP/1.0\x0d\x0a"
31                         "User-agent: libwebsockets\x0d\x0a"
32 /*Proxy-authorization: basic aGVsbG86d29ybGQ= */
33                         "\x0d\x0a",
34                         lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS),
35                         wsi->u.hdr.ah->c_port);
36                 ads = context->http_proxy_address;
37
38 #ifdef LWS_USE_IPV6
39                 if (LWS_IPV6_ENABLED(context))
40                         server_addr6.sin6_port = htons(context->http_proxy_port);
41                 else
42 #endif
43                         server_addr4.sin_port = htons(context->http_proxy_port);
44
45         } else {
46                 ads = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS);
47 #ifdef LWS_USE_IPV6
48                 if (LWS_IPV6_ENABLED(context))
49                         server_addr6.sin6_port = htons(wsi->u.hdr.ah->c_port);
50                 else
51 #endif
52                         server_addr4.sin_port = htons(wsi->u.hdr.ah->c_port);
53         }
54
55         /*
56          * prepare the actual connection (to the proxy, if any)
57          */
58        lwsl_client("libwebsocket_client_connect_2: address %s\n", ads);
59
60 #ifdef LWS_USE_IPV6
61         if (LWS_IPV6_ENABLED(context)) {
62                 memset(&hints, 0, sizeof(struct addrinfo));
63                 n = getaddrinfo(ads, NULL, &hints, &result);
64                 if (n) {
65                         lwsl_err("getaddrinfo: %s\n", gai_strerror(n));
66                         goto oom4;
67                 }
68
69                 server_addr6.sin6_family = AF_INET6;
70                 switch (result->ai_family) {
71                 case AF_INET:
72                         /* map IPv4 to IPv6 */
73                         bzero((char *)&server_addr6.sin6_addr,
74                                                 sizeof(struct in6_addr));
75                         server_addr6.sin6_addr.s6_addr[10] = 0xff;
76                         server_addr6.sin6_addr.s6_addr[11] = 0xff;
77                         memcpy(&server_addr6.sin6_addr.s6_addr[12],
78                                 &((struct sockaddr_in *)result->ai_addr)->sin_addr,
79                                                         sizeof(struct in_addr));
80                         break;
81                 case AF_INET6:
82                         memcpy(&server_addr6.sin6_addr,
83                           &((struct sockaddr_in6 *)result->ai_addr)->sin6_addr,
84                                                 sizeof(struct in6_addr));
85                         break;
86                 default:
87                         lwsl_err("Unknown address family\n");
88                         freeaddrinfo(result);
89                         goto oom4;
90                 }
91
92                 freeaddrinfo(result);
93         } else
94 #endif
95         {
96                 server_hostent = gethostbyname(ads);
97                 if (!server_hostent) {
98                         lwsl_err("Unable to get host name from %s\n", ads);
99                         goto oom4;
100                 }
101
102                 server_addr4.sin_family = AF_INET;
103                 server_addr4.sin_addr =
104                                 *((struct in_addr *)server_hostent->h_addr);
105                 bzero(&server_addr4.sin_zero, 8);
106         }
107
108         if (wsi->sock < 0) {
109
110 #ifdef LWS_USE_IPV6
111                 if (LWS_IPV6_ENABLED(context))
112                         wsi->sock = socket(AF_INET6, SOCK_STREAM, 0);
113                 else
114 #endif
115                         wsi->sock = socket(AF_INET, SOCK_STREAM, 0);
116
117                 if (wsi->sock < 0) {
118                         lwsl_warn("Unable to open socket\n");
119                         goto oom4;
120                 }
121
122                 if (lws_plat_set_socket_options(context, wsi->sock)) {
123                         lwsl_err("Failed to set wsi socket options\n");
124                         compatible_close(wsi->sock);
125                         goto oom4;
126                 }
127
128                 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_CONNECT;
129
130                 insert_wsi_socket_into_fds(context, wsi);
131
132                 libwebsocket_set_timeout(wsi,
133                         PENDING_TIMEOUT_AWAITING_CONNECT_RESPONSE,
134                                                               AWAITING_TIMEOUT);
135 #ifdef LWS_USE_IPV6
136                 if (LWS_IPV6_ENABLED(context)) {
137                         v = (struct sockaddr *)&client_addr6;
138                         n = sizeof(client_addr6);
139                         bzero((char *)v, n);
140                         client_addr6.sin6_family = AF_INET6;
141                 } else
142 #endif
143                 {
144                         v = (struct sockaddr *)&client_addr4;
145                         n = sizeof(client_addr4);
146                         bzero((char *)v, n);
147                         client_addr4.sin_family = AF_INET;
148                 }
149
150                 if (context->iface) {
151                         if (interface_to_sa(context, context->iface,
152                                         (struct sockaddr_in *)v, n) < 0) {
153                                 lwsl_err("Unable to find interface %s\n",
154                                                                 context->iface);
155                                 compatible_close(wsi->sock);
156                                 goto failed;
157                         }
158
159                         if (bind(wsi->sock, v, n) < 0) {
160                                 lwsl_err("Error binding to interface %s",
161                                                                 context->iface);
162                                 compatible_close(wsi->sock);
163                                 goto failed;
164                         }
165                 }
166         }
167
168 #ifdef LWS_USE_IPV6
169         if (LWS_IPV6_ENABLED(context)) {
170                 v = (struct sockaddr *)&server_addr6;
171                 n = sizeof(struct sockaddr_in6);
172         } else
173 #endif
174         {
175                 v = (struct sockaddr *)&server_addr4;
176                 n = sizeof(struct sockaddr);
177         }
178
179         if (connect(wsi->sock, v, n) == -1 || LWS_ERRNO == LWS_EISCONN) {
180
181                 if (LWS_ERRNO == LWS_EALREADY || LWS_ERRNO == LWS_EINPROGRESS
182                                               || LWS_ERRNO == LWS_EWOULDBLOCK) {
183                         lwsl_client("nonblocking connect retry\n");
184
185                         /*
186                          * must do specifically a POLLOUT poll to hear
187                          * about the connect completion
188                          */
189                         if (lws_change_pollfd(wsi, 0, LWS_POLLOUT))
190                                 goto oom4;
191
192                         return wsi;
193                 }
194
195                 if (LWS_ERRNO != LWS_EISCONN) {
196                         lwsl_debug("Connect failed errno=%d\n", LWS_ERRNO);
197                         goto failed;
198                 }
199         }
200
201         lwsl_client("connected\n");
202
203         /* we are connected to server, or proxy */
204
205         if (context->http_proxy_port) {
206
207                 /* OK from now on we talk via the proxy, so connect to that */
208
209                 /*
210                  * (will overwrite existing pointer,
211                  * leaving old string/frag there but unreferenced)
212                  */
213                 if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS,
214                                                    context->http_proxy_address))
215                         goto failed;
216                 wsi->u.hdr.ah->c_port = context->http_proxy_port;
217
218                 n = send(wsi->sock, context->service_buffer, plen, MSG_NOSIGNAL);
219                 if (n < 0) {
220                         lwsl_debug("ERROR writing to proxy socket\n");
221                         goto failed;
222                 }
223
224                 libwebsocket_set_timeout(wsi,
225                         PENDING_TIMEOUT_AWAITING_PROXY_RESPONSE,
226                                                               AWAITING_TIMEOUT);
227
228                 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY;
229
230                 return wsi;
231         }
232
233         /*
234          * provoke service to issue the handshake directly
235          * we need to do it this way because in the proxy case, this is the
236          * next state and executed only if and when we get a good proxy
237          * response inside the state machine... but notice in SSL case this
238          * may not have sent anything yet with 0 return, and won't until some
239          * many retries from main loop.  To stop that becoming endless,
240          * cover with a timeout.
241          */
242
243         libwebsocket_set_timeout(wsi,
244                 PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE, AWAITING_TIMEOUT);
245
246         wsi->mode = LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE;
247         pfd.fd = wsi->sock;
248         pfd.revents = LWS_POLLIN;
249
250         n = libwebsocket_service_fd(context, &pfd);
251
252         if (n < 0)
253                 goto failed;
254
255         if (n) /* returns 1 on failure after closing wsi */
256                 return NULL;
257
258         return wsi;
259
260 oom4:
261         free(wsi->u.hdr.ah);
262         free(wsi);
263         return NULL;
264
265 failed:
266         libwebsocket_close_and_free_session(context, wsi,
267                                                      LWS_CLOSE_STATUS_NOSTATUS);
268         return NULL;
269 }
270
271 /**
272  * libwebsocket_client_connect() - Connect to another websocket server
273  * @context:    Websocket context
274  * @address:    Remote server address, eg, "myserver.com"
275  * @port:       Port to connect to on the remote server, eg, 80
276  * @ssl_connection:     0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self
277  *                      signed certs
278  * @path:       Websocket path on server
279  * @host:       Hostname on server
280  * @origin:     Socket origin name
281  * @protocol:   Comma-separated list of protocols being asked for from
282  *              the server, or just one.  The server will pick the one it
283  *              likes best.
284  * @ietf_version_or_minus_one: -1 to ask to connect using the default, latest
285  *              protocol supported, or the specific protocol ordinal
286  *
287  *      This function creates a connection to a remote server
288  */
289
290 LWS_VISIBLE struct libwebsocket *
291 libwebsocket_client_connect(struct libwebsocket_context *context,
292                               const char *address,
293                               int port,
294                               int ssl_connection,
295                               const char *path,
296                               const char *host,
297                               const char *origin,
298                               const char *protocol,
299                               int ietf_version_or_minus_one)
300 {
301         struct libwebsocket *wsi;
302
303 #ifndef LWS_OPENSSL_SUPPORT
304         if (ssl_connection) {
305                 lwsl_err("libwebsockets not configured for ssl\n");
306                 return NULL;
307         }
308 #endif
309
310         wsi = (struct libwebsocket *) malloc(sizeof(struct libwebsocket));
311         if (wsi == NULL)
312                 goto bail;
313
314         memset(wsi, 0, sizeof(*wsi));
315         wsi->sock = -1;
316
317         /* -1 means just use latest supported */
318
319         if (ietf_version_or_minus_one == -1)
320                 ietf_version_or_minus_one = SPEC_LATEST_SUPPORTED;
321
322         wsi->ietf_spec_revision = ietf_version_or_minus_one;
323         wsi->user_space = NULL;
324         wsi->state = WSI_STATE_CLIENT_UNCONNECTED;
325         wsi->protocol = NULL;
326         wsi->pending_timeout = NO_PENDING_TIMEOUT;
327
328 #ifdef LWS_OPENSSL_SUPPORT
329         wsi->use_ssl = ssl_connection;
330 #endif
331
332         if (lws_allocate_header_table(wsi))
333                 goto bail;
334
335         /*
336          * we're not necessarily in a position to action these right away,
337          * stash them... we only need during connect phase so u.hdr is fine
338          */
339         wsi->u.hdr.ah->c_port = port;
340         if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS, address))
341                 goto bail1;
342
343         /* these only need u.hdr lifetime as well */
344
345         if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_URI, path))
346                 goto bail1;
347
348         if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_HOST, host))
349                 goto bail1;
350
351         if (origin)
352                 if (lws_hdr_simple_create(wsi,
353                                 _WSI_TOKEN_CLIENT_ORIGIN, origin))
354                         goto bail1;
355         /*
356          * this is a list of protocols we tell the server we're okay with
357          * stash it for later when we compare server response with it
358          */
359         if (protocol)
360                 if (lws_hdr_simple_create(wsi,
361                                 _WSI_TOKEN_CLIENT_SENT_PROTOCOLS, protocol))
362                         goto bail1;
363
364         wsi->protocol = &context->protocols[0];
365
366         /*
367          * Check with each extension if it is able to route and proxy this
368          * connection for us.  For example, an extension like x-google-mux
369          * can handle this and then we don't need an actual socket for this
370          * connection.
371          */
372         
373         if (lws_ext_callback_for_each_extension_type(context, wsi,
374                         LWS_EXT_CALLBACK_CAN_PROXY_CLIENT_CONNECTION,
375                                                 (void *)address, port) > 0) {
376                 lwsl_client("libwebsocket_client_connect: ext handling conn\n");
377
378                 libwebsocket_set_timeout(wsi,
379                         PENDING_TIMEOUT_AWAITING_EXTENSION_CONNECT_RESPONSE,
380                                                               AWAITING_TIMEOUT);
381
382                 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT;
383                 return wsi;
384         }
385         lwsl_client("libwebsocket_client_connect: direct conn\n");
386
387        return libwebsocket_client_connect_2(context, wsi);
388
389 bail1:
390         free(wsi->u.hdr.ah);
391 bail:
392         free(wsi);
393
394         return NULL;
395 }
396
397
398 /**
399  * libwebsocket_client_connect_extended() - Connect to another websocket server
400  * @context:    Websocket context
401  * @address:    Remote server address, eg, "myserver.com"
402  * @port:       Port to connect to on the remote server, eg, 80
403  * @ssl_connection:     0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self
404  *                      signed certs
405  * @path:       Websocket path on server
406  * @host:       Hostname on server
407  * @origin:     Socket origin name
408  * @protocol:   Comma-separated list of protocols being asked for from
409  *              the server, or just one.  The server will pick the one it
410  *              likes best.
411  * @ietf_version_or_minus_one: -1 to ask to connect using the default, latest
412  *              protocol supported, or the specific protocol ordinal
413  * @userdata: Pre-allocated user data
414  *
415  *      This function creates a connection to a remote server
416  */
417
418 LWS_VISIBLE struct libwebsocket *
419 libwebsocket_client_connect_extended(struct libwebsocket_context *context,
420                               const char *address,
421                               int port,
422                               int ssl_connection,
423                               const char *path,
424                               const char *host,
425                               const char *origin,
426                               const char *protocol,
427                               int ietf_version_or_minus_one,
428                               void *userdata)
429 {
430         struct libwebsocket *ws =
431                 libwebsocket_client_connect(context, address, port,
432                         ssl_connection, path, host, origin, protocol,
433                                                      ietf_version_or_minus_one);
434
435         if (ws && !ws->user_space && userdata)
436                 ws->user_space = userdata ;
437
438         return ws ;
439 }