uhttpd:
[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
319 int main (int argc, char **argv)
320 {
321 #ifdef HAVE_LUA
322         /* Lua runtime */
323         lua_State *L = NULL;
324 #endif
325
326         /* master file descriptor list */
327         fd_set used_fds, serv_fds, read_fds;
328
329         /* working structs */
330         struct addrinfo hints;
331         struct http_request *req;
332         struct uh_path_info *pin;
333         struct client *cl;
334         struct sigaction sa;
335         struct config conf;
336
337         /* maximum file descriptor number */
338         int new_fd, cur_fd, max_fd = 0;
339
340         int tls = 0;
341         int keys = 0;
342         int bound = 0;
343         int nofork = 0;
344
345         /* args */
346         char opt;
347         char bind[128];
348         char *port = NULL;
349
350         /* clear the master and temp sets */
351         FD_ZERO(&used_fds);
352         FD_ZERO(&serv_fds);
353         FD_ZERO(&read_fds);
354
355         /* handle SIGPIPE, SIGCHILD */
356         sa.sa_handler = SIG_IGN;
357         sigaction(SIGPIPE, &sa, NULL);
358         sigaction(SIGCHLD, &sa, NULL);
359
360         sa.sa_handler = uh_sigterm;
361         sigaction(SIGINT,  &sa, NULL);
362         sigaction(SIGTERM, &sa, NULL);
363
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;
369
370         /* parse args */
371         memset(&conf, 0, sizeof(conf));
372         memset(bind, 0, sizeof(bind));
373
374 #ifdef HAVE_TLS
375         /* init SSL context */
376         if( ! (conf.tls = uh_tls_ctx_init()) )
377         {
378                 fprintf(stderr, "Failed to initalize SSL context\n");
379                 exit(1);
380         }
381 #endif
382
383         while( (opt = getopt(argc, argv, "fC:K:p:s:h:c:l:L:d:")) > 0 )
384         {
385                 switch(opt)
386                 {
387                         /* [addr:]port */
388                         case 'p':
389                         case 's':
390                                 if( (port = strrchr(optarg, ':')) != NULL )
391                                 {
392                                         if( (optarg[0] == '[') && (port > optarg) && (port[-1] == ']') )
393                                                 memcpy(bind, optarg + 1,
394                                                         min(sizeof(bind), (int)(port - optarg) - 2));
395                                         else
396                                                 memcpy(bind, optarg,
397                                                         min(sizeof(bind), (int)(port - optarg)));
398
399                                         port++;
400                                 }
401                                 else
402                                 {
403                                         port = optarg;
404                                 }
405
406                                 if( opt == 's' )
407                                         tls = 1;
408
409                                 /* bind sockets */
410                                 bound += uh_socket_bind(
411                                         &serv_fds, &max_fd, bind[0] ? bind : NULL, port,
412                                         &hints, tls, &conf
413                                 );
414
415                                 break;
416
417 #ifdef HAVE_TLS
418                         /* certificate */
419                         case 'C':
420                                 if( SSL_CTX_use_certificate_file(conf.tls, optarg, SSL_FILETYPE_ASN1) < 1 )
421                                 {
422                                         fprintf(stderr, "Invalid certificate file given\n");
423                                         exit(1);
424                                 }
425
426                                 keys++;
427                                 break;
428
429                         /* key */
430                         case 'K':
431                                 if( SSL_CTX_use_PrivateKey_file(conf.tls, optarg, SSL_FILETYPE_ASN1) < 1 )
432                                 {
433                                         fprintf(stderr, "Invalid private key file given\n");
434                                         exit(1);
435                                 }
436
437                                 keys++;
438                                 break;
439 #endif
440
441                         /* docroot */
442                         case 'h':
443                                 if( ! realpath(optarg, conf.docroot) )
444                                 {
445                                         fprintf(stderr, "Invalid directory %s: %s\n", optarg, strerror(errno));
446                                         exit(1);
447                                 }
448                                 break;
449
450 #ifdef HAVE_CGI
451                         /* cgi prefix */
452                         case 'c':
453                                 conf.cgi_prefix = optarg;
454                                 break;
455 #endif
456
457 #ifdef HAVE_LUA
458                         /* lua prefix */
459                         case 'l':
460                                 conf.lua_prefix = optarg;
461                                 break;
462
463                         /* lua handler */
464                         case 'L':
465                                 conf.lua_handler = optarg;
466                                 break;
467 #endif
468
469                         /* no fork */
470                         case 'f':
471                                 nofork = 1;
472                                 break;
473
474                         /* urldecode */
475                         case 'd':
476                                 if( (port = malloc(strlen(optarg)+1)) != NULL )
477                                 {
478                                         memset(port, 0, strlen(optarg)+1);
479                                         uh_urldecode(port, strlen(optarg), optarg, strlen(optarg));
480                                         printf("%s", port);
481                                         free(port);
482                                         exit(0);
483                                 }
484                                 break;
485
486                         default:
487                                 fprintf(stderr,
488                                         "Usage: %s -p [addr:]port [-h docroot]\n"
489                                         "       -p      Bind to specified address and port, multiple allowed\n"
490 #ifdef HAVE_TLS
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"
494 #endif
495                                         "       -h      Specify the document root, default is '.'\n"
496                                         "       -f      Do not fork to background\n"
497 #ifdef HAVE_LUA
498                                         "       -l      URL prefix for Lua handler, default is '/lua'\n"
499                                         "       -L      Lua handler script, omit to disable Lua\n"
500 #endif
501 #ifdef HAVE_CGI
502                                         "       -c      URL prefix for CGI handler, default is '/cgi-bin'\n"
503 #endif
504                                         "       -d      URL decode given string\n"
505                                         "\n", argv[0]
506                                 );
507
508                                 exit(1);
509                 }
510         }
511
512 #ifdef HAVE_TLS
513         if( (tls == 1) && (keys < 2) )
514         {
515                 fprintf(stderr, "Missing private key or certificate file\n");
516                 exit(1);
517         }
518 #endif
519
520         if( bound < 1 )
521         {
522                 fprintf(stderr, "No sockets bound, unable to continue\n");
523                 exit(1);
524         }
525
526         /* default docroot */
527         if( !conf.docroot[0] && !realpath(".", conf.docroot) )
528         {
529                 fprintf(stderr, "Can not determine default document root: %s\n",
530                         strerror(errno));
531                 exit(1);
532         }
533
534 #ifdef HAVE_CGI
535         /* default cgi prefix */
536         if( ! conf.cgi_prefix )
537                 conf.cgi_prefix = "/cgi-bin";
538 #endif
539
540 #ifdef HAVE_LUA
541         /* init Lua runtime if handler is specified */
542         if( conf.lua_handler )
543         {
544                 /* default lua prefix */
545                 if( ! conf.lua_prefix )
546                         conf.lua_prefix = "/lua";
547
548                 L = uh_lua_init(conf.lua_handler);
549         }
550 #endif
551
552         /* fork (if not disabled) */
553         if( ! nofork )
554         {
555                 switch( fork() )
556                 {
557                         case -1:
558                                 perror("fork()");
559                                 exit(1);
560
561                         case 0:
562                                 /* daemon setup */
563                                 if( chdir("/") )
564                                         perror("chdir()");
565
566                                 if( (cur_fd = open("/dev/null", O_WRONLY)) > -1 )
567                                         dup2(cur_fd, 0);
568
569                                 if( (cur_fd = open("/dev/null", O_RDONLY)) > -1 )
570                                         dup2(cur_fd, 1);
571
572                                 if( (cur_fd = open("/dev/null", O_RDONLY)) > -1 )
573                                         dup2(cur_fd, 2);
574
575                                 break;
576
577                         default:
578                                 exit(0);
579                 }
580         }
581
582         /* backup server descriptor set */
583         used_fds = serv_fds;
584
585         /* loop */
586         while(run)
587         {
588                 /* create a working copy of the used fd set */
589                 read_fds = used_fds;
590
591                 /* sleep until socket activity */
592                 if( select(max_fd + 1, &read_fds, NULL, NULL, NULL) == -1 )
593                 {
594                         perror("select()");
595                         exit(1);
596                 }
597
598                 /* run through the existing connections looking for data to be read */
599                 for( cur_fd = 0; cur_fd <= max_fd; cur_fd++ )
600                 {
601                         /* is a socket managed by us */
602                         if( FD_ISSET(cur_fd, &read_fds) )
603                         {
604                                 /* is one of our listen sockets */
605                                 if( FD_ISSET(cur_fd, &serv_fds) )
606                                 {
607                                         /* handle new connections */
608                                         if( (new_fd = accept(cur_fd, NULL, 0)) != -1 )
609                                         {
610                                                 /* add to global client list */
611                                                 if( (cl = uh_client_add(new_fd, uh_listener_lookup(cur_fd))) != NULL )
612                                                 {
613 #ifdef HAVE_TLS
614                                                         /* setup client tls context */
615                                                         uh_tls_client_accept(cl);
616 #endif
617
618                                                         /* add client socket to global fdset */
619                                                         FD_SET(new_fd, &used_fds);
620                                                         max_fd = max(max_fd, new_fd);
621                                                 }
622
623                                                 /* insufficient resources */
624                                                 else
625                                                 {
626                                                         fprintf(stderr,
627                                                                 "uh_client_add(): Can not manage more than "
628                                                                 "%i client sockets, connection dropped\n",
629                                                                 UH_LIMIT_CLIENTS
630                                                         );
631
632                                                         close(new_fd);
633                                                 }
634                                         }
635                                 }
636
637                                 /* is a client socket */
638                                 else
639                                 {
640                                         if( ! (cl = uh_client_lookup(cur_fd)) )
641                                         {
642                                                 /* this should not happen! */
643                                                 fprintf(stderr,
644                                                         "uh_client_lookup(): No entry for fd %i!\n",
645                                                         cur_fd);
646
647                                                 goto cleanup;
648                                         }
649
650                                         /* parse message header */
651                                         if( (req = uh_http_header_recv(cl)) != NULL )
652                                         {
653                                                 /* dispatch request */
654                                                 if( (pin = uh_path_lookup(cl, req->url)) != NULL )
655                                                 {
656 #ifdef HAVE_CGI
657                                                         if( strstr(pin->name, conf.cgi_prefix) == pin->name )
658                                                         {
659                                                                 uh_cgi_request(cl, req, pin);
660                                                         }
661                                                         else
662 #endif
663                                                         {
664                                                                 uh_file_request(cl, req, pin);
665                                                         }
666                                                 }
667 #ifdef HAVE_LUA
668                                                 /* Lua request? */
669                                                 else if( strstr(req->url, conf.lua_prefix) == req->url )
670                                                 {
671                                                         uh_lua_request(cl, req, L);
672                                                 }
673 #endif
674                                                 /* 404 */
675                                                 else
676                                                 {
677                                                         uh_http_sendhf(cl, 404, "Not Found",
678                                                                 "No such file or directory");
679                                                 }
680                                         }
681
682                                         /* 400 */
683                                         else
684                                         {
685                                                 uh_http_sendhf(cl, 400, "Bad Request",
686                                                         "Malformed request received");
687                                         }
688
689 #ifdef HAVE_TLS
690                                         /* free client tls context */
691                                         uh_tls_client_close(cl);
692 #endif
693
694                                         cleanup:
695
696                                         /* close client socket */
697                                         close(cur_fd);
698                                         FD_CLR(cur_fd, &used_fds);
699
700                                         /* remove from global client list */
701                                         uh_client_remove(cur_fd);
702                                 }
703                         }
704                 }
705         }
706
707 #ifdef HAVE_LUA
708         /* destroy the Lua state */
709         if( L != NULL )
710                 lua_close(L);
711 #endif
712
713         return 0;
714 }
715