65f09f715209c948f1fe723560e53501c246b8a2
[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;
253     struct config *cf, *ccf;
254     struct child *ch;
255     
256     cf = getconfig(path);
257     if((cf->capture != NULL) && (cf->caproot || !cf->path || strcmp(cf->path, "."))) {
258         cpath = sprintf2("%s/", path);
259         if((ch = findchild(cpath, cf->capture, &ccf)) == NULL) {
260             free(cpath);
261             flog(LOG_ERR, "child %s requested for capture, but was not declared", cf->capture);
262             simpleerror(fd, 500, "Configuration Error", "The server is erroneously configured. Handler %s was requested, but not declared.", cf->capture);
263             return(1);
264         }
265         free(cpath);
266         if(*rest == '/')
267             rest++;
268         replrest(req, rest);
269         if(childhandle(ch, req, fd, chinit, ccf?ccf->path:NULL))
270             childerror(req, fd);
271         return(1);
272     }
273     return(0);
274 }
275
276 static int checkpath(struct hthead *req, int fd, char *path, char *rest, int final)
277 {
278     char *p, *el;
279     int rv;
280     
281     el = NULL;
282     rv = 0;
283     
284     if(!strncmp(path, "./", 2))
285         path += 2;
286     if(checkdir(req, fd, path, rest))
287         return(1);
288     
289     if((p = strchr(rest, '/')) == NULL) {
290         el = unquoteurl(rest);
291         rest = "";
292     } else {
293         char buf[p - rest + 1];
294         memcpy(buf, rest, p - rest);
295         buf[p - rest] = 0;
296         el = unquoteurl(buf);
297         rest = p;
298     }
299     if(el == NULL) {
300         simpleerror(fd, 400, "Bad Request", "The requested URL contains an invalid escape sequence.");
301         rv = 1;
302         goto out;
303     }
304     if(strchr(el, '/') || (!*el && *rest)) {
305         rv = 0;
306         goto out;
307     }
308     if(!*el) {
309         replrest(req, rest);
310         handledir(req, fd, path);
311         rv = 1;
312         goto out;
313     }
314     rv = checkentry(req, fd, path, rest, el, final);
315     
316 out:
317     if(final && !rv) {
318         handle404(req, fd, sprintf3("%s/", path));
319         rv = 1;
320     }
321     if(el != NULL)
322         free(el);
323     return(rv);
324 }
325
326 static void serve(struct hthead *req, int fd)
327 {
328     now = time(NULL);
329     checkpath(req, fd, ".", req->rest, 1);
330 }
331
332 static void chldhandler(int sig)
333 {
334     pid_t pid;
335     int st;
336     
337     while((pid = waitpid(-1, &st, WNOHANG)) > 0) {
338         if(WCOREDUMP(st))
339             flog(LOG_WARNING, "child process %i dumped core", pid);
340     }
341 }
342
343 static void sighandler(int sig)
344 {
345 }
346
347 static void usage(FILE *out)
348 {
349     fprintf(out, "usage: dirplex [-hN] [-c CONFIG] DIR\n");
350 }
351
352 int main(int argc, char **argv)
353 {
354     int c;
355     int nodef;
356     char *gcf, *lcf, *clcf;
357     struct hthead *req;
358     int fd;
359     
360     nodef = 0;
361     lcf = NULL;
362     while((c = getopt(argc, argv, "hNc:")) >= 0) {
363         switch(c) {
364         case 'h':
365             usage(stdout);
366             exit(0);
367         case 'N':
368             nodef = 1;
369             break;
370         case 'c':
371             lcf = optarg;
372             break;
373         default:
374             usage(stderr);
375             exit(1);
376         }
377     }
378     if(argc - optind < 1) {
379         usage(stderr);
380         exit(1);
381     }
382     if(!nodef) {
383         if((gcf = findstdconf("ashd/dirplex.rc")) != NULL) {
384             gconfig = readconfig(gcf);
385             free(gcf);
386         }
387     }
388     if(lcf != NULL) {
389         if(strchr(lcf, '/') == NULL) {
390             if((clcf = findstdconf(sprintf3("ashd/%s", lcf))) == NULL) {
391                 flog(LOG_ERR, "could not find requested configuration `%s'", lcf);
392                 exit(1);
393             }
394             if((lconfig = readconfig(clcf)) == NULL)
395                 exit(1);
396             free(clcf);
397         } else {
398             if((lconfig = readconfig(lcf)) == NULL)
399                 exit(1);
400         }
401     }
402     if(chdir(argv[optind])) {
403         flog(LOG_ERR, "could not change directory to %s: %s", argv[optind], strerror(errno));
404         exit(1);
405     }
406     signal(SIGCHLD, chldhandler);
407     signal(SIGPIPE, sighandler);
408     while(1) {
409         if((fd = recvreq(0, &req)) < 0) {
410             if(errno != 0)
411                 flog(LOG_ERR, "recvreq: %s", strerror(errno));
412             break;
413         }
414         serve(req, fd);
415         freehthead(req);
416         close(fd);
417     }
418     return(0);
419 }