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)
45 char *p = (char *)&context->service_buffer[0];
51 case LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY:
53 /* handle proxy hung up on us */
55 if (pollfd->revents & (POLLERR | POLLHUP)) {
57 lwsl_warn("Proxy connection %p (fd=%d) dead\n",
58 (void *)wsi, pollfd->fd);
60 libwebsocket_close_and_free_session(context, wsi,
61 LWS_CLOSE_STATUS_NOSTATUS);
65 n = recv(wsi->sock, context->service_buffer,
66 sizeof context->service_buffer, 0);
68 libwebsocket_close_and_free_session(context, wsi,
69 LWS_CLOSE_STATUS_NOSTATUS);
70 lwsl_err("ERROR reading from proxy socket\n");
74 context->service_buffer[13] = '\0';
75 if (strcmp((char *)context->service_buffer, "HTTP/1.0 200 ")) {
76 libwebsocket_close_and_free_session(context, wsi,
77 LWS_CLOSE_STATUS_NOSTATUS);
78 lwsl_err("ERROR from proxy: %s\n", context->service_buffer);
82 /* clear his proxy connection timeout */
84 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
88 case LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE:
91 * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE
92 * timeout protection set in client-handshake.c
95 #ifdef LWS_OPENSSL_SUPPORT
98 * take care of our libwebsocket_callback_on_writable
99 * happening at a time when there's no real connection yet
102 pollfd->events &= ~POLLOUT;
104 /* external POLL support via protocol 0 */
105 context->protocols[0].callback(context, wsi,
106 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
107 (void *)(long)wsi->sock, NULL, POLLOUT);
109 /* we can retry this... so just cook the SSL BIO the first time */
111 if (wsi->use_ssl && !wsi->ssl) {
113 wsi->ssl = SSL_new(context->ssl_client_ctx);
116 /* CyaSSL does certificate verification differently from OpenSSL.
117 * If we should ignore the certificate, we need to set this before
118 * SSL_new and SSL_connect is called. Otherwise the connect will
119 * simply fail with error code -155 */
120 if (wsi->use_ssl == 2) {
121 CyaSSL_set_verify(wsi->ssl, SSL_VERIFY_NONE, NULL);
125 wsi->client_bio = BIO_new_socket(wsi->sock, BIO_NOCLOSE);
127 SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
130 CyaSSL_set_using_nonblock(wsi->ssl, 1);
132 BIO_set_nbio(wsi->client_bio, 1); /* nonblocking */
135 SSL_set_ex_data(wsi->ssl,
136 openssl_websocket_private_data_index,
141 lws_latency_pre(context, wsi);
142 n = SSL_connect(wsi->ssl);
143 lws_latency(context, wsi, "SSL_connect LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE", n, n > 0);
146 n = SSL_get_error(wsi->ssl, n);
148 if (n == SSL_ERROR_WANT_READ ||
149 n == SSL_ERROR_WANT_WRITE) {
151 * wants us to retry connect due to state of the
152 * underlying ssl layer... but since it may be
153 * stalled on blocked write, no incoming data may
154 * arrive to trigger the retry. Force (possibly
155 * many if the SSL state persists in returning the
156 * condition code, but other sockets are getting
157 * serviced inbetweentimes) us to get called back
161 lwsl_info("SSL_connect -> SSL_ERROR_WANT_... retrying\n");
162 libwebsocket_callback_on_writable(context, wsi);
164 return 0; /* no error */
171 * retry if new data comes until we
172 * run into the connection timeout or win
175 lwsl_err("SSL connect error %s\n",
176 ERR_error_string(ERR_get_error(),
177 (char *)context->service_buffer));
182 /* See note above about CyaSSL certificate verification */
183 lws_latency_pre(context, wsi);
184 n = SSL_get_verify_result(wsi->ssl);
185 lws_latency(context, wsi, "SSL_get_verify_result LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE", n, n > 0);
186 if ((n != X509_V_OK) && (
187 n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
188 wsi->use_ssl != 2)) {
190 lwsl_err("server's cert didn't "
191 "look good %d\n", n);
192 libwebsocket_close_and_free_session(context,
193 wsi, LWS_CLOSE_STATUS_NOSTATUS);
201 p = libwebsockets_generate_client_handshake(context, wsi, p);
203 lwsl_err("Failed to generate handshake for client, closing it\n");
204 libwebsocket_close_and_free_session(context, wsi,
205 LWS_CLOSE_STATUS_NOSTATUS);
209 /* send our request to the server */
211 lws_latency_pre(context, wsi);
212 #ifdef LWS_OPENSSL_SUPPORT
214 n = SSL_write(wsi->ssl, context->service_buffer, p - (char *)context->service_buffer);
217 n = send(wsi->sock, context->service_buffer, p - (char *)context->service_buffer, 0);
218 lws_latency(context, wsi, "send or SSL_write LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE", n, n >= 0);
221 lwsl_debug("ERROR writing to client socket\n");
222 libwebsocket_close_and_free_session(context, wsi,
223 LWS_CLOSE_STATUS_NOSTATUS);
227 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
228 wsi->u.hdr.lextable_pos = 0;
229 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY;
230 libwebsocket_set_timeout(wsi,
231 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, AWAITING_TIMEOUT);
235 case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
237 /* handle server hung up on us */
239 if (pollfd->revents & (POLLERR | POLLHUP)) {
241 lwsl_debug("Server connection %p (fd=%d) dead\n",
242 (void *)wsi, pollfd->fd);
247 if (!(pollfd->revents & POLLIN))
250 /* interpret the server response */
253 * HTTP/1.1 101 Switching Protocols
255 * Connection: Upgrade
256 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
257 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
258 * Sec-WebSocket-Protocol: chat
262 * we have to take some care here to only take from the
263 * socket bytewise. The browser may (and has been seen to
264 * in the case that onopen() performs websocket traffic)
265 * coalesce both handshake response and websocket traffic
266 * in one packet, since at that point the connection is
267 * definitively ready from browser pov.
271 while (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE && len > 0) {
272 #ifdef LWS_OPENSSL_SUPPORT
274 len = SSL_read(wsi->ssl, &c, 1);
276 n = SSL_get_error(wsi->ssl, len);
277 if (n == SSL_ERROR_WANT_READ ||
278 n == SSL_ERROR_WANT_WRITE)
283 len = recv(wsi->sock, &c, 1, 0);
288 if (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)
355 #ifndef LWS_NO_EXTENSIONS
357 struct libwebsocket_extension *ext;
365 * well, what the server sent looked reasonable for syntax.
366 * Now let's confirm it sent all the necessary headers
369 if (lws_hdr_total_length(wsi, WSI_TOKEN_ACCEPT) == 0)
372 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP);
375 if (p && strncmp(p, "101", 3)) {
376 lwsl_warn("libwebsocket_client_handshake "
377 "server sent bad HTTP response '%s'\n", p);
381 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE);
385 if (strcmp(p, "websocket")) {
386 lwsl_warn("libwebsocket_client_handshake server "
387 "sent bad Upgrade header '%s'\n", p);
391 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_CONNECTION);
395 if (strcmp(p, "upgrade")) {
396 lwsl_warn("libwebsocket_client_handshake server "
397 "sent bad Connection hdr '%s'\n", p);
401 pc = wsi->c_protocol;
403 lwsl_parser("lws_client_interpret_server_handshake: "
404 "NULL c_protocol\n");
406 lwsl_parser("lws_client_interpret_server_handshake: "
407 "cPprotocol='%s'\n", pc);
410 * confirm the protocol the server wants to talk was in the list
411 * of protocols we offered
414 len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
417 lwsl_info("lws_client_interpret_server_handshake "
418 "WSI_TOKEN_PROTOCOL is null\n");
420 * no protocol name to work from,
421 * default to first protocol
423 wsi->protocol = &context->protocols[0];
424 wsi->c_callback = wsi->protocol->callback;
425 free(wsi->c_protocol);
427 goto check_extensions;
430 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL);
433 while (*pc && !okay) {
434 if (!strncmp(pc, p, len) && (pc[len] == ',' || pc[len] == '\0')) {
438 while (*pc && *pc != ',')
440 while (*pc && *pc != ' ')
444 /* done with him now */
447 free(wsi->c_protocol);
450 lwsl_err("libwebsocket_client_handshake server "
451 "sent bad protocol '%s'\n", p);
456 * identify the selected protocol struct and set it
459 wsi->protocol = NULL;
460 while (context->protocols[n].callback && !wsi->protocol) {
461 if (strcmp(p, context->protocols[n].name) == 0) {
462 wsi->protocol = &context->protocols[n];
463 wsi->c_callback = wsi->protocol->callback;
469 if (wsi->protocol == NULL) {
470 lwsl_err("libwebsocket_client_handshake server "
471 "requested protocol '%s', which we "
472 "said we supported but we don't!\n", p);
478 #ifndef LWS_NO_EXTENSIONS
479 /* instantiate the accepted extensions */
481 if (!lws_hdr_total_length(wsi, WSI_TOKEN_EXTENSIONS)) {
482 lwsl_ext("no client extenstions allowed by server\n");
487 * break down the list of server accepted extensions
488 * and go through matching them or identifying bogons
491 if (lws_hdr_copy(wsi, (char *)context->service_buffer, sizeof(context->service_buffer), WSI_TOKEN_EXTENSIONS) < 0)
494 c = (char *)context->service_buffer;
498 if (*c && (*c != ',' && *c != ' ' && *c != '\t')) {
500 if (n < sizeof(ext_name) - 1)
513 /* check we actually support it */
515 lwsl_ext("checking client ext %s\n", ext_name);
518 ext = wsi->protocol->owning_server->extensions;
519 while (ext && ext->callback) {
521 if (strcmp(ext_name, ext->name)) {
528 lwsl_ext("instantiating client ext %s\n", ext_name);
530 /* instantiate the extension on this conn */
532 wsi->active_extensions_user[
533 wsi->count_active_extensions] =
534 malloc(ext->per_session_data_size);
535 if (wsi->active_extensions_user[
536 wsi->count_active_extensions] == NULL) {
537 lwsl_err("Out of mem\n");
540 memset(wsi->active_extensions_user[
541 wsi->count_active_extensions], 0,
542 ext->per_session_data_size);
543 wsi->active_extensions[
544 wsi->count_active_extensions] = ext;
546 /* allow him to construct his context */
548 ext->callback(wsi->protocol->owning_server,
550 LWS_EXT_CALLBACK_CLIENT_CONSTRUCT,
551 wsi->active_extensions_user[
552 wsi->count_active_extensions],
555 wsi->count_active_extensions++;
561 lwsl_warn("Server said we should use"
562 "an unknown extension '%s'!\n", ext_name);
573 * Confirm his accept token is the one we precomputed
576 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_ACCEPT);
577 if (strcmp(p, wsi->u.hdr.initial_handshake_hash_base64)) {
578 lwsl_warn("libwebsocket_client_handshake server "
579 "sent bad ACCEPT '%s' vs computed '%s'\n", p,
580 wsi->u.hdr.initial_handshake_hash_base64);
584 /* allocate the per-connection user memory (if any) */
585 if (wsi->protocol->per_session_data_size &&
586 !libwebsocket_ensure_user_space(wsi))
590 * we seem to be good to go, give client last chance to check
594 wsi->protocol->callback(context, wsi,
595 LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH,
596 wsi->user_space, NULL, 0);
598 /* clear his proxy connection timeout */
600 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
602 /* free up his parsing allocations */
606 /* mark him as being alive */
608 wsi->state = WSI_STATE_ESTABLISHED;
609 wsi->mode = LWS_CONNMODE_WS_CLIENT;
611 /* union transition */
613 memset(&wsi->u, 0, sizeof wsi->u);
616 * create the frame buffer for this connection according to the
617 * size mentioned in the protocol definition. If 0 there, then
618 * use a big default for compatibility
621 n = wsi->protocol->rx_buffer_size;
623 n = LWS_MAX_SOCKET_IO_BUF;
624 n += LWS_SEND_BUFFER_PRE_PADDING + LWS_SEND_BUFFER_POST_PADDING;
625 wsi->u.ws.rx_user_buffer = malloc(n);
626 if (!wsi->u.ws.rx_user_buffer) {
627 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
630 lwsl_info("Allocating client RX buffer %d\n", n);
632 lwsl_debug("handshake OK for protocol %s\n", wsi->protocol->name);
634 /* call him back to inform him he is up */
636 wsi->protocol->callback(context, wsi,
637 LWS_CALLBACK_CLIENT_ESTABLISHED,
638 wsi->user_space, NULL, 0);
639 #ifndef LWS_NO_EXTENSIONS
641 * inform all extensions, not just active ones since they
645 ext = context->extensions;
647 while (ext && ext->callback) {
649 for (n = 0; n < wsi->count_active_extensions; n++)
650 if (wsi->active_extensions[n] == ext)
651 v = wsi->active_extensions_user[n];
653 ext->callback(context, ext, wsi,
654 LWS_EXT_CALLBACK_ANY_WSI_ESTABLISHED, v, NULL, 0);
663 free(wsi->c_protocol);
667 wsi->c_callback(context, wsi,
668 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
669 wsi->user_space, NULL, 0);
671 lwsl_info("closing connection due to bail2 connection error\n");
673 /* free up his parsing allocations */
678 libwebsocket_close_and_free_session(context, wsi,
679 LWS_CLOSE_STATUS_PROTOCOL_ERR);
686 libwebsockets_generate_client_handshake(struct libwebsocket_context *context,
687 struct libwebsocket *wsi, char *pkt)
694 #ifndef LWS_NO_EXTENSIONS
695 struct libwebsocket_extension *ext;
696 struct libwebsocket_extension *ext1;
699 static const char magic_websocket_guid[] =
700 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
703 * create the random key
706 n = libwebsockets_get_random(context, hash, 16);
708 lwsl_err("Unable to read from random dev %s\n",
709 SYSTEM_RANDOM_FILEPATH);
715 free(wsi->c_protocol);
716 libwebsocket_close_and_free_session(context, wsi,
717 LWS_CLOSE_STATUS_NOSTATUS);
721 lws_b64_encode_string(hash, 16, key_b64, sizeof key_b64);
724 * 00 example client handshake
726 * GET /socket.io/websocket HTTP/1.1
728 * Connection: Upgrade
729 * Host: 127.0.0.1:9999
730 * Origin: http://127.0.0.1
731 * Sec-WebSocket-Key1: 1 0 2#0W 9 89 7 92 ^
732 * Sec-WebSocket-Key2: 7 7Y 4328 B2v[8(z1
733 * Cookie: socketio=websocket
737 * 04 example client handshake
740 * Host: server.example.com
742 * Connection: Upgrade
743 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
744 * Sec-WebSocket-Origin: http://example.com
745 * Sec-WebSocket-Protocol: chat, superchat
746 * Sec-WebSocket-Version: 4
749 p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", wsi->c_path);
751 p += sprintf(p, "Pragma: no-cache\x0d\x0a"
752 "Cache-Control: no-cache\x0d\x0a");
754 p += sprintf(p, "Host: %s\x0d\x0a", wsi->c_host);
755 p += sprintf(p, "Upgrade: websocket\x0d\x0a"
756 "Connection: Upgrade\x0d\x0a"
757 "Sec-WebSocket-Key: ");
759 p += strlen(key_b64);
760 p += sprintf(p, "\x0d\x0a");
762 if (wsi->ietf_spec_revision == 13)
763 p += sprintf(p, "Origin: %s\x0d\x0a", wsi->c_origin);
765 p += sprintf(p, "Sec-WebSocket-Origin: %s\x0d\x0a",
769 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
772 /* tell the server what extensions we could support */
774 p += sprintf(p, "Sec-WebSocket-Extensions: ");
775 #ifndef LWS_NO_EXTENSIONS
776 ext = context->extensions;
777 while (ext && ext->callback) {
780 ext1 = context->extensions;
782 while (ext1 && ext1->callback) {
783 n |= ext1->callback(context, ext1, wsi,
784 LWS_EXT_CALLBACK_CHECK_OK_TO_PROPOSE_EXTENSION,
785 NULL, (char *)ext->name, 0);
790 if (n) { /* an extension vetos us */
791 lwsl_ext("ext %s vetoed\n", (char *)ext->name);
796 n = context->protocols[0].callback(context, wsi,
797 LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
798 wsi->user_space, (char *)ext->name, 0);
801 * zero return from callback means
802 * go ahead and allow the extension,
803 * it's what we get if the callback is
816 p += sprintf(p, "%s", ext->name);
822 p += sprintf(p, "\x0d\x0a");
824 if (wsi->ietf_spec_revision)
825 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
826 wsi->ietf_spec_revision);
828 /* give userland a chance to append, eg, cookies */
830 context->protocols[0].callback(context, wsi,
831 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
832 NULL, &p, (pkt + sizeof(context->service_buffer)) - p - 12);
834 p += sprintf(p, "\x0d\x0a");
836 /* prepare the expected server accept response */
838 n = snprintf(buf, sizeof buf, "%s%s", key_b64, magic_websocket_guid);
839 buf[sizeof(buf) - 1] = '\0';
840 SHA1((unsigned char *)buf, n, (unsigned char *)hash);
842 lws_b64_encode_string(hash, 20,
843 wsi->u.hdr.initial_handshake_hash_base64,
844 sizeof wsi->u.hdr.initial_handshake_hash_base64);
846 /* done with these now */