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> ...]
12 * client (C wrapper) connects to server
13 * (including reading ack byte)
15 * === acquire lock ===
16 * makes new listening socket
17 * makes first-instance socketpair
18 * forks setup (script, sock fds indicated in env)
19 * fd0, fd1, fd2: from-outer-caller
20 * other fd: call(client-end)(fake)
21 * reaps setup (and reports error)
22 * (implicitly releases lock)
24 * setup (pre-exec) fd0: null,
25 * fd[12: fd2-from-outer-caller
26 * env fds: listener, call(server-end)(fake)
27 * env fds: orig-fd[01]
30 * setup (script) runs initialisation parts of the script
31 * at prefork establishment point:
32 * setup (pm) [1] opens syslog
36 # server (pm) [1] [fd0: null],
37 * [fd[12: fd2-from-outer-caller]
38 * right away, forks one fa-monitor
39 * [2] closes outer caller fds and call(fake)
40 * [server (pm)] fd[012]: null
41 * other fds: listener, syslog
42 * runs in loop accepting and forking,
43 * reaping and limiting children (incl fa-monitor)
44 * reports failures of monitors to syslog
46 * f-a monitor forks executor
48 * [fd[12: fd2-from-outer-caller]
49 * [other fds: call(server-end)(fake), syslog]
50 * runs as monitor, below
53 * [client (C wrapper)] if client connect succeeds:
54 * now fd: call(client-end)
55 * sends message with: cmdline, env
58 * [server (script)] accepts, forks monitor
60 * monitor [1] [fd[012]: null]
61 * other fds: syslog, call(server-end)
63 * receives args, env, fds
66 * executor sorts out fds:
67 * fd0, fd1, fd2: from-outer-caller
68 * close fds: call(server-end)
69 * retained fds: syslog
72 * runs main part of script
75 * [monitor] [fd[012]: null]
76 * [other fds: call(server-end), syslog]
78 * reports status via socket
80 * [client (C wrapper)] [fd0, fd1, fd2: from-outer-caller]
81 * [other fd: call(client-end)]
82 * receives status, exits appropriately
83 * (if was bad signal, reports to stderr, exits 127)
86 #include <arpa/inet.h>
90 struct sockaddr_un sun;
94 static struct sockaddr_unix socket_sun;
95 static const char *const *executor_argv;
97 static void propagate_exit_status(int status, const char *what) {
100 if (WIFEXITED(status)) {
104 if (WIFSIGNALED(status)) {
105 int sig = WTERMSIG(status);
106 const char *signame = strsignal(sig);
107 if (signame == 0) signame = "unknown signal";
109 if (! WCOREDUMP(status) &&
116 sa.sa_handler = SIG_DFL;
117 r = sigaction(sig, &sa, 0);
118 if (r) diee("failed to reset signal handler while propagating %s",
123 sigaddset(&sset, sig);
124 r = sigprocmask(SIG_UNBLOCK, &sset, 0);
125 if (r) diee("failed to reset signal block while propagating %s",
129 die("unexpectedly kept running after raising (to propagate) %s",
133 die("setup failed due to signal %d %s%s", sig, signame,
134 WCOREDUMP(status) ? " (core dumped)" : "");
137 die("setup failed with weird wait status %d 0x%x", status, status);
140 static __attribute((noreturn)) void die_data_overflow(void) {
141 die("cannot handle data with length >2^32");
144 static void prepare_data(size_t *len, char **buf,
145 const void *data, size_t dl) {
147 if (dl >= SIZE_MAX - *len)
152 memcpy(*buf, data, dl);
157 static void prepare_length(size_t *len, char **buf, size_t dl_sz) {
158 if (dl_sz > UINT32_MAX) die_data_overflow();
159 uint32_t dl = htonl(dl_sz);
160 prepare_data(len, buf, &dl, sizeof(dl));
163 static void prepare_string(size_t *len, char **buf, const char *s) {
164 size_t sl = strlen(s);
165 prepare_data(len, buf, s, sl+1);
168 static void prepare_message(size_t *len, char **buf) {
171 const char *const *p = (void*)environ;
174 prepare_string(len, buf, s);
177 prepare_string(len, buf, "");
181 prepare_string(len, buf, s);
184 static void send_fd(int via_fd, int payload_fd) {
186 struct cmsghdr align;
187 char buf[CMSG_SPACE(sizeof(payload_fd))];
197 iov.iov_base = &dummy_byte;
203 msg.msg_control = cmsg_buf.buf;
204 msg.msg_controllen = sizeof(cmsg_buf.buf);
206 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
207 cmsg->cmsg_level = SOL_SOCKET;
208 cmsg->cmsg_type = SCM_RIGHTS;
209 cmsg->cmsg_len = CMSG_LEN(sizeof(payload_fd));
210 *(int*)CMSG_DATA(cmsg) = payload_fd;
212 msg.msg_controllen = sizeof(cmsg_buf.buf);
215 ssize_t r = sendmsg(via_fd, &msg, 0);
217 if (errno == EINTR) continue;
225 static void send_request(int call_fd) {
226 // Sending these first makes it easier for the script to
227 // use buffered IO for the message.
233 prepare_message(&len, 0);
234 char *m = malloc(len);
235 if (!m) diee("failed to allocate for message");
237 prepare_length(0, &p, len - 4);
238 prepare_message(0, &p);
239 assert(p == m + len);
243 ssize_t r = write(call_fd, p, len);
245 if (errno == EINTR) continue;
246 diee("write request");
255 // Returns: call(client-end) fd, or -1 to mean "is garbage"
256 // find_socket_path must have been called
257 static int connect_existing(void) {
261 fd = socket(AF_UNIX, SOCK_STREAM, 0);
262 if (fd==-1) diee("socket() for client");
264 socklen_t salen = sizeof(sun);
265 r = connect(client, (const struct sockaddr*)&socket_sun, salen);
267 if (errno==ECONNREFUSED || errno==ENOENT) goto x_garbgae;
268 diee("connect() %s", socket_path);
273 sr = read(fd, &ack, 1);
275 if (errno==ECONNRESET) goto x_garbage;
276 if (errno==EINTR) continue;
277 diee("read() ack byte");
279 if (sr == 0) { goto x_garbage; }
280 if (ack != '\n') die("got ack byte 0x%02x, not '\n'", ack);
284 // We're committed now, send the request (or bail out)
285 send_request(call, argv);
290 if (fd >= 0) close(fd);
294 static void become_setup(int sfd, int fake_pair[2])
295 __attribute__((noreturn))
298 int call_fd = fake_pair[1];
300 int fd0_save = dup(0); if (fd0_save < 0) diee("dup stdin");
301 int fd1_save = dup(1); if (fd1_save < 0) diee("dup stdin");
303 int null_0 = open("/dev/null", O_RDONLY); if (null_0 < 0) diee("open null");
304 if (dup2(null_0, 0)) diee("dup2 /dev/null onto stdin");
305 if (dup2(2, 1) != 1) die("dup2 stderr onto stdout");
307 putenv(asprintf("PREFORK_INTERP=%d,%d,%d,%d,%s",
308 sfd, call_fd, fd0_save, fd1_save, socket_path));
310 execvp(executor_argv[0], executor_argv);
311 diee("execute %s", executor_argv[0]);
314 static int connect_or_spawn(void) {
315 int fd = connect_existing();
316 if (fd >= 0) return fd;
318 int lockfd = acquire_lock();
319 fd = connect_existing();
320 if (fd >= 0) { close(lockfd); return fd; }
322 // We must start a fresh one, and we hold the lock
324 r = unlink(socketpath);
325 if (r<0) diee("failed to remove stale socket %s", socketpath);
328 r = socketpair(AF_UNIX, SOCK_STREAM, 0, fake_pair);
329 if (r<0) diee("socketpair() for fake initial connection");
331 int sfd = socket(AF_UNIX, SOCK_STREAM, 0);
332 if (sfd<0) diee("socket() for new listener");
334 salen_t salen = sizeof(sun);
335 r= bind(sfd, (const struct sockaddr*)&socket_sun, saledn);
336 if (r<0) diee("bind() on new listener");
338 // We never want callers to get ECONNREFUSED!.
339 // There is a race here: from my RTFM they may get ECONNREFUSED
340 // if they tr between our bind() and listen(). But if they do, they'll
341 // acquire the lock (serialising with us) and retry, and then it will work.
342 r = listen(sfd, INT_MAX);
343 if (r<0) diee("listen() for new listener");
345 pid_t setup_pid = fork();
346 if (setup_pid == (pid_t)-1) diee("fork for spawn setup");
347 if (!setup_pid) become_setup(sfd, fake_pair);
352 pid_t got = waitpid(setup_pid, &status, 0);
353 if (got == (pid_t)-1) diee("waitpid setup [%ld]", (long)setup_pid);
354 if (got != setup_pid) diee("waitpid setup [%ld] gave [%ld]!",
355 (long)setup_pid, (long)got);
356 if (status != 0) propagate_exit_status(status);
362 static void make_executor_argv(const char *const *argv) {
363 #define EACH_NEW_ARGV(EACH) { \
364 arg = interp; { EACH } \
365 if ((arg = script)) { EACH } \
366 const char *const *walk = argv; \
367 while ((arg = *walk++)) { EACH } \
371 MAKE_NEW_ARGV( (void)arg; count++; );
373 executor_argv = calloc(count, sizeof(char*));
374 if (!executor_argv) diee("allocate for arguments");
376 char **out = executor_argv;
377 MAKE_NEW_ARGV( *out++ = arg; );
381 int main(int argc_unused, const char *const *argv) {
388 // which ought to be passed on to the actual executor.
389 make_executor_argv(argv);
393 sun.sun_family = AF_UNIX;
394 assert(strlen(socket_path) <= sizeof(sun.sun_path));
395 strncpy(sun.sun_path, socket_path, sizeof(sun.sun_path));
397 int call_fd = connect_or_spawn();