1 #include "private-libwebsockets.h"
6 * In-place str to lower case
19 libwebsocket_client_close(struct libwebsocket *wsi)
22 struct libwebsocket_context *clients;
23 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 2 +
24 LWS_SEND_BUFFER_POST_PADDING];
26 if (n == WSI_STATE_DEAD_SOCKET)
30 * signal we are closing, libsocket_write will
31 * add any necessary version-specific stuff. If the write fails,
32 * no worries we are closing anyway. If we didn't initiate this
33 * close, then our state has been changed to
34 * WSI_STATE_RETURNED_CLOSE_ALREADY and we can skip this
37 if (n == WSI_STATE_ESTABLISHED)
38 libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], 0,
40 /* mark the WSI as dead and let the callback know */
42 wsi->state = WSI_STATE_DEAD_SOCKET;
45 if (wsi->protocol->callback && n == WSI_STATE_ESTABLISHED)
46 wsi->protocol->callback(wsi, LWS_CALLBACK_CLOSED,
47 wsi->user_space, NULL, 0);
49 /* remove it from the client polling list */
50 clients = wsi->protocol->owning_server;
52 for (n = 0; n < clients->fds_count; n++) {
53 if (clients->wsi[n] != wsi)
55 while (n < clients->fds_count - 1) {
56 clients->fds[n] = clients->fds[n + 1];
57 clients->wsi[n] = clients->wsi[n + 1];
60 /* we only have to deal with one */
61 n = clients->fds_count;
66 /* clean out any parsing allocations */
68 for (n = 0; n < WSI_TOKEN_COUNT; n++)
69 if (wsi->utf8_token[n].token)
70 free(wsi->utf8_token[n].token);
72 /* shut down reasonably cleanly */
74 #ifdef LWS_OPENSSL_SUPPORT
76 n = SSL_get_fd(wsi->ssl);
77 SSL_shutdown(wsi->ssl);
82 shutdown(wsi->sock, SHUT_RDWR);
84 #ifdef LWS_OPENSSL_SUPPORT
91 * libwebsocket_client_connect() - Connect to another websocket server
92 * @this: Websocket context
93 * @address: Remote server address, eg, "myserver.com"
94 * @port: Port to connect to on the remote server, eg, 80
95 * @ssl_connection: 0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self
97 * @path: Websocket path on server
98 * @host: Hostname on server
99 * @origin: Socket origin name
100 * @protocol: Comma-separated list of protocols being asked for from
101 * the server, or just one. The server will pick the one it
103 * @ietf_version_or_minus_one: -1 to ask to connect using the default, latest
104 * protocol supported, or the specific protocol ordinal
106 * This function creates a connection to a remote server
109 struct libwebsocket *
110 libwebsocket_client_connect(struct libwebsocket_context *this,
117 const char *protocol,
118 int ietf_version_or_minus_one)
120 struct hostent *server_hostent;
121 struct sockaddr_in server_addr;
127 static const char magic_websocket_guid[] =
128 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
129 static const char magic_websocket_04_masking_guid[] =
130 "61AC5F19-FBBA-4540-B96F-6561F1AB40A8";
136 struct libwebsocket *wsi;
139 #ifdef LWS_OPENSSL_SUPPORT
140 char ssl_err_buf[512];
142 if (ssl_connection) {
143 fprintf(stderr, "libwebsockets not configured for ssl\n");
148 wsi = malloc(sizeof(struct libwebsocket));
150 fprintf(stderr, "Out of memory allocing new connection\n");
154 this->wsi[this->fds_count] = wsi;
156 /* -1 means just use latest supported */
158 if (ietf_version_or_minus_one == -1)
159 ietf_version_or_minus_one = 5;
161 wsi->ietf_spec_revision = ietf_version_or_minus_one;
162 wsi->name_buffer_pos = 0;
163 wsi->user_space = NULL;
164 wsi->state = WSI_STATE_CLIENT_UNCONNECTED;
165 wsi->pings_vs_pongs = 0;
166 wsi->protocol = NULL;
168 /* set up appropriate masking */
170 wsi->xor_mask = xor_no_mask;
172 switch (wsi->ietf_spec_revision) {
174 wsi->xor_mask = xor_mask_04;
177 wsi->xor_mask = xor_mask_05;
181 "Client ietf version %d not supported\n",
182 wsi->ietf_spec_revision);
186 /* force no mask if he asks for that though */
188 if (this->options & LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK)
189 wsi->xor_mask = xor_no_mask;
191 for (n = 0; n < WSI_TOKEN_COUNT; n++) {
192 wsi->utf8_token[n].token = NULL;
193 wsi->utf8_token[n].token_len = 0;
200 if (this->http_proxy_port) {
201 plen = sprintf(pkt, "CONNECT %s:%u HTTP/1.0\x0d\x0a"
202 "User-agent: libwebsockets\x0d\x0a"
203 /*Proxy-authorization: basic aGVsbG86d29ybGQ= */
204 "\x0d\x0a", address, port);
206 /* OK from now on we talk via the proxy */
208 address = this->http_proxy_address;
209 port = this->http_proxy_port;
213 * prepare the actual connection (to the proxy, if any)
216 server_hostent = gethostbyname(address);
217 if (server_hostent == NULL) {
218 fprintf(stderr, "Unable to get host name from %s\n", address);
222 wsi->sock = socket(AF_INET, SOCK_STREAM, 0);
225 fprintf(stderr, "Unable to open socket\n");
230 server_addr.sin_family = AF_INET;
231 server_addr.sin_port = htons(port);
232 server_addr.sin_addr = *((struct in_addr *)server_hostent->h_addr);
233 bzero(&server_addr.sin_zero, 8);
235 if (connect(wsi->sock, (struct sockaddr *)&server_addr,
236 sizeof(struct sockaddr)) == -1) {
237 fprintf(stderr, "Connect failed\n");
241 /* we are connected to server, or proxy */
243 if (this->http_proxy_port) {
245 n = send(wsi->sock, pkt, plen, 0);
248 fprintf(stderr, "ERROR writing to proxy socket\n");
256 n = poll(&pfd, 1, 5000);
259 fprintf(stderr, "libwebsocket_client_handshake "
260 "timeout on proxy response");
264 n = recv(wsi->sock, pkt, sizeof pkt, 0);
267 fprintf(stderr, "ERROR reading from proxy socket\n");
272 if (strcmp(pkt, "HTTP/1.0 200 ") != 0) {
274 fprintf(stderr, "ERROR from proxy: %s\n", pkt);
278 /* we can just start sending to proxy */
281 #ifdef LWS_OPENSSL_SUPPORT
282 if (ssl_connection) {
284 wsi->ssl = SSL_new(this->ssl_client_ctx);
285 wsi->client_bio = BIO_new_socket(wsi->sock, BIO_NOCLOSE);
286 SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
288 if (SSL_connect(wsi->ssl) <= 0) {
289 fprintf(stderr, "SSL connect error %s\n",
290 ERR_error_string(ERR_get_error(), ssl_err_buf));
294 n = SSL_get_verify_result(wsi->ssl);
295 if (n != X509_V_OK) {
296 if (n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
297 ssl_connection != 2) {
299 fprintf(stderr, "server's cert didn't "
300 "look good %d\n", n);
309 #ifdef LWS_OPENSSL_SUPPORT
314 * create the random key
317 fd = open(SYSTEM_RANDOM_FILEPATH, O_RDONLY);
319 fprintf(stderr, "Unable to open random device %s\n",
320 SYSTEM_RANDOM_FILEPATH);
323 n = read(fd, hash, 16);
325 fprintf(stderr, "Unable to read from random device %s\n",
326 SYSTEM_RANDOM_FILEPATH);
332 lws_b64_encode_string(hash, 16, key_b64, sizeof key_b64);
335 * 04 example client handshake
338 * Host: server.example.com
340 * Connection: Upgrade
341 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
342 * Sec-WebSocket-Origin: http://example.com
343 * Sec-WebSocket-Protocol: chat, superchat
344 * Sec-WebSocket-Version: 4
347 p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", path);
348 p += sprintf(p, "Host: %s\x0d\x0a", host);
349 p += sprintf(p, "Upgrade: websocket\x0d\x0a");
350 p += sprintf(p, "Connection: Upgrade\x0d\x0aSec-WebSocket-Key: ");
352 p += strlen(key_b64);
353 p += sprintf(p, "\x0d\x0aSec-WebSocket-Origin: %s\x0d\x0a", origin);
354 if (protocol != NULL)
355 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a", protocol);
356 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a\x0d\x0a",
357 wsi->ietf_spec_revision);
360 /* prepare the expected server accept response */
362 strcpy(buf, key_b64);
363 strcpy(&buf[strlen(buf)], magic_websocket_guid);
365 SHA1((unsigned char *)buf, strlen(buf), (unsigned char *)hash);
367 lws_b64_encode_string(hash, 20, wsi->initial_handshake_hash_base64,
368 sizeof wsi->initial_handshake_hash_base64);
370 /* send our request to the server */
372 #ifdef LWS_OPENSSL_SUPPORT
374 n = SSL_write(wsi->ssl, pkt, p - pkt);
377 n = send(wsi->sock, pkt, p - pkt, 0);
380 fprintf(stderr, "ERROR writing to client socket\n");
384 wsi->parser_state = WSI_TOKEN_NAME_PART;
390 n = poll(&pfd, 1, 5000);
392 fprintf(stderr, "libwebsocket_client_handshake socket error "
393 "while waiting for handshake response");
397 fprintf(stderr, "libwebsocket_client_handshake timeout "
398 "while waiting for handshake response");
402 /* interpret the server response */
405 * HTTP/1.1 101 Switching Protocols
407 * Connection: Upgrade
408 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
409 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
410 * Sec-WebSocket-Protocol: chat
413 #ifdef LWS_OPENSSL_SUPPORT
415 len = SSL_read(wsi->ssl, pkt, sizeof pkt);
418 len = recv(wsi->sock, pkt, sizeof pkt, 0);
421 fprintf(stderr, "libwebsocket_client_handshake read error\n");
426 for (n = 0; n < len; n++)
427 libwebsocket_parse(wsi, *p++);
429 if (wsi->parser_state != WSI_PARSING_COMPLETE) {
430 fprintf(stderr, "libwebsocket_client_handshake server response"
431 " failed parsing\n");
436 * well, what the server sent looked reasonable for syntax.
437 * Now let's confirm it sent all the necessary headers
440 if (!wsi->utf8_token[WSI_TOKEN_HTTP].token_len ||
441 !wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len ||
442 !wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len ||
443 !wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len ||
444 !wsi->utf8_token[WSI_TOKEN_NONCE].token_len ||
445 (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len &&
447 fprintf(stderr, "libwebsocket_client_handshake "
448 "missing required header(s)\n");
450 fprintf(stderr, "%s", pkt);
455 * Everything seems to be there, now take a closer look at what is in
459 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
460 if (strcmp(wsi->utf8_token[WSI_TOKEN_HTTP].token,
461 "101 switching protocols")) {
462 fprintf(stderr, "libwebsocket_client_handshake server sent bad"
463 " HTTP response '%s'\n",
464 wsi->utf8_token[WSI_TOKEN_HTTP].token);
468 strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
469 if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token, "websocket")) {
470 fprintf(stderr, "libwebsocket_client_handshake server sent bad"
471 " Upgrade header '%s'\n",
472 wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
476 strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
477 if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token, "upgrade")) {
478 fprintf(stderr, "libwebsocket_client_handshake server sent bad"
479 " Connection hdr '%s'\n",
480 wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
484 * confirm the protocol the server wants to talk was in the list of
485 * protocols we offered
488 if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
490 /* no protocol name to work from, default to first protocol */
491 wsi->protocol = &this->protocols[0];
497 while (*pc && !okay) {
498 if ((!strncmp(pc, wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
499 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len)) &&
500 (pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == ',' ||
501 pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == '\0')) {
505 while (*pc && *pc != ',')
507 while (*pc && *pc != ' ')
511 fprintf(stderr, "libwebsocket_client_handshake server "
512 "sent bad protocol '%s'\n",
513 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
518 * identify the selected protocol struct and set it
521 wsi->protocol = NULL;
522 while (this->protocols[n].callback) {
523 if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
524 this->protocols[n].name) == 0)
525 wsi->protocol = &this->protocols[n];
529 if (wsi->protocol == NULL) {
530 fprintf(stderr, "libwebsocket_client_handshake server "
531 "requested protocol '%s', which we "
532 "said we supported but we don't!\n",
533 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
539 * Confirm his accept token is the same as the one we precomputed
542 if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
543 wsi->initial_handshake_hash_base64)) {
544 fprintf(stderr, "libwebsocket_client_handshake server sent "
545 "bad ACCEPT '%s' vs computed '%s'\n",
546 wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
547 wsi->initial_handshake_hash_base64);
552 * Calculate the masking key to use when sending data to server
555 strcpy(buf, key_b64);
556 p = buf + strlen(key_b64);
557 strcpy(p, wsi->utf8_token[WSI_TOKEN_NONCE].token);
558 p += wsi->utf8_token[WSI_TOKEN_NONCE].token_len;
559 strcpy(p, magic_websocket_04_masking_guid);
560 SHA1((unsigned char *)buf, strlen(buf), wsi->masking_key_04);
562 /* allocate the per-connection user memory (if any) */
564 if (wsi->protocol->per_session_data_size) {
565 wsi->user_space = malloc(
566 wsi->protocol->per_session_data_size);
567 if (wsi->user_space == NULL) {
568 fprintf(stderr, "Out of memory for "
569 "conn user space\n");
573 wsi->user_space = NULL;
575 /* okay he is good to go */
577 this->fds[this->fds_count].fd = wsi->sock;
578 this->fds[this->fds_count].revents = 0;
579 this->fds[this->fds_count++].events = POLLIN;
581 wsi->state = WSI_STATE_ESTABLISHED;
582 wsi->mode = LWS_CONNMODE_WS_CLIENT;
584 fprintf(stderr, "handshake OK for protocol %s\n", wsi->protocol->name);
586 /* call him back to inform him he is up */
588 wsi->protocol->callback(wsi,
589 LWS_CALLBACK_CLIENT_ESTABLISHED,
596 libwebsocket_client_close(wsi);