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"
25 #if defined (LWS_WITH_ESP8266)
27 void *memcpy(void *dest, const void *src, size_t n)
29 return ets_memcpy(dest, src, n);
34 lws_context_init_server(struct lws_context_creation_info *info,
35 struct lws_vhost *vhost)
38 int n, opt = 1, limit = 1;
40 lws_sockfd_type sockfd;
46 /* set up our external listening socket we serve on */
48 if (info->port == CONTEXT_PORT_NO_LISTEN || info->port == CONTEXT_PORT_NO_LISTEN_SERVER)
51 vh = vhost->context->vhost_list;
53 if (vh->listen_port == info->port) {
54 if ((!info->iface && !vh->iface) ||
55 (info->iface && vh->iface &&
56 !strcmp(info->iface, vh->iface))) {
57 vhost->listen_port = info->port;
58 vhost->iface = info->iface;
59 lwsl_notice(" using listen skt from vhost %s\n",
68 #if defined(__linux__)
69 limit = vhost->context->count_threads;
72 for (m = 0; m < limit; m++) {
73 #ifdef LWS_USE_UNIX_SOCK
74 if (LWS_UNIX_SOCK_ENABLED(vhost))
75 sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
79 if (LWS_IPV6_ENABLED(vhost))
80 sockfd = socket(AF_INET6, SOCK_STREAM, 0);
83 sockfd = socket(AF_INET, SOCK_STREAM, 0);
87 #if defined(LWS_WITH_ESP8266)
88 sockfd = esp8266_create_tcp_listen_socket(vhost);
89 if (!lws_sockfd_valid(sockfd)) {
92 lwsl_err("ERROR opening socket\n");
95 #if LWS_POSIX && !defined(LWS_WITH_ESP32)
97 * allow us to restart even if old sockets in TIME_WAIT
99 if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
100 (const void *)&opt, sizeof(opt)) < 0) {
101 lwsl_err("reuseaddr failed\n");
102 compatible_close(sockfd);
106 #if defined(LWS_USE_IPV6) && defined(IPV6_V6ONLY)
107 if (LWS_IPV6_ENABLED(vhost)) {
108 if (vhost->options & LWS_SERVER_OPTION_IPV6_V6ONLY_MODIFY) {
109 int value = (vhost->options & LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE) ? 1 : 0;
110 if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
111 (const void*)&value, sizeof(value)) < 0) {
112 compatible_close(sockfd);
119 #if defined(__linux__) && defined(SO_REUSEPORT) && LWS_MAX_SMP > 1
120 if (vhost->context->count_threads > 1)
121 if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT,
122 (const void *)&opt, sizeof(opt)) < 0) {
123 compatible_close(sockfd);
128 lws_plat_set_socket_options(vhost, sockfd);
131 n = lws_socket_bind(vhost, sockfd, info->port, info->iface);
136 vhost->listen_port = info->port;
137 vhost->iface = info->iface;
139 wsi = lws_zalloc(sizeof(struct lws));
141 lwsl_err("Out of mem\n");
144 wsi->context = vhost->context;
145 wsi->desc.sockfd = sockfd;
146 wsi->mode = LWSCM_SERVER_LISTENER;
147 wsi->protocol = vhost->protocols;
153 if (LWS_LIBUV_ENABLED(vhost->context))
154 lws_uv_initvhost(vhost, wsi);
157 if (insert_wsi_socket_into_fds(vhost->context, wsi))
160 vhost->context->count_wsi_allocated++;
161 vhost->lserv_wsi = wsi;
164 n = listen(wsi->desc.sockfd, LWS_SOMAXCONN);
166 lwsl_err("listen failed with error %d\n", LWS_ERRNO);
167 vhost->lserv_wsi = NULL;
168 vhost->context->count_wsi_allocated--;
169 remove_wsi_socket_from_fds(wsi);
172 } /* for each thread able to independently listen */
174 #if defined(LWS_WITH_ESP8266)
175 esp8266_tcp_stream_bind(wsi->desc.sockfd, info->port, wsi);
178 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS)) {
179 #ifdef LWS_USE_UNIX_SOCK
180 if (LWS_UNIX_SOCK_ENABLED(vhost))
181 lwsl_notice(" Listening on \"%s\"\n", info->iface);
184 lwsl_notice(" Listening on port %d\n", info->port);
190 compatible_close(sockfd);
195 #if defined(LWS_WITH_ESP8266)
197 #define strchr ets_strchr
201 lws_select_vhost(struct lws_context *context, int port, const char *servername)
203 struct lws_vhost *vhost = context->vhost_list;
207 n = strlen(servername);
209 p = strchr(servername, ':');
211 colon = p - servername;
213 /* Priotity 1: first try exact matches */
216 if (port == vhost->listen_port &&
217 !strncmp(vhost->name, servername, colon)) {
218 lwsl_info("SNI: Found: %s\n", servername);
221 vhost = vhost->vhost_next;
225 * Priority 2: if no exact matches, try matching *.vhost-name
226 * unintentional matches are possible but resolve to x.com for *.x.com
227 * which is reasonable. If exact match exists we already chose it and
228 * never reach here. SSL will still fail it if the cert doesn't allow
232 vhost = context->vhost_list;
234 m = strlen(vhost->name);
235 if (port == vhost->listen_port &&
237 servername[colon - m - 1] == '.' &&
238 !strncmp(vhost->name, servername + colon - m, m)) {
239 lwsl_info("SNI: Found %s on wildcard: %s\n",
240 servername, vhost->name);
243 vhost = vhost->vhost_next;
246 /* Priority 3: match the first vhost on our port */
248 vhost = context->vhost_list;
250 if (port == vhost->listen_port) {
251 lwsl_info("vhost match to %s based on port %d\n",
255 vhost = vhost->vhost_next;
263 LWS_VISIBLE LWS_EXTERN const char *
264 lws_get_mimetype(const char *file, const struct lws_http_mount *m)
266 int n = strlen(file);
267 const struct lws_protocol_vhost_options *pvo = NULL;
270 pvo = m->extra_mimetypes;
275 if (!strcmp(&file[n - 4], ".ico"))
276 return "image/x-icon";
278 if (!strcmp(&file[n - 4], ".gif"))
281 if (!strcmp(&file[n - 3], ".js"))
282 return "text/javascript";
284 if (!strcmp(&file[n - 4], ".png"))
287 if (!strcmp(&file[n - 4], ".jpg"))
290 if (!strcmp(&file[n - 3], ".gz"))
291 return "application/gzip";
293 if (!strcmp(&file[n - 4], ".JPG"))
296 if (!strcmp(&file[n - 5], ".html"))
299 if (!strcmp(&file[n - 4], ".css"))
302 if (!strcmp(&file[n - 4], ".txt"))
305 if (!strcmp(&file[n - 4], ".svg"))
306 return "image/svg+xml";
308 if (!strcmp(&file[n - 4], ".ttf"))
309 return "application/x-font-ttf";
311 if (!strcmp(&file[n - 4], ".otf"))
312 return "application/font-woff";
314 if (!strcmp(&file[n - 5], ".woff"))
315 return "application/font-woff";
317 if (!strcmp(&file[n - 4], ".xml"))
318 return "application/xml";
321 if (pvo->name[0] == '*') /* ie, match anything */
324 if (!strcmp(&file[n - strlen(pvo->name)], pvo->name))
332 static lws_fop_flags_t
333 lws_vfs_prepare_flags(struct lws *wsi)
335 lws_fop_flags_t f = 0;
337 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_ACCEPT_ENCODING))
340 if (strstr(lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_ACCEPT_ENCODING),
342 lwsl_info("client indicates GZIP is acceptable\n");
343 f |= LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP;
350 lws_http_serve(struct lws *wsi, char *uri, const char *origin,
351 const struct lws_http_mount *m)
353 const struct lws_protocol_vhost_options *pvo = m->interpret;
354 struct lws_process_html_args args;
355 const char *mimetype;
356 #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP8266)
357 const struct lws_plat_file_ops *fops;
359 lws_fop_flags_t fflags = LWS_O_RDONLY;
360 #if defined(WIN32) && defined(LWS_HAVE__STAT32I64)
361 struct _stat32i64 st;
367 char path[256], sym[512];
368 unsigned char *p = (unsigned char *)sym + 32 + LWS_PRE, *start = p;
369 unsigned char *end = p + sizeof(sym) - 32 - LWS_PRE;
370 #if !defined(WIN32) && LWS_POSIX && !defined(LWS_WITH_ESP32)
375 lws_snprintf(path, sizeof(path) - 1, "%s/%s", origin, uri);
377 #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP8266)
379 fflags |= lws_vfs_prepare_flags(wsi);
383 fops = lws_vfs_select_fops(wsi->context->fops, path, &vpath);
385 if (wsi->u.http.fop_fd)
386 lws_vfs_file_close(&wsi->u.http.fop_fd);
388 wsi->u.http.fop_fd = fops->LWS_FOP_OPEN(wsi->context->fops,
389 path, vpath, &fflags);
390 if (!wsi->u.http.fop_fd) {
391 lwsl_err("Unable to open '%s'\n", path);
396 /* if it can't be statted, don't try */
397 if (fflags & LWS_FOP_FLAG_VIRTUAL)
399 #if defined(LWS_WITH_ESP32)
403 if (fstat(wsi->u.http.fop_fd->fd, &st)) {
404 lwsl_info("unable to stat %s\n", path);
408 #if defined(LWS_HAVE__STAT32I64)
409 if (_stat32i64(path, &st)) {
410 lwsl_info("unable to stat %s\n", path);
414 if (stat(path, &st)) {
415 lwsl_info("unable to stat %s\n", path);
421 wsi->u.http.fop_fd->mod_time = (uint32_t)st.st_mtime;
422 fflags |= LWS_FOP_FLAG_MOD_TIME_VALID;
424 lwsl_debug(" %s mode %d\n", path, S_IFMT & st.st_mode);
425 #if !defined(WIN32) && LWS_POSIX && !defined(LWS_WITH_ESP32)
426 if ((S_IFMT & st.st_mode) == S_IFLNK) {
427 len = readlink(path, sym, sizeof(sym) - 1);
429 lwsl_err("Failed to read link %s\n", path);
433 lwsl_debug("symlink %s -> %s\n", path, sym);
434 lws_snprintf(path, sizeof(path) - 1, "%s", sym);
437 if ((S_IFMT & st.st_mode) == S_IFDIR) {
438 lwsl_debug("default filename append to dir\n");
439 lws_snprintf(path, sizeof(path) - 1, "%s/%s/index.html",
443 } while ((S_IFMT & st.st_mode) != S_IFREG && spin < 5);
446 lwsl_err("symlink loop %s \n", path);
448 n = sprintf(sym, "%08lX%08lX",
449 (unsigned long)lws_vfs_get_length(wsi->u.http.fop_fd),
450 (unsigned long)lws_vfs_get_mod_time(wsi->u.http.fop_fd));
452 /* disable ranges if IF_RANGE token invalid */
454 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_RANGE))
455 if (strcmp(sym, lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_IF_RANGE)))
456 /* differs - defeat Range: */
457 wsi->u.http.ah->frag_index[WSI_TOKEN_HTTP_RANGE] = 0;
459 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_NONE_MATCH)) {
461 * he thinks he has some version of it already,
462 * check if the tag matches
464 if (!strcmp(sym, lws_hdr_simple_ptr(wsi,
465 WSI_TOKEN_HTTP_IF_NONE_MATCH))) {
467 lwsl_debug("%s: ETAG match %s %s\n", __func__,
470 /* we don't need to send the payload */
471 if (lws_add_http_header_status(wsi,
472 HTTP_STATUS_NOT_MODIFIED, &p, end))
475 if (lws_add_http_header_by_token(wsi,
477 (unsigned char *)sym, n, &p, end))
480 if (lws_finalize_http_header(wsi, &p, end))
483 n = lws_write(wsi, start, p - start,
484 LWS_WRITE_HTTP_HEADERS);
485 if (n != (p - start)) {
486 lwsl_err("_write returned %d from %ld\n", n,
491 lws_vfs_file_close(&wsi->u.http.fop_fd);
493 return lws_http_transaction_completed(wsi);
497 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ETAG,
498 (unsigned char *)sym, n, &p, end))
502 mimetype = lws_get_mimetype(path, m);
504 lwsl_err("unknown mimetype for %s\n", path);
508 lwsl_debug("sending no mimetype for %s\n", path);
510 wsi->sending_chunked = 0;
513 * check if this is in the list of file suffixes to be interpreted by
518 if (n > (int)strlen(pvo->name) &&
519 !strcmp(&path[n - strlen(pvo->name)], pvo->name)) {
520 wsi->sending_chunked = 1;
521 wsi->protocol_interpret_idx = (char)(long)pvo->value;
522 lwsl_info("want %s interpreted by %s\n", path,
523 wsi->vhost->protocols[(int)(long)(pvo->value)].name);
524 wsi->protocol = &wsi->vhost->protocols[(int)(long)(pvo->value)];
525 if (lws_ensure_user_space(wsi))
533 const struct lws_protocols *pp = lws_vhost_name_to_protocol(
534 wsi->vhost, m->protocol);
536 if (lws_bind_protocol(wsi, pp))
539 args.max_len = end - p;
540 if (pp->callback(wsi, LWS_CALLBACK_ADD_HEADERS,
541 wsi->user_space, &args, 0))
543 p = (unsigned char *)args.p;
546 n = lws_serve_http_file(wsi, path, mimetype, (char *)start, p - start);
548 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
549 return -1; /* error or can't reuse connection: close the socket */
557 const struct lws_http_mount *
558 lws_find_mount(struct lws *wsi, const char *uri_ptr, int uri_len)
560 const struct lws_http_mount *hm, *hit = NULL;
563 hm = wsi->vhost->mount_list;
565 if (uri_len >= hm->mountpoint_len &&
566 !strncmp(uri_ptr, hm->mountpoint, hm->mountpoint_len) &&
567 (uri_ptr[hm->mountpoint_len] == '\0' ||
568 uri_ptr[hm->mountpoint_len] == '/' ||
569 hm->mountpoint_len == 1)
571 if (hm->origin_protocol == LWSMPRO_CALLBACK ||
572 ((hm->origin_protocol == LWSMPRO_CGI ||
573 lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI) ||
575 hm->mountpoint_len > best)) {
576 best = hm->mountpoint_len;
589 lws_find_string_in_file(const char *filename, const char *string, int stringlen)
592 int fd, match = 0, pos = 0, n = 0, hit = 0;
594 fd = open(filename, O_RDONLY);
596 lwsl_err("can't open auth file: %s\n", filename);
602 n = read(fd, buf, sizeof(buf));
604 if (match == stringlen)
611 if (match == stringlen) {
612 if (buf[pos] == '\r' || buf[pos] == '\n') {
619 if (buf[pos] == string[match])
633 lws_unauthorised_basic_auth(struct lws *wsi)
635 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
636 unsigned char *start = pt->serv_buf + LWS_PRE,
637 *p = start, *end = p + 512;
641 /* no auth... tell him it is required */
643 if (lws_add_http_header_status(wsi, HTTP_STATUS_UNAUTHORIZED, &p, end))
646 n = lws_snprintf(buf, sizeof(buf), "Basic realm=\"lwsws\"");
647 if (lws_add_http_header_by_token(wsi,
648 WSI_TOKEN_HTTP_WWW_AUTHENTICATE,
649 (unsigned char *)buf, n, &p, end))
652 if (lws_finalize_http_header(wsi, &p, end))
655 n = lws_write(wsi, start, p - start, LWS_WRITE_HTTP_HEADERS);
659 return lws_http_transaction_completed(wsi);
665 int lws_clean_url(char *p)
668 if (p[0] == '/' && p[1] == '/') {
683 lws_http_action(struct lws *wsi)
685 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
686 enum http_connection_type connection_type;
687 enum http_version request_version;
688 char content_length_str[32];
689 struct lws_process_html_args args;
690 const struct lws_http_mount *hit = NULL;
691 unsigned int n, count = 0;
692 char http_version_str[10];
693 char http_conn_str[20];
694 int http_version_len;
695 char *uri_ptr = NULL, *s;
699 static const unsigned char methods[] = {
702 WSI_TOKEN_OPTIONS_URI,
705 WSI_TOKEN_DELETE_URI,
708 WSI_TOKEN_HTTP_COLON_PATH,
711 #if defined(_DEBUG) || defined(LWS_WITH_ACCESS_LOG)
712 static const char * const method_names[] = {
713 "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE", "CONNECT",
719 static const char * const oprot[] = {
720 "http://", "https://"
723 /* it's not websocket.... shall we accept it as http? */
725 for (n = 0; n < ARRAY_SIZE(methods); n++)
726 if (lws_hdr_total_length(wsi, methods[n]))
729 lwsl_warn("Missing URI in HTTP request\n");
734 lwsl_warn("multiple methods?\n");
738 if (lws_ensure_user_space(wsi))
741 for (n = 0; n < ARRAY_SIZE(methods); n++)
742 if (lws_hdr_total_length(wsi, methods[n])) {
743 uri_ptr = lws_hdr_simple_ptr(wsi, methods[n]);
744 uri_len = lws_hdr_total_length(wsi, methods[n]);
745 lwsl_info("Method: %s request for '%s'\n",
746 method_names[n], uri_ptr);
753 /* we insist on absolute paths */
755 if (uri_ptr[0] != '/') {
756 lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
761 /* HTTP header had a content length? */
763 wsi->u.http.content_length = 0;
764 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) ||
765 lws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI) ||
766 lws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI))
767 wsi->u.http.content_length = 100 * 1024 * 1024;
769 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
770 lws_hdr_copy(wsi, content_length_str,
771 sizeof(content_length_str) - 1,
772 WSI_TOKEN_HTTP_CONTENT_LENGTH);
773 wsi->u.http.content_length = atoll(content_length_str);
776 if (wsi->http2_substream) {
777 wsi->u.http.request_version = HTTP_VERSION_2;
779 /* http_version? Default to 1.0, override with token: */
780 request_version = HTTP_VERSION_1_0;
782 /* Works for single digit HTTP versions. : */
783 http_version_len = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP);
784 if (http_version_len > 7) {
785 lws_hdr_copy(wsi, http_version_str,
786 sizeof(http_version_str) - 1, WSI_TOKEN_HTTP);
787 if (http_version_str[5] == '1' && http_version_str[7] == '1')
788 request_version = HTTP_VERSION_1_1;
790 wsi->u.http.request_version = request_version;
792 /* HTTP/1.1 defaults to "keep-alive", 1.0 to "close" */
793 if (request_version == HTTP_VERSION_1_1)
794 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
796 connection_type = HTTP_CONNECTION_CLOSE;
798 /* Override default if http "Connection:" header: */
799 if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) {
800 lws_hdr_copy(wsi, http_conn_str, sizeof(http_conn_str) - 1,
801 WSI_TOKEN_CONNECTION);
802 http_conn_str[sizeof(http_conn_str) - 1] = '\0';
803 if (!strcasecmp(http_conn_str, "keep-alive"))
804 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
806 if (!strcasecmp(http_conn_str, "close"))
807 connection_type = HTTP_CONNECTION_CLOSE;
809 wsi->u.http.connection_type = connection_type;
812 n = wsi->protocol->callback(wsi, LWS_CALLBACK_FILTER_HTTP_CONNECTION,
813 wsi->user_space, uri_ptr, uri_len);
815 lwsl_info("LWS_CALLBACK_HTTP closing\n");
820 * if there is content supposed to be coming,
821 * put a timeout on it having arrived
823 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
824 wsi->context->timeout_secs);
825 #ifdef LWS_OPENSSL_SUPPORT
826 if (wsi->redirect_to_https) {
828 * we accepted http:// only so we could redirect to
829 * https://, so issue the redirect. Create the redirection
830 * URI from the host: header and ignore the path part
832 unsigned char *start = pt->serv_buf + LWS_PRE, *p = start,
835 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
838 n = sprintf((char *)end, "https://%s/",
839 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
841 n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
846 return lws_http_transaction_completed(wsi);
850 #ifdef LWS_WITH_ACCESS_LOG
852 * Produce Apache-compatible log string for wsi, like this:
854 * 2.31.234.19 - - [27/Mar/2016:03:22:44 +0800]
855 * "GET /aep-screen.png HTTP/1.1"
856 * 200 152987 "https://libwebsockets.org/index.html"
857 * "Mozilla/5.0 (Macint... Chrome/49.0.2623.87 Safari/537.36"
861 static const char * const hver[] = {
862 "http/1.0", "http/1.1", "http/2"
865 char ads[INET6_ADDRSTRLEN];
867 char ads[INET_ADDRSTRLEN];
872 time_t t = time(NULL);
875 if (wsi->access_log_pending)
878 wsi->access_log.header_log = lws_malloc(l);
879 if (wsi->access_log.header_log) {
883 strftime(da, sizeof(da), "%d/%b/%Y:%H:%M:%S %z", tmp);
885 strcpy(da, "01/Jan/1970:00:00:00 +0000");
887 pa = lws_get_peer_simple(wsi, ads, sizeof(ads));
892 me = method_names[meth];
896 lws_snprintf(wsi->access_log.header_log, l,
897 "%s - - [%s] \"%s %s %s\"",
899 hver[wsi->u.http.request_version]);
901 l = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT);
903 wsi->access_log.user_agent = lws_malloc(l + 2);
904 if (wsi->access_log.user_agent)
905 lws_hdr_copy(wsi, wsi->access_log.user_agent,
906 l + 1, WSI_TOKEN_HTTP_USER_AGENT);
908 lwsl_err("OOM getting user agent\n");
910 wsi->access_log_pending = 1;
915 /* can we serve it from the mount list? */
917 hit = lws_find_mount(wsi, uri_ptr, uri_len);
919 /* deferred cleanup and reset to protocols[0] */
921 lwsl_info("no hit\n");
923 if (lws_bind_protocol(wsi, &wsi->vhost->protocols[0]))
926 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
927 wsi->user_space, uri_ptr, uri_len);
932 s = uri_ptr + hit->mountpoint_len;
935 * if we have a mountpoint like https://xxx.com/yyy
936 * there is an implied / at the end for our purposes since
937 * we can only mount on a "directory".
939 * But if we just go with that, the browser cannot understand
940 * that he is actually looking down one "directory level", so
941 * even though we give him /yyy/abc.html he acts like the
942 * current directory level is /. So relative urls like "x.png"
943 * wrongly look outside the mountpoint.
945 * Therefore if we didn't come in on a url with an explicit
946 * / at the end, we must redirect to add it so the browser
947 * understands he is one "directory level" down.
949 if ((hit->mountpoint_len > 1 ||
950 (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
951 hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&
953 (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
954 hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&
955 (hit->origin_protocol != LWSMPRO_CGI &&
956 hit->origin_protocol != LWSMPRO_CALLBACK //&&
957 //hit->protocol == NULL
959 unsigned char *start = pt->serv_buf + LWS_PRE,
960 *p = start, *end = p + 512;
962 lwsl_debug("Doing 301 '%s' org %s\n", s, hit->origin);
964 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
967 /* > at start indicates deal with by redirect */
968 if (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
969 hit->origin_protocol == LWSMPRO_REDIR_HTTPS)
970 n = lws_snprintf((char *)end, 256, "%s%s",
971 oprot[hit->origin_protocol & 1],
974 n = lws_snprintf((char *)end, 256,
975 "%s%s%s/", oprot[lws_is_ssl(wsi)],
976 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST),
978 lws_clean_url((char *)end);
980 n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
985 return lws_http_transaction_completed(wsi);
991 if (hit->basic_auth_login_file) {
992 char b64[160], plain[(sizeof(b64) * 3) / 4];
995 /* Did he send auth? */
996 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_AUTHORIZATION))
997 return lws_unauthorised_basic_auth(wsi);
999 n = HTTP_STATUS_FORBIDDEN;
1001 m = lws_hdr_copy(wsi, b64, sizeof(b64), WSI_TOKEN_HTTP_AUTHORIZATION);
1003 lwsl_err("b64 auth too long\n");
1004 goto transaction_result_n;
1008 if (strcasecmp(b64, "Basic")) {
1009 lwsl_err("auth missing basic: %s\n", b64);
1010 goto transaction_result_n;
1013 /* It'll be like Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l */
1015 m = lws_b64_decode_string(b64 + 6, plain, sizeof(plain));
1017 lwsl_err("plain auth too long\n");
1018 goto transaction_result_n;
1021 // lwsl_notice(plain);
1023 if (!lws_find_string_in_file(hit->basic_auth_login_file, plain, m)) {
1024 lwsl_err("basic auth lookup failed\n");
1025 return lws_unauthorised_basic_auth(wsi);
1028 lwsl_notice("basic auth accepted\n");
1030 /* accept the auth */
1034 #if defined(LWS_WITH_HTTP_PROXY)
1036 * The mount is a reverse proxy?
1039 if (hit->origin_protocol == LWSMPRO_HTTPS ||
1040 hit->origin_protocol == LWSMPRO_HTTP) {
1041 struct lws_client_connect_info i;
1042 char ads[96], rpath[256], *pcolon, *pslash, *p;
1045 memset(&i, 0, sizeof(i));
1046 i.context = lws_get_context(wsi);
1048 pcolon = strchr(hit->origin, ':');
1049 pslash = strchr(hit->origin, '/');
1051 lwsl_err("Proxy mount origin '%s' must have /\n", hit->origin);
1054 if (pcolon > pslash)
1058 n = pcolon - hit->origin;
1060 n = pslash - hit->origin;
1062 if (n >= sizeof(ads) - 2)
1063 n = sizeof(ads) - 2;
1065 memcpy(ads, hit->origin, n);
1070 if (hit->origin_protocol == LWSMPRO_HTTPS) {
1072 i.ssl_connection = 1;
1075 i.port = atoi(pcolon + 1);
1077 lws_snprintf(rpath, sizeof(rpath) - 1, "/%s/%s", pslash + 1, uri_ptr + hit->mountpoint_len);
1078 lws_clean_url(rpath);
1079 na = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_URI_ARGS);
1081 p = rpath + strlen(rpath);
1083 lws_hdr_copy(wsi, p, &rpath[sizeof(rpath) - 1] - p, WSI_TOKEN_HTTP_URI_ARGS);
1097 i.uri_replace_from = hit->origin;
1098 i.uri_replace_to = hit->mountpoint;
1100 lwsl_notice("proxying to %s port %d url %s, ssl %d, from %s, to %s\n",
1101 i.address, i.port, i.path, i.ssl_connection, i.uri_replace_from, i.uri_replace_to);
1103 if (!lws_client_connect_via_info(&i)) {
1104 lwsl_err("proxy connect fail\n");
1113 * A particular protocol callback is mounted here?
1115 * For the duration of this http transaction, bind us to the
1116 * associated protocol
1118 if (hit->origin_protocol == LWSMPRO_CALLBACK || hit->protocol) {
1119 const struct lws_protocols *pp;
1120 const char *name = hit->origin;
1122 name = hit->protocol;
1124 pp = lws_vhost_name_to_protocol(wsi->vhost, name);
1127 lwsl_err("Unable to find plugin '%s'\n",
1132 if (lws_bind_protocol(wsi, pp))
1137 args.max_len = hit->auth_mask;
1138 args.final = 0; /* used to signal callback dealt with it */
1140 n = wsi->protocol->callback(wsi, LWS_CALLBACK_CHECK_ACCESS_RIGHTS,
1141 wsi->user_space, &args, 0);
1143 lws_return_http_status(wsi, HTTP_STATUS_UNAUTHORIZED,
1147 if (args.final) /* callback completely handled it well */
1150 if (hit->cgienv && wsi->protocol->callback(wsi,
1151 LWS_CALLBACK_HTTP_PMO,
1152 wsi->user_space, (void *)hit->cgienv, 0))
1155 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) {
1156 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
1158 uri_ptr + hit->mountpoint_len,
1159 uri_len - hit->mountpoint_len);
1165 /* did we hit something with a cgi:// origin? */
1166 if (hit->origin_protocol == LWSMPRO_CGI) {
1167 const char *cmd[] = {
1168 NULL, /* replace with cgi path */
1172 lwsl_debug("%s: cgi\n", __func__);
1173 cmd[0] = hit->origin;
1176 if (hit->cgi_timeout)
1177 n = hit->cgi_timeout;
1179 n = lws_cgi(wsi, cmd, hit->mountpoint_len, n,
1182 lwsl_err("%s: cgi failed\n", __func__);
1191 if (s[0] == '\0' || (n == 1 && s[n - 1] == '/'))
1192 s = (char *)hit->def;
1196 wsi->cache_secs = hit->cache_max_age;
1197 wsi->cache_reuse = hit->cache_reusable;
1198 wsi->cache_revalidate = hit->cache_revalidate;
1199 wsi->cache_intermediaries = hit->cache_intermediaries;
1201 n = lws_http_serve(wsi, s, hit->origin, hit);
1204 * lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
1206 if (hit->protocol) {
1207 const struct lws_protocols *pp = lws_vhost_name_to_protocol(
1208 wsi->vhost, hit->protocol);
1210 if (lws_bind_protocol(wsi, pp))
1213 n = pp->callback(wsi, LWS_CALLBACK_HTTP,
1215 uri_ptr + hit->mountpoint_len,
1216 uri_len - hit->mountpoint_len);
1218 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
1219 wsi->user_space, uri_ptr, uri_len);
1224 lwsl_info("LWS_CALLBACK_HTTP closing\n");
1233 * If we're not issuing a file, check for content_length or
1234 * HTTP keep-alive. No keep-alive header allocation for
1235 * ISSUING_FILE, as this uses HTTP/1.0.
1237 * In any case, return 0 and let lws_read decide how to
1238 * proceed based on state
1240 if (wsi->state != LWSS_HTTP_ISSUING_FILE)
1241 /* Prepare to read body if we have a content length: */
1242 if (wsi->u.http.content_length > 0)
1243 wsi->state = LWSS_HTTP_BODY;
1248 /* we're closing, losing some rx is OK */
1249 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1250 // lwsl_notice("%s: drop1\n", __func__);
1251 lws_header_table_detach(wsi, 1);
1255 transaction_result_n:
1256 lws_return_http_status(wsi, n, NULL);
1258 return lws_http_transaction_completed(wsi);
1263 lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len)
1265 int protocol_len, n = 0, hit, non_space_char_found = 0, m;
1266 struct lws_context *context = lws_get_context(wsi);
1267 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1268 struct _lws_header_related hdr;
1269 struct allocated_headers *ah;
1270 unsigned char *obuf = *buf;
1271 char protocol_list[128];
1272 char protocol_name[64];
1276 if (len >= 10000000) {
1277 lwsl_err("%s: assert: len %ld\n", __func__, (long)len);
1281 if (!wsi->u.hdr.ah) {
1282 lwsl_err("%s: assert: NULL ah\n", __func__);
1287 wsi->more_rx_waiting = !!len;
1289 if (wsi->mode != LWSCM_HTTP_SERVING &&
1290 wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED) {
1291 lwsl_err("%s: bad wsi mode %d\n", __func__, wsi->mode);
1295 m = lws_parse(wsi, *(*buf)++);
1299 * we are transitioning from http with
1300 * an AH, to raw. Drop the ah and set
1304 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1305 lws_bind_protocol(wsi, &wsi->vhost->protocols[
1307 raw_protocol_index]);
1308 lwsl_info("transition to raw vh %s prot %d\n",
1310 wsi->vhost->raw_protocol_index);
1311 if ((wsi->protocol->callback)(wsi,
1312 LWS_CALLBACK_RAW_ADOPT,
1313 wsi->user_space, NULL, 0))
1316 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1317 lws_union_transition(wsi, LWSCM_RAW);
1318 lws_header_table_detach(wsi, 1);
1320 if (m == 2 && (wsi->protocol->callback)(wsi,
1321 LWS_CALLBACK_RAW_RX,
1322 wsi->user_space, obuf, olen))
1327 lwsl_info("lws_parse failed\n");
1331 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
1334 lwsl_parser("%s: lws_parse sees parsing complete\n", __func__);
1335 lwsl_debug("%s: wsi->more_rx_waiting=%d\n", __func__,
1336 wsi->more_rx_waiting);
1338 /* check for unwelcome guests */
1340 if (wsi->context->reject_service_keywords) {
1341 const struct lws_protocol_vhost_options *rej =
1342 wsi->context->reject_service_keywords;
1343 char ua[384], *msg = NULL;
1345 if (lws_hdr_copy(wsi, ua, sizeof(ua) - 1,
1346 WSI_TOKEN_HTTP_USER_AGENT) > 0) {
1347 ua[sizeof(ua) - 1] = '\0';
1349 if (strstr(ua, rej->name)) {
1350 msg = strchr(rej->value, ' ');
1353 lws_return_http_status(wsi, atoi(rej->value), msg);
1355 wsi->vhost->conn_stats.rejected++;
1366 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
1367 struct lws_vhost *vhost = lws_select_vhost(
1368 context, wsi->vhost->listen_port,
1369 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
1374 lwsl_info("no host\n");
1376 wsi->vhost->conn_stats.trans++;
1377 if (!wsi->conn_stat_done) {
1378 wsi->vhost->conn_stats.conn++;
1379 wsi->conn_stat_done = 1;
1382 if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECT)) {
1383 lwsl_info("Changing to RAW mode\n");
1385 goto raw_transition;
1388 wsi->mode = LWSCM_PRE_WS_SERVING_ACCEPT;
1389 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1391 /* is this websocket protocol or normal http 1.0? */
1393 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
1394 if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
1396 wsi->vhost->conn_stats.ws_upg++;
1397 lwsl_info("Upgrade to ws\n");
1400 #ifdef LWS_USE_HTTP2
1401 if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
1403 wsi->vhost->conn_stats.http2_upg++;
1404 lwsl_info("Upgrade to h2c\n");
1408 lwsl_info("Unknown upgrade\n");
1409 /* dunno what he wanted to upgrade to */
1413 /* no upgrade ack... he remained as HTTP */
1415 lwsl_info("No upgrade\n");
1418 lws_union_transition(wsi, LWSCM_HTTP_SERVING_ACCEPTED);
1419 wsi->state = LWSS_HTTP;
1420 wsi->u.http.fop_fd = NULL;
1422 /* expose it at the same offset as u.hdr */
1423 wsi->u.http.ah = ah;
1424 lwsl_debug("%s: wsi %p: ah %p\n", __func__, (void *)wsi,
1425 (void *)wsi->u.hdr.ah);
1427 n = lws_http_action(wsi);
1431 #ifdef LWS_USE_HTTP2
1433 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) {
1434 lwsl_info("missing http2_settings\n");
1438 lwsl_info("h2c upgrade...\n");
1440 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS);
1441 /* convert the peer's HTTP-Settings */
1442 n = lws_b64_decode_string(p, protocol_list,
1443 sizeof(protocol_list));
1445 lwsl_parser("HTTP2_SETTINGS too long\n");
1449 /* adopt the header info */
1453 lws_union_transition(wsi, LWSCM_HTTP2_SERVING);
1455 /* http2 union member has http union struct at start */
1456 wsi->u.http.ah = ah;
1458 lws_http2_init(&wsi->u.http2.peer_settings);
1459 lws_http2_init(&wsi->u.http2.my_settings);
1463 lws_http2_interpret_settings_payload(&wsi->u.http2.peer_settings,
1464 (unsigned char *)protocol_list, n);
1466 strcpy(protocol_list,
1467 "HTTP/1.1 101 Switching Protocols\x0d\x0a"
1468 "Connection: Upgrade\x0d\x0a"
1469 "Upgrade: h2c\x0d\x0a\x0d\x0a");
1470 n = lws_issue_raw(wsi, (unsigned char *)protocol_list,
1471 strlen(protocol_list));
1472 if (n != strlen(protocol_list)) {
1473 lwsl_debug("http2 switch: ERROR writing to socket\n");
1477 wsi->state = LWSS_HTTP2_AWAIT_CLIENT_PREFACE;
1484 lwsl_err("NULL protocol at lws_read\n");
1489 * Select the first protocol we support from the list
1490 * the client sent us.
1492 * Copy it to remove header fragmentation
1495 if (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1,
1496 WSI_TOKEN_PROTOCOL) < 0) {
1497 lwsl_err("protocol list too long");
1501 protocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
1502 protocol_list[protocol_len] = '\0';
1506 while (*p && !hit) {
1508 non_space_char_found = 0;
1509 while (n < sizeof(protocol_name) - 1 && *p &&
1511 // ignore leading spaces
1512 if (!non_space_char_found && *p == ' ') {
1516 non_space_char_found = 1;
1517 protocol_name[n++] = *p++;
1519 protocol_name[n] = '\0';
1523 lwsl_info("checking %s\n", protocol_name);
1526 while (wsi->vhost->protocols[n].callback) {
1527 lwsl_info("try %s\n", wsi->vhost->protocols[n].name);
1529 if (wsi->vhost->protocols[n].name &&
1530 !strcmp(wsi->vhost->protocols[n].name,
1532 wsi->protocol = &wsi->vhost->protocols[n];
1541 /* we didn't find a protocol he wanted? */
1544 if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL)) {
1545 lwsl_info("No protocol from \"%s\" supported\n",
1550 * some clients only have one protocol and
1551 * do not send the protocol list header...
1552 * allow it and match to the vhost's default
1553 * protocol (which itself defaults to zero)
1555 lwsl_info("defaulting to prot handler %d\n",
1556 wsi->vhost->default_protocol_index);
1557 n = wsi->vhost->default_protocol_index;
1558 wsi->protocol = &wsi->vhost->protocols[
1559 (int)wsi->vhost->default_protocol_index];
1562 /* allocate wsi->user storage */
1563 if (lws_ensure_user_space(wsi))
1567 * Give the user code a chance to study the request and
1568 * have the opportunity to deny it
1570 if ((wsi->protocol->callback)(wsi,
1571 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
1573 lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) {
1574 lwsl_warn("User code denied connection\n");
1579 * Perform the handshake according to the protocol version the
1583 switch (wsi->ietf_spec_revision) {
1585 lwsl_parser("lws_parse calling handshake_04\n");
1586 if (handshake_0405(context, wsi)) {
1587 lwsl_info("hs0405 has failed the connection\n");
1593 lwsl_info("Unknown client spec version %d\n",
1594 wsi->ietf_spec_revision);
1598 lws_same_vh_protocol_insert(wsi, n);
1600 /* we are upgrading to ws, so http/1.1 and keepalive +
1601 * pipelined header considerations about keeping the ah around
1602 * no longer apply. However it's common for the first ws
1603 * protocol data to have been coalesced with the browser
1604 * upgrade request and to already be in the ah rx buffer.
1607 lwsl_info("%s: %p: inheriting ah in ws mode (rxpos:%d, rxlen:%d)\n",
1608 __func__, wsi, wsi->u.hdr.ah->rxpos,
1609 wsi->u.hdr.ah->rxlen);
1613 lws_union_transition(wsi, LWSCM_WS_SERVING);
1615 * first service is WS mode will notice this, use the RX and
1616 * then detach the ah (caution: we are not in u.hdr union
1617 * mode any more then... ah_temp member is at start the same
1620 * Because rxpos/rxlen shows something in the ah, we will get
1621 * service guaranteed next time around the event loop
1623 * All union members begin with hdr, so we can use it even
1624 * though we transitioned to ws union mode (the ah detach
1625 * code uses it anyway).
1630 lws_restart_ws_ping_pong_timer(wsi);
1633 * create the frame buffer for this connection according to the
1634 * size mentioned in the protocol definition. If 0 there, use
1635 * a big default for compatibility
1638 n = wsi->protocol->rx_buffer_size;
1640 n = context->pt_serv_buf_size;
1642 wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
1643 if (!wsi->u.ws.rx_ubuf) {
1644 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
1647 wsi->u.ws.rx_ubuf_alloc = n;
1648 lwsl_debug("Allocating RX buffer %d\n", n);
1649 #if LWS_POSIX && !defined(LWS_WITH_ESP32)
1650 if (setsockopt(wsi->desc.sockfd, SOL_SOCKET, SO_SNDBUF,
1651 (const char *)&n, sizeof n)) {
1652 lwsl_warn("Failed to set SNDBUF to %d", n);
1657 lwsl_parser("accepted v%02d connection\n",
1658 wsi->ietf_spec_revision);
1660 /* notify user code that we're ready to roll */
1662 if (wsi->protocol->callback)
1663 if (wsi->protocol->callback(wsi, LWS_CALLBACK_ESTABLISHED,
1665 #ifdef LWS_OPENSSL_SUPPORT
1673 /* !!! drop ah unreservedly after ESTABLISHED */
1674 if (!wsi->more_rx_waiting) {
1675 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1677 //lwsl_notice("%p: dropping ah EST\n", wsi);
1678 lws_header_table_detach(wsi, 1);
1682 } /* while all chars are handled */
1687 /* drop the header info */
1688 /* we're closing, losing some rx is OK */
1689 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1690 //lwsl_notice("%s: drop2\n", __func__);
1691 lws_header_table_detach(wsi, 1);
1697 lws_get_idlest_tsi(struct lws_context *context)
1699 unsigned int lowest = ~0;
1700 int n = 0, hit = -1;
1702 for (; n < context->count_threads; n++) {
1703 if ((unsigned int)context->pt[n].fds_count !=
1704 context->fd_limit_per_thread - 1 &&
1705 (unsigned int)context->pt[n].fds_count < lowest) {
1706 lowest = context->pt[n].fds_count;
1715 lws_create_new_server_wsi(struct lws_vhost *vhost)
1717 struct lws *new_wsi;
1718 int n = lws_get_idlest_tsi(vhost->context);
1721 lwsl_err("no space for new conn\n");
1725 new_wsi = lws_zalloc(sizeof(struct lws));
1726 if (new_wsi == NULL) {
1727 lwsl_err("Out of memory for new connection\n");
1732 lwsl_debug("Accepted wsi %p to context %p, tsi %d\n", new_wsi,
1733 vhost->context, new_wsi->tsi);
1735 new_wsi->vhost = vhost;
1736 new_wsi->context = vhost->context;
1737 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1738 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1740 /* initialize the instance struct */
1742 new_wsi->state = LWSS_HTTP;
1743 new_wsi->mode = LWSCM_HTTP_SERVING;
1744 new_wsi->hdr_parsing_completed = 0;
1746 #ifdef LWS_OPENSSL_SUPPORT
1747 new_wsi->use_ssl = LWS_SSL_ENABLED(vhost);
1751 * these can only be set once the protocol is known
1752 * we set an unestablished connection's protocol pointer
1753 * to the start of the supported list, so it can look
1754 * for matching ones during the handshake
1756 new_wsi->protocol = vhost->protocols;
1757 new_wsi->user_space = NULL;
1758 new_wsi->ietf_spec_revision = 0;
1759 new_wsi->desc.sockfd = LWS_SOCK_INVALID;
1760 vhost->context->count_wsi_allocated++;
1763 * outermost create notification for wsi
1764 * no user_space because no protocol selection
1766 vhost->protocols[0].callback(new_wsi, LWS_CALLBACK_WSI_CREATE,
1772 LWS_VISIBLE int LWS_WARN_UNUSED_RESULT
1773 lws_http_transaction_completed(struct lws *wsi)
1775 int n = NO_PENDING_TIMEOUT;
1777 lws_access_log(wsi);
1779 lwsl_info("%s: wsi %p\n", __func__, wsi);
1780 /* if we can't go back to accept new headers, drop the connection */
1781 if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
1782 lwsl_info("%s: %p: close connection\n", __func__, wsi);
1786 if (lws_bind_protocol(wsi, &wsi->vhost->protocols[0]))
1789 /* otherwise set ourselves up ready to go again */
1790 wsi->state = LWSS_HTTP;
1791 wsi->mode = LWSCM_HTTP_SERVING;
1792 wsi->u.http.content_length = 0;
1793 wsi->u.http.content_remain = 0;
1794 wsi->hdr_parsing_completed = 0;
1795 #ifdef LWS_WITH_ACCESS_LOG
1796 wsi->access_log.sent = 0;
1799 if (wsi->vhost->keepalive_timeout)
1800 n = PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE;
1801 lws_set_timeout(wsi, n, wsi->vhost->keepalive_timeout);
1804 * We already know we are on http1.1 / keepalive and the next thing
1805 * coming will be another header set.
1807 * If there is no pending rx and we still have the ah, drop it and
1808 * reacquire a new ah when the new headers start to arrive. (Otherwise
1809 * we needlessly hog an ah indefinitely.)
1811 * However if there is pending rx and we know from the keepalive state
1812 * that is already at least the start of another header set, simply
1813 * reset the existing header table and keep it.
1815 if (wsi->u.hdr.ah) {
1816 lwsl_info("%s: wsi->more_rx_waiting=%d\n", __func__,
1817 wsi->more_rx_waiting);
1819 if (!wsi->more_rx_waiting) {
1820 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1821 lws_header_table_detach(wsi, 1);
1822 #ifdef LWS_OPENSSL_SUPPORT
1824 * additionally... if we are hogging an SSL instance
1825 * with no pending pipelined headers (or ah now), and
1826 * SSL is scarce, drop this connection without waiting
1829 if (wsi->vhost->use_ssl &&
1830 wsi->context->simultaneous_ssl_restriction &&
1831 wsi->context->simultaneous_ssl ==
1832 wsi->context->simultaneous_ssl_restriction) {
1833 lwsl_info("%s: simultaneous_ssl_restriction and nothing pipelined\n", __func__);
1838 lws_header_table_reset(wsi, 1);
1841 /* If we're (re)starting on headers, need other implied init */
1842 wsi->u.hdr.ues = URIES_IDLE;
1844 lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
1849 /* if not a socket, it's a raw, non-ssl file descriptor */
1851 LWS_VISIBLE struct lws *
1852 lws_adopt_descriptor_vhost(struct lws_vhost *vh, lws_adoption_type type,
1853 lws_sock_file_fd_type fd, const char *vh_prot_name,
1856 struct lws_context *context = vh->context;
1857 struct lws *new_wsi = lws_create_new_server_wsi(vh);
1858 struct lws_context_per_thread *pt;
1862 if (type & LWS_ADOPT_SOCKET)
1863 compatible_close(fd.sockfd);
1866 pt = &context->pt[(int)new_wsi->tsi];
1867 lws_stats_atomic_bump(context, pt, LWSSTATS_C_CONNECTIONS, 1);
1870 new_wsi->parent = parent;
1871 new_wsi->sibling_list = parent->child_list;
1872 parent->child_list = new_wsi;
1878 new_wsi->protocol = lws_vhost_name_to_protocol(new_wsi->vhost,
1880 if (!new_wsi->protocol) {
1881 lwsl_err("Protocol %s not enabled on vhost %s\n",
1882 vh_prot_name, new_wsi->vhost->name);
1885 if (lws_ensure_user_space(new_wsi)) {
1886 lwsl_notice("OOM trying to get user_space\n");
1890 if (type & LWS_ADOPT_HTTP) /* he will transition later */
1892 &vh->protocols[vh->default_protocol_index];
1893 else { /* this is the only time he will transition */
1894 lws_bind_protocol(new_wsi,
1895 &vh->protocols[vh->raw_protocol_index]);
1896 lws_union_transition(new_wsi, LWSCM_RAW);
1899 if (type & LWS_ADOPT_SOCKET) { /* socket desc */
1900 lwsl_debug("%s: new wsi %p, sockfd %d\n", __func__, new_wsi,
1901 (int)(size_t)fd.sockfd);
1903 if (type & LWS_ADOPT_HTTP)
1904 /* the transport is accepted...
1905 * give him time to negotiate */
1906 lws_set_timeout(new_wsi,
1907 PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
1908 context->timeout_secs);
1911 #if defined(LWS_WITH_ESP8266)
1912 esp8266_tcp_stream_accept(accept_fd, new_wsi);
1915 } else /* file desc */
1916 lwsl_debug("%s: new wsi %p, filefd %d\n", __func__, new_wsi,
1917 (int)(size_t)fd.filefd);
1920 * A new connection was accepted. Give the user a chance to
1921 * set properties of the newly created wsi. There's no protocol
1922 * selected yet so we issue this to the vhosts's default protocol,
1923 * itself by default protocols[0]
1925 n = LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED;
1926 if (!(type & LWS_ADOPT_HTTP)) {
1927 if (!(type & LWS_ADOPT_SOCKET))
1928 n = LWS_CALLBACK_RAW_ADOPT_FILE;
1930 n = LWS_CALLBACK_RAW_ADOPT;
1933 if (!LWS_SSL_ENABLED(new_wsi->vhost) || !(type & LWS_ADOPT_ALLOW_SSL) ||
1934 !(type & LWS_ADOPT_SOCKET)) {
1936 if (!(type & LWS_ADOPT_HTTP)) {
1937 if (!(type & LWS_ADOPT_SOCKET))
1938 new_wsi->mode = LWSCM_RAW_FILEDESC;
1940 new_wsi->mode = LWSCM_RAW;
1944 if (!(type & LWS_ADOPT_HTTP))
1945 new_wsi->mode = LWSCM_SSL_INIT_RAW;
1947 new_wsi->mode = LWSCM_SSL_INIT;
1952 lws_libev_accept(new_wsi, new_wsi->desc);
1953 lws_libuv_accept(new_wsi, new_wsi->desc);
1954 lws_libevent_accept(new_wsi, new_wsi->desc);
1957 if (insert_wsi_socket_into_fds(context, new_wsi)) {
1958 lwsl_err("%s: fail inserting socket\n", __func__);
1962 if (lws_server_socket_service_ssl(new_wsi, fd.sockfd)) {
1963 lwsl_err("%s: fail ssl negotiation\n", __func__);
1968 * by deferring callback to this point, after insertion to fds,
1969 * lws_callback_on_writable() can work from the callback
1971 if ((new_wsi->protocol->callback)(
1972 new_wsi, n, new_wsi->user_space, NULL, 0))
1975 if (type & LWS_ADOPT_HTTP) {
1976 if (!lws_header_table_attach(new_wsi, 0)) {
1977 lwsl_debug("Attached ah immediately\n");
1979 lwsl_notice("%s: waiting for ah\n", __func__);
1986 if (type & LWS_ADOPT_SOCKET)
1987 lws_close_free_wsi(new_wsi, LWS_CLOSE_STATUS_NOSTATUS);
1992 lwsl_notice("%s: exiting on bail\n", __func__);
1994 parent->child_list = new_wsi->sibling_list;
1995 if (new_wsi->user_space)
1996 lws_free(new_wsi->user_space);
1998 compatible_close(fd.sockfd);
2003 LWS_VISIBLE struct lws *
2004 lws_adopt_socket_vhost(struct lws_vhost *vh, lws_sockfd_type accept_fd)
2006 lws_sock_file_fd_type fd;
2008 fd.sockfd = accept_fd;
2009 return lws_adopt_descriptor_vhost(vh, LWS_ADOPT_SOCKET |
2010 LWS_ADOPT_HTTP | LWS_ADOPT_ALLOW_SSL, fd, NULL, NULL);
2013 LWS_VISIBLE struct lws *
2014 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd)
2016 return lws_adopt_socket_vhost(context->vhost_list, accept_fd);
2019 /* Common read-buffer adoption for lws_adopt_*_readbuf */
2021 adopt_socket_readbuf(struct lws *wsi, const char *readbuf, size_t len)
2023 struct lws_context_per_thread *pt;
2024 struct allocated_headers *ah;
2025 struct lws_pollfd *pfd;
2030 if (!readbuf || len == 0)
2033 if (len > sizeof(ah->rx)) {
2034 lwsl_err("%s: rx in too big\n", __func__);
2039 * we can't process the initial read data until we can attach an ah.
2041 * if one is available, get it and place the data in his ah rxbuf...
2042 * wsi with ah that have pending rxbuf get auto-POLLIN service.
2044 * no autoservice because we didn't get a chance to attach the
2045 * readbuf data to wsi or ah yet, and we will do it next if we get
2048 if (wsi->u.hdr.ah || !lws_header_table_attach(wsi, 0)) {
2050 memcpy(ah->rx, readbuf, len);
2054 lwsl_notice("%s: calling service on readbuf ah\n", __func__);
2055 pt = &wsi->context->pt[(int)wsi->tsi];
2057 /* unlike a normal connect, we have the headers already
2058 * (or the first part of them anyway).
2059 * libuv won't come back and service us without a network
2060 * event, so we need to do the header service right here.
2062 pfd = &pt->fds[wsi->position_in_fds_table];
2063 pfd->revents |= LWS_POLLIN;
2064 lwsl_err("%s: calling service\n", __func__);
2065 if (lws_service_fd_tsi(wsi->context, pfd, wsi->tsi))
2066 /* service closed us */
2071 lwsl_err("%s: deferring handling ah\n", __func__);
2073 * hum if no ah came, we are on the wait list and must defer
2074 * dealing with this until the ah arrives.
2076 * later successful lws_header_table_attach() will apply the
2077 * below to the rx buffer (via lws_header_table_reset()).
2079 wsi->u.hdr.preamble_rx = lws_malloc(len);
2080 if (!wsi->u.hdr.preamble_rx) {
2084 memcpy(wsi->u.hdr.preamble_rx, readbuf, len);
2085 wsi->u.hdr.preamble_rx_len = len;
2090 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
2095 LWS_VISIBLE struct lws *
2096 lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
2097 const char *readbuf, size_t len)
2099 return adopt_socket_readbuf(lws_adopt_socket(context, accept_fd), readbuf, len);
2102 LWS_VISIBLE struct lws *
2103 lws_adopt_socket_vhost_readbuf(struct lws_vhost *vhost, lws_sockfd_type accept_fd,
2104 const char *readbuf, size_t len)
2106 return adopt_socket_readbuf(lws_adopt_socket_vhost(vhost, accept_fd), readbuf, len);
2110 lws_server_socket_service(struct lws_context *context, struct lws *wsi,
2111 struct lws_pollfd *pollfd)
2113 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
2114 lws_sockfd_type accept_fd = LWS_SOCK_INVALID;
2115 struct allocated_headers *ah;
2116 lws_sock_file_fd_type fd;
2117 int opts = LWS_ADOPT_SOCKET | LWS_ADOPT_ALLOW_SSL;
2119 struct sockaddr_storage cli_addr;
2124 // lwsl_notice("%s: mode %d\n", __func__, wsi->mode);
2126 switch (wsi->mode) {
2128 case LWSCM_HTTP_SERVING:
2129 case LWSCM_HTTP_SERVING_ACCEPTED:
2130 case LWSCM_HTTP2_SERVING:
2133 /* handle http headers coming in */
2135 /* pending truncated sends have uber priority */
2137 if (wsi->trunc_len) {
2138 if (!(pollfd->revents & LWS_POLLOUT))
2141 if (lws_issue_raw(wsi, wsi->trunc_alloc +
2143 wsi->trunc_len) < 0)
2146 * we can't afford to allow input processing to send
2147 * something new, so spin around he event loop until
2148 * he doesn't have any partials
2153 /* any incoming data ready? */
2155 if (!(pollfd->revents & pollfd->events & LWS_POLLIN))
2159 * If we previously just did POLLIN when IN and OUT were
2160 * signalled (because POLLIN processing may have used up
2161 * the POLLOUT), don't let that happen twice in a row...
2162 * next time we see the situation favour POLLOUT
2164 #if !defined(LWS_WITH_ESP8266)
2165 if (wsi->favoured_pollin &&
2166 (pollfd->revents & pollfd->events & LWS_POLLOUT)) {
2167 wsi->favoured_pollin = 0;
2172 /* these states imply we MUST have an ah attached */
2174 if (wsi->mode != LWSCM_RAW && (wsi->state == LWSS_HTTP ||
2175 wsi->state == LWSS_HTTP_ISSUING_FILE ||
2176 wsi->state == LWSS_HTTP_HEADERS)) {
2177 if (!wsi->u.hdr.ah) {
2179 //lwsl_err("wsi %p: missing ah\n", wsi);
2180 /* no autoservice beacuse we will do it next */
2181 if (lws_header_table_attach(wsi, 0)) {
2182 lwsl_info("wsi %p: failed to acquire ah\n", wsi);
2188 //lwsl_notice("%s: %p: rxpos:%d rxlen:%d\n", __func__, wsi,
2189 // ah->rxpos, ah->rxlen);
2191 /* if nothing in ah rx buffer, get some fresh rx */
2192 if (ah->rxpos == ah->rxlen) {
2193 ah->rxlen = lws_ssl_capable_read(wsi, ah->rx,
2196 //lwsl_notice("%s: wsi %p, ah->rxlen = %d\r\n",
2197 // __func__, wsi, ah->rxlen);
2198 switch (ah->rxlen) {
2200 lwsl_info("%s: read 0 len\n", __func__);
2201 /* lwsl_info(" state=%d\n", wsi->state); */
2202 // if (!wsi->hdr_parsing_completed)
2203 // lws_header_table_detach(wsi);
2205 case LWS_SSL_CAPABLE_ERROR:
2207 case LWS_SSL_CAPABLE_MORE_SERVICE:
2208 ah->rxlen = ah->rxpos = 0;
2213 if (!(ah->rxpos != ah->rxlen && ah->rxlen)) {
2214 lwsl_err("%s: assert: rxpos %d, rxlen %d\n",
2215 __func__, ah->rxpos, ah->rxlen);
2220 /* just ignore incoming if waiting for close */
2221 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
2222 n = lws_read(wsi, ah->rx + ah->rxpos,
2223 ah->rxlen - ah->rxpos);
2224 if (n < 0) /* we closed wsi */
2226 if (wsi->u.hdr.ah) {
2227 if ( wsi->u.hdr.ah->rxlen)
2228 wsi->u.hdr.ah->rxpos += n;
2230 lwsl_debug("%s: wsi %p: ah read rxpos %d, rxlen %d\n", __func__, wsi, wsi->u.hdr.ah->rxpos, wsi->u.hdr.ah->rxlen);
2232 if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen &&
2233 (wsi->mode != LWSCM_HTTP_SERVING &&
2234 wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED &&
2235 wsi->mode != LWSCM_HTTP2_SERVING))
2236 lws_header_table_detach(wsi, 1);
2244 len = lws_ssl_capable_read(wsi, pt->serv_buf,
2245 context->pt_serv_buf_size);
2246 lwsl_debug("%s: wsi %p read %d\r\n", __func__, wsi, len);
2249 lwsl_info("%s: read 0 len\n", __func__);
2250 /* lwsl_info(" state=%d\n", wsi->state); */
2251 // if (!wsi->hdr_parsing_completed)
2252 // lws_header_table_detach(wsi);
2254 case LWS_SSL_CAPABLE_ERROR:
2256 case LWS_SSL_CAPABLE_MORE_SERVICE:
2260 if (wsi->mode == LWSCM_RAW) {
2261 n = user_callback_handle_rxflow(wsi->protocol->callback,
2262 wsi, LWS_CALLBACK_RAW_RX,
2263 wsi->user_space, pt->serv_buf, len);
2265 lwsl_info("LWS_CALLBACK_RAW_RX_fail\n");
2271 /* just ignore incoming if waiting for close */
2272 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
2274 * this may want to send
2275 * (via HTTP callback for example)
2277 n = lws_read(wsi, pt->serv_buf, len);
2278 if (n < 0) /* we closed wsi */
2281 * he may have used up the
2282 * writability above, if we will defer POLLOUT
2283 * processing in favour of POLLIN, note it
2285 if (pollfd->revents & LWS_POLLOUT)
2286 wsi->favoured_pollin = 1;
2292 /* this handles POLLOUT for http serving fragments */
2294 if (!(pollfd->revents & LWS_POLLOUT))
2298 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
2299 lwsl_notice("%s a\n", __func__);
2303 if (wsi->mode == LWSCM_RAW) {
2304 lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_WRITEABLE_CB, 1);
2305 #if defined(LWS_WITH_STATS)
2307 uint64_t ul = time_in_microseconds() - wsi->active_writable_req_us;
2309 lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_MS_WRITABLE_DELAY, ul);
2310 lws_stats_atomic_max(wsi->context, pt, LWSSTATS_MS_WORST_WRITABLE_DELAY, ul);
2311 wsi->active_writable_req_us = 0;
2314 n = user_callback_handle_rxflow(wsi->protocol->callback,
2315 wsi, LWS_CALLBACK_RAW_WRITEABLE,
2316 wsi->user_space, NULL, 0);
2318 lwsl_info("writeable_fail\n");
2324 if (!wsi->hdr_parsing_completed)
2327 if (wsi->state != LWSS_HTTP_ISSUING_FILE) {
2329 lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_WRITEABLE_CB, 1);
2330 #if defined(LWS_WITH_STATS)
2332 uint64_t ul = time_in_microseconds() - wsi->active_writable_req_us;
2334 lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_MS_WRITABLE_DELAY, ul);
2335 lws_stats_atomic_max(wsi->context, pt, LWSSTATS_MS_WORST_WRITABLE_DELAY, ul);
2336 wsi->active_writable_req_us = 0;
2340 n = user_callback_handle_rxflow(wsi->protocol->callback,
2341 wsi, LWS_CALLBACK_HTTP_WRITEABLE,
2342 wsi->user_space, NULL, 0);
2344 lwsl_info("writeable_fail\n");
2350 /* >0 == completion, <0 == error */
2351 n = lws_serve_http_file_fragment(wsi);
2352 if (n < 0 || (n > 0 && lws_http_transaction_completed(wsi))) {
2353 lwsl_info("completed\n");
2359 case LWSCM_SERVER_LISTENER:
2362 /* pollin means a client has connected to us then */
2365 if (!(pollfd->revents & LWS_POLLIN) || !(pollfd->events & LWS_POLLIN))
2368 #ifdef LWS_OPENSSL_SUPPORT
2370 * can we really accept it, with regards to SSL limit?
2371 * another vhost may also have had POLLIN on his listener this
2372 * round and used it up already
2375 if (wsi->vhost->use_ssl &&
2376 context->simultaneous_ssl_restriction &&
2377 context->simultaneous_ssl ==
2378 context->simultaneous_ssl_restriction)
2379 /* no... ignore it, he won't come again until we are
2380 * below the simultaneous_ssl_restriction limit and
2381 * POLLIN is enabled on him again
2385 /* listen socket got an unencrypted connection... */
2387 clilen = sizeof(cli_addr);
2388 lws_latency_pre(context, wsi);
2389 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
2391 lws_latency(context, wsi, "listener accept", accept_fd,
2393 if (accept_fd < 0) {
2394 if (LWS_ERRNO == LWS_EAGAIN ||
2395 LWS_ERRNO == LWS_EWOULDBLOCK) {
2396 // lwsl_err("accept asks to try again\n");
2399 lwsl_err("ERROR on accept: %s\n", strerror(LWS_ERRNO));
2403 lws_plat_set_socket_options(wsi->vhost, accept_fd);
2405 #if defined(LWS_USE_IPV6)
2406 lwsl_debug("accepted new conn port %u on fd=%d\n",
2407 ((cli_addr.ss_family == AF_INET6) ?
2408 ntohs(((struct sockaddr_in6 *) &cli_addr)->sin6_port) :
2409 ntohs(((struct sockaddr_in *) &cli_addr)->sin_port)),
2412 lwsl_debug("accepted new conn port %u on fd=%d\n",
2413 ntohs(((struct sockaddr_in *) &cli_addr)->sin_port),
2418 /* not very beautiful... */
2419 accept_fd = (lws_sockfd_type)pollfd;
2422 * look at who we connected to and give user code a chance
2423 * to reject based on client IP. There's no protocol selected
2424 * yet so we issue this to protocols[0]
2426 if ((wsi->vhost->protocols[0].callback)(wsi,
2427 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
2428 NULL, (void *)(long)accept_fd, 0)) {
2429 lwsl_debug("Callback denied network connection\n");
2430 compatible_close(accept_fd);
2434 if (!(wsi->vhost->options & LWS_SERVER_OPTION_ONLY_RAW))
2435 opts |= LWS_ADOPT_HTTP;
2437 fd.sockfd = accept_fd;
2438 if (!lws_adopt_descriptor_vhost(wsi->vhost, opts, fd,
2440 /* already closed cleanly as necessary */
2444 } while (pt->fds_count < context->fd_limit_per_thread - 1 &&
2445 lws_poll_listen_fd(&pt->fds[wsi->position_in_fds_table]) > 0);
2453 if (!lws_server_socket_service_ssl(wsi, accept_fd))
2457 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
2463 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
2464 const char *other_headers, int other_headers_len)
2466 static const char * const intermediates[] = { "private", "public" };
2467 struct lws_context *context = lws_get_context(wsi);
2468 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
2469 #if defined(LWS_WITH_RANGES)
2470 struct lws_range_parsing *rp = &wsi->u.http.range;
2472 char cache_control[50], *cc = "no-store";
2473 unsigned char *response = pt->serv_buf + LWS_PRE;
2474 unsigned char *p = response;
2475 unsigned char *end = p + context->pt_serv_buf_size - LWS_PRE;
2476 lws_filepos_t computed_total_content_length;
2477 int ret = 0, cclen = 8, n = HTTP_STATUS_OK;
2478 lws_fop_flags_t fflags = LWS_O_RDONLY;
2479 #if defined(LWS_WITH_RANGES)
2482 const struct lws_plat_file_ops *fops;
2486 * We either call the platform fops .open with first arg platform fops,
2487 * or we call fops_zip .open with first arg platform fops, and fops_zip
2488 * open will decide whether to switch to fops_zip or stay with fops_def.
2490 * If wsi->u.http.fop_fd is already set, the caller already opened it
2492 if (!wsi->u.http.fop_fd) {
2493 fops = lws_vfs_select_fops(wsi->context->fops, file, &vpath);
2494 fflags |= lws_vfs_prepare_flags(wsi);
2495 wsi->u.http.fop_fd = fops->LWS_FOP_OPEN(wsi->context->fops,
2496 file, vpath, &fflags);
2497 if (!wsi->u.http.fop_fd) {
2498 lwsl_err("Unable to open '%s'\n", file);
2503 wsi->u.http.filelen = lws_vfs_get_length(wsi->u.http.fop_fd);
2504 computed_total_content_length = wsi->u.http.filelen;
2506 #if defined(LWS_WITH_RANGES)
2507 ranges = lws_ranges_init(wsi, rp, wsi->u.http.filelen);
2509 lwsl_debug("Range count %d\n", ranges);
2512 * 1 range -> 206 + Content-Type: normal; Content-Range;
2513 * more -> 206 + Content-Type: multipart/byteranges
2514 * Repeat the true Content-Type in each multipart header
2515 * along with Content-Range
2518 /* it means he expressed a range in Range:, but it was illegal */
2519 lws_return_http_status(wsi, HTTP_STATUS_REQ_RANGE_NOT_SATISFIABLE, NULL);
2520 if (lws_http_transaction_completed(wsi))
2521 return -1; /* <0 means just hang up */
2523 lws_vfs_file_close(&wsi->u.http.fop_fd);
2525 return 0; /* == 0 means we dealt with the transaction complete */
2528 n = HTTP_STATUS_PARTIAL_CONTENT;
2531 if (lws_add_http_header_status(wsi, n, &p, end))
2534 if ((wsi->u.http.fop_fd->flags & (LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP |
2535 LWS_FOP_FLAG_COMPR_IS_GZIP)) ==
2536 (LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP | LWS_FOP_FLAG_COMPR_IS_GZIP)) {
2537 if (lws_add_http_header_by_token(wsi,
2538 WSI_TOKEN_HTTP_CONTENT_ENCODING,
2539 (unsigned char *)"gzip", 4, &p, end))
2541 lwsl_info("file is being provided in gzip\n");
2544 #if defined(LWS_WITH_RANGES)
2545 if (ranges < 2 && content_type && content_type[0])
2546 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
2547 (unsigned char *)content_type,
2548 strlen(content_type), &p, end))
2551 if (ranges >= 2) { /* multipart byteranges */
2552 strncpy(wsi->u.http.multipart_content_type, content_type,
2553 sizeof(wsi->u.http.multipart_content_type) - 1);
2554 wsi->u.http.multipart_content_type[
2555 sizeof(wsi->u.http.multipart_content_type) - 1] = '\0';
2556 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
2557 (unsigned char *)"multipart/byteranges; boundary=_lws",
2562 * our overall content length has to include
2564 * - (n + 1) x "_lws\r\n"
2565 * - n x Content-Type: xxx/xxx\r\n
2566 * - n x Content-Range: bytes xxx-yyy/zzz\r\n
2568 * - the actual payloads (aggregated in rp->agg)
2570 * Precompute it for the main response header
2573 computed_total_content_length = (lws_filepos_t)rp->agg +
2574 6 /* final _lws\r\n */;
2576 lws_ranges_reset(rp);
2577 while (lws_ranges_next(rp)) {
2578 n = lws_snprintf(cache_control, sizeof(cache_control),
2579 "bytes %llu-%llu/%llu",
2580 rp->start, rp->end, rp->extent);
2582 computed_total_content_length +=
2583 6 /* header _lws\r\n */ +
2584 14 + strlen(content_type) + 2 + /* Content-Type: xxx/xxx\r\n */
2585 15 + n + 2 + /* Content-Range: xxxx\r\n */
2589 lws_ranges_reset(rp);
2590 lws_ranges_next(rp);
2594 computed_total_content_length = (lws_filepos_t)rp->agg;
2595 n = lws_snprintf(cache_control, sizeof(cache_control), "bytes %llu-%llu/%llu",
2596 rp->start, rp->end, rp->extent);
2598 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_RANGE,
2599 (unsigned char *)cache_control,
2604 wsi->u.http.range.inside = 0;
2606 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ACCEPT_RANGES,
2607 (unsigned char *)"bytes", 5, &p, end))
2611 if (!wsi->sending_chunked) {
2612 if (lws_add_http_header_content_length(wsi,
2613 computed_total_content_length,
2617 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_TRANSFER_ENCODING,
2618 (unsigned char *)"chunked",
2623 if (wsi->cache_secs && wsi->cache_reuse) {
2624 if (wsi->cache_revalidate) {
2626 cclen = sprintf(cache_control, "%s max-age: %u",
2627 intermediates[wsi->cache_intermediaries],
2635 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CACHE_CONTROL,
2636 (unsigned char *)cc, cclen, &p, end))
2639 if (wsi->u.http.connection_type == HTTP_CONNECTION_KEEP_ALIVE)
2640 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
2641 (unsigned char *)"keep-alive", 10, &p, end))
2644 if (other_headers) {
2645 if ((end - p) < other_headers_len)
2647 memcpy(p, other_headers, other_headers_len);
2648 p += other_headers_len;
2651 if (lws_finalize_http_header(wsi, &p, end))
2654 ret = lws_write(wsi, response, p - response, LWS_WRITE_HTTP_HEADERS);
2655 if (ret != (p - response)) {
2656 lwsl_err("_write returned %d from %ld\n", ret, (long)(p - response));
2660 wsi->u.http.filepos = 0;
2661 wsi->state = LWSS_HTTP_ISSUING_FILE;
2663 return lws_serve_http_file_fragment(wsi);
2667 lws_interpret_incoming_packet(struct lws *wsi, unsigned char **buf, size_t len)
2671 lwsl_parser("%s: received %d byte packet\n", __func__, (int)len);
2673 lwsl_hexdump(*buf, len);
2676 /* let the rx protocol state machine have as much as it needs */
2680 * we were accepting input but now we stopped doing so
2682 if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
2683 lws_rxflow_cache(wsi, *buf, 0, len);
2684 lwsl_parser("%s: cached %ld\n", __func__, (long)len);
2688 if (wsi->u.ws.rx_draining_ext) {
2689 // lwsl_notice("draining with 0\n");
2690 m = lws_rx_sm(wsi, 0);
2696 /* account for what we're using in rxflow buffer */
2697 if (wsi->rxflow_buffer)
2700 /* consume payload bytes efficiently */
2702 wsi->lws_rx_parse_state ==
2703 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED) {
2704 m = lws_payload_until_length_exhausted(wsi, buf, &len);
2705 if (wsi->rxflow_buffer)
2706 wsi->rxflow_pos += m;
2709 /* process the byte */
2710 m = lws_rx_sm(wsi, *(*buf)++);
2716 lwsl_parser("%s: exit with %d unused\n", __func__, (int)len);
2722 lws_server_get_canonical_hostname(struct lws_context *context,
2723 struct lws_context_creation_info *info)
2725 if (lws_check_opt(info->options, LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME))
2727 #if LWS_POSIX && !defined(LWS_WITH_ESP32)
2728 /* find canonical hostname */
2729 gethostname((char *)context->canonical_hostname,
2730 sizeof(context->canonical_hostname) - 1);
2732 lwsl_notice(" canonical_hostname = %s\n", context->canonical_hostname);
2738 #define LWS_MAX_ELEM_NAME 32
2740 enum urldecode_stateful {
2754 static const char * const mp_hdr[] = {
2755 "content-disposition: ",
2760 typedef int (*lws_urldecode_stateful_cb)(void *data,
2761 const char *name, char **buf, int len, int final);
2763 struct lws_urldecode_stateful {
2766 char name[LWS_MAX_ELEM_NAME];
2767 char temp[LWS_MAX_ELEM_NAME];
2768 char content_type[32];
2769 char content_disp[32];
2770 char content_disp_filename[256];
2771 char mime_boundary[128];
2778 unsigned int multipart_form_data:1;
2779 unsigned int inside_quote:1;
2780 unsigned int subname:1;
2781 unsigned int boundary_real_crlf:1;
2783 enum urldecode_stateful state;
2785 lws_urldecode_stateful_cb output;
2788 static struct lws_urldecode_stateful *
2789 lws_urldecode_s_create(struct lws *wsi, char *out, int out_len, void *data,
2790 lws_urldecode_stateful_cb output)
2792 struct lws_urldecode_stateful *s = lws_zalloc(sizeof(*s));
2800 s->out_len = out_len;
2809 if (lws_hdr_copy(wsi, buf, sizeof(buf), WSI_TOKEN_HTTP_CONTENT_TYPE) > 0) {
2810 /* multipart/form-data; boundary=----WebKitFormBoundarycc7YgAPEIHvgE9Bf */
2812 if (!strncmp(buf, "multipart/form-data", 19)) {
2813 s->multipart_form_data = 1;
2814 s->state = MT_LOOK_BOUND_IN;
2816 p = strstr(buf, "boundary=");
2819 s->mime_boundary[m++] = '\x0d';
2820 s->mime_boundary[m++] = '\x0a';
2821 s->mime_boundary[m++] = '-';
2822 s->mime_boundary[m++] = '-';
2823 while (m < sizeof(s->mime_boundary) - 1 &&
2825 s->mime_boundary[m++] = *p++;
2827 s->mime_boundary[m] = '\0';
2829 lwsl_notice("boundary '%s'\n", s->mime_boundary);
2838 lws_urldecode_s_process(struct lws_urldecode_stateful *s, const char *in, int len)
2841 char c, was_end = 0;
2844 if (s->pos == s->out_len - s->mp - 1) {
2845 if (s->output(s->data, s->name, &s->out, s->pos, 0))
2853 /* states for url arg style */
2856 s->inside_quote = 0;
2858 s->name[s->pos] = '\0';
2865 s->name[s->pos] = '\0';
2866 if (s->output(s->data, s->name, &s->out, s->pos, 1))
2873 if (s->pos >= sizeof(s->name) - 1) {
2874 lwsl_notice("Name too long\n");
2877 s->name[s->pos++] = *in++;
2886 s->out[s->pos] = '\0';
2887 if (s->output(s->data, s->name, &s->out, s->pos, 1))
2896 s->out[s->pos++] = ' ';
2899 s->out[s->pos++] = *in++;
2902 n = char_to_hex(*in);
2912 n = char_to_hex(*in);
2917 s->out[s->pos++] = s->sum | n;
2922 /* states for multipart / mime style */
2924 case MT_LOOK_BOUND_IN:
2926 if (*in == s->mime_boundary[s->mp] &&
2927 s->mime_boundary[s->mp]) {
2930 if (!s->mime_boundary[s->mp]) {
2932 s->state = MT_IGNORE1;
2934 if (s->pos || was_end)
2935 if (s->output(s->data, s->name,
2936 &s->out, s->pos, 1))
2941 s->content_disp[0] = '\0';
2943 s->content_disp_filename[0] = '\0';
2944 s->boundary_real_crlf = 1;
2950 if (!s->boundary_real_crlf)
2953 memcpy(s->out + s->pos, s->mime_boundary + n, s->mp - n);
2956 goto retry_as_first;
2959 s->out[s->pos++] = *in;
2967 if (c >= 'A' && c <= 'Z')
2969 for (n = 0; n < ARRAY_SIZE(mp_hdr); n++)
2970 if (c == mp_hdr[n][s->mp]) {
2984 if (mp_hdr[hit][s->mp])
2992 s->state = MT_LOOK_BOUND_IN;
2994 s->state += hit + 1;
2998 /* form-data; name="file"; filename="t.txt" */
3000 if (*in == '\x0d') {
3001 // lwsl_notice("disp: '%s', '%s', '%s'\n",
3002 // s->content_disp, s->name,
3003 // s->content_disp_filename);
3005 if (s->content_disp_filename[0])
3006 if (s->output(s->data, s->name,
3007 &s->out, s->pos, LWS_UFS_OPEN))
3009 s->state = MT_IGNORE2;
3020 s->inside_quote ^= 1;
3026 s->temp[s->mp] = '\0';
3031 if (s->mp < sizeof(s->temp) - 1 &&
3032 (*in != ' ' || s->inside_quote))
3033 s->temp[s->mp++] = *in;
3038 if (s->mp < sizeof(s->content_disp) - 1)
3039 s->content_disp[s->mp++] = *in;
3040 s->content_disp[s->mp] = '\0';
3044 if (!strcmp(s->temp, "name")) {
3045 if (s->mp < sizeof(s->name) - 1)
3046 s->name[s->mp++] = *in;
3047 s->name[s->mp] = '\0';
3051 if (!strcmp(s->temp, "filename")) {
3052 if (s->mp < sizeof(s->content_disp_filename) - 1)
3053 s->content_disp_filename[s->mp++] = *in;
3054 s->content_disp_filename[s->mp] = '\0';
3063 s->state = MT_IGNORE2;
3065 if (s->mp < sizeof(s->content_type) - 1)
3066 s->content_type[s->mp++] = *in;
3067 s->content_type[s->mp] = '\0';
3074 s->state = MT_IGNORE2;
3081 s->state = MT_HNAME;
3091 lws_urldecode_s_destroy(struct lws_urldecode_stateful *s)
3095 if (s->state != US_IDLE)
3099 if (s->output(s->data, s->name, &s->out, s->pos, 1))
3108 struct lws_urldecode_stateful *s;
3109 lws_spa_fileupload_cb opt_cb;
3110 const char * const *param_names;
3124 lws_urldecode_spa_lookup(struct lws_spa *spa,
3129 for (n = 0; n < spa->count_params; n++)
3130 if (!strcmp(spa->param_names[n], name))
3137 lws_urldecode_spa_cb(void *data, const char *name, char **buf, int len,
3140 struct lws_spa *spa =
3141 (struct lws_spa *)data;
3144 if (spa->s->content_disp_filename[0]) {
3146 n = spa->opt_cb(spa->opt_data, name,
3147 spa->s->content_disp_filename,
3155 n = lws_urldecode_spa_lookup(spa, name);
3157 if (n == -1 || !len) /* unrecognized */
3160 if (!spa->params[n])
3161 spa->params[n] = *buf;
3163 if ((*buf) + len >= spa->end) {
3164 lwsl_notice("%s: exceeded storage\n", __func__);
3168 spa->param_length[n] += len;
3170 /* move it on inside storage */
3174 spa->s->out_len -= len + 1;
3179 LWS_VISIBLE LWS_EXTERN struct lws_spa *
3180 lws_spa_create(struct lws *wsi, const char * const *param_names,
3181 int count_params, int max_storage,
3182 lws_spa_fileupload_cb opt_cb, void *opt_data)
3184 struct lws_spa *spa = lws_zalloc(sizeof(*spa));
3189 spa->param_names = param_names;
3190 spa->count_params = count_params;
3191 spa->max_storage = max_storage;
3192 spa->opt_cb = opt_cb;
3193 spa->opt_data = opt_data;
3195 spa->storage = lws_malloc(max_storage);
3198 spa->end = spa->storage + max_storage - 1;
3200 spa->params = lws_zalloc(sizeof(char *) * count_params);
3204 spa->s = lws_urldecode_s_create(wsi, spa->storage, max_storage, spa,
3205 lws_urldecode_spa_cb);
3209 spa->param_length = lws_zalloc(sizeof(int) * count_params);
3210 if (!spa->param_length)
3213 lwsl_info("%s: Created SPA %p\n", __func__, spa);
3218 lws_urldecode_s_destroy(spa->s);
3220 lws_free(spa->params);
3222 lws_free(spa->storage);
3229 LWS_VISIBLE LWS_EXTERN int
3230 lws_spa_process(struct lws_spa *ludspa, const char *in, int len)
3233 lwsl_err("%s: NULL spa\n", __func__);
3236 /* we reject any junk after the last part arrived and we finalized */
3237 if (ludspa->finalized)
3240 return lws_urldecode_s_process(ludspa->s, in, len);
3243 LWS_VISIBLE LWS_EXTERN int
3244 lws_spa_get_length(struct lws_spa *ludspa, int n)
3246 if (n >= ludspa->count_params)
3249 return ludspa->param_length[n];
3252 LWS_VISIBLE LWS_EXTERN const char *
3253 lws_spa_get_string(struct lws_spa *ludspa, int n)
3255 if (n >= ludspa->count_params)
3258 return ludspa->params[n];
3261 LWS_VISIBLE LWS_EXTERN int
3262 lws_spa_finalize(struct lws_spa *spa)
3265 lws_urldecode_s_destroy(spa->s);
3274 LWS_VISIBLE LWS_EXTERN int
3275 lws_spa_destroy(struct lws_spa *spa)
3279 lwsl_notice("%s: destroy spa %p\n", __func__, spa);
3282 lws_urldecode_s_destroy(spa->s);
3284 lwsl_debug("%s %p %p %p %p\n", __func__,
3291 lws_free(spa->param_length);
3292 lws_free(spa->params);
3293 lws_free(spa->storage);
3300 LWS_VISIBLE LWS_EXTERN int
3301 lws_spa_destroy(struct lws_spa *spa)
3305 lwsl_info("%s: destroy spa %p\n", __func__, spa);
3308 lws_urldecode_s_destroy(spa->s);
3310 lwsl_debug("%s\n", __func__);
3312 lws_free(spa->param_length);
3313 lws_free(spa->params);
3314 lws_free(spa->storage);
3320 LWS_VISIBLE LWS_EXTERN int
3321 lws_chunked_html_process(struct lws_process_html_args *args,
3322 struct lws_process_html_state *s)
3324 char *sp, buffer[32];
3328 /* do replacements */
3330 old_len = args->len;
3333 while (sp < args->p + old_len) {
3335 if (args->len + 7 >= args->max_len) {
3336 lwsl_err("Used up interpret padding\n");
3340 if ((!s->pos && *sp == '$') || s->pos) {
3341 int hits = 0, hit = 0;
3345 s->swallow[s->pos++] = *sp;
3346 if (s->pos == sizeof(s->swallow) - 1)
3348 for (n = 0; n < s->count_vars; n++)
3349 if (!strncmp(s->swallow, s->vars[n], s->pos)) {
3355 s->swallow[s->pos] = '\0';
3356 memcpy(s->start, s->swallow, s->pos);
3362 if (hits == 1 && s->pos == strlen(s->vars[hit])) {
3363 pc = s->replace(s->data, hit);
3367 s->swallow[s->pos] = '\0';
3369 memmove(s->start + n,
3371 old_len - (sp - args->p));
3372 old_len += (n - s->pos) + 1;
3374 memcpy(s->start, pc, n);
3388 /* no space left for final chunk trailer */
3389 if (args->final && args->len + 7 >= args->max_len)
3392 n = sprintf(buffer, "%X\x0d\x0a", args->len);
3395 memcpy(args->p, buffer, n);
3399 sp = args->p + args->len;
3409 sp = args->p + args->len;