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], ".svg"))
319 return "image/svg+xml";
321 if (!strcmp(&file[n - 4], ".ttf"))
322 return "application/x-font-ttf";
324 if (!strcmp(&file[n - 5], ".woff"))
325 return "application/font-woff";
327 if (!strcmp(&file[n - 4], ".xml"))
328 return "application/xml";
331 if (pvo->name[0] == '*') /* ie, match anything */
334 if (!strcmp(&file[n - strlen(pvo->name)], pvo->name))
344 lws_http_serve(struct lws *wsi, char *uri, const char *origin,
345 const struct lws_http_mount *m)
347 const struct lws_protocol_vhost_options *pvo = m->interpret;
348 struct lws_process_html_args args;
349 const char *mimetype;
350 #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP8266)
354 char path[256], sym[512];
355 unsigned char *p = (unsigned char *)sym + 32 + LWS_PRE, *start = p;
356 unsigned char *end = p + sizeof(sym) - 32 - LWS_PRE;
357 #if !defined(WIN32) && LWS_POSIX
362 lws_snprintf(path, sizeof(path) - 1, "%s/%s", origin, uri);
364 #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP8266)
368 if (stat(path, &st)) {
369 lwsl_info("unable to stat %s\n", path);
373 lwsl_debug(" %s mode %d\n", path, S_IFMT & st.st_mode);
374 #if !defined(WIN32) && LWS_POSIX
375 if ((S_IFMT & st.st_mode) == S_IFLNK) {
376 len = readlink(path, sym, sizeof(sym) - 1);
378 lwsl_err("Failed to read link %s\n", path);
382 lwsl_debug("symlink %s -> %s\n", path, sym);
383 lws_snprintf(path, sizeof(path) - 1, "%s", sym);
386 if ((S_IFMT & st.st_mode) == S_IFDIR) {
387 lwsl_debug("default filename append to dir\n");
388 lws_snprintf(path, sizeof(path) - 1, "%s/%s/index.html",
392 } while ((S_IFMT & st.st_mode) != S_IFREG && spin < 5);
395 lwsl_err("symlink loop %s \n", path);
397 n = sprintf(sym, "%08lX%08lX", (unsigned long)st.st_size,
398 (unsigned long)st.st_mtime);
400 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_NONE_MATCH)) {
402 * he thinks he has some version of it already,
403 * check if the tag matches
405 if (!strcmp(sym, lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_IF_NONE_MATCH))) {
407 lwsl_debug("%s: ETAG match %s %s\n", __func__,
410 /* we don't need to send the payload */
411 if (lws_add_http_header_status(wsi, 304, &p, end))
414 if (lws_add_http_header_by_token(wsi,
416 (unsigned char *)sym, n, &p, end))
419 if (lws_finalize_http_header(wsi, &p, end))
422 n = lws_write(wsi, start, p - start,
423 LWS_WRITE_HTTP_HEADERS);
424 if (n != (p - start)) {
425 lwsl_err("_write returned %d from %d\n", n, p - start);
429 return lws_http_transaction_completed(wsi);
433 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ETAG,
434 (unsigned char *)sym, n, &p, end))
438 mimetype = lws_get_mimetype(path, m);
440 lwsl_err("unknown mimetype for %s\n", path);
444 lwsl_debug("sending no mimetype for %s\n", path);
446 wsi->sending_chunked = 0;
449 * check if this is in the list of file suffixes to be interpreted by
454 if (n > (int)strlen(pvo->name) &&
455 !strcmp(&path[n - strlen(pvo->name)], pvo->name)) {
456 wsi->sending_chunked = 1;
457 wsi->protocol_interpret_idx = (char)(long)pvo->value;
458 lwsl_info("want %s interpreted by %s\n", path,
459 wsi->vhost->protocols[(int)(long)(pvo->value)].name);
460 wsi->protocol = &wsi->vhost->protocols[(int)(long)(pvo->value)];
461 if (lws_ensure_user_space(wsi))
469 const struct lws_protocols *pp = lws_vhost_name_to_protocol(
470 wsi->vhost, m->protocol);
472 if (lws_bind_protocol(wsi, pp))
475 args.max_len = end - p;
476 if (pp->callback(wsi, LWS_CALLBACK_ADD_HEADERS,
477 wsi->user_space, &args, 0))
479 p = (unsigned char *)args.p;
482 n = lws_serve_http_file(wsi, path, mimetype, (char *)start, p - start);
484 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
485 return -1; /* error or can't reuse connection: close the socket */
493 const struct lws_http_mount *
494 lws_find_mount(struct lws *wsi, const char *uri_ptr, int uri_len)
496 const struct lws_http_mount *hm, *hit = NULL;
499 hm = wsi->vhost->mount_list;
501 if (uri_len >= hm->mountpoint_len &&
502 !strncmp(uri_ptr, hm->mountpoint, hm->mountpoint_len) &&
503 (uri_ptr[hm->mountpoint_len] == '\0' ||
504 uri_ptr[hm->mountpoint_len] == '/' ||
505 hm->mountpoint_len == 1)
507 if (hm->origin_protocol == LWSMPRO_CALLBACK ||
508 ((hm->origin_protocol == LWSMPRO_CGI ||
509 lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI) ||
511 hm->mountpoint_len > best)) {
512 best = hm->mountpoint_len;
523 lws_http_action(struct lws *wsi)
525 struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
526 enum http_connection_type connection_type;
527 enum http_version request_version;
528 char content_length_str[32];
529 struct lws_process_html_args args;
530 const struct lws_http_mount *hit = NULL;
531 unsigned int n, count = 0;
532 char http_version_str[10];
533 char http_conn_str[20];
534 int http_version_len;
535 char *uri_ptr = NULL, *s;
539 static const unsigned char methods[] = {
542 WSI_TOKEN_OPTIONS_URI,
545 WSI_TOKEN_DELETE_URI,
547 WSI_TOKEN_HTTP_COLON_PATH,
550 #if defined(_DEBUG) || defined(LWS_WITH_ACCESS_LOG)
551 static const char * const method_names[] = {
552 "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE",
558 static const char * const oprot[] = {
559 "http://", "https://"
562 /* it's not websocket.... shall we accept it as http? */
564 for (n = 0; n < ARRAY_SIZE(methods); n++)
565 if (lws_hdr_total_length(wsi, methods[n]))
568 lwsl_warn("Missing URI in HTTP request\n");
573 lwsl_warn("multiple methods?\n");
577 if (lws_ensure_user_space(wsi))
580 for (n = 0; n < ARRAY_SIZE(methods); n++)
581 if (lws_hdr_total_length(wsi, methods[n])) {
582 uri_ptr = lws_hdr_simple_ptr(wsi, methods[n]);
583 uri_len = lws_hdr_total_length(wsi, methods[n]);
584 lwsl_info("Method: %s request for '%s'\n",
585 method_names[n], uri_ptr);
592 /* we insist on absolute paths */
594 if (uri_ptr[0] != '/') {
595 lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
600 /* HTTP header had a content length? */
602 wsi->u.http.content_length = 0;
603 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) ||
604 lws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI) ||
605 lws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI))
606 wsi->u.http.content_length = 100 * 1024 * 1024;
608 if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
609 lws_hdr_copy(wsi, content_length_str,
610 sizeof(content_length_str) - 1,
611 WSI_TOKEN_HTTP_CONTENT_LENGTH);
612 wsi->u.http.content_length = atoi(content_length_str);
615 if (wsi->http2_substream) {
616 wsi->u.http.request_version = HTTP_VERSION_2;
618 /* http_version? Default to 1.0, override with token: */
619 request_version = HTTP_VERSION_1_0;
621 /* Works for single digit HTTP versions. : */
622 http_version_len = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP);
623 if (http_version_len > 7) {
624 lws_hdr_copy(wsi, http_version_str,
625 sizeof(http_version_str) - 1, WSI_TOKEN_HTTP);
626 if (http_version_str[5] == '1' && http_version_str[7] == '1')
627 request_version = HTTP_VERSION_1_1;
629 wsi->u.http.request_version = request_version;
631 /* HTTP/1.1 defaults to "keep-alive", 1.0 to "close" */
632 if (request_version == HTTP_VERSION_1_1)
633 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
635 connection_type = HTTP_CONNECTION_CLOSE;
637 /* Override default if http "Connection:" header: */
638 if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) {
639 lws_hdr_copy(wsi, http_conn_str, sizeof(http_conn_str) - 1,
640 WSI_TOKEN_CONNECTION);
641 http_conn_str[sizeof(http_conn_str) - 1] = '\0';
642 if (!strcasecmp(http_conn_str, "keep-alive"))
643 connection_type = HTTP_CONNECTION_KEEP_ALIVE;
645 if (!strcasecmp(http_conn_str, "close"))
646 connection_type = HTTP_CONNECTION_CLOSE;
648 wsi->u.http.connection_type = connection_type;
651 n = wsi->protocol->callback(wsi, LWS_CALLBACK_FILTER_HTTP_CONNECTION,
652 wsi->user_space, uri_ptr, uri_len);
654 lwsl_info("LWS_CALLBACK_HTTP closing\n");
659 * if there is content supposed to be coming,
660 * put a timeout on it having arrived
662 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
663 wsi->context->timeout_secs);
664 #ifdef LWS_OPENSSL_SUPPORT
665 if (wsi->redirect_to_https) {
667 * we accepted http:// only so we could redirect to
668 * https://, so issue the redirect. Create the redirection
669 * URI from the host: header and ignore the path part
671 unsigned char *start = pt->serv_buf + LWS_PRE, *p = start,
674 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
677 n = sprintf((char *)end, "https://%s/",
678 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
680 n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
685 return lws_http_transaction_completed(wsi);
689 #ifdef LWS_WITH_ACCESS_LOG
691 * Produce Apache-compatible log string for wsi, like this:
693 * 2.31.234.19 - - [27/Mar/2016:03:22:44 +0800]
694 * "GET /aep-screen.png HTTP/1.1"
695 * 200 152987 "https://libwebsockets.org/index.html"
696 * "Mozilla/5.0 (Macint... Chrome/49.0.2623.87 Safari/537.36"
700 static const char * const hver[] = {
701 "http/1.0", "http/1.1", "http/2"
704 char ads[INET6_ADDRSTRLEN];
706 char ads[INET_ADDRSTRLEN];
711 time_t t = time(NULL);
714 if (wsi->access_log_pending)
717 wsi->access_log.header_log = lws_malloc(l);
718 if (wsi->access_log.header_log) {
722 strftime(da, sizeof(da), "%d/%b/%Y:%H:%M:%S %z", tmp);
724 strcpy(da, "01/Jan/1970:00:00:00 +0000");
726 pa = lws_get_peer_simple(wsi, ads, sizeof(ads));
731 me = method_names[meth];
735 lws_snprintf(wsi->access_log.header_log, l,
736 "%s - - [%s] \"%s %s %s\"",
738 hver[wsi->u.http.request_version]);
740 l = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT);
742 wsi->access_log.user_agent = lws_malloc(l + 2);
743 if (wsi->access_log.user_agent)
744 lws_hdr_copy(wsi, wsi->access_log.user_agent,
745 l + 1, WSI_TOKEN_HTTP_USER_AGENT);
747 lwsl_err("OOM getting user agent\n");
749 wsi->access_log_pending = 1;
754 /* can we serve it from the mount list? */
756 hit = lws_find_mount(wsi, uri_ptr, uri_len);
758 /* deferred cleanup and reset to protocols[0] */
760 lwsl_info("no hit\n");
762 if (lws_bind_protocol(wsi, &wsi->vhost->protocols[0]))
765 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
766 wsi->user_space, uri_ptr, uri_len);
771 s = uri_ptr + hit->mountpoint_len;
775 args.max_len = hit->auth_mask;
776 args.final = 0; /* used to signal callback dealt with it */
778 n = wsi->protocol->callback(wsi, LWS_CALLBACK_CHECK_ACCESS_RIGHTS,
779 wsi->user_space, &args, 0);
781 lws_return_http_status(wsi, HTTP_STATUS_UNAUTHORIZED,
785 if (args.final) /* callback completely handled it well */
789 * if we have a mountpoint like https://xxx.com/yyy
790 * there is an implied / at the end for our purposes since
791 * we can only mount on a "directory".
793 * But if we just go with that, the browser cannot understand
794 * that he is actually looking down one "directory level", so
795 * even though we give him /yyy/abc.html he acts like the
796 * current directory level is /. So relative urls like "x.png"
797 * wrongly look outside the mountpoint.
799 * Therefore if we didn't come in on a url with an explicit
800 * / at the end, we must redirect to add it so the browser
801 * understands he is one "directory level" down.
803 if ((hit->mountpoint_len > 1 ||
804 (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
805 hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&
807 (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
808 hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&
809 (hit->origin_protocol != LWSMPRO_CGI &&
810 hit->origin_protocol != LWSMPRO_CALLBACK //&&
811 //hit->protocol == NULL
813 unsigned char *start = pt->serv_buf + LWS_PRE,
814 *p = start, *end = p + 512;
816 lwsl_debug("Doing 301 '%s' org %s\n", s, hit->origin);
818 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
821 /* > at start indicates deal with by redirect */
822 if (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
823 hit->origin_protocol == LWSMPRO_REDIR_HTTPS)
824 n = lws_snprintf((char *)end, 256, "%s%s",
825 oprot[hit->origin_protocol & 1],
828 n = lws_snprintf((char *)end, 256,
829 "%s%s%s/", oprot[lws_is_ssl(wsi)],
830 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST),
833 n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
838 return lws_http_transaction_completed(wsi);
842 * A particular protocol callback is mounted here?
844 * For the duration of this http transaction, bind us to the
845 * associated protocol
847 if (hit->origin_protocol == LWSMPRO_CALLBACK || hit->protocol) {
848 const struct lws_protocols *pp;
849 const char *name = hit->origin;
851 name = hit->protocol;
853 pp = lws_vhost_name_to_protocol(wsi->vhost, name);
856 lwsl_err("Unable to find plugin '%s'\n",
861 if (lws_bind_protocol(wsi, pp))
864 if (hit->cgienv && wsi->protocol->callback(wsi,
865 LWS_CALLBACK_HTTP_PMO,
866 wsi->user_space, (void *)hit->cgienv, 0))
869 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) {
870 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
872 uri_ptr + hit->mountpoint_len,
873 uri_len - hit->mountpoint_len);
879 /* did we hit something with a cgi:// origin? */
880 if (hit->origin_protocol == LWSMPRO_CGI) {
881 const char *cmd[] = {
882 NULL, /* replace with cgi path */
885 unsigned char *p, *end, buffer[1024];
887 lwsl_debug("%s: cgi\n", __func__);
888 cmd[0] = hit->origin;
891 if (hit->cgi_timeout)
892 n = hit->cgi_timeout;
894 n = lws_cgi(wsi, cmd, hit->mountpoint_len, n,
897 lwsl_err("%s: cgi failed\n");
900 p = buffer + LWS_PRE;
901 end = p + sizeof(buffer) - LWS_PRE;
903 if (lws_add_http_header_status(wsi, 200, &p, end))
905 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
906 (unsigned char *)"close", 5, &p, end))
908 n = lws_write(wsi, buffer + LWS_PRE,
909 p - (buffer + LWS_PRE),
910 LWS_WRITE_HTTP_HEADERS);
917 if (s[0] == '\0' || (n == 1 && s[n - 1] == '/'))
918 s = (char *)hit->def;
922 wsi->cache_secs = hit->cache_max_age;
923 wsi->cache_reuse = hit->cache_reusable;
924 wsi->cache_revalidate = hit->cache_revalidate;
925 wsi->cache_intermediaries = hit->cache_intermediaries;
927 n = lws_http_serve(wsi, s, hit->origin, hit);
930 * lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
933 const struct lws_protocols *pp = lws_vhost_name_to_protocol(
934 wsi->vhost, hit->protocol);
936 if (lws_bind_protocol(wsi, pp))
939 n = pp->callback(wsi, LWS_CALLBACK_HTTP,
941 uri_ptr + hit->mountpoint_len,
942 uri_len - hit->mountpoint_len);
944 n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
945 wsi->user_space, uri_ptr, uri_len);
950 lwsl_info("LWS_CALLBACK_HTTP closing\n");
959 * If we're not issuing a file, check for content_length or
960 * HTTP keep-alive. No keep-alive header allocation for
961 * ISSUING_FILE, as this uses HTTP/1.0.
963 * In any case, return 0 and let lws_read decide how to
964 * proceed based on state
966 if (wsi->state != LWSS_HTTP_ISSUING_FILE)
967 /* Prepare to read body if we have a content length: */
968 if (wsi->u.http.content_length > 0)
969 wsi->state = LWSS_HTTP_BODY;
974 /* we're closing, losing some rx is OK */
975 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
976 // lwsl_notice("%s: drop1\n", __func__);
977 lws_header_table_detach(wsi, 1);
983 lws_bind_protocol(struct lws *wsi, const struct lws_protocols *p)
985 // if (wsi->protocol == p)
989 wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_DROP_PROTOCOL,
990 wsi->user_space, NULL, 0);
991 if (!wsi->user_space_externally_allocated)
992 lws_free_set_NULL(wsi->user_space);
998 if (lws_ensure_user_space(wsi))
1001 if (wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP_BIND_PROTOCOL,
1002 wsi->user_space, NULL, 0))
1010 lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len)
1012 struct lws_context *context = lws_get_context(wsi);
1013 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1014 struct _lws_header_related hdr;
1015 struct allocated_headers *ah;
1016 int protocol_len, n = 0, hit;
1017 char protocol_list[128];
1018 char protocol_name[64];
1021 if (len >= 10000000) {
1022 lwsl_err("%s: assert: len %ld\n", __func__, (long)len);
1026 if (!wsi->u.hdr.ah) {
1027 lwsl_err("%s: assert: NULL ah\n", __func__);
1032 wsi->more_rx_waiting = !!len;
1034 if (wsi->mode != LWSCM_HTTP_SERVING &&
1035 wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED) {
1036 lwsl_err("%s: bad wsi mode %d\n", __func__, wsi->mode);
1040 if (lws_parse(wsi, *(*buf)++)) {
1041 lwsl_info("lws_parse failed\n");
1045 if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
1048 lwsl_parser("%s: lws_parse sees parsing complete\n", __func__);
1049 lwsl_debug("%s: wsi->more_rx_waiting=%d\n", __func__,
1050 wsi->more_rx_waiting);
1054 if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
1055 struct lws_vhost *vhost = lws_select_vhost(
1056 context, wsi->vhost->listen_port,
1057 lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
1062 lwsl_info("no host\n");
1064 wsi->vhost->trans++;
1065 if (!wsi->conn_stat_done) {
1067 wsi->conn_stat_done = 1;
1070 wsi->mode = LWSCM_PRE_WS_SERVING_ACCEPT;
1071 lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
1073 /* is this websocket protocol or normal http 1.0? */
1075 if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
1076 if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
1078 wsi->vhost->ws_upgrades++;
1079 lwsl_info("Upgrade to ws\n");
1082 #ifdef LWS_USE_HTTP2
1083 if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
1085 wsi->vhost->http2_upgrades++;
1086 lwsl_info("Upgrade to h2c\n");
1090 lwsl_info("Unknown upgrade\n");
1091 /* dunno what he wanted to upgrade to */
1095 /* no upgrade ack... he remained as HTTP */
1097 lwsl_info("No upgrade\n");
1100 lws_union_transition(wsi, LWSCM_HTTP_SERVING_ACCEPTED);
1101 wsi->state = LWSS_HTTP;
1102 wsi->u.http.fd = LWS_INVALID_FILE;
1104 /* expose it at the same offset as u.hdr */
1105 wsi->u.http.ah = ah;
1106 lwsl_debug("%s: wsi %p: ah %p\n", __func__, (void *)wsi,
1107 (void *)wsi->u.hdr.ah);
1109 n = lws_http_action(wsi);
1113 #ifdef LWS_USE_HTTP2
1115 if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) {
1116 lwsl_info("missing http2_settings\n");
1120 lwsl_info("h2c upgrade...\n");
1122 p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS);
1123 /* convert the peer's HTTP-Settings */
1124 n = lws_b64_decode_string(p, protocol_list,
1125 sizeof(protocol_list));
1127 lwsl_parser("HTTP2_SETTINGS too long\n");
1131 /* adopt the header info */
1135 lws_union_transition(wsi, LWSCM_HTTP2_SERVING);
1137 /* http2 union member has http union struct at start */
1138 wsi->u.http.ah = ah;
1140 lws_http2_init(&wsi->u.http2.peer_settings);
1141 lws_http2_init(&wsi->u.http2.my_settings);
1145 lws_http2_interpret_settings_payload(&wsi->u.http2.peer_settings,
1146 (unsigned char *)protocol_list, n);
1148 strcpy(protocol_list,
1149 "HTTP/1.1 101 Switching Protocols\x0d\x0a"
1150 "Connection: Upgrade\x0d\x0a"
1151 "Upgrade: h2c\x0d\x0a\x0d\x0a");
1152 n = lws_issue_raw(wsi, (unsigned char *)protocol_list,
1153 strlen(protocol_list));
1154 if (n != strlen(protocol_list)) {
1155 lwsl_debug("http2 switch: ERROR writing to socket\n");
1159 wsi->state = LWSS_HTTP2_AWAIT_CLIENT_PREFACE;
1166 lwsl_err("NULL protocol at lws_read\n");
1171 * Select the first protocol we support from the list
1172 * the client sent us.
1174 * Copy it to remove header fragmentation
1177 if (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1,
1178 WSI_TOKEN_PROTOCOL) < 0) {
1179 lwsl_err("protocol list too long");
1183 protocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
1184 protocol_list[protocol_len] = '\0';
1188 while (*p && !hit) {
1190 while (n < sizeof(protocol_name) - 1 && *p && *p !=',')
1191 protocol_name[n++] = *p++;
1192 protocol_name[n] = '\0';
1196 lwsl_info("checking %s\n", protocol_name);
1199 while (wsi->vhost->protocols[n].callback) {
1200 if (wsi->vhost->protocols[n].name &&
1201 !strcmp(wsi->vhost->protocols[n].name,
1203 wsi->protocol = &wsi->vhost->protocols[n];
1212 /* we didn't find a protocol he wanted? */
1215 if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL)) {
1216 lwsl_info("No protocol from \"%s\" supported\n",
1221 * some clients only have one protocol and
1222 * do not send the protocol list header...
1223 * allow it and match to the vhost's default
1224 * protocol (which itself defaults to zero)
1226 lwsl_info("defaulting to prot handler %d\n",
1227 wsi->vhost->default_protocol_index);
1229 wsi->protocol = &wsi->vhost->protocols[
1230 (int)wsi->vhost->default_protocol_index];
1233 /* allocate wsi->user storage */
1234 if (lws_ensure_user_space(wsi))
1238 * Give the user code a chance to study the request and
1239 * have the opportunity to deny it
1241 if ((wsi->protocol->callback)(wsi,
1242 LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
1244 lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) {
1245 lwsl_warn("User code denied connection\n");
1250 * Perform the handshake according to the protocol version the
1254 switch (wsi->ietf_spec_revision) {
1256 lwsl_parser("lws_parse calling handshake_04\n");
1257 if (handshake_0405(context, wsi)) {
1258 lwsl_info("hs0405 has failed the connection\n");
1264 lwsl_info("Unknown client spec version %d\n",
1265 wsi->ietf_spec_revision);
1270 * stitch protocol choice into the vh protocol linked list
1271 * We always insert ourselves at the start of the list
1276 //lwsl_err("%s: pre insert vhost start wsi %p, that wsi prev == %p\n",
1278 // wsi->vhost->same_vh_protocol_list[n],
1279 // wsi->same_vh_protocol_prev);
1280 wsi->same_vh_protocol_prev = /* guy who points to us */
1281 &wsi->vhost->same_vh_protocol_list[n];
1282 wsi->same_vh_protocol_next = /* old first guy is our next */
1283 wsi->vhost->same_vh_protocol_list[n];
1284 /* we become the new first guy */
1285 wsi->vhost->same_vh_protocol_list[n] = wsi;
1287 if (wsi->same_vh_protocol_next)
1288 /* old first guy points back to us now */
1289 wsi->same_vh_protocol_next->same_vh_protocol_prev =
1290 &wsi->same_vh_protocol_next;
1294 /* we are upgrading to ws, so http/1.1 and keepalive +
1295 * pipelined header considerations about keeping the ah around
1296 * no longer apply. However it's common for the first ws
1297 * protocol data to have been coalesced with the browser
1298 * upgrade request and to already be in the ah rx buffer.
1301 lwsl_info("%s: %p: inheriting ah in ws mode (rxpos:%d, rxlen:%d)\n",
1302 __func__, wsi, wsi->u.hdr.ah->rxpos,
1303 wsi->u.hdr.ah->rxlen);
1307 lws_union_transition(wsi, LWSCM_WS_SERVING);
1309 * first service is WS mode will notice this, use the RX and
1310 * then detach the ah (caution: we are not in u.hdr union
1311 * mode any more then... ah_temp member is at start the same
1314 * Because rxpos/rxlen shows something in the ah, we will get
1315 * service guaranteed next time around the event loop
1317 * All union members begin with hdr, so we can use it even
1318 * though we transitioned to ws union mode (the ah detach
1319 * code uses it anyway).
1324 lws_restart_ws_ping_pong_timer(wsi);
1327 * create the frame buffer for this connection according to the
1328 * size mentioned in the protocol definition. If 0 there, use
1329 * a big default for compatibility
1332 n = wsi->protocol->rx_buffer_size;
1334 n = context->pt_serv_buf_size;
1336 wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
1337 if (!wsi->u.ws.rx_ubuf) {
1338 lwsl_err("Out of Mem allocating rx buffer %d\n", n);
1341 wsi->u.ws.rx_ubuf_alloc = n;
1342 lwsl_debug("Allocating RX buffer %d\n", n);
1344 if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF,
1345 (const char *)&n, sizeof n)) {
1346 lwsl_warn("Failed to set SNDBUF to %d", n);
1351 lwsl_parser("accepted v%02d connection\n",
1352 wsi->ietf_spec_revision);
1354 /* notify user code that we're ready to roll */
1356 if (wsi->protocol->callback)
1357 if (wsi->protocol->callback(wsi, LWS_CALLBACK_ESTABLISHED,
1359 #ifdef LWS_OPENSSL_SUPPORT
1367 /* !!! drop ah unreservedly after ESTABLISHED */
1368 if (!wsi->more_rx_waiting) {
1369 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1371 //lwsl_notice("%p: dropping ah EST\n", wsi);
1372 lws_header_table_detach(wsi, 1);
1376 } /* while all chars are handled */
1381 /* drop the header info */
1382 /* we're closing, losing some rx is OK */
1383 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1384 //lwsl_notice("%s: drop2\n", __func__);
1385 lws_header_table_detach(wsi, 1);
1391 lws_get_idlest_tsi(struct lws_context *context)
1393 unsigned int lowest = ~0;
1394 int n = 0, hit = -1;
1396 for (; n < context->count_threads; n++) {
1397 if ((unsigned int)context->pt[n].fds_count !=
1398 context->fd_limit_per_thread - 1 &&
1399 (unsigned int)context->pt[n].fds_count < lowest) {
1400 lowest = context->pt[n].fds_count;
1409 lws_create_new_server_wsi(struct lws_vhost *vhost)
1411 struct lws *new_wsi;
1412 int n = lws_get_idlest_tsi(vhost->context);
1415 lwsl_err("no space for new conn\n");
1419 new_wsi = lws_zalloc(sizeof(struct lws));
1420 if (new_wsi == NULL) {
1421 lwsl_err("Out of memory for new connection\n");
1426 lwsl_info("Accepted %p to tsi %d\n", new_wsi, new_wsi->tsi);
1428 new_wsi->vhost = vhost;
1429 new_wsi->context = vhost->context;
1430 new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
1431 new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
1433 /* initialize the instance struct */
1435 new_wsi->state = LWSS_HTTP;
1436 new_wsi->mode = LWSCM_HTTP_SERVING;
1437 new_wsi->hdr_parsing_completed = 0;
1439 #ifdef LWS_OPENSSL_SUPPORT
1440 new_wsi->use_ssl = LWS_SSL_ENABLED(vhost);
1444 * these can only be set once the protocol is known
1445 * we set an unestablished connection's protocol pointer
1446 * to the start of the supported list, so it can look
1447 * for matching ones during the handshake
1449 new_wsi->protocol = vhost->protocols;
1450 new_wsi->user_space = NULL;
1451 new_wsi->ietf_spec_revision = 0;
1452 new_wsi->sock = LWS_SOCK_INVALID;
1453 vhost->context->count_wsi_allocated++;
1456 * outermost create notification for wsi
1457 * no user_space because no protocol selection
1459 vhost->protocols[0].callback(new_wsi, LWS_CALLBACK_WSI_CREATE,
1465 LWS_VISIBLE int LWS_WARN_UNUSED_RESULT
1466 lws_http_transaction_completed(struct lws *wsi)
1468 int n = NO_PENDING_TIMEOUT;
1470 lws_access_log(wsi);
1472 lwsl_info("%s: wsi %p\n", __func__, wsi);
1473 /* if we can't go back to accept new headers, drop the connection */
1474 if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
1475 lwsl_info("%s: %p: close connection\n", __func__, wsi);
1479 if (lws_bind_protocol(wsi, &wsi->vhost->protocols[0]))
1482 /* otherwise set ourselves up ready to go again */
1483 wsi->state = LWSS_HTTP;
1484 wsi->mode = LWSCM_HTTP_SERVING;
1485 wsi->u.http.content_length = 0;
1486 wsi->u.http.content_remain = 0;
1487 wsi->hdr_parsing_completed = 0;
1488 #ifdef LWS_WITH_ACCESS_LOG
1489 wsi->access_log.sent = 0;
1492 if (wsi->vhost->keepalive_timeout)
1493 n = PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE;
1494 lws_set_timeout(wsi, n, wsi->vhost->keepalive_timeout);
1497 * We already know we are on http1.1 / keepalive and the next thing
1498 * coming will be another header set.
1500 * If there is no pending rx and we still have the ah, drop it and
1501 * reacquire a new ah when the new headers start to arrive. (Otherwise
1502 * we needlessly hog an ah indefinitely.)
1504 * However if there is pending rx and we know from the keepalive state
1505 * that is already at least the start of another header set, simply
1506 * reset the existing header table and keep it.
1508 if (wsi->u.hdr.ah) {
1509 lwsl_info("%s: wsi->more_rx_waiting=%d\n", __func__,
1510 wsi->more_rx_waiting);
1512 if (!wsi->more_rx_waiting) {
1513 wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
1514 lws_header_table_detach(wsi, 1);
1516 lws_header_table_reset(wsi, 1);
1519 /* If we're (re)starting on headers, need other implied init */
1520 wsi->u.hdr.ues = URIES_IDLE;
1522 lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
1528 lws_adopt_socket_vhost(struct lws_vhost *vh, lws_sockfd_type accept_fd)
1530 struct lws_context *context = vh->context;
1531 struct lws *new_wsi = lws_create_new_server_wsi(vh);
1534 compatible_close(accept_fd);
1538 //lwsl_notice("%s: new wsi %p, sockfd %d, cb %p\n", __func__, new_wsi, accept_fd, context->vhost_list->protocols[0].callback);
1540 new_wsi->sock = accept_fd;
1542 /* the transport is accepted... give him time to negotiate */
1543 lws_set_timeout(new_wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
1544 context->timeout_secs);
1547 #if defined(LWS_WITH_ESP8266)
1548 esp8266_tcp_stream_accept(accept_fd, new_wsi);
1550 mbed3_tcp_stream_accept(accept_fd, new_wsi);
1554 * A new connection was accepted. Give the user a chance to
1555 * set properties of the newly created wsi. There's no protocol
1556 * selected yet so we issue this to protocols[0]
1558 if ((context->vhost_list->protocols[0].callback)(new_wsi,
1559 LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED, NULL, NULL, 0)) {
1560 /* force us off the timeout list by hand */
1561 lws_set_timeout(new_wsi, NO_PENDING_TIMEOUT, 0);
1562 compatible_close(new_wsi->sock);
1567 lws_libev_accept(new_wsi, new_wsi->sock);
1568 lws_libuv_accept(new_wsi, new_wsi->sock);
1570 if (!LWS_SSL_ENABLED(new_wsi->vhost)) {
1571 if (insert_wsi_socket_into_fds(context, new_wsi)) {
1572 lwsl_err("%s: fail inserting socket\n", __func__);
1576 new_wsi->mode = LWSCM_SSL_INIT;
1577 if (lws_server_socket_service_ssl(new_wsi, accept_fd)) {
1578 lwsl_err("%s: fail ssl negotiation\n", __func__);
1583 if (!lws_header_table_attach(new_wsi, 0))
1584 lwsl_debug("Attached ah immediately\n");
1589 lws_close_free_wsi(new_wsi, LWS_CLOSE_STATUS_NOSTATUS);
1594 LWS_VISIBLE struct lws *
1595 lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd)
1597 return lws_adopt_socket_vhost(context->vhost_list, accept_fd);
1600 LWS_VISIBLE LWS_EXTERN struct lws *
1601 lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
1602 const char *readbuf, size_t len)
1604 struct lws *wsi = lws_adopt_socket(context, accept_fd);
1605 struct lws_context_per_thread *pt;
1606 struct allocated_headers *ah;
1607 struct lws_pollfd *pfd;
1615 if (len > sizeof(ah->rx)) {
1616 lwsl_err("%s: rx in too big\n", __func__);
1621 * we can't process the initial read data until we can attach an ah.
1623 * if one is available, get it and place the data in his ah rxbuf...
1624 * wsi with ah that have pending rxbuf get auto-POLLIN service.
1626 * no autoservice because we didn't get a chance to attach the
1627 * readbuf data to wsi or ah yet, and we will do it next if we get
1630 if (wsi->u.hdr.ah || !lws_header_table_attach(wsi, 0)) {
1632 memcpy(ah->rx, readbuf, len);
1636 lwsl_notice("%s: calling service on readbuf ah\n", __func__);
1637 pt = &context->pt[(int)wsi->tsi];
1639 /* unlike a normal connect, we have the headers already
1640 * (or the first part of them anyway).
1641 * libuv won't come back and service us without a network
1642 * event, so we need to do the header service right here.
1644 pfd = &pt->fds[wsi->position_in_fds_table];
1645 pfd->revents |= LWS_POLLIN;
1646 lwsl_err("%s: calling service\n", __func__);
1647 if (lws_service_fd_tsi(context, pfd, wsi->tsi))
1648 /* service closed us */
1653 lwsl_err("%s: deferring handling ah\n", __func__);
1655 * hum if no ah came, we are on the wait list and must defer
1656 * dealing with this until the ah arrives.
1658 * later successful lws_header_table_attach() will apply the
1659 * below to the rx buffer (via lws_header_table_reset()).
1661 wsi->u.hdr.preamble_rx = lws_malloc(len);
1662 if (!wsi->u.hdr.preamble_rx) {
1666 memcpy(wsi->u.hdr.preamble_rx, readbuf, len);
1667 wsi->u.hdr.preamble_rx_len = len;
1672 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1678 lws_server_socket_service(struct lws_context *context, struct lws *wsi,
1679 struct lws_pollfd *pollfd)
1681 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1682 lws_sockfd_type accept_fd = LWS_SOCK_INVALID;
1683 struct allocated_headers *ah;
1685 struct sockaddr_in cli_addr;
1690 // lwsl_notice("%s: mode %d\n", __func__, wsi->mode);
1692 switch (wsi->mode) {
1694 case LWSCM_HTTP_SERVING:
1695 case LWSCM_HTTP_SERVING_ACCEPTED:
1696 case LWSCM_HTTP2_SERVING:
1698 /* handle http headers coming in */
1700 /* pending truncated sends have uber priority */
1702 if (wsi->trunc_len) {
1703 if (!(pollfd->revents & LWS_POLLOUT))
1706 if (lws_issue_raw(wsi, wsi->trunc_alloc +
1708 wsi->trunc_len) < 0)
1711 * we can't afford to allow input processing to send
1712 * something new, so spin around he event loop until
1713 * he doesn't have any partials
1718 /* any incoming data ready? */
1720 if (!(pollfd->revents & pollfd->events & LWS_POLLIN))
1724 * If we previously just did POLLIN when IN and OUT were
1725 * signalled (because POLLIN processing may have used up
1726 * the POLLOUT), don't let that happen twice in a row...
1727 * next time we see the situation favour POLLOUT
1729 #if !defined(LWS_WITH_ESP8266)
1730 if (wsi->favoured_pollin &&
1731 (pollfd->revents & pollfd->events & LWS_POLLOUT)) {
1732 wsi->favoured_pollin = 0;
1736 /* these states imply we MUST have an ah attached */
1738 if (wsi->state == LWSS_HTTP ||
1739 wsi->state == LWSS_HTTP_ISSUING_FILE ||
1740 wsi->state == LWSS_HTTP_HEADERS) {
1741 if (!wsi->u.hdr.ah) {
1743 //lwsl_err("wsi %p: missing ah\n", wsi);
1744 /* no autoservice beacuse we will do it next */
1745 if (lws_header_table_attach(wsi, 0)) {
1746 lwsl_err("wsi %p: failed to acquire ah\n", wsi);
1752 //lwsl_notice("%s: %p: rxpos:%d rxlen:%d\n", __func__, wsi,
1753 // ah->rxpos, ah->rxlen);
1755 /* if nothing in ah rx buffer, get some fresh rx */
1756 if (ah->rxpos == ah->rxlen) {
1757 ah->rxlen = lws_ssl_capable_read(wsi, ah->rx,
1760 //lwsl_notice("%s: wsi %p, ah->rxlen = %d\r\n",
1761 // __func__, wsi, ah->rxlen);
1762 switch (ah->rxlen) {
1764 lwsl_info("%s: read 0 len\n", __func__);
1765 /* lwsl_info(" state=%d\n", wsi->state); */
1766 // if (!wsi->hdr_parsing_completed)
1767 // lws_header_table_detach(wsi);
1769 case LWS_SSL_CAPABLE_ERROR:
1771 case LWS_SSL_CAPABLE_MORE_SERVICE:
1772 ah->rxlen = ah->rxpos = 0;
1777 if (!(ah->rxpos != ah->rxlen && ah->rxlen)) {
1778 lwsl_err("%s: assert: rxpos %d, rxlen %d\n",
1779 __func__, ah->rxpos, ah->rxlen);
1784 /* just ignore incoming if waiting for close */
1785 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
1786 n = lws_read(wsi, ah->rx + ah->rxpos,
1787 ah->rxlen - ah->rxpos);
1788 if (n < 0) /* we closed wsi */
1790 if (wsi->u.hdr.ah) {
1791 if ( wsi->u.hdr.ah->rxlen)
1792 wsi->u.hdr.ah->rxpos += n;
1794 lwsl_debug("%s: wsi %p: ah read rxpos %d, rxlen %d\n", __func__, wsi, wsi->u.hdr.ah->rxpos, wsi->u.hdr.ah->rxlen);
1796 if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen &&
1797 (wsi->mode != LWSCM_HTTP_SERVING &&
1798 wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED &&
1799 wsi->mode != LWSCM_HTTP2_SERVING))
1800 lws_header_table_detach(wsi, 1);
1808 len = lws_ssl_capable_read(wsi, pt->serv_buf,
1809 context->pt_serv_buf_size);
1810 lwsl_notice("%s: wsi %p read %d\r\n", __func__, wsi, len);
1813 lwsl_info("%s: read 0 len\n", __func__);
1814 /* lwsl_info(" state=%d\n", wsi->state); */
1815 // if (!wsi->hdr_parsing_completed)
1816 // lws_header_table_detach(wsi);
1818 case LWS_SSL_CAPABLE_ERROR:
1820 case LWS_SSL_CAPABLE_MORE_SERVICE:
1824 /* just ignore incoming if waiting for close */
1825 if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
1827 * this may want to send
1828 * (via HTTP callback for example)
1830 n = lws_read(wsi, pt->serv_buf, len);
1831 if (n < 0) /* we closed wsi */
1834 * he may have used up the
1835 * writability above, if we will defer POLLOUT
1836 * processing in favour of POLLIN, note it
1838 if (pollfd->revents & LWS_POLLOUT)
1839 wsi->favoured_pollin = 1;
1845 /* this handles POLLOUT for http serving fragments */
1847 if (!(pollfd->revents & LWS_POLLOUT))
1851 if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
1852 lwsl_notice("%s a\n", __func__);
1856 if (!wsi->hdr_parsing_completed)
1859 if (wsi->state != LWSS_HTTP_ISSUING_FILE) {
1860 n = user_callback_handle_rxflow(wsi->protocol->callback,
1861 wsi, LWS_CALLBACK_HTTP_WRITEABLE,
1862 wsi->user_space, NULL, 0);
1864 lwsl_info("writeable_fail\n");
1870 /* >0 == completion, <0 == error */
1871 n = lws_serve_http_file_fragment(wsi);
1872 if (n < 0 || (n > 0 && lws_http_transaction_completed(wsi))) {
1873 lwsl_info("completed\n");
1879 case LWSCM_SERVER_LISTENER:
1882 /* pollin means a client has connected to us then */
1885 if (!(pollfd->revents & LWS_POLLIN) || !(pollfd->events & LWS_POLLIN))
1888 /* listen socket got an unencrypted connection... */
1890 clilen = sizeof(cli_addr);
1891 lws_latency_pre(context, wsi);
1892 accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
1894 lws_latency(context, wsi, "listener accept", accept_fd,
1896 if (accept_fd < 0) {
1897 if (LWS_ERRNO == LWS_EAGAIN ||
1898 LWS_ERRNO == LWS_EWOULDBLOCK) {
1899 lwsl_err("accept asks to try again\n");
1902 lwsl_err("ERROR on accept: %s\n", strerror(LWS_ERRNO));
1906 lws_plat_set_socket_options(wsi->vhost, accept_fd);
1908 lwsl_debug("accepted new conn port %u on fd=%d\n",
1909 ntohs(cli_addr.sin_port), accept_fd);
1912 /* not very beautiful... */
1913 accept_fd = (lws_sockfd_type)pollfd;
1916 * look at who we connected to and give user code a chance
1917 * to reject based on client IP. There's no protocol selected
1918 * yet so we issue this to protocols[0]
1920 if ((wsi->vhost->protocols[0].callback)(wsi,
1921 LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
1922 NULL, (void *)(long)accept_fd, 0)) {
1923 lwsl_debug("Callback denied network connection\n");
1924 compatible_close(accept_fd);
1928 if (!lws_adopt_socket_vhost(wsi->vhost, accept_fd))
1929 /* already closed cleanly as necessary */
1933 } while (pt->fds_count < context->fd_limit_per_thread - 1 &&
1934 lws_poll_listen_fd(&pt->fds[wsi->position_in_fds_table]) > 0);
1942 if (!lws_server_socket_service_ssl(wsi, accept_fd))
1946 lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
1952 lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
1953 const char *other_headers, int other_headers_len)
1955 static const char * const intermediates[] = { "private", "public" };
1956 struct lws_context *context = lws_get_context(wsi);
1957 struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
1958 char cache_control[50], *cc = "no-store";
1959 unsigned char *response = pt->serv_buf + LWS_PRE;
1960 unsigned char *p = response;
1961 unsigned char *end = p + context->pt_serv_buf_size - LWS_PRE;
1962 int ret = 0, cclen = 8;
1964 wsi->u.http.fd = lws_plat_file_open(wsi, file, &wsi->u.http.filelen,
1967 if (wsi->u.http.fd == LWS_INVALID_FILE) {
1968 lwsl_err("Unable to open '%s'\n", file);
1973 if (lws_add_http_header_status(wsi, 200, &p, end))
1975 if (content_type && content_type[0]) {
1976 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
1977 (unsigned char *)content_type,
1978 strlen(content_type), &p, end))
1982 if (!wsi->sending_chunked) {
1983 if (lws_add_http_header_content_length(wsi, wsi->u.http.filelen, &p, end))
1986 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_TRANSFER_ENCODING,
1987 (unsigned char *)"chunked",
1992 if (wsi->cache_secs && wsi->cache_reuse) {
1993 if (wsi->cache_revalidate) {
1995 cclen = sprintf(cache_control, "%s max-age: %u",
1996 intermediates[wsi->cache_intermediaries],
2004 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CACHE_CONTROL,
2005 (unsigned char *)cc, cclen, &p, end))
2008 if (wsi->u.http.connection_type == HTTP_CONNECTION_KEEP_ALIVE)
2009 if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
2010 (unsigned char *)"keep-alive", 10, &p, end))
2013 if (other_headers) {
2014 if ((end - p) < other_headers_len)
2016 memcpy(p, other_headers, other_headers_len);
2017 p += other_headers_len;
2020 if (lws_finalize_http_header(wsi, &p, end))
2023 ret = lws_write(wsi, response, p - response, LWS_WRITE_HTTP_HEADERS);
2024 if (ret != (p - response)) {
2025 lwsl_err("_write returned %d from %d\n", ret, (p - response));
2029 wsi->u.http.filepos = 0;
2030 wsi->state = LWSS_HTTP_ISSUING_FILE;
2032 return lws_serve_http_file_fragment(wsi);
2036 lws_interpret_incoming_packet(struct lws *wsi, unsigned char **buf, size_t len)
2040 lwsl_parser("%s: received %d byte packet\n", __func__, (int)len);
2042 lwsl_hexdump(*buf, len);
2045 /* let the rx protocol state machine have as much as it needs */
2049 * we were accepting input but now we stopped doing so
2051 if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
2052 lws_rxflow_cache(wsi, *buf, 0, len);
2053 lwsl_parser("%s: cached %d\n", __func__, len);
2057 if (wsi->u.ws.rx_draining_ext) {
2058 m = lws_rx_sm(wsi, 0);
2064 /* account for what we're using in rxflow buffer */
2065 if (wsi->rxflow_buffer)
2068 /* consume payload bytes efficiently */
2069 if (wsi->lws_rx_parse_state ==
2070 LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED) {
2071 m = lws_payload_until_length_exhausted(wsi, buf, &len);
2072 if (wsi->rxflow_buffer)
2073 wsi->rxflow_pos += m;
2076 /* process the byte */
2077 m = lws_rx_sm(wsi, *(*buf)++);
2083 lwsl_parser("%s: exit with %d unused\n", __func__, (int)len);
2089 lws_server_get_canonical_hostname(struct lws_context *context,
2090 struct lws_context_creation_info *info)
2092 if (lws_check_opt(info->options, LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME))
2095 /* find canonical hostname */
2096 gethostname((char *)context->canonical_hostname,
2097 sizeof(context->canonical_hostname) - 1);
2099 lwsl_notice(" canonical_hostname = %s\n", context->canonical_hostname);
2105 #define LWS_MAX_ELEM_NAME 32
2107 enum urldecode_stateful {
2121 static const char * const mp_hdr[] = {
2122 "content-disposition: ",
2127 typedef int (*lws_urldecode_stateful_cb)(void *data,
2128 const char *name, char **buf, int len, int final);
2130 struct lws_urldecode_stateful {
2133 char name[LWS_MAX_ELEM_NAME];
2134 char temp[LWS_MAX_ELEM_NAME];
2135 char content_type[32];
2136 char content_disp[32];
2137 char content_disp_filename[256];
2138 char mime_boundary[128];
2144 unsigned int multipart_form_data:1;
2145 unsigned int inside_quote:1;
2146 unsigned int subname:1;
2147 unsigned int boundary_real_crlf:1;
2149 enum urldecode_stateful state;
2151 lws_urldecode_stateful_cb output;
2154 static struct lws_urldecode_stateful *
2155 lws_urldecode_s_create(struct lws *wsi, char *out, int out_len, void *data,
2156 lws_urldecode_stateful_cb output)
2158 struct lws_urldecode_stateful *s = lws_zalloc(sizeof(*s));
2166 s->out_len = out_len;
2174 if (lws_hdr_copy(wsi, buf, sizeof(buf), WSI_TOKEN_HTTP_CONTENT_TYPE) > 0) {
2175 /* multipart/form-data; boundary=----WebKitFormBoundarycc7YgAPEIHvgE9Bf */
2177 if (!strncmp(buf, "multipart/form-data", 19)) {
2178 s->multipart_form_data = 1;
2179 s->state = MT_LOOK_BOUND_IN;
2181 p = strstr(buf, "boundary=");
2184 s->mime_boundary[m++] = '\x0d';
2185 s->mime_boundary[m++] = '\x0a';
2186 s->mime_boundary[m++] = '-';
2187 s->mime_boundary[m++] = '-';
2188 while (m < sizeof(s->mime_boundary) - 1 &&
2190 s->mime_boundary[m++] = *p++;
2192 s->mime_boundary[m] = '\0';
2194 lwsl_notice("boundary '%s'\n", s->mime_boundary);
2203 lws_urldecode_s_process(struct lws_urldecode_stateful *s, const char *in, int len)
2209 if (s->pos == s->out_len - s->mp - 1) {
2210 if (s->output(s->data, s->name, &s->out, s->pos, 0))
2217 /* states for url arg style */
2220 s->inside_quote = 0;
2222 s->name[s->pos] = '\0';
2229 s->name[s->pos] = '\0';
2230 if (s->output(s->data, s->name, &s->out, s->pos, 1))
2237 if (s->pos >= sizeof(s->name) - 1) {
2238 lwsl_notice("Name too long\n");
2241 s->name[s->pos++] = *in++;
2250 s->out[s->pos] = '\0';
2251 if (s->output(s->data, s->name, &s->out, s->pos, 1))
2260 s->out[s->pos++] = ' ';
2263 s->out[s->pos++] = *in++;
2266 n = char_to_hex(*in);
2276 n = char_to_hex(*in);
2281 s->out[s->pos++] = sum | n;
2286 /* states for multipart / mime style */
2288 case MT_LOOK_BOUND_IN:
2290 if (*in == s->mime_boundary[s->mp] &&
2291 s->mime_boundary[s->mp]) {
2294 if (!s->mime_boundary[s->mp]) {
2296 s->state = MT_IGNORE1;
2299 if (s->output(s->data, s->name,
2300 &s->out, s->pos, 1))
2305 s->content_disp[0] = '\0';
2307 s->content_disp_filename[0] = '\0';
2308 s->boundary_real_crlf = 1;
2314 if (!s->boundary_real_crlf)
2317 memcpy(s->out + s->pos, s->mime_boundary + n, s->mp - n);
2320 goto retry_as_first;
2323 s->out[s->pos++] = *in;
2331 if (c >= 'A' && c <= 'Z')
2333 for (n = 0; n < ARRAY_SIZE(mp_hdr); n++)
2334 if (c == mp_hdr[n][s->mp]) {
2348 if (mp_hdr[hit][s->mp])
2356 s->state = MT_LOOK_BOUND_IN;
2358 s->state += hit + 1;
2362 /* form-data; name="file"; filename="t.txt" */
2364 if (*in == '\x0d') {
2365 // lwsl_notice("disp: '%s', '%s', '%s'\n",
2366 // s->content_disp, s->name,
2367 // s->content_disp_filename);
2369 if (s->content_disp_filename[0])
2370 if (s->output(s->data, s->name,
2371 &s->out, s->pos, LWS_UFS_OPEN))
2373 s->state = MT_IGNORE2;
2384 s->inside_quote ^= 1;
2390 s->temp[s->mp] = '\0';
2395 if (s->mp < sizeof(s->temp) - 1 &&
2396 (*in != ' ' || s->inside_quote))
2397 s->temp[s->mp++] = *in;
2402 if (s->mp < sizeof(s->content_disp) - 1)
2403 s->content_disp[s->mp++] = *in;
2404 s->content_disp[s->mp] = '\0';
2408 if (!strcmp(s->temp, "name")) {
2409 if (s->mp < sizeof(s->name) - 1)
2410 s->name[s->mp++] = *in;
2411 s->name[s->mp] = '\0';
2415 if (!strcmp(s->temp, "filename")) {
2416 if (s->mp < sizeof(s->content_disp_filename) - 1)
2417 s->content_disp_filename[s->mp++] = *in;
2418 s->content_disp_filename[s->mp] = '\0';
2427 s->state = MT_IGNORE2;
2429 if (s->mp < sizeof(s->content_type) - 1)
2430 s->content_type[s->mp++] = *in;
2431 s->content_type[s->mp] = '\0';
2438 s->state = MT_IGNORE2;
2445 s->state = MT_HNAME;
2455 lws_urldecode_s_destroy(struct lws_urldecode_stateful *s)
2459 if (s->state != US_IDLE)
2463 if (s->output(s->data, s->name, &s->out, s->pos, 1))
2472 struct lws_urldecode_stateful *s;
2473 lws_spa_fileupload_cb opt_cb;
2474 const char * const *param_names;
2486 lws_urldecode_spa_lookup(struct lws_spa *spa,
2491 for (n = 0; n < spa->count_params; n++)
2492 if (!strcmp(spa->param_names[n], name))
2499 lws_urldecode_spa_cb(void *data, const char *name, char **buf, int len,
2502 struct lws_spa *spa =
2503 (struct lws_spa *)data;
2506 if (spa->s->content_disp_filename[0]) {
2508 n = spa->opt_cb(spa->opt_data, name,
2509 spa->s->content_disp_filename,
2517 n = lws_urldecode_spa_lookup(spa, name);
2519 if (n == -1 || !len) /* unrecognized */
2522 if (!spa->params[n])
2523 spa->params[n] = *buf;
2525 if ((*buf) + len >= spa->end) {
2526 lwsl_notice("%s: exceeded storage\n", __func__);
2530 spa->param_length[n] += len;
2532 /* move it on inside storage */
2536 spa->s->out_len -= len + 1;
2541 LWS_VISIBLE LWS_EXTERN struct lws_spa *
2542 lws_spa_create(struct lws *wsi, const char * const *param_names,
2543 int count_params, int max_storage,
2544 lws_spa_fileupload_cb opt_cb, void *opt_data)
2546 struct lws_spa *spa = lws_zalloc(sizeof(*spa));
2551 spa->param_names = param_names;
2552 spa->count_params = count_params;
2553 spa->max_storage = max_storage;
2554 spa->opt_cb = opt_cb;
2555 spa->opt_data = opt_data;
2557 spa->storage = lws_malloc(max_storage);
2560 spa->end = spa->storage + max_storage - 1;
2562 spa->params = lws_zalloc(sizeof(char *) * count_params);
2566 spa->s = lws_urldecode_s_create(wsi, spa->storage, max_storage, spa,
2567 lws_urldecode_spa_cb);
2571 spa->param_length = lws_zalloc(sizeof(int) * count_params);
2572 if (!spa->param_length)
2575 lwsl_notice("%s: Created SPA %p\n", __func__, spa);
2580 lws_urldecode_s_destroy(spa->s);
2582 lws_free(spa->params);
2584 lws_free(spa->storage);
2591 LWS_VISIBLE LWS_EXTERN int
2592 lws_spa_process(struct lws_spa *ludspa, const char *in, int len)
2595 lwsl_err("%s: NULL spa\n");
2598 return lws_urldecode_s_process(ludspa->s, in, len);
2601 LWS_VISIBLE LWS_EXTERN int
2602 lws_spa_get_length(struct lws_spa *ludspa, int n)
2604 if (n >= ludspa->count_params)
2607 return ludspa->param_length[n];
2610 LWS_VISIBLE LWS_EXTERN const char *
2611 lws_spa_get_string(struct lws_spa *ludspa, int n)
2613 if (n >= ludspa->count_params)
2616 return ludspa->params[n];
2619 LWS_VISIBLE LWS_EXTERN int
2620 lws_spa_finalize(struct lws_spa *spa)
2623 lws_urldecode_s_destroy(spa->s);
2630 LWS_VISIBLE LWS_EXTERN int
2631 lws_spa_destroy(struct lws_spa *spa)
2635 lwsl_notice("%s: destroy spa %p\n", __func__, spa);
2638 lws_urldecode_s_destroy(spa->s);
2640 lwsl_debug("%s\n", __func__);
2642 lws_free(spa->param_length);
2643 lws_free(spa->params);
2644 lws_free(spa->storage);
2650 LWS_VISIBLE LWS_EXTERN int
2651 lws_chunked_html_process(struct lws_process_html_args *args,
2652 struct lws_process_html_state *s)
2654 char *sp, buffer[32];
2658 /* do replacements */
2660 old_len = args->len;
2663 while (sp < args->p + old_len) {
2665 if (args->len + 7 >= args->max_len) {
2666 lwsl_err("Used up interpret padding\n");
2670 if ((!s->pos && *sp == '$') || s->pos) {
2671 int hits = 0, hit = 0;
2675 s->swallow[s->pos++] = *sp;
2676 if (s->pos == sizeof(s->swallow) - 1)
2678 for (n = 0; n < s->count_vars; n++)
2679 if (!strncmp(s->swallow, s->vars[n], s->pos)) {
2685 s->swallow[s->pos] = '\0';
2686 memcpy(s->start, s->swallow, s->pos);
2692 if (hits == 1 && s->pos == strlen(s->vars[hit])) {
2693 pc = s->replace(s->data, hit);
2697 s->swallow[s->pos] = '\0';
2699 memmove(s->start + n,
2701 old_len - (sp - args->p));
2702 old_len += (n - s->pos) + 1;
2704 memcpy(s->start, pc, n);
2718 /* no space left for final chunk trailer */
2719 if (args->final && args->len + 7 >= args->max_len)
2722 n = sprintf(buffer, "%X\x0d\x0a", args->len);
2725 memcpy(args->p, buffer, n);
2729 sp = args->p + args->len;
2739 sp = args->p + args->len;