etc: Add environment option to run init.d/ashd silently.
[ashd.git] / src / dirplex / dirplex.c
1 /*
2     ashd - A Sane HTTP Daemon
3     Copyright (C) 2008  Fredrik Tolf <fredrik@dolda2000.com>
4
5     This program is free software: you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation, either version 3 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include <stdlib.h>
20 #include <stdio.h>
21 #include <string.h>
22 #include <unistd.h>
23 #include <errno.h>
24 #include <sys/stat.h>
25 #include <ctype.h>
26 #include <dirent.h>
27 #include <time.h>
28 #include <fnmatch.h>
29 #include <sys/wait.h>
30 #include <sys/signal.h>
31
32 #ifdef HAVE_CONFIG_H
33 #include <config.h>
34 #endif
35 #include <utils.h>
36 #include <log.h>
37 #include <req.h>
38 #include <proc.h>
39 #include <resp.h>
40 #include <cf.h>
41
42 #include "dirplex.h"
43
44 time_t now;
45
46 static void chinit(void *idata)
47 {
48     char *twd = idata;
49     
50     if(twd != NULL) {
51         /* This should never be able to fail other than for critical
52          * I/O errors or some such, since the path has already been
53          * traversed. */
54         if(chdir(twd))
55             exit(127);
56     }
57 }
58
59 static void childerror(struct hthead *req, int fd)
60 {
61     if(errno == EAGAIN)
62         simpleerror(fd, 500, "Server Error", "The request handler is overloaded.");
63     else
64         simpleerror(fd, 500, "Server Error", "The request handler crashed.");
65 }
66
67 static void handle(struct hthead *req, int fd, char *path, struct pattern *pat)
68 {
69     struct child *ch;
70     struct config *ccf;
71     struct headmod *head;
72     char *twd;
73
74     for(head = pat->headers; head != NULL; head = head->next) {
75         headrmheader(req, head->name);
76         headappheader(req, head->name, head->value);
77     }
78     if(!strncmp(path, "./", 2) && path[2])
79         path += 2;
80     if(pat->fchild) {
81         headappheader(req, "X-Ash-File", path);
82         stdforkserve(pat->fchild, req, fd, NULL, NULL);
83     } else {
84         if((ch = findchild(path, pat->childnm, &ccf)) == NULL) {
85             flog(LOG_ERR, "child %s requested, but was not declared", pat->childnm);
86             simpleerror(fd, 500, "Configuration Error", "The server is erroneously configured. Handler %s was requested, but not declared.", pat->childnm);
87             return;
88         }
89         if((twd = ccf?ccf->path:NULL) != NULL) {
90             if(!strcmp(twd, ".")) {
91                 twd = NULL;
92             } else if(strncmp(path, twd, strlen(twd)) || (path[strlen(twd)] != '/')) {
93                 /* Should be an impossible case under the current (and
94                  * foreseeable) scheme. */
95                 simpleerror(fd, 500, "Server Error", "An internal server error occurred.");
96                 return;
97             } else {
98                 path = path + strlen(twd) + 1;
99             }
100         }
101         headappheader(req, "X-Ash-File", path);
102         if(childhandle(ch, req, fd, chinit, twd))
103             childerror(req, fd);
104     }
105 }
106
107 static void handle404(struct hthead *req, int fd, char *path)
108 {
109     struct child *ch;
110     struct config *ccf;
111     struct pattern *pat;
112     
113     char tmp[strlen(path) + 1];
114     strcpy(tmp, path);
115     if((pat = findmatch(tmp, 0, PT_NOTFOUND)) != NULL) {
116         handle(req, fd, tmp, pat);
117     } else {
118         ch = findchild(tmp, ".notfound", &ccf);
119         if(childhandle(ch, req, fd, chinit, ccf?ccf->path:NULL))
120             childerror(req, fd);
121     }
122 }
123
124 static void handlefile(struct hthead *req, int fd, char *path)
125 {
126     struct pattern *pat;
127
128     if((pat = findmatch(path, 0, PT_FILE)) == NULL) {
129         handle404(req, fd, path);
130         return;
131     }
132     handle(req, fd, path, pat);
133 }
134
135 static int checkaccess(char *path, char *name)
136 {
137     int i, o;
138     struct config **cfs;
139     
140     if(*name == '.') {
141         cfs = getconfigs(sprintf3("%s/", path));
142         for(i = 0; cfs[i] != NULL; i++) {
143             if(cfs[i]->dotallow != NULL) {
144                 for(o = 0; cfs[i]->dotallow[o] != NULL; o++) {
145                     if(!fnmatch(cfs[i]->dotallow[o], name, 0))
146                         return(1);
147                 }
148                 break;
149             }
150         }
151         return(0);
152     }
153     return(1);
154 }
155
156 static char *findfile(char *path, char *name, struct stat *sb)
157 {
158     DIR *dir;
159     struct stat sbuf;
160     struct dirent *dent;
161     char *p, *fp, *ret;
162     
163     if(sb == NULL)
164         sb = &sbuf;
165     if((dir = opendir(path)) == NULL)
166         return(NULL);
167     ret = NULL;
168     while((dent = readdir(dir)) != NULL) {
169         /* Ignore backup files.
170          * XXX: There is probably a better and more extensible way to
171          * do this. */
172         if(dent->d_name[strlen(dent->d_name) - 1] == '~')
173             continue;
174         if((p = strchr(dent->d_name, '.')) == NULL)
175             continue;
176         if(p - dent->d_name != strlen(name))
177             continue;
178         if(strncmp(dent->d_name, name, strlen(name)))
179             continue;
180         fp = sprintf2("%s/%s", path, dent->d_name);
181         if(stat(fp, sb)) {
182             free(fp);
183             continue;
184         }
185         if(!S_ISREG(sb->st_mode)) {
186             free(fp);
187             continue;
188         }
189         if(!checkaccess(path, dent->d_name)) {
190             free(fp);
191             continue;
192         }
193         ret = fp;
194         break;
195     }
196     closedir(dir);
197     return(ret);
198 }
199
200 static void handledir(struct hthead *req, int fd, char *path)
201 {
202     struct config **cfs;
203     int i, o;
204     struct stat sb;
205     char *inm, *ipath, *cpath;
206     struct pattern *pat;
207     
208     cpath = sprintf2("%s/", path);
209     cfs = getconfigs(cpath);
210     for(i = 0; cfs[i] != NULL; i++) {
211         if(cfs[i]->index != NULL) {
212             for(o = 0; cfs[i]->index[o] != NULL; o++) {
213                 inm = cfs[i]->index[o];
214                 ipath = sprintf2("%s/%s", path, inm);
215                 if(!stat(ipath, &sb) && S_ISREG(sb.st_mode)) {
216                     handlefile(req, fd, ipath);
217                     free(ipath);
218                     goto out;
219                 }
220                 free(ipath);
221                 
222                 if(!strchr(inm, '.') && ((ipath = findfile(path, inm, NULL)) != NULL)) {
223                     handlefile(req, fd, ipath);
224                     free(ipath);
225                     goto out;
226                 }
227             }
228             break;
229         }
230     }
231     if((pat = findmatch(cpath, 0, PT_DIR)) != NULL) {
232         handle(req, fd, cpath, pat);
233         goto out;
234     }
235     simpleerror(fd, 403, "Not Authorized", "Will not send listings for this directory.");
236     
237 out:
238     free(cpath);
239 }
240
241 static int checkpath(struct hthead *req, int fd, char *path, char *rest, int final);
242
243 static int checkentry(struct hthead *req, int fd, char *path, char *rest, char *el, int final)
244 {
245     struct stat sb;
246     char *newpath;
247     int rv;
248     
249     if(!stat(sprintf3("%s/%s", path, el), &sb)) {
250         if(!checkaccess(path, el))
251             return(0);
252         if(S_ISDIR(sb.st_mode)) {
253             if(!*rest) {
254                 stdredir(req, fd, 301, sprintf3("%s/", el));
255                 return(1);
256             }
257             newpath = sprintf2("%s/%s", path, el);
258             rv = checkpath(req, fd, newpath, rest + 1, final);
259             free(newpath);
260             return(rv);
261         } else if(S_ISREG(sb.st_mode)) {
262             newpath = sprintf2("%s/%s", path, el);
263             replrest(req, rest);
264             handlefile(req, fd, newpath);
265             free(newpath);
266             return(1);
267         }
268         handle404(req, fd, sprintf3("%s/", path));
269         return(1);
270     }
271     if(!strchr(el, '.') && ((newpath = findfile(path, el, NULL)) != NULL)) {
272         replrest(req, rest);
273         handlefile(req, fd, newpath);
274         free(newpath);
275         return(1);
276     }
277     return(0);
278 }
279
280 static int checkdir(struct hthead *req, int fd, char *path, char *rest)
281 {
282     char *cpath, *newpath;
283     struct config *cf, *ccf;
284     struct child *ch;
285     struct stat sb;
286     int rv;
287     
288     cf = getconfig(path);
289     if((cf->capture != NULL) && (cf->caproot || !cf->path || strcmp(cf->path, "."))) {
290         cpath = sprintf2("%s/", path);
291         if((ch = findchild(cpath, cf->capture, &ccf)) == NULL) {
292             free(cpath);
293             flog(LOG_ERR, "child %s requested for capture, but was not declared", cf->capture);
294             simpleerror(fd, 500, "Configuration Error", "The server is erroneously configured. Handler %s was requested, but not declared.", cf->capture);
295             return(1);
296         }
297         free(cpath);
298         if(*rest == '/')
299             rest++;
300         replrest(req, rest);
301         if(childhandle(ch, req, fd, chinit, ccf?ccf->path:NULL))
302             childerror(req, fd);
303         return(1);
304     }
305     if(cf->reparse != NULL) {
306         newpath = (cf->reparse[0] == '/')?sstrdup(cf->reparse):sprintf2("%s/%s", path, cf->reparse);
307         rv = stat(newpath, &sb);
308         if(!rv && S_ISDIR(sb.st_mode)) {
309             rv = checkpath(req, fd, newpath, rest, !cf->parsecomb);
310         } else if(!rv && S_ISREG(sb.st_mode)) {
311             replrest(req, rest);
312             handlefile(req, fd, newpath);
313             rv = 1;
314         } else {
315             rv = !cf->parsecomb;
316         }
317         free(newpath);
318         if(rv)
319             return(rv);
320     }
321     return(0);
322 }
323
324 static int checkpath(struct hthead *req, int fd, char *path, char *rest, int final)
325 {
326     char *p, *el;
327     int rv;
328     
329     el = NULL;
330     rv = 0;
331     
332     if(!strncmp(path, "./", 2))
333         path += 2;
334     if(checkdir(req, fd, path, rest))
335         return(1);
336     
337     if((p = strchr(rest, '/')) == NULL) {
338         el = unquoteurl(rest);
339         rest = "";
340     } else {
341         char buf[p - rest + 1];
342         memcpy(buf, rest, p - rest);
343         buf[p - rest] = 0;
344         el = unquoteurl(buf);
345         rest = p;
346     }
347     if(el == NULL) {
348         simpleerror(fd, 400, "Bad Request", "The requested URL contains an invalid escape sequence.");
349         rv = 1;
350         goto out;
351     }
352     if(strchr(el, '/') || (!*el && *rest)) {
353         rv = 0;
354         goto out;
355     }
356     if(!*el) {
357         replrest(req, rest);
358         handledir(req, fd, path);
359         rv = 1;
360         goto out;
361     }
362     rv = checkentry(req, fd, path, rest, el, final);
363     
364 out:
365     if(final && !rv) {
366         handle404(req, fd, sprintf3("%s/", path));
367         rv = 1;
368     }
369     if(el != NULL)
370         free(el);
371     return(rv);
372 }
373
374 static void serve(struct hthead *req, int fd)
375 {
376     now = time(NULL);
377     checkpath(req, fd, ".", req->rest, 1);
378 }
379
380 static void chldhandler(int sig)
381 {
382     pid_t pid;
383     int st;
384     
385     while((pid = waitpid(-1, &st, WNOHANG)) > 0) {
386         if(WCOREDUMP(st))
387             flog(LOG_WARNING, "child process %i dumped core", pid);
388     }
389 }
390
391 static void sighandler(int sig)
392 {
393 }
394
395 static void usage(FILE *out)
396 {
397     fprintf(out, "usage: dirplex [-hN] [-c CONFIG] DIR\n");
398 }
399
400 int main(int argc, char **argv)
401 {
402     int c;
403     int nodef;
404     char *gcf, *lcf, *clcf;
405     struct hthead *req;
406     int fd;
407     
408     nodef = 0;
409     lcf = NULL;
410     while((c = getopt(argc, argv, "hNc:")) >= 0) {
411         switch(c) {
412         case 'h':
413             usage(stdout);
414             exit(0);
415         case 'N':
416             nodef = 1;
417             break;
418         case 'c':
419             lcf = optarg;
420             break;
421         default:
422             usage(stderr);
423             exit(1);
424         }
425     }
426     if(argc - optind < 1) {
427         usage(stderr);
428         exit(1);
429     }
430     if(!nodef) {
431         if((gcf = findstdconf("ashd/dirplex.rc")) != NULL) {
432             gconfig = readconfig(gcf);
433             free(gcf);
434         }
435     }
436     if(lcf != NULL) {
437         if(strchr(lcf, '/') == NULL) {
438             if((clcf = findstdconf(sprintf3("ashd/%s", lcf))) == NULL) {
439                 flog(LOG_ERR, "could not find requested configuration `%s'", lcf);
440                 exit(1);
441             }
442             if((lconfig = readconfig(clcf)) == NULL)
443                 exit(1);
444             free(clcf);
445         } else {
446             if((lconfig = readconfig(lcf)) == NULL)
447                 exit(1);
448         }
449     }
450     if(chdir(argv[optind])) {
451         flog(LOG_ERR, "could not change directory to %s: %s", argv[optind], strerror(errno));
452         exit(1);
453     }
454     signal(SIGCHLD, chldhandler);
455     signal(SIGPIPE, sighandler);
456     while(1) {
457         if((fd = recvreq(0, &req)) < 0) {
458             if(errno != 0)
459                 flog(LOG_ERR, "recvreq: %s", strerror(errno));
460             break;
461         }
462         serve(req, fd);
463         freehthead(req);
464         close(fd);
465     }
466     return(0);
467 }