11d2e547faea048aad0f844ab79b2a468f8fdb52
[project/uhttpd.git] / main.c
1 /*
2  * uhttpd - Tiny single-threaded httpd
3  *
4  *   Copyright (C) 2010-2012 Jo-Philipp Wich <xm@subsignal.org>
5  *   Copyright (C) 2012 Felix Fietkau <nbd@openwrt.org>
6  *
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
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
107         s = strrchr(arg, ':');
108         if (s) {
109                 host = arg;
110                 port = s + 1;
111                 *s = 0;
112         }
113
114         return uh_socket_bind(host, port, tls);
115 }
116
117 static int usage(const char *name)
118 {
119         fprintf(stderr,
120                 "Usage: %s -p [addr:]port -h docroot\n"
121                 "       -f              Do not fork to background\n"
122                 "       -c file         Configuration file, default is '/etc/httpd.conf'\n"
123                 "       -p [addr:]port  Bind to specified address and port, multiple allowed\n"
124 #ifdef HAVE_TLS
125                 "       -s [addr:]port  Like -p but provide HTTPS on this port\n"
126                 "       -C file         ASN.1 server certificate file\n"
127                 "       -K file         ASN.1 server private key file\n"
128 #endif
129                 "       -h directory    Specify the document root, default is '.'\n"
130                 "       -E string       Use given virtual URL as 404 error handler\n"
131                 "       -I string       Use given filename as index for directories, multiple allowed\n"
132                 "       -S              Do not follow symbolic links outside of the docroot\n"
133                 "       -D              Do not allow directory listings, send 403 instead\n"
134                 "       -R              Enable RFC1918 filter\n"
135                 "       -n count        Maximum allowed number of concurrent requests\n"
136 #ifdef HAVE_LUA
137                 "       -l string       URL prefix for Lua handler, default is '/lua'\n"
138                 "       -L file         Lua handler script, omit to disable Lua\n"
139 #endif
140 #ifdef HAVE_UBUS
141                 "       -u string       URL prefix for HTTP/JSON handler\n"
142                 "       -U file         Override ubus socket path\n"
143 #endif
144                 "       -x string       URL prefix for CGI handler, default is '/cgi-bin'\n"
145                 "       -i .ext=path    Use interpreter at path for files with the given extension\n"
146                 "       -t seconds      CGI, Lua and UBUS script timeout in seconds, default is 60\n"
147                 "       -T seconds      Network timeout in seconds, default is 30\n"
148                 "       -k seconds              HTTP keepalive timeout\n"
149                 "       -d string       URL decode given string\n"
150                 "       -r string       Specify basic auth realm\n"
151                 "       -m string       MD5 crypt given string\n"
152                 "\n", name
153         );
154         return 1;
155 }
156
157 static void init_defaults(void)
158 {
159         conf.script_timeout = 60;
160         conf.network_timeout = 30;
161         conf.http_keepalive = 20;
162         conf.max_requests = 3;
163         conf.realm = "Protected Area";
164         conf.cgi_prefix = "/cgi-bin";
165         conf.cgi_path = "/sbin:/usr/sbin:/bin:/usr/bin";
166
167         uh_index_add("index.html");
168         uh_index_add("index.htm");
169         uh_index_add("default.html");
170         uh_index_add("default.htm");
171 }
172
173 static void fixup_prefix(char *str)
174 {
175         int len;
176
177         if (!str || !str[0])
178                 return;
179
180         len = strlen(str) - 1;
181
182         while (len > 0 && str[len] == '/')
183                 len--;
184
185         str[len + 1] = 0;
186 }
187
188 int main(int argc, char **argv)
189 {
190         const char *tls_key = NULL, *tls_crt = NULL;
191         bool nofork = false;
192         char *port;
193         int opt, ch;
194         int cur_fd;
195         int bound = 0;
196         int n_tls = 0;
197
198         BUILD_BUG_ON(sizeof(uh_buf) < PATH_MAX);
199
200         uh_dispatch_add(&cgi_dispatch);
201         init_defaults();
202         signal(SIGPIPE, SIG_IGN);
203
204         while ((ch = getopt(argc, argv, "fSDRC:K:E:I:p:s:h:c:l:L:d:r:m:n:x:i:t:k:T:A:u:U:")) != -1) {
205                 bool tls = false;
206
207                 switch(ch) {
208                 case 's':
209                         n_tls++;
210                         tls = true;
211                         /* fall through */
212                 case 'p':
213                         bound += add_listener_arg(optarg, tls);
214                         break;
215
216                 case 'h':
217                         if (!realpath(optarg, uh_buf)) {
218                                 fprintf(stderr, "Error: Invalid directory %s: %s\n",
219                                                 optarg, strerror(errno));
220                                 exit(1);
221                         }
222                         conf.docroot = strdup(uh_buf);
223                         break;
224
225                 case 'E':
226                         if (optarg[0] != '/') {
227                                 fprintf(stderr, "Error: Invalid error handler: %s\n",
228                                                 optarg);
229                                 exit(1);
230                         }
231                         conf.error_handler = optarg;
232                         break;
233
234                 case 'I':
235                         if (optarg[0] == '/') {
236                                 fprintf(stderr, "Error: Invalid index page: %s\n",
237                                                 optarg);
238                                 exit(1);
239                         }
240                         uh_index_add(optarg);
241                         break;
242
243                 case 'S':
244                         conf.no_symlinks = 1;
245                         break;
246
247                 case 'D':
248                         conf.no_dirlists = 1;
249                         break;
250
251                 case 'R':
252                         conf.rfc1918_filter = 1;
253                         break;
254
255                 case 'n':
256                         conf.max_requests = atoi(optarg);
257                         break;
258
259                 case 'x':
260                         fixup_prefix(optarg);
261                         conf.cgi_prefix = optarg;
262                         break;
263
264                 case 'i':
265                         port = strchr(optarg, '=');
266                         if (optarg[0] != '.' || !port) {
267                                 fprintf(stderr, "Error: Invalid interpreter: %s\n",
268                                                 optarg);
269                                 exit(1);
270                         }
271
272                         *port++ = 0;
273                         uh_interpreter_add(optarg, port);
274                         break;
275
276                 case 't':
277                         conf.script_timeout = atoi(optarg);
278                         break;
279
280                 case 'T':
281                         conf.network_timeout = atoi(optarg);
282                         break;
283
284                 case 'k':
285                         conf.http_keepalive = atoi(optarg);
286                         break;
287
288                 case 'A':
289                         conf.tcp_keepalive = atoi(optarg);
290                         break;
291
292                 case 'f':
293                         nofork = 1;
294                         break;
295
296                 case 'd':
297                         port = alloca(strlen(optarg) + 1);
298                         if (!port)
299                                 return -1;
300
301                         /* "decode" plus to space to retain compat */
302                         for (opt = 0; optarg[opt]; opt++)
303                                 if (optarg[opt] == '+')
304                                         optarg[opt] = ' ';
305
306                         /* opt now contains strlen(optarg) -- no need to re-scan */
307                         if (uh_urldecode(port, opt, optarg, opt) < 0) {
308                                 fprintf(stderr, "uhttpd: invalid encoding\n");
309                                 return -1;
310                         }
311
312                         printf("%s", port);
313                         break;
314
315                 /* basic auth realm */
316                 case 'r':
317                         conf.realm = optarg;
318                         break;
319
320                 /* md5 crypt */
321                 case 'm':
322                         printf("%s\n", crypt(optarg, "$1$"));
323                         return 0;
324                         break;
325
326                 /* config file */
327                 case 'c':
328                         conf.file = optarg;
329                         break;
330
331                 case 'C':
332                         tls_crt = optarg;
333                         break;
334
335                 case 'K':
336                         tls_key = optarg;
337                         break;
338 #ifdef HAVE_LUA
339                 case 'l':
340                         conf.lua_prefix = optarg;
341                         break;
342
343                 case 'L':
344                         conf.lua_handler = optarg;
345                         break;
346 #endif
347 #ifdef HAVE_UBUS
348                 case 'u':
349                         conf.ubus_prefix = optarg;
350                         break;
351
352                 case 'U':
353                         conf.ubus_socket = optarg;
354                         break;
355 #endif
356                 default:
357                         return usage(argv[0]);
358                 }
359         }
360
361         uh_config_parse();
362
363         if (!bound) {
364                 fprintf(stderr, "Error: No sockets bound, unable to continue\n");
365                 return 1;
366         }
367
368         if (n_tls) {
369                 if (!tls_crt || !tls_key) {
370                         fprintf(stderr, "Please specify a certificate and "
371                                         "a key file to enable SSL support\n");
372                         return 1;
373                 }
374
375 #ifdef HAVE_TLS
376                 if (uh_tls_init(tls_key, tls_crt))
377                     return 1;
378 #else
379                 fprintf(stderr, "Error: TLS support not compiled in.\n");
380                 return 1;
381 #endif
382         }
383
384 #ifdef HAVE_LUA
385         if (conf.lua_handler || conf.lua_prefix) {
386                 if (!conf.lua_handler || !conf.lua_prefix) {
387                         fprintf(stderr, "Need handler and prefix to enable Lua support\n");
388                         return 1;
389                 }
390                 if (uh_plugin_init("uhttpd_lua.so"))
391                         return 1;
392         }
393 #endif
394 #ifdef HAVE_UBUS
395         if (conf.ubus_prefix && uh_plugin_init("uhttpd_ubus.so"))
396                 return 1;
397 #endif
398
399         /* fork (if not disabled) */
400         if (!nofork) {
401                 switch (fork()) {
402                 case -1:
403                         perror("fork()");
404                         exit(1);
405
406                 case 0:
407                         /* daemon setup */
408                         if (chdir("/"))
409                                 perror("chdir()");
410
411                         cur_fd = open("/dev/null", O_WRONLY);
412                         if (cur_fd > 0) {
413                                 dup2(cur_fd, 0);
414                                 dup2(cur_fd, 1);
415                                 dup2(cur_fd, 2);
416                         }
417
418                         break;
419
420                 default:
421                         exit(0);
422                 }
423         }
424
425         return run_server();
426 }