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 * === acquire lock ===
22 * makes new listening socket
23 * makes first-instance socketpair
24 * forks setup (script, sock fds indicated in env)
25 * fd0, fd1, fd2: from-outer
26 * other fd: call(client-end)(fake)
27 * reaps setup (and reports error)
28 * (implicitly releases lock)
30 * setup (pre-exec) fd0: null,
31 * fd[12]: fd2-from-outer
32 * env fds: listener, call(server-end)(fake)
34 * possibly clean env, argv
36 * setup (script) runs initialisation parts of the script
37 * at prefork establishment point:
38 * setup (pm) [1] opens syslog
42 * server (pm) [1] [fd0: null],
43 * [fd[12]: fd2-from-outer]
44 * right away, forks init monitor
45 * [2] closes outer caller fds and call(fake)
46 * [server (pm)] fd[012]: null
47 * other fds: listener, syslog
48 * runs in loop accepting and forking,
49 * reaping and limiting children (incl init monitor)
50 * reports failures of monitors to syslog
52 * [client (C wrapper)] if client connect succeeds:
53 * now fd: call(client-end)
54 * sends message with: cmdline, env
57 * [server (script)] accepts, forks subseq monitor
59 * monitor [1] [fd0: null]
60 * (init [fd[12]: init: fd2-from-outer; subseq: null]
61 * or errors: init: fd2; subseq: syslog
62 * subseq) other fds: syslog, call(server-end)
64 * receives args, env, fds
67 * executor sorts out fds:
68 * fd0, fd1, fd2: from-outer
69 * close fds: call(server-end)
70 * retained fds: syslog
73 * runs main part of script
76 * [monitor] [fd[012]: null]
77 * [fd[12]: init: fd2-from-outer; subseq: null]
78 * [errors: init: fd2; subseq: syslog]
80 * reports status via socket
82 * [client (C wrapper)] [fd0, fd1, fd2: from-outer]
83 * [other fd: call(client-end)]
84 * receives status, exits appropriately
85 * (if was bad signal, reports to stderr, exits 127)
88 #include <arpa/inet.h>
92 const char our_name[] = "prefork-interp";
94 static struct sockaddr_un sockaddr_sun;
95 static FILE *call_sock;
99 static const char *const *executor_argv;
101 static const char header_magic[4] = "PFI\n";
103 void fusagemessage(FILE *f) {
104 fprintf(f, "usage: #!/usr/bin/prefork-interp [<options>]\n");
107 static int laundering;
109 const struct cmdinfo cmdinfos[]= {
111 { 0, 'U', 0, .iassignto= &laundering, .arg= 'U' },
115 void ident_addinit(void) {
116 char ident_magic[1] = { 0 };
117 sha256_update(&identsc, sizeof(ident_magic), ident_magic);
120 static void propagate_exit_status(int status, const char *what) {
123 if (WIFEXITED(status)) {
127 if (WIFSIGNALED(status)) {
128 int sig = WTERMSIG(status);
129 const char *signame = strsignal(sig);
130 if (signame == 0) signame = "unknown signal";
132 if (! WCOREDUMP(status) &&
139 sa.sa_handler = SIG_DFL;
140 r = sigaction(sig, &sa, 0);
141 if (r) diee("failed to reset signal handler while propagating %s",
146 sigaddset(&sset, sig);
147 r = sigprocmask(SIG_UNBLOCK, &sset, 0);
148 if (r) diee("failed to reset signal block while propagating %s",
152 die("unexpectedly kept running after raising (to propagate) %s",
156 die("%s failed due to signal %d %s%s", what, sig, signame,
157 WCOREDUMP(status) ? " (core dumped)" : "");
160 die("%s failed with weird wait status %d 0x%x", what, status, status);
163 static __attribute((noreturn)) void die_data_overflow(void) {
164 die("cannot handle data with length >2^32");
167 static void prepare_data(size_t *len, char **buf,
168 const void *data, size_t dl) {
170 if (dl >= SIZE_MAX - *len)
175 memcpy(*buf, data, dl);
180 static void prepare_length(size_t *len, char **buf, size_t dl_sz) {
181 if (dl_sz > UINT32_MAX) die_data_overflow();
182 uint32_t dl = htonl(dl_sz);
183 prepare_data(len, buf, &dl, sizeof(dl));
186 static void prepare_string(size_t *len, char **buf, const char *s) {
187 size_t sl = strlen(s);
188 prepare_data(len, buf, s, sl+1);
191 static void prepare_message(size_t *len, char **buf) {
194 const char *const *p = (void*)environ;
197 prepare_string(len, buf, s);
200 prepare_string(len, buf, "");
204 prepare_string(len, buf, s);
207 static void send_fd(int payload_fd) {
208 int via_fd = fileno(call_sock);
211 struct cmsghdr align;
212 char buf[CMSG_SPACE(sizeof(payload_fd))];
222 iov.iov_base = &dummy_byte;
228 msg.msg_control = cmsg_buf.buf;
229 msg.msg_controllen = sizeof(cmsg_buf.buf);
231 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
232 cmsg->cmsg_level = SOL_SOCKET;
233 cmsg->cmsg_type = SCM_RIGHTS;
234 cmsg->cmsg_len = CMSG_LEN(sizeof(payload_fd));
235 *(int*)CMSG_DATA(cmsg) = payload_fd;
237 msg.msg_controllen = sizeof(cmsg_buf.buf);
240 ssize_t r = sendmsg(via_fd, &msg, 0);
242 if (errno == EINTR) continue;
250 static void send_request(void) {
251 // Sending these first makes it easier for the script to
252 // use buffered IO for the message.
258 prepare_message(&len, 0);
259 char *m = malloc(len);
260 if (!m) diee("failed to allocate for message");
262 prepare_length(0, &p, len - 4);
263 prepare_message(0, &p);
264 assert(p == m + len);
266 ssize_t sr = fwrite(p, len, 1, call_sock);
267 if (sr != 1) diee("write request");
270 static FILE *call_sock_from_fd(int fd) {
273 FILE *call_sock = fdopen(fd, "r+");
274 if (!call_sock) diee("fdopen socket");
276 r = setvbuf(call_sock, 0, _IONBF, 0);
277 if (r) die("setvbuf socket");
282 static bool was_eof(FILE *call_sock) {
283 return feof(call_sock) || errno==ECONNRESET;
287 static int protocol_read_maybe(void *data, size_t sz) {
288 size_t sr = fread(data, sz, 1, call_sock);
290 if (was_eof(call_sock)) return -1;
291 diee("read() on monitor call socket");
296 static void protocol_read(void *data, size_t sz) {
297 if (protocol_read_maybe(data, sz) < 0)
298 die("monitor process quit unexpectedly");
301 // Returns 0 if OK, error msg if peer was garbage.
302 static const char *protocol_greeting(void) {
303 char got_magic[sizeof(header_magic)];
305 if (protocol_read_maybe(&got_magic, sizeof(got_magic)) < 0)
306 return "initial monitor process quit";
308 if (memcmp(got_magic, header_magic, sizeof(header_magic)))
309 die("got unexpected protocol magic 0x%02x%02x%02x%02x",
310 got_magic[0], got_magic[1], got_magic[2], got_magic[3]);
313 protocol_read(&xdata_len, sizeof(xdata_len));
314 void *xdata = xmalloc(xdata_len);
315 protocol_read(xdata, xdata_len);
320 // Returns: call(client-end), or 0 to mean "is garbage"
321 // find_socket_path must have been called
322 static FILE *connect_existing(void) {
326 fd = socket(AF_UNIX, SOCK_STREAM, 0);
327 if (fd==-1) diee("socket() for client");
329 socklen_t salen = sizeof(sockaddr_sun);
330 r = connect(fd, (const struct sockaddr*)&sockaddr_sun, salen);
332 if (errno==ECONNREFUSED || errno==ENOENT) goto x_garbage;
333 diee("connect() %s", socket_path);
336 call_sock = call_sock_from_fd(fd);
339 if (protocol_greeting())
345 if (call_sock) { fclose(call_sock); call_sock=0; }
346 if (fd >= 0) close(fd);
350 static __attribute__((noreturn))
351 void become_setup(int sfd, int fake_pair[2]) {
353 int call_fd = fake_pair[1];
355 int null_0 = open("/dev/null", O_RDONLY); if (null_0 < 0) diee("open null");
356 if (dup2(null_0, 0)) diee("dup2 /dev/null onto stdin");
357 if (dup2(2, 1) != 1) die("dup2 stderr onto stdout");
359 // Extension could work like this:
361 // We advertise a new protocol (perhaps one which is nearly entirely
362 // different after the connect) by putting a name for it comma-separated
363 // next to "v1". Simple extension can be done by having the script
364 // side say something about it in the ack xdata, which we currently ignore.
365 putenv(m_asprintf("PREFORK_INTERP=v1 %d,%d %s",
366 sfd, call_fd, socket_path));
368 execvp(executor_argv[0], (char**)executor_argv);
369 diee("execute %s", executor_argv[0]);
372 static void connect_or_spawn(void) {
375 call_sock = connect_existing();
376 if (call_sock) return;
378 int lockfd = acquire_lock();
379 call_sock = connect_existing();
380 if (call_sock) { close(lockfd); return; }
382 // We must start a fresh one, and we hold the lock
384 r = unlink(socket_path);
385 if (r<0 && errno!=ENOENT)
386 diee("failed to remove stale socket %s", socket_path);
389 r = socketpair(AF_UNIX, SOCK_STREAM, 0, fake_pair);
390 if (r<0) diee("socketpair() for fake initial connection");
392 int sfd = socket(AF_UNIX, SOCK_STREAM, 0);
393 if (sfd<0) diee("socket() for new listener");
395 socklen_t salen = sizeof(sockaddr_sun);
396 r= bind(sfd, (const struct sockaddr*)&sockaddr_sun, salen);
397 if (r<0) diee("bind() on new listener");
399 // We never want callers to get ECONNREFUSED. But:
400 // There is a race here: from my RTFM they may get ECONNREFUSED
401 // if they try between our bind() and listen(). But if they do, they'll
402 // acquire the lock (serialising with us) and retry, and then it will work.
403 r = listen(sfd, INT_MAX);
404 if (r<0) diee("listen() for new listener");
406 pid_t setup_pid = fork();
407 if (setup_pid == (pid_t)-1) diee("fork for spawn setup");
408 if (!setup_pid) become_setup(sfd, fake_pair);
412 call_sock = call_sock_from_fd(fake_pair[0]);
415 pid_t got = waitpid(setup_pid, &status, 0);
416 if (got == (pid_t)-1) diee("waitpid setup [%ld]", (long)setup_pid);
417 if (got != setup_pid) diee("waitpid setup [%ld] gave [%ld]!",
418 (long)setup_pid, (long)got);
419 if (status != 0) propagate_exit_status(status, "setup");
421 const char *emsg = protocol_greeting();
422 if (emsg) die("setup failed: %s", emsg);
428 static void make_executor_argv(const char *const *argv) {
429 switch (laundering) {
431 default: die("need -U (specifying unlaundered argument handling)");
435 #define EACH_NEW_ARG(EACH) { \
436 arg = interp; { EACH } \
437 if ((arg = script)) { EACH } \
438 const char *const *walk = argv; \
439 while ((arg = *walk++)) { EACH } \
443 EACH_NEW_ARG( (void)arg; count++; );
445 const char **out = calloc(count, sizeof(char*));
446 executor_argv = (const char* const*)out;
447 if (!executor_argv) diee("allocate for arguments");
449 EACH_NEW_ARG( *out++ = arg; );
453 int main(int argc_unused, const char *const *argv) {
460 // which ought to be passed on to the actual executor.
461 make_executor_argv(argv);
464 FILLZERO(sockaddr_sun);
465 sockaddr_sun.sun_family = AF_UNIX;
466 assert(strlen(socket_path) <= sizeof(sockaddr_sun.sun_path));
467 strncpy(sockaddr_sun.sun_path, socket_path, sizeof(sockaddr_sun.sun_path));
471 // We're committed now, send the request (or bail out)
475 protocol_read(&status, sizeof(status));
477 status = ntohl(status);
478 if (status > INT_MAX) die("status 0x%lx does not fit in an int",
479 (unsigned long)status);
481 propagate_exit_status(status, "invocation");