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