Accept square bracket notation for IPv6 addresses
[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 #define _BSD_SOURCE
21 #define _GNU_SOURCE
22 #define _XOPEN_SOURCE 700
23 #include <sys/types.h>
24 #include <sys/socket.h>
25 #include <netinet/in.h>
26
27 #include <getopt.h>
28 #include <errno.h>
29 #include <netdb.h>
30 #include <signal.h>
31
32 #include <libubox/usock.h>
33
34 #include "uhttpd.h"
35 #include "tls.h"
36
37 char uh_buf[4096];
38
39 static int run_server(void)
40 {
41 uloop_init();
42 uh_setup_listeners();
43 uh_plugin_post_init();
44 uloop_run();
45
46 return 0;
47 }
48
49 static void uh_config_parse(void)
50 {
51 const char *path = conf.file;
52 FILE *c;
53 char line[512];
54 char *col1;
55 char *col2;
56 char *eol;
57
58 if (!path)
59 path = "/etc/httpd.conf";
60
61 c = fopen(path, "r");
62 if (!c)
63 return;
64
65 memset(line, 0, sizeof(line));
66
67 while (fgets(line, sizeof(line) - 1, c)) {
68 if ((line[0] == '/') && (strchr(line, ':') != NULL)) {
69 if (!(col1 = strchr(line, ':')) || (*col1++ = 0) ||
70 !(col2 = strchr(col1, ':')) || (*col2++ = 0) ||
71 !(eol = strchr(col2, '\n')) || (*eol++ = 0))
72 continue;
73
74 uh_auth_add(line, col1, col2);
75 } else if (!strncmp(line, "I:", 2)) {
76 if (!(col1 = strchr(line, ':')) || (*col1++ = 0) ||
77 !(eol = strchr(col1, '\n')) || (*eol++ = 0))
78 continue;
79
80 uh_index_add(strdup(col1));
81 } else if (!strncmp(line, "E404:", 5)) {
82 if (!(col1 = strchr(line, ':')) || (*col1++ = 0) ||
83 !(eol = strchr(col1, '\n')) || (*eol++ = 0))
84 continue;
85
86 conf.error_handler = strdup(col1);
87 }
88 else if ((line[0] == '*') && (strchr(line, ':') != NULL)) {
89 if (!(col1 = strchr(line, '*')) || (*col1++ = 0) ||
90 !(col2 = strchr(col1, ':')) || (*col2++ = 0) ||
91 !(eol = strchr(col2, '\n')) || (*eol++ = 0))
92 continue;
93
94 uh_interpreter_add(col1, col2);
95 }
96 }
97
98 fclose(c);
99 }
100
101 static int add_listener_arg(char *arg, bool tls)
102 {
103 char *host = NULL;
104 char *port = arg;
105 char *s;
106 int l;
107
108 s = strrchr(arg, ':');
109 if (s) {
110 host = arg;
111 port = s + 1;
112 *s = 0;
113 }
114
115 if (host && *host == '[') {
116 l = strlen(host);
117 if (l >= 2) {
118 host[l-1] = 0;
119 host++;
120 }
121 }
122
123 return uh_socket_bind(host, port, tls);
124 }
125
126 static int usage(const char *name)
127 {
128 fprintf(stderr,
129 "Usage: %s -p [addr:]port -h docroot\n"
130 " -f Do not fork to background\n"
131 " -c file Configuration file, default is '/etc/httpd.conf'\n"
132 " -p [addr:]port Bind to specified address and port, multiple allowed\n"
133 #ifdef HAVE_TLS
134 " -s [addr:]port Like -p but provide HTTPS on this port\n"
135 " -C file ASN.1 server certificate file\n"
136 " -K file ASN.1 server private key file\n"
137 #endif
138 " -h directory Specify the document root, default is '.'\n"
139 " -E string Use given virtual URL as 404 error handler\n"
140 " -I string Use given filename as index for directories, multiple allowed\n"
141 " -S Do not follow symbolic links outside of the docroot\n"
142 " -D Do not allow directory listings, send 403 instead\n"
143 " -R Enable RFC1918 filter\n"
144 " -n count Maximum allowed number of concurrent script requests\n"
145 " -N count Maximum allowed number of concurrent connections\n"
146 #ifdef HAVE_LUA
147 " -l string URL prefix for Lua handler, default is '/lua'\n"
148 " -L file Lua handler script, omit to disable Lua\n"
149 #endif
150 #ifdef HAVE_UBUS
151 " -u string URL prefix for UBUS via JSON-RPC handler\n"
152 " -U file Override ubus socket path\n"
153 " -a Do not authenticate JSON-RPC requests against UBUS session api\n"
154 #endif
155 " -x string URL prefix for CGI handler, default is '/cgi-bin'\n"
156 " -i .ext=path Use interpreter at path for files with the given extension\n"
157 " -t seconds CGI, Lua and UBUS script timeout in seconds, default is 60\n"
158 " -T seconds Network timeout in seconds, default is 30\n"
159 " -k seconds HTTP keepalive timeout\n"
160 " -d string URL decode given string\n"
161 " -r string Specify basic auth realm\n"
162 " -m string MD5 crypt given string\n"
163 "\n", name
164 );
165 return 1;
166 }
167
168 static void init_defaults(void)
169 {
170 conf.script_timeout = 60;
171 conf.network_timeout = 30;
172 conf.http_keepalive = 20;
173 conf.max_script_requests = 3;
174 conf.max_connections = 100;
175 conf.realm = "Protected Area";
176 conf.cgi_prefix = "/cgi-bin";
177 conf.cgi_path = "/sbin:/usr/sbin:/bin:/usr/bin";
178
179 uh_index_add("index.html");
180 uh_index_add("index.htm");
181 uh_index_add("default.html");
182 uh_index_add("default.htm");
183 }
184
185 static void fixup_prefix(char *str)
186 {
187 int len;
188
189 if (!str || !str[0])
190 return;
191
192 len = strlen(str) - 1;
193
194 while (len > 0 && str[len] == '/')
195 len--;
196
197 str[len + 1] = 0;
198 }
199
200 int main(int argc, char **argv)
201 {
202 bool nofork = false;
203 char *port;
204 int opt, ch;
205 int cur_fd;
206 int bound = 0;
207
208 #ifdef HAVE_TLS
209 int n_tls = 0;
210 const char *tls_key = NULL, *tls_crt = NULL;
211 #endif
212
213 BUILD_BUG_ON(sizeof(uh_buf) < PATH_MAX);
214
215 uh_dispatch_add(&cgi_dispatch);
216 init_defaults();
217 signal(SIGPIPE, SIG_IGN);
218
219 while ((ch = getopt(argc, argv, "afSDRC:K:E:I:p:s:h:c:l:L:d:r:m:n:N:x:i:t:k:T:A:u:U:")) != -1) {
220 switch(ch) {
221 #ifdef HAVE_TLS
222 case 'C':
223 tls_crt = optarg;
224 break;
225
226 case 'K':
227 tls_key = optarg;
228 break;
229
230 case 's':
231 n_tls++;
232 /* fall through */
233 #else
234 case 'C':
235 case 'K':
236 case 's':
237 fprintf(stderr, "uhttpd: TLS support not compiled, "
238 "ignoring -%c\n", opt);
239 break;
240 #endif
241 case 'p':
242 bound += add_listener_arg(optarg, (ch == 's'));
243 break;
244
245 case 'h':
246 if (!realpath(optarg, uh_buf)) {
247 fprintf(stderr, "Error: Invalid directory %s: %s\n",
248 optarg, strerror(errno));
249 exit(1);
250 }
251 conf.docroot = strdup(uh_buf);
252 break;
253
254 case 'E':
255 if (optarg[0] != '/') {
256 fprintf(stderr, "Error: Invalid error handler: %s\n",
257 optarg);
258 exit(1);
259 }
260 conf.error_handler = optarg;
261 break;
262
263 case 'I':
264 if (optarg[0] == '/') {
265 fprintf(stderr, "Error: Invalid index page: %s\n",
266 optarg);
267 exit(1);
268 }
269 uh_index_add(optarg);
270 break;
271
272 case 'S':
273 conf.no_symlinks = 1;
274 break;
275
276 case 'D':
277 conf.no_dirlists = 1;
278 break;
279
280 case 'R':
281 conf.rfc1918_filter = 1;
282 break;
283
284 case 'n':
285 conf.max_script_requests = atoi(optarg);
286 break;
287
288 case 'N':
289 conf.max_connections = atoi(optarg);
290 break;
291
292 case 'x':
293 fixup_prefix(optarg);
294 conf.cgi_prefix = optarg;
295 break;
296
297 case 'i':
298 port = strchr(optarg, '=');
299 if (optarg[0] != '.' || !port) {
300 fprintf(stderr, "Error: Invalid interpreter: %s\n",
301 optarg);
302 exit(1);
303 }
304
305 *port++ = 0;
306 uh_interpreter_add(optarg, port);
307 break;
308
309 case 't':
310 conf.script_timeout = atoi(optarg);
311 break;
312
313 case 'T':
314 conf.network_timeout = atoi(optarg);
315 break;
316
317 case 'k':
318 conf.http_keepalive = atoi(optarg);
319 break;
320
321 case 'A':
322 conf.tcp_keepalive = atoi(optarg);
323 break;
324
325 case 'f':
326 nofork = 1;
327 break;
328
329 case 'd':
330 port = alloca(strlen(optarg) + 1);
331 if (!port)
332 return -1;
333
334 /* "decode" plus to space to retain compat */
335 for (opt = 0; optarg[opt]; opt++)
336 if (optarg[opt] == '+')
337 optarg[opt] = ' ';
338
339 /* opt now contains strlen(optarg) -- no need to re-scan */
340 if (uh_urldecode(port, opt, optarg, opt) < 0) {
341 fprintf(stderr, "uhttpd: invalid encoding\n");
342 return -1;
343 }
344
345 printf("%s", port);
346 break;
347
348 /* basic auth realm */
349 case 'r':
350 conf.realm = optarg;
351 break;
352
353 /* md5 crypt */
354 case 'm':
355 printf("%s\n", crypt(optarg, "$1$"));
356 return 0;
357 break;
358
359 /* config file */
360 case 'c':
361 conf.file = optarg;
362 break;
363
364 #ifdef HAVE_LUA
365 case 'l':
366 conf.lua_prefix = optarg;
367 break;
368
369 case 'L':
370 conf.lua_handler = optarg;
371 break;
372 #else
373 case 'l':
374 case 'L':
375 fprintf(stderr, "uhttpd: Lua support not compiled, "
376 "ignoring -%c\n", opt);
377 break;
378 #endif
379 #ifdef HAVE_UBUS
380 case 'a':
381 conf.ubus_noauth = 1;
382 break;
383
384 case 'u':
385 conf.ubus_prefix = optarg;
386 break;
387
388 case 'U':
389 conf.ubus_socket = optarg;
390 break;
391 #else
392 case 'a':
393 case 'u':
394 case 'U':
395 fprintf(stderr, "uhttpd: UBUS support not compiled, "
396 "ignoring -%c\n", opt);
397 break;
398 #endif
399 default:
400 return usage(argv[0]);
401 }
402 }
403
404 uh_config_parse();
405
406 if (!bound) {
407 fprintf(stderr, "Error: No sockets bound, unable to continue\n");
408 return 1;
409 }
410
411 if (!conf.docroot) {
412 if (!realpath(".", uh_buf)) {
413 fprintf(stderr, "Error: Unable to determine work dir\n");
414 return 1;
415 }
416 conf.docroot = strdup(uh_buf);
417 }
418
419 #ifdef HAVE_TLS
420 if (n_tls) {
421 if (!tls_crt || !tls_key) {
422 fprintf(stderr, "Please specify a certificate and "
423 "a key file to enable SSL support\n");
424 return 1;
425 }
426
427 if (uh_tls_init(tls_key, tls_crt))
428 return 1;
429 }
430 #endif
431
432 #ifdef HAVE_LUA
433 if (conf.lua_handler || conf.lua_prefix) {
434 if (!conf.lua_handler || !conf.lua_prefix) {
435 fprintf(stderr, "Need handler and prefix to enable Lua support\n");
436 return 1;
437 }
438 if (uh_plugin_init("uhttpd_lua.so"))
439 return 1;
440 }
441 #endif
442 #ifdef HAVE_UBUS
443 if (conf.ubus_prefix && uh_plugin_init("uhttpd_ubus.so"))
444 return 1;
445 #endif
446
447 /* fork (if not disabled) */
448 if (!nofork) {
449 switch (fork()) {
450 case -1:
451 perror("fork()");
452 exit(1);
453
454 case 0:
455 /* daemon setup */
456 if (chdir("/"))
457 perror("chdir()");
458
459 cur_fd = open("/dev/null", O_WRONLY);
460 if (cur_fd > 0) {
461 dup2(cur_fd, 0);
462 dup2(cur_fd, 1);
463 dup2(cur_fd, 2);
464 }
465
466 break;
467
468 default:
469 exit(0);
470 }
471 }
472
473 return run_server();
474 }