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