chiark / gitweb /
prefork-interp: make sockaddr_sun static
[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
96 #define ACK_BYTE '\n'
97
98 static const char *const *executor_argv;
99
100 static const char header_magic[4] = "PFI\n";
101
102 void fusagemessage(FILE *f) {
103   fprintf(f, "usage: #!/usr/bin/prefork-interp [<options>]\n");
104 }
105
106 static int laundering;
107
108 const struct cmdinfo cmdinfos[]= {
109   PREFORK_CMDINFOS
110   { 0, 'U',   0,                    .iassignto= &laundering,    .arg= 'U' },
111   { 0 }
112 };
113
114 void ident_addinit(void) {
115   char ident_magic[1] = { 0 };
116   sha256_update(&identsc, sizeof(ident_magic), ident_magic);
117 }
118
119 static void propagate_exit_status(int status, const char *what) {
120   int r;
121
122   if (WIFEXITED(status)) {
123     _exit(status);
124   }
125
126   if (WIFSIGNALED(status)) {
127     int sig = WTERMSIG(status);
128     const char *signame = strsignal(sig);
129     if (signame == 0) signame = "unknown signal";
130
131     if (! WCOREDUMP(status) &&
132         (sig == SIGINT ||
133          sig == SIGHUP ||
134          sig == SIGPIPE ||
135          sig == SIGKILL)) {
136       struct sigaction sa;
137       FILLZERO(sa);
138       sa.sa_handler = SIG_DFL;
139       r = sigaction(sig, &sa, 0);
140       if (r) diee("failed to reset signal handler while propagating %s",
141                   signame);
142       
143       sigset_t sset;
144       sigemptyset(&sset);
145       sigaddset(&sset, sig);
146       r = sigprocmask(SIG_UNBLOCK, &sset, 0);
147       if (r) diee("failed to reset signal block while propagating %s",
148                   signame);
149
150       raise(sig);
151       die("unexpectedly kept running after raising (to propagate) %s",
152           signame);
153     }
154
155     die("%s failed due to signal %d %s%s", what, sig, signame,
156         WCOREDUMP(status) ? " (core dumped)" : "");
157   }
158
159   die("%s failed with weird wait status %d 0x%x", what, status, status);
160 }
161
162 static __attribute((noreturn)) void die_data_overflow(void) {
163   die("cannot handle data with length >2^32");
164 }
165
166 static void prepare_data(size_t *len, char **buf,
167                          const void *data, size_t dl) {
168   if (len) {
169     if (dl >= SIZE_MAX - *len)
170       die_data_overflow();
171     *len += dl;
172   }
173   if (buf) {
174     memcpy(*buf, data, dl);
175     *buf += dl;
176   }
177 }
178   
179 static void prepare_length(size_t *len, char **buf, size_t dl_sz) {
180   if (dl_sz > UINT32_MAX) die_data_overflow();
181   uint32_t dl = htonl(dl_sz);
182   prepare_data(len, buf, &dl, sizeof(dl));
183 }
184
185 static void prepare_string(size_t *len, char **buf, const char *s) {
186   size_t sl = strlen(s);
187   prepare_data(len, buf, s, sl+1);
188 }
189
190 static void prepare_message(size_t *len, char **buf) {
191   const char *s;
192
193   const char *const *p = (void*)environ;
194   while ((s = *p++)) {
195     if (strchr(s, '='))
196       prepare_string(len, buf, s);
197   }
198
199   prepare_string(len, buf, "");
200
201   p = executor_argv;
202   while ((s = *p++))
203     prepare_string(len, buf, s);
204 }
205
206 static void send_fd(FILE *call_sock, int payload_fd) {
207   int via_fd = fileno(call_sock);
208
209   union {
210     struct cmsghdr align;
211     char buf[CMSG_SPACE(sizeof(payload_fd))];
212   } cmsg_buf;
213
214   struct msghdr msg;
215   FILLZERO(msg);
216   FILLZERO(cmsg_buf);
217
218   char dummy_byte = 0;
219   struct iovec iov;
220   FILLZERO(iov);
221   iov.iov_base = &dummy_byte;
222   iov.iov_len = 1;
223
224   msg.msg_name = 0;
225   msg.msg_iov = &iov;
226   msg.msg_iovlen = 1;
227   msg.msg_control = cmsg_buf.buf;
228   msg.msg_controllen = sizeof(cmsg_buf.buf);
229
230   struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
231   cmsg->cmsg_level = SOL_SOCKET;
232   cmsg->cmsg_type = SCM_RIGHTS;
233   cmsg->cmsg_len = CMSG_LEN(sizeof(payload_fd));
234   *(int*)CMSG_DATA(cmsg) = payload_fd;
235
236   msg.msg_controllen = sizeof(cmsg_buf.buf);
237
238   for (;;) {
239     ssize_t r = sendmsg(via_fd, &msg, 0);
240     if (r == -1) {
241       if (errno == EINTR) continue;
242       diee("send fd");
243     }
244     assert(r == 1);
245     break;
246   }
247 }
248
249 static void send_request(FILE *call_sock) {
250   // Sending these first makes it easier for the script to
251   // use buffered IO for the message.
252   send_fd(call_sock, 0);
253   send_fd(call_sock, 1);
254   send_fd(call_sock, 2);
255
256   size_t len = 4;
257   prepare_message(&len, 0);
258   char *m = malloc(len);
259   if (!m) diee("failed to allocate for message");
260   char *p = m;
261   prepare_length(0, &p, len - 4);
262   prepare_message(0, &p);
263   assert(p == m + len);
264
265   ssize_t sr = fwrite(p, len, 1, call_sock);
266   if (sr != 1) diee("write request");
267 }
268
269 static FILE *call_sock_from_fd(int fd) {
270   int r;
271
272   FILE *call_sock = fdopen(fd, "r+");
273   if (!call_sock) diee("fdopen socket");
274
275   r = setvbuf(call_sock, 0, _IONBF, 0);
276   if (r) die("setvbuf socket");
277
278   return call_sock;
279 }
280
281 static bool was_eof(FILE *call_sock) {
282   return feof(call_sock) || errno==ECONNRESET;
283 }
284
285 // Returns -1 on EOF
286 static int protocol_read_maybe(FILE *call_sock, void *data, size_t sz) {
287   size_t sr = fread(data, sz, 1, call_sock);
288   if (sr != 1) {
289     if (was_eof(call_sock)) return -1;
290     diee("read() on monitor call socket");
291   }
292   return 0;
293 }
294
295 static void protocol_read(FILE *call_sock, void *data, size_t sz) {
296   if (protocol_read_maybe(call_sock, data, sz) < 0)
297     die("monitor process quit unexpectedly");
298 }
299
300 // Returns 0 if OK, error msg if peer was garbage.
301 static const char *protocol_greeting(FILE *call_sock) {
302   char got_magic[sizeof(header_magic)];
303
304   if (protocol_read_maybe(call_sock, &got_magic, sizeof(got_magic)) < 0)
305     return "initial monitor process quit";
306
307   if (memcmp(got_magic, header_magic, sizeof(header_magic)))
308     die("got unexpected protocol magic 0x%02x%02x%02x%02x",
309         got_magic[0], got_magic[1], got_magic[2], got_magic[3]);
310
311   uint32_t xdata_len;
312   protocol_read(call_sock, &xdata_len, sizeof(xdata_len));
313   void *xdata = xmalloc(xdata_len);
314   protocol_read(call_sock, xdata, xdata_len);
315
316   return 0;
317 }
318
319 // Returns: call(client-end), or 0 to mean "is garbage"
320 // find_socket_path must have been called
321 static FILE *connect_existing(void) {
322   int r;
323   int fd = -1;
324   FILE *call_sock = 0;
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 (protocol_greeting(call_sock))
340     goto x_garbage;
341
342   return call_sock;
343
344  x_garbage:
345   if (call_sock) fclose(call_sock);
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 FILE *connect_or_spawn(void) {
373   int r;
374
375   FILE *call_sock = connect_existing();
376   if (call_sock) return call_sock;
377
378   int lockfd = acquire_lock();
379   call_sock = connect_existing();
380   if (call_sock) { close(lockfd); return call_sock; }
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 = protocol_greeting(call_sock);
422   if (emsg) die("setup failed: %s", emsg);
423
424   close(lockfd);
425   return call_sock;
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   FILE *call_sock = connect_or_spawn();
470
471   // We're committed now, send the request (or bail out)
472   send_request(call_sock);
473
474   uint32_t status;
475   protocol_read(call_sock, &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 }