2 * "Interpreter" that you can put in #! like this
3 * #!/usr/bin/prefork-interp [<options>] <interpreter>
6 * prefork-interp [<option> ..] <interpreter> [<script> [<args> ...]]
7 * prefork-interp [<option>,..],<interpreter> <script> [<args> ...]
8 * prefork-interp '[<option> ..] <interpreter>' <script> [<args> ...]
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
18 * client (C wrapper) connects to server
19 * (including reading ack byte)
21 * === acquires lock ===
22 * makes new listening socket
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)
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
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
44 * possibly clean env, argv
46 * setup (script) runs initialisation parts of the script
47 * at prefork establishment point:
48 * setup (pm) [1] opens syslog
52 * server (pm) [1] [fd0: null],
53 * [fd[12]: fd2-from-outer]
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
63 * [client (C wrapper)] if client connect succeeds:
64 * now fd: call(client-end)
65 * sends message with: cmdline, env
68 * [server (script)] accepts, forks subseq monitor
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)
75 * receives args, env, fds
78 * executor sorts out fds:
79 * fd0, fd1, fd2: from-outer
80 * close fds: call(server-end)
81 * retained fds: syslog
84 * runs main part of script
87 * [monitor] [fd[012]: null]
88 * [fd[12]: init: fd2-from-outer; subseq: null]
89 * [errors: init: fd2; subseq: syslog]
91 * reports status via socket
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)
99 #include <arpa/inet.h>
105 const char our_name[] = "prefork-interp";
107 static struct sockaddr_un sockaddr_sun;
108 static FILE *call_sock;
110 #define ACK_BYTE '\n'
112 static const char *const *executor_argv;
114 static const char header_magic[4] = "PFI\n";
116 void fusagemessage(FILE *f) {
117 fprintf(f, "usage: #!/usr/bin/prefork-interp [<options>]\n");
120 static int laundering;
121 static int max_sockets = 100; // maximum entries in the run dir is 2x this
123 static struct stat initial_stab;
125 const struct cmdinfo cmdinfos[]= {
127 { 0, 'U', 0, .iassignto= &laundering, .arg= 'U' },
131 void ident_addinit(void) {
132 char ident_magic[1] = { 0 };
133 sha256_update(&identsc, sizeof(ident_magic), ident_magic);
136 static void propagate_exit_status(int status, const char *what) {
139 if (WIFEXITED(status)) {
143 if (WIFSIGNALED(status)) {
144 int sig = WTERMSIG(status);
145 const char *signame = strsignal(sig);
146 if (signame == 0) signame = "unknown signal";
148 if (! WCOREDUMP(status) &&
155 sa.sa_handler = SIG_DFL;
156 r = sigaction(sig, &sa, 0);
157 if (r) diee("failed to reset signal handler while propagating %s",
162 sigaddset(&sset, sig);
163 r = sigprocmask(SIG_UNBLOCK, &sset, 0);
164 if (r) diee("failed to reset signal block while propagating %s",
168 die("unexpectedly kept running after raising (to propagate) %s",
172 die("%s failed due to signal %d %s%s", what, sig, signame,
173 WCOREDUMP(status) ? " (core dumped)" : "");
176 die("%s failed with weird wait status %d 0x%x", what, status, status);
184 static int preclean_entry_compar_name(const void *av, const void *bv) {
185 const PrecleanEntry *a = av;
186 const PrecleanEntry *b = bv;
187 return strcmp(a->name_hash, b->name_hash);
190 static int preclean_entry_compar_atime(const void *av, const void *bv) {
191 const PrecleanEntry *ae = av; time_t a = ae->atime;
192 const PrecleanEntry *be = bv; time_t b = be->atime;
197 static time_t preclean_stat_atime(const char *s_path) {
199 int r= lstat(s_path, &stab);
201 if (errno!=ENOENT) diee("pre-cleanup: stat socket (%s)", s_path);
204 return stab.st_atime;
207 static void preclean(void) {
208 DIR *dir = opendir(run_base);
210 if (errno == ENOENT) return;
211 diee("pre-cleanup: open run dir (%s)", run_base);
214 PrecleanEntry *entries=0;
215 size_t avail_entries=0;
216 size_t used_entries=0;
219 while ((errno = 0, de = readdir(dir))) {
220 char c0 = de->d_name[0];
221 if (!(c0 == 'l' || c0 == 's')) continue;
222 char *name_hash = m_asprintf("%s", de->d_name+1);
223 char *s_path = m_asprintf("%s/s%s", run_base, name_hash);
224 time_t atime = preclean_stat_atime(s_path);
226 if (avail_entries == used_entries) {
227 assert(avail_entries < INT_MAX / 4 / sizeof(PrecleanEntry));
230 entries = realloc(entries, avail_entries * sizeof(PrecleanEntry));
232 entries[used_entries].name_hash = name_hash;
233 entries[used_entries].atime = atime;
236 if (errno) diee("pre-cleanup: read run dir (%s)", run_base);
238 // First we dedupe (after sorting by path)
239 qsort(entries, used_entries, sizeof(PrecleanEntry),
240 preclean_entry_compar_name);
241 PrecleanEntry *p, *q;
242 for (p=entries, q=entries; p < entries + used_entries; p++) {
243 if (q > entries && !strcmp(p->name_hash, (q-1)->name_hash))
247 used_entries = q - entries;
249 // Now maybe delete some things
251 // Actually this has an off-by-one error since we are about
252 // to create a socket, so the actual number of sockets is one more.
253 // But, *actually*, since there might be multiple of us running at once,
254 // we might have even more than that. This doesn't really matter.
255 if (used_entries > max_sockets) {
256 qsort(entries, used_entries, sizeof(PrecleanEntry),
257 preclean_entry_compar_atime);
258 for (p=entries; p < entries + max_sockets; p++) {
259 char *l_path = m_asprintf("%s/l%s", run_base, p->name_hash);
260 char *s_path = m_asprintf("%s/s%s", run_base, p->name_hash);
261 int lock_fd = flock_file(l_path);
262 // Recheck atime - we might have raced!
263 time_t atime = preclean_stat_atime(s_path);
264 if (atime == p->atime) {
265 // Raced. This will leave use deleting too few things. Whatever.
267 int r= unlink(s_path);
268 if (r && errno!=ENOENT) diee("preclean: delete stale (%s)", s_path);
270 if (r) diee("preclean: delete stale lock (%s)", s_path);
271 // NB we don't hold the lock any more now.
279 for (p=entries; p < entries + used_entries; p++)
284 static __attribute((noreturn)) void die_data_overflow(void) {
285 die("cannot handle data with length >2^32");
288 static void prepare_data(size_t *len, char **buf,
289 const void *data, size_t dl) {
291 if (dl >= SIZE_MAX - *len)
296 memcpy(*buf, data, dl);
301 static void prepare_length(size_t *len, char **buf, size_t dl_sz) {
302 if (dl_sz > UINT32_MAX) die_data_overflow();
303 uint32_t dl = htonl(dl_sz);
304 prepare_data(len, buf, &dl, sizeof(dl));
307 static void prepare_string(size_t *len, char **buf, const char *s) {
308 size_t sl = strlen(s);
309 prepare_data(len, buf, s, sl+1);
312 static void prepare_message(size_t *len, char **buf) {
315 const char *const *p = (void*)environ;
318 prepare_string(len, buf, s);
321 prepare_string(len, buf, "");
325 prepare_string(len, buf, s);
328 static void send_fd(int payload_fd) {
329 int via_fd = fileno(call_sock);
332 struct cmsghdr align;
333 char buf[CMSG_SPACE(sizeof(payload_fd))];
343 iov.iov_base = &dummy_byte;
349 msg.msg_control = cmsg_buf.buf;
350 msg.msg_controllen = sizeof(cmsg_buf.buf);
352 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
353 cmsg->cmsg_level = SOL_SOCKET;
354 cmsg->cmsg_type = SCM_RIGHTS;
355 cmsg->cmsg_len = CMSG_LEN(sizeof(payload_fd));
356 *(int*)CMSG_DATA(cmsg) = payload_fd;
358 msg.msg_controllen = sizeof(cmsg_buf.buf);
361 ssize_t r = sendmsg(via_fd, &msg, 0);
363 if (errno == EINTR) continue;
371 static void send_request(void) {
372 // Sending these first makes it easier for the script to
373 // use buffered IO for the message.
379 prepare_message(&len, 0);
381 size_t tlen = len + 4;
382 char *m = xmalloc(tlen);
384 prepare_length(0, &p, len);
385 prepare_message(0, &p);
386 assert(p == m + tlen);
388 ssize_t sr = fwrite(m, tlen, 1, call_sock);
389 if (sr != 1) diee("write request (buffer)");
391 if (fflush(call_sock)) diee("write request");
394 static FILE *call_sock_from_fd(int fd) {
397 FILE *call_sock = fdopen(fd, "r+");
398 if (!call_sock) diee("fdopen socket");
400 r = setvbuf(call_sock, 0, _IONBF, 0);
401 if (r) die("setvbuf socket");
406 static bool was_eof(FILE *call_sock) {
407 return feof(call_sock) || errno==ECONNRESET;
411 static int protocol_read_maybe(void *data, size_t sz) {
413 size_t sr = fread(data, sz, 1, call_sock);
415 if (was_eof(call_sock)) return -1;
416 diee("read() on monitor call socket (%zd)", sz);
421 static void protocol_read(void *data, size_t sz) {
422 if (protocol_read_maybe(data, sz) < 0)
423 die("monitor process quit unexpectedly");
426 // Returns 0 if OK, error msg if peer was garbage.
427 static const char *read_greeting(void) {
428 char got_magic[sizeof(header_magic)];
430 if (protocol_read_maybe(&got_magic, sizeof(got_magic)) < 0)
431 return "initial monitor process quit";
433 if (memcmp(got_magic, header_magic, sizeof(header_magic)))
434 die("got unexpected protocol magic 0x%02x%02x%02x%02x",
435 got_magic[0], got_magic[1], got_magic[2], got_magic[3]);
438 protocol_read(&xdata_len, sizeof(xdata_len));
439 void *xdata = xmalloc(xdata_len);
440 protocol_read(xdata, xdata_len);
445 // Returns: call(client-end), or 0 to mean "is garbage"
446 // find_socket_path must have been called
447 static FILE *connect_existing(void) {
451 fd = socket(AF_UNIX, SOCK_STREAM, 0);
452 if (fd==-1) diee("socket() for client");
454 socklen_t salen = sizeof(sockaddr_sun);
455 r = connect(fd, (const struct sockaddr*)&sockaddr_sun, salen);
457 if (errno==ECONNREFUSED || errno==ENOENT) goto x_garbage;
458 diee("connect() %s", socket_path);
461 call_sock = call_sock_from_fd(fd);
470 if (call_sock) { fclose(call_sock); call_sock=0; }
471 if (fd >= 0) close(fd);
475 static void watcher_cb_stdin(uv_poll_t *handle, int status, int events) {
479 if ((errno = -status)) diee("watcher: poll stdin");
483 if (!(errno==EINTR || errno==EWOULDBLOCK || errno==EAGAIN))
484 diee("watcher: read sentinel stdin");
488 static void watcher_cb_sockpath(uv_fs_event_t *handle, const char *filename,
489 int events, int status) {
491 struct stat now_stab;
493 if ((errno = -status)) diee("watcher: poll stdin");
495 r= stat(socket_path, &now_stab);
497 if (errno==ENOENT) _exit(0);
498 if (errno==EINTR) continue;
499 diee("stat socket: %s", socket_path);
501 if (!stabs_same_inode(&now_stab, &initial_stab))
506 // On entry, stderr is still inherited, but 0 and 1 are the pipes
507 static __attribute__((noreturn))
508 void become_watcher(void) {
510 uv_poll_t uvhandle_stdin;
511 uv_fs_event_t uvhandle_sockpath;
516 errno= -uv_loop_init(&loop);
517 if (errno) diee("watcher: uv_loop_init");
519 errno= -uv_poll_init(&loop, &uvhandle_stdin, 0);
520 if (errno) diee("watcher: uv_poll_init");
521 errno= -uv_poll_start(&uvhandle_stdin,
522 UV_READABLE | UV_WRITABLE | UV_DISCONNECT,
524 if (errno) diee("watcher: uv_poll_start");
526 errno= -uv_fs_event_init(&loop, &uvhandle_sockpath);
527 if (errno) diee("watcher: uv_fs_event_init");
529 errno= -uv_fs_event_start(&uvhandle_sockpath, watcher_cb_sockpath,
531 if (errno) diee("watcher: uv_fs_event_start");
533 // OK everything is set up, let us daemonise
534 if (dup2(1,2) != 2) diee("watcher: set daemonised stderr");
535 r= setvbuf(stderr, 0, _IOLBF, BUFSIZ);
536 if (r) diee("watcher: setvbuf stderr");
538 pid_t child = fork();
539 if (child == (pid_t)-1) diee("watcher: fork");
542 if (setsid() == (pid_t)-1) diee("watcher: setsid");
544 r= uv_run(&loop, UV_RUN_DEFAULT);
545 die("uv_run returned (%d)", r);
548 static __attribute__((noreturn))
549 void become_setup(int sfd, int fake_pair[2],
550 int watcher_stdin, int watcher_stderr) {
552 int call_fd = fake_pair[1];
554 int null_0 = open("/dev/null", O_RDONLY); if (null_0 < 0) diee("open null");
555 if (dup2(null_0, 0)) diee("dup2 /dev/null onto stdin");
557 if (dup2(2, 1) != 1) die("dup2 stderr onto stdout");
561 // Extension could work like this:
563 // We advertise a new protocol (perhaps one which is nearly entirely
564 // different after the connect) by putting a name for it comma-separated
565 // next to "v1". Simple extension can be done by having the script
566 // side say something about it in the ack xdata, which we currently ignore.
567 putenv(m_asprintf("PREFORK_INTERP=v1 %d,%d,%d,%d",
568 sfd, call_fd, watcher_stdin, watcher_stderr));
570 execvp(executor_argv[0], (char**)executor_argv);
571 diee("execute %s", executor_argv[0]);
574 static void connect_or_spawn(void) {
577 call_sock = connect_existing();
578 if (call_sock) return;
580 // We're going to make a new one, so clean out old ones
583 int lockfd = acquire_lock();
584 call_sock = connect_existing();
585 if (call_sock) { close(lockfd); return; }
587 // We must start a fresh one, and we hold the lock
589 r = unlink(socket_path);
590 if (r<0 && errno!=ENOENT)
591 diee("failed to remove stale socket %s", socket_path);
593 int sfd = socket(AF_UNIX, SOCK_STREAM, 0);
594 if (sfd<0) diee("socket() for new listener");
596 socklen_t salen = sizeof(sockaddr_sun);
597 r= bind(sfd, (const struct sockaddr*)&sockaddr_sun, salen);
598 if (r<0) diee("bind() on new listener");
600 r= stat(socket_path, &initial_stab);
601 if (r<0) diee("stat() fresh socket");
603 // We never want callers to get ECONNREFUSED. But:
604 // There is a race here: from my RTFM they may get ECONNREFUSED
605 // if they try between our bind() and listen(). But if they do, they'll
606 // acquire the lock (serialising with us) and retry, and then it will work.
607 r = listen(sfd, INT_MAX);
608 if (r<0) diee("listen() for new listener");
612 int watcher_stdin[2];
613 int watcher_stderr[2];
614 if (pipe(watcher_stdin) || pipe(watcher_stderr))
615 diee("pipe() for socket inode watcher");
617 pid_t watcher = fork();
618 if (watcher == (pid_t)-1) diee("fork for watcher");
622 close(watcher_stdin[1]);
623 close(watcher_stderr[0]);
624 if (dup2(watcher_stdin[0], 0) != 0 ||
625 dup2(watcher_stderr[1], 1) != 1)
626 diee("initial dup2() for watcher");
627 close(watcher_stdin[0]);
628 close(watcher_stderr[1]);
632 close(watcher_stdin[0]);
633 close(watcher_stderr[1]);
634 nonblock(watcher_stderr[0]);
639 r = socketpair(AF_UNIX, SOCK_STREAM, 0, fake_pair);
640 if (r<0) diee("socketpair() for fake initial connection");
642 pid_t setup_pid = fork();
643 if (setup_pid == (pid_t)-1) diee("fork for spawn setup");
644 if (!setup_pid) become_setup(sfd, fake_pair,
645 watcher_stdin[1], watcher_stderr[0]);
649 call_sock = call_sock_from_fd(fake_pair[0]);
652 pid_t got = waitpid(setup_pid, &status, 0);
653 if (got == (pid_t)-1) diee("waitpid setup [%ld]", (long)setup_pid);
654 if (got != setup_pid) diee("waitpid setup [%ld] gave [%ld]!",
655 (long)setup_pid, (long)got);
656 if (status != 0) propagate_exit_status(status, "setup");
658 const char *emsg = read_greeting();
659 if (emsg) die("setup failed: %s", emsg);
665 static void make_executor_argv(const char *const *argv) {
666 switch (laundering) {
668 default: die("need -U (specifying unlaundered argument handling)");
672 #define EACH_NEW_ARG(EACH) { \
673 arg = interp; { EACH } \
674 if ((arg = script)) { EACH } \
675 const char *const *walk = argv; \
676 while ((arg = *walk++)) { EACH } \
680 EACH_NEW_ARG( (void)arg; count++; );
682 const char **out = calloc(count, sizeof(char*));
683 executor_argv = (const char* const*)out;
684 if (!executor_argv) diee("allocate for arguments");
686 EACH_NEW_ARG( *out++ = arg; );
690 int main(int argc_unused, const char *const *argv) {
697 // which ought to be passed on to the actual executor.
698 make_executor_argv(argv);
701 FILLZERO(sockaddr_sun);
702 sockaddr_sun.sun_family = AF_UNIX;
703 assert(strlen(socket_path) <= sizeof(sockaddr_sun.sun_path));
704 strncpy(sockaddr_sun.sun_path, socket_path, sizeof(sockaddr_sun.sun_path));
708 // We're committed now, send the request (or bail out)
712 protocol_read(&status, sizeof(status));
714 status = ntohl(status);
715 if (status > INT_MAX) die("status 0x%lx does not fit in an int",
716 (unsigned long)status);
718 propagate_exit_status(status, "invocation");