blob: e93ce99061ec6f0934925882c4a02e31b719f730 [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 Green90c7cbc2011-01-27 06:26:52 +0000118#ifdef LWS_OPENSSL_SUPPORT
119 char ssl_err_buf[512];
120#else
121 if (ssl_connection) {
122 fprintf(stderr, "libwebsockets not configured for ssl\n");
123 return NULL;
124 }
125#endif
Andy Green4739e5c2011-01-22 12:51:57 +0000126
Andy Green6964bb52011-01-23 16:50:33 +0000127 wsi = malloc(sizeof(struct libwebsocket));
Andy Green90c7cbc2011-01-27 06:26:52 +0000128 if (wsi == NULL) {
129 fprintf(stderr, "Out of memort allocing new connection\n");
Andy Green4739e5c2011-01-22 12:51:57 +0000130 return NULL;
Andy Green90c7cbc2011-01-27 06:26:52 +0000131 }
Andy Green4739e5c2011-01-22 12:51:57 +0000132
Andy Green90c7cbc2011-01-27 06:26:52 +0000133 this->wsi[this->fds_count] = wsi;
Andy Green4739e5c2011-01-22 12:51:57 +0000134
135 wsi->ietf_spec_revision = 4;
136 wsi->name_buffer_pos = 0;
137 wsi->user_space = NULL;
138 wsi->state = WSI_STATE_CLIENT_UNCONNECTED;
139 wsi->pings_vs_pongs = 0;
140
141 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
142 wsi->utf8_token[n].token = NULL;
143 wsi->utf8_token[n].token_len = 0;
144 }
145
146 /*
147 * prepare the actual connection
148 */
149
150 server_hostent = gethostbyname(address);
151 if (server_hostent == NULL) {
152 fprintf(stderr, "Unable to get host name from %s\n", address);
153 goto bail1;
154 }
155
156 wsi->sock = socket(AF_INET, SOCK_STREAM, 0);
Andy Green6964bb52011-01-23 16:50:33 +0000157
Andy Green4739e5c2011-01-22 12:51:57 +0000158 if (wsi->sock < 0) {
159 fprintf(stderr, "Unable to open socket\n");
160 goto bail1;
161 }
162
163
164 server_addr.sin_family = AF_INET;
165 server_addr.sin_port = htons(port);
166 server_addr.sin_addr = *((struct in_addr *)server_hostent->h_addr);
167 bzero(&server_addr.sin_zero, 8);
168
169 if (connect(wsi->sock, (struct sockaddr *)&server_addr,
170 sizeof(struct sockaddr)) == -1) {
Andy Green90c7cbc2011-01-27 06:26:52 +0000171 fprintf(stderr, "Connect failed\n");
Andy Green4739e5c2011-01-22 12:51:57 +0000172 goto bail1;
Andy Green6964bb52011-01-23 16:50:33 +0000173 }
Andy Green4739e5c2011-01-22 12:51:57 +0000174
Andy Green90c7cbc2011-01-27 06:26:52 +0000175#ifdef LWS_OPENSSL_SUPPORT
176 if (ssl_connection) {
177
178 wsi->ssl = SSL_new(this->ssl_client_ctx);
179 wsi->client_bio = BIO_new_socket(wsi->sock, BIO_NOCLOSE);
180 SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
181
182 if (SSL_connect(wsi->ssl) <= 0) {
183 fprintf(stderr, "SSL connect error %s\n",
184 ERR_error_string(ERR_get_error(), ssl_err_buf));
185 goto bail2;
186 }
187
188 n = SSL_get_verify_result(wsi->ssl);
189 if (n != X509_V_OK) {
190 if (n == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT &&
191 ssl_connection == 2)
192 goto cert_okay;
193
194 fprintf(stderr, "server's cert didn't look good %d\n", n);
195 goto bail2;
196 }
197 } else
198 wsi->ssl = NULL;
199cert_okay:
200#endif
Andy Green6964bb52011-01-23 16:50:33 +0000201 /*
202 * create the random key
203 */
Andy Green4739e5c2011-01-22 12:51:57 +0000204
205 fd = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
206 if (fd < 1) {
207 fprintf(stderr, "Unable to open random device %s\n",
208 SYSTEM_RANDOM_FILEPATH);
209 goto bail2;
210 }
211 n = read(fd, hash, 16);
212 if (n != 16) {
213 fprintf(stderr, "Unable to read from random device %s\n",
214 SYSTEM_RANDOM_FILEPATH);
215 close(fd);
216 goto bail2;
217 }
218 close(fd);
219
Andy Green6964bb52011-01-23 16:50:33 +0000220 lws_b64_encode_string(hash, 16, key_b64, sizeof key_b64);
Andy Green4739e5c2011-01-22 12:51:57 +0000221
222 /*
223 * 04 example client handshake
224 *
225 * GET /chat HTTP/1.1
226 * Host: server.example.com
227 * Upgrade: websocket
228 * Connection: Upgrade
229 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
230 * Sec-WebSocket-Origin: http://example.com
231 * Sec-WebSocket-Protocol: chat, superchat
232 * Sec-WebSocket-Version: 4
233 */
234
235 p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", path);
236 p += sprintf(p, "Host: %s\x0d\x0a", host);
237 p += sprintf(p, "Upgrade: websocket\x0d\x0a");
238 p += sprintf(p, "Connection: Upgrade\x0d\x0aSec-WebSocket-Key: ");
239 strcpy(p, key_b64);
240 p += strlen(key_b64);
241 p += sprintf(p, "\x0d\x0aSec-WebSocket-Origin: %s\x0d\x0a", origin);
242 if (protocol != NULL)
243 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a", protocol);
244 p += sprintf(p, "Sec-WebSocket-Version: 4\x0d\x0a\x0d\x0a");
245
246
247 /* prepare the expected server accept response */
248
249 strcpy(buf, key_b64);
250 strcpy(&buf[strlen(buf)], magic_websocket_guid);
251
252 SHA1((unsigned char *)buf, strlen(buf), (unsigned char *)hash);
253
254 lws_b64_encode_string(hash, 20, wsi->initial_handshake_hash_base64,
255 sizeof wsi->initial_handshake_hash_base64);
256
257 /* send our request to the server */
258
Andy Green90c7cbc2011-01-27 06:26:52 +0000259#ifdef LWS_OPENSSL_SUPPORT
260 if (ssl_connection)
261 n = SSL_write(wsi->ssl, pkt, p - pkt);
262 else
263#endif
264 n = send(wsi->sock, pkt, p - pkt, 0);
265
266 if (n < 0) {
267 fprintf(stderr, "ERROR writing to client socket\n");
268 goto bail2;
269 }
Andy Green4739e5c2011-01-22 12:51:57 +0000270
271 wsi->parser_state = WSI_TOKEN_NAME_PART;
272
273 pfd.fd = wsi->sock;
274 pfd.events = POLLIN;
275 pfd.revents = 0;
276
277 n = poll(&pfd, 1, 5000);
278 if (n < 0) {
279 fprintf(stderr, "libwebsocket_client_handshake socket error "
280 "while waiting for handshake response");
281 goto bail2;
282 }
283 if (n == 0) {
284 fprintf(stderr, "libwebsocket_client_handshake timeout "
285 "while waiting for handshake response");
286 goto bail2;
287 }
288
289 /* interpret the server response */
290
291 /*
292 * HTTP/1.1 101 Switching Protocols
293 * Upgrade: websocket
294 * Connection: Upgrade
295 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
296 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
297 * Sec-WebSocket-Protocol: chat
298 */
299
Andy Green90c7cbc2011-01-27 06:26:52 +0000300#ifdef LWS_OPENSSL_SUPPORT
301 if (ssl_connection)
302 len = SSL_read(wsi->ssl, pkt, sizeof pkt);
303 else
304#endif
305 len = recv(wsi->sock, pkt, sizeof pkt, 0);
306
Andy Green4739e5c2011-01-22 12:51:57 +0000307 if (len < 0) {
308 fprintf(stderr, "libwebsocket_client_handshake read error\n");
309 goto bail2;
310 }
311
312 p = pkt;
313 for (n = 0; n < len; n++)
314 libwebsocket_parse(wsi, *p++);
315
316 if (wsi->parser_state != WSI_PARSING_COMPLETE) {
317 fprintf(stderr, "libwebsocket_client_handshake server response"
318 " failed parsing\n");
319 goto bail2;
320 }
321
322 /*
323 * well, what the server sent looked reasonable for syntax.
324 * Now let's confirm it sent all the necessary headers
325 */
326
327 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
328 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
329 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
330 !wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len ||
331 !wsi->utf8_token[WSI_TOKEN_NONCE].token_len ||
332 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
333 protocol != NULL)) {
334 fprintf(stderr, "libwebsocket_client_handshake "
335 "missing required header\n");
336 goto bail2;
337 }
338
339 /*
340 * Everything seems to be there, now take a closer look at what is in
341 * each header
342 */
343
344 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
345 if (strcmp(wsi->utf8_token[WSI_TOKEN_HTTP].token,
346 "101 switching protocols")) {
347 fprintf(stderr, "libwebsocket_client_handshake server sent bad"
348 " HTTP response '%s'\n",
349 wsi->utf8_token[WSI_TOKEN_HTTP].token);
350 goto bail2;
351 }
352
353 strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
354 if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token, "websocket")) {
355 fprintf(stderr, "libwebsocket_client_handshake server sent bad"
356 " Upgrade header '%s'\n",
357 wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
358 goto bail2;
Andy Green6964bb52011-01-23 16:50:33 +0000359 }
Andy Green4739e5c2011-01-22 12:51:57 +0000360
361 strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
362 if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token, "upgrade")) {
363 fprintf(stderr, "libwebsocket_client_handshake server sent bad"
364 " Connection hdr '%s'\n",
365 wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
366 goto bail2;
367 }
368 /*
369 * confirm the protocol the server wants to talk was in the list of
370 * protocols we offered
371 */
372
373 if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
374
375 /* no protocol name to work from, default to first protocol */
Andy Green90c7cbc2011-01-27 06:26:52 +0000376 wsi->protocol = &this->protocols[0];
Andy Green4739e5c2011-01-22 12:51:57 +0000377
378 goto check_accept;
379 }
380
381 pc = protocol;
382 while (*pc && !okay) {
383 if ((!strncmp(pc, wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
384 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len)) &&
385 (pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == ',' ||
386 pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == '\0')) {
387 okay = 1;
388 continue;
389 }
390 while (*pc && *pc != ',')
391 pc++;
392 while (*pc && *pc != ' ')
393 pc++;
394 }
395 if (!okay) {
396 fprintf(stderr, "libwebsocket_client_handshake server "
397 "sent bad protocol '%s'\n",
398 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
399 goto bail2;
400 }
401
402 /*
403 * identify the selected protocol struct and set it
404 */
405 n = 0;
406 wsi->protocol = NULL;
Andy Green90c7cbc2011-01-27 06:26:52 +0000407 while (this->protocols[n].callback) {
Andy Green4739e5c2011-01-22 12:51:57 +0000408 if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
Andy Green90c7cbc2011-01-27 06:26:52 +0000409 this->protocols[n].name) == 0)
410 wsi->protocol = &this->protocols[n];
Andy Green4739e5c2011-01-22 12:51:57 +0000411 n++;
412 }
413
414 if (wsi->protocol == NULL) {
415 fprintf(stderr, "libwebsocket_client_handshake server "
416 "requested protocol '%s', which we "
417 "said we supported but we don't!\n",
418 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
419 goto bail2;
420 }
421
422check_accept:
423 /*
424 * Confirm his accept token is the same as the one we precomputed
425 */
426
427 if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
428 wsi->initial_handshake_hash_base64)) {
429 fprintf(stderr, "libwebsocket_client_handshake server sent "
430 "bad ACCEPT '%s' vs computed '%s'\n",
431 wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
432 wsi->initial_handshake_hash_base64);
433 goto bail2;
434 }
435
436 /*
437 * Calculate the masking key to use when sending data to server
438 */
439
440 strcpy(buf, key_b64);
441 p = buf + strlen(key_b64);
442 strcpy(p, wsi->utf8_token[WSI_TOKEN_NONCE].token);
443 p += wsi->utf8_token[WSI_TOKEN_NONCE].token_len;
444 strcpy(p, magic_websocket_04_masking_guid);
445 SHA1((unsigned char *)buf, strlen(buf), wsi->masking_key_04);
446
447 /* okay he is good to go */
448
Andy Green90c7cbc2011-01-27 06:26:52 +0000449 this->fds[this->fds_count].fd = wsi->sock;
450 this->fds[this->fds_count].revents = 0;
451 this->fds[this->fds_count++].events = POLLIN;
Andy Green4739e5c2011-01-22 12:51:57 +0000452
453 wsi->state = WSI_STATE_ESTABLISHED;
454 wsi->client_mode = 1;
455
456 fprintf(stderr, "handshake OK for protocol %s\n", wsi->protocol->name);
457
Andy Green90c7cbc2011-01-27 06:26:52 +0000458 /* call him back to inform him he is up */
459
460 wsi->protocol->callback(wsi,
461 LWS_CALLBACK_CLIENT_ESTABLISHED,
462 wsi->user_space,
463 NULL, 0);
Andy Green4739e5c2011-01-22 12:51:57 +0000464 return wsi;
465
466
467bail2:
468 libwebsocket_client_close(wsi);
469bail1:
470 free(wsi);
471
472 return NULL;
473}