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 %ld\n", __func__, (long)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 %ld\n", __func__, (long)len);
69 LWS_VISIBLE LWS_EXTERN void
70 lws_client_http_body_pending(struct lws *wsi, int something_left_to_send)
72 wsi->client_http_body_pending = !!something_left_to_send;
76 lws_client_socket_service(struct lws_context *context, struct lws *wsi,
77 struct lws_pollfd *pollfd)
79 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
80 char *p = (char *)&pt->serv_buf[0];
81 const char *cce = NULL;
85 #if defined(LWS_WITH_SOCKS5)
86 char conn_mode = 0, pending_timeout = 0;
91 case LWSCM_WSCL_WAITING_CONNECT:
94 * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE
95 * timeout protection set in client-handshake.c
98 if (!lws_client_connect_2(wsi)) {
100 lwsl_client("closed\n");
104 /* either still pending connection, or changed mode */
107 #if defined(LWS_WITH_SOCKS5)
108 /* SOCKS Greeting Reply */
109 case LWSCM_WSCL_WAITING_SOCKS_GREETING_REPLY:
111 /* handle proxy hung up on us */
113 if (pollfd->revents & LWS_POLLHUP) {
115 lwsl_warn("SOCKS connection %p (fd=%d) dead\n",
116 (void *)wsi, pollfd->fd);
118 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
122 n = recv(wsi->desc.sockfd, sb, context->pt_serv_buf_size, 0);
124 if (LWS_ERRNO == LWS_EAGAIN) {
125 lwsl_debug("SOCKS read returned EAGAIN..."
130 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
131 lwsl_err("ERROR reading from SOCKS socket\n");
135 /* processing greeting reply */
136 if (pt->serv_buf[0] == SOCKS_VERSION_5
137 && pt->serv_buf[1] == SOCKS_AUTH_NO_AUTH)
139 lwsl_client("%s\n", "SOCKS greeting reply received "
140 "- No Authentication Method");
141 socks_generate_msg(wsi, SOCKS_MSG_CONNECT, (size_t *)&len);
143 conn_mode = LWSCM_WSCL_WAITING_SOCKS_CONNECT_REPLY;
144 pending_timeout = PENDING_TIMEOUT_AWAITING_SOCKS_CONNECT_REPLY;
145 lwsl_client("%s\n", "Sending SOCKS connect command");
147 else if (pt->serv_buf[0] == SOCKS_VERSION_5
148 && pt->serv_buf[1] == SOCKS_AUTH_USERNAME_PASSWORD)
150 lwsl_client("%s\n", "SOCKS greeting reply received "
151 "- User Name Password Method");
152 socks_generate_msg(wsi, SOCKS_MSG_USERNAME_PASSWORD,
155 conn_mode = LWSCM_WSCL_WAITING_SOCKS_AUTH_REPLY;
156 pending_timeout = PENDING_TIMEOUT_AWAITING_SOCKS_AUTH_REPLY;
157 lwsl_client("%s\n", "Sending SOCKS user/password");
161 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
162 lwsl_err("ERROR SOCKS greeting reply failed, method "
163 "code: %d\n", pt->serv_buf[1]);
167 n = send(wsi->desc.sockfd, (char *)pt->serv_buf, len,
170 lwsl_debug("ERROR writing socks command to socks proxy "
175 lws_set_timeout(wsi, pending_timeout, AWAITING_TIMEOUT);
176 wsi->mode = conn_mode;
179 /* SOCKS auth Reply */
180 case LWSCM_WSCL_WAITING_SOCKS_AUTH_REPLY:
182 /* handle proxy hung up on us */
184 if (pollfd->revents & LWS_POLLHUP) {
186 lwsl_warn("SOCKS connection %p (fd=%d) dead\n",
187 (void *)wsi, pollfd->fd);
189 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
193 n = recv(wsi->desc.sockfd, sb, context->pt_serv_buf_size, 0);
195 if (LWS_ERRNO == LWS_EAGAIN) {
196 lwsl_debug("SOCKS read returned EAGAIN... "
201 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
202 lwsl_err("ERROR reading from socks socket\n");
206 /* processing auth reply */
207 if (pt->serv_buf[0] == SOCKS_SUBNEGOTIATION_VERSION_1
208 && pt->serv_buf[1] == SOCKS_SUBNEGOTIATION_STATUS_SUCCESS)
210 lwsl_client("%s\n", "SOCKS password reply recieved - "
212 socks_generate_msg(wsi, SOCKS_MSG_CONNECT, (size_t *)&len);
214 conn_mode = LWSCM_WSCL_WAITING_SOCKS_CONNECT_REPLY;
216 PENDING_TIMEOUT_AWAITING_SOCKS_CONNECT_REPLY;
217 lwsl_client("%s\n", "Sending SOCKS connect command");
221 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
222 lwsl_err("ERROR : SOCKS user/password reply failed, "
223 "error code: %d\n", pt->serv_buf[1]);
227 n = send(wsi->desc.sockfd, (char *)pt->serv_buf, len,
230 lwsl_debug("ERROR writing connect command to SOCKS "
235 lws_set_timeout(wsi, pending_timeout, AWAITING_TIMEOUT);
236 wsi->mode = conn_mode;
240 /* SOCKS connect command Reply */
241 case LWSCM_WSCL_WAITING_SOCKS_CONNECT_REPLY:
243 /* handle proxy hung up on us */
245 if (pollfd->revents & LWS_POLLHUP) {
247 lwsl_warn("SOCKS connection %p (fd=%d) dead\n",
248 (void *)wsi, pollfd->fd);
250 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
254 n = recv(wsi->desc.sockfd, sb, context->pt_serv_buf_size, 0);
256 if (LWS_ERRNO == LWS_EAGAIN) {
257 lwsl_debug("SOCKS read returned EAGAIN... "
262 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
263 lwsl_err("ERROR reading from socks socket\n");
267 /* processing connect reply */
268 if (pt->serv_buf[0] == SOCKS_VERSION_5
269 && pt->serv_buf[1] == SOCKS_REQUEST_REPLY_SUCCESS)
271 lwsl_client("%s\n", "SOCKS connect reply recieved - "
276 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
277 lwsl_err("ERROR SOCKS connect reply failed, error "
278 "code: %d\n", pt->serv_buf[1]);
282 /* free stash since we are done with it */
283 lws_free_set_NULL(wsi->u.hdr.stash);
285 if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS,
286 wsi->vhost->socks_proxy_address))
288 wsi->c_port = wsi->vhost->socks_proxy_port;
290 /* clear his proxy connection timeout */
292 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
294 goto start_ws_hanshake;
296 case LWSCM_WSCL_WAITING_PROXY_REPLY:
298 /* handle proxy hung up on us */
300 if (pollfd->revents & LWS_POLLHUP) {
302 lwsl_warn("Proxy connection %p (fd=%d) dead\n",
303 (void *)wsi, pollfd->fd);
305 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
309 n = recv(wsi->desc.sockfd, sb, context->pt_serv_buf_size, 0);
311 if (LWS_ERRNO == LWS_EAGAIN) {
312 lwsl_debug("Proxy read returned EAGAIN... retrying\n");
316 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
317 lwsl_err("ERROR reading from proxy socket\n");
321 pt->serv_buf[13] = '\0';
322 if (strcmp(sb, "HTTP/1.0 200 ") &&
323 strcmp(sb, "HTTP/1.1 200 ")) {
324 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
325 lwsl_err("ERROR proxy: %s\n", sb);
329 /* clear his proxy connection timeout */
331 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
335 case LWSCM_WSCL_ISSUE_HANDSHAKE:
338 * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE
339 * timeout protection set in client-handshake.c
341 * take care of our lws_callback_on_writable
342 * happening at a time when there's no real connection yet
344 #if defined(LWS_WITH_SOCKS5)
347 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0))
350 #ifdef LWS_OPENSSL_SUPPORT
351 /* we can retry this... just cook the SSL BIO the first time */
353 if (wsi->use_ssl && !wsi->ssl) {
354 if (lws_ssl_client_bio_create(wsi))
359 n = lws_ssl_client_connect1(wsi);
363 cce = "lws_ssl_client_connect1 failed";
371 case LWSCM_WSCL_WAITING_SSL:
374 n = lws_ssl_client_connect2(wsi);
378 cce = "lws_ssl_client_connect2 failed";
385 wsi->mode = LWSCM_WSCL_ISSUE_HANDSHAKE2;
386 lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND,
387 context->timeout_secs);
391 case LWSCM_WSCL_ISSUE_HANDSHAKE2:
392 p = lws_generate_client_handshake(wsi, p);
394 if (wsi->mode == LWSCM_RAW)
397 lwsl_err("Failed to generate handshake for client\n");
398 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
402 /* send our request to the server */
404 lws_latency_pre(context, wsi);
406 n = lws_ssl_capable_write(wsi, (unsigned char *)sb, p - sb);
407 lws_latency(context, wsi, "send lws_issue_raw", n,
410 case LWS_SSL_CAPABLE_ERROR:
411 lwsl_debug("ERROR writing to client socket\n");
412 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
414 case LWS_SSL_CAPABLE_MORE_SERVICE:
415 lws_callback_on_writable(wsi);
419 if (wsi->client_http_body_pending) {
420 wsi->mode = LWSCM_WSCL_ISSUE_HTTP_BODY;
421 lws_set_timeout(wsi, PENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD,
422 context->timeout_secs);
423 /* user code must ask for writable callback */
427 goto client_http_body_sent;
429 case LWSCM_WSCL_ISSUE_HTTP_BODY:
430 if (wsi->client_http_body_pending) {
431 lws_set_timeout(wsi, PENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD,
432 context->timeout_secs);
433 /* user code must ask for writable callback */
436 client_http_body_sent:
437 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
438 wsi->u.hdr.lextable_pos = 0;
439 wsi->mode = LWSCM_WSCL_WAITING_SERVER_REPLY;
440 lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE,
441 context->timeout_secs);
444 case LWSCM_WSCL_WAITING_SERVER_REPLY:
446 /* handle server hung up on us */
448 if (pollfd->revents & LWS_POLLHUP) {
450 lwsl_debug("Server connection %p (fd=%d) dead\n",
451 (void *)wsi, pollfd->fd);
452 cce = "Peer hung up";
456 if (!(pollfd->revents & LWS_POLLIN))
459 /* interpret the server response */
462 * HTTP/1.1 101 Switching Protocols
464 * Connection: Upgrade
465 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
466 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
467 * Sec-WebSocket-Protocol: chat
471 * we have to take some care here to only take from the
472 * socket bytewise. The browser may (and has been seen to
473 * in the case that onopen() performs websocket traffic)
474 * coalesce both handshake response and websocket traffic
475 * in one packet, since at that point the connection is
476 * definitively ready from browser pov.
479 while (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE &&
481 n = lws_ssl_capable_read(wsi, &c, 1);
482 lws_latency(context, wsi, "send lws_issue_raw", n,
486 case LWS_SSL_CAPABLE_ERROR:
489 case LWS_SSL_CAPABLE_MORE_SERVICE:
493 if (lws_parse(wsi, c)) {
494 lwsl_warn("problems parsing header\n");
500 * hs may also be coming in multiple packets, there is a 5-sec
501 * libwebsocket timeout still active here too, so if parsing did
502 * not complete just wait for next packet coming in this state
505 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
509 * otherwise deal with the handshake. If there's any
510 * packet traffic already arrived we'll trigger poll() again
511 * right away and deal with it that way
514 return lws_client_interpret_server_handshake(wsi);
517 lwsl_info("closing conn at LWS_CONNMODE...SERVER_REPLY\n");
519 lwsl_info("reason: %s\n", cce);
520 wsi->protocol->callback(wsi,
521 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
522 wsi->user_space, (void *)cce, cce ? strlen(cce) : 0);
523 wsi->already_did_cce = 1;
524 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
527 case LWSCM_WSCL_WAITING_EXTENSION_CONNECT:
528 lwsl_ext("LWSCM_WSCL_WAITING_EXTENSION_CONNECT\n");
531 case LWSCM_WSCL_PENDING_CANDIDATE_CHILD:
532 lwsl_ext("LWSCM_WSCL_PENDING_CANDIDATE_CHILD\n");
542 * In-place str to lower case
549 #ifdef LWS_PLAT_OPTEE
550 int tolower_optee(int c);
551 *s = tolower_optee((int)*s);
553 *s = tolower((int)*s);
559 int LWS_WARN_UNUSED_RESULT
560 lws_http_transaction_completed_client(struct lws *wsi)
562 lwsl_debug("%s: wsi %p\n", __func__, wsi);
563 /* if we can't go back to accept new headers, drop the connection */
564 if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
565 lwsl_info("%s: %p: close connection\n", __func__, wsi);
569 /* we don't support chained client connections yet */
572 /* otherwise set ourselves up ready to go again */
573 wsi->state = LWSS_CLIENT_HTTP_ESTABLISHED;
574 wsi->mode = LWSCM_HTTP_CLIENT_ACCEPTED;
575 wsi->u.http.content_length = 0;
576 wsi->hdr_parsing_completed = 0;
578 /* He asked for it to stay alive indefinitely */
579 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
582 * As client, nothing new is going to come until we ask for it
583 * we can drop the ah, if any
586 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
587 lws_header_table_detach(wsi, 0);
590 /* If we're (re)starting on headers, need other implied init */
591 wsi->u.hdr.ues = URIES_IDLE;
593 lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
598 LWS_VISIBLE LWS_EXTERN unsigned int
599 lws_http_client_http_response(struct lws *wsi)
604 return wsi->u.http.ah->http_response;
608 lws_client_interpret_server_handshake(struct lws *wsi)
610 int n, len, okay = 0, port = 0, ssl = 0;
611 int close_reason = LWS_CLOSE_STATUS_PROTOCOL_ERR;
612 struct lws_context *context = wsi->context;
613 const char *pc, *prot, *ads = NULL, *path, *cce = NULL;
614 struct allocated_headers *ah = NULL;
617 #ifndef LWS_NO_EXTENSIONS
618 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
619 char *sb = (char *)&pt->serv_buf[0];
620 const struct lws_ext_options *opts;
621 const struct lws_extension *ext;
631 /* we are being an http client...
633 lws_union_transition(wsi, LWSCM_HTTP_CLIENT_ACCEPTED);
634 wsi->state = LWSS_CLIENT_HTTP_ESTABLISHED;
636 ah->http_response = 0;
640 * well, what the server sent looked reasonable for syntax.
641 * Now let's confirm it sent all the necessary headers
643 * http (non-ws) client will expect something like this
646 * server:.libwebsockets
647 * content-type:.text/html
648 * content-length:.17703
649 * set-cookie:.test=LWS_1456736240_336776_COOKIE;Max-Age=360000
655 wsi->u.http.connection_type = HTTP_CONNECTION_KEEP_ALIVE;
656 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP);
657 if (wsi->do_ws && !p) {
658 lwsl_info("no URI\n");
659 cce = "HS: URI missing";
663 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP1_0);
664 wsi->u.http.connection_type = HTTP_CONNECTION_CLOSE;
667 cce = "HS: URI missing";
668 lwsl_info("no URI\n");
673 ah->http_response = n;
675 if (n == 301 || n == 302 || n == 303 || n == 307 || n == 308) {
676 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_LOCATION);
678 cce = "HS: Redirect code but no Location";
682 /* Relative reference absolute path */
685 #ifdef LWS_OPENSSL_SUPPORT
688 ads = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS);
690 path = p + 1; /* +1 as lws_client_reset expects leading / to be omitted */
692 /* Absolute (Full) URI */
693 else if (strchr(p, ':'))
695 if (lws_parse_uri(p, &prot, &ads, &port, &path)) {
696 cce = "HS: URI did not parse";
700 if (!strcmp(prot, "wss") || !strcmp(prot, "https"))
703 /* Relative reference relative path */
706 /* This doesn't try to calculate an absolute path, that will be left to the server */
707 #ifdef LWS_OPENSSL_SUPPORT
710 ads = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS);
712 path = new_path + 1; /* +1 as lws_client_reset expects leading / to be omitted */
713 strncpy(new_path, lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_URI), sizeof(new_path));
714 new_path[sizeof(new_path) - 1] = '\0';
715 q = strrchr(new_path, '/');
718 strncpy(q + 1, p, sizeof(new_path) - (q - new_path) - 1);
719 new_path[sizeof(new_path) - 1] = '\0';
727 #ifdef LWS_OPENSSL_SUPPORT
728 if (wsi->use_ssl && !ssl) {
729 cce = "HS: Redirect attempted SSL downgrade";
734 if (!lws_client_reset(&wsi, ssl, ads, port, path, ads)) {
735 /* there are two ways to fail out with NULL return...
736 * simple, early problem where the wsi is intact, or
737 * we went through with the reconnect attempt and the
738 * wsi is already closed. In the latter case, the wsi
739 * has beet set to NULL additionally.
741 lwsl_err("Redirect failed\n");
742 cce = "HS: Redirect failed";
752 if (n != 200 && n != 201 && n != 304 && n != 401) {
753 lwsl_notice("Connection failed with code %d\n", n);
754 cce = "HS: Server unrecognized response code";
758 #ifdef LWS_WITH_HTTP_PROXY
759 wsi->perform_rewrite = 0;
760 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
761 if (!strncmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE),
763 wsi->perform_rewrite = 1;
767 /* allocate the per-connection user memory (if any) */
768 if (lws_ensure_user_space(wsi)) {
769 lwsl_err("Problem allocating wsi user mem\n");
774 /* he may choose to send us stuff in chunked transfer-coding */
776 wsi->chunk_remaining = 0; /* ie, next thing is chunk size */
777 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_TRANSFER_ENCODING)) {
778 wsi->chunked = !strcmp(lws_hdr_simple_ptr(wsi,
779 WSI_TOKEN_HTTP_TRANSFER_ENCODING),
781 /* first thing is hex, after payload there is crlf */
782 wsi->chunk_parser = ELCP_HEX;
785 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
786 wsi->u.http.content_length =
787 atoll(lws_hdr_simple_ptr(wsi,
788 WSI_TOKEN_HTTP_CONTENT_LENGTH));
789 lwsl_notice("%s: incoming content length %llu\n", __func__,
790 (unsigned long long)wsi->u.http.content_length);
791 wsi->u.http.content_remain = wsi->u.http.content_length;
792 } else /* can't do 1.1 without a content length or chunked */
794 wsi->u.http.connection_type = HTTP_CONNECTION_CLOSE;
797 * we seem to be good to go, give client last chance to check
800 if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH,
801 wsi->user_space, NULL, 0)) {
803 cce = "HS: disallowed by client filter";
807 /* clear his proxy connection timeout */
808 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
810 wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
812 /* call him back to inform him he is up */
813 if (wsi->protocol->callback(wsi,
814 LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP,
815 wsi->user_space, NULL, 0)) {
816 cce = "HS: disallowed at ESTABLISHED";
820 /* free up his parsing allocations */
821 lws_header_table_detach(wsi, 0);
823 lwsl_notice("%s: client connection up\n", __func__);
828 if (lws_hdr_total_length(wsi, WSI_TOKEN_ACCEPT) == 0) {
829 lwsl_info("no ACCEPT\n");
830 cce = "HS: ACCEPT missing";
834 if (p && strncmp(p, "101", 3)) {
836 "lws_client_handshake: got bad HTTP response '%s'\n", p);
837 cce = "HS: ws upgrade response not 101";
841 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE);
843 lwsl_info("no UPGRADE\n");
844 cce = "HS: UPGRADE missing";
848 if (strcmp(p, "websocket")) {
850 "lws_client_handshake: got bad Upgrade header '%s'\n", p);
851 cce = "HS: Upgrade to something other than websocket";
855 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_CONNECTION);
857 lwsl_info("no Connection hdr\n");
858 cce = "HS: CONNECTION missing";
862 if (strcmp(p, "upgrade")) {
863 lwsl_warn("lws_client_int_s_hs: bad header %s\n", p);
864 cce = "HS: UPGRADE malformed";
868 pc = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);
870 lwsl_parser("lws_client_int_s_hs: no protocol list\n");
872 lwsl_parser("lws_client_int_s_hs: protocol list '%s'\n", pc);
875 * confirm the protocol the server wants to talk was in the list
876 * of protocols we offered
879 len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
881 lwsl_info("lws_client_int_s_hs: WSI_TOKEN_PROTOCOL is null\n");
883 * no protocol name to work from,
884 * default to first protocol
887 wsi->protocol = &wsi->vhost->protocols[0];
888 goto check_extensions;
891 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL);
894 while (pc && *pc && !okay) {
895 if (!strncmp(pc, p, len) &&
896 (pc[len] == ',' || pc[len] == '\0')) {
900 while (*pc && *pc++ != ',')
902 while (*pc && *pc == ' ')
907 lwsl_err("lws_client_int_s_hs: got bad protocol %s\n", p);
908 cce = "HS: PROTOCOL malformed";
913 * identify the selected protocol struct and set it
916 wsi->protocol = NULL;
917 while (wsi->vhost->protocols[n].callback && !wsi->protocol) {
918 if (strcmp(p, wsi->vhost->protocols[n].name) == 0) {
919 wsi->protocol = &wsi->vhost->protocols[n];
925 if (wsi->protocol == NULL) {
926 lwsl_err("lws_client_int_s_hs: fail protocol %s\n", p);
927 cce = "HS: Cannot match protocol";
933 * stitch protocol choice into the vh protocol linked list
934 * We always insert ourselves at the start of the list
939 //lwsl_err("%s: pre insert vhost start wsi %p, that wsi prev == %p\n",
941 // wsi->vhost->same_vh_protocol_list[n],
942 // wsi->same_vh_protocol_prev);
943 wsi->same_vh_protocol_prev = /* guy who points to us */
944 &wsi->vhost->same_vh_protocol_list[n];
945 wsi->same_vh_protocol_next = /* old first guy is our next */
946 wsi->vhost->same_vh_protocol_list[n];
947 /* we become the new first guy */
948 wsi->vhost->same_vh_protocol_list[n] = wsi;
950 if (wsi->same_vh_protocol_next)
951 /* old first guy points back to us now */
952 wsi->same_vh_protocol_next->same_vh_protocol_prev =
953 &wsi->same_vh_protocol_next;
955 #ifndef LWS_NO_EXTENSIONS
956 /* instantiate the accepted extensions */
958 if (!lws_hdr_total_length(wsi, WSI_TOKEN_EXTENSIONS)) {
959 lwsl_ext("no client extensions allowed by server\n");
964 * break down the list of server accepted extensions
965 * and go through matching them or identifying bogons
968 if (lws_hdr_copy(wsi, sb, context->pt_serv_buf_size, WSI_TOKEN_EXTENSIONS) < 0) {
969 lwsl_warn("ext list from server failed to copy\n");
970 cce = "HS: EXT: list too big";
980 if (*c && (*c != ',' && *c != '\t')) {
986 if (ignore || *c == ' ') {
992 if (n < sizeof(ext_name) - 1)
1006 /* check we actually support it */
1008 lwsl_notice("checking client ext %s\n", ext_name);
1011 ext = wsi->vhost->extensions;
1012 while (ext && ext->callback) {
1013 if (strcmp(ext_name, ext->name)) {
1019 lwsl_notice("instantiating client ext %s\n", ext_name);
1021 /* instantiate the extension on this conn */
1023 wsi->active_extensions[wsi->count_act_ext] = ext;
1025 /* allow him to construct his ext instance */
1027 if (ext->callback(lws_get_context(wsi), ext, wsi,
1028 LWS_EXT_CB_CLIENT_CONSTRUCT,
1029 (void *)&wsi->act_ext_user[wsi->count_act_ext],
1030 (void *)&opts, 0)) {
1031 lwsl_notice(" ext %s failed construction\n", ext_name);
1037 * allow the user code to override ext defaults if it
1041 if (user_callback_handle_rxflow(wsi->protocol->callback,
1042 wsi, LWS_CALLBACK_WS_EXT_DEFAULTS,
1043 (char *)ext->name, ext_name,
1044 sizeof(ext_name))) {
1045 cce = "HS: EXT: failed setting defaults";
1050 lws_ext_parse_options(ext, wsi, wsi->act_ext_user[
1051 wsi->count_act_ext], opts, ext_name,
1052 strlen(ext_name))) {
1053 lwsl_err("%s: unable to parse user defaults '%s'",
1054 __func__, ext_name);
1055 cce = "HS: EXT: failed parsing defaults";
1060 * give the extension the server options
1062 if (a && lws_ext_parse_options(ext, wsi,
1063 wsi->act_ext_user[wsi->count_act_ext],
1065 lwsl_err("%s: unable to parse remote def '%s'",
1067 cce = "HS: EXT: failed parsing options";
1071 if (ext->callback(lws_get_context(wsi), ext, wsi,
1072 LWS_EXT_CB_OPTION_CONFIRM,
1073 wsi->act_ext_user[wsi->count_act_ext],
1075 lwsl_err("%s: ext %s rejects server options %s",
1076 __func__, ext->name, a);
1077 cce = "HS: EXT: Rejects server options";
1081 wsi->count_act_ext++;
1087 lwsl_warn("Unknown ext '%s'!\n", ext_name);
1088 cce = "HS: EXT: unknown ext";
1100 * Confirm his accept token is the one we precomputed
1103 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_ACCEPT);
1104 if (strcmp(p, wsi->u.hdr.ah->initial_handshake_hash_base64)) {
1105 lwsl_warn("lws_client_int_s_hs: accept '%s' wrong vs '%s'\n", p,
1106 wsi->u.hdr.ah->initial_handshake_hash_base64);
1107 cce = "HS: Accept hash wrong";
1111 /* allocate the per-connection user memory (if any) */
1112 if (lws_ensure_user_space(wsi)) {
1113 lwsl_err("Problem allocating wsi user mem\n");
1119 * we seem to be good to go, give client last chance to check
1122 if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH,
1123 wsi->user_space, NULL, 0)) {
1124 cce = "HS: Rejected by filter cb";
1128 /* clear his proxy connection timeout */
1129 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1131 /* free up his parsing allocations */
1132 lws_header_table_detach(wsi, 0);
1134 lws_union_transition(wsi, LWSCM_WS_CLIENT);
1135 wsi->state = LWSS_ESTABLISHED;
1136 lws_restart_ws_ping_pong_timer(wsi);
1138 wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1141 * create the frame buffer for this connection according to the
1142 * size mentioned in the protocol definition. If 0 there, then
1143 * use a big default for compatibility
1145 n = wsi->protocol->rx_buffer_size;
1147 n = context->pt_serv_buf_size;
1149 wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
1150 if (!wsi->u.ws.rx_ubuf) {
1151 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
1155 wsi->u.ws.rx_ubuf_alloc = n;
1156 lwsl_info("Allocating client RX buffer %d\n", n);
1158 #if !defined(LWS_WITH_ESP32)
1159 if (setsockopt(wsi->desc.sockfd, SOL_SOCKET, SO_SNDBUF, (const char *)&n,
1161 lwsl_warn("Failed to set SNDBUF to %d", n);
1162 cce = "HS: SO_SNDBUF failed";
1167 lwsl_debug("handshake OK for protocol %s\n", wsi->protocol->name);
1169 /* call him back to inform him he is up */
1171 if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_ESTABLISHED,
1172 wsi->user_space, NULL, 0)) {
1173 cce = "HS: Rejected at CLIENT_ESTABLISHED";
1176 #ifndef LWS_NO_EXTENSIONS
1178 * inform all extensions, not just active ones since they
1181 ext = wsi->vhost->extensions;
1183 while (ext && ext->callback) {
1185 for (n = 0; n < wsi->count_act_ext; n++)
1186 if (wsi->active_extensions[n] == ext)
1187 v = wsi->act_ext_user[n];
1189 ext->callback(context, ext, wsi,
1190 LWS_EXT_CB_ANY_WSI_ESTABLISHED, v, NULL, 0);
1198 close_reason = LWS_CLOSE_STATUS_NOSTATUS;
1202 wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
1203 wsi->user_space, (void *)cce,
1204 (unsigned int)strlen(cce));
1205 wsi->already_did_cce = 1;
1207 lwsl_info("closing connection due to bail2 connection error\n");
1209 /* closing will free up his parsing allocations */
1210 lws_close_free_wsi(wsi, close_reason);
1217 lws_generate_client_handshake(struct lws *wsi, char *pkt)
1219 char buf[128], hash[20], key_b64[40], *p = pkt;
1220 struct lws_context *context = wsi->context;
1223 #ifndef LWS_NO_EXTENSIONS
1224 const struct lws_extension *ext;
1227 const char *pp = lws_hdr_simple_ptr(wsi,
1228 _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);
1230 meth = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_METHOD);
1238 if (!strcmp(meth, "RAW")) {
1239 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1240 lwsl_notice("client transition to raw\n");
1243 const struct lws_protocols *pr;
1245 pr = lws_vhost_name_to_protocol(wsi->vhost, pp);
1248 lwsl_err("protocol %s not enabled on vhost\n",
1253 lws_bind_protocol(wsi, pr);
1256 if ((wsi->protocol->callback)(wsi,
1257 LWS_CALLBACK_RAW_ADOPT,
1258 wsi->user_space, NULL, 0))
1261 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1262 lws_union_transition(wsi, LWSCM_RAW);
1263 lws_header_table_detach(wsi, 1);
1270 * create the random key
1272 n = lws_get_random(context, hash, 16);
1274 lwsl_err("Unable to read from random dev %s\n",
1275 SYSTEM_RANDOM_FILEPATH);
1276 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1280 lws_b64_encode_string(hash, 16, key_b64, sizeof(key_b64));
1284 * 04 example client handshake
1286 * GET /chat HTTP/1.1
1287 * Host: server.example.com
1288 * Upgrade: websocket
1289 * Connection: Upgrade
1290 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
1291 * Sec-WebSocket-Origin: http://example.com
1292 * Sec-WebSocket-Protocol: chat, superchat
1293 * Sec-WebSocket-Version: 4
1296 p += sprintf(p, "%s %s HTTP/1.1\x0d\x0a", meth,
1297 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_URI));
1299 p += sprintf(p, "Pragma: no-cache\x0d\x0a"
1300 "Cache-Control: no-cache\x0d\x0a");
1302 p += sprintf(p, "Host: %s\x0d\x0a",
1303 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_HOST));
1305 if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN)) {
1306 if (lws_check_opt(context->options, LWS_SERVER_OPTION_JUST_USE_RAW_ORIGIN))
1307 p += sprintf(p, "Origin: %s\x0d\x0a",
1308 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN));
1310 p += sprintf(p, "Origin: http://%s\x0d\x0a",
1311 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN));
1315 p += sprintf(p, "Upgrade: websocket\x0d\x0a"
1316 "Connection: Upgrade\x0d\x0a"
1317 "Sec-WebSocket-Key: ");
1319 p += strlen(key_b64);
1320 p += sprintf(p, "\x0d\x0a");
1321 if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS))
1322 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
1323 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS));
1325 /* tell the server what extensions we could support */
1327 #ifndef LWS_NO_EXTENSIONS
1328 ext = wsi->vhost->extensions;
1329 while (ext && ext->callback) {
1330 n = lws_ext_cb_all_exts(context, wsi,
1331 LWS_EXT_CB_CHECK_OK_TO_PROPOSE_EXTENSION,
1332 (char *)ext->name, 0);
1333 if (n) { /* an extension vetos us */
1334 lwsl_ext("ext %s vetoed\n", (char *)ext->name);
1338 n = wsi->vhost->protocols[0].callback(wsi,
1339 LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
1340 wsi->user_space, (char *)ext->name, 0);
1343 * zero return from callback means
1344 * go ahead and allow the extension,
1345 * it's what we get if the callback is
1359 p += sprintf(p, "Sec-WebSocket-Extensions: ");
1360 p += sprintf(p, "%s", ext->client_offer);
1366 p += sprintf(p, "\x0d\x0a");
1369 if (wsi->ietf_spec_revision)
1370 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
1371 wsi->ietf_spec_revision);
1373 /* prepare the expected server accept response */
1375 key_b64[39] = '\0'; /* enforce composed length below buf sizeof */
1376 n = sprintf(buf, "%s258EAFA5-E914-47DA-95CA-C5AB0DC85B11", key_b64);
1378 lws_SHA1((unsigned char *)buf, n, (unsigned char *)hash);
1380 lws_b64_encode_string(hash, 20,
1381 wsi->u.hdr.ah->initial_handshake_hash_base64,
1382 sizeof(wsi->u.hdr.ah->initial_handshake_hash_base64));
1385 /* give userland a chance to append, eg, cookies */
1387 wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
1388 wsi->user_space, &p, (pkt + context->pt_serv_buf_size) - p - 12);
1390 p += sprintf(p, "\x0d\x0a");