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