refactor ssl related code into ssl.c
[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         wsi = (struct libwebsocket *) malloc(sizeof(struct libwebsocket));
304         if (wsi == NULL)
305                 goto bail;
306
307         memset(wsi, 0, sizeof(*wsi));
308         wsi->sock = -1;
309
310         /* -1 means just use latest supported */
311
312         if (ietf_version_or_minus_one == -1)
313                 ietf_version_or_minus_one = SPEC_LATEST_SUPPORTED;
314
315         wsi->ietf_spec_revision = ietf_version_or_minus_one;
316         wsi->user_space = NULL;
317         wsi->state = WSI_STATE_CLIENT_UNCONNECTED;
318         wsi->protocol = NULL;
319         wsi->pending_timeout = NO_PENDING_TIMEOUT;
320
321 #ifdef LWS_OPENSSL_SUPPORT
322         wsi->use_ssl = ssl_connection;
323 #else
324         if (ssl_connection) {
325                 lwsl_err("libwebsockets not configured for ssl\n");
326                 goto bail;
327         }
328 #endif
329
330         if (lws_allocate_header_table(wsi))
331                 goto bail;
332
333         /*
334          * we're not necessarily in a position to action these right away,
335          * stash them... we only need during connect phase so u.hdr is fine
336          */
337         wsi->u.hdr.ah->c_port = port;
338         if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS, address))
339                 goto bail1;
340
341         /* these only need u.hdr lifetime as well */
342
343         if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_URI, path))
344                 goto bail1;
345
346         if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_HOST, host))
347                 goto bail1;
348
349         if (origin)
350                 if (lws_hdr_simple_create(wsi,
351                                 _WSI_TOKEN_CLIENT_ORIGIN, origin))
352                         goto bail1;
353         /*
354          * this is a list of protocols we tell the server we're okay with
355          * stash it for later when we compare server response with it
356          */
357         if (protocol)
358                 if (lws_hdr_simple_create(wsi,
359                                 _WSI_TOKEN_CLIENT_SENT_PROTOCOLS, protocol))
360                         goto bail1;
361
362         wsi->protocol = &context->protocols[0];
363
364         /*
365          * Check with each extension if it is able to route and proxy this
366          * connection for us.  For example, an extension like x-google-mux
367          * can handle this and then we don't need an actual socket for this
368          * connection.
369          */
370         
371         if (lws_ext_callback_for_each_extension_type(context, wsi,
372                         LWS_EXT_CALLBACK_CAN_PROXY_CLIENT_CONNECTION,
373                                                 (void *)address, port) > 0) {
374                 lwsl_client("libwebsocket_client_connect: ext handling conn\n");
375
376                 libwebsocket_set_timeout(wsi,
377                         PENDING_TIMEOUT_AWAITING_EXTENSION_CONNECT_RESPONSE,
378                                                               AWAITING_TIMEOUT);
379
380                 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT;
381                 return wsi;
382         }
383         lwsl_client("libwebsocket_client_connect: direct conn\n");
384
385        return libwebsocket_client_connect_2(context, wsi);
386
387 bail1:
388         free(wsi->u.hdr.ah);
389 bail:
390         free(wsi);
391
392         return NULL;
393 }
394
395
396 /**
397  * libwebsocket_client_connect_extended() - Connect to another websocket server
398  * @context:    Websocket context
399  * @address:    Remote server address, eg, "myserver.com"
400  * @port:       Port to connect to on the remote server, eg, 80
401  * @ssl_connection:     0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self
402  *                      signed certs
403  * @path:       Websocket path on server
404  * @host:       Hostname on server
405  * @origin:     Socket origin name
406  * @protocol:   Comma-separated list of protocols being asked for from
407  *              the server, or just one.  The server will pick the one it
408  *              likes best.
409  * @ietf_version_or_minus_one: -1 to ask to connect using the default, latest
410  *              protocol supported, or the specific protocol ordinal
411  * @userdata: Pre-allocated user data
412  *
413  *      This function creates a connection to a remote server
414  */
415
416 LWS_VISIBLE struct libwebsocket *
417 libwebsocket_client_connect_extended(struct libwebsocket_context *context,
418                               const char *address,
419                               int port,
420                               int ssl_connection,
421                               const char *path,
422                               const char *host,
423                               const char *origin,
424                               const char *protocol,
425                               int ietf_version_or_minus_one,
426                               void *userdata)
427 {
428         struct libwebsocket *ws =
429                 libwebsocket_client_connect(context, address, port,
430                         ssl_connection, path, host, origin, protocol,
431                                                      ietf_version_or_minus_one);
432
433         if (ws && !ws->user_space && userdata)
434                 ws->user_space = userdata ;
435
436         return ws ;
437 }