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