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