chiark / gitweb /
prefork-interp: Protocol work
[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_string_list(size_t *len, char **buf,
192                                 const char *const *list) {
193   const char *s;
194   const char *const *p;
195   
196   size_t count = 0;
197   for (p = list; (s = *p++); ) count++;
198   char *count_s = m_asprintf("%zd", count);
199
200   prepare_string(len, buf, count_s);
201   for (p = list; (s = *p++); ) prepare_string(len, buf, s);
202 }
203
204 static void prepare_message(size_t *len, char **buf) {
205   prepare_string_list(len, buf, (const char* const*)environ);
206   prepare_string_list(len, buf, executor_argv);
207 }
208
209 static void send_fd(int payload_fd) {
210   int via_fd = fileno(call_sock);
211
212   union {
213     struct cmsghdr align;
214     char buf[CMSG_SPACE(sizeof(payload_fd))];
215   } cmsg_buf;
216
217   struct msghdr msg;
218   FILLZERO(msg);
219   FILLZERO(cmsg_buf);
220
221   char dummy_byte = 0;
222   struct iovec iov;
223   FILLZERO(iov);
224   iov.iov_base = &dummy_byte;
225   iov.iov_len = 1;
226
227   msg.msg_name = 0;
228   msg.msg_iov = &iov;
229   msg.msg_iovlen = 1;
230   msg.msg_control = cmsg_buf.buf;
231   msg.msg_controllen = sizeof(cmsg_buf.buf);
232
233   struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
234   cmsg->cmsg_level = SOL_SOCKET;
235   cmsg->cmsg_type = SCM_RIGHTS;
236   cmsg->cmsg_len = CMSG_LEN(sizeof(payload_fd));
237   *(int*)CMSG_DATA(cmsg) = payload_fd;
238
239   msg.msg_controllen = sizeof(cmsg_buf.buf);
240
241   for (;;) {
242     ssize_t r = sendmsg(via_fd, &msg, 0);
243     if (r == -1) {
244       if (errno == EINTR) continue;
245       diee("send fd");
246     }
247     assert(r == 1);
248     break;
249   }
250 }
251
252 static void send_request(void) {
253   // Sending these first makes it easier for the script to
254   // use buffered IO for the message.
255   send_fd(0);
256   send_fd(1);
257   send_fd(2);
258
259   size_t len = 0;
260   prepare_message(&len, 0);
261
262   char *m = xmalloc(len + 4);
263   char *p = m;
264   prepare_length(0, &p, len);
265   prepare_message(0, &p);
266   assert(p == m + len + 4);
267
268   ssize_t sr = fwrite(p, len, 1, call_sock);
269   if (sr != 1) diee("write request");
270 }
271
272 static FILE *call_sock_from_fd(int fd) {
273   int r;
274
275   FILE *call_sock = fdopen(fd, "r+");
276   if (!call_sock) diee("fdopen socket");
277
278   r = setvbuf(call_sock, 0, _IONBF, 0);
279   if (r) die("setvbuf socket");
280
281   return call_sock;
282 }
283
284 static bool was_eof(FILE *call_sock) {
285   return feof(call_sock) || errno==ECONNRESET;
286 }
287
288 // Returns -1 on EOF
289 static int protocol_read_maybe(void *data, size_t sz) {
290   size_t sr = fread(data, sz, 1, call_sock);
291   if (sr != 1) {
292     if (was_eof(call_sock)) return -1;
293     diee("read() on monitor call socket");
294   }
295   return 0;
296 }
297
298 static void protocol_read(void *data, size_t sz) {
299   if (protocol_read_maybe(data, sz) < 0)
300     die("monitor process quit unexpectedly");
301 }
302
303 // Returns 0 if OK, error msg if peer was garbage.
304 static const char *read_greeting(void) {
305   char got_magic[sizeof(header_magic)];
306
307   if (protocol_read_maybe(&got_magic, sizeof(got_magic)) < 0)
308     return "initial monitor process quit";
309
310   if (memcmp(got_magic, header_magic, sizeof(header_magic)))
311     die("got unexpected protocol magic 0x%02x%02x%02x%02x",
312         got_magic[0], got_magic[1], got_magic[2], got_magic[3]);
313
314   uint32_t xdata_len;
315   protocol_read(&xdata_len, sizeof(xdata_len));
316   void *xdata = xmalloc(xdata_len);
317   protocol_read(xdata, xdata_len);
318
319   return 0;
320 }
321
322 // Returns: call(client-end), or 0 to mean "is garbage"
323 // find_socket_path must have been called
324 static FILE *connect_existing(void) {
325   int r;
326   int fd = -1;
327
328   fd = socket(AF_UNIX, SOCK_STREAM, 0);
329   if (fd==-1) diee("socket() for client");
330
331   socklen_t salen = sizeof(sockaddr_sun);
332   r = connect(fd, (const struct sockaddr*)&sockaddr_sun, salen);
333   if (r==-1) {
334     if (errno==ECONNREFUSED || errno==ENOENT) goto x_garbage;
335     diee("connect() %s", socket_path);
336   }
337
338   call_sock = call_sock_from_fd(fd);
339   fd = -1;
340
341   if (read_greeting())
342     goto x_garbage;
343
344   return call_sock;
345
346  x_garbage:
347   if (call_sock) { fclose(call_sock); call_sock=0; }
348   if (fd >= 0) close(fd);
349   return 0;
350 }
351
352 static __attribute__((noreturn))
353 void become_setup(int sfd, int fake_pair[2]) {
354   close(fake_pair[0]);
355   int call_fd = fake_pair[1];
356
357   int null_0 = open("/dev/null", O_RDONLY);  if (null_0 < 0) diee("open null");
358   if (dup2(null_0, 0)) diee("dup2 /dev/null onto stdin");
359   if (dup2(2, 1) != 1) die("dup2 stderr onto stdout");
360
361   // Extension could work like this:
362   //
363   // We advertise a new protocol (perhaps one which is nearly entirely
364   // different after the connect) by putting a name for it comma-separated
365   // next to "v1".  Simple extension can be done by having the script
366   // side say something about it in the ack xdata, which we currently ignore.
367   putenv(m_asprintf("PREFORK_INTERP=v1 %d,%d %s",
368                     sfd, call_fd, socket_path));
369
370   execvp(executor_argv[0], (char**)executor_argv);
371   diee("execute %s", executor_argv[0]);
372 }
373
374 static void connect_or_spawn(void) {
375   int r;
376
377   call_sock = connect_existing();
378   if (call_sock) return;
379
380   int lockfd = acquire_lock();
381   call_sock = connect_existing();
382   if (call_sock) { close(lockfd); return; }
383
384   // We must start a fresh one, and we hold the lock
385
386   r = unlink(socket_path);
387   if (r<0 && errno!=ENOENT)
388     diee("failed to remove stale socket %s", socket_path);
389
390   int fake_pair[2];
391   r = socketpair(AF_UNIX, SOCK_STREAM, 0, fake_pair);
392   if (r<0) diee("socketpair() for fake initial connection");
393
394   int sfd = socket(AF_UNIX, SOCK_STREAM, 0);
395   if (sfd<0) diee("socket() for new listener");
396
397   socklen_t salen = sizeof(sockaddr_sun);
398   r= bind(sfd, (const struct sockaddr*)&sockaddr_sun, salen);
399   if (r<0) diee("bind() on new listener");
400
401   // We never want callers to get ECONNREFUSED.  But:
402   // There is a race here: from my RTFM they may get ECONNREFUSED
403   // if they try between our bind() and listen().  But if they do, they'll
404   // acquire the lock (serialising with us) and retry, and then it will work.
405   r = listen(sfd, INT_MAX);
406   if (r<0) diee("listen() for new listener");
407
408   pid_t setup_pid = fork();
409   if (setup_pid == (pid_t)-1) diee("fork for spawn setup");
410   if (!setup_pid) become_setup(sfd, fake_pair);
411   close(fake_pair[1]);
412   close(sfd);
413
414   call_sock = call_sock_from_fd(fake_pair[0]);
415
416   int status;
417   pid_t got = waitpid(setup_pid, &status, 0);
418   if (got == (pid_t)-1) diee("waitpid setup [%ld]", (long)setup_pid);
419   if (got != setup_pid) diee("waitpid setup [%ld] gave [%ld]!",
420                              (long)setup_pid, (long)got);
421   if (status != 0) propagate_exit_status(status, "setup");
422
423   const char *emsg = read_greeting();
424   if (emsg) die("setup failed: %s", emsg);
425
426   close(lockfd);
427   return;
428 }
429
430 static void make_executor_argv(const char *const *argv) {
431   switch (laundering) {
432   case 'U': break;
433   default: die("need -U (specifying unlaundered argument handling)");
434   }
435
436   const char *arg;
437   #define EACH_NEW_ARG(EACH) {                  \
438     arg = interp; { EACH }                      \
439     if ((arg = script)) { EACH }                \
440     const char *const *walk = argv;             \
441     while ((arg = *walk++)) { EACH }            \
442   }
443
444   size_t count = 1;
445   EACH_NEW_ARG( (void)arg; count++; );
446
447   const char **out = calloc(count, sizeof(char*));
448   executor_argv = (const char* const*)out;
449   if (!executor_argv) diee("allocate for arguments");
450
451   EACH_NEW_ARG( *out++ = arg; );
452   *out++ = 0;
453 }  
454
455 int main(int argc_unused, const char *const *argv) {
456   process_opts(&argv);
457
458   // Now we have
459   //  - possibly interp
460   //  - possibly script
461   //  - remaining args
462   // which ought to be passed on to the actual executor.
463   make_executor_argv(argv);
464
465   find_socket_path();
466   FILLZERO(sockaddr_sun);
467   sockaddr_sun.sun_family = AF_UNIX;
468   assert(strlen(socket_path) <= sizeof(sockaddr_sun.sun_path));
469   strncpy(sockaddr_sun.sun_path, socket_path, sizeof(sockaddr_sun.sun_path));
470
471   connect_or_spawn();
472
473   // We're committed now, send the request (or bail out)
474   send_request();
475
476   uint32_t status;
477   protocol_read(&status, sizeof(status));
478
479   status = ntohl(status);
480   if (status > INT_MAX) die("status 0x%lx does not fit in an int",
481                             (unsigned long)status);
482
483   propagate_exit_status(status, "invocation");
484 }