add basic tls support, todo: error handling
[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         uloop_run();
44
45         return 0;
46 }
47
48 static void uh_config_parse(void)
49 {
50         const char *path = conf.file;
51         FILE *c;
52         char line[512];
53         char *col1;
54         char *col2;
55         char *eol;
56
57         if (!path)
58                 path = "/etc/httpd.conf";
59
60         c = fopen(path, "r");
61         if (!c)
62                 return;
63
64         memset(line, 0, sizeof(line));
65
66         while (fgets(line, sizeof(line) - 1, c)) {
67                 if ((line[0] == '/') && (strchr(line, ':') != NULL)) {
68                         if (!(col1 = strchr(line, ':')) || (*col1++ = 0) ||
69                                 !(col2 = strchr(col1, ':')) || (*col2++ = 0) ||
70                                 !(eol = strchr(col2, '\n')) || (*eol++  = 0))
71                                 continue;
72
73                         uh_auth_add(line, col1, col2);
74                 } else if (!strncmp(line, "I:", 2)) {
75                         if (!(col1 = strchr(line, ':')) || (*col1++ = 0) ||
76                                 !(eol = strchr(col1, '\n')) || (*eol++  = 0))
77                                 continue;
78
79                         uh_index_add(strdup(col1));
80                 } else if (!strncmp(line, "E404:", 5)) {
81                         if (!(col1 = strchr(line, ':')) || (*col1++ = 0) ||
82                                 !(eol = strchr(col1, '\n')) || (*eol++  = 0))
83                                 continue;
84
85                         conf.error_handler = strdup(col1);
86                 }
87 #ifdef HAVE_CGI
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                         if (!uh_interpreter_add(col1, col2))
95                                 fprintf(stderr,
96                                                 "Unable to add interpreter %s for extension %s: "
97                                                 "Out of memory\n", col2, col1
98                                 );
99                 }
100 #endif
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
112         s = strrchr(arg, ':');
113         if (s) {
114                 host = arg;
115                 port = s + 1;
116                 *s = 0;
117         }
118
119         return uh_socket_bind(host, port, tls);
120 }
121
122 static int usage(const char *name)
123 {
124         fprintf(stderr,
125                 "Usage: %s -p [addr:]port -h docroot\n"
126                 "       -f              Do not fork to background\n"
127                 "       -c file         Configuration file, default is '/etc/httpd.conf'\n"
128                 "       -p [addr:]port  Bind to specified address and port, multiple allowed\n"
129 #ifdef HAVE_TLS
130                 "       -s [addr:]port  Like -p but provide HTTPS on this port\n"
131                 "       -C file         ASN.1 server certificate file\n"
132                 "       -K file         ASN.1 server private key file\n"
133 #endif
134                 "       -h directory    Specify the document root, default is '.'\n"
135                 "       -E string       Use given virtual URL as 404 error handler\n"
136                 "       -I string       Use given filename as index for directories, multiple allowed\n"
137                 "       -S              Do not follow symbolic links outside of the docroot\n"
138                 "       -D              Do not allow directory listings, send 403 instead\n"
139                 "       -R              Enable RFC1918 filter\n"
140                 "       -n count        Maximum allowed number of concurrent requests\n"
141 #ifdef HAVE_LUA
142                 "       -l string       URL prefix for Lua handler, default is '/lua'\n"
143                 "       -L file         Lua handler script, omit to disable Lua\n"
144 #endif
145 #ifdef HAVE_UBUS
146                 "       -u string       URL prefix for HTTP/JSON handler\n"
147                 "       -U file         Override ubus socket path\n"
148 #endif
149                 "       -x string       URL prefix for CGI handler, default is '/cgi-bin'\n"
150                 "       -i .ext=path    Use interpreter at path for files with the given extension\n"
151                 "       -t seconds      CGI, Lua and UBUS script timeout in seconds, default is 60\n"
152                 "       -T seconds      Network timeout in seconds, default is 30\n"
153                 "       -d string       URL decode given string\n"
154                 "       -r string       Specify basic auth realm\n"
155                 "       -m string       MD5 crypt given string\n"
156                 "\n", name
157         );
158         return 1;
159 }
160
161 static void init_defaults(void)
162 {
163         conf.script_timeout = 60;
164         conf.network_timeout = 30;
165         conf.http_keepalive = 20;
166         conf.max_requests = 3;
167         conf.realm = "Protected Area";
168         conf.cgi_prefix = "/cgi-bin";
169         conf.cgi_path = "/sbin:/usr/sbin:/bin:/usr/bin";
170
171         uh_index_add("index.html");
172         uh_index_add("index.htm");
173         uh_index_add("default.html");
174         uh_index_add("default.htm");
175 }
176
177 static void fixup_prefix(char *str)
178 {
179         int len;
180
181         if (!str || !str[0])
182                 return;
183
184         len = strlen(str) - 1;
185
186         while (len > 0 && str[len] == '/')
187                 len--;
188
189         str[len + 1] = 0;
190 }
191
192 int main(int argc, char **argv)
193 {
194         const char *tls_key, *tls_crt;
195         bool nofork = false;
196         char *port;
197         int opt, ch;
198         int cur_fd;
199         int bound = 0;
200         int n_tls = 0;
201
202         BUILD_BUG_ON(sizeof(uh_buf) < PATH_MAX);
203
204         uh_dispatch_add(&cgi_dispatch);
205         init_defaults();
206         signal(SIGPIPE, SIG_IGN);
207
208         while ((ch = getopt(argc, argv, "fSDRC:K:E:I:p:s:h:c:l:L:d:r:m:n:x:i:t:T:A:u:U:")) != -1) {
209                 bool tls = false;
210
211                 switch(ch) {
212                 case 's':
213                         n_tls++;
214                         tls = true;
215                         /* fall through */
216                 case 'p':
217                         bound += add_listener_arg(optarg, tls);
218                         break;
219
220                 case 'h':
221                         if (!realpath(optarg, uh_buf)) {
222                                 fprintf(stderr, "Error: Invalid directory %s: %s\n",
223                                                 optarg, strerror(errno));
224                                 exit(1);
225                         }
226                         conf.docroot = strdup(uh_buf);
227                         break;
228
229                 case 'E':
230                         if (optarg[0] != '/') {
231                                 fprintf(stderr, "Error: Invalid error handler: %s\n",
232                                                 optarg);
233                                 exit(1);
234                         }
235                         conf.error_handler = optarg;
236                         break;
237
238                 case 'I':
239                         if (optarg[0] == '/') {
240                                 fprintf(stderr, "Error: Invalid index page: %s\n",
241                                                 optarg);
242                                 exit(1);
243                         }
244                         uh_index_add(optarg);
245                         break;
246
247                 case 'S':
248                         conf.no_symlinks = 1;
249                         break;
250
251                 case 'D':
252                         conf.no_dirlists = 1;
253                         break;
254
255                 case 'R':
256                         conf.rfc1918_filter = 1;
257                         break;
258
259                 case 'n':
260                         conf.max_requests = atoi(optarg);
261                         break;
262
263                 case 'x':
264                         fixup_prefix(optarg);
265                         conf.cgi_prefix = optarg;
266                         break;
267
268                 case 'i':
269                         port = strchr(optarg, '=');
270                         if (optarg[0] != '.' || !port) {
271                                 fprintf(stderr, "Error: Invalid interpreter: %s\n",
272                                                 optarg);
273                                 exit(1);
274                         }
275
276                         *port++ = 0;
277                         uh_interpreter_add(optarg, port);
278                         break;
279
280                 case 't':
281                         conf.script_timeout = atoi(optarg);
282                         break;
283
284                 case 'T':
285                         conf.network_timeout = 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                 default:
339                         return usage(argv[0]);
340                 }
341         }
342
343         uh_config_parse();
344
345         if (!bound) {
346                 fprintf(stderr, "Error: No sockets bound, unable to continue\n");
347                 return 1;
348         }
349
350         if (n_tls) {
351                 if (!tls_crt || !tls_key) {
352                         fprintf(stderr, "Please specify a certificate and "
353                                         "a key file to enable SSL support\n");
354                         return 1;
355                 }
356
357 #ifdef HAVE_TLS
358                 if (uh_tls_init(tls_key, tls_crt))
359                     return 1;
360 #else
361                 fprintf(stderr, "Error: TLS support not compiled in.\n");
362                 return 1;
363 #endif
364         }
365
366         /* fork (if not disabled) */
367         if (!nofork) {
368                 switch (fork()) {
369                 case -1:
370                         perror("fork()");
371                         exit(1);
372
373                 case 0:
374                         /* daemon setup */
375                         if (chdir("/"))
376                                 perror("chdir()");
377
378                         cur_fd = open("/dev/null", O_WRONLY);
379                         if (cur_fd > 0) {
380                                 dup2(cur_fd, 0);
381                                 dup2(cur_fd, 1);
382                                 dup2(cur_fd, 2);
383                         }
384
385                         break;
386
387                 default:
388                         exit(0);
389                 }
390         }
391
392         return run_server();
393 }