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;
45 /* set up our external listening socket we serve on */
47 if (info->port == CONTEXT_PORT_NO_LISTEN)
50 vh = vhost->context->vhost_list;
52 if (vh->listen_port == info->port) {
53 if ((!info->iface && !vh->iface) ||
54 (info->iface && vh->iface &&
55 !strcmp(info->iface, vh->iface))) {
56 vhost->listen_port = info->port;
57 vhost->iface = info->iface;
58 lwsl_notice(" using listen skt from vhost %s\n",
67 #if defined(__linux__)
68 limit = vhost->context->count_threads;
71 for (m = 0; m < limit; m++) {
72 #ifdef LWS_USE_UNIX_SOCK
73 if (LWS_UNIX_SOCK_ENABLED(vhost))
74 sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
78 if (LWS_IPV6_ENABLED(vhost))
79 sockfd = socket(AF_INET6, SOCK_STREAM, 0);
82 sockfd = socket(AF_INET, SOCK_STREAM, 0);
86 #if defined(LWS_WITH_ESP8266)
87 sockfd = esp8266_create_tcp_listen_socket(vhost);
88 if (!lws_sockfd_valid(sockfd)) {
91 sockfd = mbed3_create_tcp_stream_socket();
92 if (!lws_sockfd_valid(sockfd)) {
95 lwsl_err("ERROR opening socket\n");
101 * allow us to restart even if old sockets in TIME_WAIT
103 if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
104 (const void *)&opt, sizeof(opt)) < 0) {
105 compatible_close(sockfd);
109 #if defined(LWS_USE_IPV6) && defined(IPV6_V6ONLY)
110 if (LWS_IPV6_ENABLED(vhost)) {
111 if (vhost->options & LWS_SERVER_OPTION_IPV6_V6ONLY_MODIFY) {
112 int value = (vhost->options & LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE) ? 1 : 0;
113 if (setsockopt(sockfd, SOL_IPV6, IPV6_V6ONLY,
114 (const void*)&value, sizeof(value)) < 0) {
115 compatible_close(sockfd);
122 #if defined(__linux__) && defined(SO_REUSEPORT) && LWS_MAX_SMP > 1
123 if (vhost->context->count_threads > 1)
124 if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT,
125 (const void *)&opt, sizeof(opt)) < 0) {
126 compatible_close(sockfd);
131 lws_plat_set_socket_options(vhost, sockfd);
134 n = lws_socket_bind(vhost, sockfd, info->port, info->iface);
139 vhost->listen_port = info->port;
140 vhost->iface = info->iface;
142 wsi = lws_zalloc(sizeof(struct lws));
144 lwsl_err("Out of mem\n");
147 wsi->context = vhost->context;
149 wsi->mode = LWSCM_SERVER_LISTENER;
150 wsi->protocol = vhost->protocols;
155 vhost->context->pt[m].wsi_listening = wsi;
156 if (insert_wsi_socket_into_fds(vhost->context, wsi))
159 vhost->context->count_wsi_allocated++;
160 vhost->lserv_wsi = wsi;
163 listen(wsi->sock, LWS_SOMAXCONN);
164 } /* for each thread able to independently listen */
166 #if defined(LWS_WITH_ESP8266)
167 esp8266_tcp_stream_bind(wsi->sock, info->port, wsi);
169 mbed3_tcp_stream_bind(wsi->sock, info->port, wsi);
172 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS)) {
173 #ifdef LWS_USE_UNIX_SOCK
174 if (LWS_UNIX_SOCK_ENABLED(vhost))
175 lwsl_notice(" Listening on \"%s\"\n", info->iface);
178 lwsl_notice(" Listening on port %d\n", info->port);
184 compatible_close(sockfd);
190 _lws_server_listen_accept_flow_control(struct lws *twsi, int on)
192 struct lws_context_per_thread *pt = &twsi->context->pt[(int)twsi->tsi];
193 struct lws *wsi = pt->wsi_listening;
196 if (!wsi || twsi->context->being_destroyed)
199 lwsl_debug("%s: Thr %d: LISTEN wsi %p: state %d\n",
200 __func__, twsi->tsi, (void *)wsi, on);
203 n = lws_change_pollfd(wsi, 0, LWS_POLLIN);
205 n = lws_change_pollfd(wsi, LWS_POLLIN, 0);
210 #if defined(LWS_WITH_ESP8266)
212 #define strchr ets_strchr
216 lws_select_vhost(struct lws_context *context, int port, const char *servername)
218 struct lws_vhost *vhost = context->vhost_list;
222 n = strlen(servername);
224 p = strchr(servername, ':');
226 colon = p - servername;
228 /* first try exact matches */
231 if (port == vhost->listen_port &&
232 !strncmp(vhost->name, servername, colon)) {
233 lwsl_info("SNI: Found: %s\n", servername);
236 vhost = vhost->vhost_next;
240 * if no exact matches, try matching *.vhost-name
241 * unintentional matches are possible but resolve to x.com for *.x.com
242 * which is reasonable. If exact match exists we already chose it and
243 * never reach here. SSL will still fail it if the cert doesn't allow
247 vhost = context->vhost_list;
249 m = strlen(vhost->name);
250 if (port == vhost->listen_port &&
252 servername[colon - m - 1] == '.' &&
253 !strncmp(vhost->name, servername + colon - m, m)) {
254 lwsl_info("SNI: Found %s on wildcard: %s\n",
255 servername, vhost->name);
258 vhost = vhost->vhost_next;
264 LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
265 lws_vhost_name_to_protocol(struct lws_vhost *vh, const char *name)
269 for (n = 0; n < vh->count_protocols; n++)
270 if (!strcmp(name, vh->protocols[n].name))
271 return &vh->protocols[n];
276 LWS_VISIBLE LWS_EXTERN const char *
277 lws_get_mimetype(const char *file, const struct lws_http_mount *m)
279 int n = strlen(file);
280 const struct lws_protocol_vhost_options *pvo = NULL;
283 pvo = m->extra_mimetypes;
288 if (!strcmp(&file[n - 4], ".ico"))
289 return "image/x-icon";
291 if (!strcmp(&file[n - 4], ".gif"))
294 if (!strcmp(&file[n - 3], ".js"))
295 return "text/javascript";
297 if (!strcmp(&file[n - 4], ".png"))
300 if (!strcmp(&file[n - 4], ".jpg"))
303 if (!strcmp(&file[n - 3], ".gz"))
304 return "application/gzip";
306 if (!strcmp(&file[n - 4], ".JPG"))
309 if (!strcmp(&file[n - 5], ".html"))
312 if (!strcmp(&file[n - 4], ".css"))
315 if (!strcmp(&file[n - 4], ".txt"))
318 if (!strcmp(&file[n - 4], ".ttf"))
319 return "application/x-font-ttf";
321 if (!strcmp(&file[n - 5], ".woff"))
322 return "application/font-woff";
324 if (!strcmp(&file[n - 4], ".xml"))
325 return "application/xml";
328 if (!strcmp(&file[n - strlen(pvo->name)], pvo->name))
338 lws_http_serve(struct lws *wsi, char *uri, const char *origin,
339 const struct lws_http_mount *m)
341 const struct lws_protocol_vhost_options *pvo = m->interpret;
342 struct lws_process_html_args args;
343 const char *mimetype;
344 #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP8266)
348 char path[256], sym[512];
349 unsigned char *p = (unsigned char *)sym + 32 + LWS_PRE, *start = p;
350 unsigned char *end = p + sizeof(sym) - 32 - LWS_PRE;
351 #if !defined(WIN32) && LWS_POSIX
356 snprintf(path, sizeof(path) - 1, "%s/%s", origin, uri);
358 #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP8266)
362 if (stat(path, &st)) {
363 lwsl_info("unable to stat %s\n", path);
367 lwsl_debug(" %s mode %d\n", path, S_IFMT & st.st_mode);
368 #if !defined(WIN32) && LWS_POSIX
369 if ((S_IFMT & st.st_mode) == S_IFLNK) {
370 len = readlink(path, sym, sizeof(sym) - 1);
372 lwsl_err("Failed to read link %s\n", path);
376 lwsl_debug("symlink %s -> %s\n", path, sym);
377 snprintf(path, sizeof(path) - 1, "%s", sym);
380 if ((S_IFMT & st.st_mode) == S_IFDIR) {
381 lwsl_debug("default filename append to dir\n");
382 snprintf(path, sizeof(path) - 1, "%s/%s/index.html",
386 } while ((S_IFMT & st.st_mode) != S_IFREG && spin < 5);
389 lwsl_err("symlink loop %s \n", path);
391 n = sprintf(sym, "%08lX%08lX", (unsigned long)st.st_size,
392 (unsigned long)st.st_mtime);
394 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_NONE_MATCH)) {
396 * he thinks he has some version of it already,
397 * check if the tag matches
399 if (!strcmp(sym, lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_IF_NONE_MATCH))) {
401 lwsl_debug("%s: ETAG match %s %s\n", __func__,
404 /* we don't need to send the payload */
405 if (lws_add_http_header_status(wsi, 304, &p, end))
407 if (lws_add_http_header_by_token(wsi,
409 (unsigned char *)sym, n, &p, end))
411 if (lws_finalize_http_header(wsi, &p, end))
414 n = lws_write(wsi, start, p - start,
415 LWS_WRITE_HTTP_HEADERS);
416 if (n != (p - start)) {
417 lwsl_err("_write returned %d from %d\n", n, p - start);
421 return lws_http_transaction_completed(wsi);
425 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ETAG,
426 (unsigned char *)sym, n, &p, end))
430 mimetype = lws_get_mimetype(path, m);
432 lwsl_err("unknown mimetype for %s\n", path);
436 wsi->sending_chunked = 0;
439 * check if this is in the list of file suffixes to be interpreted by
444 if (n > (int)strlen(pvo->name) &&
445 !strcmp(&path[n - strlen(pvo->name)], pvo->name)) {
446 wsi->sending_chunked = 1;
447 wsi->protocol_interpret_idx = (char)(long)pvo->value;
448 lwsl_info("want %s interpreted by %s\n", path,
449 wsi->vhost->protocols[(int)(long)(pvo->value)].name);
450 wsi->protocol = &wsi->vhost->protocols[(int)(long)(pvo->value)];
451 if (lws_ensure_user_space(wsi))
459 const struct lws_protocols *pp = lws_vhost_name_to_protocol(
460 wsi->vhost, m->protocol);
462 if (lws_bind_protocol(wsi, pp))
465 args.max_len = end - p;
466 if (pp->callback(wsi, LWS_CALLBACK_ADD_HEADERS,
467 wsi->user_space, &args, 0))
469 p = (unsigned char *)args.p;
472 n = lws_serve_http_file(wsi, path, mimetype, (char *)start, p - start);
474 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
475 return -1; /* error or can't reuse connection: close the socket */
483 const struct lws_http_mount *
484 lws_find_mount(struct lws *wsi, const char *uri_ptr, int uri_len)
486 const struct lws_http_mount *hm, *hit = NULL;
489 hm = wsi->vhost->mount_list;
491 if (uri_len >= hm->mountpoint_len &&
492 !strncmp(uri_ptr, hm->mountpoint, hm->mountpoint_len) &&
493 (uri_ptr[hm->mountpoint_len] == '\0' ||
494 uri_ptr[hm->mountpoint_len] == '/' ||
495 hm->mountpoint_len == 1)
497 if (hm->origin_protocol == LWSMPRO_CALLBACK ||
498 ((hm->origin_protocol == LWSMPRO_CGI ||
499 lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI) ||
501 hm->mountpoint_len > best)) {
502 best = hm->mountpoint_len;
513 lws_http_action(struct lws *wsi)
515 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
516 enum http_connection_type connection_type;
517 enum http_version request_version;
518 char content_length_str[32];
519 struct lws_process_html_args args;
520 const struct lws_http_mount *hit = NULL;
521 unsigned int n, count = 0;
522 char http_version_str[10];
523 char http_conn_str[20];
524 int http_version_len;
525 char *uri_ptr = NULL, *s;
529 static const unsigned char methods[] = {
532 WSI_TOKEN_OPTIONS_URI,
535 WSI_TOKEN_DELETE_URI,
537 WSI_TOKEN_HTTP_COLON_PATH,
540 #if defined(_DEBUG) || defined(LWS_WITH_ACCESS_LOG)
541 static const char * const method_names[] = {
542 "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
548 static const char * const oprot[] = {
549 "http://", "https://"
552 /* it's not websocket.... shall we accept it as http? */
554 for (n = 0; n < ARRAY_SIZE(methods); n++)
555 if (lws_hdr_total_length(wsi, methods[n]))
558 lwsl_warn("Missing URI in HTTP request\n");
563 lwsl_warn("multiple methods?\n");
567 if (lws_ensure_user_space(wsi))
570 for (n = 0; n < ARRAY_SIZE(methods); n++)
571 if (lws_hdr_total_length(wsi, methods[n])) {
572 uri_ptr = lws_hdr_simple_ptr(wsi, methods[n]);
573 uri_len = lws_hdr_total_length(wsi, methods[n]);
574 lwsl_info("Method: %s request for '%s'\n",
575 method_names[n], uri_ptr);
582 /* we insist on absolute paths */
584 if (uri_ptr[0] != '/') {
585 lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
590 /* HTTP header had a content length? */
592 wsi->u.http.content_length = 0;
593 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) ||
594 lws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI) ||
595 lws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI))
596 wsi->u.http.content_length = 100 * 1024 * 1024;
598 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
599 lws_hdr_copy(wsi, content_length_str,
600 sizeof(content_length_str) - 1,
601 WSI_TOKEN_HTTP_CONTENT_LENGTH);
602 wsi->u.http.content_length = atoi(content_length_str);
605 if (wsi->http2_substream) {
606 wsi->u.http.request_version = HTTP_VERSION_2;
608 /* http_version? Default to 1.0, override with token: */
609 request_version = HTTP_VERSION_1_0;
611 /* Works for single digit HTTP versions. : */
612 http_version_len = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP);
613 if (http_version_len > 7) {
614 lws_hdr_copy(wsi, http_version_str,
615 sizeof(http_version_str) - 1, WSI_TOKEN_HTTP);
616 if (http_version_str[5] == '1' && http_version_str[7] == '1')
617 request_version = HTTP_VERSION_1_1;
619 wsi->u.http.request_version = request_version;
621 /* HTTP/1.1 defaults to "keep-alive", 1.0 to "close" */
622 if (request_version == HTTP_VERSION_1_1)
623 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
625 connection_type = HTTP_CONNECTION_CLOSE;
627 /* Override default if http "Connection:" header: */
628 if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) {
629 lws_hdr_copy(wsi, http_conn_str, sizeof(http_conn_str) - 1,
630 WSI_TOKEN_CONNECTION);
631 http_conn_str[sizeof(http_conn_str) - 1] = '\0';
632 if (!strcasecmp(http_conn_str, "keep-alive"))
633 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
635 if (!strcasecmp(http_conn_str, "close"))
636 connection_type = HTTP_CONNECTION_CLOSE;
638 wsi->u.http.connection_type = connection_type;
641 n = wsi->protocol->callback(wsi, LWS_CALLBACK_FILTER_HTTP_CONNECTION,
642 wsi->user_space, uri_ptr, uri_len);
644 lwsl_info("LWS_CALLBACK_HTTP closing\n");
649 * if there is content supposed to be coming,
650 * put a timeout on it having arrived
652 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
653 wsi->context->timeout_secs);
654 #ifdef LWS_OPENSSL_SUPPORT
655 if (wsi->redirect_to_https) {
657 * we accepted http:// only so we could redirect to
658 * https://, so issue the redirect. Create the redirection
659 * URI from the host: header and ignore the path part
661 unsigned char *start = pt->serv_buf + LWS_PRE, *p = start,
664 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
667 n = sprintf((char *)end, "https://%s/",
668 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
670 n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
675 return lws_http_transaction_completed(wsi);
679 #ifdef LWS_WITH_ACCESS_LOG
681 * Produce Apache-compatible log string for wsi, like this:
683 * 2.31.234.19 - - [27/Mar/2016:03:22:44 +0800]
684 * "GET /aep-screen.png HTTP/1.1"
685 * 200 152987 "https://libwebsockets.org/index.html"
686 * "Mozilla/5.0 (Macint... Chrome/49.0.2623.87 Safari/537.36"
690 static const char * const hver[] = {
691 "http/1.0", "http/1.1", "http/2"
694 char ads[INET6_ADDRSTRLEN];
696 char ads[INET_ADDRSTRLEN];
701 time_t t = time(NULL);
704 if (wsi->access_log_pending)
707 wsi->access_log.header_log = lws_malloc(l);
708 if (wsi->access_log.header_log) {
712 strftime(da, sizeof(da), "%d/%b/%Y:%H:%M:%S %z", tmp);
714 strcpy(da, "01/Jan/1970:00:00:00 +0000");
716 pa = lws_get_peer_simple(wsi, ads, sizeof(ads));
721 me = method_names[meth];
725 snprintf(wsi->access_log.header_log, l,
726 "%s - - [%s] \"%s %s %s\"",
728 hver[wsi->u.http.request_version]);
730 l = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT);
732 wsi->access_log.user_agent = lws_malloc(l + 2);
733 if (wsi->access_log.user_agent)
734 lws_hdr_copy(wsi, wsi->access_log.user_agent,
735 l + 1, WSI_TOKEN_HTTP_USER_AGENT);
737 lwsl_err("OOM getting user agent\n");
739 wsi->access_log_pending = 1;
744 /* can we serve it from the mount list? */
746 hit = lws_find_mount(wsi, uri_ptr, uri_len);
748 /* deferred cleanup and reset to protocols[0] */
750 lwsl_info("no hit\n");
752 if (lws_bind_protocol(wsi, &wsi->vhost->protocols[0]))
755 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
756 wsi->user_space, uri_ptr, uri_len);
761 s = uri_ptr + hit->mountpoint_len;
765 args.max_len = hit->auth_mask;
766 args.final = 0; /* used to signal callback dealt with it */
768 n = wsi->protocol->callback(wsi, LWS_CALLBACK_CHECK_ACCESS_RIGHTS,
769 wsi->user_space, &args, 0);
771 lws_return_http_status(wsi, HTTP_STATUS_UNAUTHORIZED,
775 if (args.final) /* callback completely handled it well */
779 * if we have a mountpoint like https://xxx.com/yyy
780 * there is an implied / at the end for our purposes since
781 * we can only mount on a "directory".
783 * But if we just go with that, the browser cannot understand
784 * that he is actually looking down one "directory level", so
785 * even though we give him /yyy/abc.html he acts like the
786 * current directory level is /. So relative urls like "x.png"
787 * wrongly look outside the mountpoint.
789 * Therefore if we didn't come in on a url with an explicit
790 * / at the end, we must redirect to add it so the browser
791 * understands he is one "directory level" down.
793 if ((hit->mountpoint_len > 1 ||
794 (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
795 hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&
797 (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
798 hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&
799 (hit->origin_protocol != LWSMPRO_CGI &&
800 hit->origin_protocol != LWSMPRO_CALLBACK //&&
801 //hit->protocol == NULL
803 unsigned char *start = pt->serv_buf + LWS_PRE,
804 *p = start, *end = p + 512;
806 lwsl_debug("Doing 301 '%s' org %s\n", s, hit->origin);
808 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
811 /* > at start indicates deal with by redirect */
812 if (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
813 hit->origin_protocol == LWSMPRO_REDIR_HTTPS)
814 n = snprintf((char *)end, 256, "%s%s",
815 oprot[hit->origin_protocol & 1],
818 n = snprintf((char *)end, 256,
819 "%s%s%s/", oprot[lws_is_ssl(wsi)],
820 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST),
823 n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
828 return lws_http_transaction_completed(wsi);
832 * A particular protocol callback is mounted here?
834 * For the duration of this http transaction, bind us to the
835 * associated protocol
837 if (hit->origin_protocol == LWSMPRO_CALLBACK || hit->protocol) {
838 const struct lws_protocols *pp;
839 const char *name = hit->origin;
841 name = hit->protocol;
843 pp = lws_vhost_name_to_protocol(wsi->vhost, name);
846 lwsl_err("Unable to find plugin '%s'\n",
851 if (lws_bind_protocol(wsi, pp))
854 if (hit->cgienv && wsi->protocol->callback(wsi,
855 LWS_CALLBACK_HTTP_PMO,
856 wsi->user_space, (void *)hit->cgienv, 0))
859 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) {
860 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
862 uri_ptr + hit->mountpoint_len,
863 uri_len - hit->mountpoint_len);
869 /* did we hit something with a cgi:// origin? */
870 if (hit->origin_protocol == LWSMPRO_CGI) {
871 const char *cmd[] = {
872 NULL, /* replace with cgi path */
875 unsigned char *p, *end, buffer[256];
877 lwsl_debug("%s: cgi\n", __func__);
878 cmd[0] = hit->origin;
881 if (hit->cgi_timeout)
882 n = hit->cgi_timeout;
884 n = lws_cgi(wsi, cmd, hit->mountpoint_len, n,
887 lwsl_err("%s: cgi failed\n");
890 p = buffer + LWS_PRE;
891 end = p + sizeof(buffer) - LWS_PRE;
893 if (lws_add_http_header_status(wsi, 200, &p, end))
895 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
896 (unsigned char *)"close", 5, &p, end))
898 n = lws_write(wsi, buffer + LWS_PRE,
899 p - (buffer + LWS_PRE),
900 LWS_WRITE_HTTP_HEADERS);
907 if (s[0] == '\0' || (n == 1 && s[n - 1] == '/'))
908 s = (char *)hit->def;
912 wsi->cache_secs = hit->cache_max_age;
913 wsi->cache_reuse = hit->cache_reusable;
914 wsi->cache_revalidate = hit->cache_revalidate;
915 wsi->cache_intermediaries = hit->cache_intermediaries;
917 n = lws_http_serve(wsi, s, hit->origin, hit);
920 * lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
923 const struct lws_protocols *pp = lws_vhost_name_to_protocol(
924 wsi->vhost, hit->protocol);
926 if (lws_bind_protocol(wsi, pp))
929 n = pp->callback(wsi, LWS_CALLBACK_HTTP,
931 uri_ptr + hit->mountpoint_len,
932 uri_len - hit->mountpoint_len);
934 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
935 wsi->user_space, uri_ptr, uri_len);
940 lwsl_info("LWS_CALLBACK_HTTP closing\n");
949 * If we're not issuing a file, check for content_length or
950 * HTTP keep-alive. No keep-alive header allocation for
951 * ISSUING_FILE, as this uses HTTP/1.0.
953 * In any case, return 0 and let lws_read decide how to
954 * proceed based on state
956 if (wsi->state != LWSS_HTTP_ISSUING_FILE)
957 /* Prepare to read body if we have a content length: */
958 if (wsi->u.http.content_length > 0)
959 wsi->state = LWSS_HTTP_BODY;
964 /* we're closing, losing some rx is OK */
965 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
966 // lwsl_notice("%s: drop1\n", __func__);
967 lws_header_table_detach(wsi, 1);
973 lws_bind_protocol(struct lws *wsi, const struct lws_protocols *p)
975 // if (wsi->protocol == p)
979 wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_DROP_PROTOCOL,
980 wsi->user_space, NULL, 0);
981 if (!wsi->user_space_externally_allocated)
982 lws_free_set_NULL(wsi->user_space);
988 if (lws_ensure_user_space(wsi))
991 if (wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_BIND_PROTOCOL,
992 wsi->user_space, NULL, 0))
1000 lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len)
1002 struct lws_context *context = lws_get_context(wsi);
1003 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1004 struct _lws_header_related hdr;
1005 struct allocated_headers *ah;
1006 int protocol_len, n = 0, hit;
1007 char protocol_list[128];
1008 char protocol_name[64];
1011 if (len >= 10000000) {
1012 lwsl_err("%s: assert: len %ld\n", __func__, (long)len);
1016 if (!wsi->u.hdr.ah) {
1017 lwsl_err("%s: assert: NULL ah\n", __func__);
1022 wsi->more_rx_waiting = !!len;
1024 if (wsi->mode != LWSCM_HTTP_SERVING &&
1025 wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED) {
1026 lwsl_err("%s: bad wsi mode %d\n", __func__, wsi->mode);
1030 if (lws_parse(wsi, *(*buf)++)) {
1031 lwsl_info("lws_parse failed\n");
1035 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
1038 lwsl_parser("%s: lws_parse sees parsing complete\n", __func__);
1039 lwsl_debug("%s: wsi->more_rx_waiting=%d\n", __func__,
1040 wsi->more_rx_waiting);
1044 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
1045 struct lws_vhost *vhost = lws_select_vhost(
1046 context, wsi->vhost->listen_port,
1047 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
1052 lwsl_info("no host\n");
1054 wsi->vhost->trans++;
1055 if (!wsi->conn_stat_done) {
1057 wsi->conn_stat_done = 1;
1060 wsi->mode = LWSCM_PRE_WS_SERVING_ACCEPT;
1061 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1063 /* is this websocket protocol or normal http 1.0? */
1065 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
1066 if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
1068 wsi->vhost->ws_upgrades++;
1069 lwsl_info("Upgrade to ws\n");
1072 #ifdef LWS_USE_HTTP2
1073 if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
1075 wsi->vhost->http2_upgrades++;
1076 lwsl_info("Upgrade to h2c\n");
1080 lwsl_info("Unknown upgrade\n");
1081 /* dunno what he wanted to upgrade to */
1085 /* no upgrade ack... he remained as HTTP */
1087 lwsl_info("No upgrade\n");
1090 lws_union_transition(wsi, LWSCM_HTTP_SERVING_ACCEPTED);
1091 wsi->state = LWSS_HTTP;
1092 wsi->u.http.fd = LWS_INVALID_FILE;
1094 /* expose it at the same offset as u.hdr */
1095 wsi->u.http.ah = ah;
1096 lwsl_debug("%s: wsi %p: ah %p\n", __func__, (void *)wsi,
1097 (void *)wsi->u.hdr.ah);
1099 n = lws_http_action(wsi);
1103 #ifdef LWS_USE_HTTP2
1105 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) {
1106 lwsl_info("missing http2_settings\n");
1110 lwsl_info("h2c upgrade...\n");
1112 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS);
1113 /* convert the peer's HTTP-Settings */
1114 n = lws_b64_decode_string(p, protocol_list,
1115 sizeof(protocol_list));
1117 lwsl_parser("HTTP2_SETTINGS too long\n");
1121 /* adopt the header info */
1125 lws_union_transition(wsi, LWSCM_HTTP2_SERVING);
1127 /* http2 union member has http union struct at start */
1128 wsi->u.http.ah = ah;
1130 lws_http2_init(&wsi->u.http2.peer_settings);
1131 lws_http2_init(&wsi->u.http2.my_settings);
1135 lws_http2_interpret_settings_payload(&wsi->u.http2.peer_settings,
1136 (unsigned char *)protocol_list, n);
1138 strcpy(protocol_list,
1139 "HTTP/1.1 101 Switching Protocols\x0d\x0a"
1140 "Connection: Upgrade\x0d\x0a"
1141 "Upgrade: h2c\x0d\x0a\x0d\x0a");
1142 n = lws_issue_raw(wsi, (unsigned char *)protocol_list,
1143 strlen(protocol_list));
1144 if (n != strlen(protocol_list)) {
1145 lwsl_debug("http2 switch: ERROR writing to socket\n");
1149 wsi->state = LWSS_HTTP2_AWAIT_CLIENT_PREFACE;
1156 lwsl_err("NULL protocol at lws_read\n");
1161 * Select the first protocol we support from the list
1162 * the client sent us.
1164 * Copy it to remove header fragmentation
1167 if (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1,
1168 WSI_TOKEN_PROTOCOL) < 0) {
1169 lwsl_err("protocol list too long");
1173 protocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
1174 protocol_list[protocol_len] = '\0';
1178 while (*p && !hit) {
1180 while (n < sizeof(protocol_name) - 1 && *p && *p !=',')
1181 protocol_name[n++] = *p++;
1182 protocol_name[n] = '\0';
1186 lwsl_info("checking %s\n", protocol_name);
1189 while (wsi->vhost->protocols[n].callback) {
1190 if (wsi->vhost->protocols[n].name &&
1191 !strcmp(wsi->vhost->protocols[n].name,
1193 wsi->protocol = &wsi->vhost->protocols[n];
1202 /* we didn't find a protocol he wanted? */
1205 if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL)) {
1206 lwsl_info("No protocol from \"%s\" supported\n",
1211 * some clients only have one protocol and
1212 * do not send the protocol list header...
1213 * allow it and match to the vhost's default
1214 * protocol (which itself defaults to zero)
1216 lwsl_info("defaulting to prot handler %d\n",
1217 wsi->vhost->default_protocol_index);
1219 wsi->protocol = &wsi->vhost->protocols[
1220 (int)wsi->vhost->default_protocol_index];
1223 /* allocate wsi->user storage */
1224 if (lws_ensure_user_space(wsi))
1228 * Give the user code a chance to study the request and
1229 * have the opportunity to deny it
1231 if ((wsi->protocol->callback)(wsi,
1232 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
1234 lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) {
1235 lwsl_warn("User code denied connection\n");
1240 * Perform the handshake according to the protocol version the
1244 switch (wsi->ietf_spec_revision) {
1246 lwsl_parser("lws_parse calling handshake_04\n");
1247 if (handshake_0405(context, wsi)) {
1248 lwsl_info("hs0405 has failed the connection\n");
1254 lwsl_info("Unknown client spec version %d\n",
1255 wsi->ietf_spec_revision);
1260 * stitch protocol choice into the vh protocol linked list
1261 * We always insert ourselves at the start of the list
1266 //lwsl_err("%s: pre insert vhost start wsi %p, that wsi prev == %p\n",
1268 // wsi->vhost->same_vh_protocol_list[n],
1269 // wsi->same_vh_protocol_prev);
1270 wsi->same_vh_protocol_prev = /* guy who points to us */
1271 &wsi->vhost->same_vh_protocol_list[n];
1272 wsi->same_vh_protocol_next = /* old first guy is our next */
1273 wsi->vhost->same_vh_protocol_list[n];
1274 /* we become the new first guy */
1275 wsi->vhost->same_vh_protocol_list[n] = wsi;
1277 if (wsi->same_vh_protocol_next)
1278 /* old first guy points back to us now */
1279 wsi->same_vh_protocol_next->same_vh_protocol_prev =
1280 &wsi->same_vh_protocol_next;
1284 /* we are upgrading to ws, so http/1.1 and keepalive +
1285 * pipelined header considerations about keeping the ah around
1286 * no longer apply. However it's common for the first ws
1287 * protocol data to have been coalesced with the browser
1288 * upgrade request and to already be in the ah rx buffer.
1291 lwsl_info("%s: %p: inheriting ah in ws mode (rxpos:%d, rxlen:%d)\n",
1292 __func__, wsi, wsi->u.hdr.ah->rxpos,
1293 wsi->u.hdr.ah->rxlen);
1297 lws_union_transition(wsi, LWSCM_WS_SERVING);
1299 * first service is WS mode will notice this, use the RX and
1300 * then detach the ah (caution: we are not in u.hdr union
1301 * mode any more then... ah_temp member is at start the same
1304 * Because rxpos/rxlen shows something in the ah, we will get
1305 * service guaranteed next time around the event loop
1307 * All union members begin with hdr, so we can use it even
1308 * though we transitioned to ws union mode (the ah detach
1309 * code uses it anyway).
1314 lws_restart_ws_ping_pong_timer(wsi);
1317 * create the frame buffer for this connection according to the
1318 * size mentioned in the protocol definition. If 0 there, use
1319 * a big default for compatibility
1322 n = wsi->protocol->rx_buffer_size;
1324 n = context->pt_serv_buf_size;
1326 wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
1327 if (!wsi->u.ws.rx_ubuf) {
1328 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
1331 wsi->u.ws.rx_ubuf_alloc = n;
1332 lwsl_debug("Allocating RX buffer %d\n", n);
1334 if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF,
1335 (const char *)&n, sizeof n)) {
1336 lwsl_warn("Failed to set SNDBUF to %d", n);
1341 lwsl_parser("accepted v%02d connection\n",
1342 wsi->ietf_spec_revision);
1344 /* notify user code that we're ready to roll */
1346 if (wsi->protocol->callback)
1347 if (wsi->protocol->callback(wsi, LWS_CALLBACK_ESTABLISHED,
1349 #ifdef LWS_OPENSSL_SUPPORT
1357 /* !!! drop ah unreservedly after ESTABLISHED */
1358 if (!wsi->more_rx_waiting) {
1359 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1361 //lwsl_notice("%p: dropping ah EST\n", wsi);
1362 lws_header_table_detach(wsi, 1);
1366 } /* while all chars are handled */
1371 /* drop the header info */
1372 /* we're closing, losing some rx is OK */
1373 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1374 //lwsl_notice("%s: drop2\n", __func__);
1375 lws_header_table_detach(wsi, 1);
1381 lws_get_idlest_tsi(struct lws_context *context)
1383 unsigned int lowest = ~0;
1384 int n = 0, hit = -1;
1386 for (; n < context->count_threads; n++) {
1387 if ((unsigned int)context->pt[n].fds_count !=
1388 context->fd_limit_per_thread - 1 &&
1389 (unsigned int)context->pt[n].fds_count < lowest) {
1390 lowest = context->pt[n].fds_count;
1399 lws_create_new_server_wsi(struct lws_vhost *vhost)
1401 struct lws *new_wsi;
1402 int n = lws_get_idlest_tsi(vhost->context);
1405 lwsl_err("no space for new conn\n");
1409 new_wsi = lws_zalloc(sizeof(struct lws));
1410 if (new_wsi == NULL) {
1411 lwsl_err("Out of memory for new connection\n");
1416 lwsl_info("Accepted %p to tsi %d\n", new_wsi, new_wsi->tsi);
1418 new_wsi->vhost = vhost;
1419 new_wsi->context = vhost->context;
1420 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1421 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1423 /* intialize the instance struct */
1425 new_wsi->state = LWSS_HTTP;
1426 new_wsi->mode = LWSCM_HTTP_SERVING;
1427 new_wsi->hdr_parsing_completed = 0;
1429 #ifdef LWS_OPENSSL_SUPPORT
1430 new_wsi->use_ssl = LWS_SSL_ENABLED(vhost);
1434 * these can only be set once the protocol is known
1435 * we set an unestablished connection's protocol pointer
1436 * to the start of the supported list, so it can look
1437 * for matching ones during the handshake
1439 new_wsi->protocol = vhost->protocols;
1440 new_wsi->user_space = NULL;
1441 new_wsi->ietf_spec_revision = 0;
1442 new_wsi->sock = LWS_SOCK_INVALID;
1443 vhost->context->count_wsi_allocated++;
1446 * outermost create notification for wsi
1447 * no user_space because no protocol selection
1449 vhost->protocols[0].callback(new_wsi, LWS_CALLBACK_WSI_CREATE,
1455 LWS_VISIBLE int LWS_WARN_UNUSED_RESULT
1456 lws_http_transaction_completed(struct lws *wsi)
1458 int n = NO_PENDING_TIMEOUT;
1460 lws_access_log(wsi);
1462 lwsl_info("%s: wsi %p\n", __func__, wsi);
1463 /* if we can't go back to accept new headers, drop the connection */
1464 if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
1465 lwsl_info("%s: %p: close connection\n", __func__, wsi);
1469 if (lws_bind_protocol(wsi, &wsi->vhost->protocols[0]))
1472 /* otherwise set ourselves up ready to go again */
1473 wsi->state = LWSS_HTTP;
1474 wsi->mode = LWSCM_HTTP_SERVING;
1475 wsi->u.http.content_length = 0;
1476 wsi->u.http.content_remain = 0;
1477 wsi->hdr_parsing_completed = 0;
1478 #ifdef LWS_WITH_ACCESS_LOG
1479 wsi->access_log.sent = 0;
1482 if (wsi->vhost->keepalive_timeout)
1483 n = PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE;
1484 lws_set_timeout(wsi, n, wsi->vhost->keepalive_timeout);
1487 * We already know we are on http1.1 / keepalive and the next thing
1488 * coming will be another header set.
1490 * If there is no pending rx and we still have the ah, drop it and
1491 * reacquire a new ah when the new headers start to arrive. (Otherwise
1492 * we needlessly hog an ah indefinitely.)
1494 * However if there is pending rx and we know from the keepalive state
1495 * that is already at least the start of another header set, simply
1496 * reset the existing header table and keep it.
1498 if (wsi->u.hdr.ah) {
1499 lwsl_info("%s: wsi->more_rx_waiting=%d\n", __func__,
1500 wsi->more_rx_waiting);
1502 if (!wsi->more_rx_waiting) {
1503 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1504 lws_header_table_detach(wsi, 1);
1506 lws_header_table_reset(wsi, 1);
1509 /* If we're (re)starting on headers, need other implied init */
1510 wsi->u.hdr.ues = URIES_IDLE;
1512 lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
1518 lws_adopt_socket_vhost(struct lws_vhost *vh, lws_sockfd_type accept_fd)
1520 struct lws_context *context = vh->context;
1521 struct lws *new_wsi = lws_create_new_server_wsi(vh);
1524 compatible_close(accept_fd);
1528 //lwsl_notice("%s: new wsi %p, sockfd %d, cb %p\n", __func__, new_wsi, accept_fd, context->vhost_list->protocols[0].callback);
1530 new_wsi->sock = accept_fd;
1532 /* the transport is accepted... give him time to negotiate */
1533 lws_set_timeout(new_wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
1534 context->timeout_secs);
1537 #if defined(LWS_WITH_ESP8266)
1538 esp8266_tcp_stream_accept(accept_fd, new_wsi);
1540 mbed3_tcp_stream_accept(accept_fd, new_wsi);
1544 * A new connection was accepted. Give the user a chance to
1545 * set properties of the newly created wsi. There's no protocol
1546 * selected yet so we issue this to protocols[0]
1548 if ((context->vhost_list->protocols[0].callback)(new_wsi,
1549 LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED, NULL, NULL, 0)) {
1550 compatible_close(new_wsi->sock);
1555 lws_libev_accept(new_wsi, new_wsi->sock);
1556 lws_libuv_accept(new_wsi, new_wsi->sock);
1558 if (!LWS_SSL_ENABLED(new_wsi->vhost)) {
1559 if (insert_wsi_socket_into_fds(context, new_wsi)) {
1560 lwsl_err("%s: fail inserting socket\n", __func__);
1564 new_wsi->mode = LWSCM_SSL_INIT;
1565 if (lws_server_socket_service_ssl(new_wsi, accept_fd)) {
1566 lwsl_err("%s: fail ssl negotiation\n", __func__);
1571 if (!lws_header_table_attach(new_wsi, 0))
1572 lwsl_debug("Attached ah immediately\n");
1577 lws_close_free_wsi(new_wsi, LWS_CLOSE_STATUS_NOSTATUS);
1582 LWS_VISIBLE struct lws *
1583 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd)
1585 return lws_adopt_socket_vhost(context->vhost_list, accept_fd);
1588 LWS_VISIBLE LWS_EXTERN struct lws *
1589 lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
1590 const char *readbuf, size_t len)
1592 struct lws *wsi = lws_adopt_socket(context, accept_fd);
1593 struct lws_context_per_thread *pt;
1594 struct allocated_headers *ah;
1595 struct lws_pollfd *pfd;
1603 if (len > sizeof(ah->rx)) {
1604 lwsl_err("%s: rx in too big\n", __func__);
1609 * we can't process the initial read data until we can attach an ah.
1611 * if one is available, get it and place the data in his ah rxbuf...
1612 * wsi with ah that have pending rxbuf get auto-POLLIN service.
1614 * no autoservice because we didn't get a chance to attach the
1615 * readbuf data to wsi or ah yet, and we will do it next if we get
1618 if (wsi->u.hdr.ah || !lws_header_table_attach(wsi, 0)) {
1620 memcpy(ah->rx, readbuf, len);
1624 lwsl_notice("%s: calling service on readbuf ah\n", __func__);
1625 pt = &context->pt[(int)wsi->tsi];
1627 /* unlike a normal connect, we have the headers already
1628 * (or the first part of them anyway).
1629 * libuv won't come back and service us without a network
1630 * event, so we need to do the header service right here.
1632 pfd = &pt->fds[wsi->position_in_fds_table];
1633 pfd->revents |= LWS_POLLIN;
1634 lwsl_err("%s: calling service\n", __func__);
1635 if (lws_service_fd_tsi(context, pfd, wsi->tsi))
1636 /* service closed us */
1641 lwsl_err("%s: deferring handling ah\n", __func__);
1643 * hum if no ah came, we are on the wait list and must defer
1644 * dealing with this until the ah arrives.
1646 * later successful lws_header_table_attach() will apply the
1647 * below to the rx buffer (via lws_header_table_reset()).
1649 wsi->u.hdr.preamble_rx = lws_malloc(len);
1650 if (!wsi->u.hdr.preamble_rx) {
1654 memcpy(wsi->u.hdr.preamble_rx, readbuf, len);
1655 wsi->u.hdr.preamble_rx_len = len;
1660 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1666 lws_server_socket_service(struct lws_context *context, struct lws *wsi,
1667 struct lws_pollfd *pollfd)
1669 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1670 lws_sockfd_type accept_fd = LWS_SOCK_INVALID;
1671 struct allocated_headers *ah;
1673 struct sockaddr_in cli_addr;
1678 // lwsl_notice("%s: mode %d\n", __func__, wsi->mode);
1680 switch (wsi->mode) {
1682 case LWSCM_HTTP_SERVING:
1683 case LWSCM_HTTP_SERVING_ACCEPTED:
1684 case LWSCM_HTTP2_SERVING:
1686 /* handle http headers coming in */
1688 /* pending truncated sends have uber priority */
1690 if (wsi->trunc_len) {
1691 if (!(pollfd->revents & LWS_POLLOUT))
1694 if (lws_issue_raw(wsi, wsi->trunc_alloc +
1696 wsi->trunc_len) < 0)
1699 * we can't afford to allow input processing to send
1700 * something new, so spin around he event loop until
1701 * he doesn't have any partials
1706 /* any incoming data ready? */
1708 if (!(pollfd->revents & pollfd->events & LWS_POLLIN))
1712 * If we previously just did POLLIN when IN and OUT were
1713 * signalled (because POLLIN processing may have used up
1714 * the POLLOUT), don't let that happen twice in a row...
1715 * next time we see the situation favour POLLOUT
1717 #if !defined(LWS_WITH_ESP8266)
1718 if (wsi->favoured_pollin &&
1719 (pollfd->revents & pollfd->events & LWS_POLLOUT)) {
1720 wsi->favoured_pollin = 0;
1724 /* these states imply we MUST have an ah attached */
1726 if (wsi->state == LWSS_HTTP ||
1727 wsi->state == LWSS_HTTP_ISSUING_FILE ||
1728 wsi->state == LWSS_HTTP_HEADERS) {
1729 if (!wsi->u.hdr.ah) {
1731 //lwsl_err("wsi %p: missing ah\n", wsi);
1732 /* no autoservice beacuse we will do it next */
1733 if (lws_header_table_attach(wsi, 0)) {
1734 lwsl_err("wsi %p: failed to acquire ah\n", wsi);
1740 //lwsl_notice("%s: %p: rxpos:%d rxlen:%d\n", __func__, wsi,
1741 // ah->rxpos, ah->rxlen);
1743 /* if nothing in ah rx buffer, get some fresh rx */
1744 if (ah->rxpos == ah->rxlen) {
1745 ah->rxlen = lws_ssl_capable_read(wsi, ah->rx,
1748 //lwsl_notice("%s: wsi %p, ah->rxlen = %d\r\n",
1749 // __func__, wsi, ah->rxlen);
1750 switch (ah->rxlen) {
1752 lwsl_info("%s: read 0 len\n", __func__);
1753 /* lwsl_info(" state=%d\n", wsi->state); */
1754 // if (!wsi->hdr_parsing_completed)
1755 // lws_header_table_detach(wsi);
1757 case LWS_SSL_CAPABLE_ERROR:
1759 case LWS_SSL_CAPABLE_MORE_SERVICE:
1760 ah->rxlen = ah->rxpos = 0;
1765 if (!(ah->rxpos != ah->rxlen && ah->rxlen)) {
1766 lwsl_err("%s: assert: rxpos %d, rxlen %d\n",
1767 __func__, ah->rxpos, ah->rxlen);
1772 /* just ignore incoming if waiting for close */
1773 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
1774 n = lws_read(wsi, ah->rx + ah->rxpos,
1775 ah->rxlen - ah->rxpos);
1776 if (n < 0) /* we closed wsi */
1778 if (wsi->u.hdr.ah) {
1779 if ( wsi->u.hdr.ah->rxlen)
1780 wsi->u.hdr.ah->rxpos += n;
1782 if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen &&
1783 (wsi->mode != LWSCM_HTTP_SERVING &&
1784 wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED &&
1785 wsi->mode != LWSCM_HTTP2_SERVING))
1786 lws_header_table_detach(wsi, 1);
1794 len = lws_ssl_capable_read(wsi, pt->serv_buf,
1795 context->pt_serv_buf_size);
1796 lwsl_notice("%s: wsi %p read %d\r\n", __func__, wsi, len);
1799 lwsl_info("%s: read 0 len\n", __func__);
1800 /* lwsl_info(" state=%d\n", wsi->state); */
1801 // if (!wsi->hdr_parsing_completed)
1802 // lws_header_table_detach(wsi);
1804 case LWS_SSL_CAPABLE_ERROR:
1806 case LWS_SSL_CAPABLE_MORE_SERVICE:
1810 /* just ignore incoming if waiting for close */
1811 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
1813 * this may want to send
1814 * (via HTTP callback for example)
1816 n = lws_read(wsi, pt->serv_buf, len);
1817 if (n < 0) /* we closed wsi */
1820 * he may have used up the
1821 * writability above, if we will defer POLLOUT
1822 * processing in favour of POLLIN, note it
1824 if (pollfd->revents & LWS_POLLOUT)
1825 wsi->favoured_pollin = 1;
1831 /* this handles POLLOUT for http serving fragments */
1833 if (!(pollfd->revents & LWS_POLLOUT))
1837 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
1838 lwsl_notice("%s a\n", __func__);
1842 if (!wsi->hdr_parsing_completed)
1845 if (wsi->state != LWSS_HTTP_ISSUING_FILE) {
1846 n = user_callback_handle_rxflow(wsi->protocol->callback,
1847 wsi, LWS_CALLBACK_HTTP_WRITEABLE,
1848 wsi->user_space, NULL, 0);
1850 lwsl_info("writeable_fail\n");
1856 /* >0 == completion, <0 == error */
1857 n = lws_serve_http_file_fragment(wsi);
1858 if (n < 0 || (n > 0 && lws_http_transaction_completed(wsi))) {
1859 lwsl_info("completed\n");
1865 case LWSCM_SERVER_LISTENER:
1868 /* pollin means a client has connected to us then */
1871 if (!(pollfd->revents & LWS_POLLIN) || !(pollfd->events & LWS_POLLIN))
1874 /* listen socket got an unencrypted connection... */
1876 clilen = sizeof(cli_addr);
1877 lws_latency_pre(context, wsi);
1878 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1880 lws_latency(context, wsi, "listener accept", accept_fd,
1882 if (accept_fd < 0) {
1883 if (LWS_ERRNO == LWS_EAGAIN ||
1884 LWS_ERRNO == LWS_EWOULDBLOCK) {
1885 lwsl_err("accept asks to try again\n");
1888 lwsl_err("ERROR on accept: %s\n", strerror(LWS_ERRNO));
1892 lws_plat_set_socket_options(wsi->vhost, accept_fd);
1894 lwsl_debug("accepted new conn port %u on fd=%d\n",
1895 ntohs(cli_addr.sin_port), accept_fd);
1898 /* not very beautiful... */
1899 accept_fd = (lws_sockfd_type)pollfd;
1902 * look at who we connected to and give user code a chance
1903 * to reject based on client IP. There's no protocol selected
1904 * yet so we issue this to protocols[0]
1906 if ((wsi->vhost->protocols[0].callback)(wsi,
1907 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
1908 NULL, (void *)(long)accept_fd, 0)) {
1909 lwsl_debug("Callback denied network connection\n");
1910 compatible_close(accept_fd);
1914 if (!lws_adopt_socket_vhost(wsi->vhost, accept_fd))
1915 /* already closed cleanly as necessary */
1919 } while (pt->fds_count < context->fd_limit_per_thread - 1 &&
1920 lws_poll_listen_fd(&pt->fds[wsi->position_in_fds_table]) > 0);
1928 if (!lws_server_socket_service_ssl(wsi, accept_fd))
1932 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1938 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
1939 const char *other_headers, int other_headers_len)
1941 static const char * const intermediates[] = { "private", "public" };
1942 struct lws_context *context = lws_get_context(wsi);
1943 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1944 char cache_control[50], *cc = "no-store";
1945 unsigned char *response = pt->serv_buf + LWS_PRE;
1946 unsigned char *p = response;
1947 unsigned char *end = p + context->pt_serv_buf_size - LWS_PRE;
1948 int ret = 0, cclen = 8;
1950 wsi->u.http.fd = lws_plat_file_open(wsi, file, &wsi->u.http.filelen,
1953 if (wsi->u.http.fd == LWS_INVALID_FILE) {
1954 lwsl_err("Unable to open '%s'\n", file);
1959 if (lws_add_http_header_status(wsi, 200, &p, end))
1961 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
1962 (unsigned char *)content_type,
1963 strlen(content_type), &p, end))
1966 if (!wsi->sending_chunked) {
1967 if (lws_add_http_header_content_length(wsi, wsi->u.http.filelen, &p, end))
1970 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_TRANSFER_ENCODING,
1971 (unsigned char *)"chunked",
1976 if (wsi->cache_secs && wsi->cache_reuse) {
1977 if (wsi->cache_revalidate) {
1979 cclen = sprintf(cache_control, "%s max-age: %u",
1980 intermediates[wsi->cache_intermediaries],
1988 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CACHE_CONTROL,
1989 (unsigned char *)cc, cclen, &p, end))
1992 if (wsi->u.http.connection_type == HTTP_CONNECTION_KEEP_ALIVE)
1993 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
1994 (unsigned char *)"keep-alive", 10, &p, end))
1997 if (other_headers) {
1998 if ((end - p) < other_headers_len)
2000 memcpy(p, other_headers, other_headers_len);
2001 p += other_headers_len;
2004 if (lws_finalize_http_header(wsi, &p, end))
2007 ret = lws_write(wsi, response, p - response, LWS_WRITE_HTTP_HEADERS);
2008 if (ret != (p - response)) {
2009 lwsl_err("_write returned %d from %d\n", ret, (p - response));
2013 wsi->u.http.filepos = 0;
2014 wsi->state = LWSS_HTTP_ISSUING_FILE;
2016 return lws_serve_http_file_fragment(wsi);
2020 lws_interpret_incoming_packet(struct lws *wsi, unsigned char **buf, size_t len)
2024 lwsl_parser("%s: received %d byte packet\n", __func__, (int)len);
2026 lwsl_hexdump(*buf, len);
2029 /* let the rx protocol state machine have as much as it needs */
2033 * we were accepting input but now we stopped doing so
2035 if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
2036 lws_rxflow_cache(wsi, *buf, 0, len);
2037 lwsl_parser("%s: cached %d\n", __func__, len);
2041 if (wsi->u.ws.rx_draining_ext) {
2042 m = lws_rx_sm(wsi, 0);
2048 /* account for what we're using in rxflow buffer */
2049 if (wsi->rxflow_buffer)
2052 /* consume payload bytes efficiently */
2053 if (wsi->lws_rx_parse_state ==
2054 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED)
2055 lws_payload_until_length_exhausted(wsi, buf, &len);
2057 /* process the byte */
2058 m = lws_rx_sm(wsi, *(*buf)++);
2064 lwsl_parser("%s: exit with %d unused\n", __func__, (int)len);
2070 lws_server_get_canonical_hostname(struct lws_context *context,
2071 struct lws_context_creation_info *info)
2073 if (lws_check_opt(info->options, LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME))
2076 /* find canonical hostname */
2077 gethostname((char *)context->canonical_hostname,
2078 sizeof(context->canonical_hostname) - 1);
2080 lwsl_notice(" canonical_hostname = %s\n", context->canonical_hostname);
2086 #define LWS_MAX_ELEM_NAME 32
2088 enum urldecode_stateful {
2102 static const char * const mp_hdr[] = {
2103 "content-disposition: ",
2108 typedef int (*lws_urldecode_stateful_cb)(void *data,
2109 const char *name, char **buf, int len, int final);
2111 struct lws_urldecode_stateful {
2114 char name[LWS_MAX_ELEM_NAME];
2115 char temp[LWS_MAX_ELEM_NAME];
2116 char content_type[32];
2117 char content_disp[32];
2118 char content_disp_filename[256];
2119 char mime_boundary[128];
2125 unsigned int multipart_form_data:1;
2126 unsigned int inside_quote:1;
2127 unsigned int subname:1;
2128 unsigned int boundary_real_crlf:1;
2130 enum urldecode_stateful state;
2132 lws_urldecode_stateful_cb output;
2135 static struct lws_urldecode_stateful *
2136 lws_urldecode_s_create(struct lws *wsi, char *out, int out_len, void *data,
2137 lws_urldecode_stateful_cb output)
2139 struct lws_urldecode_stateful *s = lws_zalloc(sizeof(*s));
2147 s->out_len = out_len;
2155 if (lws_hdr_copy(wsi, buf, sizeof(buf), WSI_TOKEN_HTTP_CONTENT_TYPE) > 0) {
2156 /* multipart/form-data; boundary=----WebKitFormBoundarycc7YgAPEIHvgE9Bf */
2158 if (!strncmp(buf, "multipart/form-data", 19)) {
2159 s->multipart_form_data = 1;
2160 s->state = MT_LOOK_BOUND_IN;
2162 p = strstr(buf, "boundary=");
2165 s->mime_boundary[m++] = '\x0d';
2166 s->mime_boundary[m++] = '\x0a';
2167 s->mime_boundary[m++] = '-';
2168 s->mime_boundary[m++] = '-';
2169 while (m < sizeof(s->mime_boundary) - 1 &&
2171 s->mime_boundary[m++] = *p++;
2173 s->mime_boundary[m] = '\0';
2175 lwsl_notice("boundary '%s'\n", s->mime_boundary);
2184 lws_urldecode_s_process(struct lws_urldecode_stateful *s, const char *in, int len)
2190 if (s->pos == s->out_len - s->mp - 1) {
2191 if (s->output(s->data, s->name, &s->out, s->pos, 0))
2198 /* states for url arg style */
2201 s->inside_quote = 0;
2203 s->name[s->pos] = '\0';
2210 s->name[s->pos] = '\0';
2211 if (s->output(s->data, s->name, &s->out, s->pos, 1))
2218 if (s->pos >= sizeof(s->name) - 1) {
2219 lwsl_notice("Name too long\n");
2222 s->name[s->pos++] = *in++;
2231 s->out[s->pos] = '\0';
2232 if (s->output(s->data, s->name, &s->out, s->pos, 1))
2241 s->out[s->pos++] = ' ';
2244 s->out[s->pos++] = *in++;
2247 n = char_to_hex(*in);
2257 n = char_to_hex(*in);
2262 s->out[s->pos++] = sum | n;
2267 /* states for multipart / mime style */
2269 case MT_LOOK_BOUND_IN:
2270 if (*in == s->mime_boundary[s->mp] &&
2271 s->mime_boundary[s->mp]) {
2274 if (!s->mime_boundary[s->mp]) {
2276 s->state = MT_IGNORE1;
2279 if (s->output(s->data, s->name,
2280 &s->out, s->pos, 1))
2285 s->content_disp[0] = '\0';
2287 s->content_disp_filename[0] = '\0';
2288 s->boundary_real_crlf = 1;
2294 if (!s->boundary_real_crlf)
2296 memcpy(s->out + s->pos, s->mime_boundary + n, s->mp - n);
2300 s->out[s->pos++] = *in;
2308 if (c >= 'A' && c <= 'Z')
2310 for (n = 0; n < ARRAY_SIZE(mp_hdr); n++)
2311 if (c == mp_hdr[n][s->mp]) {
2325 if (mp_hdr[hit][s->mp])
2333 s->state = MT_LOOK_BOUND_IN;
2335 s->state += hit + 1;
2339 /* form-data; name="file"; filename="t.txt" */
2341 if (*in == '\x0d') {
2342 // lwsl_notice("disp: '%s', '%s', '%s'\n",
2343 // s->content_disp, s->name,
2344 // s->content_disp_filename);
2346 if (s->content_disp_filename[0])
2347 if (s->output(s->data, s->name,
2348 &s->out, s->pos, LWS_UFS_OPEN))
2350 s->state = MT_IGNORE2;
2361 s->inside_quote ^= 1;
2367 s->temp[s->mp] = '\0';
2372 if (s->mp < sizeof(s->temp) - 1 &&
2373 (*in != ' ' || s->inside_quote))
2374 s->temp[s->mp++] = *in;
2379 if (s->mp < sizeof(s->content_disp) - 1)
2380 s->content_disp[s->mp++] = *in;
2381 s->content_disp[s->mp] = '\0';
2385 if (!strcmp(s->temp, "name")) {
2386 if (s->mp < sizeof(s->name) - 1)
2387 s->name[s->mp++] = *in;
2388 s->name[s->mp] = '\0';
2392 if (!strcmp(s->temp, "filename")) {
2393 if (s->mp < sizeof(s->content_disp_filename) - 1)
2394 s->content_disp_filename[s->mp++] = *in;
2395 s->content_disp_filename[s->mp] = '\0';
2404 s->state = MT_IGNORE2;
2406 if (s->mp < sizeof(s->content_type) - 1)
2407 s->content_type[s->mp++] = *in;
2408 s->content_type[s->mp] = '\0';
2415 s->state = MT_IGNORE2;
2422 s->state = MT_HNAME;
2432 lws_urldecode_s_destroy(struct lws_urldecode_stateful *s)
2436 if (s->state != US_IDLE)
2440 if (s->output(s->data, s->name, &s->out, s->pos, 1))
2449 struct lws_urldecode_stateful *s;
2450 lws_spa_fileupload_cb opt_cb;
2451 const char * const *param_names;
2463 lws_urldecode_spa_lookup(struct lws_spa *spa,
2468 for (n = 0; n < spa->count_params; n++)
2469 if (!strcmp(spa->param_names[n], name))
2476 lws_urldecode_spa_cb(void *data, const char *name, char **buf, int len,
2479 struct lws_spa *spa =
2480 (struct lws_spa *)data;
2483 if (spa->s->content_disp_filename[0]) {
2485 n = spa->opt_cb(spa->opt_data, name,
2486 spa->s->content_disp_filename,
2494 n = lws_urldecode_spa_lookup(spa, name);
2496 if (n == -1 || !len) /* unrecognized */
2499 if (!spa->params[n])
2500 spa->params[n] = *buf;
2502 if ((*buf) + len >= spa->end) {
2503 lwsl_notice("%s: exceeded storage\n", __func__);
2507 spa->param_length[n] += len;
2509 /* move it on inside storage */
2513 spa->s->out_len -= len + 1;
2518 LWS_VISIBLE LWS_EXTERN struct lws_spa *
2519 lws_spa_create(struct lws *wsi, const char * const *param_names,
2520 int count_params, int max_storage,
2521 lws_spa_fileupload_cb opt_cb, void *opt_data)
2523 struct lws_spa *spa = lws_zalloc(sizeof(*spa));
2528 spa->param_names = param_names;
2529 spa->count_params = count_params;
2530 spa->max_storage = max_storage;
2531 spa->opt_cb = opt_cb;
2532 spa->opt_data = opt_data;
2534 spa->storage = lws_malloc(max_storage);
2537 spa->end = spa->storage + max_storage - 1;
2539 spa->params = lws_zalloc(sizeof(char *) * count_params);
2543 spa->s = lws_urldecode_s_create(wsi, spa->storage, max_storage, spa,
2544 lws_urldecode_spa_cb);
2548 spa->param_length = lws_zalloc(sizeof(int) * count_params);
2549 if (!spa->param_length)
2552 lwsl_notice("%s: Created SPA %p\n", __func__, spa);
2557 lws_urldecode_s_destroy(spa->s);
2559 lws_free(spa->params);
2561 lws_free(spa->storage);
2568 LWS_VISIBLE LWS_EXTERN int
2569 lws_spa_process(struct lws_spa *ludspa, const char *in, int len)
2572 lwsl_err("%s: NULL spa\n");
2575 return lws_urldecode_s_process(ludspa->s, in, len);
2578 LWS_VISIBLE LWS_EXTERN int
2579 lws_spa_get_length(struct lws_spa *ludspa, int n)
2581 if (n >= ludspa->count_params)
2584 return ludspa->param_length[n];
2587 LWS_VISIBLE LWS_EXTERN const char *
2588 lws_spa_get_string(struct lws_spa *ludspa, int n)
2590 if (n >= ludspa->count_params)
2593 return ludspa->params[n];
2596 LWS_VISIBLE LWS_EXTERN int
2597 lws_spa_finalize(struct lws_spa *spa)
2600 lws_urldecode_s_destroy(spa->s);
2607 LWS_VISIBLE LWS_EXTERN int
2608 lws_spa_destroy(struct lws_spa *spa)
2612 lwsl_notice("%s: destroy spa %p\n", __func__, spa);
2615 lws_urldecode_s_destroy(spa->s);
2617 lwsl_debug("%s\n", __func__);
2619 lws_free(spa->param_length);
2620 lws_free(spa->params);
2621 lws_free(spa->storage);
2627 LWS_VISIBLE LWS_EXTERN int
2628 lws_chunked_html_process(struct lws_process_html_args *args,
2629 struct lws_process_html_state *s)
2631 char *sp, buffer[32];
2635 /* do replacements */
2637 old_len = args->len;
2640 while (sp < args->p + old_len) {
2642 if (args->len + 7 >= args->max_len) {
2643 lwsl_err("Used up interpret padding\n");
2647 if ((!s->pos && *sp == '$') || s->pos) {
2648 int hits = 0, hit = 0;
2652 s->swallow[s->pos++] = *sp;
2653 if (s->pos == sizeof(s->swallow))
2655 for (n = 0; n < s->count_vars; n++)
2656 if (!strncmp(s->swallow, s->vars[n], s->pos)) {
2662 s->swallow[s->pos] = '\0';
2663 memcpy(s->start, s->swallow, s->pos);
2669 if (hits == 1 && s->pos == strlen(s->vars[hit])) {
2670 pc = s->replace(s->data, hit);
2674 s->swallow[s->pos] = '\0';
2676 memmove(s->start + n,
2678 old_len - (sp - args->p));
2679 old_len += (n - s->pos) + 1;
2681 memcpy(s->start, pc, n);
2695 /* no space left for final chunk trailer */
2696 if (args->final && args->len + 7 >= args->max_len)
2699 n = sprintf(buffer, "%X\x0d\x0a", args->len);
2702 memcpy(args->p, buffer, n);
2706 sp = args->p + args->len;
2716 sp = args->p + args->len;