13d02a4f101512c01be6a3141f8cb186f18487ff
[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, default is '/lua'\n"
155 " -L file Lua handler script, omit to disable Lua\n"
156 #endif
157 #ifdef HAVE_UBUS
158 " -u string URL prefix for UBUS via JSON-RPC handler\n"
159 " -U file Override ubus socket path\n"
160 " -a Do not authenticate JSON-RPC requests against UBUS session api\n"
161 " -X Enable CORS HTTP headers on JSON-RPC api\n"
162 " -e Events subscription reconnection time (retry value)\n"
163 #endif
164 " -x string URL prefix for CGI handler, default is '/cgi-bin'\n"
165 " -y alias[=path] URL alias handle\n"
166 " -i .ext=path Use interpreter at path for files with the given extension\n"
167 " -t seconds CGI, Lua and UBUS script timeout in seconds, default is 60\n"
168 " -T seconds Network timeout in seconds, default is 30\n"
169 " -k seconds HTTP keepalive timeout\n"
170 " -A seconds TCP keepalive timeout, default is unset\n"
171 " -d string URL decode given string\n"
172 " -r string Specify basic auth realm\n"
173 " -m string MD5 crypt given string\n"
174 "\n", name
175 );
176 return 1;
177 }
178
179 static void init_defaults_pre(void)
180 {
181 conf.script_timeout = 60;
182 conf.network_timeout = 30;
183 conf.http_keepalive = 20;
184 conf.max_script_requests = 3;
185 conf.max_connections = 100;
186 conf.realm = "Protected Area";
187 conf.cgi_prefix = "/cgi-bin";
188 conf.cgi_path = "/sbin:/usr/sbin:/bin:/usr/bin";
189 INIT_LIST_HEAD(&conf.cgi_alias);
190 INIT_LIST_HEAD(&conf.lua_prefix);
191 #if HAVE_UCODE
192 INIT_LIST_HEAD(&conf.ucode_prefix);
193 #endif
194 }
195
196 static void init_defaults_post(void)
197 {
198 uh_index_add("index.html");
199 uh_index_add("index.htm");
200 uh_index_add("default.html");
201 uh_index_add("default.htm");
202
203 if (conf.cgi_prefix) {
204 char *str = malloc(strlen(conf.docroot) + strlen(conf.cgi_prefix) + 1);
205
206 strcpy(str, conf.docroot);
207 strcat(str, conf.cgi_prefix);
208 conf.cgi_docroot_path = str;
209 conf.cgi_prefix_len = strlen(conf.cgi_prefix);
210 };
211 }
212
213 static void fixup_prefix(char *str)
214 {
215 int len;
216
217 if (!str || !str[0])
218 return;
219
220 len = strlen(str) - 1;
221
222 while (len >= 0 && str[len] == '/')
223 len--;
224
225 str[len + 1] = 0;
226 }
227
228 #ifdef HAVE_LUA
229 static void add_lua_prefix(const char *prefix, const char *handler) {
230 struct lua_prefix *p;
231 char *pprefix, *phandler;
232
233 p = calloc_a(sizeof(*p),
234 &pprefix, strlen(prefix) + 1,
235 &phandler, strlen(handler) + 1);
236
237 if (!p)
238 return;
239
240 p->prefix = strcpy(pprefix, prefix);
241 p->handler = strcpy(phandler, handler);
242
243 list_add_tail(&p->list, &conf.lua_prefix);
244 }
245 #endif
246
247 #ifdef HAVE_UCODE
248 static void add_ucode_prefix(const char *prefix, const char *handler) {
249 struct ucode_prefix *p;
250 char *pprefix, *phandler;
251
252 p = calloc_a(sizeof(*p),
253 &pprefix, strlen(prefix) + 1,
254 &phandler, strlen(handler) + 1);
255
256 if (!p)
257 return;
258
259 p->prefix = strcpy(pprefix, prefix);
260 p->handler = strcpy(phandler, handler);
261
262 list_add_tail(&p->list, &conf.ucode_prefix);
263 }
264 #endif
265
266 int main(int argc, char **argv)
267 {
268 struct alias *alias;
269 bool nofork = false;
270 char *port;
271 int opt, ch;
272 int cur_fd;
273 int bound = 0;
274 #ifdef HAVE_TLS
275 int n_tls = 0;
276 const char *tls_key = NULL, *tls_crt = NULL, *tls_ciphers = NULL;
277 #endif
278 #ifdef HAVE_LUA
279 const char *lua_prefix = NULL, *lua_handler = NULL;
280 #endif
281 #ifdef HAVE_UCODE
282 const char *ucode_prefix = NULL, *ucode_handler = NULL;
283 #endif
284
285 BUILD_BUG_ON(sizeof(uh_buf) < PATH_MAX);
286
287 uh_dispatch_add(&cgi_dispatch);
288 init_defaults_pre();
289 signal(SIGPIPE, SIG_IGN);
290
291 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) {
292 switch(ch) {
293 #ifdef HAVE_TLS
294 case 'C':
295 tls_crt = optarg;
296 break;
297
298 case 'K':
299 tls_key = optarg;
300 break;
301
302 case 'P':
303 tls_ciphers = optarg;
304 break;
305
306 case 'q':
307 conf.tls_redirect = 1;
308 break;
309
310 case 's':
311 n_tls++;
312 /* fall through */
313 #else
314 case 'C':
315 case 'K':
316 case 'P':
317 case 'q':
318 case 's':
319 fprintf(stderr, "uhttpd: TLS support not compiled, "
320 "ignoring -%c\n", ch);
321 break;
322 #endif
323 case 'p':
324 optarg = strdup(optarg);
325 bound += add_listener_arg(optarg, (ch == 's'));
326 break;
327
328 case 'h':
329 if (!realpath(optarg, uh_buf)) {
330 fprintf(stderr, "Error: Invalid directory %s: %s\n",
331 optarg, strerror(errno));
332 exit(1);
333 }
334 conf.docroot = strdup(uh_buf);
335 break;
336
337 case 'H':
338 if (uh_handler_add(optarg)) {
339 fprintf(stderr, "Error: Failed to load handler script %s\n",
340 optarg);
341 exit(1);
342 }
343 break;
344
345 case 'E':
346 if (optarg[0] != '/') {
347 fprintf(stderr, "Error: Invalid error handler: %s\n",
348 optarg);
349 exit(1);
350 }
351 conf.error_handler = optarg;
352 break;
353
354 case 'I':
355 if (optarg[0] == '/') {
356 fprintf(stderr, "Error: Invalid index page: %s\n",
357 optarg);
358 exit(1);
359 }
360 uh_index_add(optarg);
361 break;
362
363 case 'S':
364 conf.no_symlinks = 1;
365 break;
366
367 case 'D':
368 conf.no_dirlists = 1;
369 break;
370
371 case 'R':
372 conf.rfc1918_filter = 1;
373 break;
374
375 case 'n':
376 conf.max_script_requests = atoi(optarg);
377 break;
378
379 case 'N':
380 conf.max_connections = atoi(optarg);
381 break;
382
383 case 'x':
384 fixup_prefix(optarg);
385 conf.cgi_prefix = optarg;
386 break;
387
388 case 'y':
389 alias = calloc(1, sizeof(*alias));
390 if (!alias) {
391 fprintf(stderr, "Error: failed to allocate alias\n");
392 exit(1);
393 }
394 alias->alias = strdup(optarg);
395 alias->path = strchr(alias->alias, '=');
396 if (alias->path)
397 *alias->path++ = 0;
398 list_add(&alias->list, &conf.cgi_alias);
399 break;
400
401 case 'i':
402 optarg = strdup(optarg);
403 port = strchr(optarg, '=');
404 if (optarg[0] != '.' || !port) {
405 fprintf(stderr, "Error: Invalid interpreter: %s\n",
406 optarg);
407 exit(1);
408 }
409
410 *port++ = 0;
411 uh_interpreter_add(optarg, port);
412 break;
413
414 case 't':
415 conf.script_timeout = atoi(optarg);
416 break;
417
418 case 'T':
419 conf.network_timeout = atoi(optarg);
420 break;
421
422 case 'k':
423 conf.http_keepalive = atoi(optarg);
424 break;
425
426 case 'A':
427 conf.tcp_keepalive = atoi(optarg);
428 break;
429
430 case 'f':
431 nofork = 1;
432 break;
433
434 case 'd':
435 optarg = strdup(optarg);
436 port = alloca(strlen(optarg) + 1);
437 if (!port)
438 return -1;
439
440 /* "decode" plus to space to retain compat */
441 for (opt = 0; optarg[opt]; opt++)
442 if (optarg[opt] == '+')
443 optarg[opt] = ' ';
444
445 /* opt now contains strlen(optarg) -- no need to re-scan */
446 if (uh_urldecode(port, opt, optarg, opt) < 0) {
447 fprintf(stderr, "uhttpd: invalid encoding\n");
448 return -1;
449 }
450
451 printf("%s", port);
452 return 0;
453 break;
454
455 /* basic auth realm */
456 case 'r':
457 conf.realm = optarg;
458 break;
459
460 /* md5 crypt */
461 case 'm':
462 printf("%s\n", crypt(optarg, "$1$"));
463 return 0;
464 break;
465
466 /* config file */
467 case 'c':
468 conf.file = optarg;
469 break;
470
471 #ifdef HAVE_LUA
472 case 'l':
473 case 'L':
474 if (ch == 'l') {
475 if (lua_prefix)
476 fprintf(stderr, "uhttpd: Ignoring previous -%c %s\n",
477 ch, lua_prefix);
478
479 lua_prefix = optarg;
480 }
481 else {
482 if (lua_handler)
483 fprintf(stderr, "uhttpd: Ignoring previous -%c %s\n",
484 ch, lua_handler);
485
486 lua_handler = optarg;
487 }
488
489 if (lua_prefix && lua_handler) {
490 add_lua_prefix(lua_prefix, lua_handler);
491 lua_prefix = NULL;
492 lua_handler = NULL;
493 }
494
495 break;
496 #else
497 case 'l':
498 case 'L':
499 fprintf(stderr, "uhttpd: Lua support not compiled, "
500 "ignoring -%c\n", ch);
501 break;
502 #endif
503 #ifdef HAVE_UCODE
504 case 'o':
505 case 'O':
506 if (ch == 'o') {
507 if (ucode_prefix)
508 fprintf(stderr, "uhttpd: Ignoring previous -%c %s\n",
509 ch, ucode_prefix);
510
511 ucode_prefix = optarg;
512 }
513 else {
514 if (ucode_handler)
515 fprintf(stderr, "uhttpd: Ignoring previous -%c %s\n",
516 ch, ucode_handler);
517
518 ucode_handler = optarg;
519 }
520
521 if (ucode_prefix && ucode_handler) {
522 add_ucode_prefix(ucode_prefix, ucode_handler);
523 ucode_prefix = NULL;
524 ucode_handler = NULL;
525 }
526
527 break;
528 #else
529 case 'o':
530 case 'O':
531 fprintf(stderr, "uhttpd: ucode support not compiled, "
532 "ignoring -%c\n", ch);
533 break;
534 #endif
535 #ifdef HAVE_UBUS
536 case 'a':
537 conf.ubus_noauth = 1;
538 break;
539
540 case 'u':
541 conf.ubus_prefix = optarg;
542 break;
543
544 case 'U':
545 conf.ubus_socket = optarg;
546 break;
547
548 case 'X':
549 conf.ubus_cors = 1;
550 break;
551
552 case 'e':
553 conf.events_retry = atoi(optarg);
554 break;
555 #else
556 case 'a':
557 case 'u':
558 case 'U':
559 case 'X':
560 case 'e':
561 fprintf(stderr, "uhttpd: UBUS support not compiled, "
562 "ignoring -%c\n", ch);
563 break;
564 #endif
565 default:
566 return usage(argv[0]);
567 }
568 }
569
570 uh_config_parse();
571
572 if (!conf.docroot) {
573 if (!realpath(".", uh_buf)) {
574 fprintf(stderr, "Error: Unable to determine work dir\n");
575 return 1;
576 }
577 conf.docroot = strdup(uh_buf);
578 }
579
580 init_defaults_post();
581
582 if (!bound) {
583 fprintf(stderr, "Error: No sockets bound, unable to continue\n");
584 return 1;
585 }
586
587 #ifdef HAVE_TLS
588 if (n_tls) {
589 if (!tls_crt || !tls_key) {
590 fprintf(stderr, "Please specify a certificate and "
591 "a key file to enable SSL support\n");
592 return 1;
593 }
594
595 if (uh_tls_init(tls_key, tls_crt, tls_ciphers))
596 return 1;
597 }
598 #endif
599
600 #ifdef HAVE_LUA
601 if (lua_handler || lua_prefix) {
602 fprintf(stderr, "Need handler and prefix to enable Lua support\n");
603 return 1;
604 }
605
606 if (!list_empty(&conf.lua_prefix) && uh_plugin_init("uhttpd_lua.so"))
607 return 1;
608 #endif
609 #ifdef HAVE_UCODE
610 if (ucode_handler || ucode_prefix) {
611 fprintf(stderr, "Need handler and prefix to enable ucode support\n");
612 return 1;
613 }
614
615 if (!list_empty(&conf.ucode_prefix) && uh_plugin_init("uhttpd_ucode.so"))
616 return 1;
617 #endif
618 #ifdef HAVE_UBUS
619 if (conf.ubus_prefix && uh_plugin_init("uhttpd_ubus.so"))
620 return 1;
621 #endif
622
623 /* fork (if not disabled) */
624 if (!nofork) {
625 switch (fork()) {
626 case -1:
627 perror("fork()");
628 exit(1);
629
630 case 0:
631 /* daemon setup */
632 if (chdir("/"))
633 perror("chdir()");
634
635 cur_fd = open("/dev/null", O_WRONLY);
636 if (cur_fd > 0) {
637 dup2(cur_fd, 0);
638 dup2(cur_fd, 1);
639 dup2(cur_fd, 2);
640 }
641
642 break;
643
644 default:
645 exit(0);
646 }
647 }
648
649 return run_server();
650 }