2 #include "uhttpd-utils.h"
3 #include "uhttpd-file.h"
6 #include "uhttpd-cgi.h"
10 #include "uhttpd-lua.h"
14 #include "uhttpd-tls.h"
20 static void uh_sigterm(int sig)
25 static int uh_socket_bind(
26 fd_set *serv_fds, int *max_fd, const char *host, const char *port,
27 struct addrinfo *hints, int do_tls, struct config *conf
34 struct listener *l = NULL;
35 struct addrinfo *addrs = NULL, *p = NULL;
37 if( (status = getaddrinfo(host, port, hints, &addrs)) != 0 )
39 fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(status));
42 /* try to bind a new socket to each found address */
43 for( p = addrs; p; p = p->ai_next )
46 if( (sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1 )
52 /* "address already in use" */
53 if( setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1 )
55 perror("setsockopt()");
59 /* required to get parallel v4 + v6 working */
60 if( p->ai_family == AF_INET6 )
62 if( setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &yes, sizeof(yes)) == -1 )
64 perror("setsockopt()");
70 if( bind(sock, p->ai_addr, p->ai_addrlen) == -1 )
77 if( listen(sock, UH_LIMIT_CLIENTS) == -1 )
83 /* add listener to global list */
84 if( ! (l = uh_listener_add(sock, conf)) )
87 "uh_listener_add(): Can not create more than "
88 "%i listen sockets\n", UH_LIMIT_LISTENERS
96 l->tls = do_tls ? conf->tls : NULL;
99 /* add socket to server fd set */
100 FD_SET(sock, serv_fds);
101 *max_fd = max(*max_fd, sock);
116 static struct http_request * uh_http_header_parse(struct client *cl, char *buffer, int buflen)
118 char *method = &buffer[0];
120 char *version = NULL;
122 char *headers = NULL;
123 char *hdrname = NULL;
124 char *hdrdata = NULL;
129 static struct http_request req;
131 memset(&req, 0, sizeof(req));
134 /* terminate initial header line */
135 if( (headers = strfind(buffer, buflen, "\r\n", 2)) != NULL )
137 buffer[buflen-1] = 0;
142 /* find request path */
143 if( (path = strchr(buffer, ' ')) != NULL )
146 /* find http version */
147 if( (path != NULL) && ((version = strchr(path, ' ')) != NULL) )
152 if( strcmp(method, "GET") && strcmp(method, "HEAD") && strcmp(method, "POST") )
155 uh_http_response(cl, 405, "Method Not Allowed");
163 req.method = UH_HTTP_MSG_GET;
167 req.method = UH_HTTP_MSG_HEAD;
171 req.method = UH_HTTP_MSG_POST;
177 if( !path || !strlen(path) )
179 /* malformed request */
180 uh_http_response(cl, 400, "Bad Request");
189 if( strcmp(version, "HTTP/0.9") && strcmp(version, "HTTP/1.0") && strcmp(version, "HTTP/1.1") )
191 /* unsupported version */
192 uh_http_response(cl, 400, "Bad Request");
197 req.version = strtof(&version[5], NULL);
201 /* process header fields */
202 for( i = (int)(headers - buffer); i < buflen; i++ )
204 /* found eol and have name + value, push out header tuple */
205 if( hdrname && hdrdata && (buffer[i] == '\r' || buffer[i] == '\n') )
210 if( (hdrcount + 1) < array_size(req.headers) )
212 req.headers[hdrcount++] = hdrname;
213 req.headers[hdrcount++] = hdrdata;
215 hdrname = hdrdata = NULL;
221 uh_http_response(cl, 413, "Request Entity Too Large");
226 /* have name but no value and found a colon, start of value */
227 else if( hdrname && !hdrdata && ((i+2) < buflen) &&
228 (buffer[i] == ':') && (buffer[i+1] == ' ')
231 hdrdata = &buffer[i+2];
234 /* have no name and found [A-Z], start of name */
235 else if( !hdrname && isalpha(buffer[i]) && isupper(buffer[i]) )
237 hdrname = &buffer[i];
245 /* Malformed request */
246 uh_http_response(cl, 400, "Bad Request");
251 static struct http_request * uh_http_header_recv(struct client *cl)
253 char buffer[UH_LIMIT_MSGHEAD];
254 char *bufptr = &buffer[0];
257 struct timeval timeout;
261 ssize_t blen = sizeof(buffer)-1;
265 memset(buffer, 0, sizeof(buffer));
270 FD_SET(cl->socket, &reader);
272 /* fail after 0.1s */
274 timeout.tv_usec = 100000;
276 /* check whether fd is readable */
277 if( select(cl->socket + 1, &reader, NULL, NULL, &timeout) > 0 )
280 rlen = uh_tcp_peek(cl, bufptr, blen);
284 if( (idxptr = strfind(buffer, sizeof(buffer), "\r\n\r\n", 4)) )
286 blen -= uh_tcp_recv(cl, bufptr, (int)(idxptr - bufptr) + 4);
288 /* header read complete ... */
289 return uh_http_header_parse(cl, buffer, sizeof(buffer) - blen - 1);
293 rlen = uh_tcp_recv(cl, bufptr, rlen);
300 /* invalid request (unexpected eof/timeout) */
301 uh_http_response(cl, 408, "Request Timeout");
307 /* invalid request (unexpected eof/timeout) */
308 uh_http_response(cl, 408, "Request Timeout");
313 /* request entity too large */
314 uh_http_response(cl, 413, "Request Entity Too Large");
318 static int uh_docroot_resolve(const char *path, char *buf)
320 char curpath[PATH_MAX];
322 if( ! getcwd(curpath, sizeof(curpath)) )
328 if( chdir(path) || !getcwd(buf, PATH_MAX) )
334 buf[strlen(buf)] = '/';
347 int main (int argc, char **argv)
354 /* master file descriptor list */
355 fd_set used_fds, serv_fds, read_fds;
357 /* working structs */
358 struct addrinfo hints;
359 struct http_request *req;
364 /* maximum file descriptor number */
365 int new_fd, cur_fd, max_fd = 0;
377 /* clear the master and temp sets */
382 /* handle SIGPIPE, SIGCHILD */
383 sa.sa_handler = SIG_IGN;
384 sigaction(SIGPIPE, &sa, NULL);
385 sigaction(SIGCHLD, &sa, NULL);
387 sa.sa_handler = uh_sigterm;
388 sigaction(SIGINT, &sa, NULL);
389 sigaction(SIGTERM, &sa, NULL);
391 /* prepare addrinfo hints */
392 memset(&hints, 0, sizeof(hints));
393 hints.ai_family = AF_UNSPEC;
394 hints.ai_socktype = SOCK_STREAM;
395 hints.ai_flags = AI_PASSIVE;
398 memset(&conf, 0, sizeof(conf));
399 memset(bind, 0, sizeof(bind));
402 /* init SSL context */
403 if( ! (conf.tls = uh_tls_ctx_init()) )
405 fprintf(stderr, "Failed to initalize SSL context\n");
410 while( (opt = getopt(argc, argv, "fC:K:p:s:h:c:l:L:d:")) > 0 )
417 if( (port = strrchr(optarg, ':')) != NULL )
419 if( (optarg[0] == '[') && (port > optarg) && (port[-1] == ']') )
420 memcpy(bind, optarg + 1,
421 min(sizeof(bind), (int)(port - optarg) - 2));
424 min(sizeof(bind), (int)(port - optarg)));
437 bound += uh_socket_bind(
438 &serv_fds, &max_fd, bind[0] ? bind : NULL, port,
447 if( SSL_CTX_use_certificate_file(conf.tls, optarg, SSL_FILETYPE_ASN1) < 1 )
449 fprintf(stderr, "Invalid certificate file given\n");
458 if( SSL_CTX_use_PrivateKey_file(conf.tls, optarg, SSL_FILETYPE_ASN1) < 1 )
460 fprintf(stderr, "Invalid private key file given\n");
470 if( ! uh_docroot_resolve(optarg, conf.docroot) )
472 fprintf(stderr, "Invalid directory: %s\n", optarg);
480 conf.cgi_prefix = optarg;
487 conf.lua_prefix = optarg;
492 conf.lua_handler = optarg;
503 if( (port = malloc(strlen(optarg)+1)) != NULL )
505 memset(port, 0, strlen(optarg)+1);
506 uh_urldecode(port, strlen(optarg), optarg, strlen(optarg));
515 "Usage: %s -p [addr:]port [-h docroot]\n"
516 " -p Bind to specified address and port, multiple allowed\n"
518 " -s Like -p but provide HTTPS on this port\n"
519 " -C ASN.1 server certificate file\n"
520 " -K ASN.1 server private key file\n"
522 " -h Specify the document root, default is '.'\n"
523 " -f Do not fork to background\n"
525 " -l URL prefix for Lua handler, default is '/lua'\n"
526 " -L Lua handler script, omit to disable Lua\n"
529 " -c URL prefix for CGI handler, default is '/cgi-bin'\n"
531 " -d URL decode given string\n"
540 if( (tls == 1) && (keys < 2) )
542 fprintf(stderr, "Missing private key or certificate file\n");
549 fprintf(stderr, "No sockets bound, unable to continue\n");
553 /* default docroot */
554 if( !conf.docroot[0] && !uh_docroot_resolve(".", conf.docroot) )
556 fprintf(stderr, "Can not determine default document root\n");
561 /* default cgi prefix */
562 if( ! conf.cgi_prefix )
563 conf.cgi_prefix = "/cgi-bin";
567 /* init Lua runtime if handler is specified */
568 if( conf.lua_handler )
570 /* default lua prefix */
571 if( ! conf.lua_prefix )
572 conf.lua_prefix = "/lua";
574 L = uh_lua_init(conf.lua_handler);
578 /* fork (if not disabled) */
592 if( (cur_fd = open("/dev/null", O_WRONLY)) > -1 )
595 if( (cur_fd = open("/dev/null", O_RDONLY)) > -1 )
598 if( (cur_fd = open("/dev/null", O_RDONLY)) > -1 )
608 /* backup server descriptor set */
614 /* create a working copy of the used fd set */
617 /* sleep until socket activity */
618 if( select(max_fd + 1, &read_fds, NULL, NULL, NULL) == -1 )
624 /* run through the existing connections looking for data to be read */
625 for( cur_fd = 0; cur_fd <= max_fd; cur_fd++ )
627 /* is a socket managed by us */
628 if( FD_ISSET(cur_fd, &read_fds) )
630 /* is one of our listen sockets */
631 if( FD_ISSET(cur_fd, &serv_fds) )
633 /* handle new connections */
634 if( (new_fd = accept(cur_fd, NULL, 0)) != -1 )
636 /* add to global client list */
637 if( (cl = uh_client_add(new_fd, uh_listener_lookup(cur_fd))) != NULL )
640 /* setup client tls context */
641 uh_tls_client_accept(cl);
644 /* add client socket to global fdset */
645 FD_SET(new_fd, &used_fds);
646 max_fd = max(max_fd, new_fd);
649 /* insufficient resources */
653 "uh_client_add(): Can not manage more than "
654 "%i client sockets, connection dropped\n",
663 /* is a client socket */
666 if( ! (cl = uh_client_lookup(cur_fd)) )
668 /* this should not happen! */
670 "uh_client_lookup(): No entry for fd %i!\n",
676 /* parse message header and dispatch request */
677 if( (req = uh_http_header_recv(cl)) != NULL )
680 if( strstr(req->url, conf.cgi_prefix) == req->url )
682 uh_cgi_request(cl, req);
689 (strstr(req->url, conf.lua_prefix) == req->url)
691 uh_lua_request(cl, req, L);
697 uh_file_request(cl, req);
703 /* free client tls context */
704 uh_tls_client_close(cl);
709 /* close client socket */
711 FD_CLR(cur_fd, &used_fds);
713 /* remove from global client list */
714 uh_client_remove(cur_fd);
721 /* destroy the Lua state */