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