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