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;
88 case LWSCM_WSCL_WAITING_CONNECT:
91 * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE
92 * timeout protection set in client-handshake.c
95 if (!lws_client_connect_2(wsi)) {
97 lwsl_client("closed\n");
101 /* either still pending connection, or changed mode */
104 case LWSCM_WSCL_WAITING_PROXY_REPLY:
106 /* handle proxy hung up on us */
108 if (pollfd->revents & LWS_POLLHUP) {
110 lwsl_warn("Proxy connection %p (fd=%d) dead\n",
111 (void *)wsi, pollfd->fd);
113 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
117 n = recv(wsi->desc.sockfd, sb, context->pt_serv_buf_size, 0);
119 if (LWS_ERRNO == LWS_EAGAIN) {
120 lwsl_debug("Proxy read returned EAGAIN... retrying\n");
124 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
125 lwsl_err("ERROR reading from proxy socket\n");
129 pt->serv_buf[13] = '\0';
130 if (strcmp(sb, "HTTP/1.0 200 ") &&
131 strcmp(sb, "HTTP/1.1 200 ")) {
132 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
133 lwsl_err("ERROR proxy: %s\n", sb);
137 /* clear his proxy connection timeout */
139 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
143 case LWSCM_WSCL_ISSUE_HANDSHAKE:
146 * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE
147 * timeout protection set in client-handshake.c
149 * take care of our lws_callback_on_writable
150 * happening at a time when there's no real connection yet
152 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0))
155 #ifdef LWS_OPENSSL_SUPPORT
156 /* we can retry this... just cook the SSL BIO the first time */
158 if (wsi->use_ssl && !wsi->ssl) {
159 if (lws_ssl_client_bio_create(wsi))
164 n = lws_ssl_client_connect1(wsi);
168 cce = "lws_ssl_client_connect1 failed";
176 case LWSCM_WSCL_WAITING_SSL:
179 n = lws_ssl_client_connect2(wsi);
183 cce = "lws_ssl_client_connect2 failed";
190 wsi->mode = LWSCM_WSCL_ISSUE_HANDSHAKE2;
191 lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND,
192 context->timeout_secs);
196 case LWSCM_WSCL_ISSUE_HANDSHAKE2:
197 p = lws_generate_client_handshake(wsi, p);
199 if (wsi->mode == LWSCM_RAW)
202 lwsl_err("Failed to generate handshake for client\n");
203 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
207 /* send our request to the server */
209 lws_latency_pre(context, wsi);
211 n = lws_ssl_capable_write(wsi, (unsigned char *)sb, p - sb);
212 lws_latency(context, wsi, "send lws_issue_raw", n,
215 case LWS_SSL_CAPABLE_ERROR:
216 lwsl_debug("ERROR writing to client socket\n");
217 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
219 case LWS_SSL_CAPABLE_MORE_SERVICE:
220 lws_callback_on_writable(wsi);
224 if (wsi->client_http_body_pending) {
225 wsi->mode = LWSCM_WSCL_ISSUE_HTTP_BODY;
226 lws_set_timeout(wsi, PENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD,
227 context->timeout_secs);
228 /* user code must ask for writable callback */
232 goto client_http_body_sent;
234 case LWSCM_WSCL_ISSUE_HTTP_BODY:
235 if (wsi->client_http_body_pending) {
236 lws_set_timeout(wsi, PENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD,
237 context->timeout_secs);
238 /* user code must ask for writable callback */
241 client_http_body_sent:
242 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
243 wsi->u.hdr.lextable_pos = 0;
244 wsi->mode = LWSCM_WSCL_WAITING_SERVER_REPLY;
245 lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE,
246 context->timeout_secs);
249 case LWSCM_WSCL_WAITING_SERVER_REPLY:
251 /* handle server hung up on us */
253 if (pollfd->revents & LWS_POLLHUP) {
255 lwsl_debug("Server connection %p (fd=%d) dead\n",
256 (void *)wsi, pollfd->fd);
257 cce = "Peer hung up";
261 if (!(pollfd->revents & LWS_POLLIN))
264 /* interpret the server response */
267 * HTTP/1.1 101 Switching Protocols
269 * Connection: Upgrade
270 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
271 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
272 * Sec-WebSocket-Protocol: chat
276 * we have to take some care here to only take from the
277 * socket bytewise. The browser may (and has been seen to
278 * in the case that onopen() performs websocket traffic)
279 * coalesce both handshake response and websocket traffic
280 * in one packet, since at that point the connection is
281 * definitively ready from browser pov.
284 while (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE &&
286 n = lws_ssl_capable_read(wsi, &c, 1);
287 lws_latency(context, wsi, "send lws_issue_raw", n,
291 case LWS_SSL_CAPABLE_ERROR:
294 case LWS_SSL_CAPABLE_MORE_SERVICE:
298 if (lws_parse(wsi, c)) {
299 lwsl_warn("problems parsing header\n");
305 * hs may also be coming in multiple packets, there is a 5-sec
306 * libwebsocket timeout still active here too, so if parsing did
307 * not complete just wait for next packet coming in this state
310 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
314 * otherwise deal with the handshake. If there's any
315 * packet traffic already arrived we'll trigger poll() again
316 * right away and deal with it that way
319 return lws_client_interpret_server_handshake(wsi);
322 lwsl_info("closing conn at LWS_CONNMODE...SERVER_REPLY\n");
324 lwsl_info("reason: %s\n", cce);
325 wsi->protocol->callback(wsi,
326 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
327 wsi->user_space, (void *)cce, cce ? strlen(cce) : 0);
328 wsi->already_did_cce = 1;
329 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
332 case LWSCM_WSCL_WAITING_EXTENSION_CONNECT:
333 lwsl_ext("LWSCM_WSCL_WAITING_EXTENSION_CONNECT\n");
336 case LWSCM_WSCL_PENDING_CANDIDATE_CHILD:
337 lwsl_ext("LWSCM_WSCL_PENDING_CANDIDATE_CHILD\n");
347 * In-place str to lower case
354 #ifdef LWS_PLAT_OPTEE
355 int tolower_optee(int c);
356 *s = tolower_optee((int)*s);
358 *s = tolower((int)*s);
364 int LWS_WARN_UNUSED_RESULT
365 lws_http_transaction_completed_client(struct lws *wsi)
367 lwsl_debug("%s: wsi %p\n", __func__, wsi);
368 /* if we can't go back to accept new headers, drop the connection */
369 if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
370 lwsl_info("%s: %p: close connection\n", __func__, wsi);
374 /* we don't support chained client connections yet */
377 /* otherwise set ourselves up ready to go again */
378 wsi->state = LWSS_CLIENT_HTTP_ESTABLISHED;
379 wsi->mode = LWSCM_HTTP_CLIENT_ACCEPTED;
380 wsi->u.http.content_length = 0;
381 wsi->hdr_parsing_completed = 0;
383 /* He asked for it to stay alive indefinitely */
384 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
387 * As client, nothing new is going to come until we ask for it
388 * we can drop the ah, if any
391 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
392 lws_header_table_detach(wsi, 0);
395 /* If we're (re)starting on headers, need other implied init */
396 wsi->u.hdr.ues = URIES_IDLE;
398 lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
403 LWS_VISIBLE LWS_EXTERN unsigned int
404 lws_http_client_http_response(struct lws *wsi)
409 return wsi->u.http.ah->http_response;
413 lws_client_interpret_server_handshake(struct lws *wsi)
415 int n, len, okay = 0, port = 0, ssl = 0;
416 int close_reason = LWS_CLOSE_STATUS_PROTOCOL_ERR;
417 struct lws_context *context = wsi->context;
418 const char *pc, *prot, *ads = NULL, *path, *cce = NULL;
419 struct allocated_headers *ah = NULL;
422 #ifndef LWS_NO_EXTENSIONS
423 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
424 char *sb = (char *)&pt->serv_buf[0];
425 const struct lws_ext_options *opts;
426 const struct lws_extension *ext;
436 /* we are being an http client...
438 lws_union_transition(wsi, LWSCM_HTTP_CLIENT_ACCEPTED);
439 wsi->state = LWSS_CLIENT_HTTP_ESTABLISHED;
441 ah->http_response = 0;
445 * well, what the server sent looked reasonable for syntax.
446 * Now let's confirm it sent all the necessary headers
448 * http (non-ws) client will expect something like this
451 * server:.libwebsockets
452 * content-type:.text/html
453 * content-length:.17703
454 * set-cookie:.test=LWS_1456736240_336776_COOKIE;Max-Age=360000
460 wsi->u.http.connection_type = HTTP_CONNECTION_KEEP_ALIVE;
461 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP);
462 if (wsi->do_ws && !p) {
463 lwsl_info("no URI\n");
464 cce = "HS: URI missing";
468 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP1_0);
469 wsi->u.http.connection_type = HTTP_CONNECTION_CLOSE;
472 cce = "HS: URI missing";
473 lwsl_info("no URI\n");
478 ah->http_response = n;
480 if (n == 301 || n == 302 || n == 303 || n == 307 || n == 308) {
481 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_LOCATION);
483 cce = "HS: Redirect code but no Location";
487 /* Relative reference absolute path */
490 #ifdef LWS_OPENSSL_SUPPORT
493 ads = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS);
495 path = p + 1; /* +1 as lws_client_reset expects leading / to be omitted */
497 /* Absolute (Full) URI */
498 else if (strchr(p, ':'))
500 if (lws_parse_uri(p, &prot, &ads, &port, &path)) {
501 cce = "HS: URI did not parse";
505 if (!strcmp(prot, "wss") || !strcmp(prot, "https"))
508 /* Relative reference relative path */
511 /* This doesn't try to calculate an absolute path, that will be left to the server */
512 #ifdef LWS_OPENSSL_SUPPORT
515 ads = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_PEER_ADDRESS);
517 path = new_path + 1; /* +1 as lws_client_reset expects leading / to be omitted */
518 strncpy(new_path, lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_URI), sizeof(new_path));
519 new_path[sizeof(new_path) - 1] = '\0';
520 q = strrchr(new_path, '/');
523 strncpy(q + 1, p, sizeof(new_path) - (q - new_path) - 1);
524 new_path[sizeof(new_path) - 1] = '\0';
532 #ifdef LWS_OPENSSL_SUPPORT
533 if (wsi->use_ssl && !ssl) {
534 cce = "HS: Redirect attempted SSL downgrade";
539 if (!lws_client_reset(&wsi, ssl, ads, port, path, ads)) {
540 /* there are two ways to fail out with NULL return...
541 * simple, early problem where the wsi is intact, or
542 * we went through with the reconnect attempt and the
543 * wsi is already closed. In the latter case, the wsi
544 * has beet set to NULL additionally.
546 lwsl_err("Redirect failed\n");
547 cce = "HS: Redirect failed";
557 if (n != 200 && n != 201 && n != 304 && n != 401) {
558 lwsl_notice("Connection failed with code %d\n", n);
559 cce = "HS: Server unrecognized response code";
563 #ifdef LWS_WITH_HTTP_PROXY
564 wsi->perform_rewrite = 0;
565 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
566 if (!strncmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE),
568 wsi->perform_rewrite = 1;
572 /* allocate the per-connection user memory (if any) */
573 if (lws_ensure_user_space(wsi)) {
574 lwsl_err("Problem allocating wsi user mem\n");
579 /* he may choose to send us stuff in chunked transfer-coding */
581 wsi->chunk_remaining = 0; /* ie, next thing is chunk size */
582 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_TRANSFER_ENCODING)) {
583 wsi->chunked = !strcmp(lws_hdr_simple_ptr(wsi,
584 WSI_TOKEN_HTTP_TRANSFER_ENCODING),
586 /* first thing is hex, after payload there is crlf */
587 wsi->chunk_parser = ELCP_HEX;
590 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
591 wsi->u.http.content_length =
592 atoi(lws_hdr_simple_ptr(wsi,
593 WSI_TOKEN_HTTP_CONTENT_LENGTH));
594 lwsl_notice("%s: incoming content length %d\n", __func__,
595 wsi->u.http.content_length);
596 wsi->u.http.content_remain = wsi->u.http.content_length;
597 } else /* can't do 1.1 without a content length or chunked */
599 wsi->u.http.connection_type = HTTP_CONNECTION_CLOSE;
602 * we seem to be good to go, give client last chance to check
605 if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH,
606 wsi->user_space, NULL, 0)) {
608 cce = "HS: disallowed by client filter";
612 /* clear his proxy connection timeout */
613 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
615 wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
617 /* call him back to inform him he is up */
618 if (wsi->protocol->callback(wsi,
619 LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP,
620 wsi->user_space, NULL, 0)) {
621 cce = "HS: disallowed at ESTABLISHED";
625 /* free up his parsing allocations */
626 lws_header_table_detach(wsi, 0);
628 lwsl_notice("%s: client connection up\n", __func__);
633 if (lws_hdr_total_length(wsi, WSI_TOKEN_ACCEPT) == 0) {
634 lwsl_info("no ACCEPT\n");
635 cce = "HS: ACCEPT missing";
639 if (p && strncmp(p, "101", 3)) {
641 "lws_client_handshake: got bad HTTP response '%s'\n", p);
642 cce = "HS: ws upgrade response not 101";
646 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE);
648 lwsl_info("no UPGRADE\n");
649 cce = "HS: UPGRADE missing";
653 if (strcmp(p, "websocket")) {
655 "lws_client_handshake: got bad Upgrade header '%s'\n", p);
656 cce = "HS: Upgrade to something other than websocket";
660 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_CONNECTION);
662 lwsl_info("no Connection hdr\n");
663 cce = "HS: CONNECTION missing";
667 if (strcmp(p, "upgrade")) {
668 lwsl_warn("lws_client_int_s_hs: bad header %s\n", p);
669 cce = "HS: UPGRADE malformed";
673 pc = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);
675 lwsl_parser("lws_client_int_s_hs: no protocol list\n");
677 lwsl_parser("lws_client_int_s_hs: protocol list '%s'\n", pc);
680 * confirm the protocol the server wants to talk was in the list
681 * of protocols we offered
684 len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
686 lwsl_info("lws_client_int_s_hs: WSI_TOKEN_PROTOCOL is null\n");
688 * no protocol name to work from,
689 * default to first protocol
692 wsi->protocol = &wsi->vhost->protocols[0];
693 goto check_extensions;
696 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL);
699 while (pc && *pc && !okay) {
700 if (!strncmp(pc, p, len) &&
701 (pc[len] == ',' || pc[len] == '\0')) {
705 while (*pc && *pc++ != ',')
707 while (*pc && *pc == ' ')
712 lwsl_err("lws_client_int_s_hs: got bad protocol %s\n", p);
713 cce = "HS: PROTOCOL malformed";
718 * identify the selected protocol struct and set it
721 wsi->protocol = NULL;
722 while (wsi->vhost->protocols[n].callback && !wsi->protocol) {
723 if (strcmp(p, wsi->vhost->protocols[n].name) == 0) {
724 wsi->protocol = &wsi->vhost->protocols[n];
730 if (wsi->protocol == NULL) {
731 lwsl_err("lws_client_int_s_hs: fail protocol %s\n", p);
732 cce = "HS: Cannot match protocol";
738 * stitch protocol choice into the vh protocol linked list
739 * We always insert ourselves at the start of the list
744 //lwsl_err("%s: pre insert vhost start wsi %p, that wsi prev == %p\n",
746 // wsi->vhost->same_vh_protocol_list[n],
747 // wsi->same_vh_protocol_prev);
748 wsi->same_vh_protocol_prev = /* guy who points to us */
749 &wsi->vhost->same_vh_protocol_list[n];
750 wsi->same_vh_protocol_next = /* old first guy is our next */
751 wsi->vhost->same_vh_protocol_list[n];
752 /* we become the new first guy */
753 wsi->vhost->same_vh_protocol_list[n] = wsi;
755 if (wsi->same_vh_protocol_next)
756 /* old first guy points back to us now */
757 wsi->same_vh_protocol_next->same_vh_protocol_prev =
758 &wsi->same_vh_protocol_next;
760 #ifndef LWS_NO_EXTENSIONS
761 /* instantiate the accepted extensions */
763 if (!lws_hdr_total_length(wsi, WSI_TOKEN_EXTENSIONS)) {
764 lwsl_ext("no client extensions allowed by server\n");
769 * break down the list of server accepted extensions
770 * and go through matching them or identifying bogons
773 if (lws_hdr_copy(wsi, sb, context->pt_serv_buf_size, WSI_TOKEN_EXTENSIONS) < 0) {
774 lwsl_warn("ext list from server failed to copy\n");
775 cce = "HS: EXT: list too big";
785 if (*c && (*c != ',' && *c != '\t')) {
791 if (ignore || *c == ' ') {
797 if (n < sizeof(ext_name) - 1)
811 /* check we actually support it */
813 lwsl_notice("checking client ext %s\n", ext_name);
816 ext = wsi->vhost->extensions;
817 while (ext && ext->callback) {
818 if (strcmp(ext_name, ext->name)) {
824 lwsl_notice("instantiating client ext %s\n", ext_name);
826 /* instantiate the extension on this conn */
828 wsi->active_extensions[wsi->count_act_ext] = ext;
830 /* allow him to construct his ext instance */
832 if (ext->callback(lws_get_context(wsi), ext, wsi,
833 LWS_EXT_CB_CLIENT_CONSTRUCT,
834 (void *)&wsi->act_ext_user[wsi->count_act_ext],
836 lwsl_notice(" ext %s failed construction\n", ext_name);
842 * allow the user code to override ext defaults if it
846 if (user_callback_handle_rxflow(wsi->protocol->callback,
847 wsi, LWS_CALLBACK_WS_EXT_DEFAULTS,
848 (char *)ext->name, ext_name,
850 cce = "HS: EXT: failed setting defaults";
855 lws_ext_parse_options(ext, wsi, wsi->act_ext_user[
856 wsi->count_act_ext], opts, ext_name,
858 lwsl_err("%s: unable to parse user defaults '%s'",
860 cce = "HS: EXT: failed parsing defaults";
865 * give the extension the server options
867 if (a && lws_ext_parse_options(ext, wsi,
868 wsi->act_ext_user[wsi->count_act_ext],
870 lwsl_err("%s: unable to parse remote def '%s'",
872 cce = "HS: EXT: failed parsing options";
876 if (ext->callback(lws_get_context(wsi), ext, wsi,
877 LWS_EXT_CB_OPTION_CONFIRM,
878 wsi->act_ext_user[wsi->count_act_ext],
880 lwsl_err("%s: ext %s rejects server options %s",
881 __func__, ext->name, a);
882 cce = "HS: EXT: Rejects server options";
886 wsi->count_act_ext++;
892 lwsl_warn("Unknown ext '%s'!\n", ext_name);
893 cce = "HS: EXT: unknown ext";
905 * Confirm his accept token is the one we precomputed
908 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_ACCEPT);
909 if (strcmp(p, wsi->u.hdr.ah->initial_handshake_hash_base64)) {
910 lwsl_warn("lws_client_int_s_hs: accept '%s' wrong vs '%s'\n", p,
911 wsi->u.hdr.ah->initial_handshake_hash_base64);
912 cce = "HS: Accept hash wrong";
916 /* allocate the per-connection user memory (if any) */
917 if (lws_ensure_user_space(wsi)) {
918 lwsl_err("Problem allocating wsi user mem\n");
924 * we seem to be good to go, give client last chance to check
927 if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH,
928 wsi->user_space, NULL, 0)) {
929 cce = "HS: Rejected by filter cb";
933 /* clear his proxy connection timeout */
934 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
936 /* free up his parsing allocations */
937 lws_header_table_detach(wsi, 0);
939 lws_union_transition(wsi, LWSCM_WS_CLIENT);
940 wsi->state = LWSS_ESTABLISHED;
941 lws_restart_ws_ping_pong_timer(wsi);
943 wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
946 * create the frame buffer for this connection according to the
947 * size mentioned in the protocol definition. If 0 there, then
948 * use a big default for compatibility
950 n = wsi->protocol->rx_buffer_size;
952 n = context->pt_serv_buf_size;
954 wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
955 if (!wsi->u.ws.rx_ubuf) {
956 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
960 wsi->u.ws.rx_ubuf_alloc = n;
961 lwsl_info("Allocating client RX buffer %d\n", n);
963 if (setsockopt(wsi->desc.sockfd, SOL_SOCKET, SO_SNDBUF, (const char *)&n,
965 lwsl_warn("Failed to set SNDBUF to %d", n);
966 cce = "HS: SO_SNDBUF failed";
970 lwsl_debug("handshake OK for protocol %s\n", wsi->protocol->name);
972 /* call him back to inform him he is up */
974 if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_ESTABLISHED,
975 wsi->user_space, NULL, 0)) {
976 cce = "HS: Rejected at CLIENT_ESTABLISHED";
979 #ifndef LWS_NO_EXTENSIONS
981 * inform all extensions, not just active ones since they
984 ext = wsi->vhost->extensions;
986 while (ext && ext->callback) {
988 for (n = 0; n < wsi->count_act_ext; n++)
989 if (wsi->active_extensions[n] == ext)
990 v = wsi->act_ext_user[n];
992 ext->callback(context, ext, wsi,
993 LWS_EXT_CB_ANY_WSI_ESTABLISHED, v, NULL, 0);
1001 close_reason = LWS_CLOSE_STATUS_NOSTATUS;
1005 wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
1006 wsi->user_space, (void *)cce,
1007 (unsigned int)strlen(cce));
1008 wsi->already_did_cce = 1;
1010 lwsl_info("closing connection due to bail2 connection error\n");
1012 /* closing will free up his parsing allocations */
1013 lws_close_free_wsi(wsi, close_reason);
1020 lws_generate_client_handshake(struct lws *wsi, char *pkt)
1022 char buf[128], hash[20], key_b64[40], *p = pkt;
1023 struct lws_context *context = wsi->context;
1026 #ifndef LWS_NO_EXTENSIONS
1027 const struct lws_extension *ext;
1030 const char *pp = lws_hdr_simple_ptr(wsi,
1031 _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);
1033 meth = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_METHOD);
1041 if (!strcmp(meth, "RAW")) {
1042 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1043 lwsl_notice("client transition to raw\n");
1046 const struct lws_protocols *pr;
1048 pr = lws_vhost_name_to_protocol(wsi->vhost, pp);
1051 lwsl_err("protocol %s not enabled on vhost\n",
1056 lws_bind_protocol(wsi, pr);
1059 if ((wsi->protocol->callback)(wsi,
1060 LWS_CALLBACK_RAW_ADOPT,
1061 wsi->user_space, NULL, 0))
1064 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1065 lws_union_transition(wsi, LWSCM_RAW);
1066 lws_header_table_detach(wsi, 1);
1073 * create the random key
1075 n = lws_get_random(context, hash, 16);
1077 lwsl_err("Unable to read from random dev %s\n",
1078 SYSTEM_RANDOM_FILEPATH);
1079 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1083 lws_b64_encode_string(hash, 16, key_b64, sizeof(key_b64));
1087 * 04 example client handshake
1089 * GET /chat HTTP/1.1
1090 * Host: server.example.com
1091 * Upgrade: websocket
1092 * Connection: Upgrade
1093 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
1094 * Sec-WebSocket-Origin: http://example.com
1095 * Sec-WebSocket-Protocol: chat, superchat
1096 * Sec-WebSocket-Version: 4
1099 p += sprintf(p, "%s %s HTTP/1.1\x0d\x0a", meth,
1100 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_URI));
1102 p += sprintf(p, "Pragma: no-cache\x0d\x0a"
1103 "Cache-Control: no-cache\x0d\x0a");
1105 p += sprintf(p, "Host: %s\x0d\x0a",
1106 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_HOST));
1108 if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN)) {
1109 if (lws_check_opt(context->options, LWS_SERVER_OPTION_JUST_USE_RAW_ORIGIN))
1110 p += sprintf(p, "Origin: %s\x0d\x0a",
1111 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN));
1113 p += sprintf(p, "Origin: http://%s\x0d\x0a",
1114 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN));
1118 p += sprintf(p, "Upgrade: websocket\x0d\x0a"
1119 "Connection: Upgrade\x0d\x0a"
1120 "Sec-WebSocket-Key: ");
1122 p += strlen(key_b64);
1123 p += sprintf(p, "\x0d\x0a");
1124 if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS))
1125 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
1126 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS));
1128 /* tell the server what extensions we could support */
1130 #ifndef LWS_NO_EXTENSIONS
1131 ext = wsi->vhost->extensions;
1132 while (ext && ext->callback) {
1133 n = lws_ext_cb_all_exts(context, wsi,
1134 LWS_EXT_CB_CHECK_OK_TO_PROPOSE_EXTENSION,
1135 (char *)ext->name, 0);
1136 if (n) { /* an extension vetos us */
1137 lwsl_ext("ext %s vetoed\n", (char *)ext->name);
1141 n = wsi->vhost->protocols[0].callback(wsi,
1142 LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
1143 wsi->user_space, (char *)ext->name, 0);
1146 * zero return from callback means
1147 * go ahead and allow the extension,
1148 * it's what we get if the callback is
1162 p += sprintf(p, "Sec-WebSocket-Extensions: ");
1163 p += sprintf(p, "%s", ext->client_offer);
1169 p += sprintf(p, "\x0d\x0a");
1172 if (wsi->ietf_spec_revision)
1173 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
1174 wsi->ietf_spec_revision);
1176 /* prepare the expected server accept response */
1178 key_b64[39] = '\0'; /* enforce composed length below buf sizeof */
1179 n = sprintf(buf, "%s258EAFA5-E914-47DA-95CA-C5AB0DC85B11", key_b64);
1181 lws_SHA1((unsigned char *)buf, n, (unsigned char *)hash);
1183 lws_b64_encode_string(hash, 20,
1184 wsi->u.hdr.ah->initial_handshake_hash_base64,
1185 sizeof(wsi->u.hdr.ah->initial_handshake_hash_base64));
1188 /* give userland a chance to append, eg, cookies */
1190 wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
1191 wsi->user_space, &p, (pkt + context->pt_serv_buf_size) - p - 12);
1193 p += sprintf(p, "\x0d\x0a");