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;
363 char path[256], sym[512];
364 unsigned char *p = (unsigned char *)sym + 32 + LWS_PRE, *start = p;
365 unsigned char *end = p + sizeof(sym) - 32 - LWS_PRE;
366 #if !defined(WIN32) && LWS_POSIX && !defined(LWS_WITH_ESP32)
371 lws_snprintf(path, sizeof(path) - 1, "%s/%s", origin, uri);
373 #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP8266)
375 fflags |= lws_vfs_prepare_flags(wsi);
379 fops = lws_vfs_select_fops(wsi->context->fops, path, &vpath);
381 if (wsi->u.http.fop_fd)
382 lws_vfs_file_close(&wsi->u.http.fop_fd);
384 wsi->u.http.fop_fd = fops->LWS_FOP_OPEN(wsi->context->fops,
385 path, vpath, &fflags);
386 if (!wsi->u.http.fop_fd) {
387 lwsl_err("Unable to open '%s'\n", path);
392 /* if it can't be statted, don't try */
393 if (fflags & LWS_FOP_FLAG_VIRTUAL)
395 #if defined(LWS_WITH_ESP32)
399 if (fstat(wsi->u.http.fop_fd->fd, &st)) {
400 lwsl_info("unable to stat %s\n", path);
404 if (stat(path, &st)) {
405 lwsl_info("unable to stat %s\n", path);
410 wsi->u.http.fop_fd->mod_time = (uint32_t)st.st_mtime;
411 fflags |= LWS_FOP_FLAG_MOD_TIME_VALID;
413 lwsl_debug(" %s mode %d\n", path, S_IFMT & st.st_mode);
414 #if !defined(WIN32) && LWS_POSIX && !defined(LWS_WITH_ESP32)
415 if ((S_IFMT & st.st_mode) == S_IFLNK) {
416 len = readlink(path, sym, sizeof(sym) - 1);
418 lwsl_err("Failed to read link %s\n", path);
422 lwsl_debug("symlink %s -> %s\n", path, sym);
423 lws_snprintf(path, sizeof(path) - 1, "%s", sym);
426 if ((S_IFMT & st.st_mode) == S_IFDIR) {
427 lwsl_debug("default filename append to dir\n");
428 lws_snprintf(path, sizeof(path) - 1, "%s/%s/index.html",
432 } while ((S_IFMT & st.st_mode) != S_IFREG && spin < 5);
435 lwsl_err("symlink loop %s \n", path);
437 n = sprintf(sym, "%08lX%08lX",
438 (unsigned long)lws_vfs_get_length(wsi->u.http.fop_fd),
439 (unsigned long)lws_vfs_get_mod_time(wsi->u.http.fop_fd));
441 /* disable ranges if IF_RANGE token invalid */
443 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_RANGE))
444 if (strcmp(sym, lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_IF_RANGE)))
445 /* differs - defeat Range: */
446 wsi->u.http.ah->frag_index[WSI_TOKEN_HTTP_RANGE] = 0;
448 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_NONE_MATCH)) {
450 * he thinks he has some version of it already,
451 * check if the tag matches
453 if (!strcmp(sym, lws_hdr_simple_ptr(wsi,
454 WSI_TOKEN_HTTP_IF_NONE_MATCH))) {
456 lwsl_debug("%s: ETAG match %s %s\n", __func__,
459 /* we don't need to send the payload */
460 if (lws_add_http_header_status(wsi,
461 HTTP_STATUS_NOT_MODIFIED, &p, end))
464 if (lws_add_http_header_by_token(wsi,
466 (unsigned char *)sym, n, &p, end))
469 if (lws_finalize_http_header(wsi, &p, end))
472 n = lws_write(wsi, start, p - start,
473 LWS_WRITE_HTTP_HEADERS);
474 if (n != (p - start)) {
475 lwsl_err("_write returned %d from %ld\n", n,
480 lws_vfs_file_close(&wsi->u.http.fop_fd);
482 return lws_http_transaction_completed(wsi);
486 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ETAG,
487 (unsigned char *)sym, n, &p, end))
491 mimetype = lws_get_mimetype(path, m);
493 lwsl_err("unknown mimetype for %s\n", path);
497 lwsl_debug("sending no mimetype for %s\n", path);
499 wsi->sending_chunked = 0;
502 * check if this is in the list of file suffixes to be interpreted by
507 if (n > (int)strlen(pvo->name) &&
508 !strcmp(&path[n - strlen(pvo->name)], pvo->name)) {
509 wsi->sending_chunked = 1;
510 wsi->protocol_interpret_idx = (char)(long)pvo->value;
511 lwsl_info("want %s interpreted by %s\n", path,
512 wsi->vhost->protocols[(int)(long)(pvo->value)].name);
513 wsi->protocol = &wsi->vhost->protocols[(int)(long)(pvo->value)];
514 if (lws_ensure_user_space(wsi))
522 const struct lws_protocols *pp = lws_vhost_name_to_protocol(
523 wsi->vhost, m->protocol);
525 if (lws_bind_protocol(wsi, pp))
528 args.max_len = end - p;
529 if (pp->callback(wsi, LWS_CALLBACK_ADD_HEADERS,
530 wsi->user_space, &args, 0))
532 p = (unsigned char *)args.p;
535 n = lws_serve_http_file(wsi, path, mimetype, (char *)start, p - start);
537 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
538 return -1; /* error or can't reuse connection: close the socket */
546 const struct lws_http_mount *
547 lws_find_mount(struct lws *wsi, const char *uri_ptr, int uri_len)
549 const struct lws_http_mount *hm, *hit = NULL;
552 hm = wsi->vhost->mount_list;
554 if (uri_len >= hm->mountpoint_len &&
555 !strncmp(uri_ptr, hm->mountpoint, hm->mountpoint_len) &&
556 (uri_ptr[hm->mountpoint_len] == '\0' ||
557 uri_ptr[hm->mountpoint_len] == '/' ||
558 hm->mountpoint_len == 1)
560 if (hm->origin_protocol == LWSMPRO_CALLBACK ||
561 ((hm->origin_protocol == LWSMPRO_CGI ||
562 lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI) ||
564 hm->mountpoint_len > best)) {
565 best = hm->mountpoint_len;
578 lws_find_string_in_file(const char *filename, const char *string, int stringlen)
581 int fd, match = 0, pos = 0, n = 0, hit = 0;
583 fd = open(filename, O_RDONLY);
585 lwsl_err("can't open auth file: %s\n", filename);
591 n = read(fd, buf, sizeof(buf));
593 if (match == stringlen)
600 if (match == stringlen) {
601 if (buf[pos] == '\r' || buf[pos] == '\n') {
608 if (buf[pos] == string[match])
622 lws_unauthorised_basic_auth(struct lws *wsi)
624 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
625 unsigned char *start = pt->serv_buf + LWS_PRE,
626 *p = start, *end = p + 512;
630 /* no auth... tell him it is required */
632 if (lws_add_http_header_status(wsi, HTTP_STATUS_UNAUTHORIZED, &p, end))
635 n = lws_snprintf(buf, sizeof(buf), "Basic realm=\"lwsws\"");
636 if (lws_add_http_header_by_token(wsi,
637 WSI_TOKEN_HTTP_WWW_AUTHENTICATE,
638 (unsigned char *)buf, n, &p, end))
641 if (lws_finalize_http_header(wsi, &p, end))
644 n = lws_write(wsi, start, p - start, LWS_WRITE_HTTP_HEADERS);
648 return lws_http_transaction_completed(wsi);
655 lws_http_action(struct lws *wsi)
657 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
658 enum http_connection_type connection_type;
659 enum http_version request_version;
660 char content_length_str[32];
661 struct lws_process_html_args args;
662 const struct lws_http_mount *hit = NULL;
663 unsigned int n, count = 0;
664 char http_version_str[10];
665 char http_conn_str[20];
666 int http_version_len;
667 char *uri_ptr = NULL, *s;
671 static const unsigned char methods[] = {
674 WSI_TOKEN_OPTIONS_URI,
677 WSI_TOKEN_DELETE_URI,
680 WSI_TOKEN_HTTP_COLON_PATH,
683 #if defined(_DEBUG) || defined(LWS_WITH_ACCESS_LOG)
684 static const char * const method_names[] = {
685 "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE", "CONNECT",
691 static const char * const oprot[] = {
692 "http://", "https://"
695 /* it's not websocket.... shall we accept it as http? */
697 for (n = 0; n < ARRAY_SIZE(methods); n++)
698 if (lws_hdr_total_length(wsi, methods[n]))
701 lwsl_warn("Missing URI in HTTP request\n");
706 lwsl_warn("multiple methods?\n");
710 if (lws_ensure_user_space(wsi))
713 for (n = 0; n < ARRAY_SIZE(methods); n++)
714 if (lws_hdr_total_length(wsi, methods[n])) {
715 uri_ptr = lws_hdr_simple_ptr(wsi, methods[n]);
716 uri_len = lws_hdr_total_length(wsi, methods[n]);
717 lwsl_info("Method: %s request for '%s'\n",
718 method_names[n], uri_ptr);
725 /* we insist on absolute paths */
727 if (uri_ptr[0] != '/') {
728 lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
733 /* HTTP header had a content length? */
735 wsi->u.http.content_length = 0;
736 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) ||
737 lws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI) ||
738 lws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI))
739 wsi->u.http.content_length = 100 * 1024 * 1024;
741 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
742 lws_hdr_copy(wsi, content_length_str,
743 sizeof(content_length_str) - 1,
744 WSI_TOKEN_HTTP_CONTENT_LENGTH);
745 wsi->u.http.content_length = atoi(content_length_str);
748 if (wsi->http2_substream) {
749 wsi->u.http.request_version = HTTP_VERSION_2;
751 /* http_version? Default to 1.0, override with token: */
752 request_version = HTTP_VERSION_1_0;
754 /* Works for single digit HTTP versions. : */
755 http_version_len = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP);
756 if (http_version_len > 7) {
757 lws_hdr_copy(wsi, http_version_str,
758 sizeof(http_version_str) - 1, WSI_TOKEN_HTTP);
759 if (http_version_str[5] == '1' && http_version_str[7] == '1')
760 request_version = HTTP_VERSION_1_1;
762 wsi->u.http.request_version = request_version;
764 /* HTTP/1.1 defaults to "keep-alive", 1.0 to "close" */
765 if (request_version == HTTP_VERSION_1_1)
766 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
768 connection_type = HTTP_CONNECTION_CLOSE;
770 /* Override default if http "Connection:" header: */
771 if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) {
772 lws_hdr_copy(wsi, http_conn_str, sizeof(http_conn_str) - 1,
773 WSI_TOKEN_CONNECTION);
774 http_conn_str[sizeof(http_conn_str) - 1] = '\0';
775 if (!strcasecmp(http_conn_str, "keep-alive"))
776 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
778 if (!strcasecmp(http_conn_str, "close"))
779 connection_type = HTTP_CONNECTION_CLOSE;
781 wsi->u.http.connection_type = connection_type;
784 n = wsi->protocol->callback(wsi, LWS_CALLBACK_FILTER_HTTP_CONNECTION,
785 wsi->user_space, uri_ptr, uri_len);
787 lwsl_info("LWS_CALLBACK_HTTP closing\n");
792 * if there is content supposed to be coming,
793 * put a timeout on it having arrived
795 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
796 wsi->context->timeout_secs);
797 #ifdef LWS_OPENSSL_SUPPORT
798 if (wsi->redirect_to_https) {
800 * we accepted http:// only so we could redirect to
801 * https://, so issue the redirect. Create the redirection
802 * URI from the host: header and ignore the path part
804 unsigned char *start = pt->serv_buf + LWS_PRE, *p = start,
807 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
810 n = sprintf((char *)end, "https://%s/",
811 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
813 n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
818 return lws_http_transaction_completed(wsi);
822 #ifdef LWS_WITH_ACCESS_LOG
824 * Produce Apache-compatible log string for wsi, like this:
826 * 2.31.234.19 - - [27/Mar/2016:03:22:44 +0800]
827 * "GET /aep-screen.png HTTP/1.1"
828 * 200 152987 "https://libwebsockets.org/index.html"
829 * "Mozilla/5.0 (Macint... Chrome/49.0.2623.87 Safari/537.36"
833 static const char * const hver[] = {
834 "http/1.0", "http/1.1", "http/2"
837 char ads[INET6_ADDRSTRLEN];
839 char ads[INET_ADDRSTRLEN];
844 time_t t = time(NULL);
847 if (wsi->access_log_pending)
850 wsi->access_log.header_log = lws_malloc(l);
851 if (wsi->access_log.header_log) {
855 strftime(da, sizeof(da), "%d/%b/%Y:%H:%M:%S %z", tmp);
857 strcpy(da, "01/Jan/1970:00:00:00 +0000");
859 pa = lws_get_peer_simple(wsi, ads, sizeof(ads));
864 me = method_names[meth];
868 lws_snprintf(wsi->access_log.header_log, l,
869 "%s - - [%s] \"%s %s %s\"",
871 hver[wsi->u.http.request_version]);
873 l = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT);
875 wsi->access_log.user_agent = lws_malloc(l + 2);
876 if (wsi->access_log.user_agent)
877 lws_hdr_copy(wsi, wsi->access_log.user_agent,
878 l + 1, WSI_TOKEN_HTTP_USER_AGENT);
880 lwsl_err("OOM getting user agent\n");
882 wsi->access_log_pending = 1;
887 /* can we serve it from the mount list? */
889 hit = lws_find_mount(wsi, uri_ptr, uri_len);
891 /* deferred cleanup and reset to protocols[0] */
893 lwsl_info("no hit\n");
895 if (lws_bind_protocol(wsi, &wsi->vhost->protocols[0]))
898 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
899 wsi->user_space, uri_ptr, uri_len);
904 s = uri_ptr + hit->mountpoint_len;
907 * if we have a mountpoint like https://xxx.com/yyy
908 * there is an implied / at the end for our purposes since
909 * we can only mount on a "directory".
911 * But if we just go with that, the browser cannot understand
912 * that he is actually looking down one "directory level", so
913 * even though we give him /yyy/abc.html he acts like the
914 * current directory level is /. So relative urls like "x.png"
915 * wrongly look outside the mountpoint.
917 * Therefore if we didn't come in on a url with an explicit
918 * / at the end, we must redirect to add it so the browser
919 * understands he is one "directory level" down.
921 if ((hit->mountpoint_len > 1 ||
922 (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
923 hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&
925 (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
926 hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&
927 (hit->origin_protocol != LWSMPRO_CGI &&
928 hit->origin_protocol != LWSMPRO_CALLBACK //&&
929 //hit->protocol == NULL
931 unsigned char *start = pt->serv_buf + LWS_PRE,
932 *p = start, *end = p + 512;
934 lwsl_debug("Doing 301 '%s' org %s\n", s, hit->origin);
936 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
939 /* > at start indicates deal with by redirect */
940 if (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
941 hit->origin_protocol == LWSMPRO_REDIR_HTTPS)
942 n = lws_snprintf((char *)end, 256, "%s%s",
943 oprot[hit->origin_protocol & 1],
946 n = lws_snprintf((char *)end, 256,
947 "%s%s%s/", oprot[lws_is_ssl(wsi)],
948 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST),
951 n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
956 return lws_http_transaction_completed(wsi);
962 if (hit->basic_auth_login_file) {
963 char b64[160], plain[(sizeof(b64) * 3) / 4];
966 /* Did he send auth? */
967 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_AUTHORIZATION))
968 return lws_unauthorised_basic_auth(wsi);
970 n = HTTP_STATUS_FORBIDDEN;
972 m = lws_hdr_copy(wsi, b64, sizeof(b64), WSI_TOKEN_HTTP_AUTHORIZATION);
974 lwsl_err("b64 auth too long\n");
975 goto transaction_result_n;
979 if (strcasecmp(b64, "Basic")) {
980 lwsl_err("auth missing basic: %s\n", b64);
981 goto transaction_result_n;
984 /* It'll be like Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l */
986 m = lws_b64_decode_string(b64 + 6, plain, sizeof(plain));
988 lwsl_err("plain auth too long\n");
989 goto transaction_result_n;
992 // lwsl_notice(plain);
994 if (!lws_find_string_in_file(hit->basic_auth_login_file, plain, m)) {
995 lwsl_err("basic auth lookup failed\n");
996 return lws_unauthorised_basic_auth(wsi);
999 lwsl_notice("basic auth accepted\n");
1001 /* accept the auth */
1006 * A particular protocol callback is mounted here?
1008 * For the duration of this http transaction, bind us to the
1009 * associated protocol
1011 if (hit->origin_protocol == LWSMPRO_CALLBACK || hit->protocol) {
1012 const struct lws_protocols *pp;
1013 const char *name = hit->origin;
1015 name = hit->protocol;
1017 pp = lws_vhost_name_to_protocol(wsi->vhost, name);
1020 lwsl_err("Unable to find plugin '%s'\n",
1025 if (lws_bind_protocol(wsi, pp))
1030 args.max_len = hit->auth_mask;
1031 args.final = 0; /* used to signal callback dealt with it */
1033 n = wsi->protocol->callback(wsi, LWS_CALLBACK_CHECK_ACCESS_RIGHTS,
1034 wsi->user_space, &args, 0);
1036 lws_return_http_status(wsi, HTTP_STATUS_UNAUTHORIZED,
1040 if (args.final) /* callback completely handled it well */
1043 if (hit->cgienv && wsi->protocol->callback(wsi,
1044 LWS_CALLBACK_HTTP_PMO,
1045 wsi->user_space, (void *)hit->cgienv, 0))
1048 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) {
1049 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
1051 uri_ptr + hit->mountpoint_len,
1052 uri_len - hit->mountpoint_len);
1058 /* did we hit something with a cgi:// origin? */
1059 if (hit->origin_protocol == LWSMPRO_CGI) {
1060 const char *cmd[] = {
1061 NULL, /* replace with cgi path */
1065 lwsl_debug("%s: cgi\n", __func__);
1066 cmd[0] = hit->origin;
1069 if (hit->cgi_timeout)
1070 n = hit->cgi_timeout;
1072 n = lws_cgi(wsi, cmd, hit->mountpoint_len, n,
1075 lwsl_err("%s: cgi failed\n", __func__);
1084 if (s[0] == '\0' || (n == 1 && s[n - 1] == '/'))
1085 s = (char *)hit->def;
1089 wsi->cache_secs = hit->cache_max_age;
1090 wsi->cache_reuse = hit->cache_reusable;
1091 wsi->cache_revalidate = hit->cache_revalidate;
1092 wsi->cache_intermediaries = hit->cache_intermediaries;
1094 n = lws_http_serve(wsi, s, hit->origin, hit);
1097 * lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
1099 if (hit->protocol) {
1100 const struct lws_protocols *pp = lws_vhost_name_to_protocol(
1101 wsi->vhost, hit->protocol);
1103 if (lws_bind_protocol(wsi, pp))
1106 n = pp->callback(wsi, LWS_CALLBACK_HTTP,
1108 uri_ptr + hit->mountpoint_len,
1109 uri_len - hit->mountpoint_len);
1111 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
1112 wsi->user_space, uri_ptr, uri_len);
1117 lwsl_info("LWS_CALLBACK_HTTP closing\n");
1126 * If we're not issuing a file, check for content_length or
1127 * HTTP keep-alive. No keep-alive header allocation for
1128 * ISSUING_FILE, as this uses HTTP/1.0.
1130 * In any case, return 0 and let lws_read decide how to
1131 * proceed based on state
1133 if (wsi->state != LWSS_HTTP_ISSUING_FILE)
1134 /* Prepare to read body if we have a content length: */
1135 if (wsi->u.http.content_length > 0)
1136 wsi->state = LWSS_HTTP_BODY;
1141 /* we're closing, losing some rx is OK */
1142 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1143 // lwsl_notice("%s: drop1\n", __func__);
1144 lws_header_table_detach(wsi, 1);
1148 transaction_result_n:
1149 lws_return_http_status(wsi, n, NULL);
1151 return lws_http_transaction_completed(wsi);
1156 lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len)
1158 int protocol_len, n = 0, hit, non_space_char_found = 0, m;
1159 struct lws_context *context = lws_get_context(wsi);
1160 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1161 struct _lws_header_related hdr;
1162 struct allocated_headers *ah;
1163 unsigned char *obuf = *buf;
1164 char protocol_list[128];
1165 char protocol_name[64];
1169 if (len >= 10000000) {
1170 lwsl_err("%s: assert: len %ld\n", __func__, (long)len);
1174 if (!wsi->u.hdr.ah) {
1175 lwsl_err("%s: assert: NULL ah\n", __func__);
1180 wsi->more_rx_waiting = !!len;
1182 if (wsi->mode != LWSCM_HTTP_SERVING &&
1183 wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED) {
1184 lwsl_err("%s: bad wsi mode %d\n", __func__, wsi->mode);
1188 m = lws_parse(wsi, *(*buf)++);
1192 * we are transitioning from http with
1193 * an AH, to raw. Drop the ah and set
1197 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1198 lws_bind_protocol(wsi, &wsi->vhost->protocols[
1200 raw_protocol_index]);
1201 lwsl_info("transition to raw vh %s prot %d\n",
1203 wsi->vhost->raw_protocol_index);
1204 if ((wsi->protocol->callback)(wsi,
1205 LWS_CALLBACK_RAW_ADOPT,
1206 wsi->user_space, NULL, 0))
1209 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1210 lws_union_transition(wsi, LWSCM_RAW);
1211 lws_header_table_detach(wsi, 1);
1213 if (m == 2 && (wsi->protocol->callback)(wsi,
1214 LWS_CALLBACK_RAW_RX,
1215 wsi->user_space, obuf, olen))
1220 lwsl_info("lws_parse failed\n");
1224 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
1227 lwsl_parser("%s: lws_parse sees parsing complete\n", __func__);
1228 lwsl_debug("%s: wsi->more_rx_waiting=%d\n", __func__,
1229 wsi->more_rx_waiting);
1231 /* check for unwelcome guests */
1233 if (wsi->context->reject_service_keywords) {
1234 const struct lws_protocol_vhost_options *rej =
1235 wsi->context->reject_service_keywords;
1236 char ua[384], *msg = NULL;
1238 if (lws_hdr_copy(wsi, ua, sizeof(ua) - 1,
1239 WSI_TOKEN_HTTP_USER_AGENT) > 0) {
1240 ua[sizeof(ua) - 1] = '\0';
1242 if (strstr(ua, rej->name)) {
1243 msg = strchr(rej->value, ' ');
1246 lws_return_http_status(wsi, atoi(rej->value), msg);
1248 wsi->vhost->conn_stats.rejected++;
1259 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
1260 struct lws_vhost *vhost = lws_select_vhost(
1261 context, wsi->vhost->listen_port,
1262 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
1267 lwsl_info("no host\n");
1269 wsi->vhost->conn_stats.trans++;
1270 if (!wsi->conn_stat_done) {
1271 wsi->vhost->conn_stats.conn++;
1272 wsi->conn_stat_done = 1;
1275 if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECT)) {
1276 lwsl_info("Changing to RAW mode\n");
1278 goto raw_transition;
1281 wsi->mode = LWSCM_PRE_WS_SERVING_ACCEPT;
1282 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1284 /* is this websocket protocol or normal http 1.0? */
1286 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
1287 if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
1289 wsi->vhost->conn_stats.ws_upg++;
1290 lwsl_info("Upgrade to ws\n");
1293 #ifdef LWS_USE_HTTP2
1294 if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
1296 wsi->vhost->conn_stats.http2_upg++;
1297 lwsl_info("Upgrade to h2c\n");
1301 lwsl_info("Unknown upgrade\n");
1302 /* dunno what he wanted to upgrade to */
1306 /* no upgrade ack... he remained as HTTP */
1308 lwsl_info("No upgrade\n");
1311 lws_union_transition(wsi, LWSCM_HTTP_SERVING_ACCEPTED);
1312 wsi->state = LWSS_HTTP;
1313 wsi->u.http.fop_fd = NULL;
1315 /* expose it at the same offset as u.hdr */
1316 wsi->u.http.ah = ah;
1317 lwsl_debug("%s: wsi %p: ah %p\n", __func__, (void *)wsi,
1318 (void *)wsi->u.hdr.ah);
1320 n = lws_http_action(wsi);
1324 #ifdef LWS_USE_HTTP2
1326 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) {
1327 lwsl_info("missing http2_settings\n");
1331 lwsl_info("h2c upgrade...\n");
1333 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS);
1334 /* convert the peer's HTTP-Settings */
1335 n = lws_b64_decode_string(p, protocol_list,
1336 sizeof(protocol_list));
1338 lwsl_parser("HTTP2_SETTINGS too long\n");
1342 /* adopt the header info */
1346 lws_union_transition(wsi, LWSCM_HTTP2_SERVING);
1348 /* http2 union member has http union struct at start */
1349 wsi->u.http.ah = ah;
1351 lws_http2_init(&wsi->u.http2.peer_settings);
1352 lws_http2_init(&wsi->u.http2.my_settings);
1356 lws_http2_interpret_settings_payload(&wsi->u.http2.peer_settings,
1357 (unsigned char *)protocol_list, n);
1359 strcpy(protocol_list,
1360 "HTTP/1.1 101 Switching Protocols\x0d\x0a"
1361 "Connection: Upgrade\x0d\x0a"
1362 "Upgrade: h2c\x0d\x0a\x0d\x0a");
1363 n = lws_issue_raw(wsi, (unsigned char *)protocol_list,
1364 strlen(protocol_list));
1365 if (n != strlen(protocol_list)) {
1366 lwsl_debug("http2 switch: ERROR writing to socket\n");
1370 wsi->state = LWSS_HTTP2_AWAIT_CLIENT_PREFACE;
1377 lwsl_err("NULL protocol at lws_read\n");
1382 * Select the first protocol we support from the list
1383 * the client sent us.
1385 * Copy it to remove header fragmentation
1388 if (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1,
1389 WSI_TOKEN_PROTOCOL) < 0) {
1390 lwsl_err("protocol list too long");
1394 protocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
1395 protocol_list[protocol_len] = '\0';
1399 while (*p && !hit) {
1401 non_space_char_found = 0;
1402 while (n < sizeof(protocol_name) - 1 && *p &&
1404 // ignore leading spaces
1405 if (!non_space_char_found && *p == ' ') {
1409 non_space_char_found = 1;
1410 protocol_name[n++] = *p++;
1412 protocol_name[n] = '\0';
1416 lwsl_info("checking %s\n", protocol_name);
1419 while (wsi->vhost->protocols[n].callback) {
1420 lwsl_info("try %s\n", wsi->vhost->protocols[n].name);
1422 if (wsi->vhost->protocols[n].name &&
1423 !strcmp(wsi->vhost->protocols[n].name,
1425 wsi->protocol = &wsi->vhost->protocols[n];
1434 /* we didn't find a protocol he wanted? */
1437 if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL)) {
1438 lwsl_info("No protocol from \"%s\" supported\n",
1443 * some clients only have one protocol and
1444 * do not send the protocol list header...
1445 * allow it and match to the vhost's default
1446 * protocol (which itself defaults to zero)
1448 lwsl_info("defaulting to prot handler %d\n",
1449 wsi->vhost->default_protocol_index);
1451 wsi->protocol = &wsi->vhost->protocols[
1452 (int)wsi->vhost->default_protocol_index];
1455 /* allocate wsi->user storage */
1456 if (lws_ensure_user_space(wsi))
1460 * Give the user code a chance to study the request and
1461 * have the opportunity to deny it
1463 if ((wsi->protocol->callback)(wsi,
1464 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
1466 lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) {
1467 lwsl_warn("User code denied connection\n");
1472 * Perform the handshake according to the protocol version the
1476 switch (wsi->ietf_spec_revision) {
1478 lwsl_parser("lws_parse calling handshake_04\n");
1479 if (handshake_0405(context, wsi)) {
1480 lwsl_info("hs0405 has failed the connection\n");
1486 lwsl_info("Unknown client spec version %d\n",
1487 wsi->ietf_spec_revision);
1491 lws_same_vh_protocol_insert(wsi, n);
1493 /* we are upgrading to ws, so http/1.1 and keepalive +
1494 * pipelined header considerations about keeping the ah around
1495 * no longer apply. However it's common for the first ws
1496 * protocol data to have been coalesced with the browser
1497 * upgrade request and to already be in the ah rx buffer.
1500 lwsl_info("%s: %p: inheriting ah in ws mode (rxpos:%d, rxlen:%d)\n",
1501 __func__, wsi, wsi->u.hdr.ah->rxpos,
1502 wsi->u.hdr.ah->rxlen);
1506 lws_union_transition(wsi, LWSCM_WS_SERVING);
1508 * first service is WS mode will notice this, use the RX and
1509 * then detach the ah (caution: we are not in u.hdr union
1510 * mode any more then... ah_temp member is at start the same
1513 * Because rxpos/rxlen shows something in the ah, we will get
1514 * service guaranteed next time around the event loop
1516 * All union members begin with hdr, so we can use it even
1517 * though we transitioned to ws union mode (the ah detach
1518 * code uses it anyway).
1523 lws_restart_ws_ping_pong_timer(wsi);
1526 * create the frame buffer for this connection according to the
1527 * size mentioned in the protocol definition. If 0 there, use
1528 * a big default for compatibility
1531 n = wsi->protocol->rx_buffer_size;
1533 n = context->pt_serv_buf_size;
1535 wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
1536 if (!wsi->u.ws.rx_ubuf) {
1537 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
1540 wsi->u.ws.rx_ubuf_alloc = n;
1541 lwsl_debug("Allocating RX buffer %d\n", n);
1542 #if LWS_POSIX && !defined(LWS_WITH_ESP32)
1543 if (setsockopt(wsi->desc.sockfd, SOL_SOCKET, SO_SNDBUF,
1544 (const char *)&n, sizeof n)) {
1545 lwsl_warn("Failed to set SNDBUF to %d", n);
1550 lwsl_parser("accepted v%02d connection\n",
1551 wsi->ietf_spec_revision);
1553 /* notify user code that we're ready to roll */
1555 if (wsi->protocol->callback)
1556 if (wsi->protocol->callback(wsi, LWS_CALLBACK_ESTABLISHED,
1558 #ifdef LWS_OPENSSL_SUPPORT
1566 /* !!! drop ah unreservedly after ESTABLISHED */
1567 if (!wsi->more_rx_waiting) {
1568 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1570 //lwsl_notice("%p: dropping ah EST\n", wsi);
1571 lws_header_table_detach(wsi, 1);
1575 } /* while all chars are handled */
1580 /* drop the header info */
1581 /* we're closing, losing some rx is OK */
1582 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1583 //lwsl_notice("%s: drop2\n", __func__);
1584 lws_header_table_detach(wsi, 1);
1590 lws_get_idlest_tsi(struct lws_context *context)
1592 unsigned int lowest = ~0;
1593 int n = 0, hit = -1;
1595 for (; n < context->count_threads; n++) {
1596 if ((unsigned int)context->pt[n].fds_count !=
1597 context->fd_limit_per_thread - 1 &&
1598 (unsigned int)context->pt[n].fds_count < lowest) {
1599 lowest = context->pt[n].fds_count;
1608 lws_create_new_server_wsi(struct lws_vhost *vhost)
1610 struct lws *new_wsi;
1611 int n = lws_get_idlest_tsi(vhost->context);
1614 lwsl_err("no space for new conn\n");
1618 new_wsi = lws_zalloc(sizeof(struct lws));
1619 if (new_wsi == NULL) {
1620 lwsl_err("Out of memory for new connection\n");
1625 lwsl_debug("Accepted wsi %p to context %p, tsi %d\n", new_wsi,
1626 vhost->context, new_wsi->tsi);
1628 new_wsi->vhost = vhost;
1629 new_wsi->context = vhost->context;
1630 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1631 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1633 /* initialize the instance struct */
1635 new_wsi->state = LWSS_HTTP;
1636 new_wsi->mode = LWSCM_HTTP_SERVING;
1637 new_wsi->hdr_parsing_completed = 0;
1639 #ifdef LWS_OPENSSL_SUPPORT
1640 new_wsi->use_ssl = LWS_SSL_ENABLED(vhost);
1644 * these can only be set once the protocol is known
1645 * we set an unestablished connection's protocol pointer
1646 * to the start of the supported list, so it can look
1647 * for matching ones during the handshake
1649 new_wsi->protocol = vhost->protocols;
1650 new_wsi->user_space = NULL;
1651 new_wsi->ietf_spec_revision = 0;
1652 new_wsi->desc.sockfd = LWS_SOCK_INVALID;
1653 vhost->context->count_wsi_allocated++;
1656 * outermost create notification for wsi
1657 * no user_space because no protocol selection
1659 vhost->protocols[0].callback(new_wsi, LWS_CALLBACK_WSI_CREATE,
1665 LWS_VISIBLE int LWS_WARN_UNUSED_RESULT
1666 lws_http_transaction_completed(struct lws *wsi)
1668 int n = NO_PENDING_TIMEOUT;
1670 lws_access_log(wsi);
1672 lwsl_info("%s: wsi %p\n", __func__, wsi);
1673 /* if we can't go back to accept new headers, drop the connection */
1674 if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
1675 lwsl_info("%s: %p: close connection\n", __func__, wsi);
1679 if (lws_bind_protocol(wsi, &wsi->vhost->protocols[0]))
1682 /* otherwise set ourselves up ready to go again */
1683 wsi->state = LWSS_HTTP;
1684 wsi->mode = LWSCM_HTTP_SERVING;
1685 wsi->u.http.content_length = 0;
1686 wsi->u.http.content_remain = 0;
1687 wsi->hdr_parsing_completed = 0;
1688 #ifdef LWS_WITH_ACCESS_LOG
1689 wsi->access_log.sent = 0;
1692 if (wsi->vhost->keepalive_timeout)
1693 n = PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE;
1694 lws_set_timeout(wsi, n, wsi->vhost->keepalive_timeout);
1697 * We already know we are on http1.1 / keepalive and the next thing
1698 * coming will be another header set.
1700 * If there is no pending rx and we still have the ah, drop it and
1701 * reacquire a new ah when the new headers start to arrive. (Otherwise
1702 * we needlessly hog an ah indefinitely.)
1704 * However if there is pending rx and we know from the keepalive state
1705 * that is already at least the start of another header set, simply
1706 * reset the existing header table and keep it.
1708 if (wsi->u.hdr.ah) {
1709 lwsl_info("%s: wsi->more_rx_waiting=%d\n", __func__,
1710 wsi->more_rx_waiting);
1712 if (!wsi->more_rx_waiting) {
1713 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1714 lws_header_table_detach(wsi, 1);
1715 #ifdef LWS_OPENSSL_SUPPORT
1717 * additionally... if we are hogging an SSL instance
1718 * with no pending pipelined headers (or ah now), and
1719 * SSL is scarce, drop this connection without waiting
1722 if (wsi->vhost->use_ssl &&
1723 wsi->context->simultaneous_ssl_restriction &&
1724 wsi->context->simultaneous_ssl ==
1725 wsi->context->simultaneous_ssl_restriction) {
1726 lwsl_info("%s: simultaneous_ssl_restriction and nothing pipelined\n", __func__);
1731 lws_header_table_reset(wsi, 1);
1734 /* If we're (re)starting on headers, need other implied init */
1735 wsi->u.hdr.ues = URIES_IDLE;
1737 lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
1742 /* if not a socket, it's a raw, non-ssl file descriptor */
1744 LWS_VISIBLE struct lws *
1745 lws_adopt_descriptor_vhost(struct lws_vhost *vh, lws_adoption_type type,
1746 lws_sock_file_fd_type fd, const char *vh_prot_name,
1749 struct lws_context *context = vh->context;
1750 struct lws *new_wsi = lws_create_new_server_wsi(vh);
1751 struct lws_context_per_thread *pt;
1755 if (type & LWS_ADOPT_SOCKET)
1756 compatible_close(fd.sockfd);
1759 pt = &context->pt[(int)new_wsi->tsi];
1760 lws_stats_atomic_bump(context, pt, LWSSTATS_C_CONNECTIONS, 1);
1763 new_wsi->parent = parent;
1764 new_wsi->sibling_list = parent->child_list;
1765 parent->child_list = new_wsi;
1771 new_wsi->protocol = lws_vhost_name_to_protocol(new_wsi->vhost,
1773 if (!new_wsi->protocol) {
1774 lwsl_err("Protocol %s not enabled on vhost %s\n",
1775 vh_prot_name, new_wsi->vhost->name);
1778 if (lws_ensure_user_space(new_wsi)) {
1779 lwsl_notice("OOM trying to get user_space\n");
1783 if (type & LWS_ADOPT_HTTP) /* he will transition later */
1785 &vh->protocols[vh->default_protocol_index];
1786 else { /* this is the only time he will transition */
1787 lws_bind_protocol(new_wsi,
1788 &vh->protocols[vh->raw_protocol_index]);
1789 lws_union_transition(new_wsi, LWSCM_RAW);
1792 if (type & LWS_ADOPT_SOCKET) { /* socket desc */
1793 lwsl_debug("%s: new wsi %p, sockfd %d\n", __func__, new_wsi,
1794 (int)(size_t)fd.sockfd);
1796 if (type & LWS_ADOPT_HTTP)
1797 /* the transport is accepted...
1798 * give him time to negotiate */
1799 lws_set_timeout(new_wsi,
1800 PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
1801 context->timeout_secs);
1804 #if defined(LWS_WITH_ESP8266)
1805 esp8266_tcp_stream_accept(accept_fd, new_wsi);
1808 } else /* file desc */
1809 lwsl_debug("%s: new wsi %p, filefd %d\n", __func__, new_wsi,
1810 (int)(size_t)fd.filefd);
1813 * A new connection was accepted. Give the user a chance to
1814 * set properties of the newly created wsi. There's no protocol
1815 * selected yet so we issue this to the vhosts's default protocol,
1816 * itself by default protocols[0]
1818 n = LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED;
1819 if (!(type & LWS_ADOPT_HTTP)) {
1820 if (!(type & LWS_ADOPT_SOCKET))
1821 n = LWS_CALLBACK_RAW_ADOPT_FILE;
1823 n = LWS_CALLBACK_RAW_ADOPT;
1826 if (!LWS_SSL_ENABLED(new_wsi->vhost) || !(type & LWS_ADOPT_ALLOW_SSL) ||
1827 !(type & LWS_ADOPT_SOCKET)) {
1829 if (!(type & LWS_ADOPT_HTTP)) {
1830 if (!(type & LWS_ADOPT_SOCKET))
1831 new_wsi->mode = LWSCM_RAW_FILEDESC;
1833 new_wsi->mode = LWSCM_RAW;
1837 if (!(type & LWS_ADOPT_HTTP))
1838 new_wsi->mode = LWSCM_SSL_INIT_RAW;
1840 new_wsi->mode = LWSCM_SSL_INIT;
1845 lws_libev_accept(new_wsi, new_wsi->desc);
1846 lws_libuv_accept(new_wsi, new_wsi->desc);
1847 lws_libevent_accept(new_wsi, new_wsi->desc);
1850 if (insert_wsi_socket_into_fds(context, new_wsi)) {
1851 lwsl_err("%s: fail inserting socket\n", __func__);
1855 if (lws_server_socket_service_ssl(new_wsi, fd.sockfd)) {
1856 lwsl_err("%s: fail ssl negotiation\n", __func__);
1861 * by deferring callback to this point, after insertion to fds,
1862 * lws_callback_on_writable() can work from the callback
1864 if ((new_wsi->protocol->callback)(
1865 new_wsi, n, new_wsi->user_space, NULL, 0))
1868 if (type & LWS_ADOPT_HTTP) {
1869 if (!lws_header_table_attach(new_wsi, 0)) {
1870 lwsl_debug("Attached ah immediately\n");
1872 lwsl_notice("%s: waiting for ah\n", __func__);
1879 if (type & LWS_ADOPT_SOCKET)
1880 lws_close_free_wsi(new_wsi, LWS_CLOSE_STATUS_NOSTATUS);
1885 lwsl_notice("%s: exiting on bail\n", __func__);
1887 parent->child_list = new_wsi->sibling_list;
1888 if (new_wsi->user_space)
1889 lws_free(new_wsi->user_space);
1891 compatible_close(fd.sockfd);
1896 LWS_VISIBLE struct lws *
1897 lws_adopt_socket_vhost(struct lws_vhost *vh, lws_sockfd_type accept_fd)
1899 lws_sock_file_fd_type fd;
1901 fd.sockfd = accept_fd;
1902 return lws_adopt_descriptor_vhost(vh, LWS_ADOPT_SOCKET |
1903 LWS_ADOPT_HTTP | LWS_ADOPT_ALLOW_SSL, fd, NULL, NULL);
1906 LWS_VISIBLE struct lws *
1907 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd)
1909 return lws_adopt_socket_vhost(context->vhost_list, accept_fd);
1912 /* Common read-buffer adoption for lws_adopt_*_readbuf */
1914 adopt_socket_readbuf(struct lws *wsi, const char *readbuf, size_t len)
1916 struct lws_context_per_thread *pt;
1917 struct allocated_headers *ah;
1918 struct lws_pollfd *pfd;
1923 if (!readbuf || len == 0)
1926 if (len > sizeof(ah->rx)) {
1927 lwsl_err("%s: rx in too big\n", __func__);
1932 * we can't process the initial read data until we can attach an ah.
1934 * if one is available, get it and place the data in his ah rxbuf...
1935 * wsi with ah that have pending rxbuf get auto-POLLIN service.
1937 * no autoservice because we didn't get a chance to attach the
1938 * readbuf data to wsi or ah yet, and we will do it next if we get
1941 if (wsi->u.hdr.ah || !lws_header_table_attach(wsi, 0)) {
1943 memcpy(ah->rx, readbuf, len);
1947 lwsl_notice("%s: calling service on readbuf ah\n", __func__);
1948 pt = &wsi->context->pt[(int)wsi->tsi];
1950 /* unlike a normal connect, we have the headers already
1951 * (or the first part of them anyway).
1952 * libuv won't come back and service us without a network
1953 * event, so we need to do the header service right here.
1955 pfd = &pt->fds[wsi->position_in_fds_table];
1956 pfd->revents |= LWS_POLLIN;
1957 lwsl_err("%s: calling service\n", __func__);
1958 if (lws_service_fd_tsi(wsi->context, pfd, wsi->tsi))
1959 /* service closed us */
1964 lwsl_err("%s: deferring handling ah\n", __func__);
1966 * hum if no ah came, we are on the wait list and must defer
1967 * dealing with this until the ah arrives.
1969 * later successful lws_header_table_attach() will apply the
1970 * below to the rx buffer (via lws_header_table_reset()).
1972 wsi->u.hdr.preamble_rx = lws_malloc(len);
1973 if (!wsi->u.hdr.preamble_rx) {
1977 memcpy(wsi->u.hdr.preamble_rx, readbuf, len);
1978 wsi->u.hdr.preamble_rx_len = len;
1983 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1988 LWS_VISIBLE struct lws *
1989 lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
1990 const char *readbuf, size_t len)
1992 return adopt_socket_readbuf(lws_adopt_socket(context, accept_fd), readbuf, len);
1995 LWS_VISIBLE struct lws *
1996 lws_adopt_socket_vhost_readbuf(struct lws_vhost *vhost, lws_sockfd_type accept_fd,
1997 const char *readbuf, size_t len)
1999 return adopt_socket_readbuf(lws_adopt_socket_vhost(vhost, accept_fd), readbuf, len);
2003 lws_server_socket_service(struct lws_context *context, struct lws *wsi,
2004 struct lws_pollfd *pollfd)
2006 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
2007 lws_sockfd_type accept_fd = LWS_SOCK_INVALID;
2008 struct allocated_headers *ah;
2009 lws_sock_file_fd_type fd;
2010 int opts = LWS_ADOPT_SOCKET | LWS_ADOPT_ALLOW_SSL;
2012 struct sockaddr_in cli_addr;
2017 // lwsl_notice("%s: mode %d\n", __func__, wsi->mode);
2019 switch (wsi->mode) {
2021 case LWSCM_HTTP_SERVING:
2022 case LWSCM_HTTP_SERVING_ACCEPTED:
2023 case LWSCM_HTTP2_SERVING:
2026 /* handle http headers coming in */
2028 /* pending truncated sends have uber priority */
2030 if (wsi->trunc_len) {
2031 if (!(pollfd->revents & LWS_POLLOUT))
2034 if (lws_issue_raw(wsi, wsi->trunc_alloc +
2036 wsi->trunc_len) < 0)
2039 * we can't afford to allow input processing to send
2040 * something new, so spin around he event loop until
2041 * he doesn't have any partials
2046 /* any incoming data ready? */
2048 if (!(pollfd->revents & pollfd->events & LWS_POLLIN))
2052 * If we previously just did POLLIN when IN and OUT were
2053 * signalled (because POLLIN processing may have used up
2054 * the POLLOUT), don't let that happen twice in a row...
2055 * next time we see the situation favour POLLOUT
2057 #if !defined(LWS_WITH_ESP8266)
2058 if (wsi->favoured_pollin &&
2059 (pollfd->revents & pollfd->events & LWS_POLLOUT)) {
2060 wsi->favoured_pollin = 0;
2065 /* these states imply we MUST have an ah attached */
2067 if (wsi->mode != LWSCM_RAW && (wsi->state == LWSS_HTTP ||
2068 wsi->state == LWSS_HTTP_ISSUING_FILE ||
2069 wsi->state == LWSS_HTTP_HEADERS)) {
2070 if (!wsi->u.hdr.ah) {
2072 //lwsl_err("wsi %p: missing ah\n", wsi);
2073 /* no autoservice beacuse we will do it next */
2074 if (lws_header_table_attach(wsi, 0)) {
2075 lwsl_info("wsi %p: failed to acquire ah\n", wsi);
2081 //lwsl_notice("%s: %p: rxpos:%d rxlen:%d\n", __func__, wsi,
2082 // ah->rxpos, ah->rxlen);
2084 /* if nothing in ah rx buffer, get some fresh rx */
2085 if (ah->rxpos == ah->rxlen) {
2086 ah->rxlen = lws_ssl_capable_read(wsi, ah->rx,
2089 //lwsl_notice("%s: wsi %p, ah->rxlen = %d\r\n",
2090 // __func__, wsi, ah->rxlen);
2091 switch (ah->rxlen) {
2093 lwsl_info("%s: read 0 len\n", __func__);
2094 /* lwsl_info(" state=%d\n", wsi->state); */
2095 // if (!wsi->hdr_parsing_completed)
2096 // lws_header_table_detach(wsi);
2098 case LWS_SSL_CAPABLE_ERROR:
2100 case LWS_SSL_CAPABLE_MORE_SERVICE:
2101 ah->rxlen = ah->rxpos = 0;
2106 if (!(ah->rxpos != ah->rxlen && ah->rxlen)) {
2107 lwsl_err("%s: assert: rxpos %d, rxlen %d\n",
2108 __func__, ah->rxpos, ah->rxlen);
2113 /* just ignore incoming if waiting for close */
2114 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
2115 n = lws_read(wsi, ah->rx + ah->rxpos,
2116 ah->rxlen - ah->rxpos);
2117 if (n < 0) /* we closed wsi */
2119 if (wsi->u.hdr.ah) {
2120 if ( wsi->u.hdr.ah->rxlen)
2121 wsi->u.hdr.ah->rxpos += n;
2123 lwsl_debug("%s: wsi %p: ah read rxpos %d, rxlen %d\n", __func__, wsi, wsi->u.hdr.ah->rxpos, wsi->u.hdr.ah->rxlen);
2125 if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen &&
2126 (wsi->mode != LWSCM_HTTP_SERVING &&
2127 wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED &&
2128 wsi->mode != LWSCM_HTTP2_SERVING))
2129 lws_header_table_detach(wsi, 1);
2137 len = lws_ssl_capable_read(wsi, pt->serv_buf,
2138 context->pt_serv_buf_size);
2139 lwsl_debug("%s: wsi %p read %d\r\n", __func__, wsi, len);
2142 lwsl_info("%s: read 0 len\n", __func__);
2143 /* lwsl_info(" state=%d\n", wsi->state); */
2144 // if (!wsi->hdr_parsing_completed)
2145 // lws_header_table_detach(wsi);
2147 case LWS_SSL_CAPABLE_ERROR:
2149 case LWS_SSL_CAPABLE_MORE_SERVICE:
2153 if (wsi->mode == LWSCM_RAW) {
2154 n = user_callback_handle_rxflow(wsi->protocol->callback,
2155 wsi, LWS_CALLBACK_RAW_RX,
2156 wsi->user_space, pt->serv_buf, len);
2158 lwsl_info("LWS_CALLBACK_RAW_RX_fail\n");
2164 /* just ignore incoming if waiting for close */
2165 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
2167 * this may want to send
2168 * (via HTTP callback for example)
2170 n = lws_read(wsi, pt->serv_buf, len);
2171 if (n < 0) /* we closed wsi */
2174 * he may have used up the
2175 * writability above, if we will defer POLLOUT
2176 * processing in favour of POLLIN, note it
2178 if (pollfd->revents & LWS_POLLOUT)
2179 wsi->favoured_pollin = 1;
2185 /* this handles POLLOUT for http serving fragments */
2187 if (!(pollfd->revents & LWS_POLLOUT))
2191 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
2192 lwsl_notice("%s a\n", __func__);
2196 if (wsi->mode == LWSCM_RAW) {
2197 lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_WRITEABLE_CB, 1);
2198 #if defined(LWS_WITH_STATS)
2200 uint64_t ul = time_in_microseconds() - wsi->active_writable_req_us;
2202 lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_MS_WRITABLE_DELAY, ul);
2203 lws_stats_atomic_max(wsi->context, pt, LWSSTATS_MS_WORST_WRITABLE_DELAY, ul);
2204 wsi->active_writable_req_us = 0;
2207 n = user_callback_handle_rxflow(wsi->protocol->callback,
2208 wsi, LWS_CALLBACK_RAW_WRITEABLE,
2209 wsi->user_space, NULL, 0);
2211 lwsl_info("writeable_fail\n");
2217 if (!wsi->hdr_parsing_completed)
2220 if (wsi->state != LWSS_HTTP_ISSUING_FILE) {
2222 lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_C_WRITEABLE_CB, 1);
2223 #if defined(LWS_WITH_STATS)
2225 uint64_t ul = time_in_microseconds() - wsi->active_writable_req_us;
2227 lws_stats_atomic_bump(wsi->context, pt, LWSSTATS_MS_WRITABLE_DELAY, ul);
2228 lws_stats_atomic_max(wsi->context, pt, LWSSTATS_MS_WORST_WRITABLE_DELAY, ul);
2229 wsi->active_writable_req_us = 0;
2233 n = user_callback_handle_rxflow(wsi->protocol->callback,
2234 wsi, LWS_CALLBACK_HTTP_WRITEABLE,
2235 wsi->user_space, NULL, 0);
2237 lwsl_info("writeable_fail\n");
2243 /* >0 == completion, <0 == error */
2244 n = lws_serve_http_file_fragment(wsi);
2245 if (n < 0 || (n > 0 && lws_http_transaction_completed(wsi))) {
2246 lwsl_info("completed\n");
2252 case LWSCM_SERVER_LISTENER:
2255 /* pollin means a client has connected to us then */
2258 if (!(pollfd->revents & LWS_POLLIN) || !(pollfd->events & LWS_POLLIN))
2261 #ifdef LWS_OPENSSL_SUPPORT
2263 * can we really accept it, with regards to SSL limit?
2264 * another vhost may also have had POLLIN on his listener this
2265 * round and used it up already
2268 if (wsi->vhost->use_ssl &&
2269 context->simultaneous_ssl_restriction &&
2270 context->simultaneous_ssl ==
2271 context->simultaneous_ssl_restriction)
2272 /* no... ignore it, he won't come again until we are
2273 * below the simultaneous_ssl_restriction limit and
2274 * POLLIN is enabled on him again
2278 /* listen socket got an unencrypted connection... */
2280 clilen = sizeof(cli_addr);
2281 lws_latency_pre(context, wsi);
2282 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
2284 lws_latency(context, wsi, "listener accept", accept_fd,
2286 if (accept_fd < 0) {
2287 if (LWS_ERRNO == LWS_EAGAIN ||
2288 LWS_ERRNO == LWS_EWOULDBLOCK) {
2289 // lwsl_err("accept asks to try again\n");
2292 lwsl_err("ERROR on accept: %s\n", strerror(LWS_ERRNO));
2296 lws_plat_set_socket_options(wsi->vhost, accept_fd);
2298 lwsl_debug("accepted new conn port %u on fd=%d\n",
2299 ntohs(cli_addr.sin_port), accept_fd);
2302 /* not very beautiful... */
2303 accept_fd = (lws_sockfd_type)pollfd;
2306 * look at who we connected to and give user code a chance
2307 * to reject based on client IP. There's no protocol selected
2308 * yet so we issue this to protocols[0]
2310 if ((wsi->vhost->protocols[0].callback)(wsi,
2311 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
2312 NULL, (void *)(long)accept_fd, 0)) {
2313 lwsl_debug("Callback denied network connection\n");
2314 compatible_close(accept_fd);
2318 if (!(wsi->vhost->options & LWS_SERVER_OPTION_ONLY_RAW))
2319 opts |= LWS_ADOPT_HTTP;
2321 fd.sockfd = accept_fd;
2322 if (!lws_adopt_descriptor_vhost(wsi->vhost, opts, fd,
2324 /* already closed cleanly as necessary */
2328 } while (pt->fds_count < context->fd_limit_per_thread - 1 &&
2329 lws_poll_listen_fd(&pt->fds[wsi->position_in_fds_table]) > 0);
2337 if (!lws_server_socket_service_ssl(wsi, accept_fd))
2341 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
2347 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
2348 const char *other_headers, int other_headers_len)
2350 static const char * const intermediates[] = { "private", "public" };
2351 struct lws_context *context = lws_get_context(wsi);
2352 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
2353 #if defined(LWS_WITH_RANGES)
2354 struct lws_range_parsing *rp = &wsi->u.http.range;
2356 char cache_control[50], *cc = "no-store";
2357 unsigned char *response = pt->serv_buf + LWS_PRE;
2358 unsigned char *p = response;
2359 unsigned char *end = p + context->pt_serv_buf_size - LWS_PRE;
2360 unsigned long computed_total_content_length;
2361 int ret = 0, cclen = 8, n = HTTP_STATUS_OK;
2362 lws_fop_flags_t fflags = LWS_O_RDONLY;
2363 #if defined(LWS_WITH_RANGES)
2366 const struct lws_plat_file_ops *fops;
2370 * We either call the platform fops .open with first arg platform fops,
2371 * or we call fops_zip .open with first arg platform fops, and fops_zip
2372 * open will decide whether to switch to fops_zip or stay with fops_def.
2374 * If wsi->u.http.fop_fd is already set, the caller already opened it
2376 if (!wsi->u.http.fop_fd) {
2377 fops = lws_vfs_select_fops(wsi->context->fops, file, &vpath);
2378 fflags |= lws_vfs_prepare_flags(wsi);
2379 wsi->u.http.fop_fd = fops->LWS_FOP_OPEN(wsi->context->fops,
2380 file, vpath, &fflags);
2381 if (!wsi->u.http.fop_fd) {
2382 lwsl_err("Unable to open '%s'\n", file);
2387 wsi->u.http.filelen = lws_vfs_get_length(wsi->u.http.fop_fd);
2388 computed_total_content_length = wsi->u.http.filelen;
2390 #if defined(LWS_WITH_RANGES)
2391 ranges = lws_ranges_init(wsi, rp, wsi->u.http.filelen);
2393 lwsl_debug("Range count %d\n", ranges);
2396 * 1 range -> 206 + Content-Type: normal; Content-Range;
2397 * more -> 206 + Content-Type: multipart/byteranges
2398 * Repeat the true Content-Type in each multipart header
2399 * along with Content-Range
2402 /* it means he expressed a range in Range:, but it was illegal */
2403 lws_return_http_status(wsi, HTTP_STATUS_REQ_RANGE_NOT_SATISFIABLE, NULL);
2404 if (lws_http_transaction_completed(wsi))
2405 return -1; /* <0 means just hang up */
2407 lws_vfs_file_close(&wsi->u.http.fop_fd);
2409 return 0; /* == 0 means we dealt with the transaction complete */
2412 n = HTTP_STATUS_PARTIAL_CONTENT;
2415 if (lws_add_http_header_status(wsi, n, &p, end))
2418 if ((wsi->u.http.fop_fd->flags & (LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP |
2419 LWS_FOP_FLAG_COMPR_IS_GZIP)) ==
2420 (LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP | LWS_FOP_FLAG_COMPR_IS_GZIP)) {
2421 if (lws_add_http_header_by_token(wsi,
2422 WSI_TOKEN_HTTP_CONTENT_ENCODING,
2423 (unsigned char *)"gzip", 4, &p, end))
2425 lwsl_info("file is being provided in gzip\n");
2428 #if defined(LWS_WITH_RANGES)
2429 if (ranges < 2 && content_type && content_type[0])
2430 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
2431 (unsigned char *)content_type,
2432 strlen(content_type), &p, end))
2435 if (ranges >= 2) { /* multipart byteranges */
2436 strncpy(wsi->u.http.multipart_content_type, content_type,
2437 sizeof(wsi->u.http.multipart_content_type) - 1);
2438 wsi->u.http.multipart_content_type[
2439 sizeof(wsi->u.http.multipart_content_type) - 1] = '\0';
2440 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
2441 (unsigned char *)"multipart/byteranges; boundary=_lws",
2446 * our overall content length has to include
2448 * - (n + 1) x "_lws\r\n"
2449 * - n x Content-Type: xxx/xxx\r\n
2450 * - n x Content-Range: bytes xxx-yyy/zzz\r\n
2452 * - the actual payloads (aggregated in rp->agg)
2454 * Precompute it for the main response header
2457 computed_total_content_length = (unsigned long)rp->agg +
2458 6 /* final _lws\r\n */;
2460 lws_ranges_reset(rp);
2461 while (lws_ranges_next(rp)) {
2462 n = lws_snprintf(cache_control, sizeof(cache_control),
2463 "bytes %llu-%llu/%llu",
2464 rp->start, rp->end, rp->extent);
2466 computed_total_content_length +=
2467 6 /* header _lws\r\n */ +
2468 14 + strlen(content_type) + 2 + /* Content-Type: xxx/xxx\r\n */
2469 15 + n + 2 + /* Content-Range: xxxx\r\n */
2473 lws_ranges_reset(rp);
2474 lws_ranges_next(rp);
2478 computed_total_content_length = (unsigned long)rp->agg;
2479 n = lws_snprintf(cache_control, sizeof(cache_control), "bytes %llu-%llu/%llu",
2480 rp->start, rp->end, rp->extent);
2482 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_RANGE,
2483 (unsigned char *)cache_control,
2488 wsi->u.http.range.inside = 0;
2490 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ACCEPT_RANGES,
2491 (unsigned char *)"bytes", 5, &p, end))
2495 if (!wsi->sending_chunked) {
2496 if (lws_add_http_header_content_length(wsi,
2497 computed_total_content_length,
2501 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_TRANSFER_ENCODING,
2502 (unsigned char *)"chunked",
2507 if (wsi->cache_secs && wsi->cache_reuse) {
2508 if (wsi->cache_revalidate) {
2510 cclen = sprintf(cache_control, "%s max-age: %u",
2511 intermediates[wsi->cache_intermediaries],
2519 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CACHE_CONTROL,
2520 (unsigned char *)cc, cclen, &p, end))
2523 if (wsi->u.http.connection_type == HTTP_CONNECTION_KEEP_ALIVE)
2524 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
2525 (unsigned char *)"keep-alive", 10, &p, end))
2528 if (other_headers) {
2529 if ((end - p) < other_headers_len)
2531 memcpy(p, other_headers, other_headers_len);
2532 p += other_headers_len;
2535 if (lws_finalize_http_header(wsi, &p, end))
2538 ret = lws_write(wsi, response, p - response, LWS_WRITE_HTTP_HEADERS);
2539 if (ret != (p - response)) {
2540 lwsl_err("_write returned %d from %ld\n", ret, (long)(p - response));
2544 wsi->u.http.filepos = 0;
2545 wsi->state = LWSS_HTTP_ISSUING_FILE;
2547 return lws_serve_http_file_fragment(wsi);
2551 lws_interpret_incoming_packet(struct lws *wsi, unsigned char **buf, size_t len)
2555 lwsl_parser("%s: received %d byte packet\n", __func__, (int)len);
2557 lwsl_hexdump(*buf, len);
2560 /* let the rx protocol state machine have as much as it needs */
2564 * we were accepting input but now we stopped doing so
2566 if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
2567 lws_rxflow_cache(wsi, *buf, 0, len);
2568 lwsl_parser("%s: cached %ld\n", __func__, (long)len);
2572 if (wsi->u.ws.rx_draining_ext) {
2573 // lwsl_notice("draining with 0\n");
2574 m = lws_rx_sm(wsi, 0);
2580 /* account for what we're using in rxflow buffer */
2581 if (wsi->rxflow_buffer)
2584 /* consume payload bytes efficiently */
2586 wsi->lws_rx_parse_state ==
2587 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED) {
2588 m = lws_payload_until_length_exhausted(wsi, buf, &len);
2589 if (wsi->rxflow_buffer)
2590 wsi->rxflow_pos += m;
2593 /* process the byte */
2594 m = lws_rx_sm(wsi, *(*buf)++);
2600 lwsl_parser("%s: exit with %d unused\n", __func__, (int)len);
2606 lws_server_get_canonical_hostname(struct lws_context *context,
2607 struct lws_context_creation_info *info)
2609 if (lws_check_opt(info->options, LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME))
2611 #if LWS_POSIX && !defined(LWS_WITH_ESP32)
2612 /* find canonical hostname */
2613 gethostname((char *)context->canonical_hostname,
2614 sizeof(context->canonical_hostname) - 1);
2616 lwsl_notice(" canonical_hostname = %s\n", context->canonical_hostname);
2622 #define LWS_MAX_ELEM_NAME 32
2624 enum urldecode_stateful {
2638 static const char * const mp_hdr[] = {
2639 "content-disposition: ",
2644 typedef int (*lws_urldecode_stateful_cb)(void *data,
2645 const char *name, char **buf, int len, int final);
2647 struct lws_urldecode_stateful {
2650 char name[LWS_MAX_ELEM_NAME];
2651 char temp[LWS_MAX_ELEM_NAME];
2652 char content_type[32];
2653 char content_disp[32];
2654 char content_disp_filename[256];
2655 char mime_boundary[128];
2662 unsigned int multipart_form_data:1;
2663 unsigned int inside_quote:1;
2664 unsigned int subname:1;
2665 unsigned int boundary_real_crlf:1;
2667 enum urldecode_stateful state;
2669 lws_urldecode_stateful_cb output;
2672 static struct lws_urldecode_stateful *
2673 lws_urldecode_s_create(struct lws *wsi, char *out, int out_len, void *data,
2674 lws_urldecode_stateful_cb output)
2676 struct lws_urldecode_stateful *s = lws_zalloc(sizeof(*s));
2684 s->out_len = out_len;
2693 if (lws_hdr_copy(wsi, buf, sizeof(buf), WSI_TOKEN_HTTP_CONTENT_TYPE) > 0) {
2694 /* multipart/form-data; boundary=----WebKitFormBoundarycc7YgAPEIHvgE9Bf */
2696 if (!strncmp(buf, "multipart/form-data", 19)) {
2697 s->multipart_form_data = 1;
2698 s->state = MT_LOOK_BOUND_IN;
2700 p = strstr(buf, "boundary=");
2703 s->mime_boundary[m++] = '\x0d';
2704 s->mime_boundary[m++] = '\x0a';
2705 s->mime_boundary[m++] = '-';
2706 s->mime_boundary[m++] = '-';
2707 while (m < sizeof(s->mime_boundary) - 1 &&
2709 s->mime_boundary[m++] = *p++;
2711 s->mime_boundary[m] = '\0';
2713 lwsl_notice("boundary '%s'\n", s->mime_boundary);
2722 lws_urldecode_s_process(struct lws_urldecode_stateful *s, const char *in, int len)
2725 char c, was_end = 0;
2728 if (s->pos == s->out_len - s->mp - 1) {
2729 if (s->output(s->data, s->name, &s->out, s->pos, 0))
2737 /* states for url arg style */
2740 s->inside_quote = 0;
2742 s->name[s->pos] = '\0';
2749 s->name[s->pos] = '\0';
2750 if (s->output(s->data, s->name, &s->out, s->pos, 1))
2757 if (s->pos >= sizeof(s->name) - 1) {
2758 lwsl_notice("Name too long\n");
2761 s->name[s->pos++] = *in++;
2770 s->out[s->pos] = '\0';
2771 if (s->output(s->data, s->name, &s->out, s->pos, 1))
2780 s->out[s->pos++] = ' ';
2783 s->out[s->pos++] = *in++;
2786 n = char_to_hex(*in);
2796 n = char_to_hex(*in);
2801 s->out[s->pos++] = s->sum | n;
2806 /* states for multipart / mime style */
2808 case MT_LOOK_BOUND_IN:
2810 if (*in == s->mime_boundary[s->mp] &&
2811 s->mime_boundary[s->mp]) {
2814 if (!s->mime_boundary[s->mp]) {
2816 s->state = MT_IGNORE1;
2818 if (s->pos || was_end)
2819 if (s->output(s->data, s->name,
2820 &s->out, s->pos, 1))
2825 s->content_disp[0] = '\0';
2827 s->content_disp_filename[0] = '\0';
2828 s->boundary_real_crlf = 1;
2834 if (!s->boundary_real_crlf)
2837 memcpy(s->out + s->pos, s->mime_boundary + n, s->mp - n);
2840 goto retry_as_first;
2843 s->out[s->pos++] = *in;
2851 if (c >= 'A' && c <= 'Z')
2853 for (n = 0; n < ARRAY_SIZE(mp_hdr); n++)
2854 if (c == mp_hdr[n][s->mp]) {
2868 if (mp_hdr[hit][s->mp])
2876 s->state = MT_LOOK_BOUND_IN;
2878 s->state += hit + 1;
2882 /* form-data; name="file"; filename="t.txt" */
2884 if (*in == '\x0d') {
2885 // lwsl_notice("disp: '%s', '%s', '%s'\n",
2886 // s->content_disp, s->name,
2887 // s->content_disp_filename);
2889 if (s->content_disp_filename[0])
2890 if (s->output(s->data, s->name,
2891 &s->out, s->pos, LWS_UFS_OPEN))
2893 s->state = MT_IGNORE2;
2904 s->inside_quote ^= 1;
2910 s->temp[s->mp] = '\0';
2915 if (s->mp < sizeof(s->temp) - 1 &&
2916 (*in != ' ' || s->inside_quote))
2917 s->temp[s->mp++] = *in;
2922 if (s->mp < sizeof(s->content_disp) - 1)
2923 s->content_disp[s->mp++] = *in;
2924 s->content_disp[s->mp] = '\0';
2928 if (!strcmp(s->temp, "name")) {
2929 if (s->mp < sizeof(s->name) - 1)
2930 s->name[s->mp++] = *in;
2931 s->name[s->mp] = '\0';
2935 if (!strcmp(s->temp, "filename")) {
2936 if (s->mp < sizeof(s->content_disp_filename) - 1)
2937 s->content_disp_filename[s->mp++] = *in;
2938 s->content_disp_filename[s->mp] = '\0';
2947 s->state = MT_IGNORE2;
2949 if (s->mp < sizeof(s->content_type) - 1)
2950 s->content_type[s->mp++] = *in;
2951 s->content_type[s->mp] = '\0';
2958 s->state = MT_IGNORE2;
2965 s->state = MT_HNAME;
2975 lws_urldecode_s_destroy(struct lws_urldecode_stateful *s)
2979 if (s->state != US_IDLE)
2983 if (s->output(s->data, s->name, &s->out, s->pos, 1))
2992 struct lws_urldecode_stateful *s;
2993 lws_spa_fileupload_cb opt_cb;
2994 const char * const *param_names;
3008 lws_urldecode_spa_lookup(struct lws_spa *spa,
3013 for (n = 0; n < spa->count_params; n++)
3014 if (!strcmp(spa->param_names[n], name))
3021 lws_urldecode_spa_cb(void *data, const char *name, char **buf, int len,
3024 struct lws_spa *spa =
3025 (struct lws_spa *)data;
3028 if (spa->s->content_disp_filename[0]) {
3030 n = spa->opt_cb(spa->opt_data, name,
3031 spa->s->content_disp_filename,
3039 n = lws_urldecode_spa_lookup(spa, name);
3041 if (n == -1 || !len) /* unrecognized */
3044 if (!spa->params[n])
3045 spa->params[n] = *buf;
3047 if ((*buf) + len >= spa->end) {
3048 lwsl_notice("%s: exceeded storage\n", __func__);
3052 spa->param_length[n] += len;
3054 /* move it on inside storage */
3058 spa->s->out_len -= len + 1;
3063 LWS_VISIBLE LWS_EXTERN struct lws_spa *
3064 lws_spa_create(struct lws *wsi, const char * const *param_names,
3065 int count_params, int max_storage,
3066 lws_spa_fileupload_cb opt_cb, void *opt_data)
3068 struct lws_spa *spa = lws_zalloc(sizeof(*spa));
3073 spa->param_names = param_names;
3074 spa->count_params = count_params;
3075 spa->max_storage = max_storage;
3076 spa->opt_cb = opt_cb;
3077 spa->opt_data = opt_data;
3079 spa->storage = lws_malloc(max_storage);
3082 spa->end = spa->storage + max_storage - 1;
3084 spa->params = lws_zalloc(sizeof(char *) * count_params);
3088 spa->s = lws_urldecode_s_create(wsi, spa->storage, max_storage, spa,
3089 lws_urldecode_spa_cb);
3093 spa->param_length = lws_zalloc(sizeof(int) * count_params);
3094 if (!spa->param_length)
3097 lwsl_info("%s: Created SPA %p\n", __func__, spa);
3102 lws_urldecode_s_destroy(spa->s);
3104 lws_free(spa->params);
3106 lws_free(spa->storage);
3113 LWS_VISIBLE LWS_EXTERN int
3114 lws_spa_process(struct lws_spa *ludspa, const char *in, int len)
3117 lwsl_err("%s: NULL spa\n", __func__);
3120 /* we reject any junk after the last part arrived and we finalized */
3121 if (ludspa->finalized)
3124 return lws_urldecode_s_process(ludspa->s, in, len);
3127 LWS_VISIBLE LWS_EXTERN int
3128 lws_spa_get_length(struct lws_spa *ludspa, int n)
3130 if (n >= ludspa->count_params)
3133 return ludspa->param_length[n];
3136 LWS_VISIBLE LWS_EXTERN const char *
3137 lws_spa_get_string(struct lws_spa *ludspa, int n)
3139 if (n >= ludspa->count_params)
3142 return ludspa->params[n];
3145 LWS_VISIBLE LWS_EXTERN int
3146 lws_spa_finalize(struct lws_spa *spa)
3149 lws_urldecode_s_destroy(spa->s);
3158 LWS_VISIBLE LWS_EXTERN int
3159 lws_spa_destroy(struct lws_spa *spa)
3163 lwsl_notice("%s: destroy spa %p\n", __func__, spa);
3166 lws_urldecode_s_destroy(spa->s);
3168 lwsl_debug("%s %p %p %p %p\n", __func__,
3175 lws_free(spa->param_length);
3176 lws_free(spa->params);
3177 lws_free(spa->storage);
3184 LWS_VISIBLE LWS_EXTERN int
3185 lws_spa_destroy(struct lws_spa *spa)
3189 lwsl_info("%s: destroy spa %p\n", __func__, spa);
3192 lws_urldecode_s_destroy(spa->s);
3194 lwsl_debug("%s\n", __func__);
3196 lws_free(spa->param_length);
3197 lws_free(spa->params);
3198 lws_free(spa->storage);
3204 LWS_VISIBLE LWS_EXTERN int
3205 lws_chunked_html_process(struct lws_process_html_args *args,
3206 struct lws_process_html_state *s)
3208 char *sp, buffer[32];
3212 /* do replacements */
3214 old_len = args->len;
3217 while (sp < args->p + old_len) {
3219 if (args->len + 7 >= args->max_len) {
3220 lwsl_err("Used up interpret padding\n");
3224 if ((!s->pos && *sp == '$') || s->pos) {
3225 int hits = 0, hit = 0;
3229 s->swallow[s->pos++] = *sp;
3230 if (s->pos == sizeof(s->swallow) - 1)
3232 for (n = 0; n < s->count_vars; n++)
3233 if (!strncmp(s->swallow, s->vars[n], s->pos)) {
3239 s->swallow[s->pos] = '\0';
3240 memcpy(s->start, s->swallow, s->pos);
3246 if (hits == 1 && s->pos == strlen(s->vars[hit])) {
3247 pc = s->replace(s->data, hit);
3251 s->swallow[s->pos] = '\0';
3253 memmove(s->start + n,
3255 old_len - (sp - args->p));
3256 old_len += (n - s->pos) + 1;
3258 memcpy(s->start, pc, n);
3272 /* no space left for final chunk trailer */
3273 if (args->final && args->len + 7 >= args->max_len)
3276 n = sprintf(buffer, "%X\x0d\x0a", args->len);
3279 memcpy(args->p, buffer, n);
3283 sp = args->p + args->len;
3293 sp = args->p + args->len;