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
21 State during service execution, process parentage and key fds
27 && session leader (daemon)
28 & process group leader
33 || listen watch-err/in
34 || call (accept) \ ,------2
35 || ,-----------------------------. SERVER -----0 WATCHER(C)
36 CLIENT 2--=fdpassed>=---------. \ || && | &&
37 (C) 1--=fdpassed>=---------. \ \ || inotify
38 0--=fdpassed>=---------. \ \ \ || sockpath
53 Control flow and causality
55 | - \ / process control flow
56 ... causes mediated by fds or other IPC etc.
57 && session leader (daemon)
58 & process group leader
65 tidy up stale sockets etc.
67 create listening socket
70 | `------------------.
73 make "fake" initial call socketpair
79 | script initialisation
81 | identify fds from envirnment
87 | fork for initial service
90 | | SCRIPT [server] &&
92 | | ** accept / event loop **
94 | | accepted? \ \ \idle timeout?
97 | | _________/ watch | |watch stderr eof?
99 | SCRIPT [monitor] | | |
101 | send greeting | | |
102 read greeting | | | |
120 | | kernel closes execterm
131 Or, if client is killed
156 * client (C wrapper) connects to server
157 * (including reading ack byte)
158 * if fails or garbage
159 * === acquires lock ===
160 * makes new listening socket
161 * makes watcher pipes
162 * forks watcher and awaits
163 * makes first-instance socketpair
164 * forks setup (script, sock fds indicated in env)
165 * fd0, fd1, fd2: from-outer
166 * other fd: call(client-end)(fake)
167 * reaps setup (and reports error)
168 * (implicitly releases lock)
170 * watcher fd[012]: watcher pipes
171 * starts watch on socket path
172 * sets stderr to line buffered
173 * sets stdin to nonblocking
174 * daemonises (one fork, becomes session leader)
175 * when socket stat changes, quit
177 * setup (pre-exec) fd0: null,
178 * fd[12]: fd2-from-outer
179 * env fds: listener, call(server-end)(fake),
180 * watcher read, watcher write
182 * possibly clean env, argv
184 * setup (script) runs initialisation parts of the script
185 * at prefork establishment point:
186 * setup (pm) [1] opens syslog
190 * server (pm) [1] [fd0: null],
191 * [fd[12]: fd2-from-outer]
193 * right away, forks init monitor
194 * [2] closes outer caller fds and call(fake)
195 * [server (pm)] fd[012]: null
196 * other fds: listener, syslog
197 * runs in loop accepting and forking,
198 * reaping and limiting children (incl init monitor)
199 * reports failures of monitors to syslog
201 * [client (C wrapper)] if client connect succeeds:
202 * now fd: call(client-end)
203 * sends message with: cmdline, env
206 * [server (script)] accepts, forks subseq monitor
208 * monitor [1] [fd0: null]
209 * (init [fd[12]: init: fd2-from-outer; subseq: null]
210 * or errors: init: fd2; subseq: syslog
211 * subseq) other fds: syslog, call(server-end)
213 * receives args, env, fds
216 * executor sorts out fds:
217 * fd0, fd1, fd2: from-outer
218 * close fds: call(server-end)
219 * retained fds: syslog
222 * runs main part of script
225 * [monitor] [fd[012]: null]
226 * [fd[12]: init: fd2-from-outer; subseq: null]
227 * [errors: init: fd2; subseq: syslog]
229 * reports status via socket
231 * [client (C wrapper)] [fd0, fd1, fd2: from-outer]
232 * [other fd: call(client-end)]
233 * receives status, exits appropriately
234 * (if was bad signal, reports to stderr, exits 127)
237 #include <arpa/inet.h>
243 const char our_name[] = "prefork-interp";
245 static struct sockaddr_un sockaddr_sun;
246 static FILE *call_sock;
248 #define ACK_BYTE '\n'
250 static const char *const *executor_argv;
252 static const char header_magic[4] = "PFI\n";
254 void fusagemessage(FILE *f) {
255 fprintf(f, "usage: #!/usr/bin/prefork-interp [<options>]\n");
258 static int laundering;
259 static int max_sockets = 100; // maximum entries in the run dir is 2x this
261 static struct stat initial_stab;
263 const struct cmdinfo cmdinfos[]= {
265 { 0, 'U', 0, .iassignto= &laundering, .arg= 'U' },
269 void ident_addinit(void) {
270 char ident_magic[1] = { 0 };
271 sha256_update(&identsc, sizeof(ident_magic), ident_magic);
274 static void propagate_exit_status(int status, const char *what) {
277 if (WIFEXITED(status)) {
281 if (WIFSIGNALED(status)) {
282 int sig = WTERMSIG(status);
283 const char *signame = strsignal(sig);
284 if (signame == 0) signame = "unknown signal";
286 if (! WCOREDUMP(status) &&
293 sa.sa_handler = SIG_DFL;
294 r = sigaction(sig, &sa, 0);
295 if (r) diee("failed to reset signal handler while propagating %s",
300 sigaddset(&sset, sig);
301 r = sigprocmask(SIG_UNBLOCK, &sset, 0);
302 if (r) diee("failed to reset signal block while propagating %s",
306 die("unexpectedly kept running after raising (to propagate) %s",
310 die("%s failed due to signal %d %s%s", what, sig, signame,
311 WCOREDUMP(status) ? " (core dumped)" : "");
314 die("%s failed with weird wait status %d 0x%x", what, status, status);
322 static int preclean_entry_compar_name(const void *av, const void *bv) {
323 const PrecleanEntry *a = av;
324 const PrecleanEntry *b = bv;
325 return strcmp(a->name_hash, b->name_hash);
328 static int preclean_entry_compar_atime(const void *av, const void *bv) {
329 const PrecleanEntry *ae = av; time_t a = ae->atime;
330 const PrecleanEntry *be = bv; time_t b = be->atime;
335 static time_t preclean_stat_atime(const char *s_path) {
337 int r= lstat(s_path, &stab);
339 if (errno!=ENOENT) diee("pre-cleanup: stat socket (%s)", s_path);
342 return stab.st_atime;
345 static void preclean(void) {
346 DIR *dir = opendir(run_base);
348 if (errno == ENOENT) return;
349 diee("pre-cleanup: open run dir (%s)", run_base);
352 PrecleanEntry *entries=0;
353 size_t avail_entries=0;
354 size_t used_entries=0;
357 while ((errno = 0, de = readdir(dir))) {
358 char c0 = de->d_name[0];
359 if (!(c0 == 'l' || c0 == 's')) continue;
360 char *name_hash = m_asprintf("%s", de->d_name+1);
361 char *s_path = m_asprintf("%s/s%s", run_base, name_hash);
362 time_t atime = preclean_stat_atime(s_path);
364 if (avail_entries == used_entries) {
365 assert(avail_entries < INT_MAX / 4 / sizeof(PrecleanEntry));
368 entries = realloc(entries, avail_entries * sizeof(PrecleanEntry));
370 entries[used_entries].name_hash = name_hash;
371 entries[used_entries].atime = atime;
374 if (errno) diee("pre-cleanup: read run dir (%s)", run_base);
376 // First we dedupe (after sorting by path)
377 qsort(entries, used_entries, sizeof(PrecleanEntry),
378 preclean_entry_compar_name);
379 PrecleanEntry *p, *q;
380 for (p=entries, q=entries; p < entries + used_entries; p++) {
381 if (q > entries && !strcmp(p->name_hash, (q-1)->name_hash))
385 used_entries = q - entries;
387 // Now maybe delete some things
389 // Actually this has an off-by-one error since we are about
390 // to create a socket, so the actual number of sockets is one more.
391 // But, *actually*, since there might be multiple of us running at once,
392 // we might have even more than that. This doesn't really matter.
393 if (used_entries > max_sockets) {
394 qsort(entries, used_entries, sizeof(PrecleanEntry),
395 preclean_entry_compar_atime);
396 for (p=entries; p < entries + max_sockets; p++) {
397 char *l_path = m_asprintf("%s/l%s", run_base, p->name_hash);
398 char *s_path = m_asprintf("%s/s%s", run_base, p->name_hash);
399 int lock_fd = flock_file(l_path);
400 // Recheck atime - we might have raced!
401 time_t atime = preclean_stat_atime(s_path);
402 if (atime != p->atime) {
403 // Raced. This will leave use deleting too few things. Whatever.
405 int r= unlink(s_path);
406 if (r && errno!=ENOENT) diee("preclean: delete stale (%s)", s_path);
408 if (r) diee("preclean: delete stale lock (%s)", s_path);
409 // NB we don't hold the lock any more now.
417 for (p=entries; p < entries + used_entries; p++)
422 static __attribute((noreturn)) void die_data_overflow(void) {
423 die("cannot handle data with length >2^32");
426 static void prepare_data(size_t *len, char **buf,
427 const void *data, size_t dl) {
429 if (dl >= SIZE_MAX - *len)
434 memcpy(*buf, data, dl);
439 static void prepare_length(size_t *len, char **buf, size_t dl_sz) {
440 if (dl_sz > UINT32_MAX) die_data_overflow();
441 uint32_t dl = htonl(dl_sz);
442 prepare_data(len, buf, &dl, sizeof(dl));
445 static void prepare_string(size_t *len, char **buf, const char *s) {
446 size_t sl = strlen(s);
447 prepare_data(len, buf, s, sl+1);
450 static void prepare_message(size_t *len, char **buf) {
453 const char *const *p = (void*)environ;
456 prepare_string(len, buf, s);
459 prepare_string(len, buf, "");
463 prepare_string(len, buf, s);
466 static void send_fd(int payload_fd) {
467 int via_fd = fileno(call_sock);
470 struct cmsghdr align;
471 char buf[CMSG_SPACE(sizeof(payload_fd))];
481 iov.iov_base = &dummy_byte;
487 msg.msg_control = cmsg_buf.buf;
488 msg.msg_controllen = sizeof(cmsg_buf.buf);
490 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
491 cmsg->cmsg_level = SOL_SOCKET;
492 cmsg->cmsg_type = SCM_RIGHTS;
493 cmsg->cmsg_len = CMSG_LEN(sizeof(payload_fd));
494 *(int*)CMSG_DATA(cmsg) = payload_fd;
496 msg.msg_controllen = sizeof(cmsg_buf.buf);
499 ssize_t r = sendmsg(via_fd, &msg, 0);
501 if (errno == EINTR) continue;
509 static void send_request(void) {
510 // Sending these first makes it easier for the script to
511 // use buffered IO for the message.
517 prepare_message(&len, 0);
519 size_t tlen = len + 4;
520 char *m = xmalloc(tlen);
522 prepare_length(0, &p, len);
523 prepare_message(0, &p);
524 assert(p == m + tlen);
526 ssize_t sr = fwrite(m, tlen, 1, call_sock);
527 if (sr != 1) diee("write request (buffer)");
529 if (fflush(call_sock)) diee("write request");
532 static FILE *call_sock_from_fd(int fd) {
535 FILE *call_sock = fdopen(fd, "r+");
536 if (!call_sock) diee("fdopen socket");
538 r = setvbuf(call_sock, 0, _IONBF, 0);
539 if (r) die("setvbuf socket");
544 static bool was_eof(FILE *call_sock) {
545 return feof(call_sock) || errno==ECONNRESET;
549 static int protocol_read_maybe(void *data, size_t sz) {
551 size_t sr = fread(data, sz, 1, call_sock);
553 if (was_eof(call_sock)) return -1;
554 diee("read() on monitor call socket (%zd)", sz);
559 static void protocol_read(void *data, size_t sz) {
560 if (protocol_read_maybe(data, sz) < 0)
561 die("monitor process quit unexpectedly");
564 // Returns 0 if OK, error msg if peer was garbage.
565 static const char *read_greeting(void) {
566 char got_magic[sizeof(header_magic)];
568 if (protocol_read_maybe(&got_magic, sizeof(got_magic)) < 0)
569 return "initial monitor process quit";
571 if (memcmp(got_magic, header_magic, sizeof(header_magic)))
572 die("got unexpected protocol magic 0x%02x%02x%02x%02x",
573 got_magic[0], got_magic[1], got_magic[2], got_magic[3]);
576 protocol_read(&xdata_len, sizeof(xdata_len));
577 void *xdata = xmalloc(xdata_len);
578 protocol_read(xdata, xdata_len);
583 // Returns: call(client-end), or 0 to mean "is garbage"
584 // find_socket_path must have been called
585 static FILE *connect_existing(void) {
589 fd = socket(AF_UNIX, SOCK_STREAM, 0);
590 if (fd==-1) diee("socket() for client");
592 socklen_t salen = sizeof(sockaddr_sun);
593 r = connect(fd, (const struct sockaddr*)&sockaddr_sun, salen);
595 if (errno==ECONNREFUSED || errno==ENOENT) goto x_garbage;
596 diee("connect() %s", socket_path);
599 call_sock = call_sock_from_fd(fd);
608 if (call_sock) { fclose(call_sock); call_sock=0; }
609 if (fd >= 0) close(fd);
613 static void watcher_cb_stdin(uv_poll_t *handle, int status, int events) {
617 if ((errno = -status)) diee("watcher: poll stdin");
621 if (!(errno==EINTR || errno==EWOULDBLOCK || errno==EAGAIN))
622 diee("watcher: read sentinel stdin");
626 static void watcher_cb_sockpath(uv_fs_event_t *handle, const char *filename,
627 int events, int status) {
629 struct stat now_stab;
631 if ((errno = -status)) diee("watcher: poll stdin");
633 r= stat(socket_path, &now_stab);
635 if (errno==ENOENT) _exit(0);
636 if (errno==EINTR) continue;
637 diee("stat socket: %s", socket_path);
639 if (!stabs_same_inode(&now_stab, &initial_stab))
644 // On entry, stderr is still inherited, but 0 and 1 are the pipes
645 static __attribute__((noreturn))
646 void become_watcher(void) {
648 uv_poll_t uvhandle_stdin;
649 uv_fs_event_t uvhandle_sockpath;
654 errno= -uv_loop_init(&loop);
655 if (errno) diee("watcher: uv_loop_init");
657 errno= -uv_poll_init(&loop, &uvhandle_stdin, 0);
658 if (errno) diee("watcher: uv_poll_init");
659 errno= -uv_poll_start(&uvhandle_stdin,
660 UV_READABLE | UV_WRITABLE | UV_DISCONNECT,
662 if (errno) diee("watcher: uv_poll_start");
664 errno= -uv_fs_event_init(&loop, &uvhandle_sockpath);
665 if (errno) diee("watcher: uv_fs_event_init");
667 errno= -uv_fs_event_start(&uvhandle_sockpath, watcher_cb_sockpath,
669 if (errno) diee("watcher: uv_fs_event_start");
671 // OK everything is set up, let us daemonise
672 if (dup2(1,2) != 2) diee("watcher: set daemonised stderr");
673 r= setvbuf(stderr, 0, _IOLBF, BUFSIZ);
674 if (r) diee("watcher: setvbuf stderr");
676 pid_t child = fork();
677 if (child == (pid_t)-1) diee("watcher: fork");
680 if (setsid() == (pid_t)-1) diee("watcher: setsid");
682 r= uv_run(&loop, UV_RUN_DEFAULT);
683 die("uv_run returned (%d)", r);
686 static __attribute__((noreturn))
687 void become_setup(int sfd, int fake_pair[2],
688 int watcher_stdin, int watcher_stderr) {
690 int call_fd = fake_pair[1];
692 int null_0 = open("/dev/null", O_RDONLY); if (null_0 < 0) diee("open null");
693 if (dup2(null_0, 0)) diee("dup2 /dev/null onto stdin");
695 if (dup2(2, 1) != 1) die("dup2 stderr onto stdout");
699 // Extension could work like this:
701 // We advertise a new protocol (perhaps one which is nearly entirely
702 // different after the connect) by putting a name for it comma-separated
703 // next to "v1". Simple extension can be done by having the script
704 // side say something about it in the ack xdata, which we currently ignore.
705 putenv(m_asprintf("PREFORK_INTERP=v1 %d,%d,%d,%d",
706 sfd, call_fd, watcher_stdin, watcher_stderr));
708 execvp(executor_argv[0], (char**)executor_argv);
709 diee("execute %s", executor_argv[0]);
712 static void connect_or_spawn(void) {
715 call_sock = connect_existing();
716 if (call_sock) return;
718 // We're going to make a new one, so clean out old ones
721 int lockfd = acquire_lock();
722 call_sock = connect_existing();
723 if (call_sock) { close(lockfd); return; }
725 // We must start a fresh one, and we hold the lock
727 r = unlink(socket_path);
728 if (r<0 && errno!=ENOENT)
729 diee("failed to remove stale socket %s", socket_path);
731 int sfd = socket(AF_UNIX, SOCK_STREAM, 0);
732 if (sfd<0) diee("socket() for new listener");
734 socklen_t salen = sizeof(sockaddr_sun);
735 r= bind(sfd, (const struct sockaddr*)&sockaddr_sun, salen);
736 if (r<0) diee("bind() on new listener");
738 r= stat(socket_path, &initial_stab);
739 if (r<0) diee("stat() fresh socket");
741 // We never want callers to get ECONNREFUSED. But:
742 // There is a race here: from my RTFM they may get ECONNREFUSED
743 // if they try between our bind() and listen(). But if they do, they'll
744 // acquire the lock (serialising with us) and retry, and then it will work.
745 r = listen(sfd, INT_MAX);
746 if (r<0) diee("listen() for new listener");
750 int watcher_stdin[2];
751 int watcher_stderr[2];
752 if (pipe(watcher_stdin) || pipe(watcher_stderr))
753 diee("pipe() for socket inode watcher");
755 pid_t watcher = fork();
756 if (watcher == (pid_t)-1) diee("fork for watcher");
760 close(watcher_stdin[1]);
761 close(watcher_stderr[0]);
762 if (dup2(watcher_stdin[0], 0) != 0 ||
763 dup2(watcher_stderr[1], 1) != 1)
764 diee("initial dup2() for watcher");
765 close(watcher_stdin[0]);
766 close(watcher_stderr[1]);
770 close(watcher_stdin[0]);
771 close(watcher_stderr[1]);
772 nonblock(watcher_stderr[0]);
777 r = socketpair(AF_UNIX, SOCK_STREAM, 0, fake_pair);
778 if (r<0) diee("socketpair() for fake initial connection");
780 pid_t setup_pid = fork();
781 if (setup_pid == (pid_t)-1) diee("fork for spawn setup");
782 if (!setup_pid) become_setup(sfd, fake_pair,
783 watcher_stdin[1], watcher_stderr[0]);
787 call_sock = call_sock_from_fd(fake_pair[0]);
790 pid_t got = waitpid(setup_pid, &status, 0);
791 if (got == (pid_t)-1) diee("waitpid setup [%ld]", (long)setup_pid);
792 if (got != setup_pid) diee("waitpid setup [%ld] gave [%ld]!",
793 (long)setup_pid, (long)got);
794 if (status != 0) propagate_exit_status(status, "setup");
796 const char *emsg = read_greeting();
797 if (emsg) die("setup failed: %s", emsg);
803 static void make_executor_argv(const char *const *argv) {
804 switch (laundering) {
806 default: die("need -U (specifying unlaundered argument handling)");
810 #define EACH_NEW_ARG(EACH) { \
811 arg = interp; { EACH } \
812 if ((arg = script)) { EACH } \
813 const char *const *walk = argv; \
814 while ((arg = *walk++)) { EACH } \
818 EACH_NEW_ARG( (void)arg; count++; );
820 const char **out = calloc(count, sizeof(char*));
821 executor_argv = (const char* const*)out;
822 if (!executor_argv) diee("allocate for arguments");
824 EACH_NEW_ARG( *out++ = arg; );
828 int main(int argc_unused, const char *const *argv) {
835 // which ought to be passed on to the actual executor.
836 make_executor_argv(argv);
839 FILLZERO(sockaddr_sun);
840 sockaddr_sun.sun_family = AF_UNIX;
841 assert(strlen(socket_path) <= sizeof(sockaddr_sun.sun_path));
842 strncpy(sockaddr_sun.sun_path, socket_path, sizeof(sockaddr_sun.sun_path));
846 // We're committed now, send the request (or bail out)
850 protocol_read(&status, sizeof(status));
852 status = ntohl(status);
853 if (status > INT_MAX) die("status 0x%lx does not fit in an int",
854 (unsigned long)status);
856 propagate_exit_status(status, "invocation");