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;
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->sock, 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->sock, 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 /* 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 * 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;
249 LWS_VISIBLE LWS_EXTERN const char *
250 lws_get_mimetype(const char *file, const struct lws_http_mount *m)
252 int n = strlen(file);
253 const struct lws_protocol_vhost_options *pvo = NULL;
256 pvo = m->extra_mimetypes;
261 if (!strcmp(&file[n - 4], ".ico"))
262 return "image/x-icon";
264 if (!strcmp(&file[n - 4], ".gif"))
267 if (!strcmp(&file[n - 3], ".js"))
268 return "text/javascript";
270 if (!strcmp(&file[n - 4], ".png"))
273 if (!strcmp(&file[n - 4], ".jpg"))
276 if (!strcmp(&file[n - 3], ".gz"))
277 return "application/gzip";
279 if (!strcmp(&file[n - 4], ".JPG"))
282 if (!strcmp(&file[n - 5], ".html"))
285 if (!strcmp(&file[n - 4], ".css"))
288 if (!strcmp(&file[n - 4], ".txt"))
291 if (!strcmp(&file[n - 4], ".svg"))
292 return "image/svg+xml";
294 if (!strcmp(&file[n - 4], ".ttf"))
295 return "application/x-font-ttf";
297 if (!strcmp(&file[n - 5], ".woff"))
298 return "application/font-woff";
300 if (!strcmp(&file[n - 4], ".xml"))
301 return "application/xml";
304 if (pvo->name[0] == '*') /* ie, match anything */
307 if (!strcmp(&file[n - strlen(pvo->name)], pvo->name))
317 lws_http_serve(struct lws *wsi, char *uri, const char *origin,
318 const struct lws_http_mount *m)
320 const struct lws_protocol_vhost_options *pvo = m->interpret;
321 struct lws_process_html_args args;
322 const char *mimetype;
323 #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP8266) && !defined(LWS_WITH_ESP32)
327 char path[256], sym[512];
328 unsigned char *p = (unsigned char *)sym + 32 + LWS_PRE, *start = p;
329 unsigned char *end = p + sizeof(sym) - 32 - LWS_PRE;
330 #if !defined(WIN32) && LWS_POSIX
335 lws_snprintf(path, sizeof(path) - 1, "%s/%s", origin, uri);
337 #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP8266) && !defined(LWS_WITH_ESP32)
341 if (stat(path, &st)) {
342 lwsl_info("unable to stat %s\n", path);
346 lwsl_debug(" %s mode %d\n", path, S_IFMT & st.st_mode);
347 #if !defined(WIN32) && LWS_POSIX
348 if ((S_IFMT & st.st_mode) == S_IFLNK) {
349 len = readlink(path, sym, sizeof(sym) - 1);
351 lwsl_err("Failed to read link %s\n", path);
355 lwsl_debug("symlink %s -> %s\n", path, sym);
356 lws_snprintf(path, sizeof(path) - 1, "%s", sym);
359 if ((S_IFMT & st.st_mode) == S_IFDIR) {
360 lwsl_debug("default filename append to dir\n");
361 lws_snprintf(path, sizeof(path) - 1, "%s/%s/index.html",
365 } while ((S_IFMT & st.st_mode) != S_IFREG && spin < 5);
368 lwsl_err("symlink loop %s \n", path);
370 n = sprintf(sym, "%08lX%08lX", (unsigned long)st.st_size,
371 (unsigned long)st.st_mtime);
373 /* disable ranges if IF_RANGE token invalid */
375 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_RANGE))
376 if (strcmp(sym, lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_IF_RANGE)))
377 /* differs - defeat Range: */
378 wsi->u.http.ah->frag_index[WSI_TOKEN_HTTP_RANGE] = 0;
380 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_NONE_MATCH)) {
382 * he thinks he has some version of it already,
383 * check if the tag matches
385 if (!strcmp(sym, lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_IF_NONE_MATCH))) {
387 lwsl_debug("%s: ETAG match %s %s\n", __func__,
390 /* we don't need to send the payload */
391 if (lws_add_http_header_status(wsi, 304, &p, end))
394 if (lws_add_http_header_by_token(wsi,
396 (unsigned char *)sym, n, &p, end))
399 if (lws_finalize_http_header(wsi, &p, end))
402 n = lws_write(wsi, start, p - start,
403 LWS_WRITE_HTTP_HEADERS);
404 if (n != (p - start)) {
405 lwsl_err("_write returned %d from %ld\n", n,
410 return lws_http_transaction_completed(wsi);
414 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ETAG,
415 (unsigned char *)sym, n, &p, end))
419 mimetype = lws_get_mimetype(path, m);
421 lwsl_err("unknown mimetype for %s\n", path);
425 lwsl_debug("sending no mimetype for %s\n", path);
427 wsi->sending_chunked = 0;
430 * check if this is in the list of file suffixes to be interpreted by
435 if (n > (int)strlen(pvo->name) &&
436 !strcmp(&path[n - strlen(pvo->name)], pvo->name)) {
437 wsi->sending_chunked = 1;
438 wsi->protocol_interpret_idx = (char)(long)pvo->value;
439 lwsl_info("want %s interpreted by %s\n", path,
440 wsi->vhost->protocols[(int)(long)(pvo->value)].name);
441 wsi->protocol = &wsi->vhost->protocols[(int)(long)(pvo->value)];
442 if (lws_ensure_user_space(wsi))
450 const struct lws_protocols *pp = lws_vhost_name_to_protocol(
451 wsi->vhost, m->protocol);
453 if (lws_bind_protocol(wsi, pp))
456 args.max_len = end - p;
457 if (pp->callback(wsi, LWS_CALLBACK_ADD_HEADERS,
458 wsi->user_space, &args, 0))
460 p = (unsigned char *)args.p;
463 n = lws_serve_http_file(wsi, path, mimetype, (char *)start, p - start);
465 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
466 return -1; /* error or can't reuse connection: close the socket */
474 const struct lws_http_mount *
475 lws_find_mount(struct lws *wsi, const char *uri_ptr, int uri_len)
477 const struct lws_http_mount *hm, *hit = NULL;
480 hm = wsi->vhost->mount_list;
482 if (uri_len >= hm->mountpoint_len &&
483 !strncmp(uri_ptr, hm->mountpoint, hm->mountpoint_len) &&
484 (uri_ptr[hm->mountpoint_len] == '\0' ||
485 uri_ptr[hm->mountpoint_len] == '/' ||
486 hm->mountpoint_len == 1)
488 if (hm->origin_protocol == LWSMPRO_CALLBACK ||
489 ((hm->origin_protocol == LWSMPRO_CGI ||
490 lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI) ||
492 hm->mountpoint_len > best)) {
493 best = hm->mountpoint_len;
506 lws_find_string_in_file(const char *filename, const char *string, int stringlen)
509 int fd, match = 0, pos = 0, n = 0, hit = 0;
511 fd = open(filename, O_RDONLY);
513 lwsl_err("can't open auth file: %s\n", filename);
519 n = read(fd, buf, sizeof(buf));
521 if (match == stringlen)
528 if (match == stringlen) {
529 if (buf[pos] == '\r' || buf[pos] == '\n') {
536 if (buf[pos] == string[match])
550 lws_unauthorised_basic_auth(struct lws *wsi)
552 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
553 unsigned char *start = pt->serv_buf + LWS_PRE,
554 *p = start, *end = p + 512;
558 /* no auth... tell him it is required */
560 if (lws_add_http_header_status(wsi, HTTP_STATUS_UNAUTHORIZED, &p, end))
563 n = lws_snprintf(buf, sizeof(buf), "Basic realm=\"lwsws\"");
564 if (lws_add_http_header_by_token(wsi,
565 WSI_TOKEN_HTTP_WWW_AUTHENTICATE,
566 (unsigned char *)buf, n, &p, end))
569 if (lws_finalize_http_header(wsi, &p, end))
572 n = lws_write(wsi, start, p - start, LWS_WRITE_HTTP_HEADERS);
576 return lws_http_transaction_completed(wsi);
583 lws_http_action(struct lws *wsi)
585 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
586 enum http_connection_type connection_type;
587 enum http_version request_version;
588 char content_length_str[32];
589 struct lws_process_html_args args;
590 const struct lws_http_mount *hit = NULL;
591 unsigned int n, count = 0;
592 char http_version_str[10];
593 char http_conn_str[20];
594 int http_version_len;
595 char *uri_ptr = NULL, *s;
599 static const unsigned char methods[] = {
602 WSI_TOKEN_OPTIONS_URI,
605 WSI_TOKEN_DELETE_URI,
608 WSI_TOKEN_HTTP_COLON_PATH,
611 #if defined(_DEBUG) || defined(LWS_WITH_ACCESS_LOG)
612 static const char * const method_names[] = {
613 "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE", "CONNECT",
619 static const char * const oprot[] = {
620 "http://", "https://"
623 /* it's not websocket.... shall we accept it as http? */
625 for (n = 0; n < ARRAY_SIZE(methods); n++)
626 if (lws_hdr_total_length(wsi, methods[n]))
629 lwsl_warn("Missing URI in HTTP request\n");
634 lwsl_warn("multiple methods?\n");
638 if (lws_ensure_user_space(wsi))
641 for (n = 0; n < ARRAY_SIZE(methods); n++)
642 if (lws_hdr_total_length(wsi, methods[n])) {
643 uri_ptr = lws_hdr_simple_ptr(wsi, methods[n]);
644 uri_len = lws_hdr_total_length(wsi, methods[n]);
645 lwsl_info("Method: %s request for '%s'\n",
646 method_names[n], uri_ptr);
653 /* we insist on absolute paths */
655 if (uri_ptr[0] != '/') {
656 lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
661 /* HTTP header had a content length? */
663 wsi->u.http.content_length = 0;
664 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) ||
665 lws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI) ||
666 lws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI))
667 wsi->u.http.content_length = 100 * 1024 * 1024;
669 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
670 lws_hdr_copy(wsi, content_length_str,
671 sizeof(content_length_str) - 1,
672 WSI_TOKEN_HTTP_CONTENT_LENGTH);
673 wsi->u.http.content_length = atoi(content_length_str);
676 if (wsi->http2_substream) {
677 wsi->u.http.request_version = HTTP_VERSION_2;
679 /* http_version? Default to 1.0, override with token: */
680 request_version = HTTP_VERSION_1_0;
682 /* Works for single digit HTTP versions. : */
683 http_version_len = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP);
684 if (http_version_len > 7) {
685 lws_hdr_copy(wsi, http_version_str,
686 sizeof(http_version_str) - 1, WSI_TOKEN_HTTP);
687 if (http_version_str[5] == '1' && http_version_str[7] == '1')
688 request_version = HTTP_VERSION_1_1;
690 wsi->u.http.request_version = request_version;
692 /* HTTP/1.1 defaults to "keep-alive", 1.0 to "close" */
693 if (request_version == HTTP_VERSION_1_1)
694 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
696 connection_type = HTTP_CONNECTION_CLOSE;
698 /* Override default if http "Connection:" header: */
699 if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) {
700 lws_hdr_copy(wsi, http_conn_str, sizeof(http_conn_str) - 1,
701 WSI_TOKEN_CONNECTION);
702 http_conn_str[sizeof(http_conn_str) - 1] = '\0';
703 if (!strcasecmp(http_conn_str, "keep-alive"))
704 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
706 if (!strcasecmp(http_conn_str, "close"))
707 connection_type = HTTP_CONNECTION_CLOSE;
709 wsi->u.http.connection_type = connection_type;
712 n = wsi->protocol->callback(wsi, LWS_CALLBACK_FILTER_HTTP_CONNECTION,
713 wsi->user_space, uri_ptr, uri_len);
715 lwsl_info("LWS_CALLBACK_HTTP closing\n");
720 * if there is content supposed to be coming,
721 * put a timeout on it having arrived
723 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
724 wsi->context->timeout_secs);
725 #ifdef LWS_OPENSSL_SUPPORT
726 if (wsi->redirect_to_https) {
728 * we accepted http:// only so we could redirect to
729 * https://, so issue the redirect. Create the redirection
730 * URI from the host: header and ignore the path part
732 unsigned char *start = pt->serv_buf + LWS_PRE, *p = start,
735 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
738 n = sprintf((char *)end, "https://%s/",
739 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
741 n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
746 return lws_http_transaction_completed(wsi);
750 #ifdef LWS_WITH_ACCESS_LOG
752 * Produce Apache-compatible log string for wsi, like this:
754 * 2.31.234.19 - - [27/Mar/2016:03:22:44 +0800]
755 * "GET /aep-screen.png HTTP/1.1"
756 * 200 152987 "https://libwebsockets.org/index.html"
757 * "Mozilla/5.0 (Macint... Chrome/49.0.2623.87 Safari/537.36"
761 static const char * const hver[] = {
762 "http/1.0", "http/1.1", "http/2"
765 char ads[INET6_ADDRSTRLEN];
767 char ads[INET_ADDRSTRLEN];
772 time_t t = time(NULL);
775 if (wsi->access_log_pending)
778 wsi->access_log.header_log = lws_malloc(l);
779 if (wsi->access_log.header_log) {
783 strftime(da, sizeof(da), "%d/%b/%Y:%H:%M:%S %z", tmp);
785 strcpy(da, "01/Jan/1970:00:00:00 +0000");
787 pa = lws_get_peer_simple(wsi, ads, sizeof(ads));
792 me = method_names[meth];
796 lws_snprintf(wsi->access_log.header_log, l,
797 "%s - - [%s] \"%s %s %s\"",
799 hver[wsi->u.http.request_version]);
801 l = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT);
803 wsi->access_log.user_agent = lws_malloc(l + 2);
804 if (wsi->access_log.user_agent)
805 lws_hdr_copy(wsi, wsi->access_log.user_agent,
806 l + 1, WSI_TOKEN_HTTP_USER_AGENT);
808 lwsl_err("OOM getting user agent\n");
810 wsi->access_log_pending = 1;
815 /* can we serve it from the mount list? */
817 hit = lws_find_mount(wsi, uri_ptr, uri_len);
819 /* deferred cleanup and reset to protocols[0] */
821 lwsl_info("no hit\n");
823 if (lws_bind_protocol(wsi, &wsi->vhost->protocols[0]))
826 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
827 wsi->user_space, uri_ptr, uri_len);
832 s = uri_ptr + hit->mountpoint_len;
835 * if we have a mountpoint like https://xxx.com/yyy
836 * there is an implied / at the end for our purposes since
837 * we can only mount on a "directory".
839 * But if we just go with that, the browser cannot understand
840 * that he is actually looking down one "directory level", so
841 * even though we give him /yyy/abc.html he acts like the
842 * current directory level is /. So relative urls like "x.png"
843 * wrongly look outside the mountpoint.
845 * Therefore if we didn't come in on a url with an explicit
846 * / at the end, we must redirect to add it so the browser
847 * understands he is one "directory level" down.
849 if ((hit->mountpoint_len > 1 ||
850 (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
851 hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&
853 (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
854 hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&
855 (hit->origin_protocol != LWSMPRO_CGI &&
856 hit->origin_protocol != LWSMPRO_CALLBACK //&&
857 //hit->protocol == NULL
859 unsigned char *start = pt->serv_buf + LWS_PRE,
860 *p = start, *end = p + 512;
862 lwsl_debug("Doing 301 '%s' org %s\n", s, hit->origin);
864 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
867 /* > at start indicates deal with by redirect */
868 if (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
869 hit->origin_protocol == LWSMPRO_REDIR_HTTPS)
870 n = lws_snprintf((char *)end, 256, "%s%s",
871 oprot[hit->origin_protocol & 1],
874 n = lws_snprintf((char *)end, 256,
875 "%s%s%s/", oprot[lws_is_ssl(wsi)],
876 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST),
879 n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
884 return lws_http_transaction_completed(wsi);
890 if (hit->basic_auth_login_file) {
891 char b64[160], plain[(sizeof(b64) * 3) / 4];
894 /* Did he send auth? */
895 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_AUTHORIZATION))
896 return lws_unauthorised_basic_auth(wsi);
898 n = HTTP_STATUS_FORBIDDEN;
900 m = lws_hdr_copy(wsi, b64, sizeof(b64), WSI_TOKEN_HTTP_AUTHORIZATION);
902 lwsl_err("b64 auth too long\n");
903 goto transaction_result_n;
907 if (strcasecmp(b64, "Basic")) {
908 lwsl_err("auth missing basic: %s\n", b64);
909 goto transaction_result_n;
912 /* It'll be like Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l */
914 m = lws_b64_decode_string(b64 + 6, plain, sizeof(plain));
916 lwsl_err("plain auth too long\n");
917 goto transaction_result_n;
920 // lwsl_notice(plain);
922 if (!lws_find_string_in_file(hit->basic_auth_login_file, plain, m)) {
923 lwsl_err("basic auth lookup failed\n");
924 return lws_unauthorised_basic_auth(wsi);
927 lwsl_notice("basic auth accepted\n");
929 /* accept the auth */
934 * A particular protocol callback is mounted here?
936 * For the duration of this http transaction, bind us to the
937 * associated protocol
939 if (hit->origin_protocol == LWSMPRO_CALLBACK || hit->protocol) {
940 const struct lws_protocols *pp;
941 const char *name = hit->origin;
943 name = hit->protocol;
945 pp = lws_vhost_name_to_protocol(wsi->vhost, name);
948 lwsl_err("Unable to find plugin '%s'\n",
953 if (lws_bind_protocol(wsi, pp))
958 args.max_len = hit->auth_mask;
959 args.final = 0; /* used to signal callback dealt with it */
961 n = wsi->protocol->callback(wsi, LWS_CALLBACK_CHECK_ACCESS_RIGHTS,
962 wsi->user_space, &args, 0);
964 lws_return_http_status(wsi, HTTP_STATUS_UNAUTHORIZED,
968 if (args.final) /* callback completely handled it well */
971 if (hit->cgienv && wsi->protocol->callback(wsi,
972 LWS_CALLBACK_HTTP_PMO,
973 wsi->user_space, (void *)hit->cgienv, 0))
976 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) {
977 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
979 uri_ptr + hit->mountpoint_len,
980 uri_len - hit->mountpoint_len);
986 /* did we hit something with a cgi:// origin? */
987 if (hit->origin_protocol == LWSMPRO_CGI) {
988 const char *cmd[] = {
989 NULL, /* replace with cgi path */
992 unsigned char *p, *end, buffer[1024];
994 lwsl_debug("%s: cgi\n", __func__);
995 cmd[0] = hit->origin;
998 if (hit->cgi_timeout)
999 n = hit->cgi_timeout;
1001 n = lws_cgi(wsi, cmd, hit->mountpoint_len, n,
1004 lwsl_err("%s: cgi failed\n", __func__);
1007 p = buffer + LWS_PRE;
1008 end = p + sizeof(buffer) - LWS_PRE;
1010 if (lws_add_http_header_status(wsi, 200, &p, end))
1012 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
1013 (unsigned char *)"close", 5, &p, end))
1015 n = lws_write(wsi, buffer + LWS_PRE,
1016 p - (buffer + LWS_PRE),
1017 LWS_WRITE_HTTP_HEADERS);
1024 if (s[0] == '\0' || (n == 1 && s[n - 1] == '/'))
1025 s = (char *)hit->def;
1029 wsi->cache_secs = hit->cache_max_age;
1030 wsi->cache_reuse = hit->cache_reusable;
1031 wsi->cache_revalidate = hit->cache_revalidate;
1032 wsi->cache_intermediaries = hit->cache_intermediaries;
1034 n = lws_http_serve(wsi, s, hit->origin, hit);
1037 * lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
1039 if (hit->protocol) {
1040 const struct lws_protocols *pp = lws_vhost_name_to_protocol(
1041 wsi->vhost, hit->protocol);
1043 if (lws_bind_protocol(wsi, pp))
1046 n = pp->callback(wsi, LWS_CALLBACK_HTTP,
1048 uri_ptr + hit->mountpoint_len,
1049 uri_len - hit->mountpoint_len);
1051 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
1052 wsi->user_space, uri_ptr, uri_len);
1057 lwsl_info("LWS_CALLBACK_HTTP closing\n");
1066 * If we're not issuing a file, check for content_length or
1067 * HTTP keep-alive. No keep-alive header allocation for
1068 * ISSUING_FILE, as this uses HTTP/1.0.
1070 * In any case, return 0 and let lws_read decide how to
1071 * proceed based on state
1073 if (wsi->state != LWSS_HTTP_ISSUING_FILE)
1074 /* Prepare to read body if we have a content length: */
1075 if (wsi->u.http.content_length > 0)
1076 wsi->state = LWSS_HTTP_BODY;
1081 /* we're closing, losing some rx is OK */
1082 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1083 // lwsl_notice("%s: drop1\n", __func__);
1084 lws_header_table_detach(wsi, 1);
1088 transaction_result_n:
1089 lws_return_http_status(wsi, n, NULL);
1091 return lws_http_transaction_completed(wsi);
1096 lws_bind_protocol(struct lws *wsi, const struct lws_protocols *p)
1098 // if (wsi->protocol == p)
1102 wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_DROP_PROTOCOL,
1103 wsi->user_space, NULL, 0);
1104 if (!wsi->user_space_externally_allocated)
1105 lws_free_set_NULL(wsi->user_space);
1111 if (lws_ensure_user_space(wsi))
1114 if (wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_BIND_PROTOCOL,
1115 wsi->user_space, NULL, 0))
1123 lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len)
1125 struct lws_context *context = lws_get_context(wsi);
1126 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1127 struct _lws_header_related hdr;
1128 struct allocated_headers *ah;
1129 int protocol_len, n = 0, hit, non_space_char_found = 0;
1130 char protocol_list[128];
1131 char protocol_name[64];
1134 if (len >= 10000000) {
1135 lwsl_err("%s: assert: len %ld\n", __func__, (long)len);
1139 if (!wsi->u.hdr.ah) {
1140 lwsl_err("%s: assert: NULL ah\n", __func__);
1145 wsi->more_rx_waiting = !!len;
1147 if (wsi->mode != LWSCM_HTTP_SERVING &&
1148 wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED) {
1149 lwsl_err("%s: bad wsi mode %d\n", __func__, wsi->mode);
1153 if (lws_parse(wsi, *(*buf)++)) {
1154 lwsl_info("lws_parse failed\n");
1158 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
1161 lwsl_parser("%s: lws_parse sees parsing complete\n", __func__);
1162 lwsl_debug("%s: wsi->more_rx_waiting=%d\n", __func__,
1163 wsi->more_rx_waiting);
1165 /* check for unwelcome guests */
1167 if (wsi->context->reject_service_keywords) {
1168 const struct lws_protocol_vhost_options *rej =
1169 wsi->context->reject_service_keywords;
1170 char ua[384], *msg = NULL;
1172 if (lws_hdr_copy(wsi, ua, sizeof(ua) - 1,
1173 WSI_TOKEN_HTTP_USER_AGENT) > 0) {
1174 ua[sizeof(ua) - 1] = '\0';
1176 if (strstr(ua, rej->name)) {
1177 msg = strchr(rej->value, ' ');
1180 lws_return_http_status(wsi, atoi(rej->value), msg);
1182 wsi->vhost->conn_stats.rejected++;
1193 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
1194 struct lws_vhost *vhost = lws_select_vhost(
1195 context, wsi->vhost->listen_port,
1196 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
1201 lwsl_info("no host\n");
1203 wsi->vhost->conn_stats.trans++;
1204 if (!wsi->conn_stat_done) {
1205 wsi->vhost->conn_stats.conn++;
1206 wsi->conn_stat_done = 1;
1209 if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECT)) {
1210 lwsl_info("Changing to RAW mode\n");
1211 lws_union_transition(wsi, LWSCM_RAW);
1212 if (!wsi->more_rx_waiting) {
1213 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1215 //lwsl_notice("%p: dropping ah EST\n", wsi);
1216 lws_header_table_detach(wsi, 1);
1220 wsi->mode = LWSCM_PRE_WS_SERVING_ACCEPT;
1221 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1223 /* is this websocket protocol or normal http 1.0? */
1225 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
1226 if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
1228 wsi->vhost->conn_stats.ws_upg++;
1229 lwsl_info("Upgrade to ws\n");
1232 #ifdef LWS_USE_HTTP2
1233 if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
1235 wsi->vhost->conn_stats.http2_upg++;
1236 lwsl_info("Upgrade to h2c\n");
1240 lwsl_info("Unknown upgrade\n");
1241 /* dunno what he wanted to upgrade to */
1245 /* no upgrade ack... he remained as HTTP */
1247 lwsl_info("No upgrade\n");
1250 lws_union_transition(wsi, LWSCM_HTTP_SERVING_ACCEPTED);
1251 wsi->state = LWSS_HTTP;
1252 wsi->u.http.fd = LWS_INVALID_FILE;
1254 /* expose it at the same offset as u.hdr */
1255 wsi->u.http.ah = ah;
1256 lwsl_debug("%s: wsi %p: ah %p\n", __func__, (void *)wsi,
1257 (void *)wsi->u.hdr.ah);
1259 n = lws_http_action(wsi);
1263 #ifdef LWS_USE_HTTP2
1265 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) {
1266 lwsl_info("missing http2_settings\n");
1270 lwsl_info("h2c upgrade...\n");
1272 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS);
1273 /* convert the peer's HTTP-Settings */
1274 n = lws_b64_decode_string(p, protocol_list,
1275 sizeof(protocol_list));
1277 lwsl_parser("HTTP2_SETTINGS too long\n");
1281 /* adopt the header info */
1285 lws_union_transition(wsi, LWSCM_HTTP2_SERVING);
1287 /* http2 union member has http union struct at start */
1288 wsi->u.http.ah = ah;
1290 lws_http2_init(&wsi->u.http2.peer_settings);
1291 lws_http2_init(&wsi->u.http2.my_settings);
1295 lws_http2_interpret_settings_payload(&wsi->u.http2.peer_settings,
1296 (unsigned char *)protocol_list, n);
1298 strcpy(protocol_list,
1299 "HTTP/1.1 101 Switching Protocols\x0d\x0a"
1300 "Connection: Upgrade\x0d\x0a"
1301 "Upgrade: h2c\x0d\x0a\x0d\x0a");
1302 n = lws_issue_raw(wsi, (unsigned char *)protocol_list,
1303 strlen(protocol_list));
1304 if (n != strlen(protocol_list)) {
1305 lwsl_debug("http2 switch: ERROR writing to socket\n");
1309 wsi->state = LWSS_HTTP2_AWAIT_CLIENT_PREFACE;
1316 lwsl_err("NULL protocol at lws_read\n");
1321 * Select the first protocol we support from the list
1322 * the client sent us.
1324 * Copy it to remove header fragmentation
1327 if (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1,
1328 WSI_TOKEN_PROTOCOL) < 0) {
1329 lwsl_err("protocol list too long");
1333 protocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
1334 protocol_list[protocol_len] = '\0';
1338 while (*p && !hit) {
1340 non_space_char_found = 0;
1341 while (n < sizeof(protocol_name) - 1 && *p &&
1343 // ignore leading spaces
1344 if (!non_space_char_found && *p == ' ') {
1348 non_space_char_found = 1;
1349 protocol_name[n++] = *p++;
1351 protocol_name[n] = '\0';
1355 lwsl_info("checking %s\n", protocol_name);
1358 while (wsi->vhost->protocols[n].callback) {
1359 lwsl_info("try %s\n", wsi->vhost->protocols[n].name);
1361 if (wsi->vhost->protocols[n].name &&
1362 !strcmp(wsi->vhost->protocols[n].name,
1364 wsi->protocol = &wsi->vhost->protocols[n];
1373 /* we didn't find a protocol he wanted? */
1376 if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL)) {
1377 lwsl_info("No protocol from \"%s\" supported\n",
1382 * some clients only have one protocol and
1383 * do not send the protocol list header...
1384 * allow it and match to the vhost's default
1385 * protocol (which itself defaults to zero)
1387 lwsl_info("defaulting to prot handler %d\n",
1388 wsi->vhost->default_protocol_index);
1390 wsi->protocol = &wsi->vhost->protocols[
1391 (int)wsi->vhost->default_protocol_index];
1394 /* allocate wsi->user storage */
1395 if (lws_ensure_user_space(wsi))
1399 * Give the user code a chance to study the request and
1400 * have the opportunity to deny it
1402 if ((wsi->protocol->callback)(wsi,
1403 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
1405 lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) {
1406 lwsl_warn("User code denied connection\n");
1411 * Perform the handshake according to the protocol version the
1415 switch (wsi->ietf_spec_revision) {
1417 lwsl_parser("lws_parse calling handshake_04\n");
1418 if (handshake_0405(context, wsi)) {
1419 lwsl_info("hs0405 has failed the connection\n");
1425 lwsl_info("Unknown client spec version %d\n",
1426 wsi->ietf_spec_revision);
1431 * stitch protocol choice into the vh protocol linked list
1432 * We always insert ourselves at the start of the list
1437 //lwsl_err("%s: pre insert vhost start wsi %p, that wsi prev == %p\n",
1439 // wsi->vhost->same_vh_protocol_list[n],
1440 // wsi->same_vh_protocol_prev);
1441 wsi->same_vh_protocol_prev = /* guy who points to us */
1442 &wsi->vhost->same_vh_protocol_list[n];
1443 wsi->same_vh_protocol_next = /* old first guy is our next */
1444 wsi->vhost->same_vh_protocol_list[n];
1445 /* we become the new first guy */
1446 wsi->vhost->same_vh_protocol_list[n] = wsi;
1448 if (wsi->same_vh_protocol_next)
1449 /* old first guy points back to us now */
1450 wsi->same_vh_protocol_next->same_vh_protocol_prev =
1451 &wsi->same_vh_protocol_next;
1455 /* we are upgrading to ws, so http/1.1 and keepalive +
1456 * pipelined header considerations about keeping the ah around
1457 * no longer apply. However it's common for the first ws
1458 * protocol data to have been coalesced with the browser
1459 * upgrade request and to already be in the ah rx buffer.
1462 lwsl_info("%s: %p: inheriting ah in ws mode (rxpos:%d, rxlen:%d)\n",
1463 __func__, wsi, wsi->u.hdr.ah->rxpos,
1464 wsi->u.hdr.ah->rxlen);
1468 lws_union_transition(wsi, LWSCM_WS_SERVING);
1470 * first service is WS mode will notice this, use the RX and
1471 * then detach the ah (caution: we are not in u.hdr union
1472 * mode any more then... ah_temp member is at start the same
1475 * Because rxpos/rxlen shows something in the ah, we will get
1476 * service guaranteed next time around the event loop
1478 * All union members begin with hdr, so we can use it even
1479 * though we transitioned to ws union mode (the ah detach
1480 * code uses it anyway).
1485 lws_restart_ws_ping_pong_timer(wsi);
1488 * create the frame buffer for this connection according to the
1489 * size mentioned in the protocol definition. If 0 there, use
1490 * a big default for compatibility
1493 n = wsi->protocol->rx_buffer_size;
1495 n = context->pt_serv_buf_size;
1497 wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
1498 if (!wsi->u.ws.rx_ubuf) {
1499 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
1502 wsi->u.ws.rx_ubuf_alloc = n;
1503 lwsl_debug("Allocating RX buffer %d\n", n);
1504 #if LWS_POSIX && !defined(LWS_WITH_ESP32)
1505 if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF,
1506 (const char *)&n, sizeof n)) {
1507 lwsl_warn("Failed to set SNDBUF to %d", n);
1512 lwsl_parser("accepted v%02d connection\n",
1513 wsi->ietf_spec_revision);
1515 /* notify user code that we're ready to roll */
1517 if (wsi->protocol->callback)
1518 if (wsi->protocol->callback(wsi, LWS_CALLBACK_ESTABLISHED,
1520 #ifdef LWS_OPENSSL_SUPPORT
1528 /* !!! drop ah unreservedly after ESTABLISHED */
1529 if (!wsi->more_rx_waiting) {
1530 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1532 //lwsl_notice("%p: dropping ah EST\n", wsi);
1533 lws_header_table_detach(wsi, 1);
1537 } /* while all chars are handled */
1542 /* drop the header info */
1543 /* we're closing, losing some rx is OK */
1544 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1545 //lwsl_notice("%s: drop2\n", __func__);
1546 lws_header_table_detach(wsi, 1);
1552 lws_get_idlest_tsi(struct lws_context *context)
1554 unsigned int lowest = ~0;
1555 int n = 0, hit = -1;
1557 for (; n < context->count_threads; n++) {
1558 if ((unsigned int)context->pt[n].fds_count !=
1559 context->fd_limit_per_thread - 1 &&
1560 (unsigned int)context->pt[n].fds_count < lowest) {
1561 lowest = context->pt[n].fds_count;
1570 lws_create_new_server_wsi(struct lws_vhost *vhost)
1572 struct lws *new_wsi;
1573 int n = lws_get_idlest_tsi(vhost->context);
1576 lwsl_err("no space for new conn\n");
1580 new_wsi = lws_zalloc(sizeof(struct lws));
1581 if (new_wsi == NULL) {
1582 lwsl_err("Out of memory for new connection\n");
1587 lwsl_debug("Accepted wsi %p to context %p, tsi %d\n", new_wsi,
1588 vhost->context, new_wsi->tsi);
1590 new_wsi->vhost = vhost;
1591 new_wsi->context = vhost->context;
1592 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1593 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1595 /* initialize the instance struct */
1597 new_wsi->state = LWSS_HTTP;
1598 new_wsi->mode = LWSCM_HTTP_SERVING;
1599 new_wsi->hdr_parsing_completed = 0;
1601 #ifdef LWS_OPENSSL_SUPPORT
1602 new_wsi->use_ssl = LWS_SSL_ENABLED(vhost);
1606 * these can only be set once the protocol is known
1607 * we set an unestablished connection's protocol pointer
1608 * to the start of the supported list, so it can look
1609 * for matching ones during the handshake
1611 new_wsi->protocol = vhost->protocols;
1612 new_wsi->user_space = NULL;
1613 new_wsi->ietf_spec_revision = 0;
1614 new_wsi->sock = LWS_SOCK_INVALID;
1615 vhost->context->count_wsi_allocated++;
1618 * outermost create notification for wsi
1619 * no user_space because no protocol selection
1621 vhost->protocols[0].callback(new_wsi, LWS_CALLBACK_WSI_CREATE,
1627 LWS_VISIBLE int LWS_WARN_UNUSED_RESULT
1628 lws_http_transaction_completed(struct lws *wsi)
1630 int n = NO_PENDING_TIMEOUT;
1632 lws_access_log(wsi);
1634 lwsl_info("%s: wsi %p\n", __func__, wsi);
1635 /* if we can't go back to accept new headers, drop the connection */
1636 if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
1637 lwsl_info("%s: %p: close connection\n", __func__, wsi);
1641 if (lws_bind_protocol(wsi, &wsi->vhost->protocols[0]))
1644 /* otherwise set ourselves up ready to go again */
1645 wsi->state = LWSS_HTTP;
1646 wsi->mode = LWSCM_HTTP_SERVING;
1647 wsi->u.http.content_length = 0;
1648 wsi->u.http.content_remain = 0;
1649 wsi->hdr_parsing_completed = 0;
1650 #ifdef LWS_WITH_ACCESS_LOG
1651 wsi->access_log.sent = 0;
1654 if (wsi->vhost->keepalive_timeout)
1655 n = PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE;
1656 lws_set_timeout(wsi, n, wsi->vhost->keepalive_timeout);
1659 * We already know we are on http1.1 / keepalive and the next thing
1660 * coming will be another header set.
1662 * If there is no pending rx and we still have the ah, drop it and
1663 * reacquire a new ah when the new headers start to arrive. (Otherwise
1664 * we needlessly hog an ah indefinitely.)
1666 * However if there is pending rx and we know from the keepalive state
1667 * that is already at least the start of another header set, simply
1668 * reset the existing header table and keep it.
1670 if (wsi->u.hdr.ah) {
1671 lwsl_info("%s: wsi->more_rx_waiting=%d\n", __func__,
1672 wsi->more_rx_waiting);
1674 if (!wsi->more_rx_waiting) {
1675 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1676 lws_header_table_detach(wsi, 1);
1678 lws_header_table_reset(wsi, 1);
1681 /* If we're (re)starting on headers, need other implied init */
1682 wsi->u.hdr.ues = URIES_IDLE;
1684 lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
1689 LWS_VISIBLE struct lws *
1690 lws_adopt_socket_vhost2(struct lws_vhost *vh, lws_sockfd_type accept_fd,
1691 int allow_ssl, int raw)
1693 struct lws_context *context = vh->context;
1694 struct lws *new_wsi = lws_create_new_server_wsi(vh);
1698 compatible_close(accept_fd);
1702 lwsl_debug("%s: new wsi %p, sockfd %d, cb %p\n", __func__, new_wsi,
1703 accept_fd, context->vhost_list->protocols[0].callback);
1705 new_wsi->sock = accept_fd;
1707 /* the transport is accepted... give him time to negotiate */
1708 lws_set_timeout(new_wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
1709 context->timeout_secs);
1712 #if defined(LWS_WITH_ESP8266)
1713 esp8266_tcp_stream_accept(accept_fd, new_wsi);
1717 * A new connection was accepted. Give the user a chance to
1718 * set properties of the newly created wsi. There's no protocol
1719 * selected yet so we issue this to the vhosts's default protocol,
1720 * itself by default protocols[0]
1722 n = LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED;
1724 n = LWS_CALLBACK_RAW_ADOPT;
1725 if ((context->vhost_list->protocols[vh->default_protocol_index].callback)(
1726 new_wsi, n, NULL, NULL, 0)) {
1727 /* force us off the timeout list by hand */
1728 lws_set_timeout(new_wsi, NO_PENDING_TIMEOUT, 0);
1729 compatible_close(new_wsi->sock);
1734 lws_libev_accept(new_wsi, new_wsi->sock);
1735 lws_libuv_accept(new_wsi, new_wsi->sock);
1737 if (!LWS_SSL_ENABLED(new_wsi->vhost) || allow_ssl == 0) {
1739 new_wsi->mode = LWSCM_RAW;
1740 if (insert_wsi_socket_into_fds(context, new_wsi)) {
1741 lwsl_err("%s: fail inserting socket\n", __func__);
1746 new_wsi->mode = LWSCM_SSL_INIT_RAW;
1748 new_wsi->mode = LWSCM_SSL_INIT;
1749 if (lws_server_socket_service_ssl(new_wsi, accept_fd)) {
1750 lwsl_err("%s: fail ssl negotiation\n", __func__);
1755 if (!lws_header_table_attach(new_wsi, 0))
1756 lwsl_debug("Attached ah immediately\n");
1761 lws_close_free_wsi(new_wsi, LWS_CLOSE_STATUS_NOSTATUS);
1766 LWS_VISIBLE struct lws *
1767 lws_adopt_socket_vhost(struct lws_vhost *vh, lws_sockfd_type accept_fd)
1769 return lws_adopt_socket_vhost2(vh, accept_fd, 1, 0);
1772 LWS_VISIBLE struct lws *
1773 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd)
1775 return lws_adopt_socket_vhost2(context->vhost_list, accept_fd, 1, 0);
1778 /* Common read-buffer adoption for lws_adopt_*_readbuf */
1780 adopt_socket_readbuf(struct lws *wsi, const char *readbuf, size_t len)
1782 struct lws_context_per_thread *pt;
1783 struct allocated_headers *ah;
1784 struct lws_pollfd *pfd;
1789 if (!readbuf || len == 0)
1792 if (len > sizeof(ah->rx)) {
1793 lwsl_err("%s: rx in too big\n", __func__);
1798 * we can't process the initial read data until we can attach an ah.
1800 * if one is available, get it and place the data in his ah rxbuf...
1801 * wsi with ah that have pending rxbuf get auto-POLLIN service.
1803 * no autoservice because we didn't get a chance to attach the
1804 * readbuf data to wsi or ah yet, and we will do it next if we get
1807 if (wsi->u.hdr.ah || !lws_header_table_attach(wsi, 0)) {
1809 memcpy(ah->rx, readbuf, len);
1813 lwsl_notice("%s: calling service on readbuf ah\n", __func__);
1814 pt = &wsi->context->pt[(int)wsi->tsi];
1816 /* unlike a normal connect, we have the headers already
1817 * (or the first part of them anyway).
1818 * libuv won't come back and service us without a network
1819 * event, so we need to do the header service right here.
1821 pfd = &pt->fds[wsi->position_in_fds_table];
1822 pfd->revents |= LWS_POLLIN;
1823 lwsl_err("%s: calling service\n", __func__);
1824 if (lws_service_fd_tsi(wsi->context, pfd, wsi->tsi))
1825 /* service closed us */
1830 lwsl_err("%s: deferring handling ah\n", __func__);
1832 * hum if no ah came, we are on the wait list and must defer
1833 * dealing with this until the ah arrives.
1835 * later successful lws_header_table_attach() will apply the
1836 * below to the rx buffer (via lws_header_table_reset()).
1838 wsi->u.hdr.preamble_rx = lws_malloc(len);
1839 if (!wsi->u.hdr.preamble_rx) {
1843 memcpy(wsi->u.hdr.preamble_rx, readbuf, len);
1844 wsi->u.hdr.preamble_rx_len = len;
1849 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1854 LWS_VISIBLE struct lws *
1855 lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
1856 const char *readbuf, size_t len)
1858 return adopt_socket_readbuf(lws_adopt_socket(context, accept_fd), readbuf, len);
1861 LWS_VISIBLE struct lws *
1862 lws_adopt_socket_vhost_readbuf(struct lws_vhost *vhost, lws_sockfd_type accept_fd,
1863 const char *readbuf, size_t len)
1865 return adopt_socket_readbuf(lws_adopt_socket_vhost(vhost, accept_fd), readbuf, len);
1869 lws_server_socket_service(struct lws_context *context, struct lws *wsi,
1870 struct lws_pollfd *pollfd)
1872 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1873 lws_sockfd_type accept_fd = LWS_SOCK_INVALID;
1874 struct allocated_headers *ah;
1876 struct sockaddr_in cli_addr;
1881 // lwsl_notice("%s: mode %d\n", __func__, wsi->mode);
1883 switch (wsi->mode) {
1885 case LWSCM_HTTP_SERVING:
1886 case LWSCM_HTTP_SERVING_ACCEPTED:
1887 case LWSCM_HTTP2_SERVING:
1889 /* handle http headers coming in */
1891 /* pending truncated sends have uber priority */
1893 if (wsi->trunc_len) {
1894 if (!(pollfd->revents & LWS_POLLOUT))
1897 if (lws_issue_raw(wsi, wsi->trunc_alloc +
1899 wsi->trunc_len) < 0)
1902 * we can't afford to allow input processing to send
1903 * something new, so spin around he event loop until
1904 * he doesn't have any partials
1909 /* any incoming data ready? */
1911 if (!(pollfd->revents & pollfd->events & LWS_POLLIN))
1915 * If we previously just did POLLIN when IN and OUT were
1916 * signalled (because POLLIN processing may have used up
1917 * the POLLOUT), don't let that happen twice in a row...
1918 * next time we see the situation favour POLLOUT
1920 #if !defined(LWS_WITH_ESP8266)
1921 if (wsi->favoured_pollin &&
1922 (pollfd->revents & pollfd->events & LWS_POLLOUT)) {
1923 wsi->favoured_pollin = 0;
1928 /* these states imply we MUST have an ah attached */
1930 if (wsi->state == LWSS_HTTP ||
1931 wsi->state == LWSS_HTTP_ISSUING_FILE ||
1932 wsi->state == LWSS_HTTP_HEADERS) {
1933 if (!wsi->u.hdr.ah) {
1935 //lwsl_err("wsi %p: missing ah\n", wsi);
1936 /* no autoservice beacuse we will do it next */
1937 if (lws_header_table_attach(wsi, 0)) {
1938 lwsl_err("wsi %p: failed to acquire ah\n", wsi);
1944 //lwsl_notice("%s: %p: rxpos:%d rxlen:%d\n", __func__, wsi,
1945 // ah->rxpos, ah->rxlen);
1947 /* if nothing in ah rx buffer, get some fresh rx */
1948 if (ah->rxpos == ah->rxlen) {
1949 ah->rxlen = lws_ssl_capable_read(wsi, ah->rx,
1952 //lwsl_notice("%s: wsi %p, ah->rxlen = %d\r\n",
1953 // __func__, wsi, ah->rxlen);
1954 switch (ah->rxlen) {
1956 lwsl_info("%s: read 0 len\n", __func__);
1957 /* lwsl_info(" state=%d\n", wsi->state); */
1958 // if (!wsi->hdr_parsing_completed)
1959 // lws_header_table_detach(wsi);
1961 case LWS_SSL_CAPABLE_ERROR:
1963 case LWS_SSL_CAPABLE_MORE_SERVICE:
1964 ah->rxlen = ah->rxpos = 0;
1969 if (!(ah->rxpos != ah->rxlen && ah->rxlen)) {
1970 lwsl_err("%s: assert: rxpos %d, rxlen %d\n",
1971 __func__, ah->rxpos, ah->rxlen);
1976 /* just ignore incoming if waiting for close */
1977 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
1978 n = lws_read(wsi, ah->rx + ah->rxpos,
1979 ah->rxlen - ah->rxpos);
1980 if (n < 0) /* we closed wsi */
1982 if (wsi->u.hdr.ah) {
1983 if ( wsi->u.hdr.ah->rxlen)
1984 wsi->u.hdr.ah->rxpos += n;
1986 lwsl_debug("%s: wsi %p: ah read rxpos %d, rxlen %d\n", __func__, wsi, wsi->u.hdr.ah->rxpos, wsi->u.hdr.ah->rxlen);
1988 if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen &&
1989 (wsi->mode != LWSCM_HTTP_SERVING &&
1990 wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED &&
1991 wsi->mode != LWSCM_HTTP2_SERVING))
1992 lws_header_table_detach(wsi, 1);
2000 len = lws_ssl_capable_read(wsi, pt->serv_buf,
2001 context->pt_serv_buf_size);
2002 lwsl_notice("%s: wsi %p read %d\r\n", __func__, wsi, len);
2005 lwsl_info("%s: read 0 len\n", __func__);
2006 /* lwsl_info(" state=%d\n", wsi->state); */
2007 // if (!wsi->hdr_parsing_completed)
2008 // lws_header_table_detach(wsi);
2010 case LWS_SSL_CAPABLE_ERROR:
2012 case LWS_SSL_CAPABLE_MORE_SERVICE:
2016 if (wsi->mode == LWSCM_RAW) {
2017 n = user_callback_handle_rxflow(wsi->protocol->callback,
2018 wsi, LWS_CALLBACK_RAW_RX,
2019 wsi->user_space, pt->serv_buf, len);
2021 lwsl_info("raw writeable_fail\n");
2027 /* just ignore incoming if waiting for close */
2028 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
2030 * this may want to send
2031 * (via HTTP callback for example)
2033 n = lws_read(wsi, pt->serv_buf, len);
2034 if (n < 0) /* we closed wsi */
2037 * he may have used up the
2038 * writability above, if we will defer POLLOUT
2039 * processing in favour of POLLIN, note it
2041 if (pollfd->revents & LWS_POLLOUT)
2042 wsi->favoured_pollin = 1;
2048 /* this handles POLLOUT for http serving fragments */
2050 if (!(pollfd->revents & LWS_POLLOUT))
2054 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
2055 lwsl_notice("%s a\n", __func__);
2059 if (!wsi->hdr_parsing_completed)
2062 if (wsi->state != LWSS_HTTP_ISSUING_FILE) {
2063 n = user_callback_handle_rxflow(wsi->protocol->callback,
2064 wsi, LWS_CALLBACK_HTTP_WRITEABLE,
2065 wsi->user_space, NULL, 0);
2067 lwsl_info("writeable_fail\n");
2073 /* >0 == completion, <0 == error */
2074 n = lws_serve_http_file_fragment(wsi);
2075 if (n < 0 || (n > 0 && lws_http_transaction_completed(wsi))) {
2076 lwsl_info("completed\n");
2082 case LWSCM_SERVER_LISTENER:
2085 /* pollin means a client has connected to us then */
2088 if (!(pollfd->revents & LWS_POLLIN) || !(pollfd->events & LWS_POLLIN))
2091 /* listen socket got an unencrypted connection... */
2093 clilen = sizeof(cli_addr);
2094 lws_latency_pre(context, wsi);
2095 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
2097 lws_latency(context, wsi, "listener accept", accept_fd,
2099 if (accept_fd < 0) {
2100 if (LWS_ERRNO == LWS_EAGAIN ||
2101 LWS_ERRNO == LWS_EWOULDBLOCK) {
2102 lwsl_err("accept asks to try again\n");
2105 lwsl_err("ERROR on accept: %s\n", strerror(LWS_ERRNO));
2109 lws_plat_set_socket_options(wsi->vhost, accept_fd);
2111 lwsl_debug("accepted new conn port %u on fd=%d\n",
2112 ntohs(cli_addr.sin_port), accept_fd);
2115 /* not very beautiful... */
2116 accept_fd = (lws_sockfd_type)pollfd;
2119 * look at who we connected to and give user code a chance
2120 * to reject based on client IP. There's no protocol selected
2121 * yet so we issue this to protocols[0]
2123 if ((wsi->vhost->protocols[0].callback)(wsi,
2124 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
2125 NULL, (void *)(long)accept_fd, 0)) {
2126 lwsl_debug("Callback denied network connection\n");
2127 compatible_close(accept_fd);
2131 if (!lws_adopt_socket_vhost(wsi->vhost, accept_fd))
2132 /* already closed cleanly as necessary */
2136 } while (pt->fds_count < context->fd_limit_per_thread - 1 &&
2137 lws_poll_listen_fd(&pt->fds[wsi->position_in_fds_table]) > 0);
2145 if (!lws_server_socket_service_ssl(wsi, accept_fd))
2149 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
2155 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
2156 const char *other_headers, int other_headers_len)
2158 static const char * const intermediates[] = { "private", "public" };
2159 struct lws_context *context = lws_get_context(wsi);
2160 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
2161 #if defined(LWS_WITH_RANGES)
2162 struct lws_range_parsing *rp = &wsi->u.http.range;
2164 char cache_control[50], *cc = "no-store";
2165 unsigned char *response = pt->serv_buf + LWS_PRE;
2166 unsigned char *p = response;
2167 unsigned char *end = p + context->pt_serv_buf_size - LWS_PRE;
2168 unsigned long computed_total_content_length;
2169 int ret = 0, cclen = 8, n = HTTP_STATUS_OK, fflags = O_RDONLY;
2170 #if defined(LWS_WITH_RANGES)
2174 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_ACCEPT_ENCODING))
2175 if (strstr("gzip", lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_ACCEPT_ENCODING)) &&
2176 strstr("deflate", lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_ACCEPT_ENCODING))) {
2177 lwsl_debug("client indicates GZIP is acceptable\n");
2178 fflags |= LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP;
2182 wsi->u.http.fd = lws_plat_file_open(wsi, file, &wsi->u.http.filelen,
2184 if (wsi->u.http.fd == LWS_INVALID_FILE) {
2185 lwsl_err("Unable to open '%s'\n", file);
2189 computed_total_content_length = wsi->u.http.filelen;
2191 if ((fflags & (LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP |
2192 LWS_FOP_FLAG_COMPR_IS_GZIP)) ==
2193 (LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP | LWS_FOP_FLAG_COMPR_IS_GZIP)) {
2194 if (lws_add_http_header_by_token(wsi,
2195 WSI_TOKEN_HTTP_CONTENT_ENCODING,
2196 (unsigned char *)"gzip, deflate", 13, &p, end))
2198 lwsl_debug("file is being provided in gzip\n");
2201 #if defined(LWS_WITH_RANGES)
2202 ranges = lws_ranges_init(wsi, rp, wsi->u.http.filelen);
2204 lwsl_debug("Range count %d\n", ranges);
2207 * 1 range -> 206 + Content-Type: normal; Content-Range;
2208 * more -> 206 + Content-Type: multipart/byteranges
2209 * Repeat the true Content-Type in each multipart header
2210 * along with Content-Range
2213 /* it means he expressed a range in Range:, but it was illegal */
2214 lws_return_http_status(wsi, HTTP_STATUS_REQ_RANGE_NOT_SATISFIABLE, NULL);
2215 if (lws_http_transaction_completed(wsi))
2216 return -1; /* <0 means just hang up */
2218 return 0; /* == 0 means we dealt with the transaction complete */
2221 n = HTTP_STATUS_PARTIAL_CONTENT;
2224 if (lws_add_http_header_status(wsi, n, &p, end))
2227 #if defined(LWS_WITH_RANGES)
2228 if (ranges < 2 && content_type && content_type[0])
2229 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
2230 (unsigned char *)content_type,
2231 strlen(content_type), &p, end))
2234 if (ranges >= 2) { /* multipart byteranges */
2235 strncpy(wsi->u.http.multipart_content_type, content_type,
2236 sizeof(wsi->u.http.multipart_content_type) - 1);
2237 wsi->u.http.multipart_content_type[
2238 sizeof(wsi->u.http.multipart_content_type) - 1] = '\0';
2239 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
2240 (unsigned char *)"multipart/byteranges; boundary=_lws",
2245 * our overall content length has to include
2247 * - (n + 1) x "_lws\r\n"
2248 * - n x Content-Type: xxx/xxx\r\n
2249 * - n x Content-Range: bytes xxx-yyy/zzz\r\n
2251 * - the actual payloads (aggregated in rp->agg)
2253 * Precompute it for the main response header
2256 computed_total_content_length = (unsigned long)rp->agg +
2257 6 /* final _lws\r\n */;
2259 lws_ranges_reset(rp);
2260 while (lws_ranges_next(rp)) {
2261 n = lws_snprintf(cache_control, sizeof(cache_control),
2262 "bytes %llu-%llu/%llu",
2263 rp->start, rp->end, rp->extent);
2265 computed_total_content_length +=
2266 6 /* header _lws\r\n */ +
2267 14 + strlen(content_type) + 2 + /* Content-Type: xxx/xxx\r\n */
2268 15 + n + 2 + /* Content-Range: xxxx\r\n */
2272 lws_ranges_reset(rp);
2273 lws_ranges_next(rp);
2277 computed_total_content_length = (unsigned long)rp->agg;
2278 n = lws_snprintf(cache_control, sizeof(cache_control), "bytes %llu-%llu/%llu",
2279 rp->start, rp->end, rp->extent);
2281 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_RANGE,
2282 (unsigned char *)cache_control,
2287 wsi->u.http.range.inside = 0;
2289 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ACCEPT_RANGES,
2290 (unsigned char *)"bytes", 5, &p, end))
2294 if (!wsi->sending_chunked) {
2295 if (lws_add_http_header_content_length(wsi,
2296 computed_total_content_length,
2300 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_TRANSFER_ENCODING,
2301 (unsigned char *)"chunked",
2306 if (wsi->cache_secs && wsi->cache_reuse) {
2307 if (wsi->cache_revalidate) {
2309 cclen = sprintf(cache_control, "%s max-age: %u",
2310 intermediates[wsi->cache_intermediaries],
2318 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CACHE_CONTROL,
2319 (unsigned char *)cc, cclen, &p, end))
2322 if (wsi->u.http.connection_type == HTTP_CONNECTION_KEEP_ALIVE)
2323 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
2324 (unsigned char *)"keep-alive", 10, &p, end))
2327 if (other_headers) {
2328 if ((end - p) < other_headers_len)
2330 memcpy(p, other_headers, other_headers_len);
2331 p += other_headers_len;
2334 if (lws_finalize_http_header(wsi, &p, end))
2337 ret = lws_write(wsi, response, p - response, LWS_WRITE_HTTP_HEADERS);
2338 if (ret != (p - response)) {
2339 lwsl_err("_write returned %d from %ld\n", ret, (long)(p - response));
2343 wsi->u.http.filepos = 0;
2344 wsi->state = LWSS_HTTP_ISSUING_FILE;
2346 return lws_serve_http_file_fragment(wsi);
2350 lws_interpret_incoming_packet(struct lws *wsi, unsigned char **buf, size_t len)
2354 lwsl_parser("%s: received %d byte packet\n", __func__, (int)len);
2356 lwsl_hexdump(*buf, len);
2359 /* let the rx protocol state machine have as much as it needs */
2363 * we were accepting input but now we stopped doing so
2365 if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
2366 lws_rxflow_cache(wsi, *buf, 0, len);
2367 lwsl_parser("%s: cached %ld\n", __func__, (long)len);
2371 if (wsi->u.ws.rx_draining_ext) {
2372 m = lws_rx_sm(wsi, 0);
2378 /* account for what we're using in rxflow buffer */
2379 if (wsi->rxflow_buffer)
2382 /* consume payload bytes efficiently */
2383 if (wsi->lws_rx_parse_state ==
2384 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED) {
2385 m = lws_payload_until_length_exhausted(wsi, buf, &len);
2386 if (wsi->rxflow_buffer)
2387 wsi->rxflow_pos += m;
2390 /* process the byte */
2391 m = lws_rx_sm(wsi, *(*buf)++);
2397 lwsl_parser("%s: exit with %d unused\n", __func__, (int)len);
2403 lws_server_get_canonical_hostname(struct lws_context *context,
2404 struct lws_context_creation_info *info)
2406 if (lws_check_opt(info->options, LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME))
2409 /* find canonical hostname */
2410 gethostname((char *)context->canonical_hostname,
2411 sizeof(context->canonical_hostname) - 1);
2413 lwsl_notice(" canonical_hostname = %s\n", context->canonical_hostname);
2419 #define LWS_MAX_ELEM_NAME 32
2421 enum urldecode_stateful {
2435 static const char * const mp_hdr[] = {
2436 "content-disposition: ",
2441 typedef int (*lws_urldecode_stateful_cb)(void *data,
2442 const char *name, char **buf, int len, int final);
2444 struct lws_urldecode_stateful {
2447 char name[LWS_MAX_ELEM_NAME];
2448 char temp[LWS_MAX_ELEM_NAME];
2449 char content_type[32];
2450 char content_disp[32];
2451 char content_disp_filename[256];
2452 char mime_boundary[128];
2459 unsigned int multipart_form_data:1;
2460 unsigned int inside_quote:1;
2461 unsigned int subname:1;
2462 unsigned int boundary_real_crlf:1;
2464 enum urldecode_stateful state;
2466 lws_urldecode_stateful_cb output;
2469 static struct lws_urldecode_stateful *
2470 lws_urldecode_s_create(struct lws *wsi, char *out, int out_len, void *data,
2471 lws_urldecode_stateful_cb output)
2473 struct lws_urldecode_stateful *s = lws_zalloc(sizeof(*s));
2481 s->out_len = out_len;
2490 if (lws_hdr_copy(wsi, buf, sizeof(buf), WSI_TOKEN_HTTP_CONTENT_TYPE) > 0) {
2491 /* multipart/form-data; boundary=----WebKitFormBoundarycc7YgAPEIHvgE9Bf */
2493 if (!strncmp(buf, "multipart/form-data", 19)) {
2494 s->multipart_form_data = 1;
2495 s->state = MT_LOOK_BOUND_IN;
2497 p = strstr(buf, "boundary=");
2500 s->mime_boundary[m++] = '\x0d';
2501 s->mime_boundary[m++] = '\x0a';
2502 s->mime_boundary[m++] = '-';
2503 s->mime_boundary[m++] = '-';
2504 while (m < sizeof(s->mime_boundary) - 1 &&
2506 s->mime_boundary[m++] = *p++;
2508 s->mime_boundary[m] = '\0';
2510 lwsl_notice("boundary '%s'\n", s->mime_boundary);
2519 lws_urldecode_s_process(struct lws_urldecode_stateful *s, const char *in, int len)
2522 char c, was_end = 0;
2525 if (s->pos == s->out_len - s->mp - 1) {
2526 if (s->output(s->data, s->name, &s->out, s->pos, 0))
2534 /* states for url arg style */
2537 s->inside_quote = 0;
2539 s->name[s->pos] = '\0';
2546 s->name[s->pos] = '\0';
2547 if (s->output(s->data, s->name, &s->out, s->pos, 1))
2554 if (s->pos >= sizeof(s->name) - 1) {
2555 lwsl_notice("Name too long\n");
2558 s->name[s->pos++] = *in++;
2567 s->out[s->pos] = '\0';
2568 if (s->output(s->data, s->name, &s->out, s->pos, 1))
2577 s->out[s->pos++] = ' ';
2580 s->out[s->pos++] = *in++;
2583 n = char_to_hex(*in);
2593 n = char_to_hex(*in);
2598 s->out[s->pos++] = s->sum | n;
2603 /* states for multipart / mime style */
2605 case MT_LOOK_BOUND_IN:
2607 if (*in == s->mime_boundary[s->mp] &&
2608 s->mime_boundary[s->mp]) {
2611 if (!s->mime_boundary[s->mp]) {
2613 s->state = MT_IGNORE1;
2615 if (s->pos || was_end)
2616 if (s->output(s->data, s->name,
2617 &s->out, s->pos, 1))
2622 s->content_disp[0] = '\0';
2624 s->content_disp_filename[0] = '\0';
2625 s->boundary_real_crlf = 1;
2631 if (!s->boundary_real_crlf)
2634 memcpy(s->out + s->pos, s->mime_boundary + n, s->mp - n);
2637 goto retry_as_first;
2640 s->out[s->pos++] = *in;
2648 if (c >= 'A' && c <= 'Z')
2650 for (n = 0; n < ARRAY_SIZE(mp_hdr); n++)
2651 if (c == mp_hdr[n][s->mp]) {
2665 if (mp_hdr[hit][s->mp])
2673 s->state = MT_LOOK_BOUND_IN;
2675 s->state += hit + 1;
2679 /* form-data; name="file"; filename="t.txt" */
2681 if (*in == '\x0d') {
2682 // lwsl_notice("disp: '%s', '%s', '%s'\n",
2683 // s->content_disp, s->name,
2684 // s->content_disp_filename);
2686 if (s->content_disp_filename[0])
2687 if (s->output(s->data, s->name,
2688 &s->out, s->pos, LWS_UFS_OPEN))
2690 s->state = MT_IGNORE2;
2701 s->inside_quote ^= 1;
2707 s->temp[s->mp] = '\0';
2712 if (s->mp < sizeof(s->temp) - 1 &&
2713 (*in != ' ' || s->inside_quote))
2714 s->temp[s->mp++] = *in;
2719 if (s->mp < sizeof(s->content_disp) - 1)
2720 s->content_disp[s->mp++] = *in;
2721 s->content_disp[s->mp] = '\0';
2725 if (!strcmp(s->temp, "name")) {
2726 if (s->mp < sizeof(s->name) - 1)
2727 s->name[s->mp++] = *in;
2728 s->name[s->mp] = '\0';
2732 if (!strcmp(s->temp, "filename")) {
2733 if (s->mp < sizeof(s->content_disp_filename) - 1)
2734 s->content_disp_filename[s->mp++] = *in;
2735 s->content_disp_filename[s->mp] = '\0';
2744 s->state = MT_IGNORE2;
2746 if (s->mp < sizeof(s->content_type) - 1)
2747 s->content_type[s->mp++] = *in;
2748 s->content_type[s->mp] = '\0';
2755 s->state = MT_IGNORE2;
2762 s->state = MT_HNAME;
2772 lws_urldecode_s_destroy(struct lws_urldecode_stateful *s)
2776 if (s->state != US_IDLE)
2780 if (s->output(s->data, s->name, &s->out, s->pos, 1))
2789 struct lws_urldecode_stateful *s;
2790 lws_spa_fileupload_cb opt_cb;
2791 const char * const *param_names;
2803 lws_urldecode_spa_lookup(struct lws_spa *spa,
2808 for (n = 0; n < spa->count_params; n++)
2809 if (!strcmp(spa->param_names[n], name))
2816 lws_urldecode_spa_cb(void *data, const char *name, char **buf, int len,
2819 struct lws_spa *spa =
2820 (struct lws_spa *)data;
2823 if (spa->s->content_disp_filename[0]) {
2825 n = spa->opt_cb(spa->opt_data, name,
2826 spa->s->content_disp_filename,
2834 n = lws_urldecode_spa_lookup(spa, name);
2836 if (n == -1 || !len) /* unrecognized */
2839 if (!spa->params[n])
2840 spa->params[n] = *buf;
2842 if ((*buf) + len >= spa->end) {
2843 lwsl_notice("%s: exceeded storage\n", __func__);
2847 spa->param_length[n] += len;
2849 /* move it on inside storage */
2853 spa->s->out_len -= len + 1;
2858 LWS_VISIBLE LWS_EXTERN struct lws_spa *
2859 lws_spa_create(struct lws *wsi, const char * const *param_names,
2860 int count_params, int max_storage,
2861 lws_spa_fileupload_cb opt_cb, void *opt_data)
2863 struct lws_spa *spa = lws_zalloc(sizeof(*spa));
2868 spa->param_names = param_names;
2869 spa->count_params = count_params;
2870 spa->max_storage = max_storage;
2871 spa->opt_cb = opt_cb;
2872 spa->opt_data = opt_data;
2874 spa->storage = lws_malloc(max_storage);
2877 spa->end = spa->storage + max_storage - 1;
2879 spa->params = lws_zalloc(sizeof(char *) * count_params);
2883 spa->s = lws_urldecode_s_create(wsi, spa->storage, max_storage, spa,
2884 lws_urldecode_spa_cb);
2888 spa->param_length = lws_zalloc(sizeof(int) * count_params);
2889 if (!spa->param_length)
2892 lwsl_notice("%s: Created SPA %p\n", __func__, spa);
2897 lws_urldecode_s_destroy(spa->s);
2899 lws_free(spa->params);
2901 lws_free(spa->storage);
2908 LWS_VISIBLE LWS_EXTERN int
2909 lws_spa_process(struct lws_spa *ludspa, const char *in, int len)
2912 lwsl_err("%s: NULL spa\n", __func__);
2915 return lws_urldecode_s_process(ludspa->s, in, len);
2918 LWS_VISIBLE LWS_EXTERN int
2919 lws_spa_get_length(struct lws_spa *ludspa, int n)
2921 if (n >= ludspa->count_params)
2924 return ludspa->param_length[n];
2927 LWS_VISIBLE LWS_EXTERN const char *
2928 lws_spa_get_string(struct lws_spa *ludspa, int n)
2930 if (n >= ludspa->count_params)
2933 return ludspa->params[n];
2936 LWS_VISIBLE LWS_EXTERN int
2937 lws_spa_finalize(struct lws_spa *spa)
2940 lws_urldecode_s_destroy(spa->s);
2947 LWS_VISIBLE LWS_EXTERN int
2948 lws_spa_destroy(struct lws_spa *spa)
2952 lwsl_notice("%s: destroy spa %p\n", __func__, spa);
2955 lws_urldecode_s_destroy(spa->s);
2957 lwsl_debug("%s\n", __func__);
2959 lws_free(spa->param_length);
2960 lws_free(spa->params);
2961 lws_free(spa->storage);
2967 LWS_VISIBLE LWS_EXTERN int
2968 lws_chunked_html_process(struct lws_process_html_args *args,
2969 struct lws_process_html_state *s)
2971 char *sp, buffer[32];
2975 /* do replacements */
2977 old_len = args->len;
2980 while (sp < args->p + old_len) {
2982 if (args->len + 7 >= args->max_len) {
2983 lwsl_err("Used up interpret padding\n");
2987 if ((!s->pos && *sp == '$') || s->pos) {
2988 int hits = 0, hit = 0;
2992 s->swallow[s->pos++] = *sp;
2993 if (s->pos == sizeof(s->swallow) - 1)
2995 for (n = 0; n < s->count_vars; n++)
2996 if (!strncmp(s->swallow, s->vars[n], s->pos)) {
3002 s->swallow[s->pos] = '\0';
3003 memcpy(s->start, s->swallow, s->pos);
3009 if (hits == 1 && s->pos == strlen(s->vars[hit])) {
3010 pc = s->replace(s->data, hit);
3014 s->swallow[s->pos] = '\0';
3016 memmove(s->start + n,
3018 old_len - (sp - args->p));
3019 old_len += (n - s->pos) + 1;
3021 memcpy(s->start, pc, n);
3035 /* no space left for final chunk trailer */
3036 if (args->final && args->len + 7 >= args->max_len)
3039 n = sprintf(buffer, "%X\x0d\x0a", args->len);
3042 memcpy(args->p, buffer, n);
3046 sp = args->p + args->len;
3056 sp = args->p + args->len;