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