chiark / gitweb /
4e044a26c46a12f85946534fb52fea716fc5499b
[chiark-utils.git] / cprogs / prefork-interp.c
1 /*
2  * "Interpreter" that you can put in #! like this
3  *   #!/usr/bin/prefork-interp [<options>] <interpreter>
4  *
5  * Usages:
6  *   prefork-interp  [<option> ..] <interpreter>  [<script> [<args> ...]]
7  *   prefork-interp  [<option>,..],<interpreter>   <script> [<args> ...]
8  *   prefork-interp '[<option> ..] <interpreter>'  <script> [<args> ...]
9  */
10 /*
11  * Process structure:
12  *  client (C wrapper)        connects to server
13  *                              (including reading ack byte)
14  *                            if fails or garbage
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)
23  *
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]
28  *                            close fd: lockfile
29  *
30  *     setup (script)         runs initialisation parts of the script
31  *                            at prefork establishment point:
32  *     setup (pm) [1]         opens syslog
33  *                            forks for server
34  *                [2]         exits
35  *
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
45  *                            
46  *         f-a monitor        forks executor
47  *                            closes fd: listener
48  *                            [fd[12: fd2-from-outer-caller]
49  *                            [other fds: call(server-end)(fake), syslog]
50  *                            runs as monitor, below
51  *
52  *
53  *  [client (C wrapper)]      if client connect succeeds:
54  *                            now fd: call(client-end)
55  *                               sends message with: cmdline, env
56  *                               sends fds
57  *
58  *        [server (script)]   accepts, forks monitor
59  *
60  *          monitor [1]       [fd[012]: null]
61  *                            other fds: syslog, call(server-end)
62  *                            sends ack byte
63  *                            receives args, env, fds
64  *                            forks executor
65  *
66  *            executor        sorts out fds:
67  *                            fd0, fd1, fd2: from-outer-caller
68  *                            close fds: call(server-end)
69  *                            retained fds: syslog
70  *
71  *                            sets cmdline, env
72  *                            runs main part of script
73  *                            exits normally
74  *
75  *          [monitor]         [fd[012]: null]
76  *                            [other fds: call(server-end), syslog]
77  *                            reaps executor
78  *                            reports status via socket
79  *
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)
84  */
85
86 #include <arpa/inet.h>
87
88 #include "prefork.h"
89
90 struct sockaddr_un sun;
91
92 #define ACK_BYTE '\n'
93
94 static struct sockaddr_un socket_sun;
95 static const char *const *executor_argv;
96
97 static void propagate_exit_status(int status, const char *what) {
98   int r;
99
100   if (WIFEXITED(status)) {
101     _exit(status);
102   }
103
104   if (WIFSIGNALED(status)) {
105     int sig = WTERMSIG(status);
106     const char *signame = strsignal(sig);
107     if (signame == 0) signame = "unknown signal";
108
109     if (! WCOREDUMP(status) &&
110         (sig == SIGINT ||
111          sig == SIGHUP ||
112          sig == SIGPIPE ||
113          sig == SIGKILL)) {
114       struct sigaction sa;
115       FILLZERO(sa);
116       sa.sa_handler = SIG_DFL;
117       r = sigaction(sig, &sa, 0);
118       if (r) diee("failed to reset signal handler while propagating %s",
119                   signame);
120       
121       sigset_t sset;
122       sigemptyset(&sset);
123       sigaddset(&sset, sig);
124       r = sigprocmask(SIG_UNBLOCK, &sset, 0);
125       if (r) diee("failed to reset signal block while propagating %s",
126                   signame);
127
128       raise(sig);
129       die("unexpectedly kept running after raising (to propagate) %s",
130           signame);
131     }
132
133     die("%s failed due to signal %d %s%s", what, sig, signame,
134         WCOREDUMP(status) ? " (core dumped)" : "");
135   }
136
137   die("%s failed with weird wait status %d 0x%x", what, status, status);
138 }
139
140 static __attribute((noreturn)) void die_data_overflow(void) {
141   die("cannot handle data with length >2^32");
142 }
143
144 static void prepare_data(size_t *len, char **buf,
145                          const void *data, size_t dl) {
146   if (len) {
147     if (dl >= SIZE_MAX - *len)
148       die_data_overflow();
149     *len += dl;
150   }
151   if (buf) {
152     memcpy(*buf, data, dl);
153     *buf += dl;
154   }
155 }
156   
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));
161 }
162
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);
166 }
167
168 static void prepare_message(size_t *len, char **buf) {
169   const char *s;
170
171   const char *const *p = (void*)environ;
172   while ((s = *p++)) {
173     if (strchr(s, '='))
174       prepare_string(len, buf, s);
175   }
176
177   prepare_string(len, buf, "");
178
179   p = executor_argv;
180   while ((s = *p++))
181     prepare_string(len, buf, s);
182 }
183
184 static void send_fd(FILE *call_sock, int payload_fd) {
185   int via_fd = fileno(call_sock);
186
187   union {
188     struct cmsghdr align;
189     char buf[CMSG_SPACE(sizeof(payload_fd))];
190   } cmsg_buf;
191
192   struct msghdr msg;
193   FILLZERO(msg);
194   FILLZERO(cmsg_buf);
195
196   char dummy_byte = 0;
197   struct iovec iov;
198   FILLZERO(iov);
199   iov.iov_base = &dummy_byte;
200   iov.iov_len = 1;
201
202   msg.msg_name = 0;
203   msg.msg_iov = &iov;
204   msg.msg_iovlen = 1;
205   msg.msg_control = cmsg_buf.buf;
206   msg.msg_controllen = sizeof(cmsg_buf.buf);
207
208   struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
209   cmsg->cmsg_level = SOL_SOCKET;
210   cmsg->cmsg_type = SCM_RIGHTS;
211   cmsg->cmsg_len = CMSG_LEN(sizeof(payload_fd));
212   *(int*)CMSG_DATA(cmsg) = payload_fd;
213
214   msg.msg_controllen = sizeof(cmsg_buf.buf);
215
216   for (;;) {
217     ssize_t r = sendmsg(via_fd, &msg, 0);
218     if (r == -1) {
219       if (errno == EINTR) continue;
220       diee("send fd");
221     }
222     assert(r == 1);
223     break;
224   }
225 }
226
227 static void send_request(FILE *call_sock) {
228   // Sending these first makes it easier for the script to
229   // use buffered IO for the message.
230   send_fd(call_sock, 0);
231   send_fd(call_sock, 1);
232   send_fd(call_sock, 2);
233
234   size_t len = 4;
235   prepare_message(&len, 0);
236   char *m = malloc(len);
237   if (!m) diee("failed to allocate for message");
238   char *p = m;
239   prepare_length(0, &p, len - 4);
240   prepare_message(0, &p);
241   assert(p == m + len);
242
243   ssize_t sr = fwrite(p, len, 1, call_sock);
244   if (sr != 1) diee("write request");
245 }
246
247 static FILE *call_sock_from_fd(int fd) {
248   int r;
249
250   FILE *call_sock = fdopen(fd, "r+");
251   if (!call_sock) diee("fdopen socket");
252
253   r = setvbuf(call_sock, 0, _IONBF, 0);
254   if (r) die("setvbuf socket");
255
256   return call_sock;
257 }
258
259 static bool was_eof(FILE *call_sock) {
260   return feof(call_sock) || errno==ECONNRESET;
261 }
262
263 // Returns: call(client-end), or 0 to mean "is garbage"
264 // find_socket_path must have been called
265 static FILE *connect_existing(void) {
266   int r;
267   int fd = -1;
268   FILE *call_sock;
269
270   fd = socket(AF_UNIX, SOCK_STREAM, 0);
271   if (fd==-1) diee("socket() for client");
272
273   socklen_t salen = sizeof(sun);
274   r = connect(fd, (const struct sockaddr*)&socket_sun, salen);
275   if (r==-1) {
276     if (errno==ECONNREFUSED || errno==ENOENT) goto x_garbage;
277     diee("connect() %s", socket_path);
278   }
279
280   call_sock = call_sock_from_fd(fd);
281   fd = -1;
282
283   char ack;
284   size_t sr = fread(&ack, sizeof(ack), 1, call_sock);
285   if (sr != 1) {
286     if (was_eof(call_sock)) goto x_garbage;
287     diee("read() ack byte");
288   }
289   if (ack != '\n') die("got ack byte 0x%02x, not '\n'", ack);
290
291   // We're committed now, send the request (or bail out)
292   send_request(call_sock);
293
294   return call_sock;
295
296  x_garbage:
297   fclose(call_sock);
298   if (fd >= 0) close(fd);
299   return 0;
300 }
301
302 static __attribute__((noreturn))
303 void become_setup(int sfd, int fake_pair[2]) {
304   close(fake_pair[0]);
305   int call_fd = fake_pair[1];
306
307   int fd0_save = dup(0);  if (fd0_save < 0) diee("dup stdin");
308   int fd1_save = dup(1);  if (fd1_save < 0) diee("dup stdin");
309
310   int null_0 = open("/dev/null", O_RDONLY);  if (null_0 < 0) diee("open null");
311   if (dup2(null_0, 0)) diee("dup2 /dev/null onto stdin");
312   if (dup2(2, 1) != 1) die("dup2 stderr onto stdout");
313
314   putenv(m_asprintf("PREFORK_INTERP=%d,%d,%d,%d,%s",
315                     sfd, call_fd, fd0_save, fd1_save, socket_path));
316
317   execvp(executor_argv[0], (char**)executor_argv);
318   diee("execute %s", executor_argv[0]);
319 }
320
321 static FILE *connect_or_spawn(void) {
322   int r;
323
324   FILE *call_sock = connect_existing();
325   if (call_sock) return call_sock;
326
327   int lockfd = acquire_lock();
328   call_sock = connect_existing();
329   if (call_sock) { close(lockfd); return call_sock; }
330
331   // We must start a fresh one, and we hold the lock
332
333   r = unlink(socket_path);
334   if (r<0) diee("failed to remove stale socket %s", socket_path);
335
336   int fake_pair[2];
337   r = socketpair(AF_UNIX, SOCK_STREAM, 0, fake_pair);
338   if (r<0) diee("socketpair() for fake initial connection");
339
340   int sfd = socket(AF_UNIX, SOCK_STREAM, 0);
341   if (sfd<0) diee("socket() for new listener");
342
343   socklen_t salen = sizeof(sun);
344   r= bind(sfd, (const struct sockaddr*)&socket_sun, salen);
345   if (r<0) diee("bind() on new listener");
346
347   // We never want callers to get ECONNREFUSED.  But:
348   // There is a race here: from my RTFM they may get ECONNREFUSED
349   // if they try between our bind() and listen().  But if they do, they'll
350   // acquire the lock (serialising with us) and retry, and then it will work.
351   r = listen(sfd, INT_MAX);
352   if (r<0) diee("listen() for new listener");
353
354   pid_t setup_pid = fork();
355   if (setup_pid == (pid_t)-1) diee("fork for spawn setup");
356   if (!setup_pid) become_setup(sfd, fake_pair);
357   close(fake_pair[1]);
358   close(sfd);
359
360   int status;
361   pid_t got = waitpid(setup_pid, &status, 0);
362   if (got == (pid_t)-1) diee("waitpid setup [%ld]", (long)setup_pid);
363   if (got != setup_pid) diee("waitpid setup [%ld] gave [%ld]!",
364                              (long)setup_pid, (long)got);
365   if (status != 0) propagate_exit_status(status, "setup");
366
367   close(lockfd);
368   return call_sock_from_fd(fake_pair[0]);
369 }
370
371 static void make_executor_argv(const char *const *argv) {
372   const char *arg;
373   #define EACH_NEW_ARG(EACH) {                  \
374     arg = interp; { EACH }                      \
375     if ((arg = script)) { EACH }                \
376     const char *const *walk = argv;             \
377     while ((arg = *walk++)) { EACH }            \
378   }
379
380   size_t count = 1;
381   EACH_NEW_ARG( (void)arg; count++; );
382
383   const char **out = calloc(count, sizeof(char*));
384   executor_argv = (const char* const*)out;
385   if (!executor_argv) diee("allocate for arguments");
386
387   EACH_NEW_ARG( *out++ = arg; );
388   *out++ = 0;
389 }  
390
391 int main(int argc_unused, const char *const *argv) {
392   process_opts(&argv);
393
394   // Now we have
395   //  - possibly interp
396   //  - possibly script
397   //  - remaining args
398   // which ought to be passed on to the actual executor.
399   make_executor_argv(argv);
400
401   find_socket_path();
402   FILLZERO(sun);
403   sun.sun_family = AF_UNIX;
404   assert(strlen(socket_path) <= sizeof(sun.sun_path));
405   strncpy(sun.sun_path, socket_path, sizeof(sun.sun_path));
406
407   FILE *call_sock = connect_or_spawn();
408   uint32_t status;
409   ssize_t sr = fread(&status, sizeof(status), 1, call_sock);
410   if (sr != 1) {
411     if (was_eof(call_sock)) die("per-call server monitor process quit");
412     diee("read status from call socket");
413   }
414
415   status = ntohl(status);
416   if (status > INT_MAX) die("status 0x%lx does not fit in an int",
417                             (unsigned long)status);
418
419   propagate_exit_status(status, "invocation");
420 }