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;
375 /* clear the master and temp sets */
380 /* handle SIGPIPE, SIGCHILD */
381 sa.sa_handler = SIG_IGN;
382 sigaction(SIGPIPE, &sa, NULL);
383 sigaction(SIGCHLD, &sa, NULL);
385 sa.sa_handler = uh_sigterm;
386 sigaction(SIGINT, &sa, NULL);
387 sigaction(SIGTERM, &sa, NULL);
389 /* prepare addrinfo hints */
390 memset(&hints, 0, sizeof(hints));
391 hints.ai_family = AF_UNSPEC;
392 hints.ai_socktype = SOCK_STREAM;
393 hints.ai_flags = AI_PASSIVE;
396 memset(&conf, 0, sizeof(conf));
397 memset(bind, 0, sizeof(bind));
400 /* init SSL context */
401 if( ! (conf.tls = uh_tls_ctx_init()) )
403 fprintf(stderr, "Failed to initalize SSL context\n");
408 while( (opt = getopt(argc, argv, "fC:K:p:s:h:c:l:L:d:")) > 0 )
415 if( (port = strrchr(optarg, ':')) != NULL )
417 if( (optarg[0] == '[') && (port > optarg) && (port[-1] == ']') )
418 memcpy(bind, optarg + 1,
419 min(sizeof(bind), (int)(port - optarg) - 2));
422 min(sizeof(bind), (int)(port - optarg)));
432 bound += uh_socket_bind(
433 &serv_fds, &max_fd, bind[0] ? bind : NULL, port, &hints,
434 (opt == 's') ? 1 : 0, &conf
442 if( SSL_CTX_use_certificate_file(conf.tls, optarg, SSL_FILETYPE_ASN1) < 1 )
444 fprintf(stderr, "Invalid certificate file given\n");
453 if( SSL_CTX_use_PrivateKey_file(conf.tls, optarg, SSL_FILETYPE_ASN1) < 1 )
455 fprintf(stderr, "Invalid private key file given\n");
465 if( ! uh_docroot_resolve(optarg, conf.docroot) )
467 fprintf(stderr, "Invalid directory: %s\n", optarg);
475 conf.cgi_prefix = optarg;
482 conf.lua_prefix = optarg;
487 conf.lua_handler = optarg;
498 if( (port = malloc(strlen(optarg)+1)) != NULL )
500 memset(port, 0, strlen(optarg)+1);
501 uh_urldecode(port, strlen(optarg), optarg, strlen(optarg));
510 "Usage: %s -p [addr:]port [-h docroot]\n"
511 " -p Bind to specified address and port, multiple allowed\n"
513 " -s Like -p but provide HTTPS on this port\n"
514 " -C ASN.1 server certificate file\n"
515 " -K ASN.1 server private key file\n"
517 " -h Specify the document root, default is '.'\n"
518 " -f Do not fork to background\n"
520 " -l URL prefix for Lua handler, default is '/lua'\n"
521 " -L Lua handler script, default is './lua/handler.lua'\n"
524 " -c URL prefix for CGI handler, default is '/cgi-bin'\n"
526 " -d URL decode given string\n"
537 fprintf(stderr, "Missing private key or certificate file\n");
544 fprintf(stderr, "No sockets bound, unable to continue\n");
548 /* default docroot */
549 if( !conf.docroot[0] && !uh_docroot_resolve(".", conf.docroot) )
551 fprintf(stderr, "Can not determine default document root\n");
556 /* default cgi prefix */
557 if( ! conf.cgi_prefix )
558 conf.cgi_prefix = "/cgi-bin";
562 /* init Lua runtime if handler is specified */
563 if( conf.lua_handler )
565 /* default lua prefix */
566 if( ! conf.lua_prefix )
567 conf.lua_prefix = "/lua";
569 L = uh_lua_init(conf.lua_handler);
573 /* fork (if not disabled) */
587 if( (cur_fd = open("/dev/null", O_WRONLY)) > -1 )
590 if( (cur_fd = open("/dev/null", O_RDONLY)) > -1 )
593 if( (cur_fd = open("/dev/null", O_RDONLY)) > -1 )
603 /* backup server descriptor set */
609 /* create a working copy of the used fd set */
612 /* sleep until socket activity */
613 if( select(max_fd + 1, &read_fds, NULL, NULL, NULL) == -1 )
619 /* run through the existing connections looking for data to be read */
620 for( cur_fd = 0; cur_fd <= max_fd; cur_fd++ )
622 /* is a socket managed by us */
623 if( FD_ISSET(cur_fd, &read_fds) )
625 /* is one of our listen sockets */
626 if( FD_ISSET(cur_fd, &serv_fds) )
628 /* handle new connections */
629 if( (new_fd = accept(cur_fd, NULL, 0)) != -1 )
631 /* add to global client list */
632 if( (cl = uh_client_add(new_fd, uh_listener_lookup(cur_fd))) != NULL )
635 /* setup client tls context */
636 uh_tls_client_accept(cl);
639 /* add client socket to global fdset */
640 FD_SET(new_fd, &used_fds);
641 max_fd = max(max_fd, new_fd);
644 /* insufficient resources */
648 "uh_client_add(): Can not manage more than "
649 "%i client sockets, connection dropped\n",
658 /* is a client socket */
661 if( ! (cl = uh_client_lookup(cur_fd)) )
663 /* this should not happen! */
665 "uh_client_lookup(): No entry for fd %i!\n",
671 /* parse message header and dispatch request */
672 if( (req = uh_http_header_recv(cl)) != NULL )
675 if( strstr(req->url, conf.cgi_prefix) == req->url )
677 uh_cgi_request(cl, req);
684 (strstr(req->url, conf.lua_prefix) == req->url)
686 uh_lua_request(cl, req, L);
692 uh_file_request(cl, req);
698 /* free client tls context */
699 uh_tls_client_close(cl);
704 /* close client socket */
706 FD_CLR(cur_fd, &used_fds);
708 /* remove from global client list */
709 uh_client_remove(cur_fd);
716 /* destroy the Lua state */