2 * uhttpd - Tiny non-forking 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_config_parse(const char *path)
53 if( (c = fopen(path ? path : "/etc/httpd.conf", "r")) != NULL )
55 memset(line, 0, sizeof(line));
57 while( fgets(line, sizeof(line) - 1, c) )
59 if( (line[0] == '/') && (strchr(line, ':') != NULL) )
61 if( !(user = strchr(line, ':')) || (*user++ = 0) ||
62 !(pass = strchr(user, ':')) || (*pass++ = 0) ||
63 !(eol = strchr(pass, '\n')) || (*eol++ = 0) )
66 if( !uh_auth_add(line, user, pass) )
69 "Can not manage more than %i basic auth realms, "
70 "will skip the rest\n", UH_LIMIT_AUTHREALMS
82 static int uh_socket_bind(
83 fd_set *serv_fds, int *max_fd, const char *host, const char *port,
84 struct addrinfo *hints, int do_tls, struct config *conf
91 struct listener *l = NULL;
92 struct addrinfo *addrs = NULL, *p = NULL;
94 if( (status = getaddrinfo(host, port, hints, &addrs)) != 0 )
96 fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(status));
99 /* try to bind a new socket to each found address */
100 for( p = addrs; p; p = p->ai_next )
103 if( (sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1 )
109 /* "address already in use" */
110 if( setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1 )
112 perror("setsockopt()");
116 /* required to get parallel v4 + v6 working */
117 if( p->ai_family == AF_INET6 )
119 if( setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &yes, sizeof(yes)) == -1 )
121 perror("setsockopt()");
127 if( bind(sock, p->ai_addr, p->ai_addrlen) == -1 )
134 if( listen(sock, UH_LIMIT_CLIENTS) == -1 )
140 /* add listener to global list */
141 if( ! (l = uh_listener_add(sock, conf)) )
144 "uh_listener_add(): Can not create more than "
145 "%i listen sockets\n", UH_LIMIT_LISTENERS
153 l->tls = do_tls ? conf->tls : NULL;
156 /* add socket to server fd set */
157 FD_SET(sock, serv_fds);
158 *max_fd = max(*max_fd, sock);
173 static struct http_request * uh_http_header_parse(struct client *cl, char *buffer, int buflen)
175 char *method = &buffer[0];
177 char *version = NULL;
179 char *headers = NULL;
180 char *hdrname = NULL;
181 char *hdrdata = NULL;
186 static struct http_request req;
188 memset(&req, 0, sizeof(req));
191 /* terminate initial header line */
192 if( (headers = strfind(buffer, buflen, "\r\n", 2)) != NULL )
194 buffer[buflen-1] = 0;
199 /* find request path */
200 if( (path = strchr(buffer, ' ')) != NULL )
203 /* find http version */
204 if( (path != NULL) && ((version = strchr(path, ' ')) != NULL) )
209 if( strcmp(method, "GET") && strcmp(method, "HEAD") && strcmp(method, "POST") )
212 uh_http_response(cl, 405, "Method Not Allowed");
220 req.method = UH_HTTP_MSG_GET;
224 req.method = UH_HTTP_MSG_HEAD;
228 req.method = UH_HTTP_MSG_POST;
234 if( !path || !strlen(path) )
236 /* malformed request */
237 uh_http_response(cl, 400, "Bad Request");
246 if( strcmp(version, "HTTP/0.9") && strcmp(version, "HTTP/1.0") && strcmp(version, "HTTP/1.1") )
248 /* unsupported version */
249 uh_http_response(cl, 400, "Bad Request");
254 req.version = strtof(&version[5], NULL);
258 /* process header fields */
259 for( i = (int)(headers - buffer); i < buflen; i++ )
261 /* found eol and have name + value, push out header tuple */
262 if( hdrname && hdrdata && (buffer[i] == '\r' || buffer[i] == '\n') )
267 if( (hdrcount + 1) < array_size(req.headers) )
269 req.headers[hdrcount++] = hdrname;
270 req.headers[hdrcount++] = hdrdata;
272 hdrname = hdrdata = NULL;
278 uh_http_response(cl, 413, "Request Entity Too Large");
283 /* have name but no value and found a colon, start of value */
284 else if( hdrname && !hdrdata && ((i+2) < buflen) &&
285 (buffer[i] == ':') && (buffer[i+1] == ' ')
288 hdrdata = &buffer[i+2];
291 /* have no name and found [A-Z], start of name */
292 else if( !hdrname && isalpha(buffer[i]) && isupper(buffer[i]) )
294 hdrname = &buffer[i];
302 /* Malformed request */
303 uh_http_response(cl, 400, "Bad Request");
308 static struct http_request * uh_http_header_recv(struct client *cl)
310 static char buffer[UH_LIMIT_MSGHEAD];
311 char *bufptr = &buffer[0];
314 struct timeval timeout;
318 ssize_t blen = sizeof(buffer)-1;
322 memset(buffer, 0, sizeof(buffer));
327 FD_SET(cl->socket, &reader);
329 /* fail after 0.1s */
331 timeout.tv_usec = 100000;
333 /* check whether fd is readable */
334 if( select(cl->socket + 1, &reader, NULL, NULL, &timeout) > 0 )
337 rlen = uh_tcp_peek(cl, bufptr, blen);
341 if( (idxptr = strfind(buffer, sizeof(buffer), "\r\n\r\n", 4)) )
343 blen -= uh_tcp_recv(cl, bufptr, (int)(idxptr - bufptr) + 4);
345 /* header read complete ... */
346 return uh_http_header_parse(cl, buffer, sizeof(buffer) - blen - 1);
350 rlen = uh_tcp_recv(cl, bufptr, rlen);
357 /* invalid request (unexpected eof/timeout) */
358 uh_http_response(cl, 408, "Request Timeout");
364 /* invalid request (unexpected eof/timeout) */
365 uh_http_response(cl, 408, "Request Timeout");
370 /* request entity too large */
371 uh_http_response(cl, 413, "Request Entity Too Large");
376 int main (int argc, char **argv)
383 /* master file descriptor list */
384 fd_set used_fds, serv_fds, read_fds;
386 /* working structs */
387 struct addrinfo hints;
388 struct http_request *req;
389 struct path_info *pin;
394 /* maximum file descriptor number */
395 int new_fd, cur_fd, max_fd = 0;
407 /* clear the master and temp sets */
412 /* handle SIGPIPE, SIGCHILD */
413 sa.sa_handler = SIG_IGN;
414 sigaction(SIGPIPE, &sa, NULL);
415 sigaction(SIGCHLD, &sa, NULL);
417 sa.sa_handler = uh_sigterm;
418 sigaction(SIGINT, &sa, NULL);
419 sigaction(SIGTERM, &sa, NULL);
421 /* prepare addrinfo hints */
422 memset(&hints, 0, sizeof(hints));
423 hints.ai_family = AF_UNSPEC;
424 hints.ai_socktype = SOCK_STREAM;
425 hints.ai_flags = AI_PASSIVE;
428 memset(&conf, 0, sizeof(conf));
429 memset(bind, 0, sizeof(bind));
432 /* init SSL context */
433 if( ! (conf.tls = uh_tls_ctx_init()) )
435 fprintf(stderr, "Failed to initalize SSL context\n");
440 while( (opt = getopt(argc, argv, "fC:K:p:s:h:c:l:L:d:r:m:x:")) > 0 )
447 if( (port = strrchr(optarg, ':')) != NULL )
449 if( (optarg[0] == '[') && (port > optarg) && (port[-1] == ']') )
450 memcpy(bind, optarg + 1,
451 min(sizeof(bind), (int)(port - optarg) - 2));
454 min(sizeof(bind), (int)(port - optarg)));
467 bound += uh_socket_bind(
468 &serv_fds, &max_fd, bind[0] ? bind : NULL, port,
477 if( SSL_CTX_use_certificate_file(conf.tls, optarg, SSL_FILETYPE_ASN1) < 1 )
479 fprintf(stderr, "Invalid certificate file given\n");
488 if( SSL_CTX_use_PrivateKey_file(conf.tls, optarg, SSL_FILETYPE_ASN1) < 1 )
490 fprintf(stderr, "Invalid private key file given\n");
500 if( ! realpath(optarg, conf.docroot) )
502 fprintf(stderr, "Invalid directory %s: %s\n", optarg, strerror(errno));
510 conf.cgi_prefix = optarg;
517 conf.lua_prefix = optarg;
522 conf.lua_handler = optarg;
533 if( (port = malloc(strlen(optarg)+1)) != NULL )
535 memset(port, 0, strlen(optarg)+1);
536 uh_urldecode(port, strlen(optarg), optarg, strlen(optarg));
543 /* basic auth realm */
550 printf("%s\n", crypt(optarg, "$1$"));
561 "Usage: %s -p [addr:]port [-h docroot]\n"
562 " -f Do not fork to background\n"
563 " -c file Configuration file, default is '/etc/httpd.conf'\n"
564 " -p [addr:]port Bind to specified address and port, multiple allowed\n"
566 " -s [addr:]port Like -p but provide HTTPS on this port\n"
567 " -C file ASN.1 server certificate file\n"
568 " -K file ASN.1 server private key file\n"
570 " -h directory Specify the document root, default is '.'\n"
572 " -l string URL prefix for Lua handler, default is '/lua'\n"
573 " -L file Lua handler script, omit to disable Lua\n"
576 " -x string URL prefix for CGI handler, default is '/cgi-bin'\n"
578 " -d string URL decode given string\n"
579 " -r string Specify basic auth realm\n"
580 " -m string MD5 crypt given string\n"
589 if( (tls == 1) && (keys < 2) )
591 fprintf(stderr, "Missing private key or certificate file\n");
598 fprintf(stderr, "No sockets bound, unable to continue\n");
602 /* default docroot */
603 if( !conf.docroot[0] && !realpath(".", conf.docroot) )
605 fprintf(stderr, "Can not determine default document root: %s\n",
612 conf.realm = "Protected Area";
615 uh_config_parse(conf.file);
618 /* default cgi prefix */
619 if( ! conf.cgi_prefix )
620 conf.cgi_prefix = "/cgi-bin";
624 /* init Lua runtime if handler is specified */
625 if( conf.lua_handler )
627 /* default lua prefix */
628 if( ! conf.lua_prefix )
629 conf.lua_prefix = "/lua";
631 L = uh_lua_init(conf.lua_handler);
635 /* fork (if not disabled) */
649 if( (cur_fd = open("/dev/null", O_WRONLY)) > -1 )
652 if( (cur_fd = open("/dev/null", O_RDONLY)) > -1 )
655 if( (cur_fd = open("/dev/null", O_RDONLY)) > -1 )
665 /* backup server descriptor set */
671 /* create a working copy of the used fd set */
674 /* sleep until socket activity */
675 if( select(max_fd + 1, &read_fds, NULL, NULL, NULL) == -1 )
681 /* run through the existing connections looking for data to be read */
682 for( cur_fd = 0; cur_fd <= max_fd; cur_fd++ )
684 /* is a socket managed by us */
685 if( FD_ISSET(cur_fd, &read_fds) )
687 /* is one of our listen sockets */
688 if( FD_ISSET(cur_fd, &serv_fds) )
690 /* handle new connections */
691 if( (new_fd = accept(cur_fd, NULL, 0)) != -1 )
693 /* add to global client list */
694 if( (cl = uh_client_add(new_fd, uh_listener_lookup(cur_fd))) != NULL )
697 /* setup client tls context */
698 uh_tls_client_accept(cl);
701 /* add client socket to global fdset */
702 FD_SET(new_fd, &used_fds);
703 max_fd = max(max_fd, new_fd);
706 /* insufficient resources */
710 "uh_client_add(): Can not manage more than "
711 "%i client sockets, connection dropped\n",
720 /* is a client socket */
723 if( ! (cl = uh_client_lookup(cur_fd)) )
725 /* this should not happen! */
727 "uh_client_lookup(): No entry for fd %i!\n",
733 /* parse message header */
734 if( (req = uh_http_header_recv(cl)) != NULL )
738 if( L && strstr(req->url, conf.lua_prefix) == req->url )
740 uh_lua_request(cl, req, L);
744 /* dispatch request */
745 if( (pin = uh_path_lookup(cl, req->url)) != NULL )
748 if( uh_auth_check(cl, req, pin) )
751 if( strstr(pin->name, conf.cgi_prefix) == pin->name )
753 uh_cgi_request(cl, req, pin);
758 uh_file_request(cl, req, pin);
766 uh_http_sendhf(cl, 404, "Not Found",
767 "No such file or directory");
774 uh_http_sendhf(cl, 400, "Bad Request",
775 "Malformed request received");
779 /* free client tls context */
780 uh_tls_client_close(cl);
785 /* close client socket */
787 FD_CLR(cur_fd, &used_fds);
789 /* remove from global client list */
790 uh_client_remove(cur_fd);
797 /* destroy the Lua state */