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