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