chiark / gitweb /
prefork-interp: wip, socket watch, etc.
[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   char *m = xmalloc(len + 4);
275   char *p = m;
276   prepare_length(0, &p, len);
277   prepare_message(0, &p);
278   assert(p == m + len + 4);
279
280   ssize_t sr = fwrite(p, len, 1, call_sock);
281   if (sr != 1) diee("write request (buffer)");
282
283   if (fflush(call_sock)) diee("write request");
284 }
285
286 static FILE *call_sock_from_fd(int fd) {
287   int r;
288
289   FILE *call_sock = fdopen(fd, "r+");
290   if (!call_sock) diee("fdopen socket");
291
292   r = setvbuf(call_sock, 0, _IONBF, 0);
293   if (r) die("setvbuf socket");
294
295   return call_sock;
296 }
297
298 static bool was_eof(FILE *call_sock) {
299   return feof(call_sock) || errno==ECONNRESET;
300 }
301
302 // Returns -1 on EOF
303 static int protocol_read_maybe(void *data, size_t sz) {
304   if (!sz) return 0;
305   size_t sr = fread(data, sz, 1, call_sock);
306   if (sr != 1) {
307     if (was_eof(call_sock)) return -1;
308     diee("read() on monitor call socket (%zd)", sz);
309   }
310   return 0;
311 }
312
313 static void protocol_read(void *data, size_t sz) {
314   if (protocol_read_maybe(data, sz) < 0)
315     die("monitor process quit unexpectedly");
316 }
317
318 // Returns 0 if OK, error msg if peer was garbage.
319 static const char *read_greeting(void) {
320   char got_magic[sizeof(header_magic)];
321
322   if (protocol_read_maybe(&got_magic, sizeof(got_magic)) < 0)
323     return "initial monitor process quit";
324
325   if (memcmp(got_magic, header_magic, sizeof(header_magic)))
326     die("got unexpected protocol magic 0x%02x%02x%02x%02x",
327         got_magic[0], got_magic[1], got_magic[2], got_magic[3]);
328
329   uint32_t xdata_len;
330   protocol_read(&xdata_len, sizeof(xdata_len));
331   void *xdata = xmalloc(xdata_len);
332   protocol_read(xdata, xdata_len);
333
334   return 0;
335 }
336
337 // Returns: call(client-end), or 0 to mean "is garbage"
338 // find_socket_path must have been called
339 static FILE *connect_existing(void) {
340   int r;
341   int fd = -1;
342
343   fd = socket(AF_UNIX, SOCK_STREAM, 0);
344   if (fd==-1) diee("socket() for client");
345
346   socklen_t salen = sizeof(sockaddr_sun);
347   r = connect(fd, (const struct sockaddr*)&sockaddr_sun, salen);
348   if (r==-1) {
349     if (errno==ECONNREFUSED || errno==ENOENT) goto x_garbage;
350     diee("connect() %s", socket_path);
351   }
352
353   call_sock = call_sock_from_fd(fd);
354   fd = -1;
355
356   if (read_greeting())
357     goto x_garbage;
358
359   return call_sock;
360
361  x_garbage:
362   if (call_sock) { fclose(call_sock); call_sock=0; }
363   if (fd >= 0) close(fd);
364   return 0;
365 }
366
367 static void watcher_cb_stdin(uv_poll_t *handle, int status, int events) {
368   char c;
369   int r;
370   
371   if ((errno = -status)) diee("watcher: poll stdin");
372   for (;;) {
373     r= read(0, &c, 1);
374     if (r!=-1) _exit(0);
375     if (!(errno==EINTR || errno==EWOULDBLOCK || errno==EAGAIN))
376       diee("watcher: read sentinel stdin");
377   }
378 }
379
380 static void watcher_cb_sockpath(uv_fs_event_t *handle, const char *filename,
381                                 int events, int status) {
382   int r;
383   struct stat now_stab;
384
385   if ((errno = -status)) diee("watcher: poll stdin");
386   for (;;) {
387     r= stat(socket_path, &now_stab);
388     if (r==-1) {
389       if (errno==ENOENT) _exit(0);
390       if (errno==EINTR) continue;
391       diee("stat socket: %s", socket_path);
392     }
393     if (!(now_stab.st_dev == initial_stab.st_dev &&
394           now_stab.st_ino == initial_stab.st_ino))
395       _exit(0);
396   }
397 }
398
399 // On entry, stderr is still inherited, but 0 and 1 are the pipes
400 static __attribute__((noreturn))
401 void become_watcher(void) {
402   uv_loop_t loop;
403   uv_poll_t uvhandle_stdin;
404   uv_fs_event_t uvhandle_sockpath;
405   int r;
406
407   if (fcntl(0, F_SETFL, O_NONBLOCK)) diee("watcher set stdin nonblocking");
408
409   errno= -uv_loop_init(&loop);
410   if (errno) diee("watcher: uv_loop_init");
411
412   errno= -uv_poll_init(&loop, &uvhandle_stdin, 0);
413   if (errno) diee("watcher: uv_poll_init");
414   errno= -uv_poll_start(&uvhandle_stdin,
415                         UV_READABLE | UV_WRITABLE | UV_DISCONNECT,
416                         watcher_cb_stdin);
417   if (errno) diee("watcher: uv_poll_start");
418
419   errno= -uv_fs_event_init(&loop, &uvhandle_sockpath);
420   if (errno) diee("watcher: uv_fs_event_init");
421
422   errno= -uv_fs_event_start(&uvhandle_sockpath, watcher_cb_sockpath,
423                             socket_path, 0);
424   if (errno) diee("watcher: uv_fs_event_start");
425
426   // OK everything is set up, let us daemonise
427   if (dup2(1,2) != 2) diee("watcher: set daemonised stderr");
428   r= setvbuf(stderr, 0, _IOLBF, BUFSIZ);
429   if (r) diee("watcher: setvbuf stderr");
430
431   pid_t child = fork();
432   if (child == (pid_t)-1) diee("watcher: fork");
433   if (child) _exit(0);
434
435   if (setsid() == (pid_t)-1) diee("watcher: setsid");
436
437   r= uv_run(&loop, UV_RUN_DEFAULT);
438   die("uv_run returned (%d)", r);
439 }
440
441 static __attribute__((noreturn))
442 void become_setup(int sfd, int fake_pair[2],
443                   int watcher_stdin, int watcher_stderr) {
444   close(fake_pair[0]);
445   int call_fd = fake_pair[1];
446
447   int null_0 = open("/dev/null", O_RDONLY);  if (null_0 < 0) diee("open null");
448   if (dup2(null_0, 0)) diee("dup2 /dev/null onto stdin");
449   if (dup2(2, 1) != 1) die("dup2 stderr onto stdout");
450
451   // Extension could work like this:
452   //
453   // We advertise a new protocol (perhaps one which is nearly entirely
454   // different after the connect) by putting a name for it comma-separated
455   // next to "v1".  Simple extension can be done by having the script
456   // side say something about it in the ack xdata, which we currently ignore.
457   putenv(m_asprintf("PREFORK_INTERP=v1 %d,%d %s",
458                     sfd, call_fd, socket_path, watcher_stdin, watcher_stderr));
459
460   execvp(executor_argv[0], (char**)executor_argv);
461   diee("execute %s", executor_argv[0]);
462 }
463
464 static void connect_or_spawn(void) {
465   int r;
466
467   call_sock = connect_existing();
468   if (call_sock) return;
469
470   int lockfd = acquire_lock();
471   call_sock = connect_existing();
472   if (call_sock) { close(lockfd); return; }
473
474   // We must start a fresh one, and we hold the lock
475
476   r = unlink(socket_path);
477   if (r<0 && errno!=ENOENT)
478     diee("failed to remove stale socket %s", socket_path);
479
480   int sfd = socket(AF_UNIX, SOCK_STREAM, 0);
481   if (sfd<0) diee("socket() for new listener");
482
483   socklen_t salen = sizeof(sockaddr_sun);
484   r= bind(sfd, (const struct sockaddr*)&sockaddr_sun, salen);
485   if (r<0) diee("bind() on new listener");
486
487   r= stat(socket_path, &initial_stab);
488   if (r<0) diee("stat() fresh socket");
489
490   // We never want callers to get ECONNREFUSED.  But:
491   // There is a race here: from my RTFM they may get ECONNREFUSED
492   // if they try between our bind() and listen().  But if they do, they'll
493   // acquire the lock (serialising with us) and retry, and then it will work.
494   r = listen(sfd, INT_MAX);
495   if (r<0) diee("listen() for new listener");
496
497   // Fork watcher
498
499   int watcher_stdin[2];
500   int watcher_stderr[2];
501   if (pipe(watcher_stdin) || pipe(watcher_stderr))
502     diee("pipe() for socket inode watcher");
503
504   pid_t watcher = fork();
505   if (watcher == (pid_t)-1) diee("fork for watcher");
506   if (!watcher) {
507     close(sfd);
508     close(lockfd);
509     close(watcher_stdin[1]);
510     close(watcher_stderr[0]);
511     if (dup2(watcher_stdin[0], 0) != 0 ||
512         dup2(watcher_stderr[1], 1) != 0)
513       diee("initial dup2() for watcher");
514     close(watcher_stdin[0]);
515     close(watcher_stderr[1]);
516     become_watcher();
517   }
518
519   close(watcher_stdin[0]);
520   close(watcher_stderr[1]);
521   if (fcntl(watcher_stderr[0], F_SETFL, O_NONBLOCK))
522     diee("parent set watcher stderr nonblocking");
523
524   // Fork setup
525
526   int fake_pair[2];
527   r = socketpair(AF_UNIX, SOCK_STREAM, 0, fake_pair);
528   if (r<0) diee("socketpair() for fake initial connection");
529
530   pid_t setup_pid = fork();
531   if (setup_pid == (pid_t)-1) diee("fork for spawn setup");
532   if (!setup_pid) become_setup(sfd, fake_pair,
533                                watcher_stdin[1], watcher_stderr[0]);
534   close(fake_pair[1]);
535   close(sfd);
536
537   call_sock = call_sock_from_fd(fake_pair[0]);
538
539   int status;
540   pid_t got = waitpid(setup_pid, &status, 0);
541   if (got == (pid_t)-1) diee("waitpid setup [%ld]", (long)setup_pid);
542   if (got != setup_pid) diee("waitpid setup [%ld] gave [%ld]!",
543                              (long)setup_pid, (long)got);
544   if (status != 0) propagate_exit_status(status, "setup");
545
546   const char *emsg = read_greeting();
547   if (emsg) die("setup failed: %s", emsg);
548
549   close(lockfd);
550   return;
551 }
552
553 static void make_executor_argv(const char *const *argv) {
554   switch (laundering) {
555   case 'U': break;
556   default: die("need -U (specifying unlaundered argument handling)");
557   }
558
559   const char *arg;
560   #define EACH_NEW_ARG(EACH) {                  \
561     arg = interp; { EACH }                      \
562     if ((arg = script)) { EACH }                \
563     const char *const *walk = argv;             \
564     while ((arg = *walk++)) { EACH }            \
565   }
566
567   size_t count = 1;
568   EACH_NEW_ARG( (void)arg; count++; );
569
570   const char **out = calloc(count, sizeof(char*));
571   executor_argv = (const char* const*)out;
572   if (!executor_argv) diee("allocate for arguments");
573
574   EACH_NEW_ARG( *out++ = arg; );
575   *out++ = 0;
576 }  
577
578 int main(int argc_unused, const char *const *argv) {
579   process_opts(&argv);
580
581   // Now we have
582   //  - possibly interp
583   //  - possibly script
584   //  - remaining args
585   // which ought to be passed on to the actual executor.
586   make_executor_argv(argv);
587
588   find_socket_path();
589   FILLZERO(sockaddr_sun);
590   sockaddr_sun.sun_family = AF_UNIX;
591   assert(strlen(socket_path) <= sizeof(sockaddr_sun.sun_path));
592   strncpy(sockaddr_sun.sun_path, socket_path, sizeof(sockaddr_sun.sun_path));
593
594   connect_or_spawn();
595
596   // We're committed now, send the request (or bail out)
597   send_request();
598
599   uint32_t status;
600   protocol_read(&status, sizeof(status));
601
602   status = ntohl(status);
603   if (status > INT_MAX) die("status 0x%lx does not fit in an int",
604                             (unsigned long)status);
605
606   propagate_exit_status(status, "invocation");
607 }