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