e53a3114c52e76e9c1dfe22c6b49387a5a2ee4d1
[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_pre(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
180 static void init_defaults_post(void)
181 {
182 uh_index_add("index.html");
183 uh_index_add("index.htm");
184 uh_index_add("default.html");
185 uh_index_add("default.htm");
186 }
187
188 static void fixup_prefix(char *str)
189 {
190 int len;
191
192 if (!str || !str[0])
193 return;
194
195 len = strlen(str) - 1;
196
197 while (len > 0 && str[len] == '/')
198 len--;
199
200 str[len + 1] = 0;
201 }
202
203 int main(int argc, char **argv)
204 {
205 bool nofork = false;
206 char *port;
207 int opt, ch;
208 int cur_fd;
209 int bound = 0;
210
211 #ifdef HAVE_TLS
212 int n_tls = 0;
213 const char *tls_key = NULL, *tls_crt = NULL;
214 #endif
215
216 BUILD_BUG_ON(sizeof(uh_buf) < PATH_MAX);
217
218 uh_dispatch_add(&cgi_dispatch);
219 init_defaults_pre();
220 signal(SIGPIPE, SIG_IGN);
221
222 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) {
223 switch(ch) {
224 #ifdef HAVE_TLS
225 case 'C':
226 tls_crt = optarg;
227 break;
228
229 case 'K':
230 tls_key = optarg;
231 break;
232
233 case 's':
234 n_tls++;
235 /* fall through */
236 #else
237 case 'C':
238 case 'K':
239 case 's':
240 fprintf(stderr, "uhttpd: TLS support not compiled, "
241 "ignoring -%c\n", opt);
242 break;
243 #endif
244 case 'p':
245 bound += add_listener_arg(optarg, (ch == 's'));
246 break;
247
248 case 'h':
249 if (!realpath(optarg, uh_buf)) {
250 fprintf(stderr, "Error: Invalid directory %s: %s\n",
251 optarg, strerror(errno));
252 exit(1);
253 }
254 conf.docroot = strdup(uh_buf);
255 break;
256
257 case 'E':
258 if (optarg[0] != '/') {
259 fprintf(stderr, "Error: Invalid error handler: %s\n",
260 optarg);
261 exit(1);
262 }
263 conf.error_handler = optarg;
264 break;
265
266 case 'I':
267 if (optarg[0] == '/') {
268 fprintf(stderr, "Error: Invalid index page: %s\n",
269 optarg);
270 exit(1);
271 }
272 uh_index_add(optarg);
273 break;
274
275 case 'S':
276 conf.no_symlinks = 1;
277 break;
278
279 case 'D':
280 conf.no_dirlists = 1;
281 break;
282
283 case 'R':
284 conf.rfc1918_filter = 1;
285 break;
286
287 case 'n':
288 conf.max_script_requests = atoi(optarg);
289 break;
290
291 case 'N':
292 conf.max_connections = atoi(optarg);
293 break;
294
295 case 'x':
296 fixup_prefix(optarg);
297 conf.cgi_prefix = optarg;
298 break;
299
300 case 'i':
301 port = strchr(optarg, '=');
302 if (optarg[0] != '.' || !port) {
303 fprintf(stderr, "Error: Invalid interpreter: %s\n",
304 optarg);
305 exit(1);
306 }
307
308 *port++ = 0;
309 uh_interpreter_add(optarg, port);
310 break;
311
312 case 't':
313 conf.script_timeout = atoi(optarg);
314 break;
315
316 case 'T':
317 conf.network_timeout = atoi(optarg);
318 break;
319
320 case 'k':
321 conf.http_keepalive = atoi(optarg);
322 break;
323
324 case 'A':
325 conf.tcp_keepalive = atoi(optarg);
326 break;
327
328 case 'f':
329 nofork = 1;
330 break;
331
332 case 'd':
333 port = alloca(strlen(optarg) + 1);
334 if (!port)
335 return -1;
336
337 /* "decode" plus to space to retain compat */
338 for (opt = 0; optarg[opt]; opt++)
339 if (optarg[opt] == '+')
340 optarg[opt] = ' ';
341
342 /* opt now contains strlen(optarg) -- no need to re-scan */
343 if (uh_urldecode(port, opt, optarg, opt) < 0) {
344 fprintf(stderr, "uhttpd: invalid encoding\n");
345 return -1;
346 }
347
348 printf("%s", port);
349 return 0;
350 break;
351
352 /* basic auth realm */
353 case 'r':
354 conf.realm = optarg;
355 break;
356
357 /* md5 crypt */
358 case 'm':
359 printf("%s\n", crypt(optarg, "$1$"));
360 return 0;
361 break;
362
363 /* config file */
364 case 'c':
365 conf.file = optarg;
366 break;
367
368 #ifdef HAVE_LUA
369 case 'l':
370 conf.lua_prefix = optarg;
371 break;
372
373 case 'L':
374 conf.lua_handler = optarg;
375 break;
376 #else
377 case 'l':
378 case 'L':
379 fprintf(stderr, "uhttpd: Lua support not compiled, "
380 "ignoring -%c\n", opt);
381 break;
382 #endif
383 #ifdef HAVE_UBUS
384 case 'a':
385 conf.ubus_noauth = 1;
386 break;
387
388 case 'u':
389 conf.ubus_prefix = optarg;
390 break;
391
392 case 'U':
393 conf.ubus_socket = optarg;
394 break;
395 #else
396 case 'a':
397 case 'u':
398 case 'U':
399 fprintf(stderr, "uhttpd: UBUS support not compiled, "
400 "ignoring -%c\n", opt);
401 break;
402 #endif
403 default:
404 return usage(argv[0]);
405 }
406 }
407
408 uh_config_parse();
409 init_defaults_post();
410
411 if (!bound) {
412 fprintf(stderr, "Error: No sockets bound, unable to continue\n");
413 return 1;
414 }
415
416 if (!conf.docroot) {
417 if (!realpath(".", uh_buf)) {
418 fprintf(stderr, "Error: Unable to determine work dir\n");
419 return 1;
420 }
421 conf.docroot = strdup(uh_buf);
422 }
423
424 #ifdef HAVE_TLS
425 if (n_tls) {
426 if (!tls_crt || !tls_key) {
427 fprintf(stderr, "Please specify a certificate and "
428 "a key file to enable SSL support\n");
429 return 1;
430 }
431
432 if (uh_tls_init(tls_key, tls_crt))
433 return 1;
434 }
435 #endif
436
437 #ifdef HAVE_LUA
438 if (conf.lua_handler || conf.lua_prefix) {
439 if (!conf.lua_handler || !conf.lua_prefix) {
440 fprintf(stderr, "Need handler and prefix to enable Lua support\n");
441 return 1;
442 }
443 if (uh_plugin_init("uhttpd_lua.so"))
444 return 1;
445 }
446 #endif
447 #ifdef HAVE_UBUS
448 if (conf.ubus_prefix && uh_plugin_init("uhttpd_ubus.so"))
449 return 1;
450 #endif
451
452 /* fork (if not disabled) */
453 if (!nofork) {
454 switch (fork()) {
455 case -1:
456 perror("fork()");
457 exit(1);
458
459 case 0:
460 /* daemon setup */
461 if (chdir("/"))
462 perror("chdir()");
463
464 cur_fd = open("/dev/null", O_WRONLY);
465 if (cur_fd > 0) {
466 dup2(cur_fd, 0);
467 dup2(cur_fd, 1);
468 dup2(cur_fd, 2);
469 }
470
471 break;
472
473 default:
474 exit(0);
475 }
476 }
477
478 return run_server();
479 }