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 #if !defined(LWS_NO_CLIENT)
46 if (wsi->mode == LWSCM_WS_CLIENT)
47 m = lws_client_rx_sm(wsi, 0);
50 m = lws_rx_sm(wsi, 0);
55 /* account for what we're using in rxflow buffer */
56 if (wsi->rxflow_buffer)
59 if (lws_client_rx_sm(wsi, *(*buf)++)) {
60 lwsl_debug("client_rx_sm exited\n");
65 lwsl_debug("%s: finished with %ld\n", __func__, (long)len);
74 LWS_VISIBLE LWS_EXTERN void
75 lws_client_http_body_pending(struct lws *wsi, int something_left_to_send)
77 wsi->client_http_body_pending = !!something_left_to_send;
81 lws_client_socket_service(struct lws_context *context, struct lws *wsi,
82 struct lws_pollfd *pollfd)
84 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
85 char *p = (char *)&pt->serv_buf[0];
86 const char *cce = NULL;
90 #if defined(LWS_WITH_SOCKS5)
91 char conn_mode = 0, pending_timeout = 0;
96 case LWSCM_WSCL_WAITING_CONNECT:
99 * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE
100 * timeout protection set in client-handshake.c
103 if (!lws_client_connect_2(wsi)) {
105 lwsl_client("closed\n");
109 /* either still pending connection, or changed mode */
112 #if defined(LWS_WITH_SOCKS5)
113 /* SOCKS Greeting Reply */
114 case LWSCM_WSCL_WAITING_SOCKS_GREETING_REPLY:
116 /* handle proxy hung up on us */
118 if (pollfd->revents & LWS_POLLHUP) {
120 lwsl_warn("SOCKS connection %p (fd=%d) dead\n",
121 (void *)wsi, pollfd->fd);
123 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
127 n = recv(wsi->desc.sockfd, sb, context->pt_serv_buf_size, 0);
129 if (LWS_ERRNO == LWS_EAGAIN) {
130 lwsl_debug("SOCKS read returned EAGAIN..."
135 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
136 lwsl_err("ERROR reading from SOCKS socket\n");
140 /* processing greeting reply */
141 if (pt->serv_buf[0] == SOCKS_VERSION_5
142 && pt->serv_buf[1] == SOCKS_AUTH_NO_AUTH)
144 lwsl_client("%s\n", "SOCKS greeting reply received "
145 "- No Authentication Method");
146 socks_generate_msg(wsi, SOCKS_MSG_CONNECT, (size_t *)&len);
148 conn_mode = LWSCM_WSCL_WAITING_SOCKS_CONNECT_REPLY;
149 pending_timeout = PENDING_TIMEOUT_AWAITING_SOCKS_CONNECT_REPLY;
150 lwsl_client("%s\n", "Sending SOCKS connect command");
152 else if (pt->serv_buf[0] == SOCKS_VERSION_5
153 && pt->serv_buf[1] == SOCKS_AUTH_USERNAME_PASSWORD)
155 lwsl_client("%s\n", "SOCKS greeting reply received "
156 "- User Name Password Method");
157 socks_generate_msg(wsi, SOCKS_MSG_USERNAME_PASSWORD,
160 conn_mode = LWSCM_WSCL_WAITING_SOCKS_AUTH_REPLY;
161 pending_timeout = PENDING_TIMEOUT_AWAITING_SOCKS_AUTH_REPLY;
162 lwsl_client("%s\n", "Sending SOCKS user/password");
166 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
167 lwsl_err("ERROR SOCKS greeting reply failed, method "
168 "code: %d\n", pt->serv_buf[1]);
172 n = send(wsi->desc.sockfd, (char *)pt->serv_buf, len,
175 lwsl_debug("ERROR writing socks command to socks proxy "
180 lws_set_timeout(wsi, pending_timeout, AWAITING_TIMEOUT);
181 wsi->mode = conn_mode;
184 /* SOCKS auth Reply */
185 case LWSCM_WSCL_WAITING_SOCKS_AUTH_REPLY:
187 /* handle proxy hung up on us */
189 if (pollfd->revents & LWS_POLLHUP) {
191 lwsl_warn("SOCKS connection %p (fd=%d) dead\n",
192 (void *)wsi, pollfd->fd);
194 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
198 n = recv(wsi->desc.sockfd, sb, context->pt_serv_buf_size, 0);
200 if (LWS_ERRNO == LWS_EAGAIN) {
201 lwsl_debug("SOCKS read returned EAGAIN... "
206 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
207 lwsl_err("ERROR reading from socks socket\n");
211 /* processing auth reply */
212 if (pt->serv_buf[0] == SOCKS_SUBNEGOTIATION_VERSION_1
213 && pt->serv_buf[1] == SOCKS_SUBNEGOTIATION_STATUS_SUCCESS)
215 lwsl_client("%s\n", "SOCKS password reply recieved - "
217 socks_generate_msg(wsi, SOCKS_MSG_CONNECT, (size_t *)&len);
219 conn_mode = LWSCM_WSCL_WAITING_SOCKS_CONNECT_REPLY;
221 PENDING_TIMEOUT_AWAITING_SOCKS_CONNECT_REPLY;
222 lwsl_client("%s\n", "Sending SOCKS connect command");
226 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
227 lwsl_err("ERROR : SOCKS user/password reply failed, "
228 "error code: %d\n", pt->serv_buf[1]);
232 n = send(wsi->desc.sockfd, (char *)pt->serv_buf, len,
235 lwsl_debug("ERROR writing connect command to SOCKS "
240 lws_set_timeout(wsi, pending_timeout, AWAITING_TIMEOUT);
241 wsi->mode = conn_mode;
245 /* SOCKS connect command Reply */
246 case LWSCM_WSCL_WAITING_SOCKS_CONNECT_REPLY:
248 /* handle proxy hung up on us */
250 if (pollfd->revents & LWS_POLLHUP) {
252 lwsl_warn("SOCKS connection %p (fd=%d) dead\n",
253 (void *)wsi, pollfd->fd);
255 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
259 n = recv(wsi->desc.sockfd, sb, context->pt_serv_buf_size, 0);
261 if (LWS_ERRNO == LWS_EAGAIN) {
262 lwsl_debug("SOCKS read returned EAGAIN... "
267 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
268 lwsl_err("ERROR reading from socks socket\n");
272 /* processing connect reply */
273 if (pt->serv_buf[0] == SOCKS_VERSION_5
274 && pt->serv_buf[1] == SOCKS_REQUEST_REPLY_SUCCESS)
276 lwsl_client("%s\n", "SOCKS connect reply recieved - "
281 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
282 lwsl_err("ERROR SOCKS connect reply failed, error "
283 "code: %d\n", pt->serv_buf[1]);
287 /* free stash since we are done with it */
288 lws_free_set_NULL(wsi->u.hdr.stash);
290 if (lws_hdr_simple_create(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS,
291 wsi->vhost->socks_proxy_address))
293 wsi->c_port = wsi->vhost->socks_proxy_port;
295 /* clear his proxy connection timeout */
297 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
299 goto start_ws_hanshake;
301 case LWSCM_WSCL_WAITING_PROXY_REPLY:
303 /* handle proxy hung up on us */
305 if (pollfd->revents & LWS_POLLHUP) {
307 lwsl_warn("Proxy connection %p (fd=%d) dead\n",
308 (void *)wsi, pollfd->fd);
310 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
314 n = recv(wsi->desc.sockfd, sb, context->pt_serv_buf_size, 0);
316 if (LWS_ERRNO == LWS_EAGAIN) {
317 lwsl_debug("Proxy read returned EAGAIN... retrying\n");
321 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
322 lwsl_err("ERROR reading from proxy socket\n");
326 pt->serv_buf[13] = '\0';
327 if (strcmp(sb, "HTTP/1.0 200 ") &&
328 strcmp(sb, "HTTP/1.1 200 ")) {
329 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
330 lwsl_err("ERROR proxy: %s\n", sb);
334 /* clear his proxy connection timeout */
336 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
340 case LWSCM_WSCL_ISSUE_HANDSHAKE:
343 * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE
344 * timeout protection set in client-handshake.c
346 * take care of our lws_callback_on_writable
347 * happening at a time when there's no real connection yet
349 #if defined(LWS_WITH_SOCKS5)
352 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0))
355 #ifdef LWS_OPENSSL_SUPPORT
356 /* we can retry this... just cook the SSL BIO the first time */
358 if (wsi->use_ssl && !wsi->ssl) {
359 if (lws_ssl_client_bio_create(wsi))
364 n = lws_ssl_client_connect1(wsi);
368 cce = "lws_ssl_client_connect1 failed";
376 case LWSCM_WSCL_WAITING_SSL:
379 n = lws_ssl_client_connect2(wsi);
383 cce = "lws_ssl_client_connect2 failed";
390 wsi->mode = LWSCM_WSCL_ISSUE_HANDSHAKE2;
391 lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND,
392 context->timeout_secs);
396 case LWSCM_WSCL_ISSUE_HANDSHAKE2:
397 p = lws_generate_client_handshake(wsi, p);
399 if (wsi->mode == LWSCM_RAW)
402 lwsl_err("Failed to generate handshake for client\n");
403 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
407 /* send our request to the server */
409 lws_latency_pre(context, wsi);
411 n = lws_ssl_capable_write(wsi, (unsigned char *)sb, p - sb);
412 lws_latency(context, wsi, "send lws_issue_raw", n,
415 case LWS_SSL_CAPABLE_ERROR:
416 lwsl_debug("ERROR writing to client socket\n");
417 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
419 case LWS_SSL_CAPABLE_MORE_SERVICE:
420 lws_callback_on_writable(wsi);
424 if (wsi->client_http_body_pending) {
425 wsi->mode = LWSCM_WSCL_ISSUE_HTTP_BODY;
426 lws_set_timeout(wsi, PENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD,
427 context->timeout_secs);
428 /* user code must ask for writable callback */
432 goto client_http_body_sent;
434 case LWSCM_WSCL_ISSUE_HTTP_BODY:
435 if (wsi->client_http_body_pending) {
436 lws_set_timeout(wsi, PENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD,
437 context->timeout_secs);
438 /* user code must ask for writable callback */
441 client_http_body_sent:
442 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
443 wsi->u.hdr.lextable_pos = 0;
444 wsi->mode = LWSCM_WSCL_WAITING_SERVER_REPLY;
445 lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE,
446 context->timeout_secs);
449 case LWSCM_WSCL_WAITING_SERVER_REPLY:
451 /* handle server hung up on us */
453 if (pollfd->revents & LWS_POLLHUP) {
455 lwsl_debug("Server connection %p (fd=%d) dead\n",
456 (void *)wsi, pollfd->fd);
457 cce = "Peer hung up";
461 if (!(pollfd->revents & LWS_POLLIN))
464 /* interpret the server response */
467 * HTTP/1.1 101 Switching Protocols
469 * Connection: Upgrade
470 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
471 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
472 * Sec-WebSocket-Protocol: chat
476 * we have to take some care here to only take from the
477 * socket bytewise. The browser may (and has been seen to
478 * in the case that onopen() performs websocket traffic)
479 * coalesce both handshake response and websocket traffic
480 * in one packet, since at that point the connection is
481 * definitively ready from browser pov.
484 while (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE &&
486 n = lws_ssl_capable_read(wsi, &c, 1);
487 lws_latency(context, wsi, "send lws_issue_raw", n,
491 case LWS_SSL_CAPABLE_ERROR:
494 case LWS_SSL_CAPABLE_MORE_SERVICE:
498 if (lws_parse(wsi, c)) {
499 lwsl_warn("problems parsing header\n");
505 * hs may also be coming in multiple packets, there is a 5-sec
506 * libwebsocket timeout still active here too, so if parsing did
507 * not complete just wait for next packet coming in this state
510 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
514 * otherwise deal with the handshake. If there's any
515 * packet traffic already arrived we'll trigger poll() again
516 * right away and deal with it that way
519 return lws_client_interpret_server_handshake(wsi);
522 lwsl_info("closing conn at LWS_CONNMODE...SERVER_REPLY\n");
524 lwsl_info("reason: %s\n", cce);
525 wsi->protocol->callback(wsi,
526 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
527 wsi->user_space, (void *)cce, cce ? strlen(cce) : 0);
528 wsi->already_did_cce = 1;
529 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
532 case LWSCM_WSCL_WAITING_EXTENSION_CONNECT:
533 lwsl_ext("LWSCM_WSCL_WAITING_EXTENSION_CONNECT\n");
536 case LWSCM_WSCL_PENDING_CANDIDATE_CHILD:
537 lwsl_ext("LWSCM_WSCL_PENDING_CANDIDATE_CHILD\n");
547 * In-place str to lower case
554 #ifdef LWS_PLAT_OPTEE
555 int tolower_optee(int c);
556 *s = tolower_optee((int)*s);
558 *s = tolower((int)*s);
564 int LWS_WARN_UNUSED_RESULT
565 lws_http_transaction_completed_client(struct lws *wsi)
567 lwsl_debug("%s: wsi %p\n", __func__, wsi);
568 /* if we can't go back to accept new headers, drop the connection */
569 if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
570 lwsl_info("%s: %p: close connection\n", __func__, wsi);
574 /* we don't support chained client connections yet */
577 /* otherwise set ourselves up ready to go again */
578 wsi->state = LWSS_CLIENT_HTTP_ESTABLISHED;
579 wsi->mode = LWSCM_HTTP_CLIENT_ACCEPTED;
580 wsi->u.http.content_length = 0;
581 wsi->hdr_parsing_completed = 0;
583 /* He asked for it to stay alive indefinitely */
584 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
587 * As client, nothing new is going to come until we ask for it
588 * we can drop the ah, if any
591 lws_header_table_force_to_detachable_state(wsi);
592 lws_header_table_detach(wsi, 0);
595 /* If we're (re)starting on headers, need other implied init */
596 wsi->u.hdr.ues = URIES_IDLE;
598 lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
604 LWS_VISIBLE LWS_EXTERN unsigned int
605 lws_http_client_http_response(struct lws *wsi)
610 return wsi->u.http.ah->http_response;
614 lws_client_interpret_server_handshake(struct lws *wsi)
616 int n, len, okay = 0, port = 0, ssl = 0;
617 int close_reason = LWS_CLOSE_STATUS_PROTOCOL_ERR;
618 struct lws_context *context = wsi->context;
619 const char *pc, *prot, *ads = NULL, *path, *cce = NULL;
620 struct allocated_headers *ah = NULL;
623 #ifndef LWS_NO_EXTENSIONS
624 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
625 char *sb = (char *)&pt->serv_buf[0];
626 const struct lws_ext_options *opts;
627 const struct lws_extension *ext;
634 if (wsi->u.hdr.stash)
635 lws_free_set_NULL(wsi->u.hdr.stash);
639 /* we are being an http client...
641 lws_union_transition(wsi, LWSCM_HTTP_CLIENT_ACCEPTED);
642 wsi->state = LWSS_CLIENT_HTTP_ESTABLISHED;
644 ah->http_response = 0;
648 * well, what the server sent looked reasonable for syntax.
649 * Now let's confirm it sent all the necessary headers
651 * http (non-ws) client will expect something like this
654 * server:.libwebsockets
655 * content-type:.text/html
656 * content-length:.17703
657 * set-cookie:.test=LWS_1456736240_336776_COOKIE;Max-Age=360000
663 wsi->u.http.connection_type = HTTP_CONNECTION_KEEP_ALIVE;
664 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP);
665 if (wsi->do_ws && !p) {
666 lwsl_info("no URI\n");
667 cce = "HS: URI missing";
671 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP1_0);
672 wsi->u.http.connection_type = HTTP_CONNECTION_CLOSE;
675 cce = "HS: URI missing";
676 lwsl_info("no URI\n");
681 ah->http_response = n;
683 if (n == 301 || n == 302 || n == 303 || n == 307 || n == 308) {
684 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_LOCATION);
686 cce = "HS: Redirect code but no Location";
690 /* Relative reference absolute path */
693 #ifdef LWS_OPENSSL_SUPPORT
696 ads = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS);
698 path = p + 1; /* +1 as lws_client_reset expects leading / to be omitted */
700 /* Absolute (Full) URI */
701 else if (strchr(p, ':'))
703 if (lws_parse_uri(p, &prot, &ads, &port, &path)) {
704 cce = "HS: URI did not parse";
708 if (!strcmp(prot, "wss") || !strcmp(prot, "https"))
711 /* Relative reference relative path */
714 /* This doesn't try to calculate an absolute path, that will be left to the server */
715 #ifdef LWS_OPENSSL_SUPPORT
718 ads = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS);
720 path = new_path + 1; /* +1 as lws_client_reset expects leading / to be omitted */
721 strncpy(new_path, lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_URI), sizeof(new_path));
722 new_path[sizeof(new_path) - 1] = '\0';
723 q = strrchr(new_path, '/');
726 strncpy(q + 1, p, sizeof(new_path) - (q - new_path) - 1);
727 new_path[sizeof(new_path) - 1] = '\0';
735 #ifdef LWS_OPENSSL_SUPPORT
736 if (wsi->use_ssl && !ssl) {
737 cce = "HS: Redirect attempted SSL downgrade";
742 if (!lws_client_reset(&wsi, ssl, ads, port, path, ads)) {
743 /* there are two ways to fail out with NULL return...
744 * simple, early problem where the wsi is intact, or
745 * we went through with the reconnect attempt and the
746 * wsi is already closed. In the latter case, the wsi
747 * has beet set to NULL additionally.
749 lwsl_err("Redirect failed\n");
750 cce = "HS: Redirect failed";
760 if (n != 200 && n != 201 && n != 304 && n != 401) {
761 lwsl_notice("Connection failed with code %d\n", n);
762 cce = "HS: Server unrecognized response code";
766 #ifdef LWS_WITH_HTTP_PROXY
767 wsi->perform_rewrite = 0;
768 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
769 if (!strncmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE),
771 wsi->perform_rewrite = 1;
775 /* allocate the per-connection user memory (if any) */
776 if (lws_ensure_user_space(wsi)) {
777 lwsl_err("Problem allocating wsi user mem\n");
782 /* he may choose to send us stuff in chunked transfer-coding */
784 wsi->chunk_remaining = 0; /* ie, next thing is chunk size */
785 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_TRANSFER_ENCODING)) {
786 wsi->chunked = !strcmp(lws_hdr_simple_ptr(wsi,
787 WSI_TOKEN_HTTP_TRANSFER_ENCODING),
789 /* first thing is hex, after payload there is crlf */
790 wsi->chunk_parser = ELCP_HEX;
793 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
794 wsi->u.http.content_length =
795 atoll(lws_hdr_simple_ptr(wsi,
796 WSI_TOKEN_HTTP_CONTENT_LENGTH));
797 lwsl_notice("%s: incoming content length %llu\n", __func__,
798 (unsigned long long)wsi->u.http.content_length);
799 wsi->u.http.content_remain = wsi->u.http.content_length;
800 } else /* can't do 1.1 without a content length or chunked */
802 wsi->u.http.connection_type = HTTP_CONNECTION_CLOSE;
805 * we seem to be good to go, give client last chance to check
808 if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH,
809 wsi->user_space, NULL, 0)) {
811 cce = "HS: disallowed by client filter";
815 /* clear his proxy connection timeout */
816 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
818 wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
820 /* call him back to inform him he is up */
821 if (wsi->protocol->callback(wsi,
822 LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP,
823 wsi->user_space, NULL, 0)) {
824 cce = "HS: disallowed at ESTABLISHED";
828 /* free up his parsing allocations */
829 lws_header_table_detach(wsi, 0);
831 lwsl_notice("%s: client connection up\n", __func__);
836 if (lws_hdr_total_length(wsi, WSI_TOKEN_ACCEPT) == 0) {
837 lwsl_info("no ACCEPT\n");
838 cce = "HS: ACCEPT missing";
842 if (p && strncmp(p, "101", 3)) {
844 "lws_client_handshake: got bad HTTP response '%s'\n", p);
845 cce = "HS: ws upgrade response not 101";
849 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE);
851 lwsl_info("no UPGRADE\n");
852 cce = "HS: UPGRADE missing";
856 if (strcmp(p, "websocket")) {
858 "lws_client_handshake: got bad Upgrade header '%s'\n", p);
859 cce = "HS: Upgrade to something other than websocket";
863 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_CONNECTION);
865 lwsl_info("no Connection hdr\n");
866 cce = "HS: CONNECTION missing";
870 if (strcmp(p, "upgrade")) {
871 lwsl_warn("lws_client_int_s_hs: bad header %s\n", p);
872 cce = "HS: UPGRADE malformed";
876 pc = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);
878 lwsl_parser("lws_client_int_s_hs: no protocol list\n");
880 lwsl_parser("lws_client_int_s_hs: protocol list '%s'\n", pc);
883 * confirm the protocol the server wants to talk was in the list
884 * of protocols we offered
887 len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
889 lwsl_info("lws_client_int_s_hs: WSI_TOKEN_PROTOCOL is null\n");
891 * no protocol name to work from,
892 * default to first protocol
895 wsi->protocol = &wsi->vhost->protocols[0];
896 goto check_extensions;
899 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL);
902 while (pc && *pc && !okay) {
903 if (!strncmp(pc, p, len) &&
904 (pc[len] == ',' || pc[len] == '\0')) {
908 while (*pc && *pc++ != ',')
910 while (*pc && *pc == ' ')
915 lwsl_err("lws_client_int_s_hs: got bad protocol %s\n", p);
916 cce = "HS: PROTOCOL malformed";
921 * identify the selected protocol struct and set it
924 wsi->protocol = NULL;
925 while (wsi->vhost->protocols[n].callback && !wsi->protocol) {
926 if (strcmp(p, wsi->vhost->protocols[n].name) == 0) {
927 wsi->protocol = &wsi->vhost->protocols[n];
933 if (wsi->protocol == NULL) {
934 lwsl_err("lws_client_int_s_hs: fail protocol %s\n", p);
935 cce = "HS: Cannot match protocol";
941 * stitch protocol choice into the vh protocol linked list
942 * We always insert ourselves at the start of the list
947 //lwsl_err("%s: pre insert vhost start wsi %p, that wsi prev == %p\n",
949 // wsi->vhost->same_vh_protocol_list[n],
950 // wsi->same_vh_protocol_prev);
951 wsi->same_vh_protocol_prev = /* guy who points to us */
952 &wsi->vhost->same_vh_protocol_list[n];
953 wsi->same_vh_protocol_next = /* old first guy is our next */
954 wsi->vhost->same_vh_protocol_list[n];
955 /* we become the new first guy */
956 wsi->vhost->same_vh_protocol_list[n] = wsi;
958 if (wsi->same_vh_protocol_next)
959 /* old first guy points back to us now */
960 wsi->same_vh_protocol_next->same_vh_protocol_prev =
961 &wsi->same_vh_protocol_next;
963 #ifndef LWS_NO_EXTENSIONS
964 /* instantiate the accepted extensions */
966 if (!lws_hdr_total_length(wsi, WSI_TOKEN_EXTENSIONS)) {
967 lwsl_ext("no client extensions allowed by server\n");
972 * break down the list of server accepted extensions
973 * and go through matching them or identifying bogons
976 if (lws_hdr_copy(wsi, sb, context->pt_serv_buf_size, WSI_TOKEN_EXTENSIONS) < 0) {
977 lwsl_warn("ext list from server failed to copy\n");
978 cce = "HS: EXT: list too big";
988 if (*c && (*c != ',' && *c != '\t')) {
994 if (ignore || *c == ' ') {
1000 if (n < sizeof(ext_name) - 1)
1014 /* check we actually support it */
1016 lwsl_notice("checking client ext %s\n", ext_name);
1019 ext = wsi->vhost->extensions;
1020 while (ext && ext->callback) {
1021 if (strcmp(ext_name, ext->name)) {
1027 lwsl_notice("instantiating client ext %s\n", ext_name);
1029 /* instantiate the extension on this conn */
1031 wsi->active_extensions[wsi->count_act_ext] = ext;
1033 /* allow him to construct his ext instance */
1035 if (ext->callback(lws_get_context(wsi), ext, wsi,
1036 LWS_EXT_CB_CLIENT_CONSTRUCT,
1037 (void *)&wsi->act_ext_user[wsi->count_act_ext],
1038 (void *)&opts, 0)) {
1039 lwsl_notice(" ext %s failed construction\n", ext_name);
1045 * allow the user code to override ext defaults if it
1049 if (user_callback_handle_rxflow(wsi->protocol->callback,
1050 wsi, LWS_CALLBACK_WS_EXT_DEFAULTS,
1051 (char *)ext->name, ext_name,
1052 sizeof(ext_name))) {
1053 cce = "HS: EXT: failed setting defaults";
1058 lws_ext_parse_options(ext, wsi, wsi->act_ext_user[
1059 wsi->count_act_ext], opts, ext_name,
1060 strlen(ext_name))) {
1061 lwsl_err("%s: unable to parse user defaults '%s'",
1062 __func__, ext_name);
1063 cce = "HS: EXT: failed parsing defaults";
1068 * give the extension the server options
1070 if (a && lws_ext_parse_options(ext, wsi,
1071 wsi->act_ext_user[wsi->count_act_ext],
1073 lwsl_err("%s: unable to parse remote def '%s'",
1075 cce = "HS: EXT: failed parsing options";
1079 if (ext->callback(lws_get_context(wsi), ext, wsi,
1080 LWS_EXT_CB_OPTION_CONFIRM,
1081 wsi->act_ext_user[wsi->count_act_ext],
1083 lwsl_err("%s: ext %s rejects server options %s",
1084 __func__, ext->name, a);
1085 cce = "HS: EXT: Rejects server options";
1089 wsi->count_act_ext++;
1095 lwsl_warn("Unknown ext '%s'!\n", ext_name);
1096 cce = "HS: EXT: unknown ext";
1108 * Confirm his accept token is the one we precomputed
1111 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_ACCEPT);
1112 if (strcmp(p, wsi->u.hdr.ah->initial_handshake_hash_base64)) {
1113 lwsl_warn("lws_client_int_s_hs: accept '%s' wrong vs '%s'\n", p,
1114 wsi->u.hdr.ah->initial_handshake_hash_base64);
1115 cce = "HS: Accept hash wrong";
1119 /* allocate the per-connection user memory (if any) */
1120 if (lws_ensure_user_space(wsi)) {
1121 lwsl_err("Problem allocating wsi user mem\n");
1127 * we seem to be good to go, give client last chance to check
1130 if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH,
1131 wsi->user_space, NULL, 0)) {
1132 cce = "HS: Rejected by filter cb";
1136 /* clear his proxy connection timeout */
1137 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1139 /* free up his parsing allocations */
1140 lws_header_table_detach(wsi, 0);
1142 lws_union_transition(wsi, LWSCM_WS_CLIENT);
1143 wsi->state = LWSS_ESTABLISHED;
1144 lws_restart_ws_ping_pong_timer(wsi);
1146 wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1149 * create the frame buffer for this connection according to the
1150 * size mentioned in the protocol definition. If 0 there, then
1151 * use a big default for compatibility
1153 n = wsi->protocol->rx_buffer_size;
1155 n = context->pt_serv_buf_size;
1157 wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
1158 if (!wsi->u.ws.rx_ubuf) {
1159 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
1163 wsi->u.ws.rx_ubuf_alloc = n;
1164 lwsl_info("Allocating client RX buffer %d\n", n);
1166 #if !defined(LWS_WITH_ESP32)
1167 if (setsockopt(wsi->desc.sockfd, SOL_SOCKET, SO_SNDBUF, (const char *)&n,
1169 lwsl_warn("Failed to set SNDBUF to %d", n);
1170 cce = "HS: SO_SNDBUF failed";
1175 lwsl_debug("handshake OK for protocol %s\n", wsi->protocol->name);
1177 /* call him back to inform him he is up */
1179 if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_ESTABLISHED,
1180 wsi->user_space, NULL, 0)) {
1181 cce = "HS: Rejected at CLIENT_ESTABLISHED";
1184 #ifndef LWS_NO_EXTENSIONS
1186 * inform all extensions, not just active ones since they
1189 ext = wsi->vhost->extensions;
1191 while (ext && ext->callback) {
1193 for (n = 0; n < wsi->count_act_ext; n++)
1194 if (wsi->active_extensions[n] == ext)
1195 v = wsi->act_ext_user[n];
1197 ext->callback(context, ext, wsi,
1198 LWS_EXT_CB_ANY_WSI_ESTABLISHED, v, NULL, 0);
1206 close_reason = LWS_CLOSE_STATUS_NOSTATUS;
1210 wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
1211 wsi->user_space, (void *)cce,
1212 (unsigned int)strlen(cce));
1213 wsi->already_did_cce = 1;
1215 lwsl_info("closing connection due to bail2 connection error\n");
1217 /* closing will free up his parsing allocations */
1218 lws_close_free_wsi(wsi, close_reason);
1225 lws_generate_client_handshake(struct lws *wsi, char *pkt)
1227 char buf[128], hash[20], key_b64[40], *p = pkt;
1228 struct lws_context *context = wsi->context;
1231 #ifndef LWS_NO_EXTENSIONS
1232 const struct lws_extension *ext;
1235 const char *pp = lws_hdr_simple_ptr(wsi,
1236 _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);
1238 meth = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_METHOD);
1246 if (!strcmp(meth, "RAW")) {
1247 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1248 lwsl_notice("client transition to raw\n");
1251 const struct lws_protocols *pr;
1253 pr = lws_vhost_name_to_protocol(wsi->vhost, pp);
1256 lwsl_err("protocol %s not enabled on vhost\n",
1261 lws_bind_protocol(wsi, pr);
1264 if ((wsi->protocol->callback)(wsi,
1265 LWS_CALLBACK_RAW_ADOPT,
1266 wsi->user_space, NULL, 0))
1269 lws_header_table_force_to_detachable_state(wsi);
1270 lws_union_transition(wsi, LWSCM_RAW);
1271 lws_header_table_detach(wsi, 1);
1278 * create the random key
1280 n = lws_get_random(context, hash, 16);
1282 lwsl_err("Unable to read from random dev %s\n",
1283 SYSTEM_RANDOM_FILEPATH);
1284 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1288 lws_b64_encode_string(hash, 16, key_b64, sizeof(key_b64));
1292 * 04 example client handshake
1294 * GET /chat HTTP/1.1
1295 * Host: server.example.com
1296 * Upgrade: websocket
1297 * Connection: Upgrade
1298 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
1299 * Sec-WebSocket-Origin: http://example.com
1300 * Sec-WebSocket-Protocol: chat, superchat
1301 * Sec-WebSocket-Version: 4
1304 p += sprintf(p, "%s %s HTTP/1.1\x0d\x0a", meth,
1305 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_URI));
1307 p += sprintf(p, "Pragma: no-cache\x0d\x0a"
1308 "Cache-Control: no-cache\x0d\x0a");
1310 p += sprintf(p, "Host: %s\x0d\x0a",
1311 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_HOST));
1313 if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN)) {
1314 if (lws_check_opt(context->options, LWS_SERVER_OPTION_JUST_USE_RAW_ORIGIN))
1315 p += sprintf(p, "Origin: %s\x0d\x0a",
1316 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN));
1318 p += sprintf(p, "Origin: http://%s\x0d\x0a",
1319 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN));
1323 p += sprintf(p, "Upgrade: websocket\x0d\x0a"
1324 "Connection: Upgrade\x0d\x0a"
1325 "Sec-WebSocket-Key: ");
1327 p += strlen(key_b64);
1328 p += sprintf(p, "\x0d\x0a");
1329 if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS))
1330 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
1331 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS));
1333 /* tell the server what extensions we could support */
1335 #ifndef LWS_NO_EXTENSIONS
1336 ext = wsi->vhost->extensions;
1337 while (ext && ext->callback) {
1338 n = lws_ext_cb_all_exts(context, wsi,
1339 LWS_EXT_CB_CHECK_OK_TO_PROPOSE_EXTENSION,
1340 (char *)ext->name, 0);
1341 if (n) { /* an extension vetos us */
1342 lwsl_ext("ext %s vetoed\n", (char *)ext->name);
1346 n = wsi->vhost->protocols[0].callback(wsi,
1347 LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
1348 wsi->user_space, (char *)ext->name, 0);
1351 * zero return from callback means
1352 * go ahead and allow the extension,
1353 * it's what we get if the callback is
1367 p += sprintf(p, "Sec-WebSocket-Extensions: ");
1368 p += sprintf(p, "%s", ext->client_offer);
1374 p += sprintf(p, "\x0d\x0a");
1377 if (wsi->ietf_spec_revision)
1378 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
1379 wsi->ietf_spec_revision);
1381 /* prepare the expected server accept response */
1383 key_b64[39] = '\0'; /* enforce composed length below buf sizeof */
1384 n = sprintf(buf, "%s258EAFA5-E914-47DA-95CA-C5AB0DC85B11", key_b64);
1386 lws_SHA1((unsigned char *)buf, n, (unsigned char *)hash);
1388 lws_b64_encode_string(hash, 20,
1389 wsi->u.hdr.ah->initial_handshake_hash_base64,
1390 sizeof(wsi->u.hdr.ah->initial_handshake_hash_base64));
1393 /* give userland a chance to append, eg, cookies */
1395 wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
1396 wsi->user_space, &p, (pkt + context->pt_serv_buf_size) - p - 12);
1398 p += sprintf(p, "\x0d\x0a");