chiark / gitweb /
prefork-interp: fix a comment char
[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  * 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
15  */
16 /*
17  * Process structure:
18  *  client (C wrapper)        connects to server
19  *                              (including reading ack byte)
20  *                            if fails or garbage
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)
29  *
30  *     setup (pre-exec)       fd0: null,
31  *                            fd[12]: fd2-from-outer
32  *                            env fds: listener, call(server-end)(fake)
33  *                            close fd: lockfile
34  *                            possibly clean env, argv
35  *
36  *     setup (script)         runs initialisation parts of the script
37  *                            at prefork establishment point:
38  *     setup (pm) [1]         opens syslog
39  *                            forks for server
40  *                [2]         exits
41  *
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
51  *                            
52  *  [client (C wrapper)]      if client connect succeeds:
53  *                            now fd: call(client-end)
54  *                               sends message with: cmdline, env
55  *                               sends fds
56  *
57  *        [server (script)]   accepts, forks subseq monitor
58  *
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)
63  *                            sends ack byte
64  *                            receives args, env, fds
65  *                            forks executor
66  *
67  *            executor        sorts out fds:
68  *                            fd0, fd1, fd2: from-outer
69  *                            close fds: call(server-end)
70  *                            retained fds: syslog
71  *
72  *                            sets cmdline, env
73  *                            runs main part of script
74  *                            exits normally
75  *
76  *          [monitor]         [fd[012]: null]
77  *                            [fd[12]: init: fd2-from-outer; subseq: null]
78  *                            [errors: init: fd2; subseq: syslog]
79  *                            reaps executor
80  *                            reports status via socket
81  *
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)
86  */
87
88 #include <arpa/inet.h>
89
90 #include "prefork.h"
91
92 const char our_name[] = "prefork-interp";
93
94 struct sockaddr_un sockaddr_sun;
95
96 #define ACK_BYTE '\n'
97
98 static const char *const *executor_argv;
99
100 void fusagemessage(FILE *f) {
101   fprintf(f, "usage: #!/usr/bin/prefork-interp [<options>]\n");
102 }
103
104 static int laundering;
105
106 const struct cmdinfo cmdinfos[]= {
107   PREFORK_CMDINFOS
108   { 0, 'U',   0,                    .iassignto= &laundering,    .arg= 'U' },
109   { 0 }
110 };
111
112 void ident_addinit(void) {
113   char ident_magic[1] = { 0 };
114   sha256_update(&identsc, sizeof(ident_magic), ident_magic);
115 }
116
117 static void propagate_exit_status(int status, const char *what) {
118   int r;
119
120   if (WIFEXITED(status)) {
121     _exit(status);
122   }
123
124   if (WIFSIGNALED(status)) {
125     int sig = WTERMSIG(status);
126     const char *signame = strsignal(sig);
127     if (signame == 0) signame = "unknown signal";
128
129     if (! WCOREDUMP(status) &&
130         (sig == SIGINT ||
131          sig == SIGHUP ||
132          sig == SIGPIPE ||
133          sig == SIGKILL)) {
134       struct sigaction sa;
135       FILLZERO(sa);
136       sa.sa_handler = SIG_DFL;
137       r = sigaction(sig, &sa, 0);
138       if (r) diee("failed to reset signal handler while propagating %s",
139                   signame);
140       
141       sigset_t sset;
142       sigemptyset(&sset);
143       sigaddset(&sset, sig);
144       r = sigprocmask(SIG_UNBLOCK, &sset, 0);
145       if (r) diee("failed to reset signal block while propagating %s",
146                   signame);
147
148       raise(sig);
149       die("unexpectedly kept running after raising (to propagate) %s",
150           signame);
151     }
152
153     die("%s failed due to signal %d %s%s", what, sig, signame,
154         WCOREDUMP(status) ? " (core dumped)" : "");
155   }
156
157   die("%s failed with weird wait status %d 0x%x", what, status, status);
158 }
159
160 static __attribute((noreturn)) void die_data_overflow(void) {
161   die("cannot handle data with length >2^32");
162 }
163
164 static void prepare_data(size_t *len, char **buf,
165                          const void *data, size_t dl) {
166   if (len) {
167     if (dl >= SIZE_MAX - *len)
168       die_data_overflow();
169     *len += dl;
170   }
171   if (buf) {
172     memcpy(*buf, data, dl);
173     *buf += dl;
174   }
175 }
176   
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));
181 }
182
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);
186 }
187
188 static void prepare_message(size_t *len, char **buf) {
189   const char *s;
190
191   const char *const *p = (void*)environ;
192   while ((s = *p++)) {
193     if (strchr(s, '='))
194       prepare_string(len, buf, s);
195   }
196
197   prepare_string(len, buf, "");
198
199   p = executor_argv;
200   while ((s = *p++))
201     prepare_string(len, buf, s);
202 }
203
204 static void send_fd(FILE *call_sock, int payload_fd) {
205   int via_fd = fileno(call_sock);
206
207   union {
208     struct cmsghdr align;
209     char buf[CMSG_SPACE(sizeof(payload_fd))];
210   } cmsg_buf;
211
212   struct msghdr msg;
213   FILLZERO(msg);
214   FILLZERO(cmsg_buf);
215
216   char dummy_byte = 0;
217   struct iovec iov;
218   FILLZERO(iov);
219   iov.iov_base = &dummy_byte;
220   iov.iov_len = 1;
221
222   msg.msg_name = 0;
223   msg.msg_iov = &iov;
224   msg.msg_iovlen = 1;
225   msg.msg_control = cmsg_buf.buf;
226   msg.msg_controllen = sizeof(cmsg_buf.buf);
227
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;
233
234   msg.msg_controllen = sizeof(cmsg_buf.buf);
235
236   for (;;) {
237     ssize_t r = sendmsg(via_fd, &msg, 0);
238     if (r == -1) {
239       if (errno == EINTR) continue;
240       diee("send fd");
241     }
242     assert(r == 1);
243     break;
244   }
245 }
246
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);
253
254   size_t len = 4;
255   prepare_message(&len, 0);
256   char *m = malloc(len);
257   if (!m) diee("failed to allocate for message");
258   char *p = m;
259   prepare_length(0, &p, len - 4);
260   prepare_message(0, &p);
261   assert(p == m + len);
262
263   ssize_t sr = fwrite(p, len, 1, call_sock);
264   if (sr != 1) diee("write request");
265 }
266
267 static FILE *call_sock_from_fd(int fd) {
268   int r;
269
270   FILE *call_sock = fdopen(fd, "r+");
271   if (!call_sock) diee("fdopen socket");
272
273   r = setvbuf(call_sock, 0, _IONBF, 0);
274   if (r) die("setvbuf socket");
275
276   return call_sock;
277 }
278
279 static bool was_eof(FILE *call_sock) {
280   return feof(call_sock) || errno==ECONNRESET;
281 }
282
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) {
286   int r;
287   int fd = -1;
288   FILE *call_sock = 0;
289
290   fd = socket(AF_UNIX, SOCK_STREAM, 0);
291   if (fd==-1) diee("socket() for client");
292
293   socklen_t salen = sizeof(sockaddr_sun);
294   r = connect(fd, (const struct sockaddr*)&sockaddr_sun, salen);
295   if (r==-1) {
296     if (errno==ECONNREFUSED || errno==ENOENT) goto x_garbage;
297     diee("connect() %s", socket_path);
298   }
299
300   call_sock = call_sock_from_fd(fd);
301   fd = -1;
302
303   char ack;
304   size_t sr = fread(&ack, sizeof(ack), 1, call_sock);
305   if (sr != 1) {
306     if (was_eof(call_sock)) goto x_garbage;
307     diee("read() ack byte");
308   }
309   if (ack != '\n') die("got ack byte 0x%02x, not '\n'", ack);
310
311   // We're committed now, send the request (or bail out)
312   send_request(call_sock);
313
314   return call_sock;
315
316  x_garbage:
317   if (call_sock) fclose(call_sock);
318   if (fd >= 0) close(fd);
319   return 0;
320 }
321
322 static __attribute__((noreturn))
323 void become_setup(int sfd, int fake_pair[2]) {
324   close(fake_pair[0]);
325   int call_fd = fake_pair[1];
326
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");
329
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");
333
334   putenv(m_asprintf("PREFORK_INTERP=%d,%d,%d,%d,%s",
335                     sfd, call_fd, fd0_save, fd1_save, socket_path));
336
337   execvp(executor_argv[0], (char**)executor_argv);
338   diee("execute %s", executor_argv[0]);
339 }
340
341 static FILE *connect_or_spawn(void) {
342   int r;
343
344   FILE *call_sock = connect_existing();
345   if (call_sock) return call_sock;
346
347   int lockfd = acquire_lock();
348   call_sock = connect_existing();
349   if (call_sock) { close(lockfd); return call_sock; }
350
351   // We must start a fresh one, and we hold the lock
352
353   r = unlink(socket_path);
354   if (r<0 && errno!=ENOENT)
355     diee("failed to remove stale socket %s", socket_path);
356
357   int fake_pair[2];
358   r = socketpair(AF_UNIX, SOCK_STREAM, 0, fake_pair);
359   if (r<0) diee("socketpair() for fake initial connection");
360
361   int sfd = socket(AF_UNIX, SOCK_STREAM, 0);
362   if (sfd<0) diee("socket() for new listener");
363
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");
367
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");
374
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);
378   close(fake_pair[1]);
379   close(sfd);
380
381   int status;
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");
387
388   close(lockfd);
389   return call_sock_from_fd(fake_pair[0]);
390 }
391
392 static void make_executor_argv(const char *const *argv) {
393   switch (laundering) {
394   case 'U': break;
395   default: die("need -U (specifying unlaundered argument handling)");
396   }
397
398   const char *arg;
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 }            \
404   }
405
406   size_t count = 1;
407   EACH_NEW_ARG( (void)arg; count++; );
408
409   const char **out = calloc(count, sizeof(char*));
410   executor_argv = (const char* const*)out;
411   if (!executor_argv) diee("allocate for arguments");
412
413   EACH_NEW_ARG( *out++ = arg; );
414   *out++ = 0;
415 }  
416
417 int main(int argc_unused, const char *const *argv) {
418   process_opts(&argv);
419
420   // Now we have
421   //  - possibly interp
422   //  - possibly script
423   //  - remaining args
424   // which ought to be passed on to the actual executor.
425   make_executor_argv(argv);
426
427   find_socket_path();
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));
432
433   FILE *call_sock = connect_or_spawn();
434   uint32_t status;
435   ssize_t sr = fread(&status, sizeof(status), 1, call_sock);
436   if (sr != 1) {
437     if (was_eof(call_sock)) die("per-call server monitor process quit");
438     diee("read status from call socket");
439   }
440
441   status = ntohl(status);
442   if (status > INT_MAX) die("status 0x%lx does not fit in an int",
443                             (unsigned long)status);
444
445   propagate_exit_status(status, "invocation");
446 }