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