2 * libwebsockets - small server side websockets and web server implementation
4 * Copyright (C) 2010-2013 Andy Green <andy@warmcat.com>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation:
9 * version 2.1 of the License.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22 #include "private-libwebsockets.h"
28 #ifdef LWS_BUILTIN_GETIFADDRS
29 #include <getifaddrs.h>
34 #include <sys/socket.h>
38 #ifdef LWS_OPENSSL_SUPPORT
39 extern int openssl_websocket_private_data_index;
42 int lws_client_socket_service(struct libwebsocket_context *context, struct libwebsocket *wsi, struct pollfd *pollfd)
49 #ifdef LWS_OPENSSL_SUPPORT
50 char ssl_err_buf[512];
55 case LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY:
57 /* handle proxy hung up on us */
59 if (pollfd->revents & (POLLERR | POLLHUP)) {
61 lwsl_warn("Proxy connection %p (fd=%d) dead\n",
62 (void *)wsi, pollfd->fd);
64 libwebsocket_close_and_free_session(context, wsi,
65 LWS_CLOSE_STATUS_NOSTATUS);
69 n = recv(wsi->sock, pkt, sizeof pkt, 0);
71 libwebsocket_close_and_free_session(context, wsi,
72 LWS_CLOSE_STATUS_NOSTATUS);
73 lwsl_err("ERROR reading from proxy socket\n");
78 if (strcmp(pkt, "HTTP/1.0 200 ") != 0) {
79 libwebsocket_close_and_free_session(context, wsi,
80 LWS_CLOSE_STATUS_NOSTATUS);
81 lwsl_err("ERROR from proxy: %s\n", pkt);
85 /* clear his proxy connection timeout */
87 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
91 case LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE:
94 * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE
95 * timeout protection set in client-handshake.c
98 #ifdef LWS_OPENSSL_SUPPORT
101 * take care of our libwebsocket_callback_on_writable
102 * happening at a time when there's no real connection yet
105 pollfd->events &= ~POLLOUT;
107 /* external POLL support via protocol 0 */
108 context->protocols[0].callback(context, wsi,
109 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
110 (void *)(long)wsi->sock, NULL, POLLOUT);
112 /* we can retry this... so just cook the SSL BIO the first time */
114 if (wsi->use_ssl && !wsi->ssl) {
116 wsi->ssl = SSL_new(context->ssl_client_ctx);
119 /* CyaSSL does certificate verification differently from OpenSSL.
120 * If we should ignore the certificate, we need to set this before
121 * SSL_new and SSL_connect is called. Otherwise the connect will
122 * simply fail with error code -155 */
123 if (wsi->use_ssl == 2) {
124 CyaSSL_set_verify(wsi->ssl, SSL_VERIFY_NONE, NULL);
128 wsi->client_bio = BIO_new_socket(wsi->sock, BIO_NOCLOSE);
130 SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
133 CyaSSL_set_using_nonblock(wsi->ssl, 1);
135 BIO_set_nbio(wsi->client_bio, 1); /* nonblocking */
138 SSL_set_ex_data(wsi->ssl,
139 openssl_websocket_private_data_index,
144 lws_latency_pre(context, wsi);
145 n = SSL_connect(wsi->ssl);
146 lws_latency(context, wsi, "SSL_connect LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE", n, n > 0);
149 n = SSL_get_error(wsi->ssl, n);
151 if (n == SSL_ERROR_WANT_READ ||
152 n == SSL_ERROR_WANT_WRITE) {
154 * wants us to retry connect due to state of the
155 * underlying ssl layer... but since it may be
156 * stalled on blocked write, no incoming data may
157 * arrive to trigger the retry. Force (possibly
158 * many if the SSL state persists in returning the
159 * condition code, but other sockets are getting
160 * serviced inbetweentimes) us to get called back
164 lwsl_info("SSL_connect -> SSL_ERROR_WANT_... retrying\n");
165 libwebsocket_callback_on_writable(context, wsi);
167 return 0; /* no error */
174 * retry if new data comes until we
175 * run into the connection timeout or win
178 lwsl_err("SSL connect error %s\n",
179 ERR_error_string(ERR_get_error(),
185 /* See note above about CyaSSL certificate verification */
186 lws_latency_pre(context, wsi);
187 n = SSL_get_verify_result(wsi->ssl);
188 lws_latency(context, wsi, "SSL_get_verify_result LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE", n, n > 0);
189 if ((n != X509_V_OK) && (
190 n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
191 wsi->use_ssl != 2)) {
193 lwsl_err("server's cert didn't "
194 "look good %d\n", n);
195 libwebsocket_close_and_free_session(context,
196 wsi, LWS_CLOSE_STATUS_NOSTATUS);
204 p = libwebsockets_generate_client_handshake(context, wsi, p);
206 lwsl_err("Failed to generate handshake for client, closing it\n");
207 libwebsocket_close_and_free_session(context, wsi,
208 LWS_CLOSE_STATUS_NOSTATUS);
212 /* send our request to the server */
214 lws_latency_pre(context, wsi);
215 #ifdef LWS_OPENSSL_SUPPORT
217 n = SSL_write(wsi->ssl, pkt, p - pkt);
220 n = send(wsi->sock, pkt, p - pkt, 0);
221 lws_latency(context, wsi, "send or SSL_write LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE", n, n >= 0);
224 lwsl_debug("ERROR writing to client socket\n");
225 libwebsocket_close_and_free_session(context, wsi,
226 LWS_CLOSE_STATUS_NOSTATUS);
230 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
231 wsi->u.hdr.lextable_pos = 0;
232 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY;
233 libwebsocket_set_timeout(wsi,
234 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, AWAITING_TIMEOUT);
238 case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
240 /* handle server hung up on us */
242 if (pollfd->revents & (POLLERR | POLLHUP)) {
244 lwsl_debug("Server connection %p (fd=%d) dead\n",
245 (void *)wsi, pollfd->fd);
250 if (!(pollfd->revents & POLLIN))
253 /* interpret the server response */
256 * HTTP/1.1 101 Switching Protocols
258 * Connection: Upgrade
259 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
260 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
261 * Sec-WebSocket-Protocol: chat
265 * we have to take some care here to only take from the
266 * socket bytewise. The browser may (and has been seen to
267 * in the case that onopen() performs websocket traffic)
268 * coalesce both handshake response and websocket traffic
269 * in one packet, since at that point the connection is
270 * definitively ready from browser pov.
274 while (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE && len > 0) {
275 #ifdef LWS_OPENSSL_SUPPORT
277 len = SSL_read(wsi->ssl, &c, 1);
279 n = SSL_get_error(wsi->ssl, len);
280 if (n == SSL_ERROR_WANT_READ ||
281 n == SSL_ERROR_WANT_WRITE)
286 len = recv(wsi->sock, &c, 1, 0);
291 libwebsocket_parse(wsi, c);
295 * hs may also be coming in multiple packets, there is a 5-sec
296 * libwebsocket timeout still active here too, so if parsing did
297 * not complete just wait for next packet coming in this state
300 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
304 * otherwise deal with the handshake. If there's any
305 * packet traffic already arrived we'll trigger poll() again
306 * right away and deal with it that way
309 return lws_client_interpret_server_handshake(context, wsi);
313 free(wsi->c_protocol);
314 lwsl_info("closing connection at LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY\n");
315 libwebsocket_close_and_free_session(context, wsi,
316 LWS_CLOSE_STATUS_NOSTATUS);
319 case LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT:
320 lwsl_ext("LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT\n");
323 case LWS_CONNMODE_WS_CLIENT_PENDING_CANDIDATE_CHILD:
324 lwsl_ext("LWS_CONNMODE_WS_CLIENT_PENDING_CANDIDATE_CHILD\n");
335 * In-place str to lower case
348 lws_client_interpret_server_handshake(struct libwebsocket_context *context,
349 struct libwebsocket *wsi)
353 #ifndef LWS_NO_EXTENSIONS
355 struct libwebsocket_extension *ext;
363 * well, what the server sent looked reasonable for syntax.
364 * Now let's confirm it sent all the necessary headers
367 lwsl_parser("WSI_TOKEN_HTTP: %d\n",
368 wsi->utf8_token[WSI_TOKEN_HTTP].token_len);
369 lwsl_parser("WSI_TOKEN_UPGRADE: %d\n",
370 wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len);
371 lwsl_parser("WSI_TOKEN_CONNECTION: %d\n",
372 wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len);
373 lwsl_parser("WSI_TOKEN_ACCEPT: %d\n",
374 wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len);
375 lwsl_parser("WSI_TOKEN_NONCE: %d\n",
376 wsi->utf8_token[WSI_TOKEN_NONCE].token_len);
377 lwsl_parser("WSI_TOKEN_PROTOCOL: %d\n",
378 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len);
381 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
382 if (strncmp(wsi->utf8_token[WSI_TOKEN_HTTP].token, "101", 3)) {
383 lwsl_warn("libwebsocket_client_handshake "
384 "server sent bad HTTP response '%s'\n",
385 wsi->utf8_token[WSI_TOKEN_HTTP].token);
389 strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
390 if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token,
392 lwsl_warn("libwebsocket_client_handshake server "
393 "sent bad Upgrade header '%s'\n",
394 wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
398 strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
399 if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token,
401 lwsl_warn("libwebsocket_client_handshake server "
402 "sent bad Connection hdr '%s'\n",
403 wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
407 pc = wsi->c_protocol;
409 lwsl_parser("lws_client_interpret_server_handshake: "
410 "NULL c_protocol\n");
412 lwsl_parser("lws_client_interpret_server_handshake: "
413 "cPprotocol='%s'\n", pc);
416 * confirm the protocol the server wants to talk was in the list
417 * of protocols we offered
420 if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
422 lwsl_info("lws_client_interpret_server_handshake "
423 "WSI_TOKEN_PROTOCOL is null\n");
425 * no protocol name to work from,
426 * default to first protocol
428 wsi->protocol = &context->protocols[0];
429 wsi->c_callback = wsi->protocol->callback;
430 free(wsi->c_protocol);
432 goto check_extensions;
435 while (*pc && !okay) {
436 if ((!strncmp(pc, wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
437 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len)) &&
438 (pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == ',' ||
439 pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == '\0')) {
443 while (*pc && *pc != ',')
445 while (*pc && *pc != ' ')
449 /* done with him now */
452 free(wsi->c_protocol);
455 lwsl_err("libwebsocket_client_handshake server "
456 "sent bad protocol '%s'\n",
457 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
462 * identify the selected protocol struct and set it
465 wsi->protocol = NULL;
466 while (context->protocols[n].callback && !wsi->protocol) { /* Stop after finding first one?? */
467 if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
468 context->protocols[n].name) == 0) {
469 wsi->protocol = &context->protocols[n];
470 wsi->c_callback = wsi->protocol->callback;
475 if (wsi->protocol == NULL) {
476 lwsl_err("libwebsocket_client_handshake server "
477 "requested protocol '%s', which we "
478 "said we supported but we don't!\n",
479 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
485 #ifndef LWS_NO_EXTENSIONS
486 /* instantiate the accepted extensions */
488 if (!wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token_len) {
489 lwsl_ext("no client extenstions allowed by server\n");
494 * break down the list of server accepted extensions
495 * and go through matching them or identifying bogons
498 c = wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token;
502 if (*c && (*c != ',' && *c != ' ' && *c != '\t')) {
504 if (n < sizeof(ext_name) - 1)
517 /* check we actually support it */
519 lwsl_ext("checking client ext %s\n", ext_name);
522 ext = wsi->protocol->owning_server->extensions;
523 while (ext && ext->callback) {
525 if (strcmp(ext_name, ext->name)) {
532 lwsl_ext("instantiating client ext %s\n", ext_name);
534 /* instantiate the extension on this conn */
536 wsi->active_extensions_user[
537 wsi->count_active_extensions] =
538 malloc(ext->per_session_data_size);
539 if (wsi->active_extensions_user[
540 wsi->count_active_extensions] == NULL) {
541 lwsl_err("Out of mem\n");
544 memset(wsi->active_extensions_user[
545 wsi->count_active_extensions], 0,
546 ext->per_session_data_size);
547 wsi->active_extensions[
548 wsi->count_active_extensions] = ext;
550 /* allow him to construct his context */
552 ext->callback(wsi->protocol->owning_server,
554 LWS_EXT_CALLBACK_CLIENT_CONSTRUCT,
555 wsi->active_extensions_user[
556 wsi->count_active_extensions],
559 wsi->count_active_extensions++;
565 lwsl_warn("Server said we should use"
566 "an unknown extension '%s'!\n", ext_name);
577 * Confirm his accept token is the one we precomputed
580 if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
581 wsi->u.hdr.initial_handshake_hash_base64)) {
582 lwsl_warn("libwebsocket_client_handshake server "
583 "sent bad ACCEPT '%s' vs computed '%s'\n",
584 wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
585 wsi->u.hdr.initial_handshake_hash_base64);
589 /* allocate the per-connection user memory (if any) */
590 if (wsi->protocol->per_session_data_size &&
591 !libwebsocket_ensure_user_space(wsi))
594 /* clear his proxy connection timeout */
596 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
598 /* mark him as being alive */
600 wsi->state = WSI_STATE_ESTABLISHED;
601 wsi->mode = LWS_CONNMODE_WS_CLIENT;
603 /* union transition */
604 memset(&wsi->u, 0, sizeof wsi->u);
606 lwsl_debug("handshake OK for protocol %s\n", wsi->protocol->name);
608 /* call him back to inform him he is up */
610 wsi->protocol->callback(context, wsi,
611 LWS_CALLBACK_CLIENT_ESTABLISHED,
612 wsi->user_space, NULL, 0);
613 #ifndef LWS_NO_EXTENSIONS
615 * inform all extensions, not just active ones since they
619 ext = context->extensions;
621 while (ext && ext->callback) {
623 for (n = 0; n < wsi->count_active_extensions; n++)
624 if (wsi->active_extensions[n] == ext)
625 v = wsi->active_extensions_user[n];
627 ext->callback(context, ext, wsi,
628 LWS_EXT_CALLBACK_ANY_WSI_ESTABLISHED, v, NULL, 0);
637 free(wsi->c_protocol);
640 if (wsi->c_callback) wsi->c_callback(context, wsi,
641 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
644 lwsl_info("closing connection due to bail2 connection error\n");
645 libwebsocket_close_and_free_session(context, wsi,
646 LWS_CLOSE_STATUS_PROTOCOL_ERR);
653 libwebsockets_generate_client_handshake(struct libwebsocket_context *context,
654 struct libwebsocket *wsi, char *pkt)
660 #ifndef LWS_NO_EXTENSIONS
661 struct libwebsocket_extension *ext;
662 struct libwebsocket_extension *ext1;
665 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 +
666 MAX_USER_RX_BUFFER + LWS_SEND_BUFFER_POST_PADDING];
667 static const char magic_websocket_guid[] =
668 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
671 * create the random key
674 n = libwebsockets_get_random(context, hash, 16);
676 lwsl_err("Unable to read from random dev %s\n",
677 SYSTEM_RANDOM_FILEPATH);
683 free(wsi->c_protocol);
684 libwebsocket_close_and_free_session(context, wsi,
685 LWS_CLOSE_STATUS_NOSTATUS);
689 lws_b64_encode_string(hash, 16, key_b64, sizeof key_b64);
692 * 00 example client handshake
694 * GET /socket.io/websocket HTTP/1.1
696 * Connection: Upgrade
697 * Host: 127.0.0.1:9999
698 * Origin: http://127.0.0.1
699 * Sec-WebSocket-Key1: 1 0 2#0W 9 89 7 92 ^
700 * Sec-WebSocket-Key2: 7 7Y 4328 B2v[8(z1
701 * Cookie: socketio=websocket
705 * 04 example client handshake
708 * Host: server.example.com
710 * Connection: Upgrade
711 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
712 * Sec-WebSocket-Origin: http://example.com
713 * Sec-WebSocket-Protocol: chat, superchat
714 * Sec-WebSocket-Version: 4
717 p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", wsi->c_path);
719 p += sprintf(p, "Pragma: no-cache\x0d\x0a"
720 "Cache-Control: no-cache\x0d\x0a");
722 p += sprintf(p, "Host: %s\x0d\x0a", wsi->c_host);
723 p += sprintf(p, "Upgrade: websocket\x0d\x0a"
724 "Connection: Upgrade\x0d\x0a"
725 "Sec-WebSocket-Key: ");
727 p += strlen(key_b64);
728 p += sprintf(p, "\x0d\x0a");
730 if (wsi->ietf_spec_revision == 13)
731 p += sprintf(p, "Origin: %s\x0d\x0a", wsi->c_origin);
733 p += sprintf(p, "Sec-WebSocket-Origin: %s\x0d\x0a",
737 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
740 /* tell the server what extensions we could support */
742 p += sprintf(p, "Sec-WebSocket-Extensions: ");
743 #ifndef LWS_NO_EXTENSIONS
744 ext = context->extensions;
745 while (ext && ext->callback) {
748 ext1 = context->extensions;
750 while (ext1 && ext1->callback) {
751 n |= ext1->callback(context, ext1, wsi,
752 LWS_EXT_CALLBACK_CHECK_OK_TO_PROPOSE_EXTENSION,
753 NULL, (char *)ext->name, 0);
758 if (n) { /* an extension vetos us */
759 lwsl_ext("ext %s vetoed\n", (char *)ext->name);
764 n = context->protocols[0].callback(context, wsi,
765 LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
766 wsi->user_space, (char *)ext->name, 0);
769 * zero return from callback means
770 * go ahead and allow the extension,
771 * it's what we get if the callback is
784 p += sprintf(p, "%s", ext->name);
790 p += sprintf(p, "\x0d\x0a");
792 if (wsi->ietf_spec_revision)
793 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
794 wsi->ietf_spec_revision);
796 /* give userland a chance to append, eg, cookies */
798 context->protocols[0].callback(context, wsi,
799 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
800 NULL, &p, (pkt + sizeof(pkt)) - p - 12);
802 p += sprintf(p, "\x0d\x0a");
804 /* prepare the expected server accept response */
806 strcpy((char *)buf, key_b64);
807 strcpy((char *)&buf[strlen((char *)buf)], magic_websocket_guid);
809 SHA1(buf, strlen((char *)buf), (unsigned char *)hash);
811 lws_b64_encode_string(hash, 20,
812 wsi->u.hdr.initial_handshake_hash_base64,
813 sizeof wsi->u.hdr.initial_handshake_hash_base64);
815 /* done with these now */