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];
75 const char *cce = NULL;
82 case LWSCM_WSCL_WAITING_CONNECT:
85 * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE
86 * timeout protection set in client-handshake.c
89 if (!lws_client_connect_2(wsi)) {
91 lwsl_client("closed\n");
95 /* either still pending connection, or changed mode */
98 case LWSCM_WSCL_WAITING_PROXY_REPLY:
100 /* handle proxy hung up on us */
102 if (pollfd->revents & LWS_POLLHUP) {
104 lwsl_warn("Proxy connection %p (fd=%d) dead\n",
105 (void *)wsi, pollfd->fd);
107 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
111 n = recv(wsi->sock, sb, context->pt_serv_buf_size, 0);
113 if (LWS_ERRNO == LWS_EAGAIN) {
114 lwsl_debug("Proxy read returned EAGAIN... retrying\n");
118 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
119 lwsl_err("ERROR reading from proxy socket\n");
123 pt->serv_buf[13] = '\0';
124 if (strcmp(sb, "HTTP/1.0 200 ") &&
125 strcmp(sb, "HTTP/1.1 200 ")) {
126 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
127 lwsl_err("ERROR proxy: %s\n", sb);
131 /* clear his proxy connection timeout */
133 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
137 case LWSCM_WSCL_ISSUE_HANDSHAKE:
140 * we are under PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE
141 * timeout protection set in client-handshake.c
143 * take care of our lws_callback_on_writable
144 * happening at a time when there's no real connection yet
146 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0))
149 #ifdef LWS_OPENSSL_SUPPORT
150 /* we can retry this... just cook the SSL BIO the first time */
152 if (wsi->use_ssl && !wsi->ssl)
153 lws_ssl_client_bio_create(wsi);
156 n = lws_ssl_client_connect1(wsi);
160 cce = "lws_ssl_client_connect1 failed";
168 case LWSCM_WSCL_WAITING_SSL:
171 n = lws_ssl_client_connect2(wsi);
175 cce = "lws_ssl_client_connect2 failed";
182 wsi->mode = LWSCM_WSCL_ISSUE_HANDSHAKE2;
183 lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND,
184 context->timeout_secs);
188 case LWSCM_WSCL_ISSUE_HANDSHAKE2:
189 p = lws_generate_client_handshake(wsi, p);
191 lwsl_err("Failed to generate handshake for client\n");
192 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
196 /* send our request to the server */
198 lws_latency_pre(context, wsi);
200 n = lws_ssl_capable_write(wsi, (unsigned char *)sb, p - sb);
201 lws_latency(context, wsi, "send lws_issue_raw", n,
204 case LWS_SSL_CAPABLE_ERROR:
205 lwsl_debug("ERROR writing to client socket\n");
206 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
208 case LWS_SSL_CAPABLE_MORE_SERVICE:
209 lws_callback_on_writable(wsi);
213 wsi->u.hdr.parser_state = WSI_TOKEN_NAME_PART;
214 wsi->u.hdr.lextable_pos = 0;
215 wsi->mode = LWSCM_WSCL_WAITING_SERVER_REPLY;
216 lws_set_timeout(wsi, PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE,
217 context->timeout_secs);
220 case LWSCM_WSCL_WAITING_SERVER_REPLY:
222 /* handle server hung up on us */
224 if (pollfd->revents & LWS_POLLHUP) {
226 lwsl_debug("Server connection %p (fd=%d) dead\n",
227 (void *)wsi, pollfd->fd);
228 cce = "Peer hung up";
232 if (!(pollfd->revents & LWS_POLLIN))
235 /* interpret the server response */
238 * HTTP/1.1 101 Switching Protocols
240 * Connection: Upgrade
241 * Sec-WebSocket-Accept: me89jWimTRKTWwrS3aRrL53YZSo=
242 * Sec-WebSocket-Nonce: AQIDBAUGBwgJCgsMDQ4PEC==
243 * Sec-WebSocket-Protocol: chat
247 * we have to take some care here to only take from the
248 * socket bytewise. The browser may (and has been seen to
249 * in the case that onopen() performs websocket traffic)
250 * coalesce both handshake response and websocket traffic
251 * in one packet, since at that point the connection is
252 * definitively ready from browser pov.
255 while (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE &&
257 n = lws_ssl_capable_read(wsi, &c, 1);
258 lws_latency(context, wsi, "send lws_issue_raw", n,
262 case LWS_SSL_CAPABLE_ERROR:
265 case LWS_SSL_CAPABLE_MORE_SERVICE:
269 if (lws_parse(wsi, c)) {
270 lwsl_warn("problems parsing header\n");
276 * hs may also be coming in multiple packets, there is a 5-sec
277 * libwebsocket timeout still active here too, so if parsing did
278 * not complete just wait for next packet coming in this state
281 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
285 * otherwise deal with the handshake. If there's any
286 * packet traffic already arrived we'll trigger poll() again
287 * right away and deal with it that way
290 return lws_client_interpret_server_handshake(wsi);
293 lwsl_info("closing conn at LWS_CONNMODE...SERVER_REPLY\n");
294 wsi->vhost->protocols[0].callback(wsi,
295 LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
296 wsi->user_space, (void *)cce, cce ? strlen(cce) : 0);
297 wsi->already_did_cce = 1;
298 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
301 case LWSCM_WSCL_WAITING_EXTENSION_CONNECT:
302 lwsl_ext("LWSCM_WSCL_WAITING_EXTENSION_CONNECT\n");
305 case LWSCM_WSCL_PENDING_CANDIDATE_CHILD:
306 lwsl_ext("LWSCM_WSCL_PENDING_CANDIDATE_CHILD\n");
316 * In-place str to lower case
323 *s = tolower((int)*s);
328 int LWS_WARN_UNUSED_RESULT
329 lws_http_transaction_completed_client(struct lws *wsi)
331 lwsl_debug("%s: wsi %p\n", __func__, wsi);
332 /* if we can't go back to accept new headers, drop the connection */
333 if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
334 lwsl_info("%s: %p: close connection\n", __func__, wsi);
338 /* otherwise set ourselves up ready to go again */
339 wsi->state = LWSS_CLIENT_HTTP_ESTABLISHED;
340 wsi->mode = LWSCM_HTTP_CLIENT_ACCEPTED;
341 wsi->u.http.content_length = 0;
342 wsi->hdr_parsing_completed = 0;
344 /* He asked for it to stay alive indefinitely */
345 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
348 * As client, nothing new is going to come until we ask for it
349 * we can drop the ah, if any
352 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
353 lws_header_table_detach(wsi, 0);
356 /* If we're (re)starting on headers, need other implied init */
357 wsi->u.hdr.ues = URIES_IDLE;
359 lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
365 lws_client_interpret_server_handshake(struct lws *wsi)
367 int n, len, okay = 0, port = 0, ssl = 0;
368 int close_reason = LWS_CLOSE_STATUS_PROTOCOL_ERR;
369 struct lws_context *context = wsi->context;
370 const char *pc, *prot, *ads = NULL, *path, *cce = NULL;
371 struct allocated_headers *ah;
373 #ifndef LWS_NO_EXTENSIONS
374 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
375 char *sb = (char *)&pt->serv_buf[0];
376 const struct lws_ext_options *opts;
377 const struct lws_extension *ext;
386 /* we are being an http client...
389 lws_union_transition(wsi, LWSCM_HTTP_CLIENT_ACCEPTED);
390 wsi->state = LWSS_CLIENT_HTTP_ESTABLISHED;
395 * well, what the server sent looked reasonable for syntax.
396 * Now let's confirm it sent all the necessary headers
398 * http (non-ws) client will expect something like this
401 * server:.libwebsockets
402 * content-type:.text/html
403 * content-length:.17703
404 * set-cookie:.test=LWS_1456736240_336776_COOKIE;Max-Age=360000
410 wsi->u.http.connection_type = HTTP_CONNECTION_KEEP_ALIVE;
411 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP);
412 if (wsi->do_ws && !p) {
413 lwsl_info("no URI\n");
414 cce = "HS: URI missing";
418 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP1_0);
419 wsi->u.http.connection_type = HTTP_CONNECTION_CLOSE;
422 cce = "HS: URI missing";
423 lwsl_info("no URI\n");
427 if (n == 301 || n == 302 || n == 303 || n == 307 || n == 308) {
428 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_LOCATION);
430 cce = "HS: Redirect code but no Location";
434 if (lws_parse_uri(p, &prot, &ads, &port, &path)) {
435 cce = "HS: URI did not parse";
439 if (!strcmp(prot, "wss://") || !strcmp(prot, "https://"))
442 if (lws_client_reset(wsi, ssl, ads, port, path, ads)) {
443 lwsl_err("Redirect failed\n");
444 cce = "HS: Redirect failed";
452 lwsl_notice("Connection failed with code %d", n);
453 cce = "HS: Server did not return 200";
457 #ifdef LWS_WITH_HTTP_PROXY
458 wsi->perform_rewrite = 0;
459 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE)) {
460 if (!strncmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE),
462 wsi->perform_rewrite = 1;
466 /* allocate the per-connection user memory (if any) */
467 if (lws_ensure_user_space(wsi)) {
468 lwsl_err("Problem allocating wsi user mem\n");
473 /* he may choose to send us stuff in chunked transfer-coding */
475 wsi->chunk_remaining = 0; /* ie, next thing is chunk size */
476 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_TRANSFER_ENCODING)) {
477 wsi->chunked = !strcmp(lws_hdr_simple_ptr(wsi,
478 WSI_TOKEN_HTTP_TRANSFER_ENCODING),
480 /* first thing is hex, after payload there is crlf */
481 wsi->chunk_parser = ELCP_HEX;
484 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
485 wsi->u.http.content_length =
486 atoi(lws_hdr_simple_ptr(wsi,
487 WSI_TOKEN_HTTP_CONTENT_LENGTH));
488 lwsl_notice("%s: incoming content length %d\n", __func__,
489 wsi->u.http.content_length);
490 wsi->u.http.content_remain = wsi->u.http.content_length;
491 } else /* can't do 1.1 without a content length or chunked */
493 wsi->u.http.connection_type = HTTP_CONNECTION_CLOSE;
496 * we seem to be good to go, give client last chance to check
499 if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH,
500 wsi->user_space, NULL, 0)) {
502 cce = "HS: disallowed by client filter";
506 /* clear his proxy connection timeout */
507 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
509 wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
511 /* call him back to inform him he is up */
512 if (wsi->protocol->callback(wsi,
513 LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP,
514 wsi->user_space, NULL, 0)) {
515 cce = "HS: disallowed at ESTABLISHED";
519 /* free up his parsing allocations */
520 lws_header_table_detach(wsi, 0);
522 lwsl_notice("%s: client connection up\n", __func__);
527 if (lws_hdr_total_length(wsi, WSI_TOKEN_ACCEPT) == 0) {
528 lwsl_info("no ACCEPT\n");
529 cce = "HS: ACCEPT missing";
533 if (p && strncmp(p, "101", 3)) {
535 "lws_client_handshake: got bad HTTP response '%s'\n", p);
536 cce = "HS: ws upgrade response not 101";
540 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE);
542 lwsl_info("no UPGRADE\n");
543 cce = "HS: UPGRADE missing";
547 if (strcmp(p, "websocket")) {
549 "lws_client_handshake: got bad Upgrade header '%s'\n", p);
550 cce = "HS: Upgrade to something other than websocket";
554 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_CONNECTION);
556 lwsl_info("no Connection hdr\n");
557 cce = "HS: CONNECTION missing";
561 if (strcmp(p, "upgrade")) {
562 lwsl_warn("lws_client_int_s_hs: bad header %s\n", p);
563 cce = "HS: UPGRADE malformed";
567 pc = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS);
569 lwsl_parser("lws_client_int_s_hs: no protocol list\n");
571 lwsl_parser("lws_client_int_s_hs: protocol list '%s'\n", pc);
574 * confirm the protocol the server wants to talk was in the list
575 * of protocols we offered
578 len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
580 lwsl_info("lws_client_int_s_hs: WSI_TOKEN_PROTOCOL is null\n");
582 * no protocol name to work from,
583 * default to first protocol
585 wsi->protocol = &wsi->vhost->protocols[0];
586 goto check_extensions;
589 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL);
592 while (pc && *pc && !okay) {
593 if (!strncmp(pc, p, len) &&
594 (pc[len] == ',' || pc[len] == '\0')) {
598 while (*pc && *pc++ != ',')
600 while (*pc && *pc == ' ')
605 lwsl_err("lws_client_int_s_hs: got bad protocol %s\n", p);
606 cce = "HS: PROTOCOL malformed";
611 * identify the selected protocol struct and set it
614 wsi->protocol = NULL;
615 while (wsi->vhost->protocols[n].callback && !wsi->protocol) {
616 if (strcmp(p, wsi->vhost->protocols[n].name) == 0) {
617 wsi->protocol = &wsi->vhost->protocols[n];
623 if (wsi->protocol == NULL) {
624 lwsl_err("lws_client_int_s_hs: fail protocol %s\n", p);
625 cce = "HS: Cannot match protocol";
631 * stitch protocol choice into the vh protocol linked list
632 * We always insert ourselves at the start of the list
637 //lwsl_err("%s: pre insert vhost start wsi %p, that wsi prev == %p\n",
639 // wsi->vhost->same_vh_protocol_list[n],
640 // wsi->same_vh_protocol_prev);
641 wsi->same_vh_protocol_prev = /* guy who points to us */
642 &wsi->vhost->same_vh_protocol_list[n];
643 wsi->same_vh_protocol_next = /* old first guy is our next */
644 wsi->vhost->same_vh_protocol_list[n];
645 /* we become the new first guy */
646 wsi->vhost->same_vh_protocol_list[n] = wsi;
648 if (wsi->same_vh_protocol_next)
649 /* old first guy points back to us now */
650 wsi->same_vh_protocol_next->same_vh_protocol_prev =
651 &wsi->same_vh_protocol_next;
654 #ifndef LWS_NO_EXTENSIONS
655 /* instantiate the accepted extensions */
657 if (!lws_hdr_total_length(wsi, WSI_TOKEN_EXTENSIONS)) {
658 lwsl_ext("no client extensions allowed by server\n");
663 * break down the list of server accepted extensions
664 * and go through matching them or identifying bogons
667 if (lws_hdr_copy(wsi, sb, context->pt_serv_buf_size, WSI_TOKEN_EXTENSIONS) < 0) {
668 lwsl_warn("ext list from server failed to copy\n");
669 cce = "HS: EXT: list too big";
679 if (*c && (*c != ',' && *c != '\t')) {
685 if (ignore || *c == ' ') {
691 if (n < sizeof(ext_name) - 1)
705 /* check we actually support it */
707 lwsl_notice("checking client ext %s\n", ext_name);
710 ext = wsi->vhost->extensions;
711 while (ext && ext->callback) {
712 if (strcmp(ext_name, ext->name)) {
718 lwsl_notice("instantiating client ext %s\n", ext_name);
720 /* instantiate the extension on this conn */
722 wsi->active_extensions[wsi->count_act_ext] = ext;
724 /* allow him to construct his ext instance */
726 if (ext->callback(lws_get_context(wsi), ext, wsi,
727 LWS_EXT_CB_CLIENT_CONSTRUCT,
728 (void *)&wsi->act_ext_user[wsi->count_act_ext],
730 lwsl_notice(" ext %s failed construction\n", ext_name);
736 * allow the user code to override ext defaults if it
740 if (user_callback_handle_rxflow(wsi->protocol->callback,
741 wsi, LWS_CALLBACK_WS_EXT_DEFAULTS,
742 (char *)ext->name, ext_name,
744 cce = "HS: EXT: failed setting defaults";
749 lws_ext_parse_options(ext, wsi, wsi->act_ext_user[
750 wsi->count_act_ext], opts, ext_name,
752 lwsl_err("%s: unable to parse user defaults '%s'",
754 cce = "HS: EXT: failed parsing defaults";
759 * give the extension the server options
761 if (a && lws_ext_parse_options(ext, wsi,
762 wsi->act_ext_user[wsi->count_act_ext],
764 lwsl_err("%s: unable to parse remote def '%s'",
766 cce = "HS: EXT: failed parsing options";
770 if (ext->callback(lws_get_context(wsi), ext, wsi,
771 LWS_EXT_CB_OPTION_CONFIRM,
772 wsi->act_ext_user[wsi->count_act_ext],
774 lwsl_err("%s: ext %s rejects server options %s",
776 cce = "HS: EXT: Rejects server options";
780 wsi->count_act_ext++;
786 lwsl_warn("Unknown ext '%s'!\n", ext_name);
787 cce = "HS: EXT: unknown ext";
799 * Confirm his accept token is the one we precomputed
802 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_ACCEPT);
803 if (strcmp(p, wsi->u.hdr.ah->initial_handshake_hash_base64)) {
804 lwsl_warn("lws_client_int_s_hs: accept '%s' wrong vs '%s'\n", p,
805 wsi->u.hdr.ah->initial_handshake_hash_base64);
806 cce = "HS: Accept hash wrong";
810 /* allocate the per-connection user memory (if any) */
811 if (lws_ensure_user_space(wsi)) {
812 lwsl_err("Problem allocating wsi user mem\n");
818 * we seem to be good to go, give client last chance to check
821 if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH,
822 wsi->user_space, NULL, 0)) {
823 cce = "HS: Rejected by filter cb";
827 /* clear his proxy connection timeout */
828 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
830 /* free up his parsing allocations */
831 lws_header_table_detach(wsi, 0);
833 lws_union_transition(wsi, LWSCM_WS_CLIENT);
834 wsi->state = LWSS_ESTABLISHED;
835 lws_restart_ws_ping_pong_timer(wsi);
837 wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
840 * create the frame buffer for this connection according to the
841 * size mentioned in the protocol definition. If 0 there, then
842 * use a big default for compatibility
844 n = wsi->protocol->rx_buffer_size;
846 n = context->pt_serv_buf_size;
848 wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
849 if (!wsi->u.ws.rx_ubuf) {
850 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
854 wsi->u.ws.rx_ubuf_alloc = n;
855 lwsl_info("Allocating client RX buffer %d\n", n);
857 if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF, (const char *)&n,
859 lwsl_warn("Failed to set SNDBUF to %d", n);
860 cce = "HS: SO_SNDBUF failed";
864 lwsl_debug("handshake OK for protocol %s\n", wsi->protocol->name);
866 /* call him back to inform him he is up */
868 if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_ESTABLISHED,
869 wsi->user_space, NULL, 0)) {
870 cce = "HS: Rejected at CLIENT_ESTABLISHED";
873 #ifndef LWS_NO_EXTENSIONS
875 * inform all extensions, not just active ones since they
878 ext = wsi->vhost->extensions;
880 while (ext && ext->callback) {
882 for (n = 0; n < wsi->count_act_ext; n++)
883 if (wsi->active_extensions[n] == ext)
884 v = wsi->act_ext_user[n];
886 ext->callback(context, ext, wsi,
887 LWS_EXT_CB_ANY_WSI_ESTABLISHED, v, NULL, 0);
895 close_reason = LWS_CLOSE_STATUS_NOSTATUS;
898 wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_CONNECTION_ERROR,
899 wsi->user_space, (void *)cce,
900 (unsigned int) (cce ? strlen(cce): 0));
901 wsi->already_did_cce = 1;
903 lwsl_info("closing connection due to bail2 connection error\n");
905 /* closing will free up his parsing allocations */
906 lws_close_free_wsi(wsi, close_reason);
913 lws_generate_client_handshake(struct lws *wsi, char *pkt)
915 char buf[128], hash[20], key_b64[40], *p = pkt;
916 struct lws_context *context = wsi->context;
919 #ifndef LWS_NO_EXTENSIONS
920 const struct lws_extension *ext;
924 meth = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_METHOD);
933 * create the random key
935 n = lws_get_random(context, hash, 16);
937 lwsl_err("Unable to read from random dev %s\n",
938 SYSTEM_RANDOM_FILEPATH);
939 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
943 lws_b64_encode_string(hash, 16, key_b64, sizeof(key_b64));
947 * 04 example client handshake
950 * Host: server.example.com
952 * Connection: Upgrade
953 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
954 * Sec-WebSocket-Origin: http://example.com
955 * Sec-WebSocket-Protocol: chat, superchat
956 * Sec-WebSocket-Version: 4
959 p += sprintf(p, "%s %s HTTP/1.1\x0d\x0a", meth,
960 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_URI));
962 p += sprintf(p, "Pragma: no-cache\x0d\x0a"
963 "Cache-Control: no-cache\x0d\x0a");
965 p += sprintf(p, "Host: %s\x0d\x0a",
966 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_HOST));
968 if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN))
969 p += sprintf(p, "Origin: http://%s\x0d\x0a",
970 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_ORIGIN));
973 p += sprintf(p, "Upgrade: websocket\x0d\x0a"
974 "Connection: Upgrade\x0d\x0a"
975 "Sec-WebSocket-Key: ");
977 p += strlen(key_b64);
978 p += sprintf(p, "\x0d\x0a");
979 if (lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS))
980 p += sprintf(p, "Sec-WebSocket-Protocol: %s\x0d\x0a",
981 lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS));
983 /* tell the server what extensions we could support */
985 #ifndef LWS_NO_EXTENSIONS
986 ext = wsi->vhost->extensions;
987 while (ext && ext->callback) {
988 n = lws_ext_cb_all_exts(context, wsi,
989 LWS_EXT_CB_CHECK_OK_TO_PROPOSE_EXTENSION,
990 (char *)ext->name, 0);
991 if (n) { /* an extension vetos us */
992 lwsl_ext("ext %s vetoed\n", (char *)ext->name);
996 n = wsi->vhost->protocols[0].callback(wsi,
997 LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED,
998 wsi->user_space, (char *)ext->name, 0);
1001 * zero return from callback means
1002 * go ahead and allow the extension,
1003 * it's what we get if the callback is
1017 p += sprintf(p, "Sec-WebSocket-Extensions: ");
1018 p += sprintf(p, "%s", ext->client_offer);
1024 p += sprintf(p, "\x0d\x0a");
1027 if (wsi->ietf_spec_revision)
1028 p += sprintf(p, "Sec-WebSocket-Version: %d\x0d\x0a",
1029 wsi->ietf_spec_revision);
1031 /* prepare the expected server accept response */
1033 key_b64[39] = '\0'; /* enforce composed length below buf sizeof */
1034 n = sprintf(buf, "%s258EAFA5-E914-47DA-95CA-C5AB0DC85B11", key_b64);
1036 lws_SHA1((unsigned char *)buf, n, (unsigned char *)hash);
1038 lws_b64_encode_string(hash, 20,
1039 wsi->u.hdr.ah->initial_handshake_hash_base64,
1040 sizeof(wsi->u.hdr.ah->initial_handshake_hash_base64));
1043 /* give userland a chance to append, eg, cookies */
1045 wsi->vhost->protocols[0].callback(wsi, LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER,
1046 wsi->user_space, &p, (pkt + context->pt_serv_buf_size) - p - 12);
1048 p += sprintf(p, "\x0d\x0a");