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