userplex: Corrected opening of /dev/null.
[ashd.git] / src / htparser.c
... / ...
CommitLineData
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
41static int plex;
42static char *pidfile = NULL;
43static int daemonize, usesyslog;
44
45static 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
62static 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
118fail:
119 if(req != NULL) {
120 freehthead(req);
121 req = NULL;
122 }
123out:
124 buffree(method);
125 buffree(url);
126 buffree(ver);
127 return(req);
128}
129
130static 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
151static 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
168static 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
177static 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
215static int http10keep(struct hthead *req, struct hthead *resp)
216{
217 int fc;
218
219 fc = hasheader(resp, "connection", "close");
220 headrmheader(resp, "connection");
221 if(!fc && hasheader(req, "connection", "keep-alive")) {
222 headappheader(resp, "Connection", "Keep-Alive");
223 return(1);
224 } else {
225 return(0);
226 }
227}
228
229void serve(FILE *in, struct conn *conn)
230{
231 int pfds[2];
232 FILE *out;
233 struct hthead *req, *resp;
234 char *hd;
235 off_t dlen;
236 int keep;
237
238 out = NULL;
239 req = resp = NULL;
240 while(1) {
241 if((req = parsereq(in)) == NULL)
242 break;
243 if(!canonreq(req))
244 break;
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 = parseresponse(out)) == NULL)
271 break;
272 replstr(&resp->ver, req->ver);
273
274 if(!getheader(resp, "server"))
275 headappheader(resp, "Server", sprintf3("ashd/%s", VERSION));
276
277 if(!strcmp(req->ver, "HTTP/1.0")) {
278 if(!strcasecmp(req->method, "head")) {
279 keep = http10keep(req, resp);
280 writeresp(in, resp);
281 fprintf(in, "\r\n");
282 } else if((hd = getheader(resp, "content-length")) != NULL) {
283 keep = http10keep(req, resp);
284 dlen = atoo(hd);
285 writeresp(in, resp);
286 fprintf(in, "\r\n");
287 if(passdata(out, in, dlen) != dlen)
288 break;
289 } else {
290 headrmheader(resp, "connection");
291 writeresp(in, resp);
292 fprintf(in, "\r\n");
293 passdata(out, in, -1);
294 break;
295 }
296 if(!keep)
297 break;
298 } else if(!strcmp(req->ver, "HTTP/1.1")) {
299 if(!strcasecmp(req->method, "head")) {
300 writeresp(in, resp);
301 fprintf(in, "\r\n");
302 } else if((hd = getheader(resp, "content-length")) != NULL) {
303 writeresp(in, resp);
304 fprintf(in, "\r\n");
305 dlen = atoo(hd);
306 if(passdata(out, in, dlen) != dlen)
307 break;
308 } else if(!getheader(resp, "transfer-encoding")) {
309 headappheader(resp, "Transfer-Encoding", "chunked");
310 writeresp(in, resp);
311 fprintf(in, "\r\n");
312 if(passchunks(out, in))
313 break;
314 } else {
315 writeresp(in, resp);
316 fprintf(in, "\r\n");
317 passdata(out, in, -1);
318 break;
319 }
320 if(hasheader(req, "connection", "close") || hasheader(resp, "connection", "close"))
321 break;
322 } else {
323 break;
324 }
325
326 fclose(out);
327 out = NULL;
328 freehthead(req);
329 freehthead(resp);
330 req = resp = NULL;
331 }
332
333 if(out != NULL)
334 fclose(out);
335 if(req != NULL)
336 freehthead(req);
337 if(resp != NULL)
338 freehthead(resp);
339 fclose(in);
340}
341
342static void plexwatch(struct muth *muth, va_list args)
343{
344 vavar(int, fd);
345 char *buf;
346 int ret;
347
348 while(1) {
349 block(fd, EV_READ, 0);
350 buf = smalloc(65536);
351 ret = recv(fd, buf, 65536, 0);
352 if(ret < 0) {
353 flog(LOG_WARNING, "received error on rootplex read channel: %s", strerror(errno));
354 exit(1);
355 } else if(ret == 0) {
356 exit(0);
357 }
358 /* Maybe I'd like to implement some protocol in this direction
359 * some day... */
360 free(buf);
361 }
362}
363
364static void initroot(void *uu)
365{
366 int fd;
367
368 if(daemonize) {
369 setsid();
370 chdir("/");
371 if((fd = open("/dev/null", O_RDWR)) >= 0) {
372 dup2(fd, 0);
373 dup2(fd, 1);
374 dup2(fd, 2);
375 close(fd);
376 }
377 }
378 if(usesyslog)
379 putenv("ASHD_USESYSLOG=1");
380 else
381 unsetenv("ASHD_USESYSLOG");
382}
383
384static void usage(FILE *out)
385{
386 fprintf(out, "usage: htparser [-hSf] [-u USER] [-r ROOT] [-p PIDFILE] PORTSPEC... -- ROOT [ARGS...]\n");
387 fprintf(out, "\twhere PORTSPEC is HANDLER[:PAR[=VAL][(,PAR[=VAL])...]] (try HANDLER:help)\n");
388 fprintf(out, "\tavailable handlers are `plain' and `ssl'.\n");
389}
390
391static void addport(char *spec)
392{
393 char *nm, *p, *p2, *n;
394 struct charvbuf pars, vals;
395
396 bufinit(pars);
397 bufinit(vals);
398 if((p = strchr(spec, ':')) == NULL) {
399 nm = spec;
400 } else {
401 nm = spec;
402 *(p++) = 0;
403 do {
404 if((n = strchr(p, ',')) != NULL)
405 *(n++) = 0;
406 if((p2 = strchr(p, '=')) != NULL)
407 *(p2++) = 0;
408 if(!*p) {
409 usage(stderr);
410 exit(1);
411 }
412 bufadd(pars, p);
413 if(p2)
414 bufadd(vals, p2);
415 else
416 bufadd(vals, "");
417 } while((p = n) != NULL);
418 }
419
420 /* XXX: It would be nice to decentralize this, but, meh... */
421 if(!strcmp(nm, "plain")) {
422 handleplain(pars.d, pars.b, vals.b);
423#ifdef HAVE_GNUTLS
424 } else if(!strcmp(nm, "ssl")) {
425 handlegnussl(pars.d, pars.b, vals.b);
426#endif
427 } else {
428 flog(LOG_ERR, "htparser: unknown port handler `%s'", nm);
429 exit(1);
430 }
431
432 buffree(pars);
433 buffree(vals);
434}
435
436int main(int argc, char **argv)
437{
438 int c;
439 int i, s1;
440 char *root;
441 FILE *pidout;
442 struct passwd *pwent;
443
444 daemonize = usesyslog = 0;
445 root = NULL;
446 pwent = NULL;
447 while((c = getopt(argc, argv, "+hSfu:r:p:")) >= 0) {
448 switch(c) {
449 case 'h':
450 usage(stdout);
451 exit(0);
452 case 'f':
453 daemonize = 1;
454 break;
455 case 'S':
456 usesyslog = 1;
457 break;
458 case 'u':
459 if((pwent = getpwnam(optarg)) == NULL) {
460 flog(LOG_ERR, "could not find user %s", optarg);
461 exit(1);
462 }
463 break;
464 case 'r':
465 root = optarg;
466 break;
467 case 'p':
468 pidfile = optarg;
469 break;
470 default:
471 usage(stderr);
472 exit(1);
473 }
474 }
475 s1 = 0;
476 for(i = optind; i < argc; i++) {
477 if(!strcmp(argv[i], "--"))
478 break;
479 s1 = 1;
480 addport(argv[i]);
481 }
482 if(!s1 || (i == argc)) {
483 usage(stderr);
484 exit(1);
485 }
486 if((plex = stdmkchild(argv + ++i, initroot, NULL)) < 0) {
487 flog(LOG_ERR, "could not spawn root multiplexer: %s", strerror(errno));
488 return(1);
489 }
490 mustart(plexwatch, plex);
491 pidout = NULL;
492 if(pidfile != NULL) {
493 if((pidout = fopen(pidfile, "w")) == NULL) {
494 flog(LOG_ERR, "could not open %s for writing: %s", pidfile, strerror(errno));
495 return(1);
496 }
497 }
498 if(usesyslog)
499 opensyslog();
500 if(root) {
501 if(chdir(root) || chroot(root)) {
502 flog(LOG_ERR, "could not chroot to %s: %s", root, strerror(errno));
503 exit(1);
504 }
505 }
506 if(pwent) {
507 if(setgid(pwent->pw_gid)) {
508 flog(LOG_ERR, "could not switch group to %i: %s", (int)pwent->pw_gid, strerror(errno));
509 exit(1);
510 }
511 if(setuid(pwent->pw_uid)) {
512 flog(LOG_ERR, "could not switch user to %i: %s", (int)pwent->pw_uid, strerror(errno));
513 exit(1);
514 }
515 }
516 signal(SIGPIPE, SIG_IGN);
517 if(daemonize) {
518 daemon(0, 0);
519 }
520 if(pidout != NULL) {
521 fprintf(pidout, "%i\n", getpid());
522 fclose(pidout);
523 }
524 ioloop();
525 return(0);
526}