2 * uhttpd - Tiny single-threaded httpd - Main component
4 * Copyright (C) 2010 Jo-Philipp Wich <xm@subsignal.org>
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
19 #define _XOPEN_SOURCE 500 /* crypt() */
22 #include "uhttpd-utils.h"
23 #include "uhttpd-file.h"
26 #include "uhttpd-cgi.h"
30 #include "uhttpd-lua.h"
34 #include "uhttpd-tls.h"
40 static void uh_sigterm(int sig)
45 static void uh_sigchld(int sig)
47 while (waitpid(-1, NULL, WNOHANG) > 0) { }
50 static void uh_config_parse(struct config *conf)
58 const char *path = conf->file ? conf->file : "/etc/httpd.conf";
61 if ((c = fopen(path, "r")) != NULL)
63 memset(line, 0, sizeof(line));
65 while (fgets(line, sizeof(line) - 1, c))
67 if ((line[0] == '/') && (strchr(line, ':') != NULL))
69 if (!(col1 = strchr(line, ':')) || (*col1++ = 0) ||
70 !(col2 = strchr(col1, ':')) || (*col2++ = 0) ||
71 !(eol = strchr(col2, '\n')) || (*eol++ = 0))
76 if (!uh_auth_add(line, col1, col2))
79 "Notice: No password set for user %s, ignoring "
80 "authentication on %s\n", col1, line
84 else if (!strncmp(line, "I:", 2))
86 if (!(col1 = strchr(line, ':')) || (*col1++ = 0) ||
87 !(eol = strchr(col1, '\n')) || (*eol++ = 0))
92 conf->index_file = strdup(col1);
94 else if (!strncmp(line, "E404:", 5))
96 if (!(col1 = strchr(line, ':')) || (*col1++ = 0) ||
97 !(eol = strchr(col1, '\n')) || (*eol++ = 0))
102 conf->error_handler = strdup(col1);
105 else if ((line[0] == '*') && (strchr(line, ':') != NULL))
107 if (!(col1 = strchr(line, '*')) || (*col1++ = 0) ||
108 !(col2 = strchr(col1, ':')) || (*col2++ = 0) ||
109 !(eol = strchr(col2, '\n')) || (*eol++ = 0))
114 if (!uh_interpreter_add(col1, col2))
117 "Unable to add interpreter %s for extension %s: "
118 "Out of memory\n", col2, col1
129 static int uh_socket_bind(fd_set *serv_fds, int *max_fd,
130 const char *host, const char *port,
131 struct addrinfo *hints, int do_tls,
139 int tcp_ka_idl, tcp_ka_int, tcp_ka_cnt;
141 struct listener *l = NULL;
142 struct addrinfo *addrs = NULL, *p = NULL;
144 if ((status = getaddrinfo(host, port, hints, &addrs)) != 0)
146 fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(status));
149 /* try to bind a new socket to each found address */
150 for (p = addrs; p; p = p->ai_next)
153 if ((sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
159 /* "address already in use" */
160 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)))
162 perror("setsockopt()");
167 if (conf->tcp_keepalive > 0)
171 tcp_ka_int = conf->tcp_keepalive;
173 if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(yes)) ||
174 setsockopt(sock, SOL_TCP, TCP_KEEPIDLE, &tcp_ka_idl, sizeof(tcp_ka_idl)) ||
175 setsockopt(sock, SOL_TCP, TCP_KEEPINTVL, &tcp_ka_int, sizeof(tcp_ka_int)) ||
176 setsockopt(sock, SOL_TCP, TCP_KEEPCNT, &tcp_ka_cnt, sizeof(tcp_ka_cnt)))
178 fprintf(stderr, "Notice: Unable to enable TCP keep-alive: %s\n",
183 /* required to get parallel v4 + v6 working */
184 if (p->ai_family == AF_INET6)
186 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &yes, sizeof(yes)) == -1)
188 perror("setsockopt()");
194 if (bind(sock, p->ai_addr, p->ai_addrlen) == -1)
201 if (listen(sock, UH_LIMIT_CLIENTS) == -1)
207 /* add listener to global list */
208 if (!(l = uh_listener_add(sock, conf)))
210 fprintf(stderr, "uh_listener_add(): Failed to allocate memory\n");
216 l->tls = do_tls ? conf->tls : NULL;
219 /* add socket to server fd set */
220 FD_SET(sock, serv_fds);
222 *max_fd = max(*max_fd, sock);
237 static struct http_request * uh_http_header_parse(struct client *cl,
238 char *buffer, int buflen)
240 char *method = &buffer[0];
242 char *version = NULL;
244 char *headers = NULL;
245 char *hdrname = NULL;
246 char *hdrdata = NULL;
251 static struct http_request req;
253 memset(&req, 0, sizeof(req));
256 /* terminate initial header line */
257 if ((headers = strfind(buffer, buflen, "\r\n", 2)) != NULL)
259 buffer[buflen-1] = 0;
264 /* find request path */
265 if ((path = strchr(buffer, ' ')) != NULL)
268 /* find http version */
269 if ((path != NULL) && ((version = strchr(path, ' ')) != NULL))
274 if (strcmp(method, "GET") && strcmp(method, "HEAD") && strcmp(method, "POST"))
277 uh_http_response(cl, 405, "Method Not Allowed");
285 req.method = UH_HTTP_MSG_GET;
289 req.method = UH_HTTP_MSG_HEAD;
293 req.method = UH_HTTP_MSG_POST;
299 if (!path || !strlen(path))
301 /* malformed request */
302 uh_http_response(cl, 400, "Bad Request");
311 if ((version == NULL) || (strcmp(version, "HTTP/0.9") &&
312 strcmp(version, "HTTP/1.0") && strcmp(version, "HTTP/1.1")))
314 /* unsupported version */
315 uh_http_response(cl, 400, "Bad Request");
320 req.version = strtof(&version[5], NULL);
324 /* process header fields */
325 for (i = (int)(headers - buffer); i < buflen; i++)
327 /* found eol and have name + value, push out header tuple */
328 if (hdrname && hdrdata && (buffer[i] == '\r' || buffer[i] == '\n'))
333 if ((hdrcount + 1) < array_size(req.headers))
335 req.headers[hdrcount++] = hdrname;
336 req.headers[hdrcount++] = hdrdata;
338 hdrname = hdrdata = NULL;
344 uh_http_response(cl, 413, "Request Entity Too Large");
349 /* have name but no value and found a colon, start of value */
350 else if (hdrname && !hdrdata &&
351 ((i+1) < buflen) && (buffer[i] == ':'))
354 hdrdata = &buffer[i+1];
356 while ((hdrdata + 1) < (buffer + buflen) && *hdrdata == ' ')
360 /* have no name and found [A-Za-z], start of name */
361 else if (!hdrname && isalpha(buffer[i]))
363 hdrname = &buffer[i];
368 req.redirect_status = 200;
372 /* Malformed request */
373 uh_http_response(cl, 400, "Bad Request");
378 static struct http_request * uh_http_header_recv(struct client *cl)
380 static char buffer[UH_LIMIT_MSGHEAD];
381 char *bufptr = &buffer[0];
384 struct timeval timeout;
388 ssize_t blen = sizeof(buffer)-1;
391 memset(buffer, 0, sizeof(buffer));
396 FD_SET(cl->socket, &reader);
398 /* fail after 0.1s */
400 timeout.tv_usec = 100000;
402 /* check whether fd is readable */
403 if (select(cl->socket + 1, &reader, NULL, NULL, &timeout) > 0)
406 ensure_out(rlen = uh_tcp_peek(cl, bufptr, blen));
408 if ((idxptr = strfind(buffer, sizeof(buffer), "\r\n\r\n", 4)))
410 ensure_out(rlen = uh_tcp_recv(cl, bufptr,
411 (int)(idxptr - bufptr) + 4));
413 /* header read complete ... */
415 return uh_http_header_parse(cl, buffer,
416 sizeof(buffer) - blen - 1);
420 ensure_out(rlen = uh_tcp_recv(cl, bufptr, rlen));
422 /* unexpected eof - #7904 */
432 /* invalid request (unexpected eof/timeout) */
437 /* request entity too large */
438 uh_http_response(cl, 413, "Request Entity Too Large");
444 #if defined(HAVE_LUA) || defined(HAVE_CGI)
445 static int uh_path_match(const char *prefix, const char *url)
447 if ((strstr(url, prefix) == url) &&
448 ((prefix[strlen(prefix)-1] == '/') ||
449 (strlen(url) == strlen(prefix)) ||
450 (url[strlen(prefix)] == '/')))
459 static void uh_dispatch_request(struct client *cl, struct http_request *req,
460 struct path_info *pin)
463 struct interpreter *ipr = NULL;
465 if (uh_path_match(cl->server->conf->cgi_prefix, pin->name) ||
466 (ipr = uh_interpreter_lookup(pin->phys)))
468 uh_cgi_request(cl, req, pin, ipr);
473 uh_file_request(cl, req, pin);
477 static void uh_mainloop(struct config *conf, fd_set serv_fds, int max_fd)
479 /* master file descriptor list */
480 fd_set used_fds, read_fds;
482 /* working structs */
483 struct http_request *req;
484 struct path_info *pin;
487 /* maximum file descriptor number */
488 int new_fd, cur_fd = 0;
490 /* clear the master and temp sets */
494 /* backup server descriptor set */
500 /* create a working copy of the used fd set */
503 /* sleep until socket activity */
504 if (select(max_fd + 1, &read_fds, NULL, NULL, NULL) == -1)
510 /* run through the existing connections looking for data to be read */
511 for (cur_fd = 0; cur_fd <= max_fd; cur_fd++)
513 /* is a socket managed by us */
514 if (FD_ISSET(cur_fd, &read_fds))
516 /* is one of our listen sockets */
517 if (FD_ISSET(cur_fd, &serv_fds))
519 /* handle new connections */
520 if ((new_fd = accept(cur_fd, NULL, 0)) != -1)
522 /* add to global client list */
523 if ((cl = uh_client_add(new_fd, uh_listener_lookup(cur_fd))) != NULL)
526 /* setup client tls context */
529 if (conf->tls_accept(cl) < 1)
532 "tls_accept failed, "
533 "connection dropped\n");
535 /* close client socket */
538 /* remove from global client list */
539 uh_client_remove(new_fd);
546 /* add client socket to global fdset */
547 FD_SET(new_fd, &used_fds);
549 max_fd = max(max_fd, new_fd);
552 /* insufficient resources */
557 "Cannot allocate memory\n");
564 /* is a client socket */
567 if (!(cl = uh_client_lookup(cur_fd)))
569 /* this should not happen! */
571 "uh_client_lookup(): No entry for fd %i!\n",
577 /* parse message header */
578 if ((req = uh_http_header_recv(cl)) != NULL)
580 /* RFC1918 filtering required? */
581 if (conf->rfc1918_filter &&
582 sa_rfc1918(&cl->peeraddr) &&
583 !sa_rfc1918(&cl->servaddr))
585 uh_http_sendhf(cl, 403, "Forbidden",
586 "Rejected request from RFC1918 IP "
587 "to public server address");
592 if (conf->lua_state &&
593 uh_path_match(conf->lua_prefix, req->url))
595 conf->lua_request(cl, req, conf->lua_state);
599 /* dispatch request */
600 if ((pin = uh_path_lookup(cl, req->url)) != NULL)
603 if (!pin->redirected && uh_auth_check(cl, req, pin))
604 uh_dispatch_request(cl, req, pin);
610 /* Try to invoke an error handler */
611 pin = uh_path_lookup(cl, conf->error_handler);
613 if (pin && uh_auth_check(cl, req, pin))
615 req->redirect_status = 404;
616 uh_dispatch_request(cl, req, pin);
620 uh_http_sendhf(cl, 404, "Not Found",
621 "No such file or directory");
627 /* free client tls context */
634 /* close client socket */
636 FD_CLR(cur_fd, &used_fds);
638 /* remove from global client list */
639 uh_client_remove(cur_fd);
646 /* destroy the Lua state */
647 if (conf->lua_state != NULL)
648 conf->lua_close(conf->lua_state);
653 static inline int uh_inittls(struct config *conf)
659 if (conf->tls != NULL)
662 /* load TLS plugin */
663 if (!(lib = dlopen("uhttpd_tls.so", RTLD_LAZY | RTLD_GLOBAL)))
666 "Notice: Unable to load TLS plugin - disabling SSL support! "
667 "(Reason: %s)\n", dlerror()
674 /* resolve functions */
675 if (!(conf->tls_init = dlsym(lib, "uh_tls_ctx_init")) ||
676 !(conf->tls_cert = dlsym(lib, "uh_tls_ctx_cert")) ||
677 !(conf->tls_key = dlsym(lib, "uh_tls_ctx_key")) ||
678 !(conf->tls_free = dlsym(lib, "uh_tls_ctx_free")) ||
679 !(conf->tls_accept = dlsym(lib, "uh_tls_client_accept")) ||
680 !(conf->tls_close = dlsym(lib, "uh_tls_client_close")) ||
681 !(conf->tls_recv = dlsym(lib, "uh_tls_client_recv")) ||
682 !(conf->tls_send = dlsym(lib, "uh_tls_client_send")))
685 "Error: Failed to lookup required symbols "
686 "in TLS plugin: %s\n", dlerror()
691 /* init SSL context */
692 if (!(conf->tls = conf->tls_init()))
694 fprintf(stderr, "Error: Failed to initalize SSL context\n");
703 int main (int argc, char **argv)
705 /* master file descriptor list */
708 /* working structs */
709 struct addrinfo hints;
716 /* maximum file descriptor number */
717 int cur_fd, max_fd = 0;
739 /* handle SIGPIPE, SIGINT, SIGTERM, SIGCHLD */
741 sigemptyset(&sa.sa_mask);
743 sa.sa_handler = SIG_IGN;
744 sigaction(SIGPIPE, &sa, NULL);
746 sa.sa_handler = uh_sigchld;
747 sigaction(SIGCHLD, &sa, NULL);
749 sa.sa_handler = uh_sigterm;
750 sigaction(SIGINT, &sa, NULL);
751 sigaction(SIGTERM, &sa, NULL);
755 sigaddset(&ss, SIGCHLD);
756 sigprocmask(SIG_BLOCK, &ss, NULL);
758 /* prepare addrinfo hints */
759 memset(&hints, 0, sizeof(hints));
760 hints.ai_family = AF_UNSPEC;
761 hints.ai_socktype = SOCK_STREAM;
762 hints.ai_flags = AI_PASSIVE;
765 memset(&conf, 0, sizeof(conf));
766 memset(bind, 0, sizeof(bind));
769 while ((opt = getopt(argc, argv,
770 "fSDRC:K:E:I:p:s:h:c:l:L:d:r:m:x:i:t:T:A:")) > 0)
777 if ((port = strrchr(optarg, ':')) != NULL)
779 if ((optarg[0] == '[') && (port > optarg) && (port[-1] == ']'))
780 memcpy(bind, optarg + 1,
781 min(sizeof(bind), (int)(port - optarg) - 2));
784 min(sizeof(bind), (int)(port - optarg)));
796 if (uh_inittls(&conf))
799 "Notice: TLS support is disabled, "
800 "ignoring '-s %s'\n", optarg
810 bound += uh_socket_bind(&serv_fds, &max_fd,
811 bind[0] ? bind : NULL,
812 port, &hints, (opt == 's'), &conf);
814 memset(bind, 0, sizeof(bind));
820 if (!uh_inittls(&conf))
822 if (conf.tls_cert(conf.tls, optarg) < 1)
825 "Error: Invalid certificate file given\n");
836 if (!uh_inittls(&conf))
838 if (conf.tls_key(conf.tls, optarg) < 1)
841 "Error: Invalid private key file given\n");
853 if (! realpath(optarg, conf.docroot))
855 fprintf(stderr, "Error: Invalid directory %s: %s\n",
856 optarg, strerror(errno));
863 if ((strlen(optarg) == 0) || (optarg[0] != '/'))
865 fprintf(stderr, "Error: Invalid error handler: %s\n",
869 conf.error_handler = optarg;
874 if ((strlen(optarg) == 0) || (optarg[0] == '/'))
876 fprintf(stderr, "Error: Invalid index page: %s\n",
880 conf.index_file = optarg;
883 /* don't follow symlinks */
885 conf.no_symlinks = 1;
888 /* don't list directories */
890 conf.no_dirlists = 1;
894 conf.rfc1918_filter = 1;
900 conf.cgi_prefix = optarg;
905 if ((optarg[0] == '.') && (port = strchr(optarg, '=')))
908 uh_interpreter_add(optarg, port);
912 fprintf(stderr, "Error: Invalid interpreter: %s\n",
922 conf.lua_prefix = optarg;
927 conf.lua_handler = optarg;
931 #if defined(HAVE_CGI) || defined(HAVE_LUA)
934 conf.script_timeout = atoi(optarg);
938 /* network timeout */
940 conf.network_timeout = atoi(optarg);
945 conf.tcp_keepalive = atoi(optarg);
955 if ((port = malloc(strlen(optarg)+1)) != NULL)
957 /* "decode" plus to space to retain compat */
958 for (opt = 0; optarg[opt]; opt++)
959 if (optarg[opt] == '+')
961 /* opt now contains strlen(optarg) -- no need to re-scan */
962 memset(port, 0, opt+1);
963 if (uh_urldecode(port, opt, optarg, opt) < 0)
964 fprintf(stderr, "uhttpd: invalid encoding\n");
972 /* basic auth realm */
979 printf("%s\n", crypt(optarg, "$1$"));
990 "Usage: %s -p [addr:]port [-h docroot]\n"
991 " -f Do not fork to background\n"
992 " -c file Configuration file, default is '/etc/httpd.conf'\n"
993 " -p [addr:]port Bind to specified address and port, multiple allowed\n"
995 " -s [addr:]port Like -p but provide HTTPS on this port\n"
996 " -C file ASN.1 server certificate file\n"
997 " -K file ASN.1 server private key file\n"
999 " -h directory Specify the document root, default is '.'\n"
1000 " -E string Use given virtual URL as 404 error handler\n"
1001 " -I string Use given filename as index page for directories\n"
1002 " -S Do not follow symbolic links outside of the docroot\n"
1003 " -D Do not allow directory listings, send 403 instead\n"
1004 " -R Enable RFC1918 filter\n"
1006 " -l string URL prefix for Lua handler, default is '/lua'\n"
1007 " -L file Lua handler script, omit to disable Lua\n"
1010 " -x string URL prefix for CGI handler, default is '/cgi-bin'\n"
1011 " -i .ext=path Use interpreter at path for files with the given extension\n"
1013 #if defined(HAVE_CGI) || defined(HAVE_LUA)
1014 " -t seconds CGI and Lua script timeout in seconds, default is 60\n"
1016 " -T seconds Network timeout in seconds, default is 30\n"
1017 " -d string URL decode given string\n"
1018 " -r string Specify basic auth realm\n"
1019 " -m string MD5 crypt given string\n"
1028 if ((tls == 1) && (keys < 2))
1030 fprintf(stderr, "Error: Missing private key or certificate file\n");
1037 fprintf(stderr, "Error: No sockets bound, unable to continue\n");
1041 /* default docroot */
1042 if (!conf.docroot[0] && !realpath(".", conf.docroot))
1044 fprintf(stderr, "Error: Can not determine default document root: %s\n",
1051 conf.realm = "Protected Area";
1054 uh_config_parse(&conf);
1056 /* default network timeout */
1057 if (conf.network_timeout <= 0)
1058 conf.network_timeout = 30;
1060 #if defined(HAVE_CGI) || defined(HAVE_LUA)
1061 /* default script timeout */
1062 if (conf.script_timeout <= 0)
1063 conf.script_timeout = 60;
1067 /* default cgi prefix */
1068 if (!conf.cgi_prefix)
1069 conf.cgi_prefix = "/cgi-bin";
1073 /* load Lua plugin */
1074 if (!(lib = dlopen("uhttpd_lua.so", RTLD_LAZY | RTLD_GLOBAL)))
1077 "Notice: Unable to load Lua plugin - disabling Lua support! "
1078 "(Reason: %s)\n", dlerror());
1082 /* resolve functions */
1083 if (!(conf.lua_init = dlsym(lib, "uh_lua_init")) ||
1084 !(conf.lua_close = dlsym(lib, "uh_lua_close")) ||
1085 !(conf.lua_request = dlsym(lib, "uh_lua_request")))
1088 "Error: Failed to lookup required symbols "
1089 "in Lua plugin: %s\n", dlerror()
1094 /* init Lua runtime if handler is specified */
1095 if (conf.lua_handler)
1097 /* default lua prefix */
1098 if (!conf.lua_prefix)
1099 conf.lua_prefix = "/lua";
1101 conf.lua_state = conf.lua_init(&conf);
1106 /* fork (if not disabled) */
1120 if ((cur_fd = open("/dev/null", O_WRONLY)) > -1)
1123 if ((cur_fd = open("/dev/null", O_RDONLY)) > -1)
1126 if ((cur_fd = open("/dev/null", O_RDONLY)) > -1)
1136 /* server main loop */
1137 uh_mainloop(&conf, serv_fds, max_fd);
1140 /* destroy the Lua state */
1141 if (conf.lua_state != NULL)
1142 conf.lua_close(conf.lua_state);