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