Send error reports from 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] = smalloc(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     if(stat(path, &sb))
185         return(NULL);
186     if((s = fopen(sprintf3("%s/.htrc", path), "r")) == NULL)
187         return(NULL);
188     omalloc(cf);
189     cf->mtime = sb.st_mtime;
190     cf->path = sstrdup(path);
191     eof = 0;
192     state = 0;
193     w = NULL;
194     lno = 0;
195     do {
196         if(fgets(line, sizeof(line), s) == NULL) {
197             eof = 1;
198             line[0] = 0;
199         }
200         lno++;
201         for(p = line; *p; p++) {
202             if(*p == '#')
203                 continue;
204             if(!isspace(*p))
205                 break;
206         }
207         ind = isspace(line[0]);
208         w = tokenize(line);
209         argc = calen(w);
210         
211     retry:
212         if(state == 0) {
213             if(ind) {
214                 flog(LOG_WARNING, "%s%i: unexpected line indentation in global scope", path, lno);
215                 goto next;
216             } else {
217                 if(!w[0]) {
218                 } else if(!strcmp(w[0], "child")) {
219                     if(argc < 2) {
220                         flog(LOG_WARNING, "%s:%i: missing name in child declaration", path, lno);
221                         goto next;
222                     }
223                     child = newchild(w[1], CH_SOCKET);
224                     state = 1;
225                 } else if(!strcmp(w[0], "fchild")) {
226                     if(argc < 2) {
227                         flog(LOG_WARNING, "%s:%i: missing name in child declaration", path, lno);
228                         goto next;
229                     }
230                     child = newchild(w[1], CH_FORK);
231                     state = 1;
232                 } else if(!strcmp(w[0], "match")) {
233                     pat = newpattern();
234                     state = 2;
235                 } else {
236                     flog(LOG_WARNING, "%s:%i: unknown directive %s", path, lno, w[0]);
237                 }
238             }
239         } else if(state == 1) {
240             if(ind) {
241                 if(!w[0]) {
242                 } else if(!strcmp(w[0], "exec")) {
243                     if(argc < 2) {
244                         flog(LOG_WARNING, "%s:%i: too few parameters to `exec'", path, lno);
245                         goto next;
246                     }
247                     child->argv = szmalloc(sizeof(*child->argv) * argc);
248                     for(i = 0; i < argc - 1; i++)
249                         child->argv[i] = sstrdup(w[i + 1]);
250                 } else {
251                     flog(LOG_WARNING, "%s:%i: unknown directive %s", path, lno, w[0]);
252                 }
253             } else {
254                 state = 0;
255                 if(child->argv == NULL) {
256                     flog(LOG_WARNING, "%s:%i: missing `exec' in child declaration %s", path, lno, child->name);
257                     freechild(child);
258                     goto retry;
259                 }
260                 child->next = cf->children;
261                 cf->children = child;
262                 goto retry;
263             }
264         } else if(state == 2) {
265             if(ind) {
266                 if(!w[0]) {
267                 } else if(!strcmp(w[0], "filename")) {
268                     if(argc < 2) {
269                         flog(LOG_WARNING, "%s:%i: missing pattern for `filename' match", path, lno);
270                         goto next;
271                     }
272                     rule = newrule(pat);
273                     rule->type = PAT_BASENAME;
274                     rule->pattern = sstrdup(w[1]);
275                 } else if(!strcmp(w[0], "pathname")) {
276                     if(argc < 2) {
277                         flog(LOG_WARNING, "%s:%i: missing pattern for `pathname' match", path, lno);
278                         goto next;
279                     }
280                     rule = newrule(pat);
281                     rule->type = PAT_PATHNAME;
282                     rule->pattern = sstrdup(w[1]);
283                 } else if(!strcmp(w[0], "all")) {
284                     newrule(pat)->type = PAT_ALL;
285                 } else if(!strcmp(w[0], "default")) {
286                     newrule(pat)->type = PAT_DEFAULT;
287                 } else if(!strcmp(w[0], "handler")) {
288                     if(argc < 2) {
289                         flog(LOG_WARNING, "%s:%i: missing child name for `handler' directive", path, lno);
290                         goto next;
291                     }
292                     if(pat->childnm != NULL)
293                         free(pat->childnm);
294                     pat->childnm = sstrdup(w[1]);
295                 } else {
296                     flog(LOG_WARNING, "%s:%i: unknown directive %s", path, lno, w[0]);
297                 }
298             } else {
299                 state = 0;
300                 if(pat->rules[0] == NULL) {
301                     flog(LOG_WARNING, "%s:%i: missing rules in match declaration", path, lno);
302                     freepattern(pat);
303                     goto retry;
304                 }
305                 if(pat->childnm == NULL) {
306                     flog(LOG_WARNING, "%s:%i: missing handler in match declaration", path, lno);
307                     freepattern(pat);
308                     goto retry;
309                 }
310                 pat->next = cf->patterns;
311                 cf->patterns = pat;
312                 goto retry;
313             }
314         }
315         
316     next:
317         freeca(w);
318         w = NULL;
319     } while(!eof);
320     rv = 0;
321     
322     if(w != NULL)
323         freeca(w);
324     fclose(s);
325     return(cf);
326 }
327
328 static struct config *getconfig(char *path)
329 {
330     struct config *cf;
331     struct stat sb;
332     
333     for(cf = cflist; cf != NULL; cf = cf->next) {
334         if(!strcmp(cf->path, path)) {
335             if(stat(path, &sb))
336                 return(NULL);
337             if(sb.st_mtime != cf->mtime) {
338                 freeconfig(cf);
339                 break;
340             }
341             return(cf);
342         }
343     }
344     if((cf = readconfig(path)) != NULL) {
345         cf->next = cflist;
346         cflist = cf;
347     }
348     return(cf);
349 }
350
351 static struct child *findchild(char *file, char *name)
352 {
353     char *buf, *p;
354     struct config *cf;
355     struct child *ch;
356
357     buf = sstrdup(file);
358     while(1) {
359         ch = NULL;
360         if(!strcmp(buf, "."))
361             break;
362         if((p = strrchr(buf, '/')) != NULL)
363             *p = 0;
364         else
365             strcpy(buf, ".");
366         cf = getconfig(buf);
367         if(cf == NULL)
368             continue;
369         if((ch = getchild(cf, name)) != NULL)
370             break;
371     }
372     free(buf);
373     return(ch);
374 }
375
376 static struct pattern *findmatch(char *file, int trydefault)
377 {
378     int i;
379     char *buf, *p, *bn;
380     struct config *cf;
381     struct pattern *pat;
382     struct rule *rule;
383     
384     if((bn = strrchr(file, '/')) != NULL)
385         bn++;
386     else
387         bn = file;
388     buf = sstrdup(file);
389     while(1) {
390         pat = NULL;
391         if(!strcmp(buf, "."))
392             break;
393         if((p = strrchr(buf, '/')) != NULL)
394             *p = 0;
395         else
396             strcpy(buf, ".");
397         cf = getconfig(buf);
398         if(cf == NULL)
399             continue;
400         for(pat = cf->patterns; pat != NULL; pat = pat->next) {
401             for(i = 0; (rule = pat->rules[i]) != NULL; i++) {
402                 if(rule->type == PAT_BASENAME) {
403                     if(fnmatch(rule->pattern, bn, 0))
404                         break;
405                 } else if(rule->type == PAT_PATHNAME) {
406                     if(fnmatch(rule->pattern, file, FNM_PATHNAME))
407                         break;
408                 } else if(rule->type == PAT_ALL) {
409                 } else if(rule->type == PAT_DEFAULT) {
410                     if(!trydefault)
411                         break;
412                 }
413             }
414             if(!rule)
415                 goto out;
416         }
417     }
418
419 out:
420     free(buf);
421     return(pat);
422 }
423
424 static void forkchild(struct child *ch)
425 {
426     ch->fd = stdmkchild(ch->argv);
427 }
428
429 static void passreq(struct child *ch, struct hthead *req, int fd)
430 {
431     if(ch->fd < 0)
432         forkchild(ch);
433     if(sendreq(ch->fd, req, fd)) {
434         if(errno == EPIPE) {
435             /* Assume that the child has crashed and restart it. */
436             forkchild(ch);
437             if(!sendreq(ch->fd, req, fd))
438                 return;
439         }
440         flog(LOG_ERR, "could not pass on request to child %s: %s", ch->name, strerror(errno));
441         close(ch->fd);
442         ch->fd = -1;
443     }
444 }
445
446 static void handlefile(struct hthead *req, int fd, char *path)
447 {
448     struct pattern *pat;
449     struct child *ch;
450
451     headappheader(req, "X-Ash-File", path);
452     if(((pat = findmatch(path, 0)) == NULL) && ((pat = findmatch(path, 1)) == NULL)) {
453         /* XXX: Send a 500 error? 404? */
454         return;
455     }
456     if((ch = findchild(path, pat->childnm)) == NULL) {
457         flog(LOG_ERR, "child %s requested, but was not declared", pat->childnm);
458         simpleerror(fd, 500, "Configuration Error", "The server is erroneously configured. Handler %s was requested, but not declared.", pat->childnm);
459         return;
460     }
461     
462     if(ch->type == CH_SOCKET) {
463         passreq(ch, req, fd);
464     } else if(ch->type == CH_FORK) {
465         stdforkserve(ch->argv, req, fd);
466     }
467 }
468
469 static void handledir(struct hthead *req, int fd, char *path)
470 {
471     /* XXX: Todo */
472     simpleerror(fd, 403, "Not Authorized", "Will not send directory listings or indices yet");
473 }
474
475 static int checkdir(struct hthead *req, int fd, char *path)
476 {
477     return(0);
478 }
479
480 static void serve(struct hthead *req, int fd)
481 {
482     char *p, *p2, *path, *tmp, *buf, *p3, *nm;
483     struct stat sb;
484     DIR *dir;
485     struct dirent *dent;
486     
487     nm = req->rest;
488     path = sstrdup(".");
489     p = nm;
490     while(1) {
491         if((p2 = strchr(p, '/')) == NULL) {
492         } else {
493             *(p2++) = 0;
494         }
495         
496         if(!*p) {
497             if(p2 == NULL) {
498                 if(stat(path, &sb)) {
499                     flog(LOG_WARNING, "failed to stat previously stated directory %s: %s", path, strerror(errno));
500                     simpleerror(fd, 500, "Internal Server Error", "The server encountered an unexpected condition.");
501                     goto fail;
502                 }
503                 break;
504             } else {
505                 simpleerror(fd, 404, "Not Found", "The requested URL has no corresponding resource.");
506                 goto fail;
507             }
508         }
509         if(*p == '.') {
510             simpleerror(fd, 404, "Not Found", "The requested URL has no corresponding resource.");
511             goto fail;
512         }
513         
514         getconfig(path);
515         
516         /*
517          * First, check the name verbatimely:
518          */
519         buf = sprintf3("%s/%s", path, p);
520         if(!stat(buf, &sb)) {
521             if(S_ISDIR(sb.st_mode)) {
522                 tmp = path;
523                 if(!strcmp(path, "."))
524                     path = sstrdup(p);
525                 else
526                     path = sprintf2("%s/%s", path, p);
527                 free(tmp);
528                 if(checkdir(req, fd, path))
529                     break;
530                 goto next;
531             }
532             if(S_ISREG(sb.st_mode)) {
533                 tmp = path;
534                 path = sprintf2("%s/%s", path, p);
535                 free(tmp);
536                 break;
537             }
538             simpleerror(fd, 404, "Not Found", "The requested URL has no corresponding resource.");
539             goto fail;
540         }
541
542         /*
543          * Check the file extensionlessly:
544          */
545         if(!strchr(p, '.') && ((dir = opendir(path)) != NULL)) {
546             while((dent = readdir(dir)) != NULL) {
547                 buf = sprintf3("%s/%s", path, dent->d_name);
548                 if((p3 = strchr(dent->d_name, '.')) != NULL)
549                     *p3 = 0;
550                 if(strcmp(dent->d_name, p))
551                     continue;
552                 if(stat(buf, &sb))
553                     continue;
554                 if(!S_ISREG(sb.st_mode))
555                     continue;
556                 tmp = path;
557                 path = sstrdup(buf);
558                 free(tmp);
559                 break;
560             }
561             closedir(dir);
562             if(dent != NULL)
563                 break;
564         }
565         
566         simpleerror(fd, 404, "Not Found", "The requested URL has no corresponding resource.");
567         goto fail;
568         
569     next:
570         if(p2 == NULL)
571             break;
572         p = p2;
573     }
574     if(p2 == NULL)
575         replrest(req, "");
576     else
577         replrest(req, p2);
578     if(!strncmp(path, "./", 2))
579         memmove(path, path + 2, strlen(path + 2) + 1);
580     if(S_ISDIR(sb.st_mode)) {
581         handledir(req, fd, path);
582     } else if(S_ISREG(sb.st_mode)) {
583         handlefile(req, fd, path);
584     } else {
585         simpleerror(fd, 404, "Not Found", "The requested URL has no corresponding resource.");
586         goto fail;
587     }
588     goto out;
589     
590 fail:
591     /* No special handling, for now at least. */
592 out:
593     free(path);
594 }
595
596 int main(int argc, char **argv)
597 {
598     struct hthead *req;
599     int fd;
600     
601     if(argc < 2) {
602         flog(LOG_ERR, "usage: dirplex DIR");
603         exit(1);
604     }
605     if(chdir(argv[1])) {
606         flog(LOG_ERR, "could not change directory to %s: %s", argv[1], strerror(errno));
607         exit(1);
608     }
609     signal(SIGCHLD, SIG_IGN);
610     while(1) {
611         if((fd = recvreq(0, &req)) < 0) {
612             if(errno != 0)
613                 flog(LOG_ERR, "recvreq: %s", strerror(errno));
614             break;
615         }
616         serve(req, fd);
617         freehthead(req);
618         close(fd);
619     }
620     return(0);
621 }