893350a2323fca1aaa91a2a3662dac55582d4ae0
[project/uhttpd.git] / main.c
1 /*
2 * uhttpd - Tiny single-threaded httpd
3 *
4 * Copyright (C) 2010-2013 Jo-Philipp Wich <xm@subsignal.org>
5 * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
6 *
7 * Permission to use, copy, modify, and/or distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 */
19
20 #ifndef _DEFAULT_SOURCE
21 # define _DEFAULT_SOURCE
22 #endif
23
24 #define _BSD_SOURCE
25 #define _GNU_SOURCE
26 #define _XOPEN_SOURCE 700
27 #include <sys/types.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
30
31 #include <getopt.h>
32 #include <errno.h>
33 #include <netdb.h>
34 #include <signal.h>
35
36 #include <libubox/usock.h>
37 #include <libubox/utils.h>
38
39 #include "uhttpd.h"
40 #include "tls.h"
41
42 char uh_buf[4096];
43
44 static int run_server(void)
45 {
46 uloop_init();
47 uh_setup_listeners();
48 uh_plugin_post_init();
49 uloop_run();
50
51 return 0;
52 }
53
54 static void uh_config_parse(void)
55 {
56 const char *path = conf.file;
57 FILE *c;
58 char line[512];
59 char *col1;
60 char *col2;
61 char *eol;
62
63 if (!path)
64 path = "/etc/httpd.conf";
65
66 c = fopen(path, "r");
67 if (!c)
68 return;
69
70 memset(line, 0, sizeof(line));
71
72 while (fgets(line, sizeof(line) - 1, c)) {
73 if ((line[0] == '/') && (strchr(line, ':') != NULL)) {
74 if (!(col1 = strchr(line, ':')) || (*col1++ = 0) ||
75 !(col2 = strchr(col1, ':')) || (*col2++ = 0) ||
76 !(eol = strchr(col2, '\n')) || (*eol++ = 0))
77 continue;
78
79 uh_auth_add(line, col1, col2);
80 } else if (!strncmp(line, "I:", 2)) {
81 if (!(col1 = strchr(line, ':')) || (*col1++ = 0) ||
82 !(eol = strchr(col1, '\n')) || (*eol++ = 0))
83 continue;
84
85 uh_index_add(strdup(col1));
86 } else if (!strncmp(line, "E404:", 5)) {
87 if (!(col1 = strchr(line, ':')) || (*col1++ = 0) ||
88 !(eol = strchr(col1, '\n')) || (*eol++ = 0))
89 continue;
90
91 conf.error_handler = strdup(col1);
92 }
93 else if ((line[0] == '*') && (strchr(line, ':') != NULL)) {
94 if (!(col1 = strchr(line, '*')) || (*col1++ = 0) ||
95 !(col2 = strchr(col1, ':')) || (*col2++ = 0) ||
96 !(eol = strchr(col2, '\n')) || (*eol++ = 0))
97 continue;
98
99 uh_interpreter_add(col1, col2);
100 }
101 }
102
103 fclose(c);
104 }
105
106 static int add_listener_arg(char *arg, bool tls)
107 {
108 char *host = NULL;
109 char *port = arg;
110 char *s;
111 int l;
112
113 s = strrchr(arg, ':');
114 if (s) {
115 host = arg;
116 port = s + 1;
117 *s = 0;
118 }
119
120 if (host && *host == '[') {
121 l = strlen(host);
122 if (l >= 2) {
123 host[l-1] = 0;
124 host++;
125 }
126 }
127
128 return uh_socket_bind(host, port, tls);
129 }
130
131 static int usage(const char *name)
132 {
133 fprintf(stderr,
134 "Usage: %s -p [addr:]port -h docroot\n"
135 " -f Do not fork to background\n"
136 " -c file Configuration file, default is '/etc/httpd.conf'\n"
137 " -p [addr:]port Bind to specified address and port, multiple allowed\n"
138 #ifdef HAVE_TLS
139 " -s [addr:]port Like -p but provide HTTPS on this port\n"
140 " -C file ASN.1 server certificate file\n"
141 " -K file ASN.1 server private key file\n"
142 " -P ciphers Colon separated list of allowed TLS ciphers\n"
143 " -q Redirect all HTTP requests to HTTPS\n"
144 #endif
145 " -h directory Specify the document root, default is '.'\n"
146 " -E string Use given virtual URL as 404 error handler\n"
147 " -I string Use given filename as index for directories, multiple allowed\n"
148 " -S Do not follow symbolic links outside of the docroot\n"
149 " -D Do not allow directory listings, send 403 instead\n"
150 " -R Enable RFC1918 filter\n"
151 " -n count Maximum allowed number of concurrent script requests\n"
152 " -N count Maximum allowed number of concurrent connections\n"
153 #ifdef HAVE_LUA
154 " -l string URL prefix for Lua handler\n"
155 " -L file Path to Lua handler script, -l and -L may be repeated in pairs\n"
156 #endif
157 #ifdef HAVE_UCODE
158 " -o string URL prefix for ucode handler\n"
159 " -O file Path to ucode handler script, -o and -O may be repeated in pairs\n"
160 #endif
161 #ifdef HAVE_UBUS
162 " -u string URL prefix for UBUS via JSON-RPC handler\n"
163 " -U file Override ubus socket path\n"
164 " -a Do not authenticate JSON-RPC requests against UBUS session api\n"
165 " -X Enable CORS HTTP headers on JSON-RPC api\n"
166 " -e Events subscription reconnection time (retry value)\n"
167 #endif
168 " -x string URL prefix for CGI handler, default is '/cgi-bin'\n"
169 " -y alias[=path] URL alias handle\n"
170 " -i .ext=path Use interpreter at path for files with the given extension\n"
171 " -t seconds CGI, Lua and UBUS script timeout in seconds, default is 60\n"
172 " -T seconds Network timeout in seconds, default is 30\n"
173 " -k seconds HTTP keepalive timeout\n"
174 " -A seconds TCP keepalive timeout, default is unset\n"
175 " -d string URL decode given string\n"
176 " -r string Specify basic auth realm\n"
177 " -m string MD5 crypt given string\n"
178 "\n", name
179 );
180 return 1;
181 }
182
183 static void init_defaults_pre(void)
184 {
185 conf.script_timeout = 60;
186 conf.network_timeout = 30;
187 conf.http_keepalive = 20;
188 conf.max_script_requests = 3;
189 conf.max_connections = 100;
190 conf.realm = "Protected Area";
191 conf.cgi_prefix = "/cgi-bin";
192 conf.cgi_path = "/sbin:/usr/sbin:/bin:/usr/bin";
193 INIT_LIST_HEAD(&conf.cgi_alias);
194 INIT_LIST_HEAD(&conf.lua_prefix);
195 #if HAVE_UCODE
196 INIT_LIST_HEAD(&conf.ucode_prefix);
197 #endif
198 }
199
200 static void init_defaults_post(void)
201 {
202 uh_index_add("index.html");
203 uh_index_add("index.htm");
204 uh_index_add("default.html");
205 uh_index_add("default.htm");
206
207 if (conf.cgi_prefix) {
208 char *str = malloc(strlen(conf.docroot) + strlen(conf.cgi_prefix) + 1);
209
210 strcpy(str, conf.docroot);
211 strcat(str, conf.cgi_prefix);
212 conf.cgi_docroot_path = str;
213 conf.cgi_prefix_len = strlen(conf.cgi_prefix);
214 };
215 }
216
217 static void fixup_prefix(char *str)
218 {
219 int len;
220
221 if (!str || !str[0])
222 return;
223
224 len = strlen(str) - 1;
225
226 while (len >= 0 && str[len] == '/')
227 len--;
228
229 str[len + 1] = 0;
230 }
231
232 #ifdef HAVE_LUA
233 static void add_lua_prefix(const char *prefix, const char *handler) {
234 struct lua_prefix *p;
235 char *pprefix, *phandler;
236
237 p = calloc_a(sizeof(*p),
238 &pprefix, strlen(prefix) + 1,
239 &phandler, strlen(handler) + 1);
240
241 if (!p)
242 return;
243
244 p->prefix = strcpy(pprefix, prefix);
245 p->handler = strcpy(phandler, handler);
246
247 list_add_tail(&p->list, &conf.lua_prefix);
248 }
249 #endif
250
251 #ifdef HAVE_UCODE
252 static void add_ucode_prefix(const char *prefix, const char *handler) {
253 struct ucode_prefix *p;
254 char *pprefix, *phandler;
255
256 p = calloc_a(sizeof(*p),
257 &pprefix, strlen(prefix) + 1,
258 &phandler, strlen(handler) + 1);
259
260 if (!p)
261 return;
262
263 p->prefix = strcpy(pprefix, prefix);
264 p->handler = strcpy(phandler, handler);
265
266 list_add_tail(&p->list, &conf.ucode_prefix);
267 }
268 #endif
269
270 int main(int argc, char **argv)
271 {
272 struct alias *alias;
273 bool nofork = false;
274 char *port;
275 int opt, ch;
276 int cur_fd;
277 int bound = 0;
278 #ifdef HAVE_TLS
279 int n_tls = 0;
280 const char *tls_key = NULL, *tls_crt = NULL, *tls_ciphers = NULL;
281 #endif
282 #ifdef HAVE_LUA
283 const char *lua_prefix = NULL, *lua_handler = NULL;
284 #endif
285 #ifdef HAVE_UCODE
286 const char *ucode_prefix = NULL, *ucode_handler = NULL;
287 #endif
288
289 BUILD_BUG_ON(sizeof(uh_buf) < PATH_MAX);
290
291 uh_dispatch_add(&cgi_dispatch);
292 init_defaults_pre();
293 signal(SIGPIPE, SIG_IGN);
294
295 while ((ch = getopt(argc, argv, "A:aC:c:Dd:E:e:fh:H:I:i:K:k:L:l:m:N:n:O:o:P:p:qRr:Ss:T:t:U:u:Xx:y:")) != -1) {
296 switch(ch) {
297 #ifdef HAVE_TLS
298 case 'C':
299 tls_crt = optarg;
300 break;
301
302 case 'K':
303 tls_key = optarg;
304 break;
305
306 case 'P':
307 tls_ciphers = optarg;
308 break;
309
310 case 'q':
311 conf.tls_redirect = 1;
312 break;
313
314 case 's':
315 n_tls++;
316 /* fall through */
317 #else
318 case 'C':
319 case 'K':
320 case 'P':
321 case 'q':
322 case 's':
323 fprintf(stderr, "uhttpd: TLS support not compiled, "
324 "ignoring -%c\n", ch);
325 break;
326 #endif
327 case 'p':
328 optarg = strdup(optarg);
329 bound += add_listener_arg(optarg, (ch == 's'));
330 break;
331
332 case 'h':
333 if (!realpath(optarg, uh_buf)) {
334 fprintf(stderr, "Error: Invalid directory %s: %s\n",
335 optarg, strerror(errno));
336 exit(1);
337 }
338 conf.docroot = strdup(uh_buf);
339 break;
340
341 case 'H':
342 if (uh_handler_add(optarg)) {
343 fprintf(stderr, "Error: Failed to load handler script %s\n",
344 optarg);
345 exit(1);
346 }
347 break;
348
349 case 'E':
350 if (optarg[0] != '/') {
351 fprintf(stderr, "Error: Invalid error handler: %s\n",
352 optarg);
353 exit(1);
354 }
355 conf.error_handler = optarg;
356 break;
357
358 case 'I':
359 if (optarg[0] == '/') {
360 fprintf(stderr, "Error: Invalid index page: %s\n",
361 optarg);
362 exit(1);
363 }
364 uh_index_add(optarg);
365 break;
366
367 case 'S':
368 conf.no_symlinks = 1;
369 break;
370
371 case 'D':
372 conf.no_dirlists = 1;
373 break;
374
375 case 'R':
376 conf.rfc1918_filter = 1;
377 break;
378
379 case 'n':
380 conf.max_script_requests = atoi(optarg);
381 break;
382
383 case 'N':
384 conf.max_connections = atoi(optarg);
385 break;
386
387 case 'x':
388 fixup_prefix(optarg);
389 conf.cgi_prefix = optarg;
390 break;
391
392 case 'y':
393 alias = calloc(1, sizeof(*alias));
394 if (!alias) {
395 fprintf(stderr, "Error: failed to allocate alias\n");
396 exit(1);
397 }
398 alias->alias = strdup(optarg);
399 alias->path = strchr(alias->alias, '=');
400 if (alias->path)
401 *alias->path++ = 0;
402 list_add(&alias->list, &conf.cgi_alias);
403 break;
404
405 case 'i':
406 optarg = strdup(optarg);
407 port = strchr(optarg, '=');
408 if (optarg[0] != '.' || !port) {
409 fprintf(stderr, "Error: Invalid interpreter: %s\n",
410 optarg);
411 exit(1);
412 }
413
414 *port++ = 0;
415 uh_interpreter_add(optarg, port);
416 break;
417
418 case 't':
419 conf.script_timeout = atoi(optarg);
420 break;
421
422 case 'T':
423 conf.network_timeout = atoi(optarg);
424 break;
425
426 case 'k':
427 conf.http_keepalive = atoi(optarg);
428 break;
429
430 case 'A':
431 conf.tcp_keepalive = atoi(optarg);
432 break;
433
434 case 'f':
435 nofork = 1;
436 break;
437
438 case 'd':
439 optarg = strdup(optarg);
440 port = alloca(strlen(optarg) + 1);
441 if (!port)
442 return -1;
443
444 /* "decode" plus to space to retain compat */
445 for (opt = 0; optarg[opt]; opt++)
446 if (optarg[opt] == '+')
447 optarg[opt] = ' ';
448
449 /* opt now contains strlen(optarg) -- no need to re-scan */
450 if (uh_urldecode(port, opt, optarg, opt) < 0) {
451 fprintf(stderr, "uhttpd: invalid encoding\n");
452 return -1;
453 }
454
455 printf("%s", port);
456 return 0;
457 break;
458
459 /* basic auth realm */
460 case 'r':
461 conf.realm = optarg;
462 break;
463
464 /* md5 crypt */
465 case 'm':
466 printf("%s\n", crypt(optarg, "$1$"));
467 return 0;
468 break;
469
470 /* config file */
471 case 'c':
472 conf.file = optarg;
473 break;
474
475 #ifdef HAVE_LUA
476 case 'l':
477 case 'L':
478 if (ch == 'l') {
479 if (lua_prefix)
480 fprintf(stderr, "uhttpd: Ignoring previous -%c %s\n",
481 ch, lua_prefix);
482
483 lua_prefix = optarg;
484 }
485 else {
486 if (lua_handler)
487 fprintf(stderr, "uhttpd: Ignoring previous -%c %s\n",
488 ch, lua_handler);
489
490 lua_handler = optarg;
491 }
492
493 if (lua_prefix && lua_handler) {
494 add_lua_prefix(lua_prefix, lua_handler);
495 lua_prefix = NULL;
496 lua_handler = NULL;
497 }
498
499 break;
500 #else
501 case 'l':
502 case 'L':
503 fprintf(stderr, "uhttpd: Lua support not compiled, "
504 "ignoring -%c\n", ch);
505 break;
506 #endif
507 #ifdef HAVE_UCODE
508 case 'o':
509 case 'O':
510 if (ch == 'o') {
511 if (ucode_prefix)
512 fprintf(stderr, "uhttpd: Ignoring previous -%c %s\n",
513 ch, ucode_prefix);
514
515 ucode_prefix = optarg;
516 }
517 else {
518 if (ucode_handler)
519 fprintf(stderr, "uhttpd: Ignoring previous -%c %s\n",
520 ch, ucode_handler);
521
522 ucode_handler = optarg;
523 }
524
525 if (ucode_prefix && ucode_handler) {
526 add_ucode_prefix(ucode_prefix, ucode_handler);
527 ucode_prefix = NULL;
528 ucode_handler = NULL;
529 }
530
531 break;
532 #else
533 case 'o':
534 case 'O':
535 fprintf(stderr, "uhttpd: ucode support not compiled, "
536 "ignoring -%c\n", ch);
537 break;
538 #endif
539 #ifdef HAVE_UBUS
540 case 'a':
541 conf.ubus_noauth = 1;
542 break;
543
544 case 'u':
545 conf.ubus_prefix = optarg;
546 break;
547
548 case 'U':
549 conf.ubus_socket = optarg;
550 break;
551
552 case 'X':
553 conf.ubus_cors = 1;
554 break;
555
556 case 'e':
557 conf.events_retry = atoi(optarg);
558 break;
559 #else
560 case 'a':
561 case 'u':
562 case 'U':
563 case 'X':
564 case 'e':
565 fprintf(stderr, "uhttpd: UBUS support not compiled, "
566 "ignoring -%c\n", ch);
567 break;
568 #endif
569 default:
570 return usage(argv[0]);
571 }
572 }
573
574 uh_config_parse();
575
576 if (!conf.docroot) {
577 if (!realpath(".", uh_buf)) {
578 fprintf(stderr, "Error: Unable to determine work dir\n");
579 return 1;
580 }
581 conf.docroot = strdup(uh_buf);
582 }
583
584 init_defaults_post();
585
586 if (!bound) {
587 fprintf(stderr, "Error: No sockets bound, unable to continue\n");
588 return 1;
589 }
590
591 #ifdef HAVE_TLS
592 if (n_tls) {
593 if (!tls_crt || !tls_key) {
594 fprintf(stderr, "Please specify a certificate and "
595 "a key file to enable SSL support\n");
596 return 1;
597 }
598
599 if (uh_tls_init(tls_key, tls_crt, tls_ciphers))
600 return 1;
601 }
602 #endif
603
604 #ifdef HAVE_LUA
605 if (lua_handler || lua_prefix) {
606 fprintf(stderr, "Need handler and prefix to enable Lua support\n");
607 return 1;
608 }
609
610 if (!list_empty(&conf.lua_prefix) && uh_plugin_init("uhttpd_lua.so"))
611 return 1;
612 #endif
613 #ifdef HAVE_UCODE
614 if (ucode_handler || ucode_prefix) {
615 fprintf(stderr, "Need handler and prefix to enable ucode support\n");
616 return 1;
617 }
618
619 if (!list_empty(&conf.ucode_prefix) && uh_plugin_init("uhttpd_ucode.so"))
620 return 1;
621 #endif
622 #ifdef HAVE_UBUS
623 if (conf.ubus_prefix && uh_plugin_init("uhttpd_ubus.so"))
624 return 1;
625 #endif
626
627 /* fork (if not disabled) */
628 if (!nofork) {
629 switch (fork()) {
630 case -1:
631 perror("fork()");
632 exit(1);
633
634 case 0:
635 /* daemon setup */
636 if (chdir("/"))
637 perror("chdir()");
638
639 cur_fd = open("/dev/null", O_WRONLY);
640 if (cur_fd > 0) {
641 dup2(cur_fd, 0);
642 dup2(cur_fd, 1);
643 dup2(cur_fd, 2);
644 }
645
646 break;
647
648 default:
649 exit(0);
650 }
651 }
652
653 return run_server();
654 }