Imposed some limits on request parts.
[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 struct hthead *parseresp(FILE *in)
131 {
132     struct hthead *req;
133     int code;
134     struct charbuf ver, msg;
135     int c;
136     
137     req = NULL;
138     bufinit(ver);
139     bufinit(msg);
140     code = 0;
141     while(1) {
142         c = getc(in);
143         if(c == ' ') {
144             break;
145         } else if((c == EOF) || (c < 32) || (c >= 128)) {
146             goto fail;
147         } else {
148             bufadd(ver, c);
149         }
150     }
151     while(1) {
152         c = getc(in);
153         if(c == ' ') {
154             break;
155         } else if((c == EOF) || (c < '0') || (c > '9')) {
156             goto fail;
157         } else {
158             code = (code * 10) + (c - '0');
159         }
160     }
161     while(1) {
162         c = getc(in);
163         if(c == 10) {
164             break;
165         } else if(c == 13) {
166         } else if((c == EOF) || (c < 32)) {
167             goto fail;
168         } else {
169             bufadd(msg, c);
170         }
171     }
172     bufadd(msg, 0);
173     bufadd(ver, 0);
174     req = mkresp(code, msg.b, ver.b);
175     if(parseheaders(req, in))
176         goto fail;
177     goto out;
178     
179 fail:
180     if(req != NULL) {
181         freehthead(req);
182         req = NULL;
183     }
184 out:
185     buffree(msg);
186     buffree(ver);
187     return(req);
188 }
189
190 static off_t passdata(FILE *in, FILE *out, off_t max)
191 {
192     size_t read;
193     off_t total;
194     char buf[8192];
195     
196     total = 0;
197     while(!feof(in) && ((max < 0) || (total < max))) {
198         read = sizeof(buf);
199         if(max >= 0)
200             read = min(max - total, read);
201         read = fread(buf, 1, read, in);
202         if(ferror(in))
203             return(-1);
204         if(fwrite(buf, 1, read, out) != read)
205             return(-1);
206         total += read;
207     }
208     return(total);
209 }
210
211 static int passchunks(FILE *in, FILE *out)
212 {
213     char buf[8192];
214     size_t read;
215     
216     do {
217         read = fread(buf, 1, sizeof(buf), in);
218         if(ferror(in))
219             return(-1);
220         fprintf(out, "%zx\r\n", read);
221         if(fwrite(buf, 1, read, out) != read)
222             return(-1);
223         fprintf(out, "\r\n");
224     } while(read > 0);
225     return(0);
226 }
227
228 static int hasheader(struct hthead *head, char *name, char *val)
229 {
230     char *hd;
231     
232     if((hd = getheader(head, name)) == NULL)
233         return(0);
234     return(!strcasecmp(hd, val));
235 }
236
237 void serve(FILE *in, struct conn *conn)
238 {
239     int pfds[2];
240     FILE *out;
241     struct hthead *req, *resp;
242     char *hd, *p;
243     off_t dlen;
244     
245     out = NULL;
246     req = resp = NULL;
247     while(1) {
248         if((req = parsereq(in)) == NULL)
249             break;
250         replrest(req, req->url);
251         if(req->rest[0] == '/')
252             replrest(req, req->rest + 1);
253         if((p = strchr(req->rest, '?')) != NULL)
254             *p = 0;
255         
256         if((conn->initreq != NULL) && conn->initreq(conn, req))
257             break;
258         
259         if(block(plex, EV_WRITE, 60) <= 0)
260             break;
261         if(socketpair(PF_UNIX, SOCK_STREAM, 0, pfds))
262             break;
263         if(sendreq(plex, req, pfds[0]))
264             break;
265         close(pfds[0]);
266         out = mtstdopen(pfds[1], 1, 600, "r+");
267
268         if((hd = getheader(req, "content-length")) != NULL) {
269             dlen = atoo(hd);
270             if(dlen > 0) {
271                 if(passdata(in, out, dlen) != dlen)
272                     break;
273             }
274         }
275         if(fflush(out))
276             break;
277         /* Make sure to send EOF */
278         shutdown(pfds[1], SHUT_WR);
279         
280         if((resp = parseresp(out)) == NULL)
281             break;
282         replstr(&resp->ver, req->ver);
283         
284         if(!getheader(resp, "server"))
285             headappheader(resp, "Server", sprintf3("ashd/%s", VERSION));
286
287         if(!strcmp(req->ver, "HTTP/1.0")) {
288             writeresp(in, resp);
289             fprintf(in, "\r\n");
290             if(!strcasecmp(req->method, "head")) {
291                 if(!hasheader(req, "connection", "keep-alive"))
292                     break;
293             } else if((hd = getheader(resp, "content-length")) != NULL) {
294                 dlen = atoo(hd);
295                 if(passdata(out, in, dlen) != dlen)
296                     break;
297                 if(!hasheader(req, "connection", "keep-alive"))
298                     break;
299             } else {
300                 passdata(out, in, -1);
301                 break;
302             }
303             if(hasheader(req, "connection", "close") || hasheader(resp, "connection", "close"))
304                 break;
305         } else if(!strcmp(req->ver, "HTTP/1.1")) {
306             if(!strcasecmp(req->method, "head")) {
307                 writeresp(in, resp);
308                 fprintf(in, "\r\n");
309             } else if((hd = getheader(resp, "content-length")) != NULL) {
310                 writeresp(in, resp);
311                 fprintf(in, "\r\n");
312                 dlen = atoo(hd);
313                 if(passdata(out, in, dlen) != dlen)
314                     break;
315             } else if(!getheader(resp, "transfer-encoding")) {
316                 headappheader(resp, "Transfer-Encoding", "chunked");
317                 writeresp(in, resp);
318                 fprintf(in, "\r\n");
319                 if(passchunks(out, in))
320                     break;
321             } else {
322                 writeresp(in, resp);
323                 fprintf(in, "\r\n");
324                 passdata(out, in, -1);
325                 break;
326             }
327             if(hasheader(req, "connection", "close") || hasheader(resp, "connection", "close"))
328                 break;
329         } else {
330             break;
331         }
332
333         fclose(out);
334         out = NULL;
335         freehthead(req);
336         freehthead(resp);
337         req = resp = NULL;
338     }
339     
340     if(out != NULL)
341         fclose(out);
342     if(req != NULL)
343         freehthead(req);
344     if(resp != NULL)
345         freehthead(resp);
346     fclose(in);
347 }
348
349 static void plexwatch(struct muth *muth, va_list args)
350 {
351     vavar(int, fd);
352     char *buf;
353     int ret;
354     
355     while(1) {
356         block(fd, EV_READ, 0);
357         buf = smalloc(65536);
358         ret = recv(fd, buf, 65536, 0);
359         if(ret < 0) {
360             flog(LOG_WARNING, "received error on rootplex read channel: %s", strerror(errno));
361             exit(1);
362         } else if(ret == 0) {
363             exit(0);
364         }
365         /* Maybe I'd like to implement some protocol in this direction
366          * some day... */
367         free(buf);
368     }
369 }
370
371 static void initroot(void *uu)
372 {
373     int fd;
374     
375     if(daemonize) {
376         setsid();
377         chdir("/");
378         if((fd = open("/dev/null", O_RDWR)) >= 0) {
379             dup2(fd, 0);
380             dup2(fd, 1);
381             dup2(fd, 2);
382             close(fd);
383         }
384     }
385     if(usesyslog)
386         putenv("ASHD_USESYSLOG=1");
387     else
388         unsetenv("ASHD_USESYSLOG");
389 }
390
391 static void usage(FILE *out)
392 {
393     fprintf(out, "usage: htparser [-hSf] [-u USER] [-r ROOT] [-p PIDFILE] PORTSPEC... -- ROOT [ARGS...]\n");
394     fprintf(out, "\twhere PORTSPEC is HANDLER[:PAR[=VAL][(,PAR[=VAL])...]] (try HANDLER:help)\n");
395     fprintf(out, "\tavailable handlers are `plain' and `ssl'.\n");
396 }
397
398 static void addport(char *spec)
399 {
400     char *nm, *p, *p2, *n;
401     struct charvbuf pars, vals;
402     
403     bufinit(pars);
404     bufinit(vals);
405     if((p = strchr(spec, ':')) == NULL) {
406         nm = spec;
407     } else {
408         nm = spec;
409         *(p++) = 0;
410         do {
411             if((n = strchr(p, ',')) != NULL)
412                 *(n++) = 0;
413             if((p2 = strchr(p, '=')) != NULL)
414                 *(p2++) = 0;
415             if(!*p) {
416                 usage(stderr);
417                 exit(1);
418             }
419             bufadd(pars, p);
420             if(p2)
421                 bufadd(vals, p2);
422             else
423                 bufadd(vals, "");
424         } while((p = n) != NULL);
425     }
426     
427     /* XXX: It would be nice to decentralize this, but, meh... */
428     if(!strcmp(nm, "plain")) {
429         handleplain(pars.d, pars.b, vals.b);
430 #ifdef HAVE_GNUTLS
431     } else if(!strcmp(nm, "ssl")) {
432         handlegnussl(pars.d, pars.b, vals.b);
433 #endif
434     } else {
435         flog(LOG_ERR, "htparser: unknown port handler `%s'", nm);
436         exit(1);
437     }
438     
439     buffree(pars);
440     buffree(vals);
441 }
442
443 int main(int argc, char **argv)
444 {
445     int c;
446     int i, s1;
447     char *root;
448     FILE *pidout;
449     struct passwd *pwent;
450     
451     daemonize = usesyslog = 0;
452     root = NULL;
453     pwent = NULL;
454     while((c = getopt(argc, argv, "+hSfu:r:p:")) >= 0) {
455         switch(c) {
456         case 'h':
457             usage(stdout);
458             exit(0);
459         case 'f':
460             daemonize = 1;
461             break;
462         case 'S':
463             usesyslog = 1;
464             break;
465         case 'u':
466             if((pwent = getpwnam(optarg)) == NULL) {
467                 flog(LOG_ERR, "could not find user %s", optarg);
468                 exit(1);
469             }
470             break;
471         case 'r':
472             root = optarg;
473             break;
474         case 'p':
475             pidfile = optarg;
476             break;
477         default:
478             usage(stderr);
479             exit(1);
480         }
481     }
482     s1 = 0;
483     for(i = optind; i < argc; i++) {
484         if(!strcmp(argv[i], "--"))
485             break;
486         s1 = 1;
487         addport(argv[i]);
488     }
489     if(!s1 || (i == argc)) {
490         usage(stderr);
491         exit(1);
492     }
493     if((plex = stdmkchild(argv + ++i, initroot, NULL)) < 0) {
494         flog(LOG_ERR, "could not spawn root multiplexer: %s", strerror(errno));
495         return(1);
496     }
497     mustart(plexwatch, plex);
498     pidout = NULL;
499     if(pidfile != NULL) {
500         if((pidout = fopen(pidfile, "w")) == NULL) {
501             flog(LOG_ERR, "could not open %s for writing: %s", pidfile, strerror(errno));
502             return(1);
503         }
504     }
505     if(usesyslog)
506         opensyslog();
507     if(root) {
508         if(chdir(root) || chroot(root)) {
509             flog(LOG_ERR, "could not chroot to %s: %s", root, strerror(errno));
510             exit(1);
511         }
512     }
513     if(pwent) {
514         if(setgid(pwent->pw_gid)) {
515             flog(LOG_ERR, "could not switch group to %i: %s", (int)pwent->pw_gid, strerror(errno));
516             exit(1);
517         }
518         if(setuid(pwent->pw_uid)) {
519             flog(LOG_ERR, "could not switch user to %i: %s", (int)pwent->pw_uid, strerror(errno));
520             exit(1);
521         }
522     }
523     signal(SIGPIPE, SIG_IGN);
524     if(daemonize) {
525         daemon(0, 0);
526     }
527     if(pidout != NULL) {
528         fprintf(pidout, "%i\n", getpid());
529         fclose(pidout);
530     }
531     ioloop();
532     return(0);
533 }