uhttpd: - cope with options instead of lists in uci config - fix compilation without...
[oweals/openwrt.git] / package / uhttpd / src / uhttpd.c
1 /*
2  * uhttpd - Tiny single-threaded httpd - Main component
3  *
4  *   Copyright (C) 2010 Jo-Philipp Wich <xm@subsignal.org>
5  *
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
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
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.
17  */
18
19 #define _XOPEN_SOURCE 500       /* crypt() */
20
21 #include "uhttpd.h"
22 #include "uhttpd-utils.h"
23 #include "uhttpd-file.h"
24
25 #ifdef HAVE_CGI
26 #include "uhttpd-cgi.h"
27 #endif
28
29 #ifdef HAVE_LUA
30 #include "uhttpd-lua.h"
31 #endif
32
33 #ifdef HAVE_TLS
34 #include "uhttpd-tls.h"
35 #endif
36
37
38 static int run = 1;
39
40 static void uh_sigterm(int sig)
41 {
42         run = 0;
43 }
44
45 static void uh_sigchld(int sig)
46 {
47         while( waitpid(-1, NULL, WNOHANG) > 0 ) { }
48 }
49
50 static void uh_config_parse(const char *path)
51 {
52         FILE *c;
53         char line[512];
54         char *user = NULL;
55         char *pass = NULL;
56         char *eol  = NULL;
57
58         if( (c = fopen(path ? path : "/etc/httpd.conf", "r")) != NULL )
59         {
60                 memset(line, 0, sizeof(line));
61
62                 while( fgets(line, sizeof(line) - 1, c) )
63                 {
64                         if( (line[0] == '/') && (strchr(line, ':') != NULL) )
65                         {
66                                 if( !(user = strchr(line, ':')) || (*user++ = 0) ||
67                                     !(pass = strchr(user, ':')) || (*pass++ = 0) ||
68                                         !(eol = strchr(pass, '\n')) || (*eol++  = 0) )
69                                                 continue;
70
71                                 if( !uh_auth_add(line, user, pass) )
72                                 {
73                                         fprintf(stderr,
74                                                 "Can not manage more than %i basic auth realms, "
75                                                 "will skip the rest\n", UH_LIMIT_AUTHREALMS
76                                         );
77
78                                         break;
79                                 } 
80                         }
81                 }
82
83                 fclose(c);
84         }
85 }
86
87 static int uh_socket_bind(
88         fd_set *serv_fds, int *max_fd, const char *host, const char *port,
89         struct addrinfo *hints, int do_tls, struct config *conf
90 ) {
91         int sock = -1;
92         int yes = 1;
93         int status;
94         int bound = 0;
95
96         struct listener *l = NULL;
97         struct addrinfo *addrs = NULL, *p = NULL;
98
99         if( (status = getaddrinfo(host, port, hints, &addrs)) != 0 )
100         {
101                 fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(status));
102         }
103
104         /* try to bind a new socket to each found address */
105         for( p = addrs; p; p = p->ai_next )
106         {
107                 /* get the socket */
108                 if( (sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1 )
109                 {
110                         perror("socket()");
111                         goto error;
112                 }
113
114                 /* "address already in use" */
115                 if( setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1 )
116                 {
117                         perror("setsockopt()");
118                         goto error;
119                 }
120
121                 /* required to get parallel v4 + v6 working */
122                 if( p->ai_family == AF_INET6 )
123                 {
124                         if( setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &yes, sizeof(yes)) == -1 )
125                         {
126                                 perror("setsockopt()");
127                                 goto error;
128                         }
129                 }
130
131                 /* bind */
132                 if( bind(sock, p->ai_addr, p->ai_addrlen) == -1 )
133                 {
134                         perror("bind()");
135                         goto error;
136                 }
137
138                 /* listen */
139                 if( listen(sock, UH_LIMIT_CLIENTS) == -1 )
140                 {
141                         perror("listen()");
142                         goto error;
143                 }
144
145                 /* add listener to global list */
146                 if( ! (l = uh_listener_add(sock, conf)) )
147                 {
148                         fprintf(stderr,
149                                 "uh_listener_add(): Can not create more than "
150                                 "%i listen sockets\n", UH_LIMIT_LISTENERS
151                         );
152
153                         goto error;
154                 }
155
156 #ifdef HAVE_TLS
157                 /* init TLS */
158                 l->tls = do_tls ? conf->tls : NULL;
159 #endif
160
161                 /* add socket to server fd set */
162                 FD_SET(sock, serv_fds);
163                 fd_cloexec(sock);
164                 *max_fd = max(*max_fd, sock);
165
166                 bound++;
167                 continue;
168
169                 error:
170                 if( sock > 0 )
171                         close(sock);
172         }
173
174         freeaddrinfo(addrs);
175
176         return bound;
177 }
178
179 static struct http_request * uh_http_header_parse(struct client *cl, char *buffer, int buflen)
180 {
181         char *method  = &buffer[0];
182         char *path    = NULL;
183         char *version = NULL;
184
185         char *headers = NULL;
186         char *hdrname = NULL;
187         char *hdrdata = NULL;
188
189         int i;
190         int hdrcount = 0;
191
192         static struct http_request req;
193
194         memset(&req, 0, sizeof(req));
195
196
197         /* terminate initial header line */
198         if( (headers = strfind(buffer, buflen, "\r\n", 2)) != NULL )
199         {
200                 buffer[buflen-1] = 0;
201
202                 *headers++ = 0;
203                 *headers++ = 0;
204
205                 /* find request path */
206                 if( (path = strchr(buffer, ' ')) != NULL )
207                         *path++ = 0;
208
209                 /* find http version */
210                 if( (path != NULL) && ((version = strchr(path, ' ')) != NULL) )
211                         *version++ = 0;
212
213
214                 /* check method */
215                 if( strcmp(method, "GET") && strcmp(method, "HEAD") && strcmp(method, "POST") )
216                 {
217                         /* invalid method */
218                         uh_http_response(cl, 405, "Method Not Allowed");
219                         return NULL;
220                 }
221                 else
222                 {
223                         switch(method[0])
224                         {
225                                 case 'G':
226                                         req.method = UH_HTTP_MSG_GET;
227                                         break;
228
229                                 case 'H':
230                                         req.method = UH_HTTP_MSG_HEAD;
231                                         break;
232
233                                 case 'P':
234                                         req.method = UH_HTTP_MSG_POST;
235                                         break;
236                         }
237                 }
238
239                 /* check path */
240                 if( !path || !strlen(path) )
241                 {
242                         /* malformed request */
243                         uh_http_response(cl, 400, "Bad Request");
244                         return NULL;
245                 }
246                 else
247                 {
248                         req.url = path;
249                 }
250
251                 /* check version */
252                 if( strcmp(version, "HTTP/0.9") && strcmp(version, "HTTP/1.0") && strcmp(version, "HTTP/1.1") )
253                 {
254                         /* unsupported version */
255                         uh_http_response(cl, 400, "Bad Request");
256                         return NULL;
257                 }
258                 else
259                 {
260                         req.version = strtof(&version[5], NULL);
261                 }
262
263
264                 /* process header fields */
265                 for( i = (int)(headers - buffer); i < buflen; i++ )
266                 {
267                         /* found eol and have name + value, push out header tuple */
268                         if( hdrname && hdrdata && (buffer[i] == '\r' || buffer[i] == '\n') )
269                         {
270                                 buffer[i] = 0;
271
272                                 /* store */
273                                 if( (hdrcount + 1) < array_size(req.headers) )
274                                 {
275                                         req.headers[hdrcount++] = hdrname;
276                                         req.headers[hdrcount++] = hdrdata;
277
278                                         hdrname = hdrdata = NULL;
279                                 }
280
281                                 /* too large */
282                                 else
283                                 {
284                                         uh_http_response(cl, 413, "Request Entity Too Large");
285                                         return NULL;
286                                 }
287                         }
288
289                         /* have name but no value and found a colon, start of value */
290                         else if( hdrname && !hdrdata && ((i+2) < buflen) &&
291                                 (buffer[i] == ':') && (buffer[i+1] == ' ')
292                         ) {
293                                 buffer[i] = 0;
294                                 hdrdata = &buffer[i+2];
295                         }
296
297                         /* have no name and found [A-Z], start of name */
298                         else if( !hdrname && isalpha(buffer[i]) && isupper(buffer[i]) )
299                         {
300                                 hdrname = &buffer[i];
301                         }
302                 }
303
304                 /* valid enough */
305                 return &req;
306         }
307
308         /* Malformed request */
309         uh_http_response(cl, 400, "Bad Request");
310         return NULL;
311 }
312
313
314 static struct http_request * uh_http_header_recv(struct client *cl)
315 {
316         static char buffer[UH_LIMIT_MSGHEAD];
317         char *bufptr = &buffer[0];
318         char *idxptr = NULL;
319
320         struct timeval timeout;
321
322         fd_set reader;
323
324         ssize_t blen = sizeof(buffer)-1;
325         ssize_t rlen = 0;
326
327
328         memset(buffer, 0, sizeof(buffer));
329
330         while( blen > 0 )
331         {
332                 FD_ZERO(&reader);
333                 FD_SET(cl->socket, &reader);
334
335                 /* fail after 0.1s */
336                 timeout.tv_sec  = 0;
337                 timeout.tv_usec = 100000;
338
339                 /* check whether fd is readable */
340                 if( select(cl->socket + 1, &reader, NULL, NULL, &timeout) > 0 )
341                 {
342                         /* receive data */
343                         rlen = uh_tcp_peek(cl, bufptr, blen);
344
345                         if( rlen > 0 )
346                         {
347                                 if( (idxptr = strfind(buffer, sizeof(buffer), "\r\n\r\n", 4)) )
348                                 {
349                                         blen -= uh_tcp_recv(cl, bufptr, (int)(idxptr - bufptr) + 4);
350
351                                         /* header read complete ... */
352                                         return uh_http_header_parse(cl, buffer, sizeof(buffer) - blen - 1);
353                                 }
354                                 else
355                                 {
356                                         rlen = uh_tcp_recv(cl, bufptr, rlen);
357                                         blen -= rlen;
358                                         bufptr += rlen;
359                                 }
360                         }
361                         else
362                         {
363                                 /* invalid request (unexpected eof/timeout) */
364                                 uh_http_response(cl, 408, "Request Timeout");
365                                 return NULL;
366                         }
367                 }
368                 else
369                 {
370                         /* invalid request (unexpected eof/timeout) */
371                         uh_http_response(cl, 408, "Request Timeout");
372                         return NULL;
373                 }
374         }
375
376         /* request entity too large */
377         uh_http_response(cl, 413, "Request Entity Too Large");
378         return NULL;
379 }
380
381 static int uh_path_match(const char *prefix, const char *url)
382 {
383         if( (strstr(url, prefix) == url) &&
384             ((prefix[strlen(prefix)-1] == '/') ||
385                  (strlen(url) == strlen(prefix))   ||
386                  (url[strlen(prefix)] == '/'))
387         ) {
388                 return 1;
389         }
390
391         return 0;
392 }
393
394
395 int main (int argc, char **argv)
396 {
397 #ifdef HAVE_LUA
398         /* Lua runtime */
399         lua_State *L = NULL;
400 #endif
401
402         /* master file descriptor list */
403         fd_set used_fds, serv_fds, read_fds;
404
405         /* working structs */
406         struct addrinfo hints;
407         struct http_request *req;
408         struct path_info *pin;
409         struct client *cl;
410         struct sigaction sa;
411         struct config conf;
412
413         /* signal mask */
414         sigset_t ss;
415
416         /* maximum file descriptor number */
417         int new_fd, cur_fd, max_fd = 0;
418
419         int tls = 0;
420         int keys = 0;
421         int bound = 0;
422         int nofork = 0;
423
424         /* args */
425         int opt;
426         char bind[128];
427         char *port = NULL;
428
429         /* library handles */
430         void *tls_lib;
431         void *lua_lib;
432
433         /* clear the master and temp sets */
434         FD_ZERO(&used_fds);
435         FD_ZERO(&serv_fds);
436         FD_ZERO(&read_fds);
437
438         /* handle SIGPIPE, SIGINT, SIGTERM, SIGCHLD */
439         sa.sa_flags = 0;
440         sigemptyset(&sa.sa_mask);
441
442         sa.sa_handler = SIG_IGN;
443         sigaction(SIGPIPE, &sa, NULL);
444
445         sa.sa_handler = uh_sigchld;
446         sigaction(SIGCHLD, &sa, NULL);
447
448         sa.sa_handler = uh_sigterm;
449         sigaction(SIGINT,  &sa, NULL);
450         sigaction(SIGTERM, &sa, NULL);
451
452         /* defer SIGCHLD */
453         sigemptyset(&ss);
454         sigaddset(&ss, SIGCHLD);
455         sigprocmask(SIG_BLOCK, &ss, NULL);
456
457         /* prepare addrinfo hints */
458         memset(&hints, 0, sizeof(hints));
459         hints.ai_family   = AF_UNSPEC;
460         hints.ai_socktype = SOCK_STREAM;
461         hints.ai_flags    = AI_PASSIVE;
462
463         /* parse args */
464         memset(&conf, 0, sizeof(conf));
465         memset(bind, 0, sizeof(bind));
466
467 #ifdef HAVE_TLS
468         /* load TLS plugin */
469         if( ! (tls_lib = dlopen("uhttpd_tls.so", RTLD_LAZY | RTLD_GLOBAL)) )
470         {
471                 fprintf(stderr,
472                         "Notice: Unable to load TLS plugin - disabling SSL support! "
473                         "(Reason: %s)\n", dlerror()
474                 );
475         }
476         else
477         {
478                 /* resolve functions */
479                 if( !(conf.tls_init   = dlsym(tls_lib, "uh_tls_ctx_init"))      ||
480                     !(conf.tls_cert   = dlsym(tls_lib, "uh_tls_ctx_cert"))      ||
481                     !(conf.tls_key    = dlsym(tls_lib, "uh_tls_ctx_key"))       ||
482                     !(conf.tls_free   = dlsym(tls_lib, "uh_tls_ctx_free"))      ||
483                         !(conf.tls_accept = dlsym(tls_lib, "uh_tls_client_accept")) ||
484                         !(conf.tls_close  = dlsym(tls_lib, "uh_tls_client_close"))  ||
485                         !(conf.tls_recv   = dlsym(tls_lib, "uh_tls_client_recv"))   ||
486                         !(conf.tls_send   = dlsym(tls_lib, "uh_tls_client_send"))
487                 ) {
488                         fprintf(stderr,
489                                 "Error: Failed to lookup required symbols "
490                                 "in TLS plugin: %s\n", dlerror()
491                         );
492                         exit(1);
493                 }
494
495                 /* init SSL context */
496                 if( ! (conf.tls = conf.tls_init()) )
497                 {
498                         fprintf(stderr, "Error: Failed to initalize SSL context\n");
499                         exit(1);
500                 }
501         }
502 #endif
503
504         while( (opt = getopt(argc, argv, "fC:K:p:s:h:c:l:L:d:r:m:x:t:")) > 0 )
505         {
506                 switch(opt)
507                 {
508                         /* [addr:]port */
509                         case 'p':
510                         case 's':
511                                 if( (port = strrchr(optarg, ':')) != NULL )
512                                 {
513                                         if( (optarg[0] == '[') && (port > optarg) && (port[-1] == ']') )
514                                                 memcpy(bind, optarg + 1,
515                                                         min(sizeof(bind), (int)(port - optarg) - 2));
516                                         else
517                                                 memcpy(bind, optarg,
518                                                         min(sizeof(bind), (int)(port - optarg)));
519
520                                         port++;
521                                 }
522                                 else
523                                 {
524                                         port = optarg;
525                                 }
526
527 #ifdef HAVE_TLS
528                                 if( opt == 's' )
529                                 {
530                                         if( !conf.tls )
531                                         {
532                                                 fprintf(stderr,
533                                                         "Notice: TLS support is disabled, "
534                                                         "ignoring '-s %s'\n", optarg
535                                                 );
536                                                 continue;
537                                         }
538
539                                         tls = 1;
540                                 }
541 #endif
542
543                                 /* bind sockets */
544                                 bound += uh_socket_bind(
545                                         &serv_fds, &max_fd, bind[0] ? bind : NULL, port,
546                                         &hints, (opt == 's'), &conf
547                                 );
548
549                                 break;
550
551 #ifdef HAVE_TLS
552                         /* certificate */
553                         case 'C':
554                                 if( conf.tls )
555                                 {
556                                         if( conf.tls_cert(conf.tls, optarg) < 1 )
557                                         {
558                                                 fprintf(stderr,
559                                                         "Error: Invalid certificate file given\n");
560                                                 exit(1);
561                                         }
562
563                                         keys++;
564                                 }
565
566                                 break;
567
568                         /* key */
569                         case 'K':
570                                 if( conf.tls )
571                                 {
572                                         if( conf.tls_key(conf.tls, optarg) < 1 )
573                                         {
574                                                 fprintf(stderr,
575                                                         "Error: Invalid private key file given\n");
576                                                 exit(1);
577                                         }
578
579                                         keys++;
580                                 }
581
582                                 break;
583 #endif
584
585                         /* docroot */
586                         case 'h':
587                                 if( ! realpath(optarg, conf.docroot) )
588                                 {
589                                         fprintf(stderr, "Error: Invalid directory %s: %s\n",
590                                                 optarg, strerror(errno));
591                                         exit(1);
592                                 }
593                                 break;
594
595 #ifdef HAVE_CGI
596                         /* cgi prefix */
597                         case 'x':
598                                 conf.cgi_prefix = optarg;
599                                 break;
600 #endif
601
602 #ifdef HAVE_LUA
603                         /* lua prefix */
604                         case 'l':
605                                 conf.lua_prefix = optarg;
606                                 break;
607
608                         /* lua handler */
609                         case 'L':
610                                 conf.lua_handler = optarg;
611                                 break;
612 #endif
613
614 #if defined(HAVE_CGI) || defined(HAVE_LUA)
615                         /* script timeout */
616                         case 't':
617                                 conf.script_timeout = atoi(optarg);
618                                 break;
619 #endif
620
621                         /* no fork */
622                         case 'f':
623                                 nofork = 1;
624                                 break;
625
626                         /* urldecode */
627                         case 'd':
628                                 if( (port = malloc(strlen(optarg)+1)) != NULL )
629                                 {
630                                         memset(port, 0, strlen(optarg)+1);
631                                         uh_urldecode(port, strlen(optarg), optarg, strlen(optarg));
632                                         printf("%s", port);
633                                         free(port);
634                                         exit(0);
635                                 }
636                                 break;
637
638                         /* basic auth realm */
639                         case 'r':
640                                 conf.realm = optarg;
641                                 break;
642
643                         /* md5 crypt */
644                         case 'm':
645                                 printf("%s\n", crypt(optarg, "$1$"));
646                                 exit(0);
647                                 break;
648
649                         /* config file */
650                         case 'c':
651                                 conf.file = optarg;
652                                 break;
653
654                         default:
655                                 fprintf(stderr,
656                                         "Usage: %s -p [addr:]port [-h docroot]\n"
657                                         "       -f              Do not fork to background\n"
658                                         "       -c file         Configuration file, default is '/etc/httpd.conf'\n"
659                                         "       -p [addr:]port  Bind to specified address and port, multiple allowed\n"
660 #ifdef HAVE_TLS
661                                         "       -s [addr:]port  Like -p but provide HTTPS on this port\n"
662                                         "       -C file         ASN.1 server certificate file\n"
663                                         "       -K file         ASN.1 server private key file\n"
664 #endif
665                                         "       -h directory    Specify the document root, default is '.'\n"
666 #ifdef HAVE_LUA
667                                         "       -l string       URL prefix for Lua handler, default is '/lua'\n"
668                                         "       -L file         Lua handler script, omit to disable Lua\n"
669 #endif
670 #ifdef HAVE_CGI
671                                         "       -x string       URL prefix for CGI handler, default is '/cgi-bin'\n"
672 #endif
673 #if defined(HAVE_CGI) || defined(HAVE_LUA)
674                                         "       -t seconds      CGI and Lua script timeout in seconds, default is 60\n"
675 #endif
676                                         "       -d string       URL decode given string\n"
677                                         "       -r string       Specify basic auth realm\n"
678                                         "       -m string       MD5 crypt given string\n"
679                                         "\n", argv[0]
680                                 );
681
682                                 exit(1);
683                 }
684         }
685
686 #ifdef HAVE_TLS
687         if( (tls == 1) && (keys < 2) )
688         {
689                 fprintf(stderr, "Error: Missing private key or certificate file\n");
690                 exit(1);
691         }
692 #endif
693
694         if( bound < 1 )
695         {
696                 fprintf(stderr, "Error: No sockets bound, unable to continue\n");
697                 exit(1);
698         }
699
700         /* default docroot */
701         if( !conf.docroot[0] && !realpath(".", conf.docroot) )
702         {
703                 fprintf(stderr, "Error: Can not determine default document root: %s\n",
704                         strerror(errno));
705                 exit(1);
706         }
707
708         /* default realm */
709         if( ! conf.realm )
710                 conf.realm = "Protected Area";
711
712         /* config file */
713         uh_config_parse(conf.file);
714
715 #if defined(HAVE_CGI) || defined(HAVE_LUA)
716         /* default script timeout */
717         if( conf.script_timeout <= 0 )
718                 conf.script_timeout = 60;
719 #endif
720
721 #ifdef HAVE_CGI
722         /* default cgi prefix */
723         if( ! conf.cgi_prefix )
724                 conf.cgi_prefix = "/cgi-bin";
725 #endif
726
727 #ifdef HAVE_LUA
728         /* load Lua plugin */
729         if( ! (lua_lib = dlopen("uhttpd_lua.so", RTLD_LAZY | RTLD_GLOBAL)) )
730         {
731                 fprintf(stderr,
732                         "Notice: Unable to load Lua plugin - disabling Lua support! "
733                         "(Reason: %s)\n", dlerror()
734                 );
735         }
736         else
737         {
738                 /* resolve functions */
739                 if( !(conf.lua_init    = dlsym(lua_lib, "uh_lua_init"))    ||
740                     !(conf.lua_close   = dlsym(lua_lib, "uh_lua_close"))   ||
741                     !(conf.lua_request = dlsym(lua_lib, "uh_lua_request"))
742                 ) {
743                         fprintf(stderr,
744                                 "Error: Failed to lookup required symbols "
745                                 "in Lua plugin: %s\n", dlerror()
746                         );
747                         exit(1);
748                 }
749
750                 /* init Lua runtime if handler is specified */
751                 if( conf.lua_handler )
752                 {
753                         /* default lua prefix */
754                         if( ! conf.lua_prefix )
755                                 conf.lua_prefix = "/lua";
756
757                         L = conf.lua_init(conf.lua_handler);
758                 }
759         }
760 #endif
761
762         /* fork (if not disabled) */
763         if( ! nofork )
764         {
765                 switch( fork() )
766                 {
767                         case -1:
768                                 perror("fork()");
769                                 exit(1);
770
771                         case 0:
772                                 /* daemon setup */
773                                 if( chdir("/") )
774                                         perror("chdir()");
775
776                                 if( (cur_fd = open("/dev/null", O_WRONLY)) > -1 )
777                                         dup2(cur_fd, 0);
778
779                                 if( (cur_fd = open("/dev/null", O_RDONLY)) > -1 )
780                                         dup2(cur_fd, 1);
781
782                                 if( (cur_fd = open("/dev/null", O_RDONLY)) > -1 )
783                                         dup2(cur_fd, 2);
784
785                                 break;
786
787                         default:
788                                 exit(0);
789                 }
790         }
791
792         /* backup server descriptor set */
793         used_fds = serv_fds;
794
795         /* loop */
796         while(run)
797         {
798                 /* create a working copy of the used fd set */
799                 read_fds = used_fds;
800
801                 /* sleep until socket activity */
802                 if( select(max_fd + 1, &read_fds, NULL, NULL, NULL) == -1 )
803                 {
804                         perror("select()");
805                         exit(1);
806                 }
807
808                 /* run through the existing connections looking for data to be read */
809                 for( cur_fd = 0; cur_fd <= max_fd; cur_fd++ )
810                 {
811                         /* is a socket managed by us */
812                         if( FD_ISSET(cur_fd, &read_fds) )
813                         {
814                                 /* is one of our listen sockets */
815                                 if( FD_ISSET(cur_fd, &serv_fds) )
816                                 {
817                                         /* handle new connections */
818                                         if( (new_fd = accept(cur_fd, NULL, 0)) != -1 )
819                                         {
820                                                 /* add to global client list */
821                                                 if( (cl = uh_client_add(new_fd, uh_listener_lookup(cur_fd))) != NULL )
822                                                 {
823 #ifdef HAVE_TLS
824                                                         /* setup client tls context */
825                                                         if( conf.tls )
826                                                                 conf.tls_accept(cl);
827 #endif
828
829                                                         /* add client socket to global fdset */
830                                                         FD_SET(new_fd, &used_fds);
831                                                         fd_cloexec(new_fd);
832                                                         max_fd = max(max_fd, new_fd);
833                                                 }
834
835                                                 /* insufficient resources */
836                                                 else
837                                                 {
838                                                         fprintf(stderr,
839                                                                 "uh_client_add(): Can not manage more than "
840                                                                 "%i client sockets, connection dropped\n",
841                                                                 UH_LIMIT_CLIENTS
842                                                         );
843
844                                                         close(new_fd);
845                                                 }
846                                         }
847                                 }
848
849                                 /* is a client socket */
850                                 else
851                                 {
852                                         if( ! (cl = uh_client_lookup(cur_fd)) )
853                                         {
854                                                 /* this should not happen! */
855                                                 fprintf(stderr,
856                                                         "uh_client_lookup(): No entry for fd %i!\n",
857                                                         cur_fd);
858
859                                                 goto cleanup;
860                                         }
861
862                                         /* parse message header */
863                                         if( (req = uh_http_header_recv(cl)) != NULL )
864                                         {
865 #ifdef HAVE_LUA
866                                                 /* Lua request? */
867                                                 if( L && uh_path_match(conf.lua_prefix, req->url) )
868                                                 {
869                                                         conf.lua_request(cl, req, L);
870                                                 }
871                                                 else
872 #endif
873                                                 /* dispatch request */
874                                                 if( (pin = uh_path_lookup(cl, req->url)) != NULL )
875                                                 {
876                                                         /* auth ok? */
877                                                         if( uh_auth_check(cl, req, pin) )
878                                                         {
879 #ifdef HAVE_CGI
880                                                                 if( uh_path_match(conf.cgi_prefix, pin->name) )
881                                                                 {
882                                                                         uh_cgi_request(cl, req, pin);
883                                                                 }
884                                                                 else
885 #endif
886                                                                 {
887                                                                         uh_file_request(cl, req, pin);
888                                                                 }
889                                                         }
890                                                 }
891
892                                                 /* 404 */
893                                                 else
894                                                 {
895                                                         uh_http_sendhf(cl, 404, "Not Found",
896                                                                 "No such file or directory");
897                                                 }
898                                         }
899
900                                         /* 400 */
901                                         else
902                                         {
903                                                 uh_http_sendhf(cl, 400, "Bad Request",
904                                                         "Malformed request received");
905                                         }
906
907 #ifdef HAVE_TLS
908                                         /* free client tls context */
909                                         if( conf.tls )
910                                                 conf.tls_close(cl);
911 #endif
912
913                                         cleanup:
914
915                                         /* close client socket */
916                                         close(cur_fd);
917                                         FD_CLR(cur_fd, &used_fds);
918
919                                         /* remove from global client list */
920                                         uh_client_remove(cur_fd);
921                                 }
922                         }
923                 }
924         }
925
926 #ifdef HAVE_LUA
927         /* destroy the Lua state */
928         if( L != NULL )
929                 conf.lua_close(L);
930 #endif
931
932         return 0;
933 }
934