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) )
74 if( !uh_auth_add(line, col1, col2) )
77 "Notice: No password set for user %s, ignoring "
78 "authentication on %s\n", col1, line
82 else if( !strncmp(line, "I:", 2) )
84 if( !(col1 = strchr(line, ':')) || (*col1++ = 0) ||
85 !(eol = strchr(col1, '\n')) || (*eol++ = 0) )
88 conf->index_file = strdup(col1);
90 else if( !strncmp(line, "E404:", 5) )
92 if( !(col1 = strchr(line, ':')) || (*col1++ = 0) ||
93 !(eol = strchr(col1, '\n')) || (*eol++ = 0) )
96 conf->error_handler = strdup(col1);
99 else if( (line[0] == '.') && (strchr(line, ':') != NULL) )
101 if( !(col1 = strchr(line, ':')) || (*col1++ = 0) ||
102 !(eol = strchr(col1, '\n')) || (*eol++ = 0) )
105 if( !uh_interpreter_add(line, col1) )
108 "Unable to add interpreter %s for extension %s: "
109 "Out of memory\n", col1, line
120 static int uh_socket_bind(
121 fd_set *serv_fds, int *max_fd, const char *host, const char *port,
122 struct addrinfo *hints, int do_tls, struct config *conf
129 struct listener *l = NULL;
130 struct addrinfo *addrs = NULL, *p = NULL;
132 if( (status = getaddrinfo(host, port, hints, &addrs)) != 0 )
134 fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(status));
137 /* try to bind a new socket to each found address */
138 for( p = addrs; p; p = p->ai_next )
141 if( (sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1 )
147 /* "address already in use" */
148 if( setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1 )
150 perror("setsockopt()");
154 /* required to get parallel v4 + v6 working */
155 if( p->ai_family == AF_INET6 )
157 if( setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &yes, sizeof(yes)) == -1 )
159 perror("setsockopt()");
165 if( bind(sock, p->ai_addr, p->ai_addrlen) == -1 )
172 if( listen(sock, UH_LIMIT_CLIENTS) == -1 )
178 /* add listener to global list */
179 if( ! (l = uh_listener_add(sock, conf)) )
181 fprintf(stderr, "uh_listener_add(): Failed to allocate memory\n");
187 l->tls = do_tls ? conf->tls : NULL;
190 /* add socket to server fd set */
191 FD_SET(sock, serv_fds);
193 *max_fd = max(*max_fd, sock);
208 static struct http_request * uh_http_header_parse(struct client *cl, char *buffer, int buflen)
210 char *method = &buffer[0];
212 char *version = NULL;
214 char *headers = NULL;
215 char *hdrname = NULL;
216 char *hdrdata = NULL;
221 static struct http_request req;
223 memset(&req, 0, sizeof(req));
226 /* terminate initial header line */
227 if( (headers = strfind(buffer, buflen, "\r\n", 2)) != NULL )
229 buffer[buflen-1] = 0;
234 /* find request path */
235 if( (path = strchr(buffer, ' ')) != NULL )
238 /* find http version */
239 if( (path != NULL) && ((version = strchr(path, ' ')) != NULL) )
244 if( strcmp(method, "GET") && strcmp(method, "HEAD") && strcmp(method, "POST") )
247 uh_http_response(cl, 405, "Method Not Allowed");
255 req.method = UH_HTTP_MSG_GET;
259 req.method = UH_HTTP_MSG_HEAD;
263 req.method = UH_HTTP_MSG_POST;
269 if( !path || !strlen(path) )
271 /* malformed request */
272 uh_http_response(cl, 400, "Bad Request");
281 if( (version == NULL) || (strcmp(version, "HTTP/0.9") &&
282 strcmp(version, "HTTP/1.0") && strcmp(version, "HTTP/1.1")) )
284 /* unsupported version */
285 uh_http_response(cl, 400, "Bad Request");
290 req.version = strtof(&version[5], NULL);
294 /* process header fields */
295 for( i = (int)(headers - buffer); i < buflen; i++ )
297 /* found eol and have name + value, push out header tuple */
298 if( hdrname && hdrdata && (buffer[i] == '\r' || buffer[i] == '\n') )
303 if( (hdrcount + 1) < array_size(req.headers) )
305 req.headers[hdrcount++] = hdrname;
306 req.headers[hdrcount++] = hdrdata;
308 hdrname = hdrdata = NULL;
314 uh_http_response(cl, 413, "Request Entity Too Large");
319 /* have name but no value and found a colon, start of value */
320 else if( hdrname && !hdrdata && ((i+2) < buflen) &&
321 (buffer[i] == ':') && (buffer[i+1] == ' ')
324 hdrdata = &buffer[i+2];
327 /* have no name and found [A-Z], start of name */
328 else if( !hdrname && isalpha(buffer[i]) && isupper(buffer[i]) )
330 hdrname = &buffer[i];
335 req.redirect_status = 200;
339 /* Malformed request */
340 uh_http_response(cl, 400, "Bad Request");
345 static struct http_request * uh_http_header_recv(struct client *cl)
347 static char buffer[UH_LIMIT_MSGHEAD];
348 char *bufptr = &buffer[0];
351 struct timeval timeout;
355 ssize_t blen = sizeof(buffer)-1;
359 memset(buffer, 0, sizeof(buffer));
364 FD_SET(cl->socket, &reader);
366 /* fail after 0.1s */
368 timeout.tv_usec = 100000;
370 /* check whether fd is readable */
371 if( select(cl->socket + 1, &reader, NULL, NULL, &timeout) > 0 )
374 rlen = uh_tcp_peek(cl, bufptr, blen);
378 if( (idxptr = strfind(buffer, sizeof(buffer), "\r\n\r\n", 4)) )
380 blen -= uh_tcp_recv(cl, bufptr, (int)(idxptr - bufptr) + 4);
382 /* header read complete ... */
383 return uh_http_header_parse(cl, buffer, sizeof(buffer) - blen - 1);
387 rlen = uh_tcp_recv(cl, bufptr, rlen);
394 /* invalid request (unexpected eof/timeout) */
395 uh_http_response(cl, 408, "Request Timeout");
401 /* invalid request (unexpected eof/timeout) */
402 uh_http_response(cl, 408, "Request Timeout");
407 /* request entity too large */
408 uh_http_response(cl, 413, "Request Entity Too Large");
412 #if defined(HAVE_LUA) || defined(HAVE_CGI)
413 static int uh_path_match(const char *prefix, const char *url)
415 if( (strstr(url, prefix) == url) &&
416 ((prefix[strlen(prefix)-1] == '/') ||
417 (strlen(url) == strlen(prefix)) ||
418 (url[strlen(prefix)] == '/'))
427 static void uh_dispatch_request(
428 struct client *cl, struct http_request *req, struct path_info *pin
431 struct interpreter *ipr = NULL;
433 if( uh_path_match(cl->server->conf->cgi_prefix, pin->name) ||
434 (ipr = uh_interpreter_lookup(pin->phys)) )
436 uh_cgi_request(cl, req, pin, ipr);
441 uh_file_request(cl, req, pin);
445 static void uh_mainloop(struct config *conf, fd_set serv_fds, int max_fd)
447 /* master file descriptor list */
448 fd_set used_fds, read_fds;
450 /* working structs */
451 struct http_request *req;
452 struct path_info *pin;
455 /* maximum file descriptor number */
456 int new_fd, cur_fd = 0;
458 /* clear the master and temp sets */
462 /* backup server descriptor set */
468 /* create a working copy of the used fd set */
471 /* sleep until socket activity */
472 if( select(max_fd + 1, &read_fds, NULL, NULL, NULL) == -1 )
478 /* run through the existing connections looking for data to be read */
479 for( cur_fd = 0; cur_fd <= max_fd; cur_fd++ )
481 /* is a socket managed by us */
482 if( FD_ISSET(cur_fd, &read_fds) )
484 /* is one of our listen sockets */
485 if( FD_ISSET(cur_fd, &serv_fds) )
487 /* handle new connections */
488 if( (new_fd = accept(cur_fd, NULL, 0)) != -1 )
490 /* add to global client list */
491 if( (cl = uh_client_add(new_fd, uh_listener_lookup(cur_fd))) != NULL )
494 /* setup client tls context */
496 conf->tls_accept(cl);
499 /* add client socket to global fdset */
500 FD_SET(new_fd, &used_fds);
502 max_fd = max(max_fd, new_fd);
505 /* insufficient resources */
509 "uh_client_add(): Cannot allocate memory\n");
516 /* is a client socket */
519 if( ! (cl = uh_client_lookup(cur_fd)) )
521 /* this should not happen! */
523 "uh_client_lookup(): No entry for fd %i!\n",
529 /* parse message header */
530 if( (req = uh_http_header_recv(cl)) != NULL )
532 /* RFC1918 filtering required? */
533 if( conf->rfc1918_filter &&
534 sa_rfc1918(&cl->peeraddr) &&
535 !sa_rfc1918(&cl->servaddr) )
537 uh_http_sendhf(cl, 403, "Forbidden",
538 "Rejected request from RFC1918 IP "
539 "to public server address");
544 if( conf->lua_state &&
545 uh_path_match(conf->lua_prefix, req->url) )
547 conf->lua_request(cl, req, conf->lua_state);
551 /* dispatch request */
552 if( (pin = uh_path_lookup(cl, req->url)) != NULL )
555 if( uh_auth_check(cl, req, pin) )
556 uh_dispatch_request(cl, req, pin);
562 /* Try to invoke an error handler */
563 pin = uh_path_lookup(cl, conf->error_handler);
565 if( pin && uh_auth_check(cl, req, pin) )
567 req->redirect_status = 404;
568 uh_dispatch_request(cl, req, pin);
572 uh_http_sendhf(cl, 404, "Not Found",
573 "No such file or directory");
579 /* free client tls context */
586 /* close client socket */
588 FD_CLR(cur_fd, &used_fds);
590 /* remove from global client list */
591 uh_client_remove(cur_fd);
598 /* destroy the Lua state */
599 if( conf->lua_state != NULL )
600 conf->lua_close(conf->lua_state);
605 int main (int argc, char **argv)
607 /* master file descriptor list */
608 fd_set used_fds, serv_fds, read_fds;
610 /* working structs */
611 struct addrinfo hints;
618 /* maximum file descriptor number */
619 int cur_fd, max_fd = 0;
634 #if defined(HAVE_TLS) || defined(HAVE_LUA)
639 /* clear the master and temp sets */
644 /* handle SIGPIPE, SIGINT, SIGTERM, SIGCHLD */
646 sigemptyset(&sa.sa_mask);
648 sa.sa_handler = SIG_IGN;
649 sigaction(SIGPIPE, &sa, NULL);
651 sa.sa_handler = uh_sigchld;
652 sigaction(SIGCHLD, &sa, NULL);
654 sa.sa_handler = uh_sigterm;
655 sigaction(SIGINT, &sa, NULL);
656 sigaction(SIGTERM, &sa, NULL);
660 sigaddset(&ss, SIGCHLD);
661 sigprocmask(SIG_BLOCK, &ss, NULL);
663 /* prepare addrinfo hints */
664 memset(&hints, 0, sizeof(hints));
665 hints.ai_family = AF_UNSPEC;
666 hints.ai_socktype = SOCK_STREAM;
667 hints.ai_flags = AI_PASSIVE;
670 memset(&conf, 0, sizeof(conf));
671 memset(bind, 0, sizeof(bind));
674 /* load TLS plugin */
675 if( ! (lib = dlopen("uhttpd_tls.so", RTLD_LAZY | RTLD_GLOBAL)) )
678 "Notice: Unable to load TLS plugin - disabling SSL support! "
679 "(Reason: %s)\n", dlerror()
684 /* resolve functions */
685 if( !(conf.tls_init = dlsym(lib, "uh_tls_ctx_init")) ||
686 !(conf.tls_cert = dlsym(lib, "uh_tls_ctx_cert")) ||
687 !(conf.tls_key = dlsym(lib, "uh_tls_ctx_key")) ||
688 !(conf.tls_free = dlsym(lib, "uh_tls_ctx_free")) ||
689 !(conf.tls_accept = dlsym(lib, "uh_tls_client_accept")) ||
690 !(conf.tls_close = dlsym(lib, "uh_tls_client_close")) ||
691 !(conf.tls_recv = dlsym(lib, "uh_tls_client_recv")) ||
692 !(conf.tls_send = dlsym(lib, "uh_tls_client_send"))
695 "Error: Failed to lookup required symbols "
696 "in TLS plugin: %s\n", dlerror()
701 /* init SSL context */
702 if( ! (conf.tls = conf.tls_init()) )
704 fprintf(stderr, "Error: Failed to initalize SSL context\n");
710 while( (opt = getopt(argc, argv,
711 "fSDRC:K:E:I:p:s:h:c:l:L:d:r:m:x:i:t:T:")) > 0
718 if( (port = strrchr(optarg, ':')) != NULL )
720 if( (optarg[0] == '[') && (port > optarg) && (port[-1] == ']') )
721 memcpy(bind, optarg + 1,
722 min(sizeof(bind), (int)(port - optarg) - 2));
725 min(sizeof(bind), (int)(port - optarg)));
740 "Notice: TLS support is disabled, "
741 "ignoring '-s %s'\n", optarg
751 bound += uh_socket_bind(
752 &serv_fds, &max_fd, bind[0] ? bind : NULL, port,
753 &hints, (opt == 's'), &conf
756 memset(bind, 0, sizeof(bind));
764 if( conf.tls_cert(conf.tls, optarg) < 1 )
767 "Error: Invalid certificate file given\n");
780 if( conf.tls_key(conf.tls, optarg) < 1 )
783 "Error: Invalid private key file given\n");
795 if( ! realpath(optarg, conf.docroot) )
797 fprintf(stderr, "Error: Invalid directory %s: %s\n",
798 optarg, strerror(errno));
805 if( (strlen(optarg) == 0) || (optarg[0] != '/') )
807 fprintf(stderr, "Error: Invalid error handler: %s\n",
811 conf.error_handler = optarg;
816 if( (strlen(optarg) == 0) || (optarg[0] == '/') )
818 fprintf(stderr, "Error: Invalid index page: %s\n",
822 conf.index_file = optarg;
825 /* don't follow symlinks */
827 conf.no_symlinks = 1;
830 /* don't list directories */
832 conf.no_dirlists = 1;
836 conf.rfc1918_filter = 1;
842 conf.cgi_prefix = optarg;
847 if( (optarg[0] == '.') && (port = strchr(optarg, '=')) )
850 uh_interpreter_add(optarg, port);
854 fprintf(stderr, "Error: Invalid interpreter: %s\n",
864 conf.lua_prefix = optarg;
869 conf.lua_handler = optarg;
873 #if defined(HAVE_CGI) || defined(HAVE_LUA)
876 conf.script_timeout = atoi(optarg);
880 /* network timeout */
882 conf.network_timeout = atoi(optarg);
892 if( (port = malloc(strlen(optarg)+1)) != NULL )
894 memset(port, 0, strlen(optarg)+1);
895 uh_urldecode(port, strlen(optarg), optarg, strlen(optarg));
902 /* basic auth realm */
909 printf("%s\n", crypt(optarg, "$1$"));
920 "Usage: %s -p [addr:]port [-h docroot]\n"
921 " -f Do not fork to background\n"
922 " -c file Configuration file, default is '/etc/httpd.conf'\n"
923 " -p [addr:]port Bind to specified address and port, multiple allowed\n"
925 " -s [addr:]port Like -p but provide HTTPS on this port\n"
926 " -C file ASN.1 server certificate file\n"
927 " -K file ASN.1 server private key file\n"
929 " -h directory Specify the document root, default is '.'\n"
930 " -E string Use given virtual URL as 404 error handler\n"
931 " -I string Use given filename as index page for directories\n"
932 " -S Do not follow symbolic links outside of the docroot\n"
933 " -D Do not allow directory listings, send 403 instead\n"
934 " -R Enable RFC1918 filter\n"
936 " -l string URL prefix for Lua handler, default is '/lua'\n"
937 " -L file Lua handler script, omit to disable Lua\n"
940 " -x string URL prefix for CGI handler, default is '/cgi-bin'\n"
941 " -i .ext=path Use interpreter at path for files with the given extension\n"
943 #if defined(HAVE_CGI) || defined(HAVE_LUA)
944 " -t seconds CGI and Lua script timeout in seconds, default is 60\n"
946 " -T seconds Network timeout in seconds, default is 30\n"
947 " -d string URL decode given string\n"
948 " -r string Specify basic auth realm\n"
949 " -m string MD5 crypt given string\n"
958 if( (tls == 1) && (keys < 2) )
960 fprintf(stderr, "Error: Missing private key or certificate file\n");
967 fprintf(stderr, "Error: No sockets bound, unable to continue\n");
971 /* default docroot */
972 if( !conf.docroot[0] && !realpath(".", conf.docroot) )
974 fprintf(stderr, "Error: Can not determine default document root: %s\n",
981 conf.realm = "Protected Area";
984 uh_config_parse(&conf);
986 /* default network timeout */
987 if( conf.network_timeout <= 0 )
988 conf.network_timeout = 30;
990 #if defined(HAVE_CGI) || defined(HAVE_LUA)
991 /* default script timeout */
992 if( conf.script_timeout <= 0 )
993 conf.script_timeout = 60;
997 /* default cgi prefix */
998 if( ! conf.cgi_prefix )
999 conf.cgi_prefix = "/cgi-bin";
1003 /* load Lua plugin */
1004 if( ! (lib = dlopen("uhttpd_lua.so", RTLD_LAZY | RTLD_GLOBAL)) )
1007 "Notice: Unable to load Lua plugin - disabling Lua support! "
1008 "(Reason: %s)\n", dlerror()
1013 /* resolve functions */
1014 if( !(conf.lua_init = dlsym(lib, "uh_lua_init")) ||
1015 !(conf.lua_close = dlsym(lib, "uh_lua_close")) ||
1016 !(conf.lua_request = dlsym(lib, "uh_lua_request"))
1019 "Error: Failed to lookup required symbols "
1020 "in Lua plugin: %s\n", dlerror()
1025 /* init Lua runtime if handler is specified */
1026 if( conf.lua_handler )
1028 /* default lua prefix */
1029 if( ! conf.lua_prefix )
1030 conf.lua_prefix = "/lua";
1032 conf.lua_state = conf.lua_init(conf.lua_handler);
1037 /* fork (if not disabled) */
1051 if( (cur_fd = open("/dev/null", O_WRONLY)) > -1 )
1054 if( (cur_fd = open("/dev/null", O_RDONLY)) > -1 )
1057 if( (cur_fd = open("/dev/null", O_RDONLY)) > -1 )
1067 /* server main loop */
1068 uh_mainloop(&conf, serv_fds, max_fd);
1071 /* destroy the Lua state */
1072 if( conf.lua_state != NULL )
1073 conf.lua_close(conf.lua_state);