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);
117 wsi->client_bio = BIO_new_socket(wsi->sock,
120 SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
122 BIO_set_nbio(wsi->client_bio, 1); /* nonblocking */
124 SSL_set_ex_data(wsi->ssl,
125 openssl_websocket_private_data_index,
130 lws_latency_pre(context, wsi);
131 n = SSL_connect(wsi->ssl);
132 lws_latency(context, wsi, "SSL_connect LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE", n, n > 0);
135 n = SSL_get_error(wsi->ssl, n);
137 if (n == SSL_ERROR_WANT_READ ||
138 n == SSL_ERROR_WANT_WRITE) {
140 * wants us to retry connect due to state of the
141 * underlying ssl layer... but since it may be
142 * stalled on blocked write, no incoming data may
143 * arrive to trigger the retry. Force (possibly
144 * many if the SSL state persists in returning the
145 * condition code, but other sockets are getting
146 * serviced inbetweentimes) us to get called back
150 lwsl_info("SSL_connect -> SSL_ERROR_WANT_... retrying\n");
151 libwebsocket_callback_on_writable(context, wsi);
153 return 0; /* no error */
160 * retry if new data comes until we
161 * run into the connection timeout or win
164 lwsl_err("SSL connect error %s\n",
165 ERR_error_string(ERR_get_error(),
170 lws_latency_pre(context, wsi);
171 n = SSL_get_verify_result(wsi->ssl);
172 lws_latency(context, wsi, "SSL_get_verify_result LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE", n, n > 0);
173 if ((n != X509_V_OK) && (
174 n != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
175 wsi->use_ssl != 2)) {
177 lwsl_err("server's cert didn't "
178 "look good %d\n", n);
179 libwebsocket_close_and_free_session(context,
180 wsi, LWS_CLOSE_STATUS_NOSTATUS);
187 p = libwebsockets_generate_client_handshake(context, wsi, p);
189 lwsl_err("Failed to generate handshake for client, closing it\n");
190 libwebsocket_close_and_free_session(context, wsi,
191 LWS_CLOSE_STATUS_NOSTATUS);
195 /* send our request to the server */
197 lws_latency_pre(context, wsi);
198 #ifdef LWS_OPENSSL_SUPPORT
200 n = SSL_write(wsi->ssl, pkt, p - pkt);
203 n = send(wsi->sock, pkt, p - pkt, 0);
204 lws_latency(context, wsi, "send or SSL_write LWS_CONNMODE_WS_CLIENT_ISSUE_HANDSHAKE", n, n >= 0);
207 lwsl_debug("ERROR writing to client socket\n");
208 libwebsocket_close_and_free_session(context, wsi,
209 LWS_CLOSE_STATUS_NOSTATUS);
213 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
214 wsi->u.hdr.lextable_pos = 0;
215 wsi->mode = LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY;
216 libwebsocket_set_timeout(wsi,
217 PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE, AWAITING_TIMEOUT);
221 case LWS_CONNMODE_WS_CLIENT_WAITING_SERVER_REPLY:
223 /* handle server hung up on us */
225 if (pollfd->revents & (POLLERR | POLLHUP)) {
227 lwsl_debug("Server connection %p (fd=%d) dead\n",
228 (void *)wsi, pollfd->fd);
234 /* interpret the server response */
237 * HTTP/1.1 101 Switching Protocols
239 * Connection: Upgrade
240 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
241 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
242 * Sec-WebSocket-Protocol: chat
246 * we have to take some care here to only take from the
247 * socket bytewise. The browser may (and has been seen to
248 * in the case that onopen() performs websocket traffic)
249 * coalesce both handshake response and websocket traffic
250 * in one packet, since at that point the connection is
251 * definitively ready from browser pov.
255 while (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE && len > 0) {
256 #ifdef LWS_OPENSSL_SUPPORT
258 len = SSL_read(wsi->ssl, &c, 1);
261 len = recv(wsi->sock, &c, 1, 0);
263 libwebsocket_parse(wsi, c);
267 * hs may also be coming in multiple packets, there is a 5-sec
268 * libwebsocket timeout still active here too, so if parsing did
269 * not complete just wait for next packet coming in this state
272 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
276 * otherwise deal with the handshake. If there's any
277 * packet traffic already arrived we'll trigger poll() again
278 * right away and deal with it that way
281 return lws_client_interpret_server_handshake(context, wsi);
285 free(wsi->c_protocol);
286 libwebsocket_close_and_free_session(context, wsi,
287 LWS_CLOSE_STATUS_NOSTATUS);
290 case LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT:
291 lwsl_ext("LWS_CONNMODE_WS_CLIENT_WAITING_EXTENSION_CONNECT\n");
294 case LWS_CONNMODE_WS_CLIENT_PENDING_CANDIDATE_CHILD:
295 lwsl_ext("LWS_CONNMODE_WS_CLIENT_PENDING_CANDIDATE_CHILD\n");
306 * In-place str to lower case
319 lws_client_interpret_server_handshake(struct libwebsocket_context *context,
320 struct libwebsocket *wsi)
324 #ifndef LWS_NO_EXTENSIONS
326 struct libwebsocket_extension *ext;
334 * well, what the server sent looked reasonable for syntax.
335 * Now let's confirm it sent all the necessary headers
338 lwsl_parser("WSI_TOKEN_HTTP: %d\n",
339 wsi->utf8_token[WSI_TOKEN_HTTP].token_len);
340 lwsl_parser("WSI_TOKEN_UPGRADE: %d\n",
341 wsi->utf8_token[WSI_TOKEN_UPGRADE].token_len);
342 lwsl_parser("WSI_TOKEN_CONNECTION: %d\n",
343 wsi->utf8_token[WSI_TOKEN_CONNECTION].token_len);
344 lwsl_parser("WSI_TOKEN_ACCEPT: %d\n",
345 wsi->utf8_token[WSI_TOKEN_ACCEPT].token_len);
346 lwsl_parser("WSI_TOKEN_NONCE: %d\n",
347 wsi->utf8_token[WSI_TOKEN_NONCE].token_len);
348 lwsl_parser("WSI_TOKEN_PROTOCOL: %d\n",
349 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len);
352 strtolower(wsi->utf8_token[WSI_TOKEN_HTTP].token);
353 if (strncmp(wsi->utf8_token[WSI_TOKEN_HTTP].token, "101", 3)) {
354 lwsl_warn("libwebsocket_client_handshake "
355 "server sent bad HTTP response '%s'\n",
356 wsi->utf8_token[WSI_TOKEN_HTTP].token);
360 strtolower(wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
361 if (strcmp(wsi->utf8_token[WSI_TOKEN_UPGRADE].token,
363 lwsl_warn("libwebsocket_client_handshake server "
364 "sent bad Upgrade header '%s'\n",
365 wsi->utf8_token[WSI_TOKEN_UPGRADE].token);
369 strtolower(wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
370 if (strcmp(wsi->utf8_token[WSI_TOKEN_CONNECTION].token,
372 lwsl_warn("libwebsocket_client_handshake server "
373 "sent bad Connection hdr '%s'\n",
374 wsi->utf8_token[WSI_TOKEN_CONNECTION].token);
378 pc = wsi->c_protocol;
380 lwsl_parser("lws_client_interpret_server_handshake: "
381 "NULL c_protocol\n");
383 lwsl_parser("lws_client_interpret_server_handshake: "
384 "cPprotocol='%s'\n", pc);
387 * confirm the protocol the server wants to talk was in the list
388 * of protocols we offered
391 if (!wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len) {
393 lwsl_info("lws_client_interpret_server_handshake "
394 "WSI_TOKEN_PROTOCOL is null\n");
396 * no protocol name to work from,
397 * default to first protocol
399 wsi->protocol = &context->protocols[0];
400 wsi->c_callback = wsi->protocol->callback;
401 free(wsi->c_protocol);
403 goto check_extensions;
406 while (*pc && !okay) {
407 if ((!strncmp(pc, wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
408 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len)) &&
409 (pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == ',' ||
410 pc[wsi->utf8_token[WSI_TOKEN_PROTOCOL].token_len] == '\0')) {
414 while (*pc && *pc != ',')
416 while (*pc && *pc != ' ')
420 /* done with him now */
423 free(wsi->c_protocol);
426 lwsl_err("libwebsocket_client_handshake server "
427 "sent bad protocol '%s'\n",
428 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
433 * identify the selected protocol struct and set it
436 wsi->protocol = NULL;
437 while (context->protocols[n].callback && !wsi->protocol) { /* Stop after finding first one?? */
438 if (strcmp(wsi->utf8_token[WSI_TOKEN_PROTOCOL].token,
439 context->protocols[n].name) == 0) {
440 wsi->protocol = &context->protocols[n];
441 wsi->c_callback = wsi->protocol->callback;
446 if (wsi->protocol == NULL) {
447 lwsl_err("libwebsocket_client_handshake server "
448 "requested protocol '%s', which we "
449 "said we supported but we don't!\n",
450 wsi->utf8_token[WSI_TOKEN_PROTOCOL].token);
456 #ifndef LWS_NO_EXTENSIONS
457 /* instantiate the accepted extensions */
459 if (!wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token_len) {
460 lwsl_ext("no client extenstions allowed by server\n");
465 * break down the list of server accepted extensions
466 * and go through matching them or identifying bogons
469 c = wsi->utf8_token[WSI_TOKEN_EXTENSIONS].token;
473 if (*c && (*c != ',' && *c != ' ' && *c != '\t')) {
475 if (n < sizeof(ext_name) - 1)
488 /* check we actually support it */
490 lwsl_ext("checking client ext %s\n", ext_name);
493 ext = wsi->protocol->owning_server->extensions;
494 while (ext && ext->callback) {
496 if (strcmp(ext_name, ext->name)) {
503 lwsl_ext("instantiating client ext %s\n", ext_name);
505 /* instantiate the extension on this conn */
507 wsi->active_extensions_user[
508 wsi->count_active_extensions] =
509 malloc(ext->per_session_data_size);
510 if (wsi->active_extensions_user[
511 wsi->count_active_extensions] == NULL) {
512 lwsl_err("Out of mem\n");
515 memset(wsi->active_extensions_user[
516 wsi->count_active_extensions], 0,
517 ext->per_session_data_size);
518 wsi->active_extensions[
519 wsi->count_active_extensions] = ext;
521 /* allow him to construct his context */
523 ext->callback(wsi->protocol->owning_server,
525 LWS_EXT_CALLBACK_CLIENT_CONSTRUCT,
526 wsi->active_extensions_user[
527 wsi->count_active_extensions],
530 wsi->count_active_extensions++;
536 lwsl_warn("Server said we should use"
537 "an unknown extension '%s'!\n", ext_name);
548 * Confirm his accept token is the one we precomputed
551 if (strcmp(wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
552 wsi->u.hdr.initial_handshake_hash_base64)) {
553 lwsl_warn("libwebsocket_client_handshake server "
554 "sent bad ACCEPT '%s' vs computed '%s'\n",
555 wsi->utf8_token[WSI_TOKEN_ACCEPT].token,
556 wsi->u.hdr.initial_handshake_hash_base64);
560 /* allocate the per-connection user memory (if any) */
561 if (wsi->protocol->per_session_data_size &&
562 !libwebsocket_ensure_user_space(wsi))
565 /* clear his proxy connection timeout */
567 libwebsocket_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
569 /* mark him as being alive */
571 wsi->state = WSI_STATE_ESTABLISHED;
572 wsi->mode = LWS_CONNMODE_WS_CLIENT;
574 /* union transition */
575 memset(&wsi->u, 0, sizeof wsi->u);
577 lwsl_debug("handshake OK for protocol %s\n", wsi->protocol->name);
579 /* call him back to inform him he is up */
581 wsi->protocol->callback(context, wsi,
582 LWS_CALLBACK_CLIENT_ESTABLISHED,
583 wsi->user_space, NULL, 0);
584 #ifndef LWS_NO_EXTENSIONS
586 * inform all extensions, not just active ones since they
590 ext = context->extensions;
592 while (ext && ext->callback) {
594 for (n = 0; n < wsi->count_active_extensions; n++)
595 if (wsi->active_extensions[n] == ext)
596 v = wsi->active_extensions_user[n];
598 ext->callback(context, ext, wsi,
599 LWS_EXT_CALLBACK_ANY_WSI_ESTABLISHED, v, NULL, 0);
608 free(wsi->c_protocol);
611 if (wsi->c_callback) wsi->c_callback(context, wsi,
612 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
615 libwebsocket_close_and_free_session(context, wsi,
616 LWS_CLOSE_STATUS_NOSTATUS); // But this should be LWS_CLOSE_STATUS_PROTOCOL_ERR
623 libwebsockets_generate_client_handshake(struct libwebsocket_context *context,
624 struct libwebsocket *wsi, char *pkt)
630 #ifndef LWS_NO_EXTENSIONS
631 struct libwebsocket_extension *ext;
632 struct libwebsocket_extension *ext1;
635 unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 1 +
636 MAX_USER_RX_BUFFER + LWS_SEND_BUFFER_POST_PADDING];
637 static const char magic_websocket_guid[] =
638 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
641 * create the random key
644 n = libwebsockets_get_random(context, hash, 16);
646 lwsl_err("Unable to read from random dev %s\n",
647 SYSTEM_RANDOM_FILEPATH);
653 free(wsi->c_protocol);
654 libwebsocket_close_and_free_session(context, wsi,
655 LWS_CLOSE_STATUS_NOSTATUS);
659 lws_b64_encode_string(hash, 16, key_b64, sizeof key_b64);
662 * 00 example client handshake
664 * GET /socket.io/websocket HTTP/1.1
666 * Connection: Upgrade
667 * Host: 127.0.0.1:9999
668 * Origin: http://127.0.0.1
669 * Sec-WebSocket-Key1: 1 0 2#0W 9 89 7 92 ^
670 * Sec-WebSocket-Key2: 7 7Y 4328 B2v[8(z1
671 * Cookie: socketio=websocket
675 * 04 example client handshake
678 * Host: server.example.com
680 * Connection: Upgrade
681 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
682 * Sec-WebSocket-Origin: http://example.com
683 * Sec-WebSocket-Protocol: chat, superchat
684 * Sec-WebSocket-Version: 4
687 p += sprintf(p, "GET %s HTTP/1.1\x0d\x0a", wsi->c_path);
689 p += sprintf(p, "Pragma: no-cache\x0d\x0a"
690 "Cache-Control: no-cache\x0d\x0a");
692 p += sprintf(p, "Host: %s\x0d\x0a", wsi->c_host);
693 p += sprintf(p, "Upgrade: websocket\x0d\x0a"
694 "Connection: Upgrade\x0d\x0a"
695 "Sec-WebSocket-Key: ");
697 p += strlen(key_b64);
698 p += sprintf(p, "\x0d\x0a");
700 if (wsi->ietf_spec_revision == 13)
701 p += sprintf(p, "Origin: %s\x0d\x0a", wsi->c_origin);
703 p += sprintf(p, "Sec-WebSocket-Origin: %s\x0d\x0a",
707 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
710 /* tell the server what extensions we could support */
712 p += sprintf(p, "Sec-WebSocket-Extensions: ");
713 #ifndef LWS_NO_EXTENSIONS
714 ext = context->extensions;
715 while (ext && ext->callback) {
718 ext1 = context->extensions;
720 while (ext1 && ext1->callback) {
721 n |= ext1->callback(context, ext1, wsi,
722 LWS_EXT_CALLBACK_CHECK_OK_TO_PROPOSE_EXTENSION,
723 NULL, (char *)ext->name, 0);
728 if (n) { /* an extension vetos us */
729 lwsl_ext("ext %s vetoed\n", (char *)ext->name);
734 n = context->protocols[0].callback(context, wsi,
735 LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
736 wsi->user_space, (char *)ext->name, 0);
739 * zero return from callback means
740 * go ahead and allow the extension,
741 * it's what we get if the callback is
754 p += sprintf(p, "%s", ext->name);
760 p += sprintf(p, "\x0d\x0a");
762 if (wsi->ietf_spec_revision)
763 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
764 wsi->ietf_spec_revision);
766 /* give userland a chance to append, eg, cookies */
768 context->protocols[0].callback(context, wsi,
769 LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
770 NULL, &p, (pkt + sizeof(pkt)) - p - 12);
772 p += sprintf(p, "\x0d\x0a");
774 /* prepare the expected server accept response */
776 strcpy((char *)buf, key_b64);
777 strcpy((char *)&buf[strlen((char *)buf)], magic_websocket_guid);
779 SHA1(buf, strlen((char *)buf), (unsigned char *)hash);
781 lws_b64_encode_string(hash, 20,
782 wsi->u.hdr.initial_handshake_hash_base64,
783 sizeof wsi->u.hdr.initial_handshake_hash_base64);
785 /* done with these now */