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