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