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");
319 int main (int argc, char **argv)
326 /* master file descriptor list */
327 fd_set used_fds, serv_fds, read_fds;
329 /* working structs */
330 struct addrinfo hints;
331 struct http_request *req;
332 struct uh_path_info *pin;
337 /* maximum file descriptor number */
338 int new_fd, cur_fd, max_fd = 0;
350 /* clear the master and temp sets */
355 /* handle SIGPIPE, SIGCHILD */
356 sa.sa_handler = SIG_IGN;
357 sigaction(SIGPIPE, &sa, NULL);
358 sigaction(SIGCHLD, &sa, NULL);
360 sa.sa_handler = uh_sigterm;
361 sigaction(SIGINT, &sa, NULL);
362 sigaction(SIGTERM, &sa, NULL);
364 /* prepare addrinfo hints */
365 memset(&hints, 0, sizeof(hints));
366 hints.ai_family = AF_UNSPEC;
367 hints.ai_socktype = SOCK_STREAM;
368 hints.ai_flags = AI_PASSIVE;
371 memset(&conf, 0, sizeof(conf));
372 memset(bind, 0, sizeof(bind));
375 /* init SSL context */
376 if( ! (conf.tls = uh_tls_ctx_init()) )
378 fprintf(stderr, "Failed to initalize SSL context\n");
383 while( (opt = getopt(argc, argv, "fC:K:p:s:h:c:l:L:d:")) > 0 )
390 if( (port = strrchr(optarg, ':')) != NULL )
392 if( (optarg[0] == '[') && (port > optarg) && (port[-1] == ']') )
393 memcpy(bind, optarg + 1,
394 min(sizeof(bind), (int)(port - optarg) - 2));
397 min(sizeof(bind), (int)(port - optarg)));
410 bound += uh_socket_bind(
411 &serv_fds, &max_fd, bind[0] ? bind : NULL, port,
420 if( SSL_CTX_use_certificate_file(conf.tls, optarg, SSL_FILETYPE_ASN1) < 1 )
422 fprintf(stderr, "Invalid certificate file given\n");
431 if( SSL_CTX_use_PrivateKey_file(conf.tls, optarg, SSL_FILETYPE_ASN1) < 1 )
433 fprintf(stderr, "Invalid private key file given\n");
443 if( ! realpath(optarg, conf.docroot) )
445 fprintf(stderr, "Invalid directory %s: %s\n", optarg, strerror(errno));
453 conf.cgi_prefix = optarg;
460 conf.lua_prefix = optarg;
465 conf.lua_handler = optarg;
476 if( (port = malloc(strlen(optarg)+1)) != NULL )
478 memset(port, 0, strlen(optarg)+1);
479 uh_urldecode(port, strlen(optarg), optarg, strlen(optarg));
488 "Usage: %s -p [addr:]port [-h docroot]\n"
489 " -p Bind to specified address and port, multiple allowed\n"
491 " -s Like -p but provide HTTPS on this port\n"
492 " -C ASN.1 server certificate file\n"
493 " -K ASN.1 server private key file\n"
495 " -h Specify the document root, default is '.'\n"
496 " -f Do not fork to background\n"
498 " -l URL prefix for Lua handler, default is '/lua'\n"
499 " -L Lua handler script, omit to disable Lua\n"
502 " -c URL prefix for CGI handler, default is '/cgi-bin'\n"
504 " -d URL decode given string\n"
513 if( (tls == 1) && (keys < 2) )
515 fprintf(stderr, "Missing private key or certificate file\n");
522 fprintf(stderr, "No sockets bound, unable to continue\n");
526 /* default docroot */
527 if( !conf.docroot[0] && !realpath(".", conf.docroot) )
529 fprintf(stderr, "Can not determine default document root: %s\n",
535 /* default cgi prefix */
536 if( ! conf.cgi_prefix )
537 conf.cgi_prefix = "/cgi-bin";
541 /* init Lua runtime if handler is specified */
542 if( conf.lua_handler )
544 /* default lua prefix */
545 if( ! conf.lua_prefix )
546 conf.lua_prefix = "/lua";
548 L = uh_lua_init(conf.lua_handler);
552 /* fork (if not disabled) */
566 if( (cur_fd = open("/dev/null", O_WRONLY)) > -1 )
569 if( (cur_fd = open("/dev/null", O_RDONLY)) > -1 )
572 if( (cur_fd = open("/dev/null", O_RDONLY)) > -1 )
582 /* backup server descriptor set */
588 /* create a working copy of the used fd set */
591 /* sleep until socket activity */
592 if( select(max_fd + 1, &read_fds, NULL, NULL, NULL) == -1 )
598 /* run through the existing connections looking for data to be read */
599 for( cur_fd = 0; cur_fd <= max_fd; cur_fd++ )
601 /* is a socket managed by us */
602 if( FD_ISSET(cur_fd, &read_fds) )
604 /* is one of our listen sockets */
605 if( FD_ISSET(cur_fd, &serv_fds) )
607 /* handle new connections */
608 if( (new_fd = accept(cur_fd, NULL, 0)) != -1 )
610 /* add to global client list */
611 if( (cl = uh_client_add(new_fd, uh_listener_lookup(cur_fd))) != NULL )
614 /* setup client tls context */
615 uh_tls_client_accept(cl);
618 /* add client socket to global fdset */
619 FD_SET(new_fd, &used_fds);
620 max_fd = max(max_fd, new_fd);
623 /* insufficient resources */
627 "uh_client_add(): Can not manage more than "
628 "%i client sockets, connection dropped\n",
637 /* is a client socket */
640 if( ! (cl = uh_client_lookup(cur_fd)) )
642 /* this should not happen! */
644 "uh_client_lookup(): No entry for fd %i!\n",
650 /* parse message header */
651 if( (req = uh_http_header_recv(cl)) != NULL )
653 /* dispatch request */
654 if( (pin = uh_path_lookup(cl, req->url)) != NULL )
657 if( strstr(pin->name, conf.cgi_prefix) == pin->name )
659 uh_cgi_request(cl, req, pin);
664 uh_file_request(cl, req, pin);
669 else if( strstr(req->url, conf.lua_prefix) == req->url )
671 uh_lua_request(cl, req, L);
677 uh_http_sendhf(cl, 404, "Not Found",
678 "No such file or directory");
685 uh_http_sendhf(cl, 400, "Bad Request",
686 "Malformed request received");
690 /* free client tls context */
691 uh_tls_client_close(cl);
696 /* close client socket */
698 FD_CLR(cur_fd, &used_fds);
700 /* remove from global client list */
701 uh_client_remove(cur_fd);
708 /* destroy the Lua state */