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(vhost->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 - 3], ".gz"))
218 return "application/gzip";
220 if (!strcmp(&file[n - 4], ".JPG"))
223 if (!strcmp(&file[n - 5], ".html"))
226 if (!strcmp(&file[n - 4], ".css"))
229 if (!strcmp(&file[n - 4], ".txt"))
232 if (!strcmp(&file[n - 4], ".ttf"))
233 return "application/x-font-ttf";
235 if (!strcmp(&file[n - 5], ".woff"))
236 return "application/font-woff";
238 if (!strcmp(&file[n - 4], ".xml"))
239 return "application/xml";
244 int lws_http_serve(struct lws *wsi, char *uri, const char *origin)
246 const char *mimetype;
250 char path[256], sym[256];
251 unsigned char *p = (unsigned char *)sym + 32 + LWS_PRE, *start = p;
252 unsigned char *end = p + sizeof(sym) - 32 - LWS_PRE;
258 snprintf(path, sizeof(path) - 1, "%s/%s", origin, uri);
264 if (stat(path, &st)) {
265 lwsl_info("unable to stat %s\n", path);
269 lwsl_debug(" %s mode %d\n", path, S_IFMT & st.st_mode);
271 if ((S_IFMT & st.st_mode) == S_IFLNK) {
272 len = readlink(path, sym, sizeof(sym) - 1);
274 lwsl_err("Failed to read link %s\n", path);
278 lwsl_debug("symlink %s -> %s\n", path, sym);
279 snprintf(path, sizeof(path) - 1, "%s", sym);
282 if ((S_IFMT & st.st_mode) == S_IFDIR) {
283 lwsl_debug("default filename append to dir\n");
284 snprintf(path, sizeof(path) - 1, "%s/%s/index.html",
288 } while ((S_IFMT & st.st_mode) != S_IFREG && spin < 5);
291 lwsl_err("symlink loop %s \n", path);
293 n = sprintf(sym, "%08lX%08lX", (unsigned long)st.st_size,
294 (unsigned long)st.st_mtime);
296 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_NONE_MATCH)) {
298 * he thinks he has some version of it already,
299 * check if the tag matches
301 if (!strcmp(sym, lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_IF_NONE_MATCH))) {
303 lwsl_debug("%s: ETAG match %s %s\n", __func__,
306 /* we don't need to send the payload */
307 if (lws_add_http_header_status(wsi, 304, &p, end))
309 if (lws_add_http_header_by_token(wsi,
311 (unsigned char *)sym, n, &p, end))
313 if (lws_finalize_http_header(wsi, &p, end))
316 n = lws_write(wsi, start, p - start,
317 LWS_WRITE_HTTP_HEADERS);
318 if (n != (p - start)) {
319 lwsl_err("_write returned %d from %d\n", n, p - start);
323 return lws_http_transaction_completed(wsi);
327 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ETAG,
328 (unsigned char *)sym, n, &p, end))
332 mimetype = get_mimetype(path);
334 lwsl_err("unknown mimetype for %s", path);
338 n = lws_serve_http_file(wsi, path, mimetype, (char *)start, p - start);
340 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
341 return -1; /* error or can't reuse connection: close the socket */
350 lws_http_action(struct lws *wsi)
352 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
353 enum http_connection_type connection_type;
354 enum http_version request_version;
355 char content_length_str[32];
356 const struct lws_http_mount *hm, *hit = NULL;
357 unsigned int n, count = 0;
358 char http_version_str[10];
359 char http_conn_str[20];
360 int http_version_len;
361 char *uri_ptr = NULL;
362 int uri_len = 0, best = 0;
365 static const unsigned char methods[] = {
368 WSI_TOKEN_OPTIONS_URI,
371 WSI_TOKEN_DELETE_URI,
373 WSI_TOKEN_HTTP_COLON_PATH,
376 #if defined(_DEBUG) || defined(LWS_WITH_ACCESS_LOG)
377 static const char * const method_names[] = {
378 "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
385 /* it's not websocket.... shall we accept it as http? */
387 for (n = 0; n < ARRAY_SIZE(methods); n++)
388 if (lws_hdr_total_length(wsi, methods[n]))
391 lwsl_warn("Missing URI in HTTP request\n");
396 lwsl_warn("multiple methods?\n");
400 if (lws_ensure_user_space(wsi))
403 for (n = 0; n < ARRAY_SIZE(methods); n++)
404 if (lws_hdr_total_length(wsi, methods[n])) {
405 uri_ptr = lws_hdr_simple_ptr(wsi, methods[n]);
406 uri_len = lws_hdr_total_length(wsi, methods[n]);
407 lwsl_info("Method: %s request for '%s'\n",
408 method_names[n], uri_ptr);
415 /* we insist on absolute paths */
417 if (uri_ptr[0] != '/') {
418 lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
423 /* HTTP header had a content length? */
425 wsi->u.http.content_length = 0;
426 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) ||
427 lws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI) ||
428 lws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI))
429 wsi->u.http.content_length = 100 * 1024 * 1024;
431 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
432 lws_hdr_copy(wsi, content_length_str,
433 sizeof(content_length_str) - 1,
434 WSI_TOKEN_HTTP_CONTENT_LENGTH);
435 wsi->u.http.content_length = atoi(content_length_str);
438 if (wsi->http2_substream) {
439 wsi->u.http.request_version = HTTP_VERSION_2;
441 /* http_version? Default to 1.0, override with token: */
442 request_version = HTTP_VERSION_1_0;
444 /* Works for single digit HTTP versions. : */
445 http_version_len = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP);
446 if (http_version_len > 7) {
447 lws_hdr_copy(wsi, http_version_str,
448 sizeof(http_version_str) - 1, WSI_TOKEN_HTTP);
449 if (http_version_str[5] == '1' && http_version_str[7] == '1')
450 request_version = HTTP_VERSION_1_1;
452 wsi->u.http.request_version = request_version;
454 /* HTTP/1.1 defaults to "keep-alive", 1.0 to "close" */
455 if (request_version == HTTP_VERSION_1_1)
456 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
458 connection_type = HTTP_CONNECTION_CLOSE;
460 /* Override default if http "Connection:" header: */
461 if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) {
462 lws_hdr_copy(wsi, http_conn_str, sizeof(http_conn_str) - 1,
463 WSI_TOKEN_CONNECTION);
464 http_conn_str[sizeof(http_conn_str) - 1] = '\0';
465 if (!strcasecmp(http_conn_str, "keep-alive"))
466 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
468 if (!strcasecmp(http_conn_str, "close"))
469 connection_type = HTTP_CONNECTION_CLOSE;
471 wsi->u.http.connection_type = connection_type;
474 n = wsi->protocol->callback(wsi, LWS_CALLBACK_FILTER_HTTP_CONNECTION,
475 wsi->user_space, uri_ptr, uri_len);
477 lwsl_info("LWS_CALLBACK_HTTP closing\n");
482 * if there is content supposed to be coming,
483 * put a timeout on it having arrived
485 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
486 wsi->context->timeout_secs);
487 #ifdef LWS_OPENSSL_SUPPORT
488 if (wsi->redirect_to_https) {
490 * we accepted http:// only so we could redirect to
491 * https://, so issue the redirect. Create the redirection
492 * URI from the host: header and ignore the path part
494 unsigned char *start = pt->serv_buf + LWS_PRE, *p = start,
497 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
500 n = sprintf((char *)end, "https://%s/",
501 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
503 n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
508 return lws_http_transaction_completed(wsi);
512 #ifdef LWS_WITH_ACCESS_LOG
514 * Produce Apache-compatible log string for wsi, like this:
516 * 2.31.234.19 - - [27/Mar/2016:03:22:44 +0800]
517 * "GET /aep-screen.png HTTP/1.1"
518 * 200 152987 "https://libwebsockets.org/index.html"
519 * "Mozilla/5.0 (Macint... Chrome/49.0.2623.87 Safari/537.36"
523 static const char * const hver[] = {
524 "http/1.0", "http/1.1", "http/2"
527 char ads[INET6_ADDRSTRLEN];
529 char ads[INET_ADDRSTRLEN];
534 time_t t = time(NULL);
537 if (wsi->access_log_pending)
540 wsi->access_log.header_log = lws_malloc(l);
544 strftime(da, sizeof(da), "%d/%b/%Y:%H:%M:%S %z", tmp);
546 strcpy(da, "01/Jan/1970:00:00:00 +0000");
548 pa = lws_get_peer_simple(wsi, ads, sizeof(ads));
553 me = method_names[meth];
557 snprintf(wsi->access_log.header_log, l,
558 "%s - - [%s] \"%s %s %s\"",
560 hver[wsi->u.http.request_version]);
562 l = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT);
564 wsi->access_log.user_agent = lws_malloc(l + 2);
565 lws_hdr_copy(wsi, wsi->access_log.user_agent,
566 l + 1, WSI_TOKEN_HTTP_USER_AGENT);
568 wsi->access_log_pending = 1;
572 /* can we serve it from the mount list? */
574 hm = wsi->vhost->mount_list;
576 if (uri_len >= hm->mountpoint_len &&
577 !strncmp(uri_ptr, hm->mountpoint, hm->mountpoint_len) &&
578 (uri_ptr[hm->mountpoint_len] == '\0' ||
579 uri_ptr[hm->mountpoint_len] == '/' ||
580 hm->mountpoint_len == 1)
582 if ((hm->origin_protocol == LWSMPRO_CGI ||
583 lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI)) &&
584 hm->mountpoint_len > best) {
585 best = hm->mountpoint_len;
592 char *s = uri_ptr + hit->mountpoint_len;
594 lwsl_debug("*** hit %d %d %s\n", hit->mountpoint_len,
595 hit->origin_protocol , hit->origin);
598 * if we have a mountpoint like https://xxx.com/yyy
599 * there is an implied / at the end for our purposes since
600 * we can only mount on a "directory".
602 * But if we just go with that, the browser cannot understand
603 * that he is actually looking down one "directory level", so
604 * even though we give him /yyy/abc.html he acts like the
605 * current directory level is /. So relative urls like "x.png"
606 * wrongly look outside the mountpoint.
608 * Therefore if we didn't come in on a url with an explicit
609 * / at the end, we must redirect to add it so the browser
610 * understands he is one "directory level" down.
612 if ((hit->mountpoint_len > 1 || (hit->origin_protocol & 4)) &&
613 (*s != '/' || (hit->origin_protocol & 4)) &&
614 (hit->origin_protocol != LWSMPRO_CGI)) {
615 unsigned char *start = pt->serv_buf + LWS_PRE,
616 *p = start, *end = p + 512;
617 static const char *oprot[] = {
618 "http://", "https://"
621 lwsl_debug("Doing 301 '%s' org %s\n", s, hit->origin);
623 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
626 /* > at start indicates deal with by redirect */
627 if (hit->origin_protocol & 4)
628 n = snprintf((char *)end, 256, "%s%s",
629 oprot[hit->origin_protocol & 1],
632 n = snprintf((char *)end, 256,
634 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST),
637 n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
642 return lws_http_transaction_completed(wsi);
646 /* did we hit something with a cgi:// origin? */
647 if (hit->origin_protocol == LWSMPRO_CGI) {
648 const char *cmd[] = {
649 NULL, /* replace with cgi path */
652 unsigned char *p, *end, buffer[256];
654 lwsl_debug("%s: cgi\n", __func__);
655 cmd[0] = hit->origin;
658 if (hit->cgi_timeout)
659 n = hit->cgi_timeout;
661 n = lws_cgi(wsi, cmd, hit->mountpoint_len, n,
664 lwsl_err("%s: cgi failed\n");
667 p = buffer + LWS_PRE;
668 end = p + sizeof(buffer) - LWS_PRE;
670 if (lws_add_http_header_status(wsi, 200, &p, end))
672 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
673 (unsigned char *)"close", 5, &p, end))
675 n = lws_write(wsi, buffer + LWS_PRE,
676 p - (buffer + LWS_PRE),
677 LWS_WRITE_HTTP_HEADERS);
684 if (s[0] == '\0' || (n == 1 && s[n - 1] == '/'))
685 s = (char *)hit->def;
689 wsi->cache_secs = hit->cache_max_age;
690 wsi->cache_reuse = hit->cache_reusable;
691 wsi->cache_revalidate = hit->cache_revalidate;
692 wsi->cache_intermediaries = hit->cache_intermediaries;
694 n = lws_http_serve(wsi, s, hit->origin);
697 * lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
699 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
700 wsi->user_space, uri_ptr, uri_len);
703 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
704 wsi->user_space, uri_ptr, uri_len);
707 lwsl_info("LWS_CALLBACK_HTTP closing\n");
716 * If we're not issuing a file, check for content_length or
717 * HTTP keep-alive. No keep-alive header allocation for
718 * ISSUING_FILE, as this uses HTTP/1.0.
720 * In any case, return 0 and let lws_read decide how to
721 * proceed based on state
723 if (wsi->state != LWSS_HTTP_ISSUING_FILE)
724 /* Prepare to read body if we have a content length: */
725 if (wsi->u.http.content_length > 0)
726 wsi->state = LWSS_HTTP_BODY;
731 /* we're closing, losing some rx is OK */
732 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
733 lws_header_table_detach(wsi, 1);
740 lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len)
742 struct lws_context *context = lws_get_context(wsi);
743 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
744 struct _lws_header_related hdr;
745 struct allocated_headers *ah;
746 int protocol_len, n, hit;
747 char protocol_list[128];
748 char protocol_name[32];
751 assert(len < 10000000);
752 assert(wsi->u.hdr.ah);
755 wsi->more_rx_waiting = !!len;
757 if (wsi->mode != LWSCM_HTTP_SERVING &&
758 wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED) {
759 lwsl_err("%s: bad wsi mode %d\n", __func__, wsi->mode);
763 if (lws_parse(wsi, *(*buf)++)) {
764 lwsl_info("lws_parse failed\n");
768 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
771 lwsl_parser("%s: lws_parse sees parsing complete\n", __func__);
772 lwsl_debug("%s: wsi->more_rx_waiting=%d\n", __func__,
773 wsi->more_rx_waiting);
777 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
778 struct lws_vhost *vhost = lws_select_vhost(
779 context, wsi->vhost->listen_port,
780 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
787 if (!wsi->conn_stat_done) {
789 wsi->conn_stat_done = 1;
792 wsi->mode = LWSCM_PRE_WS_SERVING_ACCEPT;
793 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
795 /* is this websocket protocol or normal http 1.0? */
797 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
798 if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
800 wsi->vhost->ws_upgrades++;
801 lwsl_info("Upgrade to ws\n");
805 if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
807 wsi->vhost->http2_upgrades++;
808 lwsl_info("Upgrade to h2c\n");
812 lwsl_err("Unknown upgrade\n");
813 /* dunno what he wanted to upgrade to */
817 /* no upgrade ack... he remained as HTTP */
819 lwsl_info("No upgrade\n");
822 lws_union_transition(wsi, LWSCM_HTTP_SERVING_ACCEPTED);
823 wsi->state = LWSS_HTTP;
824 wsi->u.http.fd = LWS_INVALID_FILE;
826 /* expose it at the same offset as u.hdr */
828 lwsl_debug("%s: wsi %p: ah %p\n", __func__, (void *)wsi,
829 (void *)wsi->u.hdr.ah);
831 n = lws_http_action(wsi);
837 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) {
838 lwsl_err("missing http2_settings\n");
842 lwsl_err("h2c upgrade...\n");
844 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS);
845 /* convert the peer's HTTP-Settings */
846 n = lws_b64_decode_string(p, protocol_list,
847 sizeof(protocol_list));
849 lwsl_parser("HTTP2_SETTINGS too long\n");
853 /* adopt the header info */
857 lws_union_transition(wsi, LWSCM_HTTP2_SERVING);
859 /* http2 union member has http union struct at start */
862 lws_http2_init(&wsi->u.http2.peer_settings);
863 lws_http2_init(&wsi->u.http2.my_settings);
867 lws_http2_interpret_settings_payload(&wsi->u.http2.peer_settings,
868 (unsigned char *)protocol_list, n);
870 strcpy(protocol_list,
871 "HTTP/1.1 101 Switching Protocols\x0d\x0a"
872 "Connection: Upgrade\x0d\x0a"
873 "Upgrade: h2c\x0d\x0a\x0d\x0a");
874 n = lws_issue_raw(wsi, (unsigned char *)protocol_list,
875 strlen(protocol_list));
876 if (n != strlen(protocol_list)) {
877 lwsl_debug("http2 switch: ERROR writing to socket\n");
881 wsi->state = LWSS_HTTP2_AWAIT_CLIENT_PREFACE;
888 lwsl_err("NULL protocol at lws_read\n");
893 * Select the first protocol we support from the list
894 * the client sent us.
896 * Copy it to remove header fragmentation
899 if (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1,
900 WSI_TOKEN_PROTOCOL) < 0) {
901 lwsl_err("protocol list too long");
905 protocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
906 protocol_list[protocol_len] = '\0';
912 while (n < sizeof(protocol_name) - 1 && *p && *p !=',')
913 protocol_name[n++] = *p++;
914 protocol_name[n] = '\0';
918 lwsl_info("checking %s\n", protocol_name);
921 while (wsi->vhost->protocols[n].callback) {
922 if (wsi->vhost->protocols[n].name &&
923 !strcmp(wsi->vhost->protocols[n].name,
925 wsi->protocol = &wsi->vhost->protocols[n];
934 /* we didn't find a protocol he wanted? */
937 if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL)) {
938 lwsl_err("No protocol from \"%s\" supported\n",
943 * some clients only have one protocol and
944 * do not send the protocol list header...
945 * allow it and match to protocol 0
947 lwsl_info("defaulting to prot 0 handler\n");
949 wsi->protocol = &wsi->vhost->protocols[0];
952 /* allocate wsi->user storage */
953 if (lws_ensure_user_space(wsi))
957 * Give the user code a chance to study the request and
958 * have the opportunity to deny it
960 if ((wsi->protocol->callback)(wsi,
961 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
963 lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) {
964 lwsl_warn("User code denied connection\n");
969 * Perform the handshake according to the protocol version the
973 switch (wsi->ietf_spec_revision) {
975 lwsl_parser("lws_parse calling handshake_04\n");
976 if (handshake_0405(context, wsi)) {
977 lwsl_info("hs0405 has failed the connection\n");
983 lwsl_warn("Unknown client spec version %d\n",
984 wsi->ietf_spec_revision);
989 * stitch protocol choice into the vh protocol linked list
990 * We always insert ourselves at the start of the list
995 //lwsl_err("%s: pre insert vhost start wsi %p, that wsi prev == %p\n",
997 // wsi->vhost->same_vh_protocol_list[n],
998 // wsi->same_vh_protocol_prev);
999 wsi->same_vh_protocol_prev = /* guy who points to us */
1000 &wsi->vhost->same_vh_protocol_list[n];
1001 wsi->same_vh_protocol_next = /* old first guy is our next */
1002 wsi->vhost->same_vh_protocol_list[n];
1003 /* we become the new first guy */
1004 wsi->vhost->same_vh_protocol_list[n] = wsi;
1006 if (wsi->same_vh_protocol_next)
1007 /* old first guy points back to us now */
1008 wsi->same_vh_protocol_next->same_vh_protocol_prev =
1009 &wsi->same_vh_protocol_next;
1013 /* we are upgrading to ws, so http/1.1 and keepalive +
1014 * pipelined header considerations about keeping the ah around
1015 * no longer apply. However it's common for the first ws
1016 * protocol data to have been coalesced with the browser
1017 * upgrade request and to already be in the ah rx buffer.
1020 lwsl_info("%s: %p: inheriting ah in ws mode (rxpos:%d, rxlen:%d)\n",
1021 __func__, wsi, wsi->u.hdr.ah->rxpos,
1022 wsi->u.hdr.ah->rxlen);
1026 lws_union_transition(wsi, LWSCM_WS_SERVING);
1028 * first service is WS mode will notice this, use the RX and
1029 * then detach the ah (caution: we are not in u.hdr union
1030 * mode any more then... ah_temp member is at start the same
1033 * Because rxpos/rxlen shows something in the ah, we will get
1034 * service guaranteed next time around the event loop
1036 * All union members begin with hdr, so we can use it even
1037 * though we transitioned to ws union mode (the ah detach
1038 * code uses it anyway).
1044 * create the frame buffer for this connection according to the
1045 * size mentioned in the protocol definition. If 0 there, use
1046 * a big default for compatibility
1049 n = wsi->protocol->rx_buffer_size;
1051 n = LWS_MAX_SOCKET_IO_BUF;
1053 wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
1054 if (!wsi->u.ws.rx_ubuf) {
1055 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
1058 wsi->u.ws.rx_ubuf_alloc = n;
1059 lwsl_info("Allocating RX buffer %d\n", n);
1061 if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF,
1062 (const char *)&n, sizeof n)) {
1063 lwsl_warn("Failed to set SNDBUF to %d", n);
1067 lwsl_parser("accepted v%02d connection\n",
1068 wsi->ietf_spec_revision);
1071 } /* while all chars are handled */
1076 /* drop the header info */
1077 /* we're closing, losing some rx is OK */
1078 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1079 lws_header_table_detach(wsi, 1);
1085 lws_get_idlest_tsi(struct lws_context *context)
1087 unsigned int lowest = ~0;
1088 int n = 0, hit = -1;
1090 for (; n < context->count_threads; n++) {
1091 if ((unsigned int)context->pt[n].fds_count !=
1092 context->fd_limit_per_thread - 1 &&
1093 (unsigned int)context->pt[n].fds_count < lowest) {
1094 lowest = context->pt[n].fds_count;
1103 lws_create_new_server_wsi(struct lws_vhost *vhost)
1105 struct lws *new_wsi;
1106 int n = lws_get_idlest_tsi(vhost->context);
1109 lwsl_err("no space for new conn\n");
1113 new_wsi = lws_zalloc(sizeof(struct lws));
1114 if (new_wsi == NULL) {
1115 lwsl_err("Out of memory for new connection\n");
1120 lwsl_info("Accepted %p to tsi %d\n", new_wsi, new_wsi->tsi);
1122 new_wsi->vhost = vhost;
1123 new_wsi->context = vhost->context;
1124 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1125 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1127 /* intialize the instance struct */
1129 new_wsi->state = LWSS_HTTP;
1130 new_wsi->mode = LWSCM_HTTP_SERVING;
1131 new_wsi->hdr_parsing_completed = 0;
1133 #ifdef LWS_OPENSSL_SUPPORT
1134 new_wsi->use_ssl = LWS_SSL_ENABLED(vhost);
1138 * these can only be set once the protocol is known
1139 * we set an unestablished connection's protocol pointer
1140 * to the start of the supported list, so it can look
1141 * for matching ones during the handshake
1143 new_wsi->protocol = vhost->protocols;
1144 new_wsi->user_space = NULL;
1145 new_wsi->ietf_spec_revision = 0;
1146 new_wsi->sock = LWS_SOCK_INVALID;
1147 vhost->context->count_wsi_allocated++;
1150 * outermost create notification for wsi
1151 * no user_space because no protocol selection
1153 vhost->protocols[0].callback(new_wsi, LWS_CALLBACK_WSI_CREATE,
1160 * lws_http_transaction_completed() - wait for new http transaction or close
1161 * @wsi: websocket connection
1163 * Returns 1 if the HTTP connection must close now
1164 * Returns 0 and resets connection to wait for new HTTP header /
1165 * transaction if possible
1168 LWS_VISIBLE int LWS_WARN_UNUSED_RESULT
1169 lws_http_transaction_completed(struct lws *wsi)
1171 int n = NO_PENDING_TIMEOUT;
1173 lws_access_log(wsi);
1175 lwsl_debug("%s: wsi %p\n", __func__, wsi);
1176 /* if we can't go back to accept new headers, drop the connection */
1177 if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
1178 lwsl_info("%s: %p: close connection\n", __func__, wsi);
1182 /* otherwise set ourselves up ready to go again */
1183 wsi->state = LWSS_HTTP;
1184 wsi->mode = LWSCM_HTTP_SERVING;
1185 wsi->u.http.content_length = 0;
1186 wsi->hdr_parsing_completed = 0;
1187 #ifdef LWS_WITH_ACCESS_LOG
1188 wsi->access_log.sent = 0;
1191 if (wsi->vhost->keepalive_timeout)
1192 n = PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE;
1193 lws_set_timeout(wsi, n, wsi->vhost->keepalive_timeout);
1196 * We already know we are on http1.1 / keepalive and the next thing
1197 * coming will be another header set.
1199 * If there is no pending rx and we still have the ah, drop it and
1200 * reacquire a new ah when the new headers start to arrive. (Otherwise
1201 * we needlessly hog an ah indefinitely.)
1203 * However if there is pending rx and we know from the keepalive state
1204 * that is already at least the start of another header set, simply
1205 * reset the existing header table and keep it.
1207 if (wsi->u.hdr.ah) {
1208 lwsl_info("%s: wsi->more_rx_waiting=%d\n", __func__,
1209 wsi->more_rx_waiting);
1211 if (!wsi->more_rx_waiting) {
1212 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1213 lws_header_table_detach(wsi, 1);
1215 lws_header_table_reset(wsi, 1);
1218 /* If we're (re)starting on headers, need other implied init */
1219 wsi->u.hdr.ues = URIES_IDLE;
1221 lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
1227 lws_adopt_socket_vhost(struct lws_vhost *vh, lws_sockfd_type accept_fd)
1229 struct lws_context *context = vh->context;
1230 struct lws *new_wsi = lws_create_new_server_wsi(vh);
1233 compatible_close(accept_fd);
1237 lwsl_info("%s: new wsi %p, sockfd %d\n", __func__, new_wsi, accept_fd);
1239 new_wsi->sock = accept_fd;
1241 /* the transport is accepted... give him time to negotiate */
1242 lws_set_timeout(new_wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
1243 context->timeout_secs);
1246 mbed3_tcp_stream_accept(accept_fd, new_wsi);
1250 * A new connection was accepted. Give the user a chance to
1251 * set properties of the newly created wsi. There's no protocol
1252 * selected yet so we issue this to protocols[0]
1254 if ((context->vhost_list->protocols[0].callback)(new_wsi,
1255 LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED, NULL, NULL, 0)) {
1256 compatible_close(new_wsi->sock);
1261 lws_libev_accept(new_wsi, new_wsi->sock);
1262 lws_libuv_accept(new_wsi, new_wsi->sock);
1264 if (!LWS_SSL_ENABLED(new_wsi->vhost)) {
1265 if (insert_wsi_socket_into_fds(context, new_wsi)) {
1266 lwsl_err("%s: fail inserting socket\n", __func__);
1270 new_wsi->mode = LWSCM_SSL_INIT;
1271 if (lws_server_socket_service_ssl(new_wsi, accept_fd)) {
1272 lwsl_err("%s: fail ssl negotiation\n", __func__);
1277 if (!lws_header_table_attach(new_wsi, 0))
1278 lwsl_debug("Attached ah immediately\n");
1283 lws_close_free_wsi(new_wsi, LWS_CLOSE_STATUS_NOSTATUS);
1289 * lws_adopt_socket() - adopt foreign socket as if listen socket accepted it
1290 * @context: lws context
1291 * @accept_fd: fd of already-accepted socket to adopt
1293 * Either returns new wsi bound to accept_fd, or closes accept_fd and
1294 * returns NULL, having cleaned up any new wsi pieces.
1296 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
1297 * to ws or just serve http.
1300 LWS_VISIBLE struct lws *
1301 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd)
1303 return lws_adopt_socket_vhost(context->vhost_list, accept_fd);
1308 * lws_adopt_socket_readbuf() - adopt foreign socket and first rx as if listen socket accepted it
1309 * @context: lws context
1310 * @accept_fd: fd of already-accepted socket to adopt
1311 * @readbuf: NULL or pointer to data that must be drained before reading from
1313 * @len: The length of the data held at @readbuf
1315 * Either returns new wsi bound to accept_fd, or closes accept_fd and
1316 * returns NULL, having cleaned up any new wsi pieces.
1318 * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
1319 * to ws or just serve http.
1321 * If your external code did not already read from the socket, you can use
1322 * lws_adopt_socket() instead.
1324 * This api is guaranteed to use the data at @readbuf first, before reading from
1327 * @readbuf is limited to the size of the ah rx buf, currently 2048 bytes.
1330 LWS_VISIBLE LWS_EXTERN struct lws *
1331 lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
1332 const char *readbuf, size_t len)
1334 struct lws *wsi = lws_adopt_socket(context, accept_fd);
1335 struct lws_context_per_thread *pt;
1336 struct allocated_headers *ah;
1337 struct lws_pollfd *pfd;
1345 if (len > sizeof(ah->rx)) {
1346 lwsl_err("%s: rx in too big\n", __func__);
1350 * we can't process the initial read data until we can attach an ah.
1352 * if one is available, get it and place the data in his ah rxbuf...
1353 * wsi with ah that have pending rxbuf get auto-POLLIN service.
1355 * no autoservice because we didn't get a chance to attach the
1356 * readbuf data to wsi or ah yet, and we will do it next if we get
1359 if (wsi->u.hdr.ah || !lws_header_table_attach(wsi, 0)) {
1361 memcpy(ah->rx, readbuf, len);
1365 lwsl_notice("%s: calling service on readbuf ah\n", __func__);
1366 pt = &context->pt[(int)wsi->tsi];
1368 /* unlike a normal connect, we have the headers already
1369 * (or the first part of them anyway).
1370 * libuv won't come back and service us without a network
1371 * event, so we need to do the header service right here.
1373 pfd = &pt->fds[wsi->position_in_fds_table];
1374 pfd->revents |= LWS_POLLIN;
1375 lwsl_err("%s: calling service\n", __func__);
1376 if (lws_service_fd_tsi(context, pfd, wsi->tsi))
1377 /* service closed us */
1382 lwsl_err("%s: deferring handling ah\n", __func__);
1384 * hum if no ah came, we are on the wait list and must defer
1385 * dealing with this until the ah arrives.
1387 * later successful lws_header_table_attach() will apply the
1388 * below to the rx buffer (via lws_header_table_reset()).
1390 wsi->u.hdr.preamble_rx = lws_malloc(len);
1391 memcpy(wsi->u.hdr.preamble_rx, readbuf, len);
1392 wsi->u.hdr.preamble_rx_len = len;
1397 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1403 lws_server_socket_service(struct lws_context *context, struct lws *wsi,
1404 struct lws_pollfd *pollfd)
1406 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1407 lws_sockfd_type accept_fd = LWS_SOCK_INVALID;
1408 struct allocated_headers *ah;
1410 struct sockaddr_in cli_addr;
1415 switch (wsi->mode) {
1417 case LWSCM_HTTP_SERVING:
1418 case LWSCM_HTTP_SERVING_ACCEPTED:
1419 case LWSCM_HTTP2_SERVING:
1421 /* handle http headers coming in */
1423 /* pending truncated sends have uber priority */
1425 if (wsi->trunc_len) {
1426 if (!(pollfd->revents & LWS_POLLOUT))
1429 if (lws_issue_raw(wsi, wsi->trunc_alloc +
1431 wsi->trunc_len) < 0)
1434 * we can't afford to allow input processing to send
1435 * something new, so spin around he event loop until
1436 * he doesn't have any partials
1441 /* any incoming data ready? */
1443 if (!(pollfd->revents & pollfd->events & LWS_POLLIN))
1447 * If we previously just did POLLIN when IN and OUT were
1448 * signalled (because POLLIN processing may have used up
1449 * the POLLOUT), don't let that happen twice in a row...
1450 * next time we see the situation favour POLLOUT
1453 if (wsi->favoured_pollin &&
1454 (pollfd->revents & pollfd->events & LWS_POLLOUT)) {
1455 wsi->favoured_pollin = 0;
1459 /* these states imply we MUST have an ah attached */
1461 if (wsi->state == LWSS_HTTP ||
1462 wsi->state == LWSS_HTTP_ISSUING_FILE ||
1463 wsi->state == LWSS_HTTP_HEADERS) {
1465 /* no autoservice beacuse we will do it next */
1466 if (lws_header_table_attach(wsi, 0))
1471 lwsl_debug("%s: %p: rxpos:%d rxlen:%d\n", __func__, wsi,
1472 ah->rxpos, ah->rxlen);
1474 /* if nothing in ah rx buffer, get some fresh rx */
1475 if (ah->rxpos == ah->rxlen) {
1476 ah->rxlen = lws_ssl_capable_read(wsi, ah->rx,
1479 lwsl_debug("%s: wsi %p, ah->rxlen = %d\r\n",
1480 __func__, wsi, ah->rxlen);
1481 switch (ah->rxlen) {
1483 lwsl_info("%s: read 0 len\n", __func__);
1484 /* lwsl_info(" state=%d\n", wsi->state); */
1485 // if (!wsi->hdr_parsing_completed)
1486 // lws_header_table_detach(wsi);
1488 case LWS_SSL_CAPABLE_ERROR:
1490 case LWS_SSL_CAPABLE_MORE_SERVICE:
1491 ah->rxlen = ah->rxpos = 0;
1495 assert(ah->rxpos != ah->rxlen && ah->rxlen);
1496 /* just ignore incoming if waiting for close */
1497 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
1498 n = lws_read(wsi, ah->rx + ah->rxpos,
1499 ah->rxlen - ah->rxpos);
1500 if (n < 0) /* we closed wsi */
1502 if (wsi->u.hdr.ah) {
1503 if ( wsi->u.hdr.ah->rxlen)
1504 wsi->u.hdr.ah->rxpos += n;
1506 if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen &&
1507 (wsi->mode != LWSCM_HTTP_SERVING &&
1508 wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED &&
1509 wsi->mode != LWSCM_HTTP2_SERVING))
1510 lws_header_table_detach(wsi, 1);
1518 len = lws_ssl_capable_read(wsi, pt->serv_buf,
1519 LWS_MAX_SOCKET_IO_BUF);
1520 lwsl_debug("%s: wsi %p read %d\r\n", __func__, wsi, len);
1523 lwsl_info("%s: read 0 len\n", __func__);
1524 /* lwsl_info(" state=%d\n", wsi->state); */
1525 // if (!wsi->hdr_parsing_completed)
1526 // lws_header_table_detach(wsi);
1528 case LWS_SSL_CAPABLE_ERROR:
1530 case LWS_SSL_CAPABLE_MORE_SERVICE:
1534 /* just ignore incoming if waiting for close */
1535 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
1537 * this may want to send
1538 * (via HTTP callback for example)
1540 n = lws_read(wsi, pt->serv_buf, len);
1541 if (n < 0) /* we closed wsi */
1544 * he may have used up the
1545 * writability above, if we will defer POLLOUT
1546 * processing in favour of POLLIN, note it
1548 if (pollfd->revents & LWS_POLLOUT)
1549 wsi->favoured_pollin = 1;
1554 /* this handles POLLOUT for http serving fragments */
1556 if (!(pollfd->revents & LWS_POLLOUT))
1560 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
1561 lwsl_notice("%s a\n", __func__);
1565 if (!wsi->hdr_parsing_completed)
1568 if (wsi->state != LWSS_HTTP_ISSUING_FILE) {
1569 n = user_callback_handle_rxflow(wsi->protocol->callback,
1570 wsi, LWS_CALLBACK_HTTP_WRITEABLE,
1571 wsi->user_space, NULL, 0);
1573 lwsl_info("writeable_fail\n");
1579 /* >0 == completion, <0 == error */
1580 n = lws_serve_http_file_fragment(wsi);
1581 if (n < 0 || (n > 0 && lws_http_transaction_completed(wsi))) {
1582 lwsl_info("completed\n");
1587 case LWSCM_SERVER_LISTENER:
1590 /* pollin means a client has connected to us then */
1593 if (!(pollfd->revents & LWS_POLLIN) || !(pollfd->events & LWS_POLLIN))
1596 /* listen socket got an unencrypted connection... */
1598 clilen = sizeof(cli_addr);
1599 lws_latency_pre(context, wsi);
1600 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1602 lws_latency(context, wsi, "listener accept", accept_fd,
1604 if (accept_fd < 0) {
1605 if (LWS_ERRNO == LWS_EAGAIN ||
1606 LWS_ERRNO == LWS_EWOULDBLOCK) {
1607 lwsl_err("accept asks to try again\n");
1610 lwsl_err("ERROR on accept: %s\n", strerror(LWS_ERRNO));
1614 lws_plat_set_socket_options(wsi->vhost, accept_fd);
1616 lwsl_debug("accepted new conn port %u on fd=%d\n",
1617 ntohs(cli_addr.sin_port), accept_fd);
1620 /* not very beautiful... */
1621 accept_fd = (lws_sockfd_type)pollfd;
1624 * look at who we connected to and give user code a chance
1625 * to reject based on client IP. There's no protocol selected
1626 * yet so we issue this to protocols[0]
1628 if ((wsi->vhost->protocols[0].callback)(wsi,
1629 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
1630 NULL, (void *)(long)accept_fd, 0)) {
1631 lwsl_debug("Callback denied network connection\n");
1632 compatible_close(accept_fd);
1636 if (!lws_adopt_socket_vhost(wsi->vhost, accept_fd))
1637 /* already closed cleanly as necessary */
1641 } while (pt->fds_count < context->fd_limit_per_thread - 1 &&
1642 lws_poll_listen_fd(&pt->fds[wsi->position_in_fds_table]) > 0);
1650 if (!lws_server_socket_service_ssl(wsi, accept_fd))
1654 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1660 * lws_serve_http_file() - Send a file back to the client using http
1661 * @wsi: Websocket instance (available from user callback)
1662 * @file: The file to issue over http
1663 * @content_type: The http content type, eg, text/html
1664 * @other_headers: NULL or pointer to header string
1665 * @other_headers_len: length of the other headers if non-NULL
1667 * This function is intended to be called from the callback in response
1668 * to http requests from the client. It allows the callback to issue
1669 * local files down the http link in a single step.
1671 * Returning <0 indicates error and the wsi should be closed. Returning
1672 * >0 indicates the file was completely sent and
1673 * lws_http_transaction_completed() called on the wsi (and close if != 0)
1674 * ==0 indicates the file transfer is started and needs more service later,
1675 * the wsi should be left alone.
1679 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
1680 const char *other_headers, int other_headers_len)
1682 static const char * const intermediates[] = { "private", "public" };
1683 struct lws_context *context = lws_get_context(wsi);
1684 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1685 char cache_control[50], *cc = "no-store";
1686 unsigned char *response = pt->serv_buf + LWS_PRE;
1687 unsigned char *p = response;
1688 unsigned char *end = p + LWS_MAX_SOCKET_IO_BUF - LWS_PRE;
1689 int ret = 0, cclen = 8;
1691 wsi->u.http.fd = lws_plat_file_open(wsi, file, &wsi->u.http.filelen,
1694 if (wsi->u.http.fd == LWS_INVALID_FILE) {
1695 lwsl_err("Unable to open '%s'\n", file);
1696 lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
1701 if (lws_add_http_header_status(wsi, 200, &p, end))
1703 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
1704 (unsigned char *)content_type,
1705 strlen(content_type), &p, end))
1707 if (lws_add_http_header_content_length(wsi, wsi->u.http.filelen, &p, end))
1710 if (wsi->cache_secs && wsi->cache_reuse) {
1711 if (wsi->cache_revalidate) {
1713 cclen = sprintf(cache_control, "%s max-age: %u",
1714 intermediates[wsi->cache_intermediaries],
1722 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CACHE_CONTROL,
1723 (unsigned char *)cc, cclen, &p, end))
1726 if (other_headers) {
1727 if ((end - p) < other_headers_len)
1729 memcpy(p, other_headers, other_headers_len);
1730 p += other_headers_len;
1733 if (lws_finalize_http_header(wsi, &p, end))
1736 ret = lws_write(wsi, response, p - response, LWS_WRITE_HTTP_HEADERS);
1737 if (ret != (p - response)) {
1738 lwsl_err("_write returned %d from %d\n", ret, (p - response));
1742 wsi->u.http.filepos = 0;
1743 wsi->state = LWSS_HTTP_ISSUING_FILE;
1745 return lws_serve_http_file_fragment(wsi);
1749 lws_interpret_incoming_packet(struct lws *wsi, unsigned char **buf, size_t len)
1753 lwsl_parser("%s: received %d byte packet\n", __func__, (int)len);
1755 lwsl_hexdump(*buf, len);
1758 /* let the rx protocol state machine have as much as it needs */
1762 * we were accepting input but now we stopped doing so
1764 if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
1765 lws_rxflow_cache(wsi, *buf, 0, len);
1766 lwsl_parser("%s: cached %d\n", __func__, len);
1770 if (wsi->u.ws.rx_draining_ext) {
1771 m = lws_rx_sm(wsi, 0);
1777 /* account for what we're using in rxflow buffer */
1778 if (wsi->rxflow_buffer)
1781 /* consume payload bytes efficiently */
1782 if (wsi->lws_rx_parse_state ==
1783 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED)
1784 lws_payload_until_length_exhausted(wsi, buf, &len);
1786 /* process the byte */
1787 m = lws_rx_sm(wsi, *(*buf)++);
1793 lwsl_parser("%s: exit with %d unused\n", __func__, (int)len);
1799 lws_server_get_canonical_hostname(struct lws_context *context,
1800 struct lws_context_creation_info *info)
1802 if (lws_check_opt(info->options, LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME))
1805 /* find canonical hostname */
1806 gethostname((char *)context->canonical_hostname,
1807 sizeof(context->canonical_hostname) - 1);
1809 lwsl_notice(" canonical_hostname = %s\n", context->canonical_hostname);