2 * libwebsockets - small server side websockets and web server implementation
4 * Copyright (C) 2010-2014 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"
25 lws_handshake_client(struct lws *wsi, unsigned char **buf, size_t len)
30 case LWSCM_WSCL_WAITING_PROXY_REPLY:
31 case LWSCM_WSCL_ISSUE_HANDSHAKE:
32 case LWSCM_WSCL_WAITING_SERVER_REPLY:
33 case LWSCM_WSCL_WAITING_EXTENSION_CONNECT:
37 * we were accepting input but now we stopped doing so
39 if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
40 lwsl_debug("%s: caching %d\n", __func__, len);
41 lws_rxflow_cache(wsi, *buf, 0, len);
44 if (wsi->u.ws.rx_draining_ext) {
45 m = lws_rx_sm(wsi, 0);
50 /* account for what we're using in rxflow buffer */
51 if (wsi->rxflow_buffer)
54 if (lws_client_rx_sm(wsi, *(*buf)++)) {
55 lwsl_debug("client_rx_sm exited\n");
60 lwsl_debug("%s: finished with %d\n", __func__, len);
70 lws_client_socket_service(struct lws_context *context, struct lws *wsi,
71 struct lws_pollfd *pollfd)
73 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
74 char *p = (char *)&pt->serv_buf[0];
81 case LWSCM_WSCL_WAITING_CONNECT:
84 * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE
85 * timeout protection set in client-handshake.c
88 if (!lws_client_connect_2(wsi)) {
90 lwsl_client("closed\n");
94 /* either still pending connection, or changed mode */
97 case LWSCM_WSCL_WAITING_PROXY_REPLY:
99 /* handle proxy hung up on us */
101 if (pollfd->revents & LWS_POLLHUP) {
103 lwsl_warn("Proxy connection %p (fd=%d) dead\n",
104 (void *)wsi, pollfd->fd);
106 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
110 n = recv(wsi->sock, sb, LWS_MAX_SOCKET_IO_BUF, 0);
112 if (LWS_ERRNO == LWS_EAGAIN) {
113 lwsl_debug("Proxy read returned EAGAIN... retrying\n");
117 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
118 lwsl_err("ERROR reading from proxy socket\n");
122 pt->serv_buf[13] = '\0';
123 if (strcmp(sb, "HTTP/1.0 200 ") &&
124 strcmp(sb, "HTTP/1.1 200 ")) {
125 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
126 lwsl_err("ERROR proxy: %s\n", sb);
130 /* clear his proxy connection timeout */
132 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
136 case LWSCM_WSCL_ISSUE_HANDSHAKE:
139 * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE
140 * timeout protection set in client-handshake.c
142 * take care of our lws_callback_on_writable
143 * happening at a time when there's no real connection yet
145 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0))
148 #ifdef LWS_OPENSSL_SUPPORT
149 /* we can retry this... just cook the SSL BIO the first time */
151 if (wsi->use_ssl && !wsi->ssl) {
152 #if defined(CYASSL_SNI_HOST_NAME) || defined(WOLFSSL_SNI_HOST_NAME) || defined(SSL_CTRL_SET_TLSEXT_HOSTNAME)
153 const char *hostname = lws_hdr_simple_ptr(wsi,
154 _WSI_TOKEN_CLIENT_HOST);
157 wsi->ssl = SSL_new(context->ssl_client_ctx);
159 SSL_set_mode(wsi->ssl,
160 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
163 * use server name indication (SNI), if supported,
164 * when establishing connection
167 #ifdef USE_OLD_CYASSL
168 #ifdef CYASSL_SNI_HOST_NAME
169 CyaSSL_UseSNI(wsi->ssl, CYASSL_SNI_HOST_NAME,
170 hostname, strlen(hostname));
173 #ifdef WOLFSSL_SNI_HOST_NAME
174 wolfSSL_UseSNI(wsi->ssl, WOLFSSL_SNI_HOST_NAME,
175 hostname, strlen(hostname));
179 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
180 SSL_set_tlsext_host_name(wsi->ssl, hostname);
186 * wolfSSL/CyaSSL does certificate verification differently
188 * If we should ignore the certificate, we need to set
189 * this before SSL_new and SSL_connect is called.
190 * Otherwise the connect will simply fail with error
193 #ifdef USE_OLD_CYASSL
194 if (wsi->use_ssl == 2)
195 CyaSSL_set_verify(wsi->ssl,
196 SSL_VERIFY_NONE, NULL);
198 if (wsi->use_ssl == 2)
199 wolfSSL_set_verify(wsi->ssl,
200 SSL_VERIFY_NONE, NULL);
202 #endif /* USE_WOLFSSL */
205 BIO_new_socket(wsi->sock, BIO_NOCLOSE);
206 SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
209 #ifdef USE_OLD_CYASSL
210 CyaSSL_set_using_nonblock(wsi->ssl, 1);
212 wolfSSL_set_using_nonblock(wsi->ssl, 1);
215 BIO_set_nbio(wsi->client_bio, 1); /* nonblocking */
218 SSL_set_ex_data(wsi->ssl,
219 openssl_websocket_private_data_index,
224 lws_latency_pre(context, wsi);
225 n = SSL_connect(wsi->ssl);
226 lws_latency(context, wsi,
227 "SSL_connect LWSCM_WSCL_ISSUE_HANDSHAKE", n, n > 0);
230 n = SSL_get_error(wsi->ssl, n);
232 if (n == SSL_ERROR_WANT_READ)
235 if (n == SSL_ERROR_WANT_WRITE) {
237 * wants us to retry connect due to
238 * state of the underlying ssl layer...
239 * but since it may be stalled on
240 * blocked write, no incoming data may
241 * arrive to trigger the retry.
242 * Force (possibly many times if the SSL
243 * state persists in returning the
244 * condition code, but other sockets
245 * are getting serviced inbetweentimes)
246 * us to get called back when writable.
248 lwsl_info("%s: WANT_WRITE... retrying\n", __func__);
249 lws_callback_on_writable(wsi);
251 wsi->mode = LWSCM_WSCL_WAITING_SSL;
253 return 0; /* no error */
260 * retry if new data comes until we
261 * run into the connection timeout or win
264 if (n != SSL_ERROR_NONE) {
265 lwsl_err("SSL connect error %lu: %s\n",
266 n, ERR_error_string(n, sb));
275 case LWSCM_WSCL_WAITING_SSL:
278 if (wsi->mode == LWSCM_WSCL_WAITING_SSL) {
279 lws_latency_pre(context, wsi);
280 n = SSL_connect(wsi->ssl);
281 lws_latency(context, wsi,
282 "SSL_connect LWSCM_WSCL_WAITING_SSL",
286 n = SSL_get_error(wsi->ssl, n);
288 if (n == SSL_ERROR_WANT_READ)
291 if (n == SSL_ERROR_WANT_WRITE) {
293 * wants us to retry connect due to
294 * state of the underlying ssl layer...
295 * but since it may be stalled on
296 * blocked write, no incoming data may
297 * arrive to trigger the retry.
298 * Force (possibly many times if the SSL
299 * state persists in returning the
300 * condition code, but other sockets
301 * are getting serviced inbetweentimes)
302 * us to get called back when writable.
304 lwsl_info("SSL_connect WANT_WRITE... retrying\n");
305 lws_callback_on_writable(wsi);
314 * retry if new data comes until we
315 * run into the connection timeout or win
318 if (n != SSL_ERROR_NONE) {
319 lwsl_err("SSL connect error %lu: %s\n",
320 n, ERR_error_string(n, sb));
328 * See comment above about wolfSSL certificate
331 lws_latency_pre(context, wsi);
332 n = SSL_get_verify_result(wsi->ssl);
333 lws_latency(context, wsi,
334 "SSL_get_verify_result LWS_CONNMODE..HANDSHAKE",
337 if (n != X509_V_OK) {
338 if ((n == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
339 n == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) && wsi->use_ssl == 2) {
340 lwsl_notice("accepting self-signed certificate\n");
342 lwsl_err("server's cert didn't look good, X509_V_ERR = %d: %s\n",
343 n, ERR_error_string(n, sb));
344 lws_close_free_wsi(wsi,
345 LWS_CLOSE_STATUS_NOSTATUS);
349 #endif /* USE_WOLFSSL */
354 wsi->mode = LWSCM_WSCL_ISSUE_HANDSHAKE2;
355 lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND,
356 context->timeout_secs);
360 case LWSCM_WSCL_ISSUE_HANDSHAKE2:
361 p = lws_generate_client_handshake(wsi, p);
363 lwsl_err("Failed to generate handshake for client\n");
364 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
368 /* send our request to the server */
370 lws_latency_pre(context, wsi);
372 n = lws_ssl_capable_write(wsi, (unsigned char *)sb, p - sb);
373 lws_latency(context, wsi, "send lws_issue_raw", n,
376 case LWS_SSL_CAPABLE_ERROR:
377 lwsl_debug("ERROR writing to client socket\n");
378 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
380 case LWS_SSL_CAPABLE_MORE_SERVICE:
381 lws_callback_on_writable(wsi);
385 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
386 wsi->u.hdr.lextable_pos = 0;
387 wsi->mode = LWSCM_WSCL_WAITING_SERVER_REPLY;
388 lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE,
389 context->timeout_secs);
392 case LWSCM_WSCL_WAITING_SERVER_REPLY:
394 /* handle server hung up on us */
396 if (pollfd->revents & LWS_POLLHUP) {
398 lwsl_debug("Server connection %p (fd=%d) dead\n",
399 (void *)wsi, pollfd->fd);
404 if (!(pollfd->revents & LWS_POLLIN))
407 /* interpret the server response */
410 * HTTP/1.1 101 Switching Protocols
412 * Connection: Upgrade
413 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
414 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
415 * Sec-WebSocket-Protocol: chat
419 * we have to take some care here to only take from the
420 * socket bytewise. The browser may (and has been seen to
421 * in the case that onopen() performs websocket traffic)
422 * coalesce both handshake response and websocket traffic
423 * in one packet, since at that point the connection is
424 * definitively ready from browser pov.
427 while (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE &&
429 n = lws_ssl_capable_read(wsi, &c, 1);
430 lws_latency(context, wsi, "send lws_issue_raw", n,
434 case LWS_SSL_CAPABLE_ERROR:
436 case LWS_SSL_CAPABLE_MORE_SERVICE:
440 if (lws_parse(wsi, c)) {
441 lwsl_warn("problems parsing header\n");
447 * hs may also be coming in multiple packets, there is a 5-sec
448 * libwebsocket timeout still active here too, so if parsing did
449 * not complete just wait for next packet coming in this state
452 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
456 * otherwise deal with the handshake. If there's any
457 * packet traffic already arrived we'll trigger poll() again
458 * right away and deal with it that way
461 return lws_client_interpret_server_handshake(wsi);
464 lwsl_info("closing conn at LWS_CONNMODE...SERVER_REPLY\n");
465 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
468 case LWSCM_WSCL_WAITING_EXTENSION_CONNECT:
469 lwsl_ext("LWSCM_WSCL_WAITING_EXTENSION_CONNECT\n");
472 case LWSCM_WSCL_PENDING_CANDIDATE_CHILD:
473 lwsl_ext("LWSCM_WSCL_PENDING_CANDIDATE_CHILD\n");
483 * In-place str to lower case
490 *s = tolower((int)*s);
496 * lws_http_transaction_completed() - wait for new http transaction or close
497 * @wsi: websocket connection
499 * Returns 1 if the HTTP connection must close now
500 * Returns 0 and resets connection to wait for new HTTP header /
501 * transaction if possible
504 int LWS_WARN_UNUSED_RESULT
505 lws_http_transaction_completed_client(struct lws *wsi)
507 lwsl_debug("%s: wsi %p\n", __func__, wsi);
508 /* if we can't go back to accept new headers, drop the connection */
509 if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
510 lwsl_info("%s: %p: close connection\n", __func__, wsi);
514 /* otherwise set ourselves up ready to go again */
515 wsi->state = LWSS_CLIENT_HTTP_ESTABLISHED;
516 wsi->mode = LWSCM_HTTP_CLIENT_ACCEPTED;
517 wsi->u.http.content_length = 0;
518 wsi->hdr_parsing_completed = 0;
520 /* He asked for it to stay alive indefinitely */
521 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
524 * As client, nothing new is going to come until we ask for it
525 * we can drop the ah, if any
528 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
529 lws_header_table_detach(wsi, 0);
532 /* If we're (re)starting on headers, need other implied init */
533 wsi->u.hdr.ues = URIES_IDLE;
535 lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
541 lws_client_interpret_server_handshake(struct lws *wsi)
543 int n, len, okay = 0, isErrorCodeReceived = 0, port = 0, ssl = 0;
544 struct lws_context *context = wsi->context;
545 int close_reason = LWS_CLOSE_STATUS_PROTOCOL_ERR;
546 const char *pc, *prot, *ads = NULL, *path;
547 struct allocated_headers *ah;
549 #ifndef LWS_NO_EXTENSIONS
550 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
551 char *sb = (char *)&pt->serv_buf[0];
552 const struct lws_ext_options *opts;
553 const struct lws_extension *ext;
562 /* we are being an http client...
565 lws_union_transition(wsi, LWSCM_HTTP_CLIENT_ACCEPTED);
566 wsi->state = LWSS_CLIENT_HTTP_ESTABLISHED;
571 * well, what the server sent looked reasonable for syntax.
572 * Now let's confirm it sent all the necessary headers
574 * http (non-ws) client will expect something like this
577 * server:.libwebsockets
578 * content-type:.text/html
579 * content-length:.17703
580 * set-cookie:.test=LWS_1456736240_336776_COOKIE;Max-Age=360000
586 wsi->u.http.connection_type = HTTP_CONNECTION_KEEP_ALIVE;
587 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP);
588 if (wsi->do_ws && !p) {
589 lwsl_info("no URI\n");
593 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP1_0);
594 wsi->u.http.connection_type = HTTP_CONNECTION_CLOSE;
597 lwsl_info("no URI\n");
601 if (n == 301 || n == 302 || n == 303 || n == 307 || n == 308) {
602 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_LOCATION);
606 if (lws_parse_uri(p, &prot, &ads, &port, &path))
609 if (!strcmp(prot, "wss://") || !strcmp(prot, "https://"))
612 if (lws_client_reset(wsi, ssl, ads, port, path, ads)) {
613 lwsl_err("Redirect failed\n");
621 lwsl_notice("Connection failed with code %d", n);
625 #ifdef LWS_WITH_HTTP_PROXY
626 wsi->perform_rewrite = 0;
627 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
628 if (!strncmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE),
630 wsi->perform_rewrite = 1;
634 /* allocate the per-connection user memory (if any) */
635 if (lws_ensure_user_space(wsi)) {
636 lwsl_err("Problem allocating wsi user mem\n");
640 /* he may choose to send us stuff in chunked transfer-coding */
642 wsi->chunk_remaining = 0; /* ie, next thing is chunk size */
643 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_TRANSFER_ENCODING)) {
644 wsi->chunked = !strcmp(lws_hdr_simple_ptr(wsi,
645 WSI_TOKEN_HTTP_TRANSFER_ENCODING),
647 /* first thing is hex, after payload there is crlf */
648 wsi->chunk_parser = ELCP_HEX;
651 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
652 wsi->u.http.content_length =
653 atoi(lws_hdr_simple_ptr(wsi,
654 WSI_TOKEN_HTTP_CONTENT_LENGTH));
655 lwsl_notice("%s: incoming content length %d\n", __func__,
656 wsi->u.http.content_length);
657 wsi->u.http.content_remain = wsi->u.http.content_length;
658 } else /* can't do 1.1 without a content length or chunked */
660 wsi->u.http.connection_type = HTTP_CONNECTION_CLOSE;
663 * we seem to be good to go, give client last chance to check
666 if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH,
667 wsi->user_space, NULL, 0))
670 /* clear his proxy connection timeout */
671 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
673 wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
675 /* call him back to inform him he is up */
676 if (wsi->protocol->callback(wsi,
677 LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP,
678 wsi->user_space, NULL, 0))
681 /* free up his parsing allocations */
682 lws_header_table_detach(wsi, 0);
684 lwsl_notice("%s: client connection up\n", __func__);
689 if (lws_hdr_total_length(wsi, WSI_TOKEN_ACCEPT) == 0) {
690 lwsl_info("no ACCEPT\n");
691 isErrorCodeReceived = 1;
695 if (p && strncmp(p, "101", 3)) {
697 "lws_client_handshake: got bad HTTP response '%s'\n", p);
701 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE);
703 lwsl_info("no UPGRADE\n");
707 if (strcmp(p, "websocket")) {
709 "lws_client_handshake: got bad Upgrade header '%s'\n", p);
713 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_CONNECTION);
715 lwsl_info("no Connection hdr\n");
719 if (strcmp(p, "upgrade")) {
720 lwsl_warn("lws_client_int_s_hs: bad header %s\n", p);
724 pc = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);
726 lwsl_parser("lws_client_int_s_hs: no protocol list\n");
728 lwsl_parser("lws_client_int_s_hs: protocol list '%s'\n", pc);
731 * confirm the protocol the server wants to talk was in the list
732 * of protocols we offered
735 len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
737 lwsl_info("lws_client_int_s_hs: WSI_TOKEN_PROTOCOL is null\n");
739 * no protocol name to work from,
740 * default to first protocol
742 wsi->protocol = &context->protocols[0];
743 goto check_extensions;
746 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL);
749 while (pc && *pc && !okay) {
750 if (!strncmp(pc, p, len) &&
751 (pc[len] == ',' || pc[len] == '\0')) {
755 while (*pc && *pc++ != ',')
757 while (*pc && *pc == ' ')
762 lwsl_err("lws_client_int_s_hs: got bad protocol %s\n", p);
767 * identify the selected protocol struct and set it
770 wsi->protocol = NULL;
771 while (context->protocols[n].callback && !wsi->protocol) {
772 if (strcmp(p, context->protocols[n].name) == 0) {
773 wsi->protocol = &context->protocols[n];
779 if (wsi->protocol == NULL) {
780 lwsl_err("lws_client_int_s_hs: fail protocol %s\n", p);
786 #ifndef LWS_NO_EXTENSIONS
787 /* instantiate the accepted extensions */
789 if (!lws_hdr_total_length(wsi, WSI_TOKEN_EXTENSIONS)) {
790 lwsl_ext("no client extensions allowed by server\n");
795 * break down the list of server accepted extensions
796 * and go through matching them or identifying bogons
799 if (lws_hdr_copy(wsi, sb, LWS_MAX_SOCKET_IO_BUF, WSI_TOKEN_EXTENSIONS) < 0) {
800 lwsl_warn("ext list from server failed to copy\n");
810 if (*c && (*c != ',' && *c != '\t')) {
816 if (ignore || *c == ' ') {
822 if (n < sizeof(ext_name) - 1)
836 /* check we actually support it */
838 lwsl_notice("checking client ext %s\n", ext_name);
841 ext = lws_get_context(wsi)->extensions;
842 while (ext && ext->callback) {
843 if (strcmp(ext_name, ext->name)) {
849 lwsl_notice("instantiating client ext %s\n", ext_name);
851 /* instantiate the extension on this conn */
853 wsi->active_extensions[wsi->count_act_ext] = ext;
855 /* allow him to construct his ext instance */
857 ext->callback(lws_get_context(wsi), ext, wsi,
858 LWS_EXT_CB_CLIENT_CONSTRUCT,
859 (void *)&wsi->act_ext_user[wsi->count_act_ext],
863 * allow the user code to override ext defaults if it
867 if (user_callback_handle_rxflow(wsi->protocol->callback,
868 wsi, LWS_CALLBACK_WS_EXT_DEFAULTS,
869 (char *)ext->name, ext_name,
874 lws_ext_parse_options(ext, wsi, wsi->act_ext_user[
875 wsi->count_act_ext], opts, ext_name,
877 lwsl_err("%s: unable to parse user defaults '%s'",
883 * give the extension the server options
885 if (a && lws_ext_parse_options(ext, wsi,
886 wsi->act_ext_user[wsi->count_act_ext],
888 lwsl_err("%s: unable to parse remote def '%s'",
893 if (ext->callback(lws_get_context(wsi), ext, wsi,
894 LWS_EXT_CB_OPTION_CONFIRM,
895 wsi->act_ext_user[wsi->count_act_ext],
897 lwsl_err("%s: ext %s rejects server options %s",
902 wsi->count_act_ext++;
908 lwsl_warn("Unknown ext '%s'!\n", ext_name);
920 * Confirm his accept token is the one we precomputed
923 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_ACCEPT);
924 if (strcmp(p, wsi->u.hdr.ah->initial_handshake_hash_base64)) {
925 lwsl_warn("lws_client_int_s_hs: accept '%s' wrong vs '%s'\n", p,
926 wsi->u.hdr.ah->initial_handshake_hash_base64);
930 /* allocate the per-connection user memory (if any) */
931 if (lws_ensure_user_space(wsi)) {
932 lwsl_err("Problem allocating wsi user mem\n");
937 * we seem to be good to go, give client last chance to check
940 if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH,
941 wsi->user_space, NULL, 0))
944 /* clear his proxy connection timeout */
945 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
947 /* free up his parsing allocations */
948 lws_header_table_detach(wsi, 0);
950 lws_union_transition(wsi, LWSCM_WS_CLIENT);
951 wsi->state = LWSS_ESTABLISHED;
953 wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
956 * create the frame buffer for this connection according to the
957 * size mentioned in the protocol definition. If 0 there, then
958 * use a big default for compatibility
960 n = wsi->protocol->rx_buffer_size;
962 n = LWS_MAX_SOCKET_IO_BUF;
964 wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
965 if (!wsi->u.ws.rx_ubuf) {
966 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
969 wsi->u.ws.rx_ubuf_alloc = n;
970 lwsl_info("Allocating client RX buffer %d\n", n);
972 if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF, (const char *)&n,
974 lwsl_warn("Failed to set SNDBUF to %d", n);
978 lwsl_debug("handshake OK for protocol %s\n", wsi->protocol->name);
980 /* call him back to inform him he is up */
982 if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_ESTABLISHED,
983 wsi->user_space, NULL, 0))
985 #ifndef LWS_NO_EXTENSIONS
987 * inform all extensions, not just active ones since they
990 ext = context->extensions;
992 while (ext && ext->callback) {
994 for (n = 0; n < wsi->count_act_ext; n++)
995 if (wsi->active_extensions[n] == ext)
996 v = wsi->act_ext_user[n];
998 ext->callback(context, ext, wsi,
999 LWS_EXT_CB_ANY_WSI_ESTABLISHED, v, NULL, 0);
1007 close_reason = LWS_CLOSE_STATUS_NOSTATUS;
1010 if (wsi->protocol && wsi->state == LWSS_ESTABLISHED) {
1011 if (isErrorCodeReceived && p) {
1012 wsi->protocol->callback(wsi,
1013 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
1015 (unsigned int)strlen(p));
1017 wsi->protocol->callback(wsi,
1018 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
1019 wsi->user_space, NULL, 0);
1023 lwsl_info("closing connection due to bail2 connection error\n");
1025 /* closing will free up his parsing allocations */
1026 lws_close_free_wsi(wsi, close_reason);
1033 lws_generate_client_handshake(struct lws *wsi, char *pkt)
1035 char buf[128], hash[20], key_b64[40], *p = pkt;
1036 struct lws_context *context = wsi->context;
1039 #ifndef LWS_NO_EXTENSIONS
1040 const struct lws_extension *ext;
1044 meth = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_METHOD);
1053 * create the random key
1055 n = lws_get_random(context, hash, 16);
1057 lwsl_err("Unable to read from random dev %s\n",
1058 SYSTEM_RANDOM_FILEPATH);
1059 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1063 lws_b64_encode_string(hash, 16, key_b64, sizeof(key_b64));
1067 * 04 example client handshake
1069 * GET /chat HTTP/1.1
1070 * Host: server.example.com
1071 * Upgrade: websocket
1072 * Connection: Upgrade
1073 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
1074 * Sec-WebSocket-Origin: http://example.com
1075 * Sec-WebSocket-Protocol: chat, superchat
1076 * Sec-WebSocket-Version: 4
1079 p += sprintf(p, "%s %s HTTP/1.1\x0d\x0a", meth,
1080 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_URI));
1082 p += sprintf(p, "Pragma: no-cache\x0d\x0a"
1083 "Cache-Control: no-cache\x0d\x0a");
1085 p += sprintf(p, "Host: %s\x0d\x0a",
1086 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_HOST));
1088 if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN))
1089 p += sprintf(p, "Origin: http://%s\x0d\x0a",
1090 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN));
1093 p += sprintf(p, "Upgrade: websocket\x0d\x0a"
1094 "Connection: Upgrade\x0d\x0a"
1095 "Sec-WebSocket-Key: ");
1097 p += strlen(key_b64);
1098 p += sprintf(p, "\x0d\x0a");
1099 if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS))
1100 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
1101 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS));
1103 /* tell the server what extensions we could support */
1105 #ifndef LWS_NO_EXTENSIONS
1106 ext = context->extensions;
1107 while (ext && ext->callback) {
1108 n = lws_ext_cb_all_exts(context, wsi,
1109 LWS_EXT_CB_CHECK_OK_TO_PROPOSE_EXTENSION,
1110 (char *)ext->name, 0);
1111 if (n) { /* an extension vetos us */
1112 lwsl_ext("ext %s vetoed\n", (char *)ext->name);
1116 n = context->protocols[0].callback(wsi,
1117 LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
1118 wsi->user_space, (char *)ext->name, 0);
1121 * zero return from callback means
1122 * go ahead and allow the extension,
1123 * it's what we get if the callback is
1137 p += sprintf(p, "Sec-WebSocket-Extensions: ");
1138 p += sprintf(p, "%s", ext->client_offer);
1144 p += sprintf(p, "\x0d\x0a");
1147 if (wsi->ietf_spec_revision)
1148 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
1149 wsi->ietf_spec_revision);
1151 /* prepare the expected server accept response */
1153 key_b64[39] = '\0'; /* enforce composed length below buf sizeof */
1154 n = sprintf(buf, "%s258EAFA5-E914-47DA-95CA-C5AB0DC85B11", key_b64);
1156 lws_SHA1((unsigned char *)buf, n, (unsigned char *)hash);
1158 lws_b64_encode_string(hash, 20,
1159 wsi->u.hdr.ah->initial_handshake_hash_base64,
1160 sizeof(wsi->u.hdr.ah->initial_handshake_hash_base64));
1163 /* give userland a chance to append, eg, cookies */
1165 context->protocols[0].callback(wsi, LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
1166 NULL, &p, (pkt + LWS_MAX_SOCKET_IO_BUF) - p - 12);
1168 p += sprintf(p, "\x0d\x0a");