Added an error message for crashing request handlers 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         simpleerror(fd, 500, "Server Error", "The request handler crashed.");
445     }
446 }
447
448 static void handlefile(struct hthead *req, int fd, char *path)
449 {
450     struct pattern *pat;
451     struct child *ch;
452
453     headappheader(req, "X-Ash-File", path);
454     if(((pat = findmatch(path, 0)) == NULL) && ((pat = findmatch(path, 1)) == NULL)) {
455         /* XXX: Send a 500 error? 404? */
456         return;
457     }
458     if((ch = findchild(path, pat->childnm)) == NULL) {
459         flog(LOG_ERR, "child %s requested, but was not declared", pat->childnm);
460         simpleerror(fd, 500, "Configuration Error", "The server is erroneously configured. Handler %s was requested, but not declared.", pat->childnm);
461         return;
462     }
463     
464     if(ch->type == CH_SOCKET) {
465         passreq(ch, req, fd);
466     } else if(ch->type == CH_FORK) {
467         stdforkserve(ch->argv, req, fd);
468     }
469 }
470
471 static void handledir(struct hthead *req, int fd, char *path)
472 {
473     /* XXX: Todo */
474     simpleerror(fd, 403, "Not Authorized", "Will not send directory listings or indices yet");
475 }
476
477 static int checkdir(struct hthead *req, int fd, char *path)
478 {
479     return(0);
480 }
481
482 static void serve(struct hthead *req, int fd)
483 {
484     char *p, *p2, *path, *tmp, *buf, *p3, *nm;
485     struct stat sb;
486     DIR *dir;
487     struct dirent *dent;
488     
489     nm = req->rest;
490     path = sstrdup(".");
491     p = nm;
492     while(1) {
493         if((p2 = strchr(p, '/')) == NULL) {
494         } else {
495             *(p2++) = 0;
496         }
497         
498         if(!*p) {
499             if(p2 == NULL) {
500                 if(stat(path, &sb)) {
501                     flog(LOG_WARNING, "failed to stat previously stated directory %s: %s", path, strerror(errno));
502                     simpleerror(fd, 500, "Internal Server Error", "The server encountered an unexpected condition.");
503                     goto fail;
504                 }
505                 break;
506             } else {
507                 simpleerror(fd, 404, "Not Found", "The requested URL has no corresponding resource.");
508                 goto fail;
509             }
510         }
511         if(*p == '.') {
512             simpleerror(fd, 404, "Not Found", "The requested URL has no corresponding resource.");
513             goto fail;
514         }
515         
516         getconfig(path);
517         
518         /*
519          * First, check the name verbatimely:
520          */
521         buf = sprintf3("%s/%s", path, p);
522         if(!stat(buf, &sb)) {
523             if(S_ISDIR(sb.st_mode)) {
524                 tmp = path;
525                 if(!strcmp(path, "."))
526                     path = sstrdup(p);
527                 else
528                     path = sprintf2("%s/%s", path, p);
529                 free(tmp);
530                 if(checkdir(req, fd, path))
531                     break;
532                 goto next;
533             }
534             if(S_ISREG(sb.st_mode)) {
535                 tmp = path;
536                 path = sprintf2("%s/%s", path, p);
537                 free(tmp);
538                 break;
539             }
540             simpleerror(fd, 404, "Not Found", "The requested URL has no corresponding resource.");
541             goto fail;
542         }
543
544         /*
545          * Check the file extensionlessly:
546          */
547         if(!strchr(p, '.') && ((dir = opendir(path)) != NULL)) {
548             while((dent = readdir(dir)) != NULL) {
549                 buf = sprintf3("%s/%s", path, dent->d_name);
550                 if((p3 = strchr(dent->d_name, '.')) != NULL)
551                     *p3 = 0;
552                 if(strcmp(dent->d_name, p))
553                     continue;
554                 if(stat(buf, &sb))
555                     continue;
556                 if(!S_ISREG(sb.st_mode))
557                     continue;
558                 tmp = path;
559                 path = sstrdup(buf);
560                 free(tmp);
561                 break;
562             }
563             closedir(dir);
564             if(dent != NULL)
565                 break;
566         }
567         
568         simpleerror(fd, 404, "Not Found", "The requested URL has no corresponding resource.");
569         goto fail;
570         
571     next:
572         if(p2 == NULL)
573             break;
574         p = p2;
575     }
576     if(p2 == NULL)
577         replrest(req, "");
578     else
579         replrest(req, p2);
580     if(!strncmp(path, "./", 2))
581         memmove(path, path + 2, strlen(path + 2) + 1);
582     if(S_ISDIR(sb.st_mode)) {
583         handledir(req, fd, path);
584     } else if(S_ISREG(sb.st_mode)) {
585         handlefile(req, fd, path);
586     } else {
587         simpleerror(fd, 404, "Not Found", "The requested URL has no corresponding resource.");
588         goto fail;
589     }
590     goto out;
591     
592 fail:
593     /* No special handling, for now at least. */
594 out:
595     free(path);
596 }
597
598 int main(int argc, char **argv)
599 {
600     struct hthead *req;
601     int fd;
602     
603     if(argc < 2) {
604         flog(LOG_ERR, "usage: dirplex DIR");
605         exit(1);
606     }
607     if(chdir(argv[1])) {
608         flog(LOG_ERR, "could not change directory to %s: %s", argv[1], strerror(errno));
609         exit(1);
610     }
611     signal(SIGCHLD, SIG_IGN);
612     while(1) {
613         if((fd = recvreq(0, &req)) < 0) {
614             if(errno != 0)
615                 flog(LOG_ERR, "recvreq: %s", strerror(errno));
616             break;
617         }
618         serve(req, fd);
619         freehthead(req);
620         close(fd);
621     }
622     return(0);
623 }