add support for sending HTTP/1.1 100 Continue
[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 #include <sys/types.h>
21 #include <sys/socket.h>
22 #include <netinet/in.h>
23
24 #include <getopt.h>
25 #include <errno.h>
26 #include <netdb.h>
27 #include <signal.h>
28
29 #include <libubox/usock.h>
30
31 #include "uhttpd.h"
32
33 char uh_buf[4096];
34
35 static int run_server(void)
36 {
37         uloop_init();
38         uh_setup_listeners();
39         uloop_run();
40
41         return 0;
42 }
43
44 static void uh_config_parse(void)
45 {
46         const char *path = conf.file;
47         FILE *c;
48         char line[512];
49         char *col1;
50         char *col2;
51         char *eol;
52
53         if (!path)
54                 path = "/etc/httpd.conf";
55
56         c = fopen(path, "r");
57         if (!c)
58                 return;
59
60         memset(line, 0, sizeof(line));
61
62         while (fgets(line, sizeof(line) - 1, c)) {
63                 if ((line[0] == '/') && (strchr(line, ':') != NULL)) {
64                         if (!(col1 = strchr(line, ':')) || (*col1++ = 0) ||
65                                 !(col2 = strchr(col1, ':')) || (*col2++ = 0) ||
66                                 !(eol = strchr(col2, '\n')) || (*eol++  = 0))
67                                 continue;
68
69                         uh_auth_add(line, col1, col2);
70                 } else if (!strncmp(line, "I:", 2)) {
71                         if (!(col1 = strchr(line, ':')) || (*col1++ = 0) ||
72                                 !(eol = strchr(col1, '\n')) || (*eol++  = 0))
73                                 continue;
74
75                         uh_index_add(strdup(col1));
76                 } else if (!strncmp(line, "E404:", 5)) {
77                         if (!(col1 = strchr(line, ':')) || (*col1++ = 0) ||
78                                 !(eol = strchr(col1, '\n')) || (*eol++  = 0))
79                                 continue;
80
81                         conf.error_handler = strdup(col1);
82                 }
83 #ifdef HAVE_CGI
84                 else if ((line[0] == '*') && (strchr(line, ':') != NULL)) {
85                         if (!(col1 = strchr(line, '*')) || (*col1++ = 0) ||
86                                 !(col2 = strchr(col1, ':')) || (*col2++ = 0) ||
87                                 !(eol = strchr(col2, '\n')) || (*eol++  = 0))
88                                 continue;
89
90                         if (!uh_interpreter_add(col1, col2))
91                                 fprintf(stderr,
92                                                 "Unable to add interpreter %s for extension %s: "
93                                                 "Out of memory\n", col2, col1
94                                 );
95                 }
96 #endif
97         }
98
99         fclose(c);
100 }
101
102 static int add_listener_arg(char *arg, bool tls)
103 {
104         char *host = NULL;
105         char *port = arg;
106         char *s;
107
108         s = strrchr(arg, ':');
109         if (s) {
110                 host = arg;
111                 port = s + 1;
112                 *s = 0;
113         }
114
115         return uh_socket_bind(host, port, tls);
116 }
117
118 static int usage(const char *name)
119 {
120         fprintf(stderr,
121                 "Usage: %s -p [addr:]port -h docroot\n"
122                 "       -f              Do not fork to background\n"
123                 "       -c file         Configuration file, default is '/etc/httpd.conf'\n"
124                 "       -p [addr:]port  Bind to specified address and port, multiple allowed\n"
125 #ifdef HAVE_TLS
126                 "       -s [addr:]port  Like -p but provide HTTPS on this port\n"
127                 "       -C file         ASN.1 server certificate file\n"
128                 "       -K file         ASN.1 server private key file\n"
129 #endif
130                 "       -h directory    Specify the document root, default is '.'\n"
131                 "       -E string       Use given virtual URL as 404 error handler\n"
132                 "       -I string       Use given filename as index for directories, multiple allowed\n"
133                 "       -S              Do not follow symbolic links outside of the docroot\n"
134                 "       -D              Do not allow directory listings, send 403 instead\n"
135                 "       -R              Enable RFC1918 filter\n"
136                 "       -n count        Maximum allowed number of concurrent requests\n"
137 #ifdef HAVE_LUA
138                 "       -l string       URL prefix for Lua handler, default is '/lua'\n"
139                 "       -L file         Lua handler script, omit to disable Lua\n"
140 #endif
141 #ifdef HAVE_UBUS
142                 "       -u string       URL prefix for HTTP/JSON handler\n"
143                 "       -U file         Override ubus socket path\n"
144 #endif
145                 "       -x string       URL prefix for CGI handler, default is '/cgi-bin'\n"
146                 "       -i .ext=path    Use interpreter at path for files with the given extension\n"
147                 "       -t seconds      CGI, Lua and UBUS script timeout in seconds, default is 60\n"
148                 "       -T seconds      Network timeout in seconds, default is 30\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         bool nofork = false;
191         char *port;
192         int opt, ch;
193         int cur_fd;
194         int bound = 0;
195
196         BUILD_BUG_ON(sizeof(uh_buf) < PATH_MAX);
197
198         uh_dispatch_add(&cgi_dispatch);
199         init_defaults();
200         signal(SIGPIPE, SIG_IGN);
201
202         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) {
203                 bool tls = false;
204
205                 switch(ch) {
206                 case 's':
207                         tls = true;
208                         /* fall through */
209                 case 'p':
210                         bound += add_listener_arg(optarg, tls);
211                         break;
212
213                 case 'h':
214                         if (!realpath(optarg, uh_buf)) {
215                                 fprintf(stderr, "Error: Invalid directory %s: %s\n",
216                                                 optarg, strerror(errno));
217                                 exit(1);
218                         }
219                         conf.docroot = strdup(uh_buf);
220                         break;
221
222                 case 'E':
223                         if (optarg[0] != '/') {
224                                 fprintf(stderr, "Error: Invalid error handler: %s\n",
225                                                 optarg);
226                                 exit(1);
227                         }
228                         conf.error_handler = optarg;
229                         break;
230
231                 case 'I':
232                         if (optarg[0] == '/') {
233                                 fprintf(stderr, "Error: Invalid index page: %s\n",
234                                                 optarg);
235                                 exit(1);
236                         }
237                         uh_index_add(optarg);
238                         break;
239
240                 case 'S':
241                         conf.no_symlinks = 1;
242                         break;
243
244                 case 'D':
245                         conf.no_dirlists = 1;
246                         break;
247
248                 case 'R':
249                         conf.rfc1918_filter = 1;
250                         break;
251
252                 case 'n':
253                         conf.max_requests = atoi(optarg);
254                         break;
255
256                 case 'x':
257                         fixup_prefix(optarg);
258                         conf.cgi_prefix = optarg;
259                         break;
260
261                 case 'i':
262                         port = strchr(optarg, '=');
263                         if (optarg[0] != '.' || !port) {
264                                 fprintf(stderr, "Error: Invalid interpreter: %s\n",
265                                                 optarg);
266                                 exit(1);
267                         }
268
269                         *port++ = 0;
270                         uh_interpreter_add(optarg, port);
271                         break;
272
273                 case 't':
274                         conf.script_timeout = atoi(optarg);
275                         break;
276
277                 case 'T':
278                         conf.network_timeout = atoi(optarg);
279                         break;
280
281                 case 'A':
282                         conf.tcp_keepalive = atoi(optarg);
283                         break;
284
285                 case 'f':
286                         nofork = 1;
287                         break;
288
289                 case 'd':
290                         port = alloca(strlen(optarg) + 1);
291                         if (!port)
292                                 return -1;
293
294                         /* "decode" plus to space to retain compat */
295                         for (opt = 0; optarg[opt]; opt++)
296                                 if (optarg[opt] == '+')
297                                         optarg[opt] = ' ';
298
299                         /* opt now contains strlen(optarg) -- no need to re-scan */
300                         if (uh_urldecode(port, opt, optarg, opt) < 0) {
301                                 fprintf(stderr, "uhttpd: invalid encoding\n");
302                                 return -1;
303                         }
304
305                         printf("%s", port);
306                         break;
307
308                 /* basic auth realm */
309                 case 'r':
310                         conf.realm = optarg;
311                         break;
312
313                 /* md5 crypt */
314                 case 'm':
315                         printf("%s\n", crypt(optarg, "$1$"));
316                         return 0;
317                         break;
318
319                 /* config file */
320                 case 'c':
321                         conf.file = optarg;
322                         break;
323
324                 default:
325                         return usage(argv[0]);
326                 }
327         }
328
329         uh_config_parse();
330
331         if (!bound) {
332                 fprintf(stderr, "Error: No sockets bound, unable to continue\n");
333                 return 1;
334         }
335
336         /* fork (if not disabled) */
337         if (!nofork) {
338                 switch (fork()) {
339                 case -1:
340                         perror("fork()");
341                         exit(1);
342
343                 case 0:
344                         /* daemon setup */
345                         if (chdir("/"))
346                                 perror("chdir()");
347
348                         cur_fd = open("/dev/null", O_WRONLY);
349                         if (cur_fd > 0) {
350                                 dup2(cur_fd, 0);
351                                 dup2(cur_fd, 1);
352                                 dup2(cur_fd, 2);
353                         }
354
355                         break;
356
357                 default:
358                         exit(0);
359                 }
360         }
361
362         return run_server();
363 }