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 - 5], ".woff"))
312 return "application/font-woff";
314 if (!strcmp(&file[n - 4], ".xml"))
315 return "application/xml";
318 if (pvo->name[0] == '*') /* ie, match anything */
321 if (!strcmp(&file[n - strlen(pvo->name)], pvo->name))
329 static lws_fop_flags_t
330 lws_vfs_prepare_flags(struct lws *wsi)
332 lws_fop_flags_t f = 0;
334 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_ACCEPT_ENCODING))
337 if (strstr(lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_ACCEPT_ENCODING),
339 lwsl_info("client indicates GZIP is acceptable\n");
340 f |= LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP;
347 lws_http_serve(struct lws *wsi, char *uri, const char *origin,
348 const struct lws_http_mount *m)
350 const struct lws_protocol_vhost_options *pvo = m->interpret;
351 struct lws_process_html_args args;
352 const char *mimetype;
353 #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP8266)
354 const struct lws_plat_file_ops *fops;
356 lws_fop_flags_t fflags = LWS_O_RDONLY;
360 char path[256], sym[512];
361 unsigned char *p = (unsigned char *)sym + 32 + LWS_PRE, *start = p;
362 unsigned char *end = p + sizeof(sym) - 32 - LWS_PRE;
363 #if !defined(WIN32) && LWS_POSIX && !defined(LWS_WITH_ESP32)
368 lws_snprintf(path, sizeof(path) - 1, "%s/%s", origin, uri);
370 #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP8266)
372 fflags |= lws_vfs_prepare_flags(wsi);
376 fops = lws_vfs_select_fops(wsi->context->fops, path, &vpath);
378 if (wsi->u.http.fop_fd)
379 lws_vfs_file_close(&wsi->u.http.fop_fd);
381 wsi->u.http.fop_fd = fops->LWS_FOP_OPEN(wsi->context->fops,
382 path, vpath, &fflags);
383 if (!wsi->u.http.fop_fd) {
384 lwsl_err("Unable to open '%s'\n", path);
389 /* if it can't be statted, don't try */
390 if (fflags & LWS_FOP_FLAG_VIRTUAL)
392 #if defined(LWS_WITH_ESP32)
396 if (fstat(wsi->u.http.fop_fd->fd, &st)) {
397 lwsl_info("unable to stat %s\n", path);
401 if (stat(path, &st)) {
402 lwsl_info("unable to stat %s\n", path);
407 wsi->u.http.fop_fd->mod_time = (uint32_t)st.st_mtime;
408 fflags |= LWS_FOP_FLAG_MOD_TIME_VALID;
410 lwsl_debug(" %s mode %d\n", path, S_IFMT & st.st_mode);
411 #if !defined(WIN32) && LWS_POSIX && !defined(LWS_WITH_ESP32)
412 if ((S_IFMT & st.st_mode) == S_IFLNK) {
413 len = readlink(path, sym, sizeof(sym) - 1);
415 lwsl_err("Failed to read link %s\n", path);
419 lwsl_debug("symlink %s -> %s\n", path, sym);
420 lws_snprintf(path, sizeof(path) - 1, "%s", sym);
423 if ((S_IFMT & st.st_mode) == S_IFDIR) {
424 lwsl_debug("default filename append to dir\n");
425 lws_snprintf(path, sizeof(path) - 1, "%s/%s/index.html",
429 } while ((S_IFMT & st.st_mode) != S_IFREG && spin < 5);
432 lwsl_err("symlink loop %s \n", path);
434 n = sprintf(sym, "%08lX%08lX",
435 (unsigned long)lws_vfs_get_length(wsi->u.http.fop_fd),
436 (unsigned long)lws_vfs_get_mod_time(wsi->u.http.fop_fd));
438 /* disable ranges if IF_RANGE token invalid */
440 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_RANGE))
441 if (strcmp(sym, lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_IF_RANGE)))
442 /* differs - defeat Range: */
443 wsi->u.http.ah->frag_index[WSI_TOKEN_HTTP_RANGE] = 0;
445 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_NONE_MATCH)) {
447 * he thinks he has some version of it already,
448 * check if the tag matches
450 if (!strcmp(sym, lws_hdr_simple_ptr(wsi,
451 WSI_TOKEN_HTTP_IF_NONE_MATCH))) {
453 lwsl_debug("%s: ETAG match %s %s\n", __func__,
456 /* we don't need to send the payload */
457 if (lws_add_http_header_status(wsi,
458 HTTP_STATUS_NOT_MODIFIED, &p, end))
461 if (lws_add_http_header_by_token(wsi,
463 (unsigned char *)sym, n, &p, end))
466 if (lws_finalize_http_header(wsi, &p, end))
469 n = lws_write(wsi, start, p - start,
470 LWS_WRITE_HTTP_HEADERS);
471 if (n != (p - start)) {
472 lwsl_err("_write returned %d from %ld\n", n,
477 lws_vfs_file_close(&wsi->u.http.fop_fd);
479 return lws_http_transaction_completed(wsi);
483 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ETAG,
484 (unsigned char *)sym, n, &p, end))
488 mimetype = lws_get_mimetype(path, m);
490 lwsl_err("unknown mimetype for %s\n", path);
494 lwsl_debug("sending no mimetype for %s\n", path);
496 wsi->sending_chunked = 0;
499 * check if this is in the list of file suffixes to be interpreted by
504 if (n > (int)strlen(pvo->name) &&
505 !strcmp(&path[n - strlen(pvo->name)], pvo->name)) {
506 wsi->sending_chunked = 1;
507 wsi->protocol_interpret_idx = (char)(long)pvo->value;
508 lwsl_info("want %s interpreted by %s\n", path,
509 wsi->vhost->protocols[(int)(long)(pvo->value)].name);
510 wsi->protocol = &wsi->vhost->protocols[(int)(long)(pvo->value)];
511 if (lws_ensure_user_space(wsi))
519 const struct lws_protocols *pp = lws_vhost_name_to_protocol(
520 wsi->vhost, m->protocol);
522 if (lws_bind_protocol(wsi, pp))
525 args.max_len = end - p;
526 if (pp->callback(wsi, LWS_CALLBACK_ADD_HEADERS,
527 wsi->user_space, &args, 0))
529 p = (unsigned char *)args.p;
532 n = lws_serve_http_file(wsi, path, mimetype, (char *)start, p - start);
534 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
535 return -1; /* error or can't reuse connection: close the socket */
543 const struct lws_http_mount *
544 lws_find_mount(struct lws *wsi, const char *uri_ptr, int uri_len)
546 const struct lws_http_mount *hm, *hit = NULL;
549 hm = wsi->vhost->mount_list;
551 if (uri_len >= hm->mountpoint_len &&
552 !strncmp(uri_ptr, hm->mountpoint, hm->mountpoint_len) &&
553 (uri_ptr[hm->mountpoint_len] == '\0' ||
554 uri_ptr[hm->mountpoint_len] == '/' ||
555 hm->mountpoint_len == 1)
557 if (hm->origin_protocol == LWSMPRO_CALLBACK ||
558 ((hm->origin_protocol == LWSMPRO_CGI ||
559 lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI) ||
561 hm->mountpoint_len > best)) {
562 best = hm->mountpoint_len;
575 lws_find_string_in_file(const char *filename, const char *string, int stringlen)
578 int fd, match = 0, pos = 0, n = 0, hit = 0;
580 fd = open(filename, O_RDONLY);
582 lwsl_err("can't open auth file: %s\n", filename);
588 n = read(fd, buf, sizeof(buf));
590 if (match == stringlen)
597 if (match == stringlen) {
598 if (buf[pos] == '\r' || buf[pos] == '\n') {
605 if (buf[pos] == string[match])
619 lws_unauthorised_basic_auth(struct lws *wsi)
621 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
622 unsigned char *start = pt->serv_buf + LWS_PRE,
623 *p = start, *end = p + 512;
627 /* no auth... tell him it is required */
629 if (lws_add_http_header_status(wsi, HTTP_STATUS_UNAUTHORIZED, &p, end))
632 n = lws_snprintf(buf, sizeof(buf), "Basic realm=\"lwsws\"");
633 if (lws_add_http_header_by_token(wsi,
634 WSI_TOKEN_HTTP_WWW_AUTHENTICATE,
635 (unsigned char *)buf, n, &p, end))
638 if (lws_finalize_http_header(wsi, &p, end))
641 n = lws_write(wsi, start, p - start, LWS_WRITE_HTTP_HEADERS);
645 return lws_http_transaction_completed(wsi);
652 lws_http_action(struct lws *wsi)
654 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
655 enum http_connection_type connection_type;
656 enum http_version request_version;
657 char content_length_str[32];
658 struct lws_process_html_args args;
659 const struct lws_http_mount *hit = NULL;
660 unsigned int n, count = 0;
661 char http_version_str[10];
662 char http_conn_str[20];
663 int http_version_len;
664 char *uri_ptr = NULL, *s;
668 static const unsigned char methods[] = {
671 WSI_TOKEN_OPTIONS_URI,
674 WSI_TOKEN_DELETE_URI,
677 WSI_TOKEN_HTTP_COLON_PATH,
680 #if defined(_DEBUG) || defined(LWS_WITH_ACCESS_LOG)
681 static const char * const method_names[] = {
682 "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE", "CONNECT",
688 static const char * const oprot[] = {
689 "http://", "https://"
692 /* it's not websocket.... shall we accept it as http? */
694 for (n = 0; n < ARRAY_SIZE(methods); n++)
695 if (lws_hdr_total_length(wsi, methods[n]))
698 lwsl_warn("Missing URI in HTTP request\n");
703 lwsl_warn("multiple methods?\n");
707 if (lws_ensure_user_space(wsi))
710 for (n = 0; n < ARRAY_SIZE(methods); n++)
711 if (lws_hdr_total_length(wsi, methods[n])) {
712 uri_ptr = lws_hdr_simple_ptr(wsi, methods[n]);
713 uri_len = lws_hdr_total_length(wsi, methods[n]);
714 lwsl_info("Method: %s request for '%s'\n",
715 method_names[n], uri_ptr);
722 /* we insist on absolute paths */
724 if (uri_ptr[0] != '/') {
725 lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
730 /* HTTP header had a content length? */
732 wsi->u.http.content_length = 0;
733 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) ||
734 lws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI) ||
735 lws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI))
736 wsi->u.http.content_length = 100 * 1024 * 1024;
738 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
739 lws_hdr_copy(wsi, content_length_str,
740 sizeof(content_length_str) - 1,
741 WSI_TOKEN_HTTP_CONTENT_LENGTH);
742 wsi->u.http.content_length = atoi(content_length_str);
745 if (wsi->http2_substream) {
746 wsi->u.http.request_version = HTTP_VERSION_2;
748 /* http_version? Default to 1.0, override with token: */
749 request_version = HTTP_VERSION_1_0;
751 /* Works for single digit HTTP versions. : */
752 http_version_len = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP);
753 if (http_version_len > 7) {
754 lws_hdr_copy(wsi, http_version_str,
755 sizeof(http_version_str) - 1, WSI_TOKEN_HTTP);
756 if (http_version_str[5] == '1' && http_version_str[7] == '1')
757 request_version = HTTP_VERSION_1_1;
759 wsi->u.http.request_version = request_version;
761 /* HTTP/1.1 defaults to "keep-alive", 1.0 to "close" */
762 if (request_version == HTTP_VERSION_1_1)
763 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
765 connection_type = HTTP_CONNECTION_CLOSE;
767 /* Override default if http "Connection:" header: */
768 if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) {
769 lws_hdr_copy(wsi, http_conn_str, sizeof(http_conn_str) - 1,
770 WSI_TOKEN_CONNECTION);
771 http_conn_str[sizeof(http_conn_str) - 1] = '\0';
772 if (!strcasecmp(http_conn_str, "keep-alive"))
773 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
775 if (!strcasecmp(http_conn_str, "close"))
776 connection_type = HTTP_CONNECTION_CLOSE;
778 wsi->u.http.connection_type = connection_type;
781 n = wsi->protocol->callback(wsi, LWS_CALLBACK_FILTER_HTTP_CONNECTION,
782 wsi->user_space, uri_ptr, uri_len);
784 lwsl_info("LWS_CALLBACK_HTTP closing\n");
789 * if there is content supposed to be coming,
790 * put a timeout on it having arrived
792 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
793 wsi->context->timeout_secs);
794 #ifdef LWS_OPENSSL_SUPPORT
795 if (wsi->redirect_to_https) {
797 * we accepted http:// only so we could redirect to
798 * https://, so issue the redirect. Create the redirection
799 * URI from the host: header and ignore the path part
801 unsigned char *start = pt->serv_buf + LWS_PRE, *p = start,
804 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
807 n = sprintf((char *)end, "https://%s/",
808 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
810 n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
815 return lws_http_transaction_completed(wsi);
819 #ifdef LWS_WITH_ACCESS_LOG
821 * Produce Apache-compatible log string for wsi, like this:
823 * 2.31.234.19 - - [27/Mar/2016:03:22:44 +0800]
824 * "GET /aep-screen.png HTTP/1.1"
825 * 200 152987 "https://libwebsockets.org/index.html"
826 * "Mozilla/5.0 (Macint... Chrome/49.0.2623.87 Safari/537.36"
830 static const char * const hver[] = {
831 "http/1.0", "http/1.1", "http/2"
834 char ads[INET6_ADDRSTRLEN];
836 char ads[INET_ADDRSTRLEN];
841 time_t t = time(NULL);
844 if (wsi->access_log_pending)
847 wsi->access_log.header_log = lws_malloc(l);
848 if (wsi->access_log.header_log) {
852 strftime(da, sizeof(da), "%d/%b/%Y:%H:%M:%S %z", tmp);
854 strcpy(da, "01/Jan/1970:00:00:00 +0000");
856 pa = lws_get_peer_simple(wsi, ads, sizeof(ads));
861 me = method_names[meth];
865 lws_snprintf(wsi->access_log.header_log, l,
866 "%s - - [%s] \"%s %s %s\"",
868 hver[wsi->u.http.request_version]);
870 l = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT);
872 wsi->access_log.user_agent = lws_malloc(l + 2);
873 if (wsi->access_log.user_agent)
874 lws_hdr_copy(wsi, wsi->access_log.user_agent,
875 l + 1, WSI_TOKEN_HTTP_USER_AGENT);
877 lwsl_err("OOM getting user agent\n");
879 wsi->access_log_pending = 1;
884 /* can we serve it from the mount list? */
886 hit = lws_find_mount(wsi, uri_ptr, uri_len);
888 /* deferred cleanup and reset to protocols[0] */
890 lwsl_info("no hit\n");
892 if (lws_bind_protocol(wsi, &wsi->vhost->protocols[0]))
895 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
896 wsi->user_space, uri_ptr, uri_len);
901 s = uri_ptr + hit->mountpoint_len;
904 * if we have a mountpoint like https://xxx.com/yyy
905 * there is an implied / at the end for our purposes since
906 * we can only mount on a "directory".
908 * But if we just go with that, the browser cannot understand
909 * that he is actually looking down one "directory level", so
910 * even though we give him /yyy/abc.html he acts like the
911 * current directory level is /. So relative urls like "x.png"
912 * wrongly look outside the mountpoint.
914 * Therefore if we didn't come in on a url with an explicit
915 * / at the end, we must redirect to add it so the browser
916 * understands he is one "directory level" down.
918 if ((hit->mountpoint_len > 1 ||
919 (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
920 hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&
922 (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
923 hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&
924 (hit->origin_protocol != LWSMPRO_CGI &&
925 hit->origin_protocol != LWSMPRO_CALLBACK //&&
926 //hit->protocol == NULL
928 unsigned char *start = pt->serv_buf + LWS_PRE,
929 *p = start, *end = p + 512;
931 lwsl_debug("Doing 301 '%s' org %s\n", s, hit->origin);
933 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
936 /* > at start indicates deal with by redirect */
937 if (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
938 hit->origin_protocol == LWSMPRO_REDIR_HTTPS)
939 n = lws_snprintf((char *)end, 256, "%s%s",
940 oprot[hit->origin_protocol & 1],
943 n = lws_snprintf((char *)end, 256,
944 "%s%s%s/", oprot[lws_is_ssl(wsi)],
945 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST),
948 n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
953 return lws_http_transaction_completed(wsi);
959 if (hit->basic_auth_login_file) {
960 char b64[160], plain[(sizeof(b64) * 3) / 4];
963 /* Did he send auth? */
964 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_AUTHORIZATION))
965 return lws_unauthorised_basic_auth(wsi);
967 n = HTTP_STATUS_FORBIDDEN;
969 m = lws_hdr_copy(wsi, b64, sizeof(b64), WSI_TOKEN_HTTP_AUTHORIZATION);
971 lwsl_err("b64 auth too long\n");
972 goto transaction_result_n;
976 if (strcasecmp(b64, "Basic")) {
977 lwsl_err("auth missing basic: %s\n", b64);
978 goto transaction_result_n;
981 /* It'll be like Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l */
983 m = lws_b64_decode_string(b64 + 6, plain, sizeof(plain));
985 lwsl_err("plain auth too long\n");
986 goto transaction_result_n;
989 // lwsl_notice(plain);
991 if (!lws_find_string_in_file(hit->basic_auth_login_file, plain, m)) {
992 lwsl_err("basic auth lookup failed\n");
993 return lws_unauthorised_basic_auth(wsi);
996 lwsl_notice("basic auth accepted\n");
998 /* accept the auth */
1003 * A particular protocol callback is mounted here?
1005 * For the duration of this http transaction, bind us to the
1006 * associated protocol
1008 if (hit->origin_protocol == LWSMPRO_CALLBACK || hit->protocol) {
1009 const struct lws_protocols *pp;
1010 const char *name = hit->origin;
1012 name = hit->protocol;
1014 pp = lws_vhost_name_to_protocol(wsi->vhost, name);
1017 lwsl_err("Unable to find plugin '%s'\n",
1022 if (lws_bind_protocol(wsi, pp))
1027 args.max_len = hit->auth_mask;
1028 args.final = 0; /* used to signal callback dealt with it */
1030 n = wsi->protocol->callback(wsi, LWS_CALLBACK_CHECK_ACCESS_RIGHTS,
1031 wsi->user_space, &args, 0);
1033 lws_return_http_status(wsi, HTTP_STATUS_UNAUTHORIZED,
1037 if (args.final) /* callback completely handled it well */
1040 if (hit->cgienv && wsi->protocol->callback(wsi,
1041 LWS_CALLBACK_HTTP_PMO,
1042 wsi->user_space, (void *)hit->cgienv, 0))
1045 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) {
1046 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
1048 uri_ptr + hit->mountpoint_len,
1049 uri_len - hit->mountpoint_len);
1055 /* did we hit something with a cgi:// origin? */
1056 if (hit->origin_protocol == LWSMPRO_CGI) {
1057 const char *cmd[] = {
1058 NULL, /* replace with cgi path */
1061 unsigned char *p, *end, buffer[1024];
1063 lwsl_debug("%s: cgi\n", __func__);
1064 cmd[0] = hit->origin;
1067 if (hit->cgi_timeout)
1068 n = hit->cgi_timeout;
1070 n = lws_cgi(wsi, cmd, hit->mountpoint_len, n,
1073 lwsl_err("%s: cgi failed\n", __func__);
1076 p = buffer + LWS_PRE;
1077 end = p + sizeof(buffer) - LWS_PRE;
1079 if (lws_add_http_header_status(wsi, HTTP_STATUS_OK, &p, end))
1081 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
1082 (unsigned char *)"close", 5, &p, end))
1084 n = lws_write(wsi, buffer + LWS_PRE,
1085 p - (buffer + LWS_PRE),
1086 LWS_WRITE_HTTP_HEADERS);
1093 if (s[0] == '\0' || (n == 1 && s[n - 1] == '/'))
1094 s = (char *)hit->def;
1098 wsi->cache_secs = hit->cache_max_age;
1099 wsi->cache_reuse = hit->cache_reusable;
1100 wsi->cache_revalidate = hit->cache_revalidate;
1101 wsi->cache_intermediaries = hit->cache_intermediaries;
1103 n = lws_http_serve(wsi, s, hit->origin, hit);
1106 * lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
1108 if (hit->protocol) {
1109 const struct lws_protocols *pp = lws_vhost_name_to_protocol(
1110 wsi->vhost, hit->protocol);
1112 if (lws_bind_protocol(wsi, pp))
1115 n = pp->callback(wsi, LWS_CALLBACK_HTTP,
1117 uri_ptr + hit->mountpoint_len,
1118 uri_len - hit->mountpoint_len);
1120 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
1121 wsi->user_space, uri_ptr, uri_len);
1126 lwsl_info("LWS_CALLBACK_HTTP closing\n");
1135 * If we're not issuing a file, check for content_length or
1136 * HTTP keep-alive. No keep-alive header allocation for
1137 * ISSUING_FILE, as this uses HTTP/1.0.
1139 * In any case, return 0 and let lws_read decide how to
1140 * proceed based on state
1142 if (wsi->state != LWSS_HTTP_ISSUING_FILE)
1143 /* Prepare to read body if we have a content length: */
1144 if (wsi->u.http.content_length > 0)
1145 wsi->state = LWSS_HTTP_BODY;
1150 /* we're closing, losing some rx is OK */
1151 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1152 // lwsl_notice("%s: drop1\n", __func__);
1153 lws_header_table_detach(wsi, 1);
1157 transaction_result_n:
1158 lws_return_http_status(wsi, n, NULL);
1160 return lws_http_transaction_completed(wsi);
1166 lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len)
1168 int protocol_len, n = 0, hit, non_space_char_found = 0, m;
1169 struct lws_context *context = lws_get_context(wsi);
1170 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1171 struct _lws_header_related hdr;
1172 struct allocated_headers *ah;
1173 unsigned char *obuf = *buf;
1174 char protocol_list[128];
1175 char protocol_name[64];
1179 if (len >= 10000000) {
1180 lwsl_err("%s: assert: len %ld\n", __func__, (long)len);
1184 if (!wsi->u.hdr.ah) {
1185 lwsl_err("%s: assert: NULL ah\n", __func__);
1190 wsi->more_rx_waiting = !!len;
1192 if (wsi->mode != LWSCM_HTTP_SERVING &&
1193 wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED) {
1194 lwsl_err("%s: bad wsi mode %d\n", __func__, wsi->mode);
1198 m = lws_parse(wsi, *(*buf)++);
1202 * we are transitioning from http with
1203 * an AH, to raw. Drop the ah and set
1207 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1208 lws_bind_protocol(wsi, &wsi->vhost->protocols[
1210 raw_protocol_index]);
1211 lwsl_info("transition to raw vh %s prot %d\n",
1213 wsi->vhost->raw_protocol_index);
1214 if ((wsi->protocol->callback)(wsi,
1215 LWS_CALLBACK_RAW_ADOPT,
1216 wsi->user_space, NULL, 0))
1219 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1220 lws_union_transition(wsi, LWSCM_RAW);
1221 lws_header_table_detach(wsi, 1);
1223 if (m == 2 && (wsi->protocol->callback)(wsi,
1224 LWS_CALLBACK_RAW_RX,
1225 wsi->user_space, obuf, olen))
1230 lwsl_info("lws_parse failed\n");
1234 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
1237 lwsl_parser("%s: lws_parse sees parsing complete\n", __func__);
1238 lwsl_debug("%s: wsi->more_rx_waiting=%d\n", __func__,
1239 wsi->more_rx_waiting);
1241 /* check for unwelcome guests */
1243 if (wsi->context->reject_service_keywords) {
1244 const struct lws_protocol_vhost_options *rej =
1245 wsi->context->reject_service_keywords;
1246 char ua[384], *msg = NULL;
1248 if (lws_hdr_copy(wsi, ua, sizeof(ua) - 1,
1249 WSI_TOKEN_HTTP_USER_AGENT) > 0) {
1250 ua[sizeof(ua) - 1] = '\0';
1252 if (strstr(ua, rej->name)) {
1253 msg = strchr(rej->value, ' ');
1256 lws_return_http_status(wsi, atoi(rej->value), msg);
1258 wsi->vhost->conn_stats.rejected++;
1269 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
1270 struct lws_vhost *vhost = lws_select_vhost(
1271 context, wsi->vhost->listen_port,
1272 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
1277 lwsl_info("no host\n");
1279 wsi->vhost->conn_stats.trans++;
1280 if (!wsi->conn_stat_done) {
1281 wsi->vhost->conn_stats.conn++;
1282 wsi->conn_stat_done = 1;
1285 if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECT)) {
1286 lwsl_info("Changing to RAW mode\n");
1288 goto raw_transition;
1291 wsi->mode = LWSCM_PRE_WS_SERVING_ACCEPT;
1292 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1294 /* is this websocket protocol or normal http 1.0? */
1296 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
1297 if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
1299 wsi->vhost->conn_stats.ws_upg++;
1300 lwsl_info("Upgrade to ws\n");
1303 #ifdef LWS_USE_HTTP2
1304 if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
1306 wsi->vhost->conn_stats.http2_upg++;
1307 lwsl_info("Upgrade to h2c\n");
1311 lwsl_info("Unknown upgrade\n");
1312 /* dunno what he wanted to upgrade to */
1316 /* no upgrade ack... he remained as HTTP */
1318 lwsl_info("No upgrade\n");
1321 lws_union_transition(wsi, LWSCM_HTTP_SERVING_ACCEPTED);
1322 wsi->state = LWSS_HTTP;
1323 wsi->u.http.fop_fd = NULL;
1325 /* expose it at the same offset as u.hdr */
1326 wsi->u.http.ah = ah;
1327 lwsl_debug("%s: wsi %p: ah %p\n", __func__, (void *)wsi,
1328 (void *)wsi->u.hdr.ah);
1330 n = lws_http_action(wsi);
1334 #ifdef LWS_USE_HTTP2
1336 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) {
1337 lwsl_info("missing http2_settings\n");
1341 lwsl_info("h2c upgrade...\n");
1343 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS);
1344 /* convert the peer's HTTP-Settings */
1345 n = lws_b64_decode_string(p, protocol_list,
1346 sizeof(protocol_list));
1348 lwsl_parser("HTTP2_SETTINGS too long\n");
1352 /* adopt the header info */
1356 lws_union_transition(wsi, LWSCM_HTTP2_SERVING);
1358 /* http2 union member has http union struct at start */
1359 wsi->u.http.ah = ah;
1361 lws_http2_init(&wsi->u.http2.peer_settings);
1362 lws_http2_init(&wsi->u.http2.my_settings);
1366 lws_http2_interpret_settings_payload(&wsi->u.http2.peer_settings,
1367 (unsigned char *)protocol_list, n);
1369 strcpy(protocol_list,
1370 "HTTP/1.1 101 Switching Protocols\x0d\x0a"
1371 "Connection: Upgrade\x0d\x0a"
1372 "Upgrade: h2c\x0d\x0a\x0d\x0a");
1373 n = lws_issue_raw(wsi, (unsigned char *)protocol_list,
1374 strlen(protocol_list));
1375 if (n != strlen(protocol_list)) {
1376 lwsl_debug("http2 switch: ERROR writing to socket\n");
1380 wsi->state = LWSS_HTTP2_AWAIT_CLIENT_PREFACE;
1387 lwsl_err("NULL protocol at lws_read\n");
1392 * Select the first protocol we support from the list
1393 * the client sent us.
1395 * Copy it to remove header fragmentation
1398 if (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1,
1399 WSI_TOKEN_PROTOCOL) < 0) {
1400 lwsl_err("protocol list too long");
1404 protocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
1405 protocol_list[protocol_len] = '\0';
1409 while (*p && !hit) {
1411 non_space_char_found = 0;
1412 while (n < sizeof(protocol_name) - 1 && *p &&
1414 // ignore leading spaces
1415 if (!non_space_char_found && *p == ' ') {
1419 non_space_char_found = 1;
1420 protocol_name[n++] = *p++;
1422 protocol_name[n] = '\0';
1426 lwsl_info("checking %s\n", protocol_name);
1429 while (wsi->vhost->protocols[n].callback) {
1430 lwsl_info("try %s\n", wsi->vhost->protocols[n].name);
1432 if (wsi->vhost->protocols[n].name &&
1433 !strcmp(wsi->vhost->protocols[n].name,
1435 wsi->protocol = &wsi->vhost->protocols[n];
1444 /* we didn't find a protocol he wanted? */
1447 if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL)) {
1448 lwsl_info("No protocol from \"%s\" supported\n",
1453 * some clients only have one protocol and
1454 * do not send the protocol list header...
1455 * allow it and match to the vhost's default
1456 * protocol (which itself defaults to zero)
1458 lwsl_info("defaulting to prot handler %d\n",
1459 wsi->vhost->default_protocol_index);
1461 wsi->protocol = &wsi->vhost->protocols[
1462 (int)wsi->vhost->default_protocol_index];
1465 /* allocate wsi->user storage */
1466 if (lws_ensure_user_space(wsi))
1470 * Give the user code a chance to study the request and
1471 * have the opportunity to deny it
1473 if ((wsi->protocol->callback)(wsi,
1474 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
1476 lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) {
1477 lwsl_warn("User code denied connection\n");
1482 * Perform the handshake according to the protocol version the
1486 switch (wsi->ietf_spec_revision) {
1488 lwsl_parser("lws_parse calling handshake_04\n");
1489 if (handshake_0405(context, wsi)) {
1490 lwsl_info("hs0405 has failed the connection\n");
1496 lwsl_info("Unknown client spec version %d\n",
1497 wsi->ietf_spec_revision);
1502 * stitch protocol choice into the vh protocol linked list
1503 * We always insert ourselves at the start of the list
1508 //lwsl_err("%s: pre insert vhost start wsi %p, that wsi prev == %p\n",
1510 // wsi->vhost->same_vh_protocol_list[n],
1511 // wsi->same_vh_protocol_prev);
1512 wsi->same_vh_protocol_prev = /* guy who points to us */
1513 &wsi->vhost->same_vh_protocol_list[n];
1514 wsi->same_vh_protocol_next = /* old first guy is our next */
1515 wsi->vhost->same_vh_protocol_list[n];
1516 /* we become the new first guy */
1517 wsi->vhost->same_vh_protocol_list[n] = wsi;
1519 if (wsi->same_vh_protocol_next)
1520 /* old first guy points back to us now */
1521 wsi->same_vh_protocol_next->same_vh_protocol_prev =
1522 &wsi->same_vh_protocol_next;
1526 /* we are upgrading to ws, so http/1.1 and keepalive +
1527 * pipelined header considerations about keeping the ah around
1528 * no longer apply. However it's common for the first ws
1529 * protocol data to have been coalesced with the browser
1530 * upgrade request and to already be in the ah rx buffer.
1533 lwsl_info("%s: %p: inheriting ah in ws mode (rxpos:%d, rxlen:%d)\n",
1534 __func__, wsi, wsi->u.hdr.ah->rxpos,
1535 wsi->u.hdr.ah->rxlen);
1539 lws_union_transition(wsi, LWSCM_WS_SERVING);
1541 * first service is WS mode will notice this, use the RX and
1542 * then detach the ah (caution: we are not in u.hdr union
1543 * mode any more then... ah_temp member is at start the same
1546 * Because rxpos/rxlen shows something in the ah, we will get
1547 * service guaranteed next time around the event loop
1549 * All union members begin with hdr, so we can use it even
1550 * though we transitioned to ws union mode (the ah detach
1551 * code uses it anyway).
1556 lws_restart_ws_ping_pong_timer(wsi);
1559 * create the frame buffer for this connection according to the
1560 * size mentioned in the protocol definition. If 0 there, use
1561 * a big default for compatibility
1564 n = wsi->protocol->rx_buffer_size;
1566 n = context->pt_serv_buf_size;
1568 wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
1569 if (!wsi->u.ws.rx_ubuf) {
1570 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
1573 wsi->u.ws.rx_ubuf_alloc = n;
1574 lwsl_debug("Allocating RX buffer %d\n", n);
1575 #if LWS_POSIX && !defined(LWS_WITH_ESP32)
1576 if (setsockopt(wsi->desc.sockfd, SOL_SOCKET, SO_SNDBUF,
1577 (const char *)&n, sizeof n)) {
1578 lwsl_warn("Failed to set SNDBUF to %d", n);
1583 lwsl_parser("accepted v%02d connection\n",
1584 wsi->ietf_spec_revision);
1586 /* notify user code that we're ready to roll */
1588 if (wsi->protocol->callback)
1589 if (wsi->protocol->callback(wsi, LWS_CALLBACK_ESTABLISHED,
1591 #ifdef LWS_OPENSSL_SUPPORT
1599 /* !!! drop ah unreservedly after ESTABLISHED */
1600 if (!wsi->more_rx_waiting) {
1601 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1603 //lwsl_notice("%p: dropping ah EST\n", wsi);
1604 lws_header_table_detach(wsi, 1);
1608 } /* while all chars are handled */
1613 /* drop the header info */
1614 /* we're closing, losing some rx is OK */
1615 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1616 //lwsl_notice("%s: drop2\n", __func__);
1617 lws_header_table_detach(wsi, 1);
1623 lws_get_idlest_tsi(struct lws_context *context)
1625 unsigned int lowest = ~0;
1626 int n = 0, hit = -1;
1628 for (; n < context->count_threads; n++) {
1629 if ((unsigned int)context->pt[n].fds_count !=
1630 context->fd_limit_per_thread - 1 &&
1631 (unsigned int)context->pt[n].fds_count < lowest) {
1632 lowest = context->pt[n].fds_count;
1641 lws_create_new_server_wsi(struct lws_vhost *vhost)
1643 struct lws *new_wsi;
1644 int n = lws_get_idlest_tsi(vhost->context);
1647 lwsl_err("no space for new conn\n");
1651 new_wsi = lws_zalloc(sizeof(struct lws));
1652 if (new_wsi == NULL) {
1653 lwsl_err("Out of memory for new connection\n");
1658 lwsl_debug("Accepted wsi %p to context %p, tsi %d\n", new_wsi,
1659 vhost->context, new_wsi->tsi);
1661 new_wsi->vhost = vhost;
1662 new_wsi->context = vhost->context;
1663 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1664 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1666 /* initialize the instance struct */
1668 new_wsi->state = LWSS_HTTP;
1669 new_wsi->mode = LWSCM_HTTP_SERVING;
1670 new_wsi->hdr_parsing_completed = 0;
1672 #ifdef LWS_OPENSSL_SUPPORT
1673 new_wsi->use_ssl = LWS_SSL_ENABLED(vhost);
1677 * these can only be set once the protocol is known
1678 * we set an unestablished connection's protocol pointer
1679 * to the start of the supported list, so it can look
1680 * for matching ones during the handshake
1682 new_wsi->protocol = vhost->protocols;
1683 new_wsi->user_space = NULL;
1684 new_wsi->ietf_spec_revision = 0;
1685 new_wsi->desc.sockfd = LWS_SOCK_INVALID;
1686 vhost->context->count_wsi_allocated++;
1689 * outermost create notification for wsi
1690 * no user_space because no protocol selection
1692 vhost->protocols[0].callback(new_wsi, LWS_CALLBACK_WSI_CREATE,
1698 LWS_VISIBLE int LWS_WARN_UNUSED_RESULT
1699 lws_http_transaction_completed(struct lws *wsi)
1701 int n = NO_PENDING_TIMEOUT;
1703 lws_access_log(wsi);
1705 lwsl_info("%s: wsi %p\n", __func__, wsi);
1706 /* if we can't go back to accept new headers, drop the connection */
1707 if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
1708 lwsl_info("%s: %p: close connection\n", __func__, wsi);
1712 if (lws_bind_protocol(wsi, &wsi->vhost->protocols[0]))
1715 /* otherwise set ourselves up ready to go again */
1716 wsi->state = LWSS_HTTP;
1717 wsi->mode = LWSCM_HTTP_SERVING;
1718 wsi->u.http.content_length = 0;
1719 wsi->u.http.content_remain = 0;
1720 wsi->hdr_parsing_completed = 0;
1721 #ifdef LWS_WITH_ACCESS_LOG
1722 wsi->access_log.sent = 0;
1725 if (wsi->vhost->keepalive_timeout)
1726 n = PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE;
1727 lws_set_timeout(wsi, n, wsi->vhost->keepalive_timeout);
1730 * We already know we are on http1.1 / keepalive and the next thing
1731 * coming will be another header set.
1733 * If there is no pending rx and we still have the ah, drop it and
1734 * reacquire a new ah when the new headers start to arrive. (Otherwise
1735 * we needlessly hog an ah indefinitely.)
1737 * However if there is pending rx and we know from the keepalive state
1738 * that is already at least the start of another header set, simply
1739 * reset the existing header table and keep it.
1741 if (wsi->u.hdr.ah) {
1742 lwsl_info("%s: wsi->more_rx_waiting=%d\n", __func__,
1743 wsi->more_rx_waiting);
1745 if (!wsi->more_rx_waiting) {
1746 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1747 lws_header_table_detach(wsi, 1);
1748 #ifdef LWS_OPENSSL_SUPPORT
1750 * additionally... if we are hogging an SSL instance
1751 * with no pending pipelined headers (or ah now), and
1752 * SSL is scarce, drop this connection without waiting
1755 if (wsi->vhost->use_ssl &&
1756 wsi->context->simultaneous_ssl == wsi->context->simultaneous_ssl_restriction) {
1757 lwsl_info("%s: simultaneous_ssl_restriction and nothing pipelined\n", __func__);
1762 lws_header_table_reset(wsi, 1);
1765 /* If we're (re)starting on headers, need other implied init */
1766 wsi->u.hdr.ues = URIES_IDLE;
1768 lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
1773 /* if not a socket, it's a raw, non-ssl file descriptor */
1775 LWS_VISIBLE struct lws *
1776 lws_adopt_descriptor_vhost(struct lws_vhost *vh, lws_adoption_type type,
1777 lws_sock_file_fd_type fd, const char *vh_prot_name,
1780 struct lws_context *context = vh->context;
1781 struct lws *new_wsi = lws_create_new_server_wsi(vh);
1785 if (type & LWS_ADOPT_SOCKET)
1786 compatible_close(fd.sockfd);
1791 new_wsi->parent = parent;
1792 new_wsi->sibling_list = parent->child_list;
1793 parent->child_list = new_wsi;
1799 new_wsi->protocol = lws_vhost_name_to_protocol(new_wsi->vhost,
1801 if (!new_wsi->protocol) {
1802 lwsl_err("Protocol %s not enabled on vhost %s\n",
1803 vh_prot_name, new_wsi->vhost->name);
1806 if (lws_ensure_user_space(new_wsi))
1809 new_wsi->protocol = &context->vhost_list->
1810 protocols[vh->default_protocol_index];
1812 if (type & LWS_ADOPT_SOCKET) { /* socket desc */
1813 lwsl_debug("%s: new wsi %p, sockfd %d\n", __func__, new_wsi,
1814 (int)(size_t)fd.sockfd);
1816 /* the transport is accepted... give him time to negotiate */
1817 lws_set_timeout(new_wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
1818 context->timeout_secs);
1821 #if defined(LWS_WITH_ESP8266)
1822 esp8266_tcp_stream_accept(accept_fd, new_wsi);
1825 } else /* file desc */
1826 lwsl_debug("%s: new wsi %p, filefd %d\n", __func__, new_wsi,
1827 (int)(size_t)fd.filefd);
1830 * A new connection was accepted. Give the user a chance to
1831 * set properties of the newly created wsi. There's no protocol
1832 * selected yet so we issue this to the vhosts's default protocol,
1833 * itself by default protocols[0]
1835 n = LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED;
1836 if (!(type & LWS_ADOPT_HTTP)) {
1837 if (!(type & LWS_ADOPT_SOCKET))
1838 n = LWS_CALLBACK_RAW_ADOPT_FILE;
1840 n = LWS_CALLBACK_RAW_ADOPT;
1842 if ((new_wsi->protocol->callback)(
1843 new_wsi, n, NULL, NULL, 0)) {
1844 if (type & LWS_ADOPT_SOCKET) {
1845 /* force us off the timeout list by hand */
1846 lws_set_timeout(new_wsi, NO_PENDING_TIMEOUT, 0);
1847 compatible_close(new_wsi->desc.sockfd);
1852 if (!LWS_SSL_ENABLED(new_wsi->vhost) || !(type & LWS_ADOPT_ALLOW_SSL) ||
1853 !(type & LWS_ADOPT_SOCKET)) {
1855 if (!(type & LWS_ADOPT_HTTP)) {
1856 if (!(type & LWS_ADOPT_SOCKET))
1857 new_wsi->mode = LWSCM_RAW_FILEDESC;
1859 new_wsi->mode = LWSCM_RAW;
1863 if (!(type & LWS_ADOPT_HTTP))
1864 new_wsi->mode = LWSCM_SSL_INIT_RAW;
1866 new_wsi->mode = LWSCM_SSL_INIT;
1871 lws_libev_accept(new_wsi, new_wsi->desc);
1872 lws_libuv_accept(new_wsi, new_wsi->desc);
1873 lws_libevent_accept(new_wsi, new_wsi->desc);
1876 if (insert_wsi_socket_into_fds(context, new_wsi)) {
1877 lwsl_err("%s: fail inserting socket\n", __func__);
1881 if (lws_server_socket_service_ssl(new_wsi, fd.sockfd)) {
1882 lwsl_err("%s: fail ssl negotiation\n", __func__);
1886 if (type & LWS_ADOPT_HTTP)
1887 if (!lws_header_table_attach(new_wsi, 0))
1888 lwsl_debug("Attached ah immediately\n");
1893 if (type & LWS_ADOPT_SOCKET)
1894 lws_close_free_wsi(new_wsi, LWS_CLOSE_STATUS_NOSTATUS);
1900 parent->child_list = new_wsi->sibling_list;
1901 if (new_wsi->user_space)
1902 lws_free(new_wsi->user_space);
1908 LWS_VISIBLE struct lws *
1909 lws_adopt_socket_vhost(struct lws_vhost *vh, lws_sockfd_type accept_fd)
1911 lws_sock_file_fd_type fd;
1913 fd.sockfd = accept_fd;
1914 return lws_adopt_descriptor_vhost(vh, LWS_ADOPT_SOCKET |
1915 LWS_ADOPT_HTTP | LWS_ADOPT_ALLOW_SSL, fd, NULL, NULL);
1918 LWS_VISIBLE struct lws *
1919 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd)
1921 return lws_adopt_socket_vhost(context->vhost_list, accept_fd);
1924 /* Common read-buffer adoption for lws_adopt_*_readbuf */
1926 adopt_socket_readbuf(struct lws *wsi, const char *readbuf, size_t len)
1928 struct lws_context_per_thread *pt;
1929 struct allocated_headers *ah;
1930 struct lws_pollfd *pfd;
1935 if (!readbuf || len == 0)
1938 if (len > sizeof(ah->rx)) {
1939 lwsl_err("%s: rx in too big\n", __func__);
1944 * we can't process the initial read data until we can attach an ah.
1946 * if one is available, get it and place the data in his ah rxbuf...
1947 * wsi with ah that have pending rxbuf get auto-POLLIN service.
1949 * no autoservice because we didn't get a chance to attach the
1950 * readbuf data to wsi or ah yet, and we will do it next if we get
1953 if (wsi->u.hdr.ah || !lws_header_table_attach(wsi, 0)) {
1955 memcpy(ah->rx, readbuf, len);
1959 lwsl_notice("%s: calling service on readbuf ah\n", __func__);
1960 pt = &wsi->context->pt[(int)wsi->tsi];
1962 /* unlike a normal connect, we have the headers already
1963 * (or the first part of them anyway).
1964 * libuv won't come back and service us without a network
1965 * event, so we need to do the header service right here.
1967 pfd = &pt->fds[wsi->position_in_fds_table];
1968 pfd->revents |= LWS_POLLIN;
1969 lwsl_err("%s: calling service\n", __func__);
1970 if (lws_service_fd_tsi(wsi->context, pfd, wsi->tsi))
1971 /* service closed us */
1976 lwsl_err("%s: deferring handling ah\n", __func__);
1978 * hum if no ah came, we are on the wait list and must defer
1979 * dealing with this until the ah arrives.
1981 * later successful lws_header_table_attach() will apply the
1982 * below to the rx buffer (via lws_header_table_reset()).
1984 wsi->u.hdr.preamble_rx = lws_malloc(len);
1985 if (!wsi->u.hdr.preamble_rx) {
1989 memcpy(wsi->u.hdr.preamble_rx, readbuf, len);
1990 wsi->u.hdr.preamble_rx_len = len;
1995 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
2000 LWS_VISIBLE struct lws *
2001 lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
2002 const char *readbuf, size_t len)
2004 return adopt_socket_readbuf(lws_adopt_socket(context, accept_fd), readbuf, len);
2007 LWS_VISIBLE struct lws *
2008 lws_adopt_socket_vhost_readbuf(struct lws_vhost *vhost, lws_sockfd_type accept_fd,
2009 const char *readbuf, size_t len)
2011 return adopt_socket_readbuf(lws_adopt_socket_vhost(vhost, accept_fd), readbuf, len);
2015 lws_server_socket_service(struct lws_context *context, struct lws *wsi,
2016 struct lws_pollfd *pollfd)
2018 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
2019 lws_sockfd_type accept_fd = LWS_SOCK_INVALID;
2020 struct allocated_headers *ah;
2022 struct sockaddr_in cli_addr;
2027 // lwsl_notice("%s: mode %d\n", __func__, wsi->mode);
2029 switch (wsi->mode) {
2031 case LWSCM_HTTP_SERVING:
2032 case LWSCM_HTTP_SERVING_ACCEPTED:
2033 case LWSCM_HTTP2_SERVING:
2036 /* handle http headers coming in */
2038 /* pending truncated sends have uber priority */
2040 if (wsi->trunc_len) {
2041 if (!(pollfd->revents & LWS_POLLOUT))
2044 if (lws_issue_raw(wsi, wsi->trunc_alloc +
2046 wsi->trunc_len) < 0)
2049 * we can't afford to allow input processing to send
2050 * something new, so spin around he event loop until
2051 * he doesn't have any partials
2056 /* any incoming data ready? */
2058 if (!(pollfd->revents & pollfd->events & LWS_POLLIN))
2062 * If we previously just did POLLIN when IN and OUT were
2063 * signalled (because POLLIN processing may have used up
2064 * the POLLOUT), don't let that happen twice in a row...
2065 * next time we see the situation favour POLLOUT
2067 #if !defined(LWS_WITH_ESP8266)
2068 if (wsi->favoured_pollin &&
2069 (pollfd->revents & pollfd->events & LWS_POLLOUT)) {
2070 wsi->favoured_pollin = 0;
2075 /* these states imply we MUST have an ah attached */
2077 if (wsi->mode != LWSCM_RAW && (wsi->state == LWSS_HTTP ||
2078 wsi->state == LWSS_HTTP_ISSUING_FILE ||
2079 wsi->state == LWSS_HTTP_HEADERS)) {
2080 if (!wsi->u.hdr.ah) {
2082 //lwsl_err("wsi %p: missing ah\n", wsi);
2083 /* no autoservice beacuse we will do it next */
2084 if (lws_header_table_attach(wsi, 0)) {
2085 lwsl_info("wsi %p: failed to acquire ah\n", wsi);
2091 //lwsl_notice("%s: %p: rxpos:%d rxlen:%d\n", __func__, wsi,
2092 // ah->rxpos, ah->rxlen);
2094 /* if nothing in ah rx buffer, get some fresh rx */
2095 if (ah->rxpos == ah->rxlen) {
2096 ah->rxlen = lws_ssl_capable_read(wsi, ah->rx,
2099 //lwsl_notice("%s: wsi %p, ah->rxlen = %d\r\n",
2100 // __func__, wsi, ah->rxlen);
2101 switch (ah->rxlen) {
2103 lwsl_info("%s: read 0 len\n", __func__);
2104 /* lwsl_info(" state=%d\n", wsi->state); */
2105 // if (!wsi->hdr_parsing_completed)
2106 // lws_header_table_detach(wsi);
2108 case LWS_SSL_CAPABLE_ERROR:
2110 case LWS_SSL_CAPABLE_MORE_SERVICE:
2111 ah->rxlen = ah->rxpos = 0;
2116 if (!(ah->rxpos != ah->rxlen && ah->rxlen)) {
2117 lwsl_err("%s: assert: rxpos %d, rxlen %d\n",
2118 __func__, ah->rxpos, ah->rxlen);
2123 /* just ignore incoming if waiting for close */
2124 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
2125 n = lws_read(wsi, ah->rx + ah->rxpos,
2126 ah->rxlen - ah->rxpos);
2127 if (n < 0) /* we closed wsi */
2129 if (wsi->u.hdr.ah) {
2130 if ( wsi->u.hdr.ah->rxlen)
2131 wsi->u.hdr.ah->rxpos += n;
2133 lwsl_debug("%s: wsi %p: ah read rxpos %d, rxlen %d\n", __func__, wsi, wsi->u.hdr.ah->rxpos, wsi->u.hdr.ah->rxlen);
2135 if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen &&
2136 (wsi->mode != LWSCM_HTTP_SERVING &&
2137 wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED &&
2138 wsi->mode != LWSCM_HTTP2_SERVING))
2139 lws_header_table_detach(wsi, 1);
2147 len = lws_ssl_capable_read(wsi, pt->serv_buf,
2148 context->pt_serv_buf_size);
2149 lwsl_debug("%s: wsi %p read %d\r\n", __func__, wsi, len);
2152 lwsl_info("%s: read 0 len\n", __func__);
2153 /* lwsl_info(" state=%d\n", wsi->state); */
2154 // if (!wsi->hdr_parsing_completed)
2155 // lws_header_table_detach(wsi);
2157 case LWS_SSL_CAPABLE_ERROR:
2159 case LWS_SSL_CAPABLE_MORE_SERVICE:
2163 if (wsi->mode == LWSCM_RAW) {
2164 n = user_callback_handle_rxflow(wsi->protocol->callback,
2165 wsi, LWS_CALLBACK_RAW_RX,
2166 wsi->user_space, pt->serv_buf, len);
2168 lwsl_info("LWS_CALLBACK_RAW_RX_fail\n");
2174 /* just ignore incoming if waiting for close */
2175 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
2177 * this may want to send
2178 * (via HTTP callback for example)
2180 n = lws_read(wsi, pt->serv_buf, len);
2181 if (n < 0) /* we closed wsi */
2184 * he may have used up the
2185 * writability above, if we will defer POLLOUT
2186 * processing in favour of POLLIN, note it
2188 if (pollfd->revents & LWS_POLLOUT)
2189 wsi->favoured_pollin = 1;
2195 /* this handles POLLOUT for http serving fragments */
2197 if (!(pollfd->revents & LWS_POLLOUT))
2201 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
2202 lwsl_notice("%s a\n", __func__);
2206 if (wsi->mode == LWSCM_RAW) {
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) {
2221 n = user_callback_handle_rxflow(wsi->protocol->callback,
2222 wsi, LWS_CALLBACK_HTTP_WRITEABLE,
2223 wsi->user_space, NULL, 0);
2225 lwsl_info("writeable_fail\n");
2231 /* >0 == completion, <0 == error */
2232 n = lws_serve_http_file_fragment(wsi);
2233 if (n < 0 || (n > 0 && lws_http_transaction_completed(wsi))) {
2234 lwsl_info("completed\n");
2240 case LWSCM_SERVER_LISTENER:
2243 /* pollin means a client has connected to us then */
2246 if (!(pollfd->revents & LWS_POLLIN) || !(pollfd->events & LWS_POLLIN))
2249 #ifdef LWS_OPENSSL_SUPPORT
2251 * can we really accept it, with regards to SSL limit?
2252 * another vhost may also have had POLLIN on his listener this
2253 * round and used it up already
2256 if (wsi->vhost->use_ssl &&
2257 context->simultaneous_ssl == context->simultaneous_ssl_restriction)
2258 /* no... ignore it, he won't come again until we are
2259 * below the simultaneous_ssl_restriction limit and
2260 * POLLIN is enabled on him again
2264 /* listen socket got an unencrypted connection... */
2266 clilen = sizeof(cli_addr);
2267 lws_latency_pre(context, wsi);
2268 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
2270 lws_latency(context, wsi, "listener accept", accept_fd,
2272 if (accept_fd < 0) {
2273 if (LWS_ERRNO == LWS_EAGAIN ||
2274 LWS_ERRNO == LWS_EWOULDBLOCK) {
2275 // lwsl_err("accept asks to try again\n");
2278 lwsl_err("ERROR on accept: %s\n", strerror(LWS_ERRNO));
2282 lws_plat_set_socket_options(wsi->vhost, accept_fd);
2284 lwsl_debug("accepted new conn port %u on fd=%d\n",
2285 ntohs(cli_addr.sin_port), accept_fd);
2288 /* not very beautiful... */
2289 accept_fd = (lws_sockfd_type)pollfd;
2292 * look at who we connected to and give user code a chance
2293 * to reject based on client IP. There's no protocol selected
2294 * yet so we issue this to protocols[0]
2296 if ((wsi->vhost->protocols[0].callback)(wsi,
2297 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
2298 NULL, (void *)(long)accept_fd, 0)) {
2299 lwsl_debug("Callback denied network connection\n");
2300 compatible_close(accept_fd);
2304 if (!lws_adopt_socket_vhost(wsi->vhost, accept_fd))
2305 /* already closed cleanly as necessary */
2309 } while (pt->fds_count < context->fd_limit_per_thread - 1 &&
2310 lws_poll_listen_fd(&pt->fds[wsi->position_in_fds_table]) > 0);
2318 if (!lws_server_socket_service_ssl(wsi, accept_fd))
2322 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
2328 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
2329 const char *other_headers, int other_headers_len)
2331 static const char * const intermediates[] = { "private", "public" };
2332 struct lws_context *context = lws_get_context(wsi);
2333 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
2334 #if defined(LWS_WITH_RANGES)
2335 struct lws_range_parsing *rp = &wsi->u.http.range;
2337 char cache_control[50], *cc = "no-store";
2338 unsigned char *response = pt->serv_buf + LWS_PRE;
2339 unsigned char *p = response;
2340 unsigned char *end = p + context->pt_serv_buf_size - LWS_PRE;
2341 unsigned long computed_total_content_length;
2342 int ret = 0, cclen = 8, n = HTTP_STATUS_OK;
2343 lws_fop_flags_t fflags = LWS_O_RDONLY;
2344 #if defined(LWS_WITH_RANGES)
2347 const struct lws_plat_file_ops *fops;
2351 * We either call the platform fops .open with first arg platform fops,
2352 * or we call fops_zip .open with first arg platform fops, and fops_zip
2353 * open will decide whether to switch to fops_zip or stay with fops_def.
2355 * If wsi->u.http.fop_fd is already set, the caller already opened it
2357 if (!wsi->u.http.fop_fd) {
2358 fops = lws_vfs_select_fops(wsi->context->fops, file, &vpath);
2359 fflags |= lws_vfs_prepare_flags(wsi);
2360 wsi->u.http.fop_fd = fops->LWS_FOP_OPEN(wsi->context->fops,
2361 file, vpath, &fflags);
2362 if (!wsi->u.http.fop_fd) {
2363 lwsl_err("Unable to open '%s'\n", file);
2368 wsi->u.http.filelen = lws_vfs_get_length(wsi->u.http.fop_fd);
2369 computed_total_content_length = wsi->u.http.filelen;
2371 #if defined(LWS_WITH_RANGES)
2372 ranges = lws_ranges_init(wsi, rp, wsi->u.http.filelen);
2374 lwsl_debug("Range count %d\n", ranges);
2377 * 1 range -> 206 + Content-Type: normal; Content-Range;
2378 * more -> 206 + Content-Type: multipart/byteranges
2379 * Repeat the true Content-Type in each multipart header
2380 * along with Content-Range
2383 /* it means he expressed a range in Range:, but it was illegal */
2384 lws_return_http_status(wsi, HTTP_STATUS_REQ_RANGE_NOT_SATISFIABLE, NULL);
2385 if (lws_http_transaction_completed(wsi))
2386 return -1; /* <0 means just hang up */
2388 lws_vfs_file_close(&wsi->u.http.fop_fd);
2390 return 0; /* == 0 means we dealt with the transaction complete */
2393 n = HTTP_STATUS_PARTIAL_CONTENT;
2396 if (lws_add_http_header_status(wsi, n, &p, end))
2399 if ((wsi->u.http.fop_fd->flags & (LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP |
2400 LWS_FOP_FLAG_COMPR_IS_GZIP)) ==
2401 (LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP | LWS_FOP_FLAG_COMPR_IS_GZIP)) {
2402 if (lws_add_http_header_by_token(wsi,
2403 WSI_TOKEN_HTTP_CONTENT_ENCODING,
2404 (unsigned char *)"gzip", 4, &p, end))
2406 lwsl_info("file is being provided in gzip\n");
2409 #if defined(LWS_WITH_RANGES)
2410 if (ranges < 2 && content_type && content_type[0])
2411 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
2412 (unsigned char *)content_type,
2413 strlen(content_type), &p, end))
2416 if (ranges >= 2) { /* multipart byteranges */
2417 strncpy(wsi->u.http.multipart_content_type, content_type,
2418 sizeof(wsi->u.http.multipart_content_type) - 1);
2419 wsi->u.http.multipart_content_type[
2420 sizeof(wsi->u.http.multipart_content_type) - 1] = '\0';
2421 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
2422 (unsigned char *)"multipart/byteranges; boundary=_lws",
2427 * our overall content length has to include
2429 * - (n + 1) x "_lws\r\n"
2430 * - n x Content-Type: xxx/xxx\r\n
2431 * - n x Content-Range: bytes xxx-yyy/zzz\r\n
2433 * - the actual payloads (aggregated in rp->agg)
2435 * Precompute it for the main response header
2438 computed_total_content_length = (unsigned long)rp->agg +
2439 6 /* final _lws\r\n */;
2441 lws_ranges_reset(rp);
2442 while (lws_ranges_next(rp)) {
2443 n = lws_snprintf(cache_control, sizeof(cache_control),
2444 "bytes %llu-%llu/%llu",
2445 rp->start, rp->end, rp->extent);
2447 computed_total_content_length +=
2448 6 /* header _lws\r\n */ +
2449 14 + strlen(content_type) + 2 + /* Content-Type: xxx/xxx\r\n */
2450 15 + n + 2 + /* Content-Range: xxxx\r\n */
2454 lws_ranges_reset(rp);
2455 lws_ranges_next(rp);
2459 computed_total_content_length = (unsigned long)rp->agg;
2460 n = lws_snprintf(cache_control, sizeof(cache_control), "bytes %llu-%llu/%llu",
2461 rp->start, rp->end, rp->extent);
2463 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_RANGE,
2464 (unsigned char *)cache_control,
2469 wsi->u.http.range.inside = 0;
2471 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ACCEPT_RANGES,
2472 (unsigned char *)"bytes", 5, &p, end))
2476 if (!wsi->sending_chunked) {
2477 if (lws_add_http_header_content_length(wsi,
2478 computed_total_content_length,
2482 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_TRANSFER_ENCODING,
2483 (unsigned char *)"chunked",
2488 if (wsi->cache_secs && wsi->cache_reuse) {
2489 if (wsi->cache_revalidate) {
2491 cclen = sprintf(cache_control, "%s max-age: %u",
2492 intermediates[wsi->cache_intermediaries],
2500 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CACHE_CONTROL,
2501 (unsigned char *)cc, cclen, &p, end))
2504 if (wsi->u.http.connection_type == HTTP_CONNECTION_KEEP_ALIVE)
2505 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
2506 (unsigned char *)"keep-alive", 10, &p, end))
2509 if (other_headers) {
2510 if ((end - p) < other_headers_len)
2512 memcpy(p, other_headers, other_headers_len);
2513 p += other_headers_len;
2516 if (lws_finalize_http_header(wsi, &p, end))
2519 ret = lws_write(wsi, response, p - response, LWS_WRITE_HTTP_HEADERS);
2520 if (ret != (p - response)) {
2521 lwsl_err("_write returned %d from %ld\n", ret, (long)(p - response));
2525 wsi->u.http.filepos = 0;
2526 wsi->state = LWSS_HTTP_ISSUING_FILE;
2528 return lws_serve_http_file_fragment(wsi);
2532 lws_interpret_incoming_packet(struct lws *wsi, unsigned char **buf, size_t len)
2536 lwsl_parser("%s: received %d byte packet\n", __func__, (int)len);
2538 lwsl_hexdump(*buf, len);
2541 /* let the rx protocol state machine have as much as it needs */
2545 * we were accepting input but now we stopped doing so
2547 if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
2548 lws_rxflow_cache(wsi, *buf, 0, len);
2549 lwsl_parser("%s: cached %ld\n", __func__, (long)len);
2553 if (wsi->u.ws.rx_draining_ext) {
2554 // lwsl_notice("draining with 0\n");
2555 m = lws_rx_sm(wsi, 0);
2561 /* account for what we're using in rxflow buffer */
2562 if (wsi->rxflow_buffer)
2565 /* consume payload bytes efficiently */
2567 wsi->lws_rx_parse_state ==
2568 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED) {
2569 m = lws_payload_until_length_exhausted(wsi, buf, &len);
2570 if (wsi->rxflow_buffer)
2571 wsi->rxflow_pos += m;
2574 /* process the byte */
2575 m = lws_rx_sm(wsi, *(*buf)++);
2581 lwsl_parser("%s: exit with %d unused\n", __func__, (int)len);
2587 lws_server_get_canonical_hostname(struct lws_context *context,
2588 struct lws_context_creation_info *info)
2590 if (lws_check_opt(info->options, LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME))
2592 #if LWS_POSIX && !defined(LWS_WITH_ESP32)
2593 /* find canonical hostname */
2594 gethostname((char *)context->canonical_hostname,
2595 sizeof(context->canonical_hostname) - 1);
2597 lwsl_notice(" canonical_hostname = %s\n", context->canonical_hostname);
2603 #define LWS_MAX_ELEM_NAME 32
2605 enum urldecode_stateful {
2619 static const char * const mp_hdr[] = {
2620 "content-disposition: ",
2625 typedef int (*lws_urldecode_stateful_cb)(void *data,
2626 const char *name, char **buf, int len, int final);
2628 struct lws_urldecode_stateful {
2631 char name[LWS_MAX_ELEM_NAME];
2632 char temp[LWS_MAX_ELEM_NAME];
2633 char content_type[32];
2634 char content_disp[32];
2635 char content_disp_filename[256];
2636 char mime_boundary[128];
2643 unsigned int multipart_form_data:1;
2644 unsigned int inside_quote:1;
2645 unsigned int subname:1;
2646 unsigned int boundary_real_crlf:1;
2648 enum urldecode_stateful state;
2650 lws_urldecode_stateful_cb output;
2653 static struct lws_urldecode_stateful *
2654 lws_urldecode_s_create(struct lws *wsi, char *out, int out_len, void *data,
2655 lws_urldecode_stateful_cb output)
2657 struct lws_urldecode_stateful *s = lws_zalloc(sizeof(*s));
2665 s->out_len = out_len;
2674 if (lws_hdr_copy(wsi, buf, sizeof(buf), WSI_TOKEN_HTTP_CONTENT_TYPE) > 0) {
2675 /* multipart/form-data; boundary=----WebKitFormBoundarycc7YgAPEIHvgE9Bf */
2677 if (!strncmp(buf, "multipart/form-data", 19)) {
2678 s->multipart_form_data = 1;
2679 s->state = MT_LOOK_BOUND_IN;
2681 p = strstr(buf, "boundary=");
2684 s->mime_boundary[m++] = '\x0d';
2685 s->mime_boundary[m++] = '\x0a';
2686 s->mime_boundary[m++] = '-';
2687 s->mime_boundary[m++] = '-';
2688 while (m < sizeof(s->mime_boundary) - 1 &&
2690 s->mime_boundary[m++] = *p++;
2692 s->mime_boundary[m] = '\0';
2694 lwsl_notice("boundary '%s'\n", s->mime_boundary);
2703 lws_urldecode_s_process(struct lws_urldecode_stateful *s, const char *in, int len)
2706 char c, was_end = 0;
2709 if (s->pos == s->out_len - s->mp - 1) {
2710 if (s->output(s->data, s->name, &s->out, s->pos, 0))
2718 /* states for url arg style */
2721 s->inside_quote = 0;
2723 s->name[s->pos] = '\0';
2730 s->name[s->pos] = '\0';
2731 if (s->output(s->data, s->name, &s->out, s->pos, 1))
2738 if (s->pos >= sizeof(s->name) - 1) {
2739 lwsl_notice("Name too long\n");
2742 s->name[s->pos++] = *in++;
2751 s->out[s->pos] = '\0';
2752 if (s->output(s->data, s->name, &s->out, s->pos, 1))
2761 s->out[s->pos++] = ' ';
2764 s->out[s->pos++] = *in++;
2767 n = char_to_hex(*in);
2777 n = char_to_hex(*in);
2782 s->out[s->pos++] = s->sum | n;
2787 /* states for multipart / mime style */
2789 case MT_LOOK_BOUND_IN:
2791 if (*in == s->mime_boundary[s->mp] &&
2792 s->mime_boundary[s->mp]) {
2795 if (!s->mime_boundary[s->mp]) {
2797 s->state = MT_IGNORE1;
2799 if (s->pos || was_end)
2800 if (s->output(s->data, s->name,
2801 &s->out, s->pos, 1))
2806 s->content_disp[0] = '\0';
2808 s->content_disp_filename[0] = '\0';
2809 s->boundary_real_crlf = 1;
2815 if (!s->boundary_real_crlf)
2818 memcpy(s->out + s->pos, s->mime_boundary + n, s->mp - n);
2821 goto retry_as_first;
2824 s->out[s->pos++] = *in;
2832 if (c >= 'A' && c <= 'Z')
2834 for (n = 0; n < ARRAY_SIZE(mp_hdr); n++)
2835 if (c == mp_hdr[n][s->mp]) {
2849 if (mp_hdr[hit][s->mp])
2857 s->state = MT_LOOK_BOUND_IN;
2859 s->state += hit + 1;
2863 /* form-data; name="file"; filename="t.txt" */
2865 if (*in == '\x0d') {
2866 // lwsl_notice("disp: '%s', '%s', '%s'\n",
2867 // s->content_disp, s->name,
2868 // s->content_disp_filename);
2870 if (s->content_disp_filename[0])
2871 if (s->output(s->data, s->name,
2872 &s->out, s->pos, LWS_UFS_OPEN))
2874 s->state = MT_IGNORE2;
2885 s->inside_quote ^= 1;
2891 s->temp[s->mp] = '\0';
2896 if (s->mp < sizeof(s->temp) - 1 &&
2897 (*in != ' ' || s->inside_quote))
2898 s->temp[s->mp++] = *in;
2903 if (s->mp < sizeof(s->content_disp) - 1)
2904 s->content_disp[s->mp++] = *in;
2905 s->content_disp[s->mp] = '\0';
2909 if (!strcmp(s->temp, "name")) {
2910 if (s->mp < sizeof(s->name) - 1)
2911 s->name[s->mp++] = *in;
2912 s->name[s->mp] = '\0';
2916 if (!strcmp(s->temp, "filename")) {
2917 if (s->mp < sizeof(s->content_disp_filename) - 1)
2918 s->content_disp_filename[s->mp++] = *in;
2919 s->content_disp_filename[s->mp] = '\0';
2928 s->state = MT_IGNORE2;
2930 if (s->mp < sizeof(s->content_type) - 1)
2931 s->content_type[s->mp++] = *in;
2932 s->content_type[s->mp] = '\0';
2939 s->state = MT_IGNORE2;
2946 s->state = MT_HNAME;
2956 lws_urldecode_s_destroy(struct lws_urldecode_stateful *s)
2960 if (s->state != US_IDLE)
2964 if (s->output(s->data, s->name, &s->out, s->pos, 1))
2973 struct lws_urldecode_stateful *s;
2974 lws_spa_fileupload_cb opt_cb;
2975 const char * const *param_names;
2989 lws_urldecode_spa_lookup(struct lws_spa *spa,
2994 for (n = 0; n < spa->count_params; n++)
2995 if (!strcmp(spa->param_names[n], name))
3002 lws_urldecode_spa_cb(void *data, const char *name, char **buf, int len,
3005 struct lws_spa *spa =
3006 (struct lws_spa *)data;
3009 if (spa->s->content_disp_filename[0]) {
3011 n = spa->opt_cb(spa->opt_data, name,
3012 spa->s->content_disp_filename,
3020 n = lws_urldecode_spa_lookup(spa, name);
3022 if (n == -1 || !len) /* unrecognized */
3025 if (!spa->params[n])
3026 spa->params[n] = *buf;
3028 if ((*buf) + len >= spa->end) {
3029 lwsl_notice("%s: exceeded storage\n", __func__);
3033 spa->param_length[n] += len;
3035 /* move it on inside storage */
3039 spa->s->out_len -= len + 1;
3044 LWS_VISIBLE LWS_EXTERN struct lws_spa *
3045 lws_spa_create(struct lws *wsi, const char * const *param_names,
3046 int count_params, int max_storage,
3047 lws_spa_fileupload_cb opt_cb, void *opt_data)
3049 struct lws_spa *spa = lws_zalloc(sizeof(*spa));
3054 spa->param_names = param_names;
3055 spa->count_params = count_params;
3056 spa->max_storage = max_storage;
3057 spa->opt_cb = opt_cb;
3058 spa->opt_data = opt_data;
3060 spa->storage = lws_malloc(max_storage);
3063 spa->end = spa->storage + max_storage - 1;
3065 spa->params = lws_zalloc(sizeof(char *) * count_params);
3069 spa->s = lws_urldecode_s_create(wsi, spa->storage, max_storage, spa,
3070 lws_urldecode_spa_cb);
3074 spa->param_length = lws_zalloc(sizeof(int) * count_params);
3075 if (!spa->param_length)
3078 lwsl_info("%s: Created SPA %p\n", __func__, spa);
3083 lws_urldecode_s_destroy(spa->s);
3085 lws_free(spa->params);
3087 lws_free(spa->storage);
3094 LWS_VISIBLE LWS_EXTERN int
3095 lws_spa_process(struct lws_spa *ludspa, const char *in, int len)
3098 lwsl_err("%s: NULL spa\n", __func__);
3101 /* we reject any junk after the last part arrived and we finalized */
3102 if (ludspa->finalized)
3105 return lws_urldecode_s_process(ludspa->s, in, len);
3108 LWS_VISIBLE LWS_EXTERN int
3109 lws_spa_get_length(struct lws_spa *ludspa, int n)
3111 if (n >= ludspa->count_params)
3114 return ludspa->param_length[n];
3117 LWS_VISIBLE LWS_EXTERN const char *
3118 lws_spa_get_string(struct lws_spa *ludspa, int n)
3120 if (n >= ludspa->count_params)
3123 return ludspa->params[n];
3126 LWS_VISIBLE LWS_EXTERN int
3127 lws_spa_finalize(struct lws_spa *spa)
3130 lws_urldecode_s_destroy(spa->s);
3139 LWS_VISIBLE LWS_EXTERN int
3140 lws_spa_destroy(struct lws_spa *spa)
3144 lwsl_notice("%s: destroy spa %p\n", __func__, spa);
3147 lws_urldecode_s_destroy(spa->s);
3149 lwsl_debug("%s %p %p %p %p\n", __func__,
3156 lws_free(spa->param_length);
3157 lws_free(spa->params);
3158 lws_free(spa->storage);
3165 LWS_VISIBLE LWS_EXTERN int
3166 lws_spa_destroy(struct lws_spa *spa)
3170 lwsl_info("%s: destroy spa %p\n", __func__, spa);
3173 lws_urldecode_s_destroy(spa->s);
3175 lwsl_debug("%s\n", __func__);
3177 lws_free(spa->param_length);
3178 lws_free(spa->params);
3179 lws_free(spa->storage);
3185 LWS_VISIBLE LWS_EXTERN int
3186 lws_chunked_html_process(struct lws_process_html_args *args,
3187 struct lws_process_html_state *s)
3189 char *sp, buffer[32];
3193 /* do replacements */
3195 old_len = args->len;
3198 while (sp < args->p + old_len) {
3200 if (args->len + 7 >= args->max_len) {
3201 lwsl_err("Used up interpret padding\n");
3205 if ((!s->pos && *sp == '$') || s->pos) {
3206 int hits = 0, hit = 0;
3210 s->swallow[s->pos++] = *sp;
3211 if (s->pos == sizeof(s->swallow) - 1)
3213 for (n = 0; n < s->count_vars; n++)
3214 if (!strncmp(s->swallow, s->vars[n], s->pos)) {
3220 s->swallow[s->pos] = '\0';
3221 memcpy(s->start, s->swallow, s->pos);
3227 if (hits == 1 && s->pos == strlen(s->vars[hit])) {
3228 pc = s->replace(s->data, hit);
3232 s->swallow[s->pos] = '\0';
3234 memmove(s->start + n,
3236 old_len - (sp - args->p));
3237 old_len += (n - s->pos) + 1;
3239 memcpy(s->start, pc, n);
3253 /* no space left for final chunk trailer */
3254 if (args->final && args->len + 7 >= args->max_len)
3257 n = sprintf(buffer, "%X\x0d\x0a", args->len);
3260 memcpy(args->p, buffer, n);
3264 sp = args->p + args->len;
3274 sp = args->p + args->len;