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.
20 #include "uhttpd-utils.h"
21 #include "uhttpd-file.h"
24 #include "uhttpd-cgi.h"
28 #include "uhttpd-lua.h"
32 #include "uhttpd-tls.h"
38 static void uh_sigterm(int sig)
43 static int uh_socket_bind(
44 fd_set *serv_fds, int *max_fd, const char *host, const char *port,
45 struct addrinfo *hints, int do_tls, struct config *conf
52 struct listener *l = NULL;
53 struct addrinfo *addrs = NULL, *p = NULL;
55 if( (status = getaddrinfo(host, port, hints, &addrs)) != 0 )
57 fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(status));
60 /* try to bind a new socket to each found address */
61 for( p = addrs; p; p = p->ai_next )
64 if( (sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1 )
70 /* "address already in use" */
71 if( setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1 )
73 perror("setsockopt()");
77 /* required to get parallel v4 + v6 working */
78 if( p->ai_family == AF_INET6 )
80 if( setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &yes, sizeof(yes)) == -1 )
82 perror("setsockopt()");
88 if( bind(sock, p->ai_addr, p->ai_addrlen) == -1 )
95 if( listen(sock, UH_LIMIT_CLIENTS) == -1 )
101 /* add listener to global list */
102 if( ! (l = uh_listener_add(sock, conf)) )
105 "uh_listener_add(): Can not create more than "
106 "%i listen sockets\n", UH_LIMIT_LISTENERS
114 l->tls = do_tls ? conf->tls : NULL;
117 /* add socket to server fd set */
118 FD_SET(sock, serv_fds);
119 *max_fd = max(*max_fd, sock);
134 static struct http_request * uh_http_header_parse(struct client *cl, char *buffer, int buflen)
136 char *method = &buffer[0];
138 char *version = NULL;
140 char *headers = NULL;
141 char *hdrname = NULL;
142 char *hdrdata = NULL;
147 static struct http_request req;
149 memset(&req, 0, sizeof(req));
152 /* terminate initial header line */
153 if( (headers = strfind(buffer, buflen, "\r\n", 2)) != NULL )
155 buffer[buflen-1] = 0;
160 /* find request path */
161 if( (path = strchr(buffer, ' ')) != NULL )
164 /* find http version */
165 if( (path != NULL) && ((version = strchr(path, ' ')) != NULL) )
170 if( strcmp(method, "GET") && strcmp(method, "HEAD") && strcmp(method, "POST") )
173 uh_http_response(cl, 405, "Method Not Allowed");
181 req.method = UH_HTTP_MSG_GET;
185 req.method = UH_HTTP_MSG_HEAD;
189 req.method = UH_HTTP_MSG_POST;
195 if( !path || !strlen(path) )
197 /* malformed request */
198 uh_http_response(cl, 400, "Bad Request");
207 if( strcmp(version, "HTTP/0.9") && strcmp(version, "HTTP/1.0") && strcmp(version, "HTTP/1.1") )
209 /* unsupported version */
210 uh_http_response(cl, 400, "Bad Request");
215 req.version = strtof(&version[5], NULL);
219 /* process header fields */
220 for( i = (int)(headers - buffer); i < buflen; i++ )
222 /* found eol and have name + value, push out header tuple */
223 if( hdrname && hdrdata && (buffer[i] == '\r' || buffer[i] == '\n') )
228 if( (hdrcount + 1) < array_size(req.headers) )
230 req.headers[hdrcount++] = hdrname;
231 req.headers[hdrcount++] = hdrdata;
233 hdrname = hdrdata = NULL;
239 uh_http_response(cl, 413, "Request Entity Too Large");
244 /* have name but no value and found a colon, start of value */
245 else if( hdrname && !hdrdata && ((i+2) < buflen) &&
246 (buffer[i] == ':') && (buffer[i+1] == ' ')
249 hdrdata = &buffer[i+2];
252 /* have no name and found [A-Z], start of name */
253 else if( !hdrname && isalpha(buffer[i]) && isupper(buffer[i]) )
255 hdrname = &buffer[i];
263 /* Malformed request */
264 uh_http_response(cl, 400, "Bad Request");
269 static struct http_request * uh_http_header_recv(struct client *cl)
271 char buffer[UH_LIMIT_MSGHEAD];
272 char *bufptr = &buffer[0];
275 struct timeval timeout;
279 ssize_t blen = sizeof(buffer)-1;
283 memset(buffer, 0, sizeof(buffer));
288 FD_SET(cl->socket, &reader);
290 /* fail after 0.1s */
292 timeout.tv_usec = 100000;
294 /* check whether fd is readable */
295 if( select(cl->socket + 1, &reader, NULL, NULL, &timeout) > 0 )
298 rlen = uh_tcp_peek(cl, bufptr, blen);
302 if( (idxptr = strfind(buffer, sizeof(buffer), "\r\n\r\n", 4)) )
304 blen -= uh_tcp_recv(cl, bufptr, (int)(idxptr - bufptr) + 4);
306 /* header read complete ... */
307 return uh_http_header_parse(cl, buffer, sizeof(buffer) - blen - 1);
311 rlen = uh_tcp_recv(cl, bufptr, rlen);
318 /* invalid request (unexpected eof/timeout) */
319 uh_http_response(cl, 408, "Request Timeout");
325 /* invalid request (unexpected eof/timeout) */
326 uh_http_response(cl, 408, "Request Timeout");
331 /* request entity too large */
332 uh_http_response(cl, 413, "Request Entity Too Large");
337 int main (int argc, char **argv)
344 /* master file descriptor list */
345 fd_set used_fds, serv_fds, read_fds;
347 /* working structs */
348 struct addrinfo hints;
349 struct http_request *req;
350 struct path_info *pin;
355 /* maximum file descriptor number */
356 int new_fd, cur_fd, max_fd = 0;
368 /* clear the master and temp sets */
373 /* handle SIGPIPE, SIGCHILD */
374 sa.sa_handler = SIG_IGN;
375 sigaction(SIGPIPE, &sa, NULL);
376 sigaction(SIGCHLD, &sa, NULL);
378 sa.sa_handler = uh_sigterm;
379 sigaction(SIGINT, &sa, NULL);
380 sigaction(SIGTERM, &sa, NULL);
382 /* prepare addrinfo hints */
383 memset(&hints, 0, sizeof(hints));
384 hints.ai_family = AF_UNSPEC;
385 hints.ai_socktype = SOCK_STREAM;
386 hints.ai_flags = AI_PASSIVE;
389 memset(&conf, 0, sizeof(conf));
390 memset(bind, 0, sizeof(bind));
393 /* init SSL context */
394 if( ! (conf.tls = uh_tls_ctx_init()) )
396 fprintf(stderr, "Failed to initalize SSL context\n");
401 while( (opt = getopt(argc, argv, "fC:K:p:s:h:c:l:L:d:")) > 0 )
408 if( (port = strrchr(optarg, ':')) != NULL )
410 if( (optarg[0] == '[') && (port > optarg) && (port[-1] == ']') )
411 memcpy(bind, optarg + 1,
412 min(sizeof(bind), (int)(port - optarg) - 2));
415 min(sizeof(bind), (int)(port - optarg)));
428 bound += uh_socket_bind(
429 &serv_fds, &max_fd, bind[0] ? bind : NULL, port,
438 if( SSL_CTX_use_certificate_file(conf.tls, optarg, SSL_FILETYPE_ASN1) < 1 )
440 fprintf(stderr, "Invalid certificate file given\n");
449 if( SSL_CTX_use_PrivateKey_file(conf.tls, optarg, SSL_FILETYPE_ASN1) < 1 )
451 fprintf(stderr, "Invalid private key file given\n");
461 if( ! realpath(optarg, conf.docroot) )
463 fprintf(stderr, "Invalid directory %s: %s\n", optarg, strerror(errno));
471 conf.cgi_prefix = optarg;
478 conf.lua_prefix = optarg;
483 conf.lua_handler = optarg;
494 if( (port = malloc(strlen(optarg)+1)) != NULL )
496 memset(port, 0, strlen(optarg)+1);
497 uh_urldecode(port, strlen(optarg), optarg, strlen(optarg));
506 "Usage: %s -p [addr:]port [-h docroot]\n"
507 " -p Bind to specified address and port, multiple allowed\n"
509 " -s Like -p but provide HTTPS on this port\n"
510 " -C ASN.1 server certificate file\n"
511 " -K ASN.1 server private key file\n"
513 " -h Specify the document root, default is '.'\n"
514 " -f Do not fork to background\n"
516 " -l URL prefix for Lua handler, default is '/lua'\n"
517 " -L Lua handler script, omit to disable Lua\n"
520 " -c URL prefix for CGI handler, default is '/cgi-bin'\n"
522 " -d URL decode given string\n"
531 if( (tls == 1) && (keys < 2) )
533 fprintf(stderr, "Missing private key or certificate file\n");
540 fprintf(stderr, "No sockets bound, unable to continue\n");
544 /* default docroot */
545 if( !conf.docroot[0] && !realpath(".", conf.docroot) )
547 fprintf(stderr, "Can not determine default document root: %s\n",
553 /* default cgi prefix */
554 if( ! conf.cgi_prefix )
555 conf.cgi_prefix = "/cgi-bin";
559 /* init Lua runtime if handler is specified */
560 if( conf.lua_handler )
562 /* default lua prefix */
563 if( ! conf.lua_prefix )
564 conf.lua_prefix = "/lua";
566 L = uh_lua_init(conf.lua_handler);
570 /* fork (if not disabled) */
584 if( (cur_fd = open("/dev/null", O_WRONLY)) > -1 )
587 if( (cur_fd = open("/dev/null", O_RDONLY)) > -1 )
590 if( (cur_fd = open("/dev/null", O_RDONLY)) > -1 )
600 /* backup server descriptor set */
606 /* create a working copy of the used fd set */
609 /* sleep until socket activity */
610 if( select(max_fd + 1, &read_fds, NULL, NULL, NULL) == -1 )
616 /* run through the existing connections looking for data to be read */
617 for( cur_fd = 0; cur_fd <= max_fd; cur_fd++ )
619 /* is a socket managed by us */
620 if( FD_ISSET(cur_fd, &read_fds) )
622 /* is one of our listen sockets */
623 if( FD_ISSET(cur_fd, &serv_fds) )
625 /* handle new connections */
626 if( (new_fd = accept(cur_fd, NULL, 0)) != -1 )
628 /* add to global client list */
629 if( (cl = uh_client_add(new_fd, uh_listener_lookup(cur_fd))) != NULL )
632 /* setup client tls context */
633 uh_tls_client_accept(cl);
636 /* add client socket to global fdset */
637 FD_SET(new_fd, &used_fds);
638 max_fd = max(max_fd, new_fd);
641 /* insufficient resources */
645 "uh_client_add(): Can not manage more than "
646 "%i client sockets, connection dropped\n",
655 /* is a client socket */
658 if( ! (cl = uh_client_lookup(cur_fd)) )
660 /* this should not happen! */
662 "uh_client_lookup(): No entry for fd %i!\n",
668 /* parse message header */
669 if( (req = uh_http_header_recv(cl)) != NULL )
671 /* dispatch request */
672 if( (pin = uh_path_lookup(cl, req->url)) != NULL )
675 if( strstr(pin->name, conf.cgi_prefix) == pin->name )
677 uh_cgi_request(cl, req, pin);
682 uh_file_request(cl, req, pin);
687 else if( strstr(req->url, conf.lua_prefix) == req->url )
689 uh_lua_request(cl, req, L);
695 uh_http_sendhf(cl, 404, "Not Found",
696 "No such file or directory");
703 uh_http_sendhf(cl, 400, "Bad Request",
704 "Malformed request received");
708 /* free client tls context */
709 uh_tls_client_close(cl);
714 /* close client socket */
716 FD_CLR(cur_fd, &used_fds);
718 /* remove from global client list */
719 uh_client_remove(cur_fd);
726 /* destroy the Lua state */