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