a195fab3d81bd885771c06085ba0510b95a23a51
[ashd.git] / src / htparser.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 <unistd.h>
21 #include <stdio.h>
22 #include <fcntl.h>
23 #include <string.h>
24 #include <sys/socket.h>
25 #include <pwd.h>
26 #include <sys/signal.h>
27 #include <errno.h>
28
29 #ifdef HAVE_CONFIG_H
30 #include <config.h>
31 #endif
32 #include <utils.h>
33 #include <mt.h>
34 #include <mtio.h>
35 #include <log.h>
36 #include <req.h>
37 #include <proc.h>
38
39 #include "htparser.h"
40
41 static int plex;
42 static char *pidfile = NULL;
43 static int daemonize, usesyslog;
44
45 static void trimx(struct hthead *req)
46 {
47     int i;
48     
49     i = 0;
50     while(i < req->noheaders) {
51         if(!strncasecmp(req->headers[i][0], "x-ash-", 6)) {
52             free(req->headers[i][0]);
53             free(req->headers[i][1]);
54             free(req->headers[i]);
55             memmove(req->headers + i, req->headers + i + 1, sizeof(*req->headers) * (--req->noheaders - i));
56         } else {
57             i++;
58         }
59     }
60 }
61
62 static struct hthead *parsereq(FILE *in)
63 {
64     struct hthead *req;
65     struct charbuf method, url, ver;
66     int c;
67     
68     req = NULL;
69     bufinit(method);
70     bufinit(url);
71     bufinit(ver);
72     while(1) {
73         c = getc(in);
74         if(c == ' ') {
75             break;
76         } else if((c == EOF) || (c < 32) || (c >= 128)) {
77             goto fail;
78         } else {
79             bufadd(method, c);
80             if(method.d >= 128)
81                 goto fail;
82         }
83     }
84     while(1) {
85         c = getc(in);
86         if(c == ' ') {
87             break;
88         } else if((c == EOF) || (c < 32)) {
89             goto fail;
90         } else {
91             bufadd(url, c);
92             if(url.d >= 65536)
93                 goto fail;
94         }
95     }
96     while(1) {
97         c = getc(in);
98         if(c == 10) {
99             break;
100         } else if(c == 13) {
101         } else if((c == EOF) || (c < 32) || (c >= 128)) {
102             goto fail;
103         } else {
104             bufadd(ver, c);
105             if(ver.d >= 128)
106                 goto fail;
107         }
108     }
109     bufadd(method, 0);
110     bufadd(url, 0);
111     bufadd(ver, 0);
112     req = mkreq(method.b, url.b, ver.b);
113     if(parseheaders(req, in))
114         goto fail;
115     trimx(req);
116     goto out;
117     
118 fail:
119     if(req != NULL) {
120         freehthead(req);
121         req = NULL;
122     }
123 out:
124     buffree(method);
125     buffree(url);
126     buffree(ver);
127     return(req);
128 }
129
130 static off_t passdata(FILE *in, FILE *out, off_t max)
131 {
132     size_t read;
133     off_t total;
134     char buf[8192];
135     
136     total = 0;
137     while(!feof(in) && ((max < 0) || (total < max))) {
138         read = sizeof(buf);
139         if(max >= 0)
140             read = min(max - total, read);
141         read = fread(buf, 1, read, in);
142         if(ferror(in))
143             return(-1);
144         if(fwrite(buf, 1, read, out) != read)
145             return(-1);
146         total += read;
147     }
148     return(total);
149 }
150
151 static int passchunks(FILE *in, FILE *out)
152 {
153     char buf[8192];
154     size_t read;
155     
156     do {
157         read = fread(buf, 1, sizeof(buf), in);
158         if(ferror(in))
159             return(-1);
160         fprintf(out, "%zx\r\n", read);
161         if(fwrite(buf, 1, read, out) != read)
162             return(-1);
163         fprintf(out, "\r\n");
164     } while(read > 0);
165     return(0);
166 }
167
168 static int hasheader(struct hthead *head, char *name, char *val)
169 {
170     char *hd;
171     
172     if((hd = getheader(head, name)) == NULL)
173         return(0);
174     return(!strcasecmp(hd, val));
175 }
176
177 static int canonreq(struct hthead *req)
178 {
179     char *p, *p2, *r;
180     int n;
181
182     if(req->url[0] == '/') {
183         replrest(req, req->url + 1);
184         if((p = strchr(req->rest, '?')) != NULL)
185             *p = 0;
186         return(1);
187     }
188     if((p = strstr(req->url, "://")) != NULL) {
189         n = p - req->url;
190         if(((n == 4) && !strncasecmp(req->url, "http", 4)) ||
191            ((n == 5) && !strncasecmp(req->url, "https", 5))) {
192             if(getheader(req, "host"))
193                 return(0);
194             p += 3;
195             if((p2 = strchr(p, '/')) == NULL) {
196                 headappheader(req, "Host", p);
197                 free(req->url);
198                 req->url = sstrdup("/");
199             } else {
200                 r = sstrdup(p2);
201                 *(p2++) = 0;
202                 headappheader(req, "Host", p);
203                 free(req->url);
204                 req->url = r;
205             }
206             replrest(req, req->url + 1);
207             if((p = strchr(req->rest, '?')) != NULL)
208                 *p = 0;
209             return(1);
210         }
211     }
212     return(0);
213 }
214
215 void serve(FILE *in, struct conn *conn)
216 {
217     int pfds[2];
218     FILE *out;
219     struct hthead *req, *resp;
220     char *hd;
221     off_t dlen;
222     
223     out = NULL;
224     req = resp = NULL;
225     while(1) {
226         if((req = parsereq(in)) == NULL)
227             break;
228         if(!canonreq(req))
229             break;
230         
231         if((conn->initreq != NULL) && conn->initreq(conn, req))
232             break;
233         
234         if(block(plex, EV_WRITE, 60) <= 0)
235             break;
236         if(socketpair(PF_UNIX, SOCK_STREAM, 0, pfds))
237             break;
238         if(sendreq(plex, req, pfds[0]))
239             break;
240         close(pfds[0]);
241         out = mtstdopen(pfds[1], 1, 600, "r+");
242
243         if((hd = getheader(req, "content-length")) != NULL) {
244             dlen = atoo(hd);
245             if(dlen > 0) {
246                 if(passdata(in, out, dlen) != dlen)
247                     break;
248             }
249         }
250         if(fflush(out))
251             break;
252         /* Make sure to send EOF */
253         shutdown(pfds[1], SHUT_WR);
254         
255         if((resp = parseresponse(out)) == NULL)
256             break;
257         replstr(&resp->ver, req->ver);
258         
259         if(!getheader(resp, "server"))
260             headappheader(resp, "Server", sprintf3("ashd/%s", VERSION));
261
262         if(!strcmp(req->ver, "HTTP/1.0")) {
263             writeresp(in, resp);
264             fprintf(in, "\r\n");
265             if(!strcasecmp(req->method, "head")) {
266                 if(!hasheader(req, "connection", "keep-alive"))
267                     break;
268             } else if((hd = getheader(resp, "content-length")) != NULL) {
269                 dlen = atoo(hd);
270                 if(passdata(out, in, dlen) != dlen)
271                     break;
272                 if(!hasheader(req, "connection", "keep-alive"))
273                     break;
274             } else {
275                 passdata(out, in, -1);
276                 break;
277             }
278             if(hasheader(req, "connection", "close") || hasheader(resp, "connection", "close"))
279                 break;
280         } else if(!strcmp(req->ver, "HTTP/1.1")) {
281             if(!strcasecmp(req->method, "head")) {
282                 writeresp(in, resp);
283                 fprintf(in, "\r\n");
284             } else if((hd = getheader(resp, "content-length")) != NULL) {
285                 writeresp(in, resp);
286                 fprintf(in, "\r\n");
287                 dlen = atoo(hd);
288                 if(passdata(out, in, dlen) != dlen)
289                     break;
290             } else if(!getheader(resp, "transfer-encoding")) {
291                 headappheader(resp, "Transfer-Encoding", "chunked");
292                 writeresp(in, resp);
293                 fprintf(in, "\r\n");
294                 if(passchunks(out, in))
295                     break;
296             } else {
297                 writeresp(in, resp);
298                 fprintf(in, "\r\n");
299                 passdata(out, in, -1);
300                 break;
301             }
302             if(hasheader(req, "connection", "close") || hasheader(resp, "connection", "close"))
303                 break;
304         } else {
305             break;
306         }
307
308         fclose(out);
309         out = NULL;
310         freehthead(req);
311         freehthead(resp);
312         req = resp = NULL;
313     }
314     
315     if(out != NULL)
316         fclose(out);
317     if(req != NULL)
318         freehthead(req);
319     if(resp != NULL)
320         freehthead(resp);
321     fclose(in);
322 }
323
324 static void plexwatch(struct muth *muth, va_list args)
325 {
326     vavar(int, fd);
327     char *buf;
328     int ret;
329     
330     while(1) {
331         block(fd, EV_READ, 0);
332         buf = smalloc(65536);
333         ret = recv(fd, buf, 65536, 0);
334         if(ret < 0) {
335             flog(LOG_WARNING, "received error on rootplex read channel: %s", strerror(errno));
336             exit(1);
337         } else if(ret == 0) {
338             exit(0);
339         }
340         /* Maybe I'd like to implement some protocol in this direction
341          * some day... */
342         free(buf);
343     }
344 }
345
346 static void initroot(void *uu)
347 {
348     int fd;
349     
350     if(daemonize) {
351         setsid();
352         chdir("/");
353         if((fd = open("/dev/null", O_RDWR)) >= 0) {
354             dup2(fd, 0);
355             dup2(fd, 1);
356             dup2(fd, 2);
357             close(fd);
358         }
359     }
360     if(usesyslog)
361         putenv("ASHD_USESYSLOG=1");
362     else
363         unsetenv("ASHD_USESYSLOG");
364 }
365
366 static void usage(FILE *out)
367 {
368     fprintf(out, "usage: htparser [-hSf] [-u USER] [-r ROOT] [-p PIDFILE] PORTSPEC... -- ROOT [ARGS...]\n");
369     fprintf(out, "\twhere PORTSPEC is HANDLER[:PAR[=VAL][(,PAR[=VAL])...]] (try HANDLER:help)\n");
370     fprintf(out, "\tavailable handlers are `plain' and `ssl'.\n");
371 }
372
373 static void addport(char *spec)
374 {
375     char *nm, *p, *p2, *n;
376     struct charvbuf pars, vals;
377     
378     bufinit(pars);
379     bufinit(vals);
380     if((p = strchr(spec, ':')) == NULL) {
381         nm = spec;
382     } else {
383         nm = spec;
384         *(p++) = 0;
385         do {
386             if((n = strchr(p, ',')) != NULL)
387                 *(n++) = 0;
388             if((p2 = strchr(p, '=')) != NULL)
389                 *(p2++) = 0;
390             if(!*p) {
391                 usage(stderr);
392                 exit(1);
393             }
394             bufadd(pars, p);
395             if(p2)
396                 bufadd(vals, p2);
397             else
398                 bufadd(vals, "");
399         } while((p = n) != NULL);
400     }
401     
402     /* XXX: It would be nice to decentralize this, but, meh... */
403     if(!strcmp(nm, "plain")) {
404         handleplain(pars.d, pars.b, vals.b);
405 #ifdef HAVE_GNUTLS
406     } else if(!strcmp(nm, "ssl")) {
407         handlegnussl(pars.d, pars.b, vals.b);
408 #endif
409     } else {
410         flog(LOG_ERR, "htparser: unknown port handler `%s'", nm);
411         exit(1);
412     }
413     
414     buffree(pars);
415     buffree(vals);
416 }
417
418 int main(int argc, char **argv)
419 {
420     int c;
421     int i, s1;
422     char *root;
423     FILE *pidout;
424     struct passwd *pwent;
425     
426     daemonize = usesyslog = 0;
427     root = NULL;
428     pwent = NULL;
429     while((c = getopt(argc, argv, "+hSfu:r:p:")) >= 0) {
430         switch(c) {
431         case 'h':
432             usage(stdout);
433             exit(0);
434         case 'f':
435             daemonize = 1;
436             break;
437         case 'S':
438             usesyslog = 1;
439             break;
440         case 'u':
441             if((pwent = getpwnam(optarg)) == NULL) {
442                 flog(LOG_ERR, "could not find user %s", optarg);
443                 exit(1);
444             }
445             break;
446         case 'r':
447             root = optarg;
448             break;
449         case 'p':
450             pidfile = optarg;
451             break;
452         default:
453             usage(stderr);
454             exit(1);
455         }
456     }
457     s1 = 0;
458     for(i = optind; i < argc; i++) {
459         if(!strcmp(argv[i], "--"))
460             break;
461         s1 = 1;
462         addport(argv[i]);
463     }
464     if(!s1 || (i == argc)) {
465         usage(stderr);
466         exit(1);
467     }
468     if((plex = stdmkchild(argv + ++i, initroot, NULL)) < 0) {
469         flog(LOG_ERR, "could not spawn root multiplexer: %s", strerror(errno));
470         return(1);
471     }
472     mustart(plexwatch, plex);
473     pidout = NULL;
474     if(pidfile != NULL) {
475         if((pidout = fopen(pidfile, "w")) == NULL) {
476             flog(LOG_ERR, "could not open %s for writing: %s", pidfile, strerror(errno));
477             return(1);
478         }
479     }
480     if(usesyslog)
481         opensyslog();
482     if(root) {
483         if(chdir(root) || chroot(root)) {
484             flog(LOG_ERR, "could not chroot to %s: %s", root, strerror(errno));
485             exit(1);
486         }
487     }
488     if(pwent) {
489         if(setgid(pwent->pw_gid)) {
490             flog(LOG_ERR, "could not switch group to %i: %s", (int)pwent->pw_gid, strerror(errno));
491             exit(1);
492         }
493         if(setuid(pwent->pw_uid)) {
494             flog(LOG_ERR, "could not switch user to %i: %s", (int)pwent->pw_uid, strerror(errno));
495             exit(1);
496         }
497     }
498     signal(SIGPIPE, SIG_IGN);
499     if(daemonize) {
500         daemon(0, 0);
501     }
502     if(pidout != NULL) {
503         fprintf(pidout, "%i\n", getpid());
504         fclose(pidout);
505     }
506     ioloop();
507     return(0);
508 }