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