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