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 int lws_client_socket_service(struct libwebsocket_context *context,
39 struct libwebsocket *wsi, struct pollfd *pollfd)
42 char *p = (char *)&context->service_buffer[0];
48 case LWS_CONNMODE_WS_CLIENT_WAITING_PROXY_REPLY:
50 /* handle proxy hung up on us */
52 if (pollfd->revents & (POLLERR | POLLHUP)) {
54 lwsl_warn("Proxy connection %p (fd=%d) dead\n",
55 (void *)wsi, pollfd->fd);
57 libwebsocket_close_and_free_session(context, wsi,
58 LWS_CLOSE_STATUS_NOSTATUS);
62 n = recv(wsi->sock, context->service_buffer,
63 sizeof(context->service_buffer), 0);
65 libwebsocket_close_and_free_session(context, wsi,
66 LWS_CLOSE_STATUS_NOSTATUS);
67 lwsl_err("ERROR reading from proxy socket\n");
71 context->service_buffer[13] = '\0';
72 if (strcmp((char *)context->service_buffer, "HTTP/1.0 200 ")) {
73 libwebsocket_close_and_free_session(context, wsi,
74 LWS_CLOSE_STATUS_NOSTATUS);
75 lwsl_err("ERROR proxy: %s\n", context->service_buffer);
79 /* clear his proxy connection timeout */
81 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
85 case LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE:
88 * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE
89 * timeout protection set in client-handshake.c
92 #ifdef LWS_OPENSSL_SUPPORT
95 * take care of our libwebsocket_callback_on_writable
96 * happening at a time when there's no real connection yet
99 pollfd->events &= ~POLLOUT;
101 /* external POLL support via protocol 0 */
102 context->protocols[0].callback(context, wsi,
103 LWS_CALLBACK_CLEAR_MODE_POLL_FD,
104 (void *)(long)wsi->sock, NULL, POLLOUT);
106 /* we can retry this... just cook the SSL BIO the first time */
108 if (wsi->use_ssl && !wsi->ssl) {
110 wsi->ssl = SSL_new(context->ssl_client_ctx);
114 * CyaSSL does certificate verification differently
116 * If we should ignore the certificate, we need to set
117 * this before SSL_new and SSL_connect is called.
118 * Otherwise the connect will simply fail with error
121 if (wsi->use_ssl == 2)
122 CyaSSL_set_verify(wsi->ssl,
123 SSL_VERIFY_NONE, NULL);
124 #endif /* USE_CYASSL */
127 BIO_new_socket(wsi->sock, BIO_NOCLOSE);
128 SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
131 CyaSSL_set_using_nonblock(wsi->ssl, 1);
133 BIO_set_nbio(wsi->client_bio, 1); /* nonblocking */
136 SSL_set_ex_data(wsi->ssl,
137 openssl_websocket_private_data_index,
142 lws_latency_pre(context, wsi);
143 n = SSL_connect(wsi->ssl);
144 lws_latency(context, wsi,
145 "SSL_connect LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE",
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
155 * state of the underlying ssl layer...
156 * but since it may be stalled on
157 * blocked write, no incoming data may
158 * arrive to trigger the retry.
159 * Force (possibly many times if the SSL
160 * state persists in returning the
161 * condition code, but other sockets
162 * are getting serviced inbetweentimes)
163 * us to get called back when writable.
167 "SSL_connect WANT_... retrying\n");
168 libwebsocket_callback_on_writable(
171 return 0; /* no error */
178 * retry if new data comes until we
179 * run into the connection timeout or win
182 lwsl_err("SSL connect error %s\n",
183 ERR_error_string(ERR_get_error(),
184 (char *)context->service_buffer));
190 * See comment above about CyaSSL certificate
193 lws_latency_pre(context, wsi);
194 n = SSL_get_verify_result(wsi->ssl);
195 lws_latency(context, wsi,
196 "SSL_get_verify_result LWS_CONNMODE..HANDSHAKE",
198 if ((n != X509_V_OK) && (
199 n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
200 wsi->use_ssl != 2)) {
203 "server's cert didn't look good %d\n", n);
204 libwebsocket_close_and_free_session(context,
205 wsi, LWS_CLOSE_STATUS_NOSTATUS);
208 #endif /* USE_CYASSL */
213 p = libwebsockets_generate_client_handshake(context, wsi, p);
215 lwsl_err("Failed to generate handshake for client\n");
216 libwebsocket_close_and_free_session(context, wsi,
217 LWS_CLOSE_STATUS_NOSTATUS);
221 /* send our request to the server */
223 lws_latency_pre(context, wsi);
224 #ifdef LWS_OPENSSL_SUPPORT
226 n = SSL_write(wsi->ssl, context->service_buffer,
227 p - (char *)context->service_buffer);
230 n = send(wsi->sock, context->service_buffer,
231 p - (char *)context->service_buffer, 0);
232 lws_latency(context, wsi,
233 "send or SSL_write LWS_CONNMODE...HANDSHAKE",
237 lwsl_debug("ERROR writing to client socket\n");
238 libwebsocket_close_and_free_session(context, wsi,
239 LWS_CLOSE_STATUS_NOSTATUS);
243 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
244 wsi->u.hdr.lextable_pos = 0;
245 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY;
246 libwebsocket_set_timeout(wsi,
247 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE,
251 case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
253 /* handle server hung up on us */
255 if (pollfd->revents & (POLLERR | POLLHUP)) {
257 lwsl_debug("Server connection %p (fd=%d) dead\n",
258 (void *)wsi, pollfd->fd);
263 if (!(pollfd->revents & POLLIN))
266 /* interpret the server response */
269 * HTTP/1.1 101 Switching Protocols
271 * Connection: Upgrade
272 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
273 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
274 * Sec-WebSocket-Protocol: chat
278 * we have to take some care here to only take from the
279 * socket bytewise. The browser may (and has been seen to
280 * in the case that onopen() performs websocket traffic)
281 * coalesce both handshake response and websocket traffic
282 * in one packet, since at that point the connection is
283 * definitively ready from browser pov.
287 while (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE &&
289 #ifdef LWS_OPENSSL_SUPPORT
291 len = SSL_read(wsi->ssl, &c, 1);
293 n = SSL_get_error(wsi->ssl, len);
294 if (n == SSL_ERROR_WANT_READ ||
295 n == SSL_ERROR_WANT_WRITE)
300 len = recv(wsi->sock, &c, 1, 0);
305 if (libwebsocket_parse(wsi, c)) {
312 * hs may also be coming in multiple packets, there is a 5-sec
313 * libwebsocket timeout still active here too, so if parsing did
314 * not complete just wait for next packet coming in this state
317 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
321 * otherwise deal with the handshake. If there's any
322 * packet traffic already arrived we'll trigger poll() again
323 * right away and deal with it that way
326 return lws_client_interpret_server_handshake(context, wsi);
330 "closing connection at LWS_CONNMODE...SERVER_REPLY\n");
331 libwebsocket_close_and_free_session(context, wsi,
332 LWS_CLOSE_STATUS_NOSTATUS);
335 case LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT:
336 lwsl_ext("LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT\n");
339 case LWS_CONNMODE_WS_CLIENT_PENDING_CANDIDATE_CHILD:
340 lwsl_ext("LWS_CONNMODE_WS_CLIENT_PENDING_CANDIDATE_CHILD\n");
351 * In-place str to lower case
364 lws_client_interpret_server_handshake(struct libwebsocket_context *context,
365 struct libwebsocket *wsi)
371 #ifndef LWS_NO_EXTENSIONS
373 struct libwebsocket_extension *ext;
381 * well, what the server sent looked reasonable for syntax.
382 * Now let's confirm it sent all the necessary headers
385 if (lws_hdr_total_length(wsi, WSI_TOKEN_ACCEPT) == 0)
388 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP);
391 if (p && strncmp(p, "101", 3)) {
393 "lws_client_handshake: got bad HTTP response '%s'\n", p);
397 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE);
401 if (strcmp(p, "websocket")) {
403 "lws_client_handshake: got bad Upgrade header '%s'\n", p);
407 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_CONNECTION);
411 if (strcmp(p, "upgrade")) {
412 lwsl_warn("lws_client_int_s_hs: bad header %s\n", p);
416 pc = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);
418 lwsl_parser("lws_client_int_s_hs: no protocol list\n");
420 lwsl_parser("lws_client_int_s_hs: protocol list '%s'\n", pc);
423 * confirm the protocol the server wants to talk was in the list
424 * of protocols we offered
427 len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
430 lwsl_info("lws_client_int_s_hs: WSI_TOKEN_PROTOCOL is null\n");
432 * no protocol name to work from,
433 * default to first protocol
435 wsi->protocol = &context->protocols[0];
436 goto check_extensions;
439 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL);
442 while (*pc && !okay) {
443 if (!strncmp(pc, p, len) &&
444 (pc[len] == ',' || pc[len] == '\0')) {
448 while (*pc && *pc != ',')
450 while (*pc && *pc != ' ')
455 lwsl_err("lws_client_int_s_hs: got bad protocol %s\n", p);
460 * identify the selected protocol struct and set it
463 wsi->protocol = NULL;
464 while (context->protocols[n].callback && !wsi->protocol) {
465 if (strcmp(p, context->protocols[n].name) == 0) {
466 wsi->protocol = &context->protocols[n];
472 if (wsi->protocol == NULL) {
473 lwsl_err("lws_client_int_s_hs: fail protocol %s\n", p);
479 #ifndef LWS_NO_EXTENSIONS
480 /* instantiate the accepted extensions */
482 if (!lws_hdr_total_length(wsi, WSI_TOKEN_EXTENSIONS)) {
483 lwsl_ext("no client extenstions allowed by server\n");
488 * break down the list of server accepted extensions
489 * and go through matching them or identifying bogons
492 if (lws_hdr_copy(wsi, (char *)context->service_buffer,
493 sizeof(context->service_buffer), WSI_TOKEN_EXTENSIONS) < 0)
496 c = (char *)context->service_buffer;
500 if (*c && (*c != ',' && *c != ' ' && *c != '\t')) {
502 if (n < sizeof(ext_name) - 1)
515 /* check we actually support it */
517 lwsl_ext("checking client ext %s\n", ext_name);
520 ext = wsi->protocol->owning_server->extensions;
521 while (ext && ext->callback) {
523 if (strcmp(ext_name, ext->name)) {
530 lwsl_ext("instantiating client ext %s\n", ext_name);
532 /* instantiate the extension on this conn */
534 wsi->active_extensions_user[
535 wsi->count_active_extensions] =
536 malloc(ext->per_session_data_size);
537 if (wsi->active_extensions_user[
538 wsi->count_active_extensions] == NULL) {
539 lwsl_err("Out of mem\n");
542 memset(wsi->active_extensions_user[
543 wsi->count_active_extensions], 0,
544 ext->per_session_data_size);
545 wsi->active_extensions[
546 wsi->count_active_extensions] = ext;
548 /* allow him to construct his context */
550 ext->callback(wsi->protocol->owning_server,
552 LWS_EXT_CALLBACK_CLIENT_CONSTRUCT,
553 wsi->active_extensions_user[
554 wsi->count_active_extensions],
557 wsi->count_active_extensions++;
563 lwsl_warn("Unknown ext '%s'!\n", ext_name);
574 * Confirm his accept token is the one we precomputed
577 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_ACCEPT);
578 if (strcmp(p, wsi->u.hdr.initial_handshake_hash_base64)) {
579 lwsl_warn("lws_client_int_s_hs: accept %s wrong vs %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);
665 wsi->protocol->callback(context, wsi,
666 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
667 wsi->user_space, NULL, 0);
669 lwsl_info("closing connection due to bail2 connection error\n");
671 /* free up his parsing allocations */
676 libwebsocket_close_and_free_session(context, wsi,
677 LWS_CLOSE_STATUS_PROTOCOL_ERR);
684 libwebsockets_generate_client_handshake(struct libwebsocket_context *context,
685 struct libwebsocket *wsi, char *pkt)
692 #ifndef LWS_NO_EXTENSIONS
693 struct libwebsocket_extension *ext;
694 struct libwebsocket_extension *ext1;
697 static const char magic_websocket_guid[] =
698 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
701 * create the random key
704 n = libwebsockets_get_random(context, hash, 16);
706 lwsl_err("Unable to read from random dev %s\n",
707 SYSTEM_RANDOM_FILEPATH);
708 libwebsocket_close_and_free_session(context, wsi,
709 LWS_CLOSE_STATUS_NOSTATUS);
713 lws_b64_encode_string(hash, 16, key_b64, sizeof(key_b64));
716 * 00 example client handshake
718 * GET /socket.io/websocket HTTP/1.1
720 * Connection: Upgrade
721 * Host: 127.0.0.1:9999
722 * Origin: http://127.0.0.1
723 * Sec-WebSocket-Key1: 1 0 2#0W 9 89 7 92 ^
724 * Sec-WebSocket-Key2: 7 7Y 4328 B2v[8(z1
725 * Cookie: socketio=websocket
729 * 04 example client handshake
732 * Host: server.example.com
734 * Connection: Upgrade
735 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
736 * Sec-WebSocket-Origin: http://example.com
737 * Sec-WebSocket-Protocol: chat, superchat
738 * Sec-WebSocket-Version: 4
741 p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a",
742 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_URI));
745 "Pragma: no-cache\x0d\x0a""Cache-Control: no-cache\x0d\x0a");
747 p += sprintf(p, "Host: %s\x0d\x0a",
748 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_HOST));
750 "Upgrade: websocket\x0d\x0aConnection: Upgrade\x0d\x0aSec-WebSocket-Key: ");
752 p += strlen(key_b64);
753 p += sprintf(p, "\x0d\x0a");
754 if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN))
755 p += sprintf(p, "Origin: %s\x0d\x0a",
756 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN));
758 if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS))
759 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
760 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS));
762 /* tell the server what extensions we could support */
764 p += sprintf(p, "Sec-WebSocket-Extensions: ");
765 #ifndef LWS_NO_EXTENSIONS
766 ext = context->extensions;
767 while (ext && ext->callback) {
770 ext1 = context->extensions;
772 while (ext1 && ext1->callback) {
773 n |= ext1->callback(context, ext1, wsi,
774 LWS_EXT_CALLBACK_CHECK_OK_TO_PROPOSE_EXTENSION,
775 NULL, (char *)ext->name, 0);
780 if (n) { /* an extension vetos us */
781 lwsl_ext("ext %s vetoed\n", (char *)ext->name);
786 n = context->protocols[0].callback(context, wsi,
787 LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
788 wsi->user_space, (char *)ext->name, 0);
791 * zero return from callback means
792 * go ahead and allow the extension,
793 * it's what we get if the callback is
806 p += sprintf(p, "%s", ext->name);
812 p += sprintf(p, "\x0d\x0a");
814 if (wsi->ietf_spec_revision)
815 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
816 wsi->ietf_spec_revision);
818 /* give userland a chance to append, eg, cookies */
820 context->protocols[0].callback(context, wsi,
821 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
822 NULL, &p, (pkt + sizeof(context->service_buffer)) - p - 12);
824 p += sprintf(p, "\x0d\x0a");
826 /* prepare the expected server accept response */
828 n = snprintf(buf, sizeof(buf), "%s%s", key_b64, magic_websocket_guid);
829 buf[sizeof(buf) - 1] = '\0';
830 SHA1((unsigned char *)buf, n, (unsigned char *)hash);
832 lws_b64_encode_string(hash, 20,
833 wsi->u.hdr.initial_handshake_hash_base64,
834 sizeof(wsi->u.hdr.initial_handshake_hash_base64));