chiark / gitweb /
prefork-interp: fixes
[chiark-utils.git] / cprogs / prefork-interp.c
1 /*
2  * "Interpreter" that you can put in #! like this
3  *   #!/usr/bin/prefork-interp [<options>] <interpreter>
4  *
5  * Usages:
6  *   prefork-interp  [<option> ..] <interpreter>  [<script> [<args> ...]]
7  *   prefork-interp  [<option>,..],<interpreter>   <script> [<args> ...]
8  *   prefork-interp '[<option> ..] <interpreter>'  <script> [<args> ...]
9  *
10  * Options must specify argument laundering mode.
11  * Currently the only mode supported is:
12  *   -U    unlaundered: setup and executor both get all arguments and env vars
13  *         ident covers only env vars specified  with -E
14  *         ident covers only arguments interpreter and (if present) script
15  */
16 /*
17  * Process structure:
18  *  client (C wrapper)        connects to server
19  *                              (including reading ack byte)
20  *                            if fails or garbage
21  *                            === acquires lock ===
22  *                            makes new listening socket
23  *                            makes watcher pipes
24  *                            forks watcher and awaits
25  *                            makes first-instance socketpair
26  *                            forks setup (script, sock fds indicated in env)
27  *                            fd0, fd1, fd2: from-outer
28  *                            other fd: call(client-end)(fake)
29  *                            reaps setup (and reports error)
30  *                            (implicitly releases lock)
31  *
32  *     watcher                fd[012]: watcher pipes
33  *                            starts watch on socket path
34  *                            sets stderr to line buffered
35  *                            sets stdin to nonblocking
36  *                            daemonises (one fork, becomes session leader)
37  *                            when socket stat changes, quit
38  *
39  *     setup (pre-exec)       fd0: null,
40  *                            fd[12]: fd2-from-outer
41  *                            env fds: listener, call(server-end)(fake),
42  *                                      watcher read, watcher write
43  *                            close fd: lockfile
44  *                            possibly clean env, argv
45  *
46  *     setup (script)         runs initialisation parts of the script
47  *                            at prefork establishment point:
48  *     setup (pm) [1]         opens syslog
49  *                            forks for server
50  *                [2]         exits
51  *
52  *        server (pm) [1]     [fd0: null],
53  *                            [fd[12]: fd2-from-outer]
54  *                            setsid
55  *                            right away, forks init monitor
56  *                    [2]     closes outer caller fds and call(fake)
57  *        [server (pm)]       fd[012]: null
58  *                            other fds: listener, syslog
59  *                            runs in loop accepting and forking,
60  *                            reaping and limiting children (incl init monitor)
61  *                            reports failures of monitors to syslog
62  *                            
63  *  [client (C wrapper)]      if client connect succeeds:
64  *                            now fd: call(client-end)
65  *                               sends message with: cmdline, env
66  *                               sends fds
67  *
68  *        [server (script)]   accepts, forks subseq monitor
69  *
70  *          monitor [1]       [fd0: null]
71  *           (init            [fd[12]: init: fd2-from-outer; subseq: null]
72  *             or             errors: init: fd2; subseq: syslog
73  *            subseq)         other fds: syslog, call(server-end)
74  *                            sends ack byte
75  *                            receives args, env, fds
76  *                            forks executor
77  *
78  *            executor        sorts out fds:
79  *                            fd0, fd1, fd2: from-outer
80  *                            close fds: call(server-end)
81  *                            retained fds: syslog
82  *
83  *                            sets cmdline, env
84  *                            runs main part of script
85  *                            exits normally
86  *
87  *          [monitor]         [fd[012]: null]
88  *                            [fd[12]: init: fd2-from-outer; subseq: null]
89  *                            [errors: init: fd2; subseq: syslog]
90  *                            reaps executor
91  *                            reports status via socket
92  *
93  *    [client (C wrapper)]    [fd0, fd1, fd2: from-outer]
94  *                            [other fd: call(client-end)]
95  *                            receives status, exits appropriately
96  *                            (if was bad signal, reports to stderr, exits 127)
97  */
98
99 #include <arpa/inet.h>
100
101 #include <uv.h>
102
103 #include "prefork.h"
104
105 const char our_name[] = "prefork-interp";
106
107 static struct sockaddr_un sockaddr_sun;
108 static FILE *call_sock;
109
110 #define ACK_BYTE '\n'
111
112 static const char *const *executor_argv;
113
114 static const char header_magic[4] = "PFI\n";
115
116 void fusagemessage(FILE *f) {
117   fprintf(f, "usage: #!/usr/bin/prefork-interp [<options>]\n");
118 }
119
120 static int laundering;
121 static struct stat initial_stab;
122
123 const struct cmdinfo cmdinfos[]= {
124   PREFORK_CMDINFOS
125   { 0, 'U',   0,                    .iassignto= &laundering,    .arg= 'U' },
126   { 0 }
127 };
128
129 void ident_addinit(void) {
130   char ident_magic[1] = { 0 };
131   sha256_update(&identsc, sizeof(ident_magic), ident_magic);
132 }
133
134 static void propagate_exit_status(int status, const char *what) {
135   int r;
136
137   if (WIFEXITED(status)) {
138     _exit(status);
139   }
140
141   if (WIFSIGNALED(status)) {
142     int sig = WTERMSIG(status);
143     const char *signame = strsignal(sig);
144     if (signame == 0) signame = "unknown signal";
145
146     if (! WCOREDUMP(status) &&
147         (sig == SIGINT ||
148          sig == SIGHUP ||
149          sig == SIGPIPE ||
150          sig == SIGKILL)) {
151       struct sigaction sa;
152       FILLZERO(sa);
153       sa.sa_handler = SIG_DFL;
154       r = sigaction(sig, &sa, 0);
155       if (r) diee("failed to reset signal handler while propagating %s",
156                   signame);
157       
158       sigset_t sset;
159       sigemptyset(&sset);
160       sigaddset(&sset, sig);
161       r = sigprocmask(SIG_UNBLOCK, &sset, 0);
162       if (r) diee("failed to reset signal block while propagating %s",
163                   signame);
164
165       raise(sig);
166       die("unexpectedly kept running after raising (to propagate) %s",
167           signame);
168     }
169
170     die("%s failed due to signal %d %s%s", what, sig, signame,
171         WCOREDUMP(status) ? " (core dumped)" : "");
172   }
173
174   die("%s failed with weird wait status %d 0x%x", what, status, status);
175 }
176
177 static __attribute((noreturn)) void die_data_overflow(void) {
178   die("cannot handle data with length >2^32");
179 }
180
181 static void prepare_data(size_t *len, char **buf,
182                          const void *data, size_t dl) {
183   if (len) {
184     if (dl >= SIZE_MAX - *len)
185       die_data_overflow();
186     *len += dl;
187   }
188   if (buf) {
189     memcpy(*buf, data, dl);
190     *buf += dl;
191   }
192 }
193   
194 static void prepare_length(size_t *len, char **buf, size_t dl_sz) {
195   if (dl_sz > UINT32_MAX) die_data_overflow();
196   uint32_t dl = htonl(dl_sz);
197   prepare_data(len, buf, &dl, sizeof(dl));
198 }
199
200 static void prepare_string(size_t *len, char **buf, const char *s) {
201   size_t sl = strlen(s);
202   prepare_data(len, buf, s, sl+1);
203 }
204
205 static void prepare_message(size_t *len, char **buf) {
206   const char *s;
207
208   const char *const *p = (void*)environ;
209   while ((s = *p++)) {
210     if (strchr(s, '='))
211       prepare_string(len, buf, s);
212   }
213
214   prepare_string(len, buf, "");
215
216   p = executor_argv;
217   while ((s = *p++))
218     prepare_string(len, buf, s);
219 }
220
221 static void send_fd(int payload_fd) {
222   int via_fd = fileno(call_sock);
223
224   union {
225     struct cmsghdr align;
226     char buf[CMSG_SPACE(sizeof(payload_fd))];
227   } cmsg_buf;
228
229   struct msghdr msg;
230   FILLZERO(msg);
231   FILLZERO(cmsg_buf);
232
233   char dummy_byte = 0;
234   struct iovec iov;
235   FILLZERO(iov);
236   iov.iov_base = &dummy_byte;
237   iov.iov_len = 1;
238
239   msg.msg_name = 0;
240   msg.msg_iov = &iov;
241   msg.msg_iovlen = 1;
242   msg.msg_control = cmsg_buf.buf;
243   msg.msg_controllen = sizeof(cmsg_buf.buf);
244
245   struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
246   cmsg->cmsg_level = SOL_SOCKET;
247   cmsg->cmsg_type = SCM_RIGHTS;
248   cmsg->cmsg_len = CMSG_LEN(sizeof(payload_fd));
249   *(int*)CMSG_DATA(cmsg) = payload_fd;
250
251   msg.msg_controllen = sizeof(cmsg_buf.buf);
252
253   for (;;) {
254     ssize_t r = sendmsg(via_fd, &msg, 0);
255     if (r == -1) {
256       if (errno == EINTR) continue;
257       diee("send fd");
258     }
259     assert(r == 1);
260     break;
261   }
262 }
263
264 static void send_request(void) {
265   // Sending these first makes it easier for the script to
266   // use buffered IO for the message.
267   send_fd(0);
268   send_fd(1);
269   send_fd(2);
270
271   size_t len = 0;
272   prepare_message(&len, 0);
273
274   size_t tlen = len + 4;
275   char *m = xmalloc(tlen);
276   char *p = m;
277   prepare_length(0, &p, len);
278   prepare_message(0, &p);
279   assert(p == m + tlen);
280
281   ssize_t sr = fwrite(m, tlen, 1, call_sock);
282   if (sr != 1) diee("write request (buffer)");
283
284   if (fflush(call_sock)) diee("write request");
285 }
286
287 static FILE *call_sock_from_fd(int fd) {
288   int r;
289
290   FILE *call_sock = fdopen(fd, "r+");
291   if (!call_sock) diee("fdopen socket");
292
293   r = setvbuf(call_sock, 0, _IONBF, 0);
294   if (r) die("setvbuf socket");
295
296   return call_sock;
297 }
298
299 static bool was_eof(FILE *call_sock) {
300   return feof(call_sock) || errno==ECONNRESET;
301 }
302
303 // Returns -1 on EOF
304 static int protocol_read_maybe(void *data, size_t sz) {
305   if (!sz) return 0;
306   size_t sr = fread(data, sz, 1, call_sock);
307   if (sr != 1) {
308     if (was_eof(call_sock)) return -1;
309     diee("read() on monitor call socket (%zd)", sz);
310   }
311   return 0;
312 }
313
314 static void protocol_read(void *data, size_t sz) {
315   if (protocol_read_maybe(data, sz) < 0)
316     die("monitor process quit unexpectedly");
317 }
318
319 // Returns 0 if OK, error msg if peer was garbage.
320 static const char *read_greeting(void) {
321   char got_magic[sizeof(header_magic)];
322
323   if (protocol_read_maybe(&got_magic, sizeof(got_magic)) < 0)
324     return "initial monitor process quit";
325
326   if (memcmp(got_magic, header_magic, sizeof(header_magic)))
327     die("got unexpected protocol magic 0x%02x%02x%02x%02x",
328         got_magic[0], got_magic[1], got_magic[2], got_magic[3]);
329
330   uint32_t xdata_len;
331   protocol_read(&xdata_len, sizeof(xdata_len));
332   void *xdata = xmalloc(xdata_len);
333   protocol_read(xdata, xdata_len);
334
335   return 0;
336 }
337
338 // Returns: call(client-end), or 0 to mean "is garbage"
339 // find_socket_path must have been called
340 static FILE *connect_existing(void) {
341   int r;
342   int fd = -1;
343
344   fd = socket(AF_UNIX, SOCK_STREAM, 0);
345   if (fd==-1) diee("socket() for client");
346
347   socklen_t salen = sizeof(sockaddr_sun);
348   r = connect(fd, (const struct sockaddr*)&sockaddr_sun, salen);
349   if (r==-1) {
350     if (errno==ECONNREFUSED || errno==ENOENT) goto x_garbage;
351     diee("connect() %s", socket_path);
352   }
353
354   call_sock = call_sock_from_fd(fd);
355   fd = -1;
356
357   if (read_greeting())
358     goto x_garbage;
359
360   return call_sock;
361
362  x_garbage:
363   if (call_sock) { fclose(call_sock); call_sock=0; }
364   if (fd >= 0) close(fd);
365   return 0;
366 }
367
368 static void watcher_cb_stdin(uv_poll_t *handle, int status, int events) {
369   char c;
370   int r;
371   
372   if ((errno = -status)) diee("watcher: poll stdin");
373   for (;;) {
374     r= read(0, &c, 1);
375     if (r!=-1) _exit(0);
376     if (!(errno==EINTR || errno==EWOULDBLOCK || errno==EAGAIN))
377       diee("watcher: read sentinel stdin");
378   }
379 }
380
381 static void watcher_cb_sockpath(uv_fs_event_t *handle, const char *filename,
382                                 int events, int status) {
383   int r;
384   struct stat now_stab;
385
386   if ((errno = -status)) diee("watcher: poll stdin");
387   for (;;) {
388     r= stat(socket_path, &now_stab);
389     if (r==-1) {
390       if (errno==ENOENT) _exit(0);
391       if (errno==EINTR) continue;
392       diee("stat socket: %s", socket_path);
393     }
394     if (!(now_stab.st_dev == initial_stab.st_dev &&
395           now_stab.st_ino == initial_stab.st_ino))
396       _exit(0);
397   }
398 }
399
400 // On entry, stderr is still inherited, but 0 and 1 are the pipes
401 static __attribute__((noreturn))
402 void become_watcher(void) {
403   uv_loop_t loop;
404   uv_poll_t uvhandle_stdin;
405   uv_fs_event_t uvhandle_sockpath;
406   int r;
407
408   nonblock(0);
409
410   errno= -uv_loop_init(&loop);
411   if (errno) diee("watcher: uv_loop_init");
412
413   errno= -uv_poll_init(&loop, &uvhandle_stdin, 0);
414   if (errno) diee("watcher: uv_poll_init");
415   errno= -uv_poll_start(&uvhandle_stdin,
416                         UV_READABLE | UV_WRITABLE | UV_DISCONNECT,
417                         watcher_cb_stdin);
418   if (errno) diee("watcher: uv_poll_start");
419
420   errno= -uv_fs_event_init(&loop, &uvhandle_sockpath);
421   if (errno) diee("watcher: uv_fs_event_init");
422
423   errno= -uv_fs_event_start(&uvhandle_sockpath, watcher_cb_sockpath,
424                             socket_path, 0);
425   if (errno) diee("watcher: uv_fs_event_start");
426
427   // OK everything is set up, let us daemonise
428   if (dup2(1,2) != 2) diee("watcher: set daemonised stderr");
429   r= setvbuf(stderr, 0, _IOLBF, BUFSIZ);
430   if (r) diee("watcher: setvbuf stderr");
431
432   pid_t child = fork();
433   if (child == (pid_t)-1) diee("watcher: fork");
434   if (child) _exit(0);
435
436   if (setsid() == (pid_t)-1) diee("watcher: setsid");
437
438   r= uv_run(&loop, UV_RUN_DEFAULT);
439   die("uv_run returned (%d)", r);
440 }
441
442 static __attribute__((noreturn))
443 void become_setup(int sfd, int fake_pair[2],
444                   int watcher_stdin, int watcher_stderr) {
445   close(fake_pair[0]);
446   int call_fd = fake_pair[1];
447
448   int null_0 = open("/dev/null", O_RDONLY);  if (null_0 < 0) diee("open null");
449   if (dup2(null_0, 0)) diee("dup2 /dev/null onto stdin");
450   close(null_0);
451   if (dup2(2, 1) != 1) die("dup2 stderr onto stdout");
452
453   nonblock(sfd);
454
455   // Extension could work like this:
456   //
457   // We advertise a new protocol (perhaps one which is nearly entirely
458   // different after the connect) by putting a name for it comma-separated
459   // next to "v1".  Simple extension can be done by having the script
460   // side say something about it in the ack xdata, which we currently ignore.
461   putenv(m_asprintf("PREFORK_INTERP=v1 %d,%d,%d,%d",
462                     sfd, call_fd, watcher_stdin, watcher_stderr));
463
464   execvp(executor_argv[0], (char**)executor_argv);
465   diee("execute %s", executor_argv[0]);
466 }
467
468 static void connect_or_spawn(void) {
469   int r;
470
471   call_sock = connect_existing();
472   if (call_sock) return;
473
474   int lockfd = acquire_lock();
475   call_sock = connect_existing();
476   if (call_sock) { close(lockfd); return; }
477
478   // We must start a fresh one, and we hold the lock
479
480   r = unlink(socket_path);
481   if (r<0 && errno!=ENOENT)
482     diee("failed to remove stale socket %s", socket_path);
483
484   int sfd = socket(AF_UNIX, SOCK_STREAM, 0);
485   if (sfd<0) diee("socket() for new listener");
486
487   socklen_t salen = sizeof(sockaddr_sun);
488   r= bind(sfd, (const struct sockaddr*)&sockaddr_sun, salen);
489   if (r<0) diee("bind() on new listener");
490
491   r= stat(socket_path, &initial_stab);
492   if (r<0) diee("stat() fresh socket");
493
494   // We never want callers to get ECONNREFUSED.  But:
495   // There is a race here: from my RTFM they may get ECONNREFUSED
496   // if they try between our bind() and listen().  But if they do, they'll
497   // acquire the lock (serialising with us) and retry, and then it will work.
498   r = listen(sfd, INT_MAX);
499   if (r<0) diee("listen() for new listener");
500
501   // Fork watcher
502
503   int watcher_stdin[2];
504   int watcher_stderr[2];
505   if (pipe(watcher_stdin) || pipe(watcher_stderr))
506     diee("pipe() for socket inode watcher");
507
508   pid_t watcher = fork();
509   if (watcher == (pid_t)-1) diee("fork for watcher");
510   if (!watcher) {
511     close(sfd);
512     close(lockfd);
513     close(watcher_stdin[1]);
514     close(watcher_stderr[0]);
515     if (dup2(watcher_stdin[0], 0) != 0 ||
516         dup2(watcher_stderr[1], 1) != 1)
517       diee("initial dup2() for watcher");
518     close(watcher_stdin[0]);
519     close(watcher_stderr[1]);
520     become_watcher();
521   }
522
523   close(watcher_stdin[0]);
524   close(watcher_stderr[1]);
525   nonblock(watcher_stderr[0]);
526
527   // Fork setup
528
529   int fake_pair[2];
530   r = socketpair(AF_UNIX, SOCK_STREAM, 0, fake_pair);
531   if (r<0) diee("socketpair() for fake initial connection");
532
533   pid_t setup_pid = fork();
534   if (setup_pid == (pid_t)-1) diee("fork for spawn setup");
535   if (!setup_pid) become_setup(sfd, fake_pair,
536                                watcher_stdin[1], watcher_stderr[0]);
537   close(fake_pair[1]);
538   close(sfd);
539
540   call_sock = call_sock_from_fd(fake_pair[0]);
541
542   int status;
543   pid_t got = waitpid(setup_pid, &status, 0);
544   if (got == (pid_t)-1) diee("waitpid setup [%ld]", (long)setup_pid);
545   if (got != setup_pid) diee("waitpid setup [%ld] gave [%ld]!",
546                              (long)setup_pid, (long)got);
547   if (status != 0) propagate_exit_status(status, "setup");
548
549   const char *emsg = read_greeting();
550   if (emsg) die("setup failed: %s", emsg);
551
552   close(lockfd);
553   return;
554 }
555
556 static void make_executor_argv(const char *const *argv) {
557   switch (laundering) {
558   case 'U': break;
559   default: die("need -U (specifying unlaundered argument handling)");
560   }
561
562   const char *arg;
563   #define EACH_NEW_ARG(EACH) {                  \
564     arg = interp; { EACH }                      \
565     if ((arg = script)) { EACH }                \
566     const char *const *walk = argv;             \
567     while ((arg = *walk++)) { EACH }            \
568   }
569
570   size_t count = 1;
571   EACH_NEW_ARG( (void)arg; count++; );
572
573   const char **out = calloc(count, sizeof(char*));
574   executor_argv = (const char* const*)out;
575   if (!executor_argv) diee("allocate for arguments");
576
577   EACH_NEW_ARG( *out++ = arg; );
578   *out++ = 0;
579 }  
580
581 int main(int argc_unused, const char *const *argv) {
582   process_opts(&argv);
583
584   // Now we have
585   //  - possibly interp
586   //  - possibly script
587   //  - remaining args
588   // which ought to be passed on to the actual executor.
589   make_executor_argv(argv);
590
591   find_socket_path();
592   FILLZERO(sockaddr_sun);
593   sockaddr_sun.sun_family = AF_UNIX;
594   assert(strlen(socket_path) <= sizeof(sockaddr_sun.sun_path));
595   strncpy(sockaddr_sun.sun_path, socket_path, sizeof(sockaddr_sun.sun_path));
596
597   connect_or_spawn();
598
599   // We're committed now, send the request (or bail out)
600   send_request();
601
602   uint32_t status;
603   protocol_read(&status, sizeof(status));
604
605   status = ntohl(status);
606   if (status > INT_MAX) die("status 0x%lx does not fit in an int",
607                             (unsigned long)status);
608
609   propagate_exit_status(status, "invocation");
610 }