uhttpd: allow the config to override the default index file
[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                         break;
350
351                 /* basic auth realm */
352                 case 'r':
353                         conf.realm = optarg;
354                         break;
355
356                 /* md5 crypt */
357                 case 'm':
358                         printf("%s\n", crypt(optarg, "$1$"));
359                         return 0;
360                         break;
361
362                 /* config file */
363                 case 'c':
364                         conf.file = optarg;
365                         break;
366
367 #ifdef HAVE_LUA
368                 case 'l':
369                         conf.lua_prefix = optarg;
370                         break;
371
372                 case 'L':
373                         conf.lua_handler = optarg;
374                         break;
375 #else
376                 case 'l':
377                 case 'L':
378                         fprintf(stderr, "uhttpd: Lua support not compiled, "
379                                         "ignoring -%c\n", opt);
380                         break;
381 #endif
382 #ifdef HAVE_UBUS
383                 case 'a':
384                         conf.ubus_noauth = 1;
385                         break;
386
387                 case 'u':
388                         conf.ubus_prefix = optarg;
389                         break;
390
391                 case 'U':
392                         conf.ubus_socket = optarg;
393                         break;
394 #else
395                 case 'a':
396                 case 'u':
397                 case 'U':
398                         fprintf(stderr, "uhttpd: UBUS support not compiled, "
399                                         "ignoring -%c\n", opt);
400                         break;
401 #endif
402                 default:
403                         return usage(argv[0]);
404                 }
405         }
406
407         uh_config_parse();
408         init_defaults_post();
409
410         if (!bound) {
411                 fprintf(stderr, "Error: No sockets bound, unable to continue\n");
412                 return 1;
413         }
414
415         if (!conf.docroot) {
416                 if (!realpath(".", uh_buf)) {
417                         fprintf(stderr, "Error: Unable to determine work dir\n");
418                         return 1;
419                 }
420                 conf.docroot = strdup(uh_buf);
421         }
422
423 #ifdef HAVE_TLS
424         if (n_tls) {
425                 if (!tls_crt || !tls_key) {
426                         fprintf(stderr, "Please specify a certificate and "
427                                         "a key file to enable SSL support\n");
428                         return 1;
429                 }
430
431                 if (uh_tls_init(tls_key, tls_crt))
432                     return 1;
433         }
434 #endif
435
436 #ifdef HAVE_LUA
437         if (conf.lua_handler || conf.lua_prefix) {
438                 if (!conf.lua_handler || !conf.lua_prefix) {
439                         fprintf(stderr, "Need handler and prefix to enable Lua support\n");
440                         return 1;
441                 }
442                 if (uh_plugin_init("uhttpd_lua.so"))
443                         return 1;
444         }
445 #endif
446 #ifdef HAVE_UBUS
447         if (conf.ubus_prefix && uh_plugin_init("uhttpd_ubus.so"))
448                 return 1;
449 #endif
450
451         /* fork (if not disabled) */
452         if (!nofork) {
453                 switch (fork()) {
454                 case -1:
455                         perror("fork()");
456                         exit(1);
457
458                 case 0:
459                         /* daemon setup */
460                         if (chdir("/"))
461                                 perror("chdir()");
462
463                         cur_fd = open("/dev/null", O_WRONLY);
464                         if (cur_fd > 0) {
465                                 dup2(cur_fd, 0);
466                                 dup2(cur_fd, 1);
467                                 dup2(cur_fd, 2);
468                         }
469
470                         break;
471
472                 default:
473                         exit(0);
474                 }
475         }
476
477         return run_server();
478 }