uhttpd: only enable Lua runtime if a handler was specified
[project/luci.git] / contrib / package / uhttpd / src / uhttpd.c
1 #include "uhttpd.h"
2 #include "uhttpd-utils.h"
3 #include "uhttpd-file.h"
4
5 #ifdef HAVE_CGI
6 #include "uhttpd-cgi.h"
7 #endif
8
9 #ifdef HAVE_LUA
10 #include "uhttpd-lua.h"
11 #endif
12
13 #ifdef HAVE_TLS
14 #include "uhttpd-tls.h"
15 #endif
16
17
18 static int run = 1;
19
20 static void uh_sigterm(int sig)
21 {
22         run = 0;
23 }
24
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
28 ) {
29         int sock = -1;
30         int yes = 1;
31         int status;
32         int bound = 0;
33
34         struct listener *l = NULL;
35         struct addrinfo *addrs = NULL, *p = NULL;
36
37         if( (status = getaddrinfo(host, port, hints, &addrs)) != 0 )
38         {
39                 fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(status));
40         }
41
42         /* try to bind a new socket to each found address */
43         for( p = addrs; p; p = p->ai_next )
44         {
45                 /* get the socket */
46                 if( (sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1 )
47                 {
48                         perror("socket()");
49                         goto error;
50                 }
51
52                 /* "address already in use" */
53                 if( setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1 )
54                 {
55                         perror("setsockopt()");
56                         goto error;
57                 }
58
59                 /* required to get parallel v4 + v6 working */
60                 if( p->ai_family == AF_INET6 )
61                 {
62                         if( setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &yes, sizeof(yes)) == -1 )
63                         {
64                                 perror("setsockopt()");
65                                 goto error;
66                         }
67                 }
68
69                 /* bind */
70                 if( bind(sock, p->ai_addr, p->ai_addrlen) == -1 )
71                 {
72                         perror("bind()");
73                         goto error;
74                 }
75
76                 /* listen */
77                 if( listen(sock, UH_LIMIT_CLIENTS) == -1 )
78                 {
79                         perror("listen()");
80                         goto error;
81                 }
82
83                 /* add listener to global list */
84                 if( ! (l = uh_listener_add(sock, conf)) )
85                 {
86                         fprintf(stderr,
87                                 "uh_listener_add(): Can not create more than "
88                                 "%i listen sockets\n", UH_LIMIT_LISTENERS
89                         );
90
91                         goto error;
92                 }
93
94 #ifdef HAVE_TLS
95                 /* init TLS */
96                 l->tls = do_tls ? conf->tls : NULL;
97 #endif
98
99                 /* add socket to server fd set */
100                 FD_SET(sock, serv_fds);
101                 *max_fd = max(*max_fd, sock);
102
103                 bound++;
104                 continue;
105
106                 error:
107                 if( sock > 0 )  
108                         close(sock);
109         }
110
111         freeaddrinfo(addrs);
112
113         return bound;
114 }
115
116 static struct http_request * uh_http_header_parse(struct client *cl, char *buffer, int buflen)
117 {
118         char *method  = &buffer[0];
119         char *path    = NULL;
120         char *version = NULL;
121
122         char *headers = NULL;
123         char *hdrname = NULL;
124         char *hdrdata = NULL;
125
126         int i;
127         int hdrcount = 0;
128
129         static struct http_request req;
130
131         memset(&req, 0, sizeof(req));
132
133
134         /* terminate initial header line */
135         if( (headers = strfind(buffer, buflen, "\r\n", 2)) != NULL )
136         {
137                 buffer[buflen-1] = 0;
138
139                 *headers++ = 0;
140                 *headers++ = 0;
141
142                 /* find request path */
143                 if( (path = strchr(buffer, ' ')) != NULL )
144                         *path++ = 0;
145
146                 /* find http version */
147                 if( (path != NULL) && ((version = strchr(path, ' ')) != NULL) )
148                         *version++ = 0;
149
150
151                 /* check method */
152                 if( strcmp(method, "GET") && strcmp(method, "HEAD") && strcmp(method, "POST") )
153                 {
154                         /* invalid method */
155                         uh_http_response(cl, 405, "Method Not Allowed");
156                         return NULL;
157                 }
158                 else
159                 {
160                         switch(method[0])
161                         {
162                                 case 'G':
163                                         req.method = UH_HTTP_MSG_GET;
164                                         break;
165
166                                 case 'H':
167                                         req.method = UH_HTTP_MSG_HEAD;
168                                         break;
169
170                                 case 'P':
171                                         req.method = UH_HTTP_MSG_POST;
172                                         break;
173                         }
174                 }
175
176                 /* check path */
177                 if( !path || !strlen(path) )
178                 {
179                         /* malformed request */
180                         uh_http_response(cl, 400, "Bad Request");
181                         return NULL;
182                 }
183                 else
184                 {
185                         req.url = path;
186                 }
187
188                 /* check version */
189                 if( strcmp(version, "HTTP/0.9") && strcmp(version, "HTTP/1.0") && strcmp(version, "HTTP/1.1") )
190                 {
191                         /* unsupported version */
192                         uh_http_response(cl, 400, "Bad Request");
193                         return NULL;
194                 }
195                 else
196                 {
197                         req.version = strtof(&version[5], NULL);
198                 }
199
200
201                 /* process header fields */
202                 for( i = (int)(headers - buffer); i < buflen; i++ )
203                 {
204                         /* found eol and have name + value, push out header tuple */
205                         if( hdrname && hdrdata && (buffer[i] == '\r' || buffer[i] == '\n') )
206                         {
207                                 buffer[i] = 0;
208
209                                 /* store */
210                                 if( (hdrcount + 1) < array_size(req.headers) )
211                                 {
212                                         req.headers[hdrcount++] = hdrname;
213                                         req.headers[hdrcount++] = hdrdata;
214
215                                         hdrname = hdrdata = NULL;
216                                 }
217
218                                 /* too large */
219                                 else
220                                 {
221                                         uh_http_response(cl, 413, "Request Entity Too Large");
222                                         return NULL;
223                                 }
224                         }
225
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] == ' ')
229                         ) {
230                                 buffer[i] = 0;
231                                 hdrdata = &buffer[i+2];
232                         }
233
234                         /* have no name and found [A-Z], start of name */
235                         else if( !hdrname && isalpha(buffer[i]) && isupper(buffer[i]) )
236                         {
237                                 hdrname = &buffer[i];
238                         }
239                 }
240
241                 /* valid enough */
242                 return &req;
243         }
244
245         /* Malformed request */
246         uh_http_response(cl, 400, "Bad Request");
247         return NULL;
248 }
249
250
251 static struct http_request * uh_http_header_recv(struct client *cl)
252 {
253         char buffer[UH_LIMIT_MSGHEAD];
254         char *bufptr = &buffer[0];
255         char *idxptr = NULL;
256
257         struct timeval timeout;
258
259         fd_set reader;
260
261         ssize_t blen = sizeof(buffer)-1;
262         ssize_t rlen = 0;
263
264
265         memset(buffer, 0, sizeof(buffer));
266
267         while( blen > 0 )
268         {
269                 FD_ZERO(&reader);
270                 FD_SET(cl->socket, &reader);
271
272                 /* fail after 0.1s */
273                 timeout.tv_sec  = 0;
274                 timeout.tv_usec = 100000;
275
276                 /* check whether fd is readable */
277                 if( select(cl->socket + 1, &reader, NULL, NULL, &timeout) > 0 )
278                 {
279                         /* receive data */
280                         rlen = uh_tcp_peek(cl, bufptr, blen);
281
282                         if( rlen > 0 )
283                         {
284                                 if( (idxptr = strfind(buffer, sizeof(buffer), "\r\n\r\n", 4)) )
285                                 {
286                                         blen -= uh_tcp_recv(cl, bufptr, (int)(idxptr - bufptr) + 4);
287
288                                         /* header read complete ... */
289                                         return uh_http_header_parse(cl, buffer, sizeof(buffer) - blen - 1);
290                                 }
291                                 else
292                                 {
293                                         rlen = uh_tcp_recv(cl, bufptr, rlen);
294                                         blen -= rlen;
295                                         bufptr += rlen;
296                                 }
297                         }
298                         else
299                         {
300                                 /* invalid request (unexpected eof/timeout) */
301                                 uh_http_response(cl, 408, "Request Timeout");
302                                 return NULL;
303                         }
304                 }
305                 else
306                 {
307                         /* invalid request (unexpected eof/timeout) */
308                         uh_http_response(cl, 408, "Request Timeout");
309                         return NULL;
310                 }
311         }
312
313         /* request entity too large */
314         uh_http_response(cl, 413, "Request Entity Too Large");
315         return NULL;
316 }
317
318 static int uh_docroot_resolve(const char *path, char *buf)
319 {
320         char curpath[PATH_MAX];
321
322         if( ! getcwd(curpath, sizeof(curpath)) )
323         {
324                 perror("getcwd()");
325                 return 0;
326         }
327
328         if( chdir(path) || !getcwd(buf, PATH_MAX) )
329         {
330                 return 0;
331         }
332         else
333         {
334                 buf[strlen(buf)] = '/';
335         }
336
337         if( chdir(curpath) )
338         {
339                 perror("chdir()");
340                 return 0;
341         }
342
343         return 1;
344 }
345
346
347 int main (int argc, char **argv)
348 {
349 #ifdef HAVE_LUA
350         /* Lua runtime */
351         lua_State *L = NULL;
352 #endif
353
354         /* master file descriptor list */
355         fd_set used_fds, serv_fds, read_fds;
356
357         /* working structs */
358         struct addrinfo hints;
359         struct http_request *req;
360         struct client *cl;
361         struct sigaction sa;
362         struct config conf;
363
364         /* maximum file descriptor number */
365         int new_fd, cur_fd, max_fd = 0;
366         int keys = 0;
367         int bound = 0;
368         int nofork = 0;
369
370         /* args */
371         char opt;
372         char bind[128];
373         char *port = NULL;
374
375         /* clear the master and temp sets */
376         FD_ZERO(&used_fds);
377         FD_ZERO(&serv_fds);
378         FD_ZERO(&read_fds);
379
380         /* handle SIGPIPE, SIGCHILD */
381         sa.sa_handler = SIG_IGN;
382         sigaction(SIGPIPE, &sa, NULL);
383         sigaction(SIGCHLD, &sa, NULL);
384
385         sa.sa_handler = uh_sigterm;
386         sigaction(SIGINT,  &sa, NULL);
387         sigaction(SIGTERM, &sa, NULL);
388
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;
394
395         /* parse args */
396         memset(&conf, 0, sizeof(conf));
397         memset(bind, 0, sizeof(bind));
398
399 #ifdef HAVE_TLS
400         /* init SSL context */
401         if( ! (conf.tls = uh_tls_ctx_init()) )
402         {
403                 fprintf(stderr, "Failed to initalize SSL context\n");
404                 exit(1);
405         }
406 #endif
407
408         while( (opt = getopt(argc, argv, "fC:K:p:s:h:c:l:L:d:")) > 0 )
409         {
410                 switch(opt)
411                 {
412                         /* [addr:]port */
413                         case 'p':
414                         case 's':
415                                 if( (port = strrchr(optarg, ':')) != NULL )
416                                 {
417                                         if( (optarg[0] == '[') && (port > optarg) && (port[-1] == ']') )
418                                                 memcpy(bind, optarg + 1,
419                                                         min(sizeof(bind), (int)(port - optarg) - 2));
420                                         else
421                                                 memcpy(bind, optarg,
422                                                         min(sizeof(bind), (int)(port - optarg)));
423
424                                         port++;
425                                 }
426                                 else
427                                 {
428                                         port = optarg;
429                                 }
430
431                                 /* bind sockets */
432                                 bound += uh_socket_bind(
433                                         &serv_fds, &max_fd, bind[0] ? bind : NULL, port, &hints,
434                                         (opt == 's') ? 1 : 0, &conf
435                                 );
436
437                                 break;
438
439 #ifdef HAVE_TLS
440                         /* certificate */
441                         case 'C':
442                                 if( SSL_CTX_use_certificate_file(conf.tls, optarg, SSL_FILETYPE_ASN1) < 1 )
443                                 {
444                                         fprintf(stderr, "Invalid certificate file given\n");
445                                         exit(1);
446                                 }
447
448                                 keys++;
449                                 break;
450
451                         /* key */
452                         case 'K':
453                                 if( SSL_CTX_use_PrivateKey_file(conf.tls, optarg, SSL_FILETYPE_ASN1) < 1 )
454                                 {
455                                         fprintf(stderr, "Invalid private key file given\n");
456                                         exit(1);
457                                 }
458
459                                 keys++;
460                                 break;
461 #endif
462
463                         /* docroot */
464                         case 'h':
465                                 if( ! uh_docroot_resolve(optarg, conf.docroot) )
466                                 {
467                                         fprintf(stderr, "Invalid directory: %s\n", optarg);
468                                         exit(1);
469                                 }
470                                 break;
471
472 #ifdef HAVE_CGI
473                         /* cgi prefix */
474                         case 'c':
475                                 conf.cgi_prefix = optarg;
476                                 break;
477 #endif
478
479 #ifdef HAVE_LUA
480                         /* lua prefix */
481                         case 'l':
482                                 conf.lua_prefix = optarg;
483                                 break;
484
485                         /* lua handler */
486                         case 'L':
487                                 conf.lua_handler = optarg;
488                                 break;
489 #endif
490
491                         /* no fork */
492                         case 'f':
493                                 nofork = 1;
494                                 break;
495
496                         /* urldecode */
497                         case 'd':
498                                 if( (port = malloc(strlen(optarg)+1)) != NULL )
499                                 {
500                                         memset(port, 0, strlen(optarg)+1);
501                                         uh_urldecode(port, strlen(optarg), optarg, strlen(optarg));
502                                         printf("%s", port);
503                                         free(port);
504                                         exit(0);
505                                 }
506                                 break;
507
508                         default:
509                                 fprintf(stderr,
510                                         "Usage: %s -p [addr:]port [-h docroot]\n"
511                                         "       -p      Bind to specified address and port, multiple allowed\n"
512 #ifdef HAVE_TLS
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"
516 #endif
517                                         "       -h      Specify the document root, default is '.'\n"
518                                         "       -f      Do not fork to background\n"
519 #ifdef HAVE_LUA
520                                         "       -l      URL prefix for Lua handler, default is '/lua'\n"
521                                         "       -L      Lua handler script, default is './lua/handler.lua'\n"
522 #endif
523 #ifdef HAVE_CGI
524                                         "       -c      URL prefix for CGI handler, default is '/cgi-bin'\n"
525 #endif
526                                         "       -d      URL decode given string\n"
527                                         "\n", argv[0]
528                                 );
529
530                                 exit(1);
531                 }
532         }
533
534 #ifdef HAVE_TLS
535         if( keys < 2 )
536         {
537                 fprintf(stderr, "Missing private key or certificate file\n");
538                 exit(1);
539         }
540 #endif
541
542         if( bound < 1 )
543         {
544                 fprintf(stderr, "No sockets bound, unable to continue\n");
545                 exit(1);
546         }
547
548         /* default docroot */
549         if( !conf.docroot[0] && !uh_docroot_resolve(".", conf.docroot) )
550         {
551                 fprintf(stderr, "Can not determine default document root\n");
552                 exit(1);
553         }
554
555 #ifdef HAVE_CGI
556         /* default cgi prefix */
557         if( ! conf.cgi_prefix )
558                 conf.cgi_prefix = "/cgi-bin";
559 #endif
560
561 #ifdef HAVE_LUA
562         /* init Lua runtime if handler is specified */
563         if( conf.lua_handler )
564         {
565                 /* default lua prefix */
566                 if( ! conf.lua_prefix )
567                         conf.lua_prefix = "/lua";
568
569                 L = uh_lua_init(conf.lua_handler);
570         }
571 #endif
572
573         /* fork (if not disabled) */
574         if( ! nofork )
575         {
576                 switch( fork() )
577                 {
578                         case -1:
579                                 perror("fork()");
580                                 exit(1);
581
582                         case 0:
583                                 /* daemon setup */
584                                 if( chdir("/") )
585                                         perror("chdir()");
586
587                                 if( (cur_fd = open("/dev/null", O_WRONLY)) > -1 )
588                                         dup2(cur_fd, 0);
589
590                                 if( (cur_fd = open("/dev/null", O_RDONLY)) > -1 )
591                                         dup2(cur_fd, 1);
592
593                                 if( (cur_fd = open("/dev/null", O_RDONLY)) > -1 )
594                                         dup2(cur_fd, 2);
595
596                                 break;
597
598                         default:
599                                 exit(0);
600                 }
601         }
602
603         /* backup server descriptor set */
604         used_fds = serv_fds;
605
606         /* loop */
607         while(run)
608         {
609                 /* create a working copy of the used fd set */
610                 read_fds = used_fds;
611
612                 /* sleep until socket activity */
613                 if( select(max_fd + 1, &read_fds, NULL, NULL, NULL) == -1 )
614                 {
615                         perror("select()");
616                         exit(1);
617                 }
618
619                 /* run through the existing connections looking for data to be read */
620                 for( cur_fd = 0; cur_fd <= max_fd; cur_fd++ )
621                 {
622                         /* is a socket managed by us */
623                         if( FD_ISSET(cur_fd, &read_fds) )
624                         {                       
625                                 /* is one of our listen sockets */
626                                 if( FD_ISSET(cur_fd, &serv_fds) )
627                                 {
628                                         /* handle new connections */
629                                         if( (new_fd = accept(cur_fd, NULL, 0)) != -1 )
630                                         {
631                                                 /* add to global client list */
632                                                 if( (cl = uh_client_add(new_fd, uh_listener_lookup(cur_fd))) != NULL )
633                                                 {
634 #ifdef HAVE_TLS
635                                                         /* setup client tls context */
636                                                         uh_tls_client_accept(cl);
637 #endif
638
639                                                         /* add client socket to global fdset */
640                                                         FD_SET(new_fd, &used_fds);
641                                                         max_fd = max(max_fd, new_fd);                                                   
642                                                 }
643
644                                                 /* insufficient resources */
645                                                 else
646                                                 {
647                                                         fprintf(stderr,
648                                                                 "uh_client_add(): Can not manage more than "
649                                                                 "%i client sockets, connection dropped\n",
650                                                                 UH_LIMIT_CLIENTS
651                                                         );
652
653                                                         close(new_fd);
654                                                 }
655                                         }
656                                 }
657
658                                 /* is a client socket */
659                                 else
660                                 {
661                                         if( ! (cl = uh_client_lookup(cur_fd)) )
662                                         {
663                                                 /* this should not happen! */
664                                                 fprintf(stderr,
665                                                         "uh_client_lookup(): No entry for fd %i!\n",
666                                                         cur_fd);
667
668                                                 goto cleanup;
669                                         }
670
671                                         /* parse message header and dispatch request */
672                                         if( (req = uh_http_header_recv(cl)) != NULL )
673                                         {
674 #ifdef HAVE_CGI
675                                                 if( strstr(req->url, conf.cgi_prefix) == req->url )
676                                                 {
677                                                         uh_cgi_request(cl, req);
678                                                 }
679                                                 else
680 #endif
681
682 #ifdef HAVE_LUA
683                                                 if( (L != NULL) &&
684                                                     (strstr(req->url, conf.lua_prefix) == req->url)
685                                                 ) {
686                                                         uh_lua_request(cl, req, L);
687                                                 }
688                                                 else
689 #endif
690
691                                                 {
692                                                         uh_file_request(cl, req);
693                                                 }
694                                         }
695
696
697 #ifdef HAVE_TLS
698                                         /* free client tls context */
699                                         uh_tls_client_close(cl);
700 #endif
701
702                                         cleanup:
703
704                                         /* close client socket */
705                                         close(cur_fd);
706                                         FD_CLR(cur_fd, &used_fds);
707
708                                         /* remove from global client list */
709                                         uh_client_remove(cur_fd);
710                                 }
711                         }
712                 }
713         }
714
715 #ifdef HAVE_LUA
716         /* destroy the Lua state */
717         if( L != NULL )
718                 lua_close(L);
719 #endif
720
721         return 0;
722 }
723