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 struct sockaddr_un sockaddr_sun;
98 static const char *const *executor_argv;
100 void fusagemessage(FILE *f) {
101 fprintf(f, "usage: #!/usr/bin/prefork-interp [<options>]\n");
104 static int laundering;
106 const struct cmdinfo cmdinfos[]= {
108 { 0, 'U', 0, .iassignto= &laundering, .arg= 'U' },
112 void ident_addinit(void) {
113 char ident_magic[1] = { 0 };
114 sha256_update(&identsc, sizeof(ident_magic), ident_magic);
117 static void propagate_exit_status(int status, const char *what) {
120 if (WIFEXITED(status)) {
124 if (WIFSIGNALED(status)) {
125 int sig = WTERMSIG(status);
126 const char *signame = strsignal(sig);
127 if (signame == 0) signame = "unknown signal";
129 if (! WCOREDUMP(status) &&
136 sa.sa_handler = SIG_DFL;
137 r = sigaction(sig, &sa, 0);
138 if (r) diee("failed to reset signal handler while propagating %s",
143 sigaddset(&sset, sig);
144 r = sigprocmask(SIG_UNBLOCK, &sset, 0);
145 if (r) diee("failed to reset signal block while propagating %s",
149 die("unexpectedly kept running after raising (to propagate) %s",
153 die("%s failed due to signal %d %s%s", what, sig, signame,
154 WCOREDUMP(status) ? " (core dumped)" : "");
157 die("%s failed with weird wait status %d 0x%x", what, status, status);
160 static __attribute((noreturn)) void die_data_overflow(void) {
161 die("cannot handle data with length >2^32");
164 static void prepare_data(size_t *len, char **buf,
165 const void *data, size_t dl) {
167 if (dl >= SIZE_MAX - *len)
172 memcpy(*buf, data, dl);
177 static void prepare_length(size_t *len, char **buf, size_t dl_sz) {
178 if (dl_sz > UINT32_MAX) die_data_overflow();
179 uint32_t dl = htonl(dl_sz);
180 prepare_data(len, buf, &dl, sizeof(dl));
183 static void prepare_string(size_t *len, char **buf, const char *s) {
184 size_t sl = strlen(s);
185 prepare_data(len, buf, s, sl+1);
188 static void prepare_message(size_t *len, char **buf) {
191 const char *const *p = (void*)environ;
194 prepare_string(len, buf, s);
197 prepare_string(len, buf, "");
201 prepare_string(len, buf, s);
204 static void send_fd(FILE *call_sock, int payload_fd) {
205 int via_fd = fileno(call_sock);
208 struct cmsghdr align;
209 char buf[CMSG_SPACE(sizeof(payload_fd))];
219 iov.iov_base = &dummy_byte;
225 msg.msg_control = cmsg_buf.buf;
226 msg.msg_controllen = sizeof(cmsg_buf.buf);
228 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
229 cmsg->cmsg_level = SOL_SOCKET;
230 cmsg->cmsg_type = SCM_RIGHTS;
231 cmsg->cmsg_len = CMSG_LEN(sizeof(payload_fd));
232 *(int*)CMSG_DATA(cmsg) = payload_fd;
234 msg.msg_controllen = sizeof(cmsg_buf.buf);
237 ssize_t r = sendmsg(via_fd, &msg, 0);
239 if (errno == EINTR) continue;
247 static void send_request(FILE *call_sock) {
248 // Sending these first makes it easier for the script to
249 // use buffered IO for the message.
250 send_fd(call_sock, 0);
251 send_fd(call_sock, 1);
252 send_fd(call_sock, 2);
255 prepare_message(&len, 0);
256 char *m = malloc(len);
257 if (!m) diee("failed to allocate for message");
259 prepare_length(0, &p, len - 4);
260 prepare_message(0, &p);
261 assert(p == m + len);
263 ssize_t sr = fwrite(p, len, 1, call_sock);
264 if (sr != 1) diee("write request");
267 static FILE *call_sock_from_fd(int fd) {
270 FILE *call_sock = fdopen(fd, "r+");
271 if (!call_sock) diee("fdopen socket");
273 r = setvbuf(call_sock, 0, _IONBF, 0);
274 if (r) die("setvbuf socket");
279 static bool was_eof(FILE *call_sock) {
280 return feof(call_sock) || errno==ECONNRESET;
283 // Returns: call(client-end), or 0 to mean "is garbage"
284 // find_socket_path must have been called
285 static FILE *connect_existing(void) {
290 fd = socket(AF_UNIX, SOCK_STREAM, 0);
291 if (fd==-1) diee("socket() for client");
293 socklen_t salen = sizeof(sockaddr_sun);
294 r = connect(fd, (const struct sockaddr*)&sockaddr_sun, salen);
296 if (errno==ECONNREFUSED || errno==ENOENT) goto x_garbage;
297 diee("connect() %s", socket_path);
300 call_sock = call_sock_from_fd(fd);
304 size_t sr = fread(&ack, sizeof(ack), 1, call_sock);
306 if (was_eof(call_sock)) goto x_garbage;
307 diee("read() ack byte");
309 if (ack != '\n') die("got ack byte 0x%02x, not '\n'", ack);
311 // We're committed now, send the request (or bail out)
312 send_request(call_sock);
317 if (call_sock) fclose(call_sock);
318 if (fd >= 0) close(fd);
322 static __attribute__((noreturn))
323 void become_setup(int sfd, int fake_pair[2]) {
325 int call_fd = fake_pair[1];
327 int fd0_save = dup(0); if (fd0_save < 0) diee("dup stdin");
328 int fd1_save = dup(1); if (fd1_save < 0) diee("dup stdin");
330 int null_0 = open("/dev/null", O_RDONLY); if (null_0 < 0) diee("open null");
331 if (dup2(null_0, 0)) diee("dup2 /dev/null onto stdin");
332 if (dup2(2, 1) != 1) die("dup2 stderr onto stdout");
334 putenv(m_asprintf("PREFORK_INTERP=%d,%d,%d,%d,%s",
335 sfd, call_fd, fd0_save, fd1_save, socket_path));
337 execvp(executor_argv[0], (char**)executor_argv);
338 diee("execute %s", executor_argv[0]);
341 static FILE *connect_or_spawn(void) {
344 FILE *call_sock = connect_existing();
345 if (call_sock) return call_sock;
347 int lockfd = acquire_lock();
348 call_sock = connect_existing();
349 if (call_sock) { close(lockfd); return call_sock; }
351 // We must start a fresh one, and we hold the lock
353 r = unlink(socket_path);
354 if (r<0 && errno!=ENOENT)
355 diee("failed to remove stale socket %s", socket_path);
358 r = socketpair(AF_UNIX, SOCK_STREAM, 0, fake_pair);
359 if (r<0) diee("socketpair() for fake initial connection");
361 int sfd = socket(AF_UNIX, SOCK_STREAM, 0);
362 if (sfd<0) diee("socket() for new listener");
364 socklen_t salen = sizeof(sockaddr_sun);
365 r= bind(sfd, (const struct sockaddr*)&sockaddr_sun, salen);
366 if (r<0) diee("bind() on new listener");
368 // We never want callers to get ECONNREFUSED. But:
369 // There is a race here: from my RTFM they may get ECONNREFUSED
370 // if they try between our bind() and listen(). But if they do, they'll
371 // acquire the lock (serialising with us) and retry, and then it will work.
372 r = listen(sfd, INT_MAX);
373 if (r<0) diee("listen() for new listener");
375 pid_t setup_pid = fork();
376 if (setup_pid == (pid_t)-1) diee("fork for spawn setup");
377 if (!setup_pid) become_setup(sfd, fake_pair);
382 pid_t got = waitpid(setup_pid, &status, 0);
383 if (got == (pid_t)-1) diee("waitpid setup [%ld]", (long)setup_pid);
384 if (got != setup_pid) diee("waitpid setup [%ld] gave [%ld]!",
385 (long)setup_pid, (long)got);
386 if (status != 0) propagate_exit_status(status, "setup");
389 return call_sock_from_fd(fake_pair[0]);
392 static void make_executor_argv(const char *const *argv) {
393 switch (laundering) {
395 default: die("need -U (specifying unlaundered argument handling)");
399 #define EACH_NEW_ARG(EACH) { \
400 arg = interp; { EACH } \
401 if ((arg = script)) { EACH } \
402 const char *const *walk = argv; \
403 while ((arg = *walk++)) { EACH } \
407 EACH_NEW_ARG( (void)arg; count++; );
409 const char **out = calloc(count, sizeof(char*));
410 executor_argv = (const char* const*)out;
411 if (!executor_argv) diee("allocate for arguments");
413 EACH_NEW_ARG( *out++ = arg; );
417 int main(int argc_unused, const char *const *argv) {
424 // which ought to be passed on to the actual executor.
425 make_executor_argv(argv);
428 FILLZERO(sockaddr_sun);
429 sockaddr_sun.sun_family = AF_UNIX;
430 assert(strlen(socket_path) <= sizeof(sockaddr_sun.sun_path));
431 strncpy(sockaddr_sun.sun_path, socket_path, sizeof(sockaddr_sun.sun_path));
433 FILE *call_sock = connect_or_spawn();
435 ssize_t sr = fread(&status, sizeof(status), 1, call_sock);
437 if (was_eof(call_sock)) die("per-call server monitor process quit");
438 diee("read status from call socket");
441 status = ntohl(status);
442 if (status > INT_MAX) die("status 0x%lx does not fit in an int",
443 (unsigned long)status);
445 propagate_exit_status(status, "invocation");