Added global config files to dirplex and patplex.
[ashd.git] / src / 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 <fnmatch.h>
28 #include <time.h>
29
30 #ifdef HAVE_CONFIG_H
31 #include <config.h>
32 #endif
33 #include <utils.h>
34 #include <mt.h>
35 #include <log.h>
36 #include <req.h>
37 #include <proc.h>
38 #include <resp.h>
39 #include <cf.h>
40
41 #define PAT_BASENAME 0
42 #define PAT_PATHNAME 1
43 #define PAT_ALL 2
44 #define PAT_DEFAULT 3
45
46 struct config {
47     struct config *next, *prev;
48     char *path;
49     time_t mtime, lastck;
50     struct child *children;
51     struct pattern *patterns;
52 };
53
54 struct rule {
55     int type;
56     char *pattern;
57 };
58
59 struct pattern {
60     struct pattern *next;
61     char *childnm;
62     struct rule **rules;
63 };
64
65 static struct config *cflist;
66 static struct config *gconfig, *lconfig;
67 static time_t now;
68
69 static void freepattern(struct pattern *pat)
70 {
71     struct rule **rule;
72     
73     for(rule = pat->rules; *rule; rule++) {
74         if((*rule)->pattern != NULL)
75             free((*rule)->pattern);
76         free(*rule);
77     }
78     if(pat->childnm != NULL)
79         free(pat->childnm);
80     free(pat);
81 }
82
83 static void freeconfig(struct config *cf)
84 {
85     struct child *ch, *nch;
86     struct pattern *pat, *npat;
87     
88     if(cf->prev != NULL)
89         cf->prev->next = cf->next;
90     if(cf->next != NULL)
91         cf->next->prev = cf->prev;
92     if(cf == cflist)
93         cflist = cf->next;
94     if(cf->path != NULL)
95         free(cf->path);
96     for(ch = cf->children; ch != NULL; ch = nch) {
97         nch = ch->next;
98         freechild(ch);
99     }
100     for(pat = cf->patterns; pat != NULL; pat = npat) {
101         npat = pat->next;
102         freepattern(pat);
103     }
104     free(cf);
105 }
106
107 static struct child *getchild(struct config *cf, char *name)
108 {
109     struct child *ch;
110     
111     for(ch = cf->children; ch; ch = ch->next) {
112         if(!strcmp(ch->name, name))
113             break;
114     }
115     return(ch);
116 }
117
118 static struct rule *newrule(struct pattern *pat)
119 {
120     int i;
121     struct rule *rule;
122     
123     for(i = 0; pat->rules[i]; i++);
124     pat->rules = srealloc(pat->rules, sizeof(*pat->rules) * (i + 2));
125     rule = pat->rules[i] = szmalloc(sizeof(*rule));
126     pat->rules[i + 1] = NULL;
127     return(rule);
128 }
129
130 static struct pattern *newpattern(void)
131 {
132     struct pattern *pat;
133     
134     omalloc(pat);
135     pat->rules = szmalloc(sizeof(*pat->rules));
136     return(pat);
137 }
138
139 static struct pattern *parsepattern(struct cfstate *s)
140 {
141     struct pattern *pat;
142     struct rule *rule;
143     int sl;
144
145     if(!strcmp(s->argv[0], "match")) {
146         s->expstart = 1;
147         pat = newpattern();
148     } else {
149         return(NULL);
150     }
151     
152     sl = s->lno;
153     while(1) {
154         getcfline(s);
155         if(!strcmp(s->argv[0], "filename")) {
156             if(s->argc < 2) {
157                 flog(LOG_WARNING, "%s:%i: missing pattern for `filename' match", s->file, s->lno);
158                 continue;
159             }
160             rule = newrule(pat);
161             rule->type = PAT_BASENAME;
162             rule->pattern = sstrdup(s->argv[1]);
163         } else if(!strcmp(s->argv[0], "pathname")) {
164             if(s->argc < 2) {
165                 flog(LOG_WARNING, "%s:%i: missing pattern for `pathname' match", s->file, s->lno);
166                 continue;
167             }
168             rule = newrule(pat);
169             rule->type = PAT_PATHNAME;
170             rule->pattern = sstrdup(s->argv[1]);
171         } else if(!strcmp(s->argv[0], "all")) {
172             newrule(pat)->type = PAT_ALL;
173         } else if(!strcmp(s->argv[0], "default")) {
174             newrule(pat)->type = PAT_DEFAULT;
175         } else if(!strcmp(s->argv[0], "handler")) {
176             if(s->argc < 2) {
177                 flog(LOG_WARNING, "%s:%i: missing child name for `handler' directive", s->file, s->lno);
178                 continue;
179             }
180             if(pat->childnm != NULL)
181                 free(pat->childnm);
182             pat->childnm = sstrdup(s->argv[1]);
183         } else if(!strcmp(s->argv[0], "end") || !strcmp(s->argv[0], "eof")) {
184             break;
185         } else {
186             flog(LOG_WARNING, "%s:%i: unknown directive `%s' in pattern declaration", s->file, s->lno, s->argv[0]);
187         }
188     }
189     
190     if(pat->rules[0] == NULL) {
191         flog(LOG_WARNING, "%s:%i: missing rules in match declaration", s->file, sl);
192         freepattern(pat);
193         return(NULL);
194     }
195     if(pat->childnm == NULL) {
196         flog(LOG_WARNING, "%s:%i: missing handler in match declaration", s->file, sl);
197         freepattern(pat);
198         return(NULL);
199     }
200     return(pat);
201 }
202
203 static struct config *emptyconfig(void)
204 {
205     struct config *cf;
206     
207     omalloc(cf);
208     return(cf);
209 }
210
211 static struct config *readconfig(char *file)
212 {
213     struct cfstate *s;
214     FILE *in;
215     struct config *cf;
216     struct child *child;
217     struct pattern *pat;
218     
219     if((in = fopen(file, "r")) == NULL) {
220         flog(LOG_WARNING, "%s: %s", file, strerror(errno));
221         return(NULL);
222     }
223     s = mkcfparser(in, file);
224     cf = emptyconfig();
225     
226     while(1) {
227         getcfline(s);
228         if((child = parsechild(s)) != NULL) {
229             child->next = cf->children;
230             cf->children = child;
231         } else if((pat = parsepattern(s)) != NULL) {
232             pat->next = cf->patterns;
233             cf->patterns = pat;
234         } else if(!strcmp(s->argv[0], "eof")) {
235             break;
236         } else {
237             flog(LOG_WARNING, "%s:%i: unknown directive `%s'", s->file, s->lno, s->argv[0]);
238         }
239     }
240     
241     freecfparser(s);
242     fclose(in);
243     return(cf);
244 }
245
246 static struct config *getconfig(char *path)
247 {
248     struct config *cf;
249     struct stat sb;
250     char *fn;
251     time_t mtime;
252     
253     fn = sprintf3("%s/.htrc", path);
254     for(cf = cflist; cf != NULL; cf = cf->next) {
255         if(!strcmp(cf->path, path)) {
256             if(now - cf->lastck > 5) {
257                 if(stat(fn, &sb) || (sb.st_mtime != cf->mtime)) {
258                     freeconfig(cf);
259                     break;
260                 }
261             }
262             cf->lastck = now;
263             return(cf);
264         }
265     }
266     if(access(fn, R_OK) || stat(fn, &sb)) {
267         cf = emptyconfig();
268         mtime = 0;
269     } else {
270         if((cf = readconfig(fn)) == NULL)
271             return(NULL);
272         mtime = sb.st_mtime;
273     }
274     cf->path = sstrdup(path);
275     cf->mtime = mtime;
276     cf->lastck = now;
277     cf->next = cflist;
278     cflist = cf;
279     return(cf);
280 }
281
282 static struct config **getconfigs(char *file)
283 {
284     static struct config **ret = NULL;
285     struct {
286         struct config **b;
287         size_t s, d;
288     } buf;
289     struct config *cf;
290     char *tmp, *p;
291     
292     if(ret != NULL)
293         free(ret);
294     bufinit(buf);
295     tmp = sstrdup(file);
296     while(1) {
297         if((p = strrchr(tmp, '/')) == NULL)
298             break;
299         *p = 0;
300         if((cf = getconfig(tmp)) != NULL)
301             bufadd(buf, cf);
302     }
303     free(tmp);
304     if((cf = getconfig(".")) != NULL)
305         bufadd(buf, cf);
306     if(lconfig != NULL)
307         bufadd(buf, lconfig);
308     if(gconfig != NULL)
309         bufadd(buf, gconfig);
310     bufadd(buf, NULL);
311     return(ret = buf.b);
312 }
313
314 static struct child *findchild(char *file, char *name)
315 {
316     int i;
317     struct config **cfs;
318     struct child *ch;
319     
320     cfs = getconfigs(file);
321     for(i = 0; cfs[i] != NULL; i++) {
322         if((ch = getchild(cfs[i], name)) != NULL)
323             break;
324     }
325     return(ch);
326 }
327
328 static struct pattern *findmatch(char *file, int trydefault)
329 {
330     int i, c;
331     char *bn;
332     struct config **cfs;
333     struct pattern *pat;
334     struct rule *rule;
335     
336     if((bn = strrchr(file, '/')) != NULL)
337         bn++;
338     else
339         bn = file;
340     cfs = getconfigs(file);
341     for(c = 0; cfs[c] != NULL; c++) {
342         for(pat = cfs[c]->patterns; pat != NULL; pat = pat->next) {
343             for(i = 0; (rule = pat->rules[i]) != NULL; i++) {
344                 if(rule->type == PAT_BASENAME) {
345                     if(fnmatch(rule->pattern, bn, 0))
346                         break;
347                 } else if(rule->type == PAT_PATHNAME) {
348                     if(fnmatch(rule->pattern, file, FNM_PATHNAME))
349                         break;
350                 } else if(rule->type == PAT_ALL) {
351                 } else if(rule->type == PAT_DEFAULT) {
352                     if(!trydefault)
353                         break;
354                 }
355             }
356             if(!rule)
357                 return(pat);
358         }
359     }
360     return(NULL);
361 }
362
363 static void handlefile(struct hthead *req, int fd, char *path)
364 {
365     struct pattern *pat;
366     struct child *ch;
367
368     headappheader(req, "X-Ash-File", path);
369     if(((pat = findmatch(path, 0)) == NULL) && ((pat = findmatch(path, 1)) == NULL)) {
370         simpleerror(fd, 404, "Not Found", "The requested URL has no corresponding resource.");
371         return;
372     }
373     if((ch = findchild(path, pat->childnm)) == NULL) {
374         flog(LOG_ERR, "child %s requested, but was not declared", pat->childnm);
375         simpleerror(fd, 500, "Configuration Error", "The server is erroneously configured. Handler %s was requested, but not declared.", pat->childnm);
376         return;
377     }
378     
379     if(childhandle(ch, req, fd))
380         simpleerror(fd, 500, "Server Error", "The request handler crashed.");
381 }
382
383 static void handledir(struct hthead *req, int fd, char *path)
384 {
385     /* XXX: Todo */
386     simpleerror(fd, 403, "Not Authorized", "Will not send directory listings or indices yet.");
387 }
388
389 static int checkdir(struct hthead *req, int fd, char *path)
390 {
391     return(0);
392 }
393
394 static void serve(struct hthead *req, int fd)
395 {
396     char *p, *p2, *path, *tmp, *buf, *p3, *nm;
397     struct stat sb;
398     DIR *dir;
399     struct dirent *dent;
400     
401     now = time(NULL);
402     nm = req->rest;
403     path = sstrdup(".");
404     p = nm;
405     while(1) {
406         if((p2 = strchr(p, '/')) == NULL) {
407         } else {
408             *(p2++) = 0;
409         }
410         
411         if(!*p) {
412             if(p2 == NULL) {
413                 if(stat(path, &sb)) {
414                     flog(LOG_WARNING, "failed to stat previously stated directory %s: %s", path, strerror(errno));
415                     simpleerror(fd, 500, "Internal Server Error", "The server encountered an unexpected condition.");
416                     goto fail;
417                 }
418                 break;
419             } else {
420                 simpleerror(fd, 404, "Not Found", "The requested URL has no corresponding resource.");
421                 goto fail;
422             }
423         }
424         if(*p == '.') {
425             simpleerror(fd, 404, "Not Found", "The requested URL has no corresponding resource.");
426             goto fail;
427         }
428         
429         getconfig(path);
430         
431         /*
432          * First, check the name verbatimely:
433          */
434         buf = sprintf3("%s/%s", path, p);
435         if(!stat(buf, &sb)) {
436             if(S_ISDIR(sb.st_mode)) {
437                 tmp = path;
438                 if(!strcmp(path, "."))
439                     path = sstrdup(p);
440                 else
441                     path = sprintf2("%s/%s", path, p);
442                 free(tmp);
443                 if(p2 == NULL) {
444                     stdredir(req, fd, 301, sprintf3("%s/", p));
445                     goto out;
446                 }
447                 if(checkdir(req, fd, path))
448                     break;
449                 goto next;
450             }
451             if(S_ISREG(sb.st_mode)) {
452                 tmp = path;
453                 path = sprintf2("%s/%s", path, p);
454                 free(tmp);
455                 break;
456             }
457             simpleerror(fd, 404, "Not Found", "The requested URL has no corresponding resource.");
458             goto fail;
459         }
460
461         /*
462          * Check the file extensionlessly:
463          */
464         if(!strchr(p, '.') && ((dir = opendir(path)) != NULL)) {
465             while((dent = readdir(dir)) != NULL) {
466                 buf = sprintf3("%s/%s", path, dent->d_name);
467                 if((p3 = strchr(dent->d_name, '.')) != NULL)
468                     *p3 = 0;
469                 if(strcmp(dent->d_name, p))
470                     continue;
471                 if(stat(buf, &sb))
472                     continue;
473                 if(!S_ISREG(sb.st_mode))
474                     continue;
475                 tmp = path;
476                 path = sstrdup(buf);
477                 free(tmp);
478                 break;
479             }
480             closedir(dir);
481             if(dent != NULL)
482                 break;
483         }
484         
485         simpleerror(fd, 404, "Not Found", "The requested URL has no corresponding resource.");
486         goto fail;
487         
488     next:
489         if(p2 == NULL)
490             break;
491         p = p2;
492     }
493     if(p2 == NULL)
494         replrest(req, "");
495     else
496         replrest(req, p2);
497     if(!strncmp(path, "./", 2))
498         memmove(path, path + 2, strlen(path + 2) + 1);
499     if(S_ISDIR(sb.st_mode)) {
500         handledir(req, fd, path);
501     } else if(S_ISREG(sb.st_mode)) {
502         handlefile(req, fd, path);
503     } else {
504         simpleerror(fd, 404, "Not Found", "The requested URL has no corresponding resource.");
505         goto fail;
506     }
507     goto out;
508     
509 fail:
510     /* No special handling, for now at least. */
511 out:
512     free(path);
513 }
514
515 static void usage(FILE *out)
516 {
517     fprintf(out, "usage: dirplex [-hN] [-c CONFIG] DIR\n");
518 }
519
520 int main(int argc, char **argv)
521 {
522     int c;
523     int nodef;
524     char *gcf, *lcf;
525     struct hthead *req;
526     int fd;
527     
528     nodef = 0;
529     lcf = NULL;
530     while((c = getopt(argc, argv, "hNc:")) >= 0) {
531         switch(c) {
532         case 'h':
533             usage(stdout);
534             exit(0);
535         case 'N':
536             nodef = 1;
537             break;
538         case 'c':
539             lcf = optarg;
540             break;
541         default:
542             usage(stderr);
543             exit(1);
544         }
545     }
546     if(argc - optind < 1) {
547         usage(stderr);
548         exit(1);
549     }
550     if(!nodef) {
551         if((gcf = findstdconf("ashd/dirplex.rc")) != NULL) {
552             gconfig = readconfig(gcf);
553             free(gcf);
554         }
555     }
556     if(lcf != NULL) {
557         if((lconfig = readconfig(lcf)) == NULL)
558             exit(1);
559     }
560     if(chdir(argv[optind])) {
561         flog(LOG_ERR, "could not change directory to %s: %s", argv[optind], strerror(errno));
562         exit(1);
563     }
564     signal(SIGCHLD, SIG_IGN);
565     while(1) {
566         if((fd = recvreq(0, &req)) < 0) {
567             if(errno != 0)
568                 flog(LOG_ERR, "recvreq: %s", strerror(errno));
569             break;
570         }
571         serve(req, fd);
572         freehthead(req);
573         close(fd);
574     }
575     return(0);
576 }