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