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