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