2 * libwebsockets - small server side websockets and web server implementation
4 * Copyright (C) 2010-2016 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,
23 #include "private-libwebsockets.h"
26 lws_context_init_server(struct lws_context_creation_info *info,
27 struct lws_vhost *vhost)
30 int n, opt = 1, limit = 1;
32 lws_sockfd_type sockfd;
37 /* set up our external listening socket we serve on */
39 if (info->port == CONTEXT_PORT_NO_LISTEN)
42 vh = vhost->context->vhost_list;
44 if (vh->listen_port == info->port) {
45 if ((!info->iface && !vh->iface) ||
46 (info->iface && vh->iface &&
47 !strcmp(info->iface, vh->iface))) {
48 vhost->listen_port = info->port;
49 vhost->iface = info->iface;
50 lwsl_notice(" using listen skt from vhost %s\n",
59 #if defined(__linux__)
60 limit = vhost->context->count_threads;
63 for (m = 0; m < limit; m++) {
64 #ifdef LWS_USE_UNIX_SOCK
65 if (LWS_UNIX_SOCK_ENABLED(vhost))
66 sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
70 if (LWS_IPV6_ENABLED(context))
71 sockfd = socket(AF_INET6, SOCK_STREAM, 0);
74 sockfd = socket(AF_INET, SOCK_STREAM, 0);
78 sockfd = mbed3_create_tcp_stream_socket();
79 if (!lws_sockfd_valid(sockfd)) {
81 lwsl_err("ERROR opening socket\n");
87 * allow us to restart even if old sockets in TIME_WAIT
89 if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
90 (const void *)&opt, sizeof(opt)) < 0) {
91 compatible_close(sockfd);
94 #if defined(__linux__) && defined(SO_REUSEPORT) && LWS_MAX_SMP > 1
95 if (vhost->context->count_threads > 1)
96 if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT,
97 (const void *)&opt, sizeof(opt)) < 0) {
98 compatible_close(sockfd);
103 lws_plat_set_socket_options(vhost, sockfd);
106 n = lws_socket_bind(vhost, sockfd, info->port, info->iface);
111 vhost->listen_port = info->port;
112 vhost->iface = info->iface;
114 wsi = lws_zalloc(sizeof(struct lws));
116 lwsl_err("Out of mem\n");
119 wsi->context = vhost->context;
121 wsi->mode = LWSCM_SERVER_LISTENER;
122 wsi->protocol = vhost->protocols;
127 vhost->context->pt[m].wsi_listening = wsi;
128 if (insert_wsi_socket_into_fds(vhost->context, wsi))
131 vhost->context->count_wsi_allocated++;
132 vhost->lserv_wsi = wsi;
135 listen(wsi->sock, LWS_SOMAXCONN);
136 } /* for each thread able to independently listen */
138 mbed3_tcp_stream_bind(wsi->sock, info->port, wsi);
140 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS)) {
141 #ifdef LWS_USE_UNIX_SOCK
142 if (LWS_UNIX_SOCK_ENABLED(vhost))
143 lwsl_notice(" Listening on \"%s\"\n", info->iface);
146 lwsl_notice(" Listening on port %d\n", info->port);
152 compatible_close(sockfd);
158 _lws_server_listen_accept_flow_control(struct lws *twsi, int on)
160 struct lws_context_per_thread *pt = &twsi->context->pt[(int)twsi->tsi];
161 struct lws *wsi = pt->wsi_listening;
164 if (!wsi || twsi->context->being_destroyed)
167 lwsl_debug("%s: Thr %d: LISTEN wsi %p: state %d\n",
168 __func__, twsi->tsi, (void *)wsi, on);
171 n = lws_change_pollfd(wsi, 0, LWS_POLLIN);
173 n = lws_change_pollfd(wsi, LWS_POLLIN, 0);
179 lws_select_vhost(struct lws_context *context, int port, const char *servername)
181 struct lws_vhost *vhost = context->vhost_list;
184 if (port == vhost->listen_port &&
185 !strcmp(vhost->name, servername)) {
186 lwsl_info("SNI: Found: %s\n", servername);
189 vhost = vhost->vhost_next;
195 static const char * get_mimetype(const char *file)
197 int n = strlen(file);
202 if (!strcmp(&file[n - 4], ".ico"))
203 return "image/x-icon";
205 if (!strcmp(&file[n - 4], ".gif"))
208 if (!strcmp(&file[n - 3], ".js"))
209 return "text/javascript";
211 if (!strcmp(&file[n - 4], ".png"))
214 if (!strcmp(&file[n - 4], ".jpg"))
217 if (!strcmp(&file[n - 5], ".html"))
220 if (!strcmp(&file[n - 4], ".css"))
223 if (!strcmp(&file[n - 4], ".ttf"))
224 return "application/x-font-ttf";
229 int lws_http_serve(struct lws *wsi, char *uri, const char *origin)
231 const char *mimetype;
233 char path[256], sym[256];
234 unsigned char *p = (unsigned char *)sym + 32 + LWS_PRE, *start = p;
235 unsigned char *end = p + sizeof(sym) - 32 - LWS_PRE;
239 snprintf(path, sizeof(path) - 1, "%s/%s", origin, uri);
244 if (stat(path, &st)) {
245 lwsl_err("unable to stat %s\n", path);
249 lwsl_debug(" %s mode %d\n", path, S_IFMT & st.st_mode);
251 if ((S_IFMT & st.st_mode) == S_IFLNK) {
252 len = readlink(path, sym, sizeof(sym) - 1);
254 lwsl_err("Failed to read link %s\n", path);
258 lwsl_debug("symlink %s -> %s\n", path, sym);
259 snprintf(path, sizeof(path) - 1, "%s", sym);
262 if ((S_IFMT & st.st_mode) == S_IFDIR) {
263 lwsl_debug("default filename append to dir\n");
264 snprintf(path, sizeof(path) - 1, "%s/%s/index.html",
268 } while ((S_IFMT & st.st_mode) != S_IFREG && spin < 5);
271 lwsl_err("symlink loop %s \n", path);
273 n = sprintf(sym, "%08lX%08lX", (unsigned long)st.st_size,
274 (unsigned long)st.st_mtime);
276 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_NONE_MATCH)) {
278 * he thinks he has some version of it already,
279 * check if the tag matches
281 if (!strcmp(sym, lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_IF_NONE_MATCH))) {
283 lwsl_debug("%s: ETAG match %s %s\n", __func__,
286 /* we don't need to send the payload */
287 if (lws_add_http_header_status(wsi, 304, &p, end))
289 if (lws_add_http_header_by_token(wsi,
291 (unsigned char *)sym, n, &p, end))
293 if (lws_finalize_http_header(wsi, &p, end))
296 n = lws_write(wsi, start, p - start,
297 LWS_WRITE_HTTP_HEADERS);
298 if (n != (p - start)) {
299 lwsl_err("_write returned %d from %d\n", n, p - start);
303 return lws_http_transaction_completed(wsi);
307 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ETAG,
308 (unsigned char *)sym, n, &p, end))
311 mimetype = get_mimetype(path);
313 lwsl_err("unknown mimetype for %s", path);
317 n = lws_serve_http_file(wsi, path, mimetype, (char *)start, p - start);
319 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
320 return -1; /* error or can't reuse connection: close the socket */
324 lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
330 lws_http_action(struct lws *wsi)
332 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
333 enum http_connection_type connection_type;
334 enum http_version request_version;
335 char content_length_str[32];
336 struct lws_http_mount *hm, *hit = NULL;
337 unsigned int n, count = 0;
338 char http_version_str[10];
339 char http_conn_str[20];
340 int http_version_len;
341 char *uri_ptr = NULL;
342 int uri_len = 0, best = 0;
345 static const unsigned char methods[] = {
348 WSI_TOKEN_OPTIONS_URI,
351 WSI_TOKEN_DELETE_URI,
353 WSI_TOKEN_HTTP_COLON_PATH,
356 #if defined(_DEBUG) || defined(LWS_WITH_ACCESS_LOG)
357 static const char * const method_names[] = {
358 "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
365 /* it's not websocket.... shall we accept it as http? */
367 for (n = 0; n < ARRAY_SIZE(methods); n++)
368 if (lws_hdr_total_length(wsi, methods[n]))
371 lwsl_warn("Missing URI in HTTP request\n");
376 lwsl_warn("multiple methods?\n");
380 if (lws_ensure_user_space(wsi))
383 for (n = 0; n < ARRAY_SIZE(methods); n++)
384 if (lws_hdr_total_length(wsi, methods[n])) {
385 uri_ptr = lws_hdr_simple_ptr(wsi, methods[n]);
386 uri_len = lws_hdr_total_length(wsi, methods[n]);
387 lwsl_info("Method: %s request for '%s'\n",
388 method_names[n], uri_ptr);
395 /* we insist on absolute paths */
397 if (uri_ptr[0] != '/') {
398 lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
403 /* HTTP header had a content length? */
405 wsi->u.http.content_length = 0;
406 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) ||
407 lws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI) ||
408 lws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI))
409 wsi->u.http.content_length = 100 * 1024 * 1024;
411 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
412 lws_hdr_copy(wsi, content_length_str,
413 sizeof(content_length_str) - 1,
414 WSI_TOKEN_HTTP_CONTENT_LENGTH);
415 wsi->u.http.content_length = atoi(content_length_str);
418 if (wsi->http2_substream) {
419 wsi->u.http.request_version = HTTP_VERSION_2;
421 /* http_version? Default to 1.0, override with token: */
422 request_version = HTTP_VERSION_1_0;
424 /* Works for single digit HTTP versions. : */
425 http_version_len = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP);
426 if (http_version_len > 7) {
427 lws_hdr_copy(wsi, http_version_str,
428 sizeof(http_version_str) - 1, WSI_TOKEN_HTTP);
429 if (http_version_str[5] == '1' && http_version_str[7] == '1')
430 request_version = HTTP_VERSION_1_1;
432 wsi->u.http.request_version = request_version;
434 /* HTTP/1.1 defaults to "keep-alive", 1.0 to "close" */
435 if (request_version == HTTP_VERSION_1_1)
436 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
438 connection_type = HTTP_CONNECTION_CLOSE;
440 /* Override default if http "Connection:" header: */
441 if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) {
442 lws_hdr_copy(wsi, http_conn_str, sizeof(http_conn_str) - 1,
443 WSI_TOKEN_CONNECTION);
444 http_conn_str[sizeof(http_conn_str) - 1] = '\0';
445 if (!strcasecmp(http_conn_str, "keep-alive"))
446 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
448 if (!strcasecmp(http_conn_str, "close"))
449 connection_type = HTTP_CONNECTION_CLOSE;
451 wsi->u.http.connection_type = connection_type;
454 n = wsi->protocol->callback(wsi, LWS_CALLBACK_FILTER_HTTP_CONNECTION,
455 wsi->user_space, uri_ptr, uri_len);
457 lwsl_info("LWS_CALLBACK_HTTP closing\n");
462 * if there is content supposed to be coming,
463 * put a timeout on it having arrived
465 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
466 wsi->context->timeout_secs);
467 #ifdef LWS_OPENSSL_SUPPORT
468 if (wsi->redirect_to_https) {
470 * we accepted http:// only so we could redirect to
471 * https://, so issue the redirect. Create the redirection
472 * URI from the host: header and ignore the path part
474 unsigned char *start = pt->serv_buf + LWS_PRE, *p = start,
477 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
480 n = sprintf((char *)end, "https://%s/",
481 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
483 n = lws_http_redirect(wsi, end, n, &p, end);
487 return lws_http_transaction_completed(wsi);
491 #ifdef LWS_WITH_ACCESS_LOG
493 * Produce Apache-compatible log string for wsi, like this:
495 * 2.31.234.19 - - [27/Mar/2016:03:22:44 +0800]
496 * "GET /aep-screen.png HTTP/1.1"
497 * 200 152987 "https://libwebsockets.org/index.html"
498 * "Mozilla/5.0 (Macint... Chrome/49.0.2623.87 Safari/537.36"
502 static const char * const hver[] = {
503 "http/1.0", "http/1.1", "http/2"
506 char ads[INET6_ADDRSTRLEN];
508 char ads[INET_ADDRSTRLEN];
513 time_t t = time(NULL);
516 if (wsi->access_log_pending)
519 wsi->access_log.header_log = lws_malloc(l);
523 strftime(da, sizeof(da), "%d/%b/%Y:%H:%M:%S %z", tmp);
525 strcpy(da, "01/Jan/1970:00:00:00 +0000");
527 pa = lws_get_peer_simple(wsi, ads, sizeof(ads));
532 me = method_names[meth];
536 snprintf(wsi->access_log.header_log, l,
537 "%s - - [%s] \"%s %s %s\"",
539 hver[wsi->u.http.request_version]);
541 l = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT);
543 wsi->access_log.user_agent = lws_malloc(l + 2);
544 lws_hdr_copy(wsi, wsi->access_log.user_agent,
545 l + 1, WSI_TOKEN_HTTP_USER_AGENT);
547 wsi->access_log_pending = 1;
551 /* can we serve it from the mount list? */
553 hm = wsi->vhost->mount_list;
555 if (uri_len >= hm->mountpoint_len &&
556 !strncmp(uri_ptr, hm->mountpoint, hm->mountpoint_len) &&
557 (uri_ptr[hm->mountpoint_len] == '\0' ||
558 uri_ptr[hm->mountpoint_len] == '/' ||
559 hm->mountpoint_len == 1)
561 if ((hm->origin_protocol == LWSMPRO_CGI ||
562 lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI)) &&
563 hm->mountpoint_len > best) {
564 best = hm->mountpoint_len;
571 char *s = uri_ptr + hit->mountpoint_len;
573 lwsl_debug("*** hit %d %d %s\n", hit->mountpoint_len,
574 hit->origin_protocol , hit->origin);
577 * if we have a mountpoint like https://xxx.com/yyy
578 * there is an implied / at the end for our purposes since
579 * we can only mount on a "directory".
581 * But if we just go with that, the browser cannot understand
582 * that he is actually looking down one "directory level", so
583 * even though we give him /yyy/abc.html he acts like the
584 * current directory level is /. So relative urls like "x.png"
585 * wrongly look outside the mountpoint.
587 * Therefore if we didn't come in on a url with an explicit
588 * / at the end, we must redirect to add it so the browser
589 * understands he is one "directory level" down.
591 if ((hit->mountpoint_len > 1 || (hit->origin_protocol & 4)) &&
592 (*s != '/' || (hit->origin_protocol & 4)) &&
593 (hit->origin_protocol != LWSMPRO_CGI)) {
594 unsigned char *start = pt->serv_buf + LWS_PRE,
595 *p = start, *end = p + 512;
596 static const char *oprot[] = {
597 "http://", "https://"
600 lwsl_debug("Doing 301 '%s' org %s\n", s, hit->origin);
602 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
605 /* > at start indicates deal with by redirect */
606 if (hit->origin_protocol & 4)
607 n = snprintf((char *)end, 256, "%s%s",
608 oprot[hit->origin_protocol & 1],
611 n = snprintf((char *)end, 256,
613 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST),
616 n = lws_http_redirect(wsi, end, n, &p, end);
620 return lws_http_transaction_completed(wsi);
624 /* did we hit something with a cgi:// origin? */
625 if (hit->origin_protocol == LWSMPRO_CGI) {
626 const char *cmd[] = {
627 NULL, /* replace with cgi path */
630 unsigned char *p, *end, buffer[256];
632 lwsl_debug("%s: cgi\n", __func__);
633 cmd[0] = hit->origin;
636 if (hit->cgi_timeout)
637 n = hit->cgi_timeout;
639 n = lws_cgi(wsi, cmd, hit->mountpoint_len, n,
642 lwsl_err("%s: cgi failed\n");
645 p = buffer + LWS_PRE;
646 end = p + sizeof(buffer) - LWS_PRE;
648 if (lws_add_http_header_status(wsi, 200, &p, end))
650 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
651 (unsigned char *)"close", 5, &p, end))
653 n = lws_write(wsi, buffer + LWS_PRE,
654 p - (buffer + LWS_PRE),
655 LWS_WRITE_HTTP_HEADERS);
662 if (s[0] == '\0' || (n == 1 && s[n - 1] == '/'))
663 s = (char *)hit->def;
667 wsi->cache_secs = hit->cache_max_age;
668 wsi->cache_reuse = hit->cache_reusable;
669 wsi->cache_revalidate = hit->cache_revalidate;
670 wsi->cache_intermediaries = hit->cache_intermediaries;
672 n = lws_http_serve(wsi, s, hit->origin);
674 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
675 wsi->user_space, uri_ptr, uri_len);
678 lwsl_info("LWS_CALLBACK_HTTP closing\n");
687 * If we're not issuing a file, check for content_length or
688 * HTTP keep-alive. No keep-alive header allocation for
689 * ISSUING_FILE, as this uses HTTP/1.0.
691 * In any case, return 0 and let lws_read decide how to
692 * proceed based on state
694 if (wsi->state != LWSS_HTTP_ISSUING_FILE)
695 /* Prepare to read body if we have a content length: */
696 if (wsi->u.http.content_length > 0)
697 wsi->state = LWSS_HTTP_BODY;
702 /* we're closing, losing some rx is OK */
703 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
704 lws_header_table_detach(wsi, 1);
711 lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len)
713 struct lws_context *context = lws_get_context(wsi);
714 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
715 struct _lws_header_related hdr;
716 struct allocated_headers *ah;
717 int protocol_len, n, hit;
718 char protocol_list[128];
719 char protocol_name[32];
722 assert(len < 10000000);
723 assert(wsi->u.hdr.ah);
726 wsi->more_rx_waiting = !!len;
728 if (wsi->mode != LWSCM_HTTP_SERVING &&
729 wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED) {
730 lwsl_err("%s: bad wsi mode %d\n", __func__, wsi->mode);
734 if (lws_parse(wsi, *(*buf)++)) {
735 lwsl_info("lws_parse failed\n");
739 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
742 lwsl_parser("%s: lws_parse sees parsing complete\n", __func__);
743 lwsl_debug("%s: wsi->more_rx_waiting=%d\n", __func__,
744 wsi->more_rx_waiting);
748 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
749 struct lws_vhost *vhost = lws_select_vhost(
750 context, wsi->vhost->listen_port,
751 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
758 if (!wsi->conn_stat_done) {
760 wsi->conn_stat_done = 1;
763 wsi->mode = LWSCM_PRE_WS_SERVING_ACCEPT;
764 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
766 /* is this websocket protocol or normal http 1.0? */
768 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
769 if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
771 wsi->vhost->ws_upgrades++;
772 lwsl_info("Upgrade to ws\n");
776 if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
778 wsi->vhost->http2_upgrades++;
779 lwsl_info("Upgrade to h2c\n");
783 lwsl_err("Unknown upgrade\n");
784 /* dunno what he wanted to upgrade to */
788 /* no upgrade ack... he remained as HTTP */
790 lwsl_info("No upgrade\n");
793 lws_union_transition(wsi, LWSCM_HTTP_SERVING_ACCEPTED);
794 wsi->state = LWSS_HTTP;
795 wsi->u.http.fd = LWS_INVALID_FILE;
797 /* expose it at the same offset as u.hdr */
799 lwsl_debug("%s: wsi %p: ah %p\n", __func__, (void *)wsi,
800 (void *)wsi->u.hdr.ah);
802 n = lws_http_action(wsi);
808 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) {
809 lwsl_err("missing http2_settings\n");
813 lwsl_err("h2c upgrade...\n");
815 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS);
816 /* convert the peer's HTTP-Settings */
817 n = lws_b64_decode_string(p, protocol_list,
818 sizeof(protocol_list));
820 lwsl_parser("HTTP2_SETTINGS too long\n");
824 /* adopt the header info */
828 lws_union_transition(wsi, LWSCM_HTTP2_SERVING);
830 /* http2 union member has http union struct at start */
833 lws_http2_init(&wsi->u.http2.peer_settings);
834 lws_http2_init(&wsi->u.http2.my_settings);
838 lws_http2_interpret_settings_payload(&wsi->u.http2.peer_settings,
839 (unsigned char *)protocol_list, n);
841 strcpy(protocol_list,
842 "HTTP/1.1 101 Switching Protocols\x0d\x0a"
843 "Connection: Upgrade\x0d\x0a"
844 "Upgrade: h2c\x0d\x0a\x0d\x0a");
845 n = lws_issue_raw(wsi, (unsigned char *)protocol_list,
846 strlen(protocol_list));
847 if (n != strlen(protocol_list)) {
848 lwsl_debug("http2 switch: ERROR writing to socket\n");
852 wsi->state = LWSS_HTTP2_AWAIT_CLIENT_PREFACE;
859 lwsl_err("NULL protocol at lws_read\n");
864 * Select the first protocol we support from the list
865 * the client sent us.
867 * Copy it to remove header fragmentation
870 if (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1,
871 WSI_TOKEN_PROTOCOL) < 0) {
872 lwsl_err("protocol list too long");
876 protocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
877 protocol_list[protocol_len] = '\0';
883 while (n < sizeof(protocol_name) - 1 && *p && *p !=',')
884 protocol_name[n++] = *p++;
885 protocol_name[n] = '\0';
889 lwsl_info("checking %s\n", protocol_name);
892 while (wsi->vhost->protocols[n].callback) {
893 if (wsi->vhost->protocols[n].name &&
894 !strcmp(wsi->vhost->protocols[n].name,
896 wsi->protocol = &wsi->vhost->protocols[n];
905 /* we didn't find a protocol he wanted? */
908 if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL)) {
909 lwsl_err("No protocol from \"%s\" supported\n",
914 * some clients only have one protocol and
915 * do not send the protocol list header...
916 * allow it and match to protocol 0
918 lwsl_info("defaulting to prot 0 handler\n");
920 wsi->protocol = &wsi->vhost->protocols[0];
923 /* allocate wsi->user storage */
924 if (lws_ensure_user_space(wsi))
928 * Give the user code a chance to study the request and
929 * have the opportunity to deny it
931 if ((wsi->protocol->callback)(wsi,
932 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
934 lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) {
935 lwsl_warn("User code denied connection\n");
940 * Perform the handshake according to the protocol version the
944 switch (wsi->ietf_spec_revision) {
946 lwsl_parser("lws_parse calling handshake_04\n");
947 if (handshake_0405(context, wsi)) {
948 lwsl_info("hs0405 has failed the connection\n");
954 lwsl_warn("Unknown client spec version %d\n",
955 wsi->ietf_spec_revision);
960 * stitch protocol choice into the vh protocol linked list
961 * We always insert ourselves at the start of the list
966 //lwsl_err("%s: pre insert vhost start wsi %p, that wsi prev == %p\n",
968 // wsi->vhost->same_vh_protocol_list[n],
969 // wsi->same_vh_protocol_prev);
970 wsi->same_vh_protocol_prev = /* guy who points to us */
971 &wsi->vhost->same_vh_protocol_list[n];
972 wsi->same_vh_protocol_next = /* old first guy is our next */
973 wsi->vhost->same_vh_protocol_list[n];
974 /* we become the new first guy */
975 wsi->vhost->same_vh_protocol_list[n] = wsi;
977 if (wsi->same_vh_protocol_next)
978 /* old first guy points back to us now */
979 wsi->same_vh_protocol_next->same_vh_protocol_prev =
980 &wsi->same_vh_protocol_next;
984 /* we are upgrading to ws, so http/1.1 and keepalive +
985 * pipelined header considerations about keeping the ah around
986 * no longer apply. However it's common for the first ws
987 * protocol data to have been coalesced with the browser
988 * upgrade request and to already be in the ah rx buffer.
991 lwsl_info("%s: %p: inheriting ah in ws mode (rxpos:%d, rxlen:%d)\n",
992 __func__, wsi, wsi->u.hdr.ah->rxpos,
993 wsi->u.hdr.ah->rxlen);
997 lws_union_transition(wsi, LWSCM_WS_SERVING);
999 * first service is WS mode will notice this, use the RX and
1000 * then detach the ah (caution: we are not in u.hdr union
1001 * mode any more then... ah_temp member is at start the same
1004 * Because rxpos/rxlen shows something in the ah, we will get
1005 * service guaranteed next time around the event loop
1007 * All union members begin with hdr, so we can use it even
1008 * though we transitioned to ws union mode (the ah detach
1009 * code uses it anyway).
1015 * create the frame buffer for this connection according to the
1016 * size mentioned in the protocol definition. If 0 there, use
1017 * a big default for compatibility
1020 n = wsi->protocol->rx_buffer_size;
1022 n = LWS_MAX_SOCKET_IO_BUF;
1024 wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
1025 if (!wsi->u.ws.rx_ubuf) {
1026 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
1029 wsi->u.ws.rx_ubuf_alloc = n;
1030 lwsl_info("Allocating RX buffer %d\n", n);
1032 if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF,
1033 (const char *)&n, sizeof n)) {
1034 lwsl_warn("Failed to set SNDBUF to %d", n);
1038 lwsl_parser("accepted v%02d connection\n",
1039 wsi->ietf_spec_revision);
1042 } /* while all chars are handled */
1047 /* drop the header info */
1048 /* we're closing, losing some rx is OK */
1049 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1050 lws_header_table_detach(wsi, 1);
1056 lws_get_idlest_tsi(struct lws_context *context)
1058 unsigned int lowest = ~0;
1059 int n = 0, hit = -1;
1061 for (; n < context->count_threads; n++) {
1062 if ((unsigned int)context->pt[n].fds_count !=
1063 context->fd_limit_per_thread - 1 &&
1064 (unsigned int)context->pt[n].fds_count < lowest) {
1065 lowest = context->pt[n].fds_count;
1074 lws_create_new_server_wsi(struct lws_vhost *vhost)
1076 struct lws *new_wsi;
1077 int n = lws_get_idlest_tsi(vhost->context);
1080 lwsl_err("no space for new conn\n");
1084 new_wsi = lws_zalloc(sizeof(struct lws));
1085 if (new_wsi == NULL) {
1086 lwsl_err("Out of memory for new connection\n");
1091 lwsl_info("Accepted %p to tsi %d\n", new_wsi, new_wsi->tsi);
1093 new_wsi->vhost = vhost;
1094 new_wsi->context = vhost->context;
1095 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1096 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1098 /* intialize the instance struct */
1100 new_wsi->state = LWSS_HTTP;
1101 new_wsi->mode = LWSCM_HTTP_SERVING;
1102 new_wsi->hdr_parsing_completed = 0;
1104 #ifdef LWS_OPENSSL_SUPPORT
1105 new_wsi->use_ssl = LWS_SSL_ENABLED(vhost);
1109 * these can only be set once the protocol is known
1110 * we set an unestablished connection's protocol pointer
1111 * to the start of the supported list, so it can look
1112 * for matching ones during the handshake
1114 new_wsi->protocol = vhost->protocols;
1115 new_wsi->user_space = NULL;
1116 new_wsi->ietf_spec_revision = 0;
1117 new_wsi->sock = LWS_SOCK_INVALID;
1118 vhost->context->count_wsi_allocated++;
1121 * outermost create notification for wsi
1122 * no user_space because no protocol selection
1124 vhost->protocols[0].callback(new_wsi, LWS_CALLBACK_WSI_CREATE,
1131 * lws_http_transaction_completed() - wait for new http transaction or close
1132 * @wsi: websocket connection
1134 * Returns 1 if the HTTP connection must close now
1135 * Returns 0 and resets connection to wait for new HTTP header /
1136 * transaction if possible
1139 LWS_VISIBLE int LWS_WARN_UNUSED_RESULT
1140 lws_http_transaction_completed(struct lws *wsi)
1142 int n = NO_PENDING_TIMEOUT;
1144 lws_access_log(wsi);
1146 lwsl_debug("%s: wsi %p\n", __func__, wsi);
1147 /* if we can't go back to accept new headers, drop the connection */
1148 if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
1149 lwsl_info("%s: %p: close connection\n", __func__, wsi);
1153 /* otherwise set ourselves up ready to go again */
1154 wsi->state = LWSS_HTTP;
1155 wsi->mode = LWSCM_HTTP_SERVING;
1156 wsi->u.http.content_length = 0;
1157 wsi->hdr_parsing_completed = 0;
1158 #ifdef LWS_WITH_ACCESS_LOG
1159 wsi->access_log.sent = 0;
1162 if (wsi->vhost->keepalive_timeout)
1163 n = PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE;
1164 lws_set_timeout(wsi, n, wsi->vhost->keepalive_timeout);
1167 * We already know we are on http1.1 / keepalive and the next thing
1168 * coming will be another header set.
1170 * If there is no pending rx and we still have the ah, drop it and
1171 * reacquire a new ah when the new headers start to arrive. (Otherwise
1172 * we needlessly hog an ah indefinitely.)
1174 * However if there is pending rx and we know from the keepalive state
1175 * that is already at least the start of another header set, simply
1176 * reset the existing header table and keep it.
1178 if (wsi->u.hdr.ah) {
1179 lwsl_info("%s: wsi->more_rx_waiting=%d\n", __func__,
1180 wsi->more_rx_waiting);
1182 if (!wsi->more_rx_waiting) {
1183 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1184 lws_header_table_detach(wsi, 1);
1186 lws_header_table_reset(wsi, 1);
1189 /* If we're (re)starting on headers, need other implied init */
1190 wsi->u.hdr.ues = URIES_IDLE;
1192 lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
1198 lws_adopt_socket_vhost(struct lws_vhost *vh, lws_sockfd_type accept_fd)
1200 struct lws_context *context = vh->context;
1201 struct lws *new_wsi = lws_create_new_server_wsi(vh);
1204 compatible_close(accept_fd);
1208 lwsl_info("%s: new wsi %p, sockfd %d\n", __func__, new_wsi, accept_fd);
1210 new_wsi->sock = accept_fd;
1212 /* the transport is accepted... give him time to negotiate */
1213 lws_set_timeout(new_wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
1214 context->timeout_secs);
1217 mbed3_tcp_stream_accept(accept_fd, new_wsi);
1221 * A new connection was accepted. Give the user a chance to
1222 * set properties of the newly created wsi. There's no protocol
1223 * selected yet so we issue this to protocols[0]
1225 if ((context->vhost_list->protocols[0].callback)(new_wsi,
1226 LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED, NULL, NULL, 0)) {
1227 compatible_close(new_wsi->sock);
1232 lws_libev_accept(new_wsi, new_wsi->sock);
1233 lws_libuv_accept(new_wsi, new_wsi->sock);
1235 if (!LWS_SSL_ENABLED(new_wsi->vhost)) {
1236 if (insert_wsi_socket_into_fds(context, new_wsi)) {
1237 lwsl_err("%s: fail inserting socket\n", __func__);
1241 new_wsi->mode = LWSCM_SSL_INIT;
1242 if (lws_server_socket_service_ssl(new_wsi, accept_fd)) {
1243 lwsl_err("%s: fail ssl negotiation\n", __func__);
1248 if (!lws_header_table_attach(new_wsi, 0))
1249 lwsl_debug("Attached ah immediately\n");
1254 lws_close_free_wsi(new_wsi, LWS_CLOSE_STATUS_NOSTATUS);
1260 * lws_adopt_socket() - adopt foreign socket as if listen socket accepted it
1261 * @context: lws context
1262 * @accept_fd: fd of already-accepted socket to adopt
1264 * Either returns new wsi bound to accept_fd, or closes accept_fd and
1265 * returns NULL, having cleaned up any new wsi pieces.
1267 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
1268 * to ws or just serve http.
1271 LWS_VISIBLE struct lws *
1272 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd)
1274 return lws_adopt_socket_vhost(context->vhost_list, accept_fd);
1279 * lws_adopt_socket_readbuf() - adopt foreign socket and first rx as if listen socket accepted it
1280 * @context: lws context
1281 * @accept_fd: fd of already-accepted socket to adopt
1282 * @readbuf: NULL or pointer to data that must be drained before reading from
1284 * @len: The length of the data held at @readbuf
1286 * Either returns new wsi bound to accept_fd, or closes accept_fd and
1287 * returns NULL, having cleaned up any new wsi pieces.
1289 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
1290 * to ws or just serve http.
1292 * If your external code did not already read from the socket, you can use
1293 * lws_adopt_socket() instead.
1295 * This api is guaranteed to use the data at @readbuf first, before reading from
1298 * @readbuf is limited to the size of the ah rx buf, currently 2048 bytes.
1301 LWS_VISIBLE LWS_EXTERN struct lws *
1302 lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
1303 const char *readbuf, size_t len)
1305 struct lws *wsi = lws_adopt_socket(context, accept_fd);
1306 struct lws_context_per_thread *pt;
1307 struct allocated_headers *ah;
1308 struct lws_pollfd *pfd;
1316 if (len > sizeof(ah->rx)) {
1317 lwsl_err("%s: rx in too big\n", __func__);
1321 * we can't process the initial read data until we can attach an ah.
1323 * if one is available, get it and place the data in his ah rxbuf...
1324 * wsi with ah that have pending rxbuf get auto-POLLIN service.
1326 * no autoservice because we didn't get a chance to attach the
1327 * readbuf data to wsi or ah yet, and we will do it next if we get
1330 if (wsi->u.hdr.ah || !lws_header_table_attach(wsi, 0)) {
1332 memcpy(ah->rx, readbuf, len);
1336 lwsl_notice("%s: calling service on readbuf ah\n", __func__);
1337 pt = &context->pt[(int)wsi->tsi];
1339 /* unlike a normal connect, we have the headers already
1340 * (or the first part of them anyway).
1341 * libuv won't come back and service us without a network
1342 * event, so we need to do the header service right here.
1344 pfd = &pt->fds[wsi->position_in_fds_table];
1345 pfd->revents |= LWS_POLLIN;
1346 lwsl_err("%s: calling service\n", __func__);
1347 if (lws_service_fd_tsi(context, pfd, wsi->tsi))
1348 /* service closed us */
1353 lwsl_err("%s: deferring handling ah\n", __func__);
1355 * hum if no ah came, we are on the wait list and must defer
1356 * dealing with this until the ah arrives.
1358 * later successful lws_header_table_attach() will apply the
1359 * below to the rx buffer (via lws_header_table_reset()).
1361 wsi->u.hdr.preamble_rx = lws_malloc(len);
1362 memcpy(wsi->u.hdr.preamble_rx, readbuf, len);
1363 wsi->u.hdr.preamble_rx_len = len;
1368 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1374 lws_server_socket_service(struct lws_context *context, struct lws *wsi,
1375 struct lws_pollfd *pollfd)
1377 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1378 lws_sockfd_type accept_fd = LWS_SOCK_INVALID;
1379 struct allocated_headers *ah;
1381 struct sockaddr_in cli_addr;
1386 switch (wsi->mode) {
1388 case LWSCM_HTTP_SERVING:
1389 case LWSCM_HTTP_SERVING_ACCEPTED:
1390 case LWSCM_HTTP2_SERVING:
1392 /* handle http headers coming in */
1394 /* pending truncated sends have uber priority */
1396 if (wsi->trunc_len) {
1397 if (!(pollfd->revents & LWS_POLLOUT))
1400 if (lws_issue_raw(wsi, wsi->trunc_alloc +
1402 wsi->trunc_len) < 0)
1405 * we can't afford to allow input processing to send
1406 * something new, so spin around he event loop until
1407 * he doesn't have any partials
1412 /* any incoming data ready? */
1414 if (!(pollfd->revents & pollfd->events & LWS_POLLIN))
1417 /* these states imply we MUST have an ah attached */
1419 if (wsi->state == LWSS_HTTP ||
1420 wsi->state == LWSS_HTTP_ISSUING_FILE ||
1421 wsi->state == LWSS_HTTP_HEADERS) {
1423 /* no autoservice beacuse we will do it next */
1424 if (lws_header_table_attach(wsi, 0))
1429 lwsl_debug("%s: %p: rxpos:%d rxlen:%d\n", __func__, wsi,
1430 ah->rxpos, ah->rxlen);
1432 /* if nothing in ah rx buffer, get some fresh rx */
1433 if (ah->rxpos == ah->rxlen) {
1434 ah->rxlen = lws_ssl_capable_read(wsi, ah->rx,
1437 lwsl_debug("%s: wsi %p, ah->rxlen = %d\r\n",
1438 __func__, wsi, ah->rxlen);
1439 switch (ah->rxlen) {
1441 lwsl_info("%s: read 0 len\n", __func__);
1442 /* lwsl_info(" state=%d\n", wsi->state); */
1443 // if (!wsi->hdr_parsing_completed)
1444 // lws_header_table_detach(wsi);
1446 case LWS_SSL_CAPABLE_ERROR:
1448 case LWS_SSL_CAPABLE_MORE_SERVICE:
1449 ah->rxlen = ah->rxpos = 0;
1453 assert(ah->rxpos != ah->rxlen && ah->rxlen);
1454 /* just ignore incoming if waiting for close */
1455 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
1456 n = lws_read(wsi, ah->rx + ah->rxpos,
1457 ah->rxlen - ah->rxpos);
1458 if (n < 0) /* we closed wsi */
1460 if (wsi->u.hdr.ah) {
1461 if ( wsi->u.hdr.ah->rxlen)
1462 wsi->u.hdr.ah->rxpos += n;
1464 if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen &&
1465 (wsi->mode != LWSCM_HTTP_SERVING &&
1466 wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED &&
1467 wsi->mode != LWSCM_HTTP2_SERVING))
1468 lws_header_table_detach(wsi, 1);
1476 len = lws_ssl_capable_read(wsi, pt->serv_buf,
1477 LWS_MAX_SOCKET_IO_BUF);
1478 lwsl_debug("%s: wsi %p read %d\r\n", __func__, wsi, len);
1481 lwsl_info("%s: read 0 len\n", __func__);
1482 /* lwsl_info(" state=%d\n", wsi->state); */
1483 // if (!wsi->hdr_parsing_completed)
1484 // lws_header_table_detach(wsi);
1486 case LWS_SSL_CAPABLE_ERROR:
1488 case LWS_SSL_CAPABLE_MORE_SERVICE:
1492 /* just ignore incoming if waiting for close */
1493 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
1495 * hm this may want to send
1496 * (via HTTP callback for example)
1498 n = lws_read(wsi, pt->serv_buf, len);
1499 if (n < 0) /* we closed wsi */
1501 /* hum he may have used up the
1502 * writability above */
1507 /* this handles POLLOUT for http serving fragments */
1509 if (!(pollfd->revents & LWS_POLLOUT))
1513 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
1514 lwsl_notice("%s a\n", __func__);
1518 if (!wsi->hdr_parsing_completed)
1521 if (wsi->state != LWSS_HTTP_ISSUING_FILE) {
1522 n = user_callback_handle_rxflow(wsi->protocol->callback,
1523 wsi, LWS_CALLBACK_HTTP_WRITEABLE,
1524 wsi->user_space, NULL, 0);
1526 lwsl_info("writeable_fail\n");
1532 /* >0 == completion, <0 == error */
1533 n = lws_serve_http_file_fragment(wsi);
1534 if (n < 0 || (n > 0 && lws_http_transaction_completed(wsi))) {
1535 lwsl_info("completed\n");
1540 case LWSCM_SERVER_LISTENER:
1543 /* pollin means a client has connected to us then */
1546 if (!(pollfd->revents & LWS_POLLIN) || !(pollfd->events & LWS_POLLIN))
1549 /* listen socket got an unencrypted connection... */
1551 clilen = sizeof(cli_addr);
1552 lws_latency_pre(context, wsi);
1553 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1555 lws_latency(context, wsi, "listener accept", accept_fd,
1557 if (accept_fd < 0) {
1558 if (LWS_ERRNO == LWS_EAGAIN ||
1559 LWS_ERRNO == LWS_EWOULDBLOCK) {
1560 lwsl_err("accept asks to try again\n");
1563 lwsl_err("ERROR on accept: %s\n", strerror(LWS_ERRNO));
1567 lws_plat_set_socket_options(wsi->vhost, accept_fd);
1569 lwsl_debug("accepted new conn port %u on fd=%d\n",
1570 ntohs(cli_addr.sin_port), accept_fd);
1573 /* not very beautiful... */
1574 accept_fd = (lws_sockfd_type)pollfd;
1577 * look at who we connected to and give user code a chance
1578 * to reject based on client IP. There's no protocol selected
1579 * yet so we issue this to protocols[0]
1581 if ((wsi->vhost->protocols[0].callback)(wsi,
1582 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
1583 NULL, (void *)(long)accept_fd, 0)) {
1584 lwsl_debug("Callback denied network connection\n");
1585 compatible_close(accept_fd);
1589 if (!lws_adopt_socket_vhost(wsi->vhost, accept_fd))
1590 /* already closed cleanly as necessary */
1594 } while (pt->fds_count < context->fd_limit_per_thread - 1 &&
1595 lws_poll_listen_fd(&pt->fds[wsi->position_in_fds_table]) > 0);
1603 if (!lws_server_socket_service_ssl(wsi, accept_fd))
1607 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1613 * lws_serve_http_file() - Send a file back to the client using http
1614 * @wsi: Websocket instance (available from user callback)
1615 * @file: The file to issue over http
1616 * @content_type: The http content type, eg, text/html
1617 * @other_headers: NULL or pointer to header string
1618 * @other_headers_len: length of the other headers if non-NULL
1620 * This function is intended to be called from the callback in response
1621 * to http requests from the client. It allows the callback to issue
1622 * local files down the http link in a single step.
1624 * Returning <0 indicates error and the wsi should be closed. Returning
1625 * >0 indicates the file was completely sent and
1626 * lws_http_transaction_completed() called on the wsi (and close if != 0)
1627 * ==0 indicates the file transfer is started and needs more service later,
1628 * the wsi should be left alone.
1632 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
1633 const char *other_headers, int other_headers_len)
1635 static const char * const intermediates[] = { "private", "public" };
1636 struct lws_context *context = lws_get_context(wsi);
1637 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1638 char cache_control[50], *cc = "no-store";
1639 unsigned char *response = pt->serv_buf + LWS_PRE;
1640 unsigned char *p = response;
1641 unsigned char *end = p + LWS_MAX_SOCKET_IO_BUF - LWS_PRE;
1642 int ret = 0, cclen = 8;
1644 wsi->u.http.fd = lws_plat_file_open(wsi, file, &wsi->u.http.filelen,
1647 if (wsi->u.http.fd == LWS_INVALID_FILE) {
1648 lwsl_err("Unable to open '%s'\n", file);
1649 lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
1654 if (lws_add_http_header_status(wsi, 200, &p, end))
1656 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
1657 (unsigned char *)content_type,
1658 strlen(content_type), &p, end))
1660 if (lws_add_http_header_content_length(wsi, wsi->u.http.filelen, &p, end))
1663 if (wsi->cache_secs && wsi->cache_reuse) {
1664 if (wsi->cache_revalidate) {
1666 cclen = sprintf(cache_control, "%s max-age: %u",
1667 intermediates[wsi->cache_intermediaries],
1675 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CACHE_CONTROL,
1676 (unsigned char *)cc, cclen, &p, end))
1679 if (other_headers) {
1680 if ((end - p) < other_headers_len)
1682 memcpy(p, other_headers, other_headers_len);
1683 p += other_headers_len;
1686 if (lws_finalize_http_header(wsi, &p, end))
1689 ret = lws_write(wsi, response, p - response, LWS_WRITE_HTTP_HEADERS);
1690 if (ret != (p - response)) {
1691 lwsl_err("_write returned %d from %d\n", ret, (p - response));
1695 wsi->u.http.filepos = 0;
1696 wsi->state = LWSS_HTTP_ISSUING_FILE;
1698 return lws_serve_http_file_fragment(wsi);
1702 lws_interpret_incoming_packet(struct lws *wsi, unsigned char **buf, size_t len)
1706 lwsl_parser("%s: received %d byte packet\n", __func__, (int)len);
1708 lwsl_hexdump(*buf, len);
1711 /* let the rx protocol state machine have as much as it needs */
1715 * we were accepting input but now we stopped doing so
1717 if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
1718 lws_rxflow_cache(wsi, *buf, 0, len);
1719 lwsl_parser("%s: cached %d\n", __func__, len);
1723 if (wsi->u.ws.rx_draining_ext) {
1724 m = lws_rx_sm(wsi, 0);
1730 /* account for what we're using in rxflow buffer */
1731 if (wsi->rxflow_buffer)
1734 /* consume payload bytes efficiently */
1735 if (wsi->lws_rx_parse_state ==
1736 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED)
1737 lws_payload_until_length_exhausted(wsi, buf, &len);
1739 /* process the byte */
1740 m = lws_rx_sm(wsi, *(*buf)++);
1746 lwsl_parser("%s: exit with %d unused\n", __func__, (int)len);
1752 lws_server_get_canonical_hostname(struct lws_context *context,
1753 struct lws_context_creation_info *info)
1755 if (lws_check_opt(info->options, LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME))
1758 /* find canonical hostname */
1759 gethostname((char *)context->canonical_hostname,
1760 sizeof(context->canonical_hostname) - 1);
1762 lwsl_notice(" canonical_hostname = %s\n", context->canonical_hostname);