callscgi: Exit properly on SIGTERM and SIGINT.
[ashd.git] / src / callscgi.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 /*
20  * XXX: All the various ways to start a child process makes this
21  * program quite ugly at the moment. It is unclear whether it is
22  * meaningfully possible to unify them better than they currently are.
23  */
24
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <unistd.h>
28 #include <string.h>
29 #include <fcntl.h>
30 #include <ctype.h>
31 #include <sys/socket.h>
32 #include <sys/un.h>
33 #include <netinet/in.h>
34 #include <netdb.h>
35 #include <sys/signal.h>
36 #include <errno.h>
37
38 #ifdef HAVE_CONFIG_H
39 #include <config.h>
40 #endif
41 #include <utils.h>
42 #include <req.h>
43 #include <log.h>
44 #include <mt.h>
45 #include <mtio.h>
46
47 static char **progspec;
48 static char *sockid, *unspec, *inspec;
49 static int nolisten;
50 static struct sockaddr *curaddr;
51 static size_t caddrlen;
52 static int cafamily, isanon;
53 static pid_t child;
54
55 static struct addrinfo *resolv(int flags)
56 {
57     int ret;
58     struct addrinfo *ai, h;
59     char *name, *srv, *p;
60     
61     if((p = strchr(inspec, ':')) != NULL) {
62         name = smalloc(p - inspec + 1);
63         memcpy(name, inspec, p - inspec);
64         name[p - inspec] = 0;
65         srv = p + 1;
66     } else {
67         name = sstrdup("localhost");
68         srv = inspec;
69     }
70     memset(&h, 0, sizeof(h));
71     h.ai_family = AF_UNSPEC;
72     h.ai_socktype = SOCK_STREAM;
73     h.ai_flags = flags;
74     ret = getaddrinfo(name, srv, &h, &ai);
75     free(name);
76     if(ret != 0) {
77         flog(LOG_ERR, "could not resolve TCP specification `%s': %s", inspec, gai_strerror(ret));
78         exit(1);
79     }
80     return(ai);
81 }
82
83 static char *mksockid(char *sockid)
84 {
85     char *home;
86     
87     home = getenv("HOME");
88     if(home && !access(sprintf3("%s/.ashd/sockets/", home), X_OK))
89         return(sprintf3("%s/.ashd/sockets/scgi-p-%s", home, sockid));
90     return(sprintf3("/tmp/scgi-%i-%s", getuid(), sockid));
91 }
92
93 static char *mkanonid(void)
94 {
95     char *home;
96     char *tmpl;
97     int fd;
98     
99     home = getenv("HOME");
100     if(home && !access(sprintf3("%s/.ashd/sockets/", home), X_OK))
101         tmpl = sprintf2("%s/.ashd/sockets/scgi-a-XXXXXX", home);
102     else
103         tmpl = sprintf2("/tmp/scgi-a-%i-XXXXXX", getuid());
104     if((fd = mkstemp(tmpl)) < 0) {
105         flog(LOG_ERR, "could not create anonymous socket `%s': %s", tmpl, strerror(errno));
106         exit(1);
107     }
108     close(fd);
109     unlink(tmpl);
110     return(tmpl);
111 }
112
113 static void startlisten(void)
114 {
115     int i, fd;
116     struct addrinfo *ai, *cai;
117     char *unpath;
118     struct sockaddr_un unm;
119     char *aname;
120     
121     isanon = 0;
122     if(inspec != NULL) {
123         fd = -1;
124         for(cai = ai = resolv(AI_PASSIVE); cai != NULL; cai = cai->ai_next) {
125             if((fd = socket(cai->ai_family, cai->ai_socktype, cai->ai_protocol)) < 0)
126                 continue;
127             if(bind(fd, cai->ai_addr, cai->ai_addrlen)) {
128                 close(fd);
129                 fd = -1;
130                 continue;
131             }
132             if(listen(fd, 128)) {
133                 close(fd);
134                 fd = -1;
135                 continue;
136             }
137             break;
138         }
139         freeaddrinfo(ai);
140         if(fd < 0) {
141             flog(LOG_ERR, "could not bind to specified TCP address: %s", strerror(errno));
142             exit(1);
143         }
144     } else if((unspec != NULL) || (sockid != NULL)) {
145         if((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
146             flog(LOG_ERR, "could not create Unix socket: %s", strerror(errno));
147             exit(1);
148         }
149         if(unspec != NULL)
150             unpath = unspec;
151         else
152             unpath = mksockid(sockid);
153         unlink(unpath);
154         unm.sun_family = AF_UNIX;
155         strcpy(unm.sun_path, unpath);
156         if(bind(fd, (struct sockaddr *)&unm, sizeof(unm))) {
157             flog(LOG_ERR, "could not bind Unix socket to `%s': %s", unspec, strerror(errno));
158             exit(1);
159         }
160         if(listen(fd, 128)) {
161             flog(LOG_ERR, "listen: %s", strerror(errno));
162             exit(1);
163         }
164     } else {
165         if((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
166             flog(LOG_ERR, "could not create Unix socket: %s", strerror(errno));
167             exit(1);
168         }
169         memset(&unm, 0, sizeof(unm));
170         aname = mkanonid();
171         unm.sun_family = AF_UNIX;
172         strcpy(unm.sun_path, aname);
173         free(aname);
174         if(bind(fd, (struct sockaddr *)&unm, sizeof(unm))) {
175             flog(LOG_ERR, "could not bind Unix socket to `%s': %s", unspec, strerror(errno));
176             exit(1);
177         }
178         if(listen(fd, 128)) {
179             flog(LOG_ERR, "listen: %s", strerror(errno));
180             exit(1);
181         }
182         
183         curaddr = smalloc(caddrlen = sizeof(unm));
184         memcpy(curaddr, &unm, sizeof(unm));
185         cafamily = AF_UNIX;
186         isanon = 1;
187     }
188     if((child = fork()) < 0) {
189         flog(LOG_ERR, "could not fork: %s", strerror(errno));
190         exit(1);
191     }
192     if(child == 0) {
193         dup2(fd, 0);
194         for(i = 3; i < FD_SETSIZE; i++)
195             close(i);
196         execvp(*progspec, progspec);
197         exit(127);
198     }
199     close(fd);
200 }
201
202 static void startnolisten(void)
203 {
204     int i, fd;
205     
206     if((child = fork()) < 0) {
207         flog(LOG_ERR, "could not fork: %s", strerror(errno));
208         exit(1);
209     }
210     if(child == 0) {
211         for(i = 3; i < FD_SETSIZE; i++)
212             close(i);
213         if((fd = open("/dev/null", O_RDONLY)) < 0) {
214             flog(LOG_ERR, "/dev/null: %s", strerror(errno));
215             exit(127);
216         }
217         dup2(fd, 0);
218         close(fd);
219         execvp(*progspec, progspec);
220         exit(127);
221     }
222 }
223
224 static int sconnect(void)
225 {
226     int fd;
227     int err;
228     socklen_t errlen;
229
230     fd = socket(cafamily, SOCK_STREAM, 0);
231     fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
232     while(1) {
233         if(connect(fd, curaddr, caddrlen)) {
234             if(errno == EINPROGRESS) {
235                 block(fd, EV_WRITE, 30);
236                 errlen = sizeof(err);
237                 if(getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) || ((errno = err) != 0)) {
238                     close(fd);
239                     return(-1);
240                 }
241                 return(fd);
242             }
243             close(fd);
244             return(-1);
245         }
246         return(fd);
247     }
248 }
249
250 static int econnect(void)
251 {
252     int fd;
253     struct addrinfo *ai, *cai;
254     int tries;
255     char *unpath;
256     struct sockaddr_un unm;
257     
258     tries = 0;
259 retry:
260     if(inspec != NULL) {
261         fd = -1;
262         for(cai = ai = resolv(0); cai != NULL; cai = cai->ai_next) {
263             if((fd = socket(cai->ai_family, cai->ai_socktype, cai->ai_protocol)) < 0)
264                 continue;
265             if(connect(fd, cai->ai_addr, cai->ai_addrlen)) {
266                 close(fd);
267                 fd = -1;
268                 continue;
269             }
270             break;
271         }
272         if(fd < 0) {
273             if(tries++ < nolisten) {
274                 sleep(1);
275                 goto retry;
276             }
277             flog(LOG_ERR, "could not connect to specified TCP address: %s", strerror(errno));
278             exit(1);
279         }
280         curaddr = smalloc(caddrlen = cai->ai_addrlen);
281         memcpy(curaddr, cai->ai_addr, caddrlen);
282         cafamily = cai->ai_family;
283         isanon = 0;
284         freeaddrinfo(ai);
285         return(fd);
286     } else if((unspec != NULL) || (sockid != NULL)) {
287         if((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
288             flog(LOG_ERR, "could not create Unix socket: %s", strerror(errno));
289             exit(1);
290         }
291         if(unspec != NULL)
292             unpath = unspec;
293         else
294             unpath = mksockid(sockid);
295         unlink(unpath);
296         unm.sun_family = AF_UNIX;
297         strcpy(unm.sun_path, unpath);
298         if(connect(fd, (struct sockaddr *)&unm, sizeof(unm))) {
299             close(fd);
300             if(tries++ < nolisten) {
301                 sleep(1);
302                 goto retry;
303             }
304             flog(LOG_ERR, "could not connect to Unix socket `%s': %s", unspec, strerror(errno));
305             exit(1);
306         }
307         curaddr = smalloc(caddrlen = sizeof(unm));
308         memcpy(curaddr, &unm, sizeof(unm));
309         cafamily = AF_UNIX;
310         isanon = 0;
311         return(fd);
312     } else {
313         flog(LOG_ERR, "servescgi: cannot use an anonymous socket without a program to start");
314         exit(1);
315     }
316 }
317
318 static int startconn(void)
319 {
320     if(*progspec) {
321         if(nolisten == 0)
322             startlisten();
323         else
324             startnolisten();
325     }
326     if(curaddr != NULL)
327         return(sconnect());
328     return(econnect());
329 }
330
331 static void killcuraddr(void)
332 {
333     if(curaddr == NULL)
334         return;
335     if(isanon) {
336         unlink(((struct sockaddr_un *)curaddr)->sun_path);
337         if(child > 0)
338             kill(child, SIGTERM);
339     }
340     free(curaddr);
341     curaddr = NULL;
342 }
343
344 static int reconn(void)
345 {
346     int fd;
347     
348     if(curaddr != NULL) {
349         if((fd = sconnect()) >= 0)
350             return(fd);
351         killcuraddr();
352     }
353     return(startconn());
354 }
355
356 static off_t passdata(FILE *in, FILE *out)
357 {
358     size_t read;
359     off_t total;
360     char buf[8192];
361     
362     total = 0;
363     while(!feof(in)) {
364         read = fread(buf, 1, sizeof(buf), in);
365         if(ferror(in))
366             return(-1);
367         if(fwrite(buf, 1, read, out) != read)
368             return(-1);
369         total += read;
370     }
371     return(total);
372 }
373
374 static void bufaddenv(struct charbuf *dst, char *name, char *fmt, ...)
375 {
376     va_list args;
377     
378     bufcatstr2(*dst, name);
379     va_start(args, fmt);
380     bvprintf(dst, fmt, args);
381     va_end(args);
382     bufadd(*dst, 0);
383 }
384
385 static char *absolutify(char *file)
386 {
387     static int inited = 0;
388     static char cwd[1024];
389     
390     if(*file != '/') {
391         if(!inited) {
392             getcwd(cwd, sizeof(cwd));
393             inited = 1;
394         }
395         return(sprintf2("%s/%s", cwd, file));
396     }
397     return(sstrdup(file));
398 }
399
400 /* Mostly copied from callcgi. */
401 static void mkcgienv(struct hthead *req, struct charbuf *dst)
402 {
403     int i;
404     char *url, *qp, *h, *p;
405     
406     bufaddenv(dst, "SERVER_SOFTWARE", "ashd/%s", VERSION);
407     bufaddenv(dst, "GATEWAY_INTERFACE", "CGI/1.1");
408     bufaddenv(dst, "SCGI", "1");
409     bufaddenv(dst, "SERVER_PROTOCOL", "%s", req->ver);
410     bufaddenv(dst, "REQUEST_METHOD", "%s", req->method);
411     bufaddenv(dst, "REQUEST_URI", "%s", req->url);
412     if(*req->rest)
413         bufaddenv(dst, "PATH_INFO", "/%s", req->rest);
414     else
415         bufaddenv(dst, "PATH_INFO", "");
416     url = sstrdup(req->url);
417     if((qp = strchr(url, '?')) != NULL)
418         *(qp++) = 0;
419     /* XXX: This is an ugly hack (I think), but though I can think of
420      * several alternatives, none seem to be better. */
421     if(*req->rest && (strlen(url) > strlen(req->rest)) &&
422        !strcmp(req->rest, url + strlen(url) - strlen(req->rest)) &&
423        (url[strlen(url) - strlen(req->rest) - 1] == '/')) {
424         bufaddenv(dst, "SCRIPT_NAME", "%.*s", (int)(strlen(url) - strlen(req->rest) - 1), url);
425     } else {
426         bufaddenv(dst, "SCRIPT_NAME", "%s", url);
427     }
428     bufaddenv(dst, "QUERY_STRING", "%s", qp?qp:"");
429     if((h = getheader(req, "Host")) != NULL)
430         bufaddenv(dst, "SERVER_NAME", "%s", h);
431     if((h = getheader(req, "X-Ash-Server-Port")) != NULL)
432         bufaddenv(dst, "SERVER_PORT", "%s", h);
433     if(((h = getheader(req, "X-Ash-Server-Protocol")) != NULL) && !strcmp(h, "https"))
434         bufaddenv(dst, "HTTPS", "on");
435     if((h = getheader(req, "X-Ash-Address")) != NULL)
436         bufaddenv(dst, "REMOTE_ADDR", "%s", h);
437     if((h = getheader(req, "Content-Type")) != NULL)
438         bufaddenv(dst, "CONTENT_TYPE", "%s", h);
439     if((h = getheader(req, "Content-Length")) != NULL)
440         bufaddenv(dst, "CONTENT_LENGTH", "%s", h);
441     else
442         bufaddenv(dst, "CONTENT_LENGTH", "0");
443     if((h = getheader(req, "X-Ash-File")) != NULL)
444         bufaddenv(dst, "SCRIPT_FILENAME", "%s", absolutify(h));
445     for(i = 0; i < req->noheaders; i++) {
446         h = sprintf2("HTTP_%s", req->headers[i][0]);
447         for(p = h; *p; p++) {
448             if(isalnum(*p))
449                 *p = toupper(*p);
450             else
451                 *p = '_';
452         }
453         bufcatstr2(*dst, h);
454         free(h);
455         bufcatstr2(*dst, req->headers[i][1]);
456     }
457 }
458
459 static char *defstatus(int code)
460 {
461     if(code == 200)
462         return("OK");
463     else if(code == 201)
464         return("Created");
465     else if(code == 202)
466         return("Accepted");
467     else if(code == 204)
468         return("No Content");
469     else if(code == 300)
470         return("Multiple Choices");
471     else if(code == 301)
472         return("Moved Permanently");
473     else if(code == 302)
474         return("Found");
475     else if(code == 303)
476         return("See Other");
477     else if(code == 304)
478         return("Not Modified");
479     else if(code == 307)
480         return("Moved Temporarily");
481     else if(code == 400)
482         return("Bad Request");
483     else if(code == 401)
484         return("Unauthorized");
485     else if(code == 403)
486         return("Forbidden");
487     else if(code == 404)
488         return("Not Found");
489     else if(code == 500)
490         return("Internal Server Error");
491     else if(code == 501)
492         return("Not Implemented");
493     else if(code == 503)
494         return("Service Unavailable");
495     else
496         return("Unknown status");
497 }
498
499 static struct hthead *parseresp(FILE *in)
500 {
501     struct hthead *resp;
502     char *st, *p;
503     
504     omalloc(resp);
505     resp->ver = sstrdup("HTTP/1.1");
506     if(parseheaders(resp, in)) {
507         freehthead(resp);
508         return(NULL);
509     }
510     if((st = getheader(resp, "Status")) != NULL) {
511         if((p = strchr(st, ' ')) != NULL) {
512             *(p++) = 0;
513             resp->code = atoi(st);
514             resp->msg = sstrdup(p);
515         } else {
516             resp->code = atoi(st);
517             resp->msg = sstrdup(defstatus(resp->code));
518         }
519         headrmheader(resp, "Status");
520     } else if(getheader(resp, "Location")) {
521         resp->code = 303;
522         resp->msg = sstrdup("See Other");
523     } else {
524         resp->code = 200;
525         resp->msg = sstrdup("OK");
526     }
527     return(resp);
528 }
529
530 static void serve(struct muth *muth, va_list args)
531 {
532     vavar(struct hthead *, req);
533     vavar(int, fd);
534     vavar(int, sfd);
535     FILE *is, *os;
536     struct charbuf head;
537     struct hthead *resp;
538     
539     sfd = reconn();
540     is = mtstdopen(fd, 1, 60, "r+");
541     os = mtstdopen(sfd, 1, 600, "r+");
542     
543     bufinit(head);
544     mkcgienv(req, &head);
545     fprintf(os, "%zi:", head.d);
546     fwrite(head.b, head.d, 1, os);
547     fputc(',', os);
548     buffree(head);
549     if(passdata(is, os) < 0)
550         goto out;
551     
552     if((resp = parseresp(os)) == NULL)
553         goto out;
554     writeresp(is, resp);
555     freehthead(resp);
556     fputc('\n', is);
557     if(passdata(os, is) < 0)
558         goto out;
559     
560 out:
561     freehthead(req);
562     fclose(is);
563     fclose(os);
564 }
565
566 static void listenloop(struct muth *muth, va_list args)
567 {
568     vavar(int, lfd);
569     int fd;
570     struct hthead *req;
571     
572     while(1) {
573         block(0, EV_READ, 0);
574         if((fd = recvreq(lfd, &req)) < 0) {
575             if(errno != 0)
576                 flog(LOG_ERR, "recvreq: %s", strerror(errno));
577             break;
578         }
579         mustart(serve, req, fd);
580     }
581 }
582
583 static void sigexit(int sig)
584 {
585     exit(0);
586 }
587
588 static void usage(FILE *out)
589 {
590     fprintf(out, "usage: servescgi [-h] [-N RETRIES] [-i ID] [-u UNIX-PATH] [-t [HOST:]TCP-PORT] [PROGRAM [ARGS...]]\n");
591 }
592
593 int main(int argc, char **argv)
594 {
595     int c;
596     
597     while((c = getopt(argc, argv, "+hN:i:u:t:")) >= 0) {
598         switch(c) {
599         case 'h':
600             usage(stdout);
601             exit(0);
602         case 'N':
603             nolisten = atoi(optarg);
604             break;
605         case 'i':
606             sockid = optarg;
607             break;
608         case 'u':
609             unspec = optarg;
610             break;
611         case 't':
612             inspec = optarg;
613             break;
614         default:
615             usage(stderr);
616             exit(1);
617         }
618     }
619     progspec = argv + optind;
620     if(((sockid != NULL) + (unspec != NULL) + (inspec != NULL)) > 1) {
621         flog(LOG_ERR, "servescgi: at most one of -i, -u or -t may be given");
622         exit(1);
623     }
624     signal(SIGCHLD, SIG_IGN);
625     signal(SIGINT, sigexit);
626     signal(SIGTERM, sigexit);
627     mustart(listenloop, 0);
628     atexit(killcuraddr);
629     ioloop();
630     return(0);
631 }