blob: 5f487e5e3ae167541991e896f34cb356f79a0c8f [file] [log] [blame]
Andy Green4739e5c2011-01-22 12:51:57 +00001#include "private-libwebsockets.h"
2#include <netdb.h>
3
4
5/*
6 * In-place str to lower case
7 */
8
9void
10strtolower(char *s)
11{
Andy Green90c7cbc2011-01-27 06:26:52 +000012 while (*s) {
13 *s = tolower(*s);
14 s++;
15 }
Andy Green4739e5c2011-01-22 12:51:57 +000016}
17
18void
19libwebsocket_client_close(struct libwebsocket *wsi)
20{
21 int n = wsi->state;
22 struct libwebsocket_context *clients;
23
24 /* mark the WSI as dead and let the callback know */
25
26 wsi->state = WSI_STATE_DEAD_SOCKET;
27
28 if (wsi->protocol) {
29 if (wsi->protocol->callback && n == WSI_STATE_ESTABLISHED)
30 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
31 wsi->user_space, NULL, 0);
32
33 /* remove it from the client polling list */
34 clients = wsi->protocol->owning_server;
35 if (clients)
36 for (n = 0; n < clients->fds_count; n++) {
37 if (clients->wsi[n] != wsi)
38 continue;
39 while (n < clients->fds_count - 1) {
40 clients->fds[n] = clients->fds[n + 1];
41 clients->wsi[n] = clients->wsi[n + 1];
42 }
43 /* we only have to deal with one */
44 n = clients->fds_count;
45 }
46
47 }
48
49 /* clean out any parsing allocations */
50
51 for (n = 0; n < WSI_TOKEN_COUNT; n++)
52 if (wsi->utf8_token[n].token)
53 free(wsi->utf8_token[n].token);
54
55 /* shut down reasonably cleanly */
56
57#ifdef LWS_OPENSSL_SUPPORT
Andy Green90c7cbc2011-01-27 06:26:52 +000058 if (wsi->ssl) {
Andy Green4739e5c2011-01-22 12:51:57 +000059 n = SSL_get_fd(wsi->ssl);
60 SSL_shutdown(wsi->ssl);
61 close(n);
62 SSL_free(wsi->ssl);
63 } else {
64#endif
65 shutdown(wsi->sock, SHUT_RDWR);
66 close(wsi->sock);
67#ifdef LWS_OPENSSL_SUPPORT
68 }
69#endif
70}
71
Andy Green90c7cbc2011-01-27 06:26:52 +000072
73/**
74 * libwebsocket_client_connect() - Connect to another websocket server
75 * @this: Websocket context
76 * @address: Remote server address, eg, "myserver.com"
77 * @port: Port to connect to on the remote server, eg, 80
78 * @ssl_connection: 0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self
79 * signed certs
80 * @path: Websocket path on server
81 * @host: Hostname on server
82 * @origin: Socket origin name
83 * @protocol: Comma-separated list of protocols being asked for from
84 * the server, or just one. The server will pick the one it
85 * likes best.
86 *
87 * This function creates a connection to a remote server
88 */
89
Andy Green4739e5c2011-01-22 12:51:57 +000090struct libwebsocket *
Andy Green90c7cbc2011-01-27 06:26:52 +000091libwebsocket_client_connect(struct libwebsocket_context *this,
Andy Green4739e5c2011-01-22 12:51:57 +000092 const char *address,
93 int port,
Andy Green90c7cbc2011-01-27 06:26:52 +000094 int ssl_connection,
Andy Green4739e5c2011-01-22 12:51:57 +000095 const char *path,
96 const char *host,
97 const char *origin,
98 const char *protocol)
99{
100 struct hostent *server_hostent;
101 struct sockaddr_in server_addr;
102 char buf[150];
103 char key_b64[150];
104 char hash[20];
105 int fd;
106 struct pollfd pfd;
107 static const char magic_websocket_guid[] =
108 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
109 static const char magic_websocket_04_masking_guid[] =
110 "61AC5F19-FBBA-4540-B96F-6561F1AB40A8";
111 char pkt[1024];
112 char *p = &pkt[0];
Andy Green6964bb52011-01-23 16:50:33 +0000113 const char *pc;
Andy Green4739e5c2011-01-22 12:51:57 +0000114 int len;
115 int okay = 0;
116 struct libwebsocket *wsi;
117 int n;
Andy Green9659f372011-01-27 22:01:43 +0000118 int plen = 0;
Andy Green90c7cbc2011-01-27 06:26:52 +0000119#ifdef LWS_OPENSSL_SUPPORT
120 char ssl_err_buf[512];
121#else
122 if (ssl_connection) {
123 fprintf(stderr, "libwebsockets not configured for ssl\n");
124 return NULL;
125 }
126#endif
Andy Green4739e5c2011-01-22 12:51:57 +0000127
Andy Green6964bb52011-01-23 16:50:33 +0000128 wsi = malloc(sizeof(struct libwebsocket));
Andy Green90c7cbc2011-01-27 06:26:52 +0000129 if (wsi == NULL) {
Andy Green9659f372011-01-27 22:01:43 +0000130 fprintf(stderr, "Out of memory allocing new connection\n");
Andy Green4739e5c2011-01-22 12:51:57 +0000131 return NULL;
Andy Green90c7cbc2011-01-27 06:26:52 +0000132 }
Andy Green4739e5c2011-01-22 12:51:57 +0000133
Andy Green90c7cbc2011-01-27 06:26:52 +0000134 this->wsi[this->fds_count] = wsi;
Andy Green4739e5c2011-01-22 12:51:57 +0000135
136 wsi->ietf_spec_revision = 4;
137 wsi->name_buffer_pos = 0;
138 wsi->user_space = NULL;
139 wsi->state = WSI_STATE_CLIENT_UNCONNECTED;
140 wsi->pings_vs_pongs = 0;
141
142 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
143 wsi->utf8_token[n].token = NULL;
144 wsi->utf8_token[n].token_len = 0;
145 }
146
147 /*
Andy Green9659f372011-01-27 22:01:43 +0000148 * proxy?
149 */
150
151 if (this->http_proxy_port) {
152 plen = sprintf(pkt, "CONNECT %s:%u HTTP/1.0\x0d\x0a"
153 "User-agent: libwebsockets\x0d\x0a"
154/*Proxy-authorization: basic aGVsbG86d29ybGQ= */
155 "\x0d\x0a", address, port);
156
157 /* OK from now on we talk via the proxy */
158
159 address = this->http_proxy_address;
160 port = this->http_proxy_port;
161 }
162
163 /*
164 * prepare the actual connection (to the proxy, if any)
Andy Green4739e5c2011-01-22 12:51:57 +0000165 */
166
167 server_hostent = gethostbyname(address);
168 if (server_hostent == NULL) {
169 fprintf(stderr, "Unable to get host name from %s\n", address);
170 goto bail1;
171 }
172
173 wsi->sock = socket(AF_INET, SOCK_STREAM, 0);
Andy Green6964bb52011-01-23 16:50:33 +0000174
Andy Green4739e5c2011-01-22 12:51:57 +0000175 if (wsi->sock < 0) {
176 fprintf(stderr, "Unable to open socket\n");
177 goto bail1;
178 }
179
180
181 server_addr.sin_family = AF_INET;
182 server_addr.sin_port = htons(port);
183 server_addr.sin_addr = *((struct in_addr *)server_hostent->h_addr);
184 bzero(&server_addr.sin_zero, 8);
185
186 if (connect(wsi->sock, (struct sockaddr *)&server_addr,
187 sizeof(struct sockaddr)) == -1) {
Andy Green90c7cbc2011-01-27 06:26:52 +0000188 fprintf(stderr, "Connect failed\n");
Andy Green4739e5c2011-01-22 12:51:57 +0000189 goto bail1;
Andy Green6964bb52011-01-23 16:50:33 +0000190 }
Andy Green4739e5c2011-01-22 12:51:57 +0000191
Andy Green9659f372011-01-27 22:01:43 +0000192 /* we are connected to server, or proxy */
193
194 /* non-SSL connection */
195
196 if (this->http_proxy_port) {
197
198 n = send(wsi->sock, pkt, plen, 0);
199 if (n < 0) {
200 fprintf(stderr, "ERROR writing to "
201 "proxy socket\n");
202 goto bail2;
203 }
204
205 n = recv(wsi->sock, pkt, sizeof pkt, 0);
206 if (n < 0) {
207 fprintf(stderr, "ERROR reading from "
208 "proxy socket\n");
209 goto bail2;
210 }
211
212 pkt[13] = '\0';
213 if (strcmp(pkt, "HTTP/1.0 200 ") != 0) {
214 fprintf(stderr, "ERROR from proxy: %s\n", pkt);
215 goto bail2;
216 }
217
218 /* we can just start sending to proxy */
219 }
220
Andy Green90c7cbc2011-01-27 06:26:52 +0000221#ifdef LWS_OPENSSL_SUPPORT
222 if (ssl_connection) {
223
224 wsi->ssl = SSL_new(this->ssl_client_ctx);
225 wsi->client_bio = BIO_new_socket(wsi->sock, BIO_NOCLOSE);
226 SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
227
228 if (SSL_connect(wsi->ssl) <= 0) {
229 fprintf(stderr, "SSL connect error %s\n",
230 ERR_error_string(ERR_get_error(), ssl_err_buf));
Andy Green9659f372011-01-27 22:01:43 +0000231 goto bail1;
Andy Green90c7cbc2011-01-27 06:26:52 +0000232 }
233
234 n = SSL_get_verify_result(wsi->ssl);
235 if (n != X509_V_OK) {
Andy Green9659f372011-01-27 22:01:43 +0000236 if (n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
237 ssl_connection != 2) {
Andy Green90c7cbc2011-01-27 06:26:52 +0000238
Andy Green9659f372011-01-27 22:01:43 +0000239 fprintf(stderr, "server's cert didn't "
240 "look good %d\n", n);
241 goto bail2;
242 }
Andy Green90c7cbc2011-01-27 06:26:52 +0000243 }
Andy Green9659f372011-01-27 22:01:43 +0000244 } else {
Andy Green90c7cbc2011-01-27 06:26:52 +0000245 wsi->ssl = NULL;
Andy Green90c7cbc2011-01-27 06:26:52 +0000246#endif
Andy Green9659f372011-01-27 22:01:43 +0000247
248
249#ifdef LWS_OPENSSL_SUPPORT
250 }
251#endif
252
Andy Green6964bb52011-01-23 16:50:33 +0000253 /*
254 * create the random key
255 */
Andy Green4739e5c2011-01-22 12:51:57 +0000256
257 fd = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
258 if (fd < 1) {
259 fprintf(stderr, "Unable to open random device %s\n",
260 SYSTEM_RANDOM_FILEPATH);
261 goto bail2;
262 }
263 n = read(fd, hash, 16);
264 if (n != 16) {
265 fprintf(stderr, "Unable to read from random device %s\n",
266 SYSTEM_RANDOM_FILEPATH);
267 close(fd);
268 goto bail2;
269 }
270 close(fd);
271
Andy Green6964bb52011-01-23 16:50:33 +0000272 lws_b64_encode_string(hash, 16, key_b64, sizeof key_b64);
Andy Green4739e5c2011-01-22 12:51:57 +0000273
274 /*
275 * 04 example client handshake
276 *
277 * GET /chat HTTP/1.1
278 * Host: server.example.com
279 * Upgrade: websocket
280 * Connection: Upgrade
281 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
282 * Sec-WebSocket-Origin: http://example.com
283 * Sec-WebSocket-Protocol: chat, superchat
284 * Sec-WebSocket-Version: 4
285 */
286
287 p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", path);
288 p += sprintf(p, "Host: %s\x0d\x0a", host);
289 p += sprintf(p, "Upgrade: websocket\x0d\x0a");
290 p += sprintf(p, "Connection: Upgrade\x0d\x0aSec-WebSocket-Key: ");
291 strcpy(p, key_b64);
292 p += strlen(key_b64);
293 p += sprintf(p, "\x0d\x0aSec-WebSocket-Origin: %s\x0d\x0a", origin);
294 if (protocol != NULL)
295 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a", protocol);
296 p += sprintf(p, "Sec-WebSocket-Version: 4\x0d\x0a\x0d\x0a");
297
298
299 /* prepare the expected server accept response */
300
301 strcpy(buf, key_b64);
302 strcpy(&buf[strlen(buf)], magic_websocket_guid);
303
304 SHA1((unsigned char *)buf, strlen(buf), (unsigned char *)hash);
305
306 lws_b64_encode_string(hash, 20, wsi->initial_handshake_hash_base64,
307 sizeof wsi->initial_handshake_hash_base64);
308
309 /* send our request to the server */
310
Andy Green90c7cbc2011-01-27 06:26:52 +0000311#ifdef LWS_OPENSSL_SUPPORT
312 if (ssl_connection)
313 n = SSL_write(wsi->ssl, pkt, p - pkt);
314 else
315#endif
316 n = send(wsi->sock, pkt, p - pkt, 0);
317
318 if (n < 0) {
319 fprintf(stderr, "ERROR writing to client socket\n");
320 goto bail2;
321 }
Andy Green4739e5c2011-01-22 12:51:57 +0000322
323 wsi->parser_state = WSI_TOKEN_NAME_PART;
324
325 pfd.fd = wsi->sock;
326 pfd.events = POLLIN;
327 pfd.revents = 0;
328
329 n = poll(&pfd, 1, 5000);
330 if (n < 0) {
331 fprintf(stderr, "libwebsocket_client_handshake socket error "
332 "while waiting for handshake response");
333 goto bail2;
334 }
335 if (n == 0) {
336 fprintf(stderr, "libwebsocket_client_handshake timeout "
337 "while waiting for handshake response");
338 goto bail2;
339 }
340
341 /* interpret the server response */
342
343 /*
344 * HTTP/1.1 101 Switching Protocols
345 * Upgrade: websocket
346 * Connection: Upgrade
347 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
348 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
349 * Sec-WebSocket-Protocol: chat
350 */
351
Andy Green90c7cbc2011-01-27 06:26:52 +0000352#ifdef LWS_OPENSSL_SUPPORT
353 if (ssl_connection)
354 len = SSL_read(wsi->ssl, pkt, sizeof pkt);
355 else
356#endif
357 len = recv(wsi->sock, pkt, sizeof pkt, 0);
358
Andy Green4739e5c2011-01-22 12:51:57 +0000359 if (len < 0) {
360 fprintf(stderr, "libwebsocket_client_handshake read error\n");
361 goto bail2;
362 }
363
364 p = pkt;
365 for (n = 0; n < len; n++)
366 libwebsocket_parse(wsi, *p++);
367
368 if (wsi->parser_state != WSI_PARSING_COMPLETE) {
369 fprintf(stderr, "libwebsocket_client_handshake server response"
370 " failed parsing\n");
371 goto bail2;
372 }
373
374 /*
375 * well, what the server sent looked reasonable for syntax.
376 * Now let's confirm it sent all the necessary headers
377 */
378
379 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
380 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
381 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
382 !wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len ||
383 !wsi->utf8_token[WSI_TOKEN_NONCE].token_len ||
384 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
385 protocol != NULL)) {
386 fprintf(stderr, "libwebsocket_client_handshake "
387 "missing required header\n");
388 goto bail2;
389 }
390
391 /*
392 * Everything seems to be there, now take a closer look at what is in
393 * each header
394 */
395
396 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
397 if (strcmp(wsi->utf8_token[WSI_TOKEN_HTTP].token,
398 "101 switching protocols")) {
399 fprintf(stderr, "libwebsocket_client_handshake server sent bad"
400 " HTTP response '%s'\n",
401 wsi->utf8_token[WSI_TOKEN_HTTP].token);
402 goto bail2;
403 }
404
405 strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
406 if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token, "websocket")) {
407 fprintf(stderr, "libwebsocket_client_handshake server sent bad"
408 " Upgrade header '%s'\n",
409 wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
410 goto bail2;
Andy Green6964bb52011-01-23 16:50:33 +0000411 }
Andy Green4739e5c2011-01-22 12:51:57 +0000412
413 strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
414 if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token, "upgrade")) {
415 fprintf(stderr, "libwebsocket_client_handshake server sent bad"
416 " Connection hdr '%s'\n",
417 wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
418 goto bail2;
419 }
420 /*
421 * confirm the protocol the server wants to talk was in the list of
422 * protocols we offered
423 */
424
425 if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
426
427 /* no protocol name to work from, default to first protocol */
Andy Green90c7cbc2011-01-27 06:26:52 +0000428 wsi->protocol = &this->protocols[0];
Andy Green4739e5c2011-01-22 12:51:57 +0000429
430 goto check_accept;
431 }
432
433 pc = protocol;
434 while (*pc && !okay) {
435 if ((!strncmp(pc, wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
436 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len)) &&
437 (pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == ',' ||
438 pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == '\0')) {
439 okay = 1;
440 continue;
441 }
442 while (*pc && *pc != ',')
443 pc++;
444 while (*pc && *pc != ' ')
445 pc++;
446 }
447 if (!okay) {
448 fprintf(stderr, "libwebsocket_client_handshake server "
449 "sent bad protocol '%s'\n",
450 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
451 goto bail2;
452 }
453
454 /*
455 * identify the selected protocol struct and set it
456 */
457 n = 0;
458 wsi->protocol = NULL;
Andy Green90c7cbc2011-01-27 06:26:52 +0000459 while (this->protocols[n].callback) {
Andy Green4739e5c2011-01-22 12:51:57 +0000460 if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
Andy Green90c7cbc2011-01-27 06:26:52 +0000461 this->protocols[n].name) == 0)
462 wsi->protocol = &this->protocols[n];
Andy Green4739e5c2011-01-22 12:51:57 +0000463 n++;
464 }
465
466 if (wsi->protocol == NULL) {
467 fprintf(stderr, "libwebsocket_client_handshake server "
468 "requested protocol '%s', which we "
469 "said we supported but we don't!\n",
470 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
471 goto bail2;
472 }
473
474check_accept:
475 /*
476 * Confirm his accept token is the same as the one we precomputed
477 */
478
479 if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
480 wsi->initial_handshake_hash_base64)) {
481 fprintf(stderr, "libwebsocket_client_handshake server sent "
482 "bad ACCEPT '%s' vs computed '%s'\n",
483 wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
484 wsi->initial_handshake_hash_base64);
485 goto bail2;
486 }
487
488 /*
489 * Calculate the masking key to use when sending data to server
490 */
491
492 strcpy(buf, key_b64);
493 p = buf + strlen(key_b64);
494 strcpy(p, wsi->utf8_token[WSI_TOKEN_NONCE].token);
495 p += wsi->utf8_token[WSI_TOKEN_NONCE].token_len;
496 strcpy(p, magic_websocket_04_masking_guid);
497 SHA1((unsigned char *)buf, strlen(buf), wsi->masking_key_04);
498
499 /* okay he is good to go */
500
Andy Green90c7cbc2011-01-27 06:26:52 +0000501 this->fds[this->fds_count].fd = wsi->sock;
502 this->fds[this->fds_count].revents = 0;
503 this->fds[this->fds_count++].events = POLLIN;
Andy Green4739e5c2011-01-22 12:51:57 +0000504
505 wsi->state = WSI_STATE_ESTABLISHED;
506 wsi->client_mode = 1;
507
508 fprintf(stderr, "handshake OK for protocol %s\n", wsi->protocol->name);
509
Andy Green90c7cbc2011-01-27 06:26:52 +0000510 /* call him back to inform him he is up */
511
512 wsi->protocol->callback(wsi,
513 LWS_CALLBACK_CLIENT_ESTABLISHED,
514 wsi->user_space,
515 NULL, 0);
Andy Green4739e5c2011-01-22 12:51:57 +0000516 return wsi;
517
518
519bail2:
520 libwebsocket_client_close(wsi);
521bail1:
522 free(wsi);
523
524 return NULL;
525}