chiark / gitweb /
prefork-interp: wip
[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-caller
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-caller
26  *                            env fds: listener, call(server-end)(fake)
27  *                            env fds: orig-fd[01]
28  *                            close fd: lockfile
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-caller]
38  *                            right away, forks one fa-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 fa-monitor)
44  *                            reports failures of monitors to syslog
45  *                            
46  *         f-a monitor        forks executor
47  *                            closes fd: listener
48  *                            [fd[12: fd2-from-outer-caller]
49  *                            [other fds: call(server-end)(fake), syslog]
50  *                            runs as monitor, below
51  *
52  *
53  *  [client (C wrapper)]      if client connect succeeds:
54  *                            now fd: call(client-end)
55  *                               sends message with: cmdline, env
56  *                               sends fds
57  *
58  *        [server (script)]   accepts, forks monitor
59  *
60  *          monitor [1]       [fd[012]: null]
61  *                            other fds: syslog, call(server-end)
62  *                            sends ack byte
63  *                            receives args, env, fds
64  *                            forks executor
65  *
66  *            executor        sorts out fds:
67  *                            fd0, fd1, fd2: from-outer-caller
68  *                            close fds: call(server-end)
69  *                            retained fds: syslog
70  *
71  *                            sets cmdline, env
72  *                            runs main part of script
73  *                            exits normally
74  *
75  *          [monitor]         [fd[012]: null]
76  *                            [other fds: call(server-end), syslog]
77  *                            reaps executor
78  *                            reports status via socket
79  *
80  *    [client (C wrapper)]    [fd0, fd1, fd2: from-outer-caller]
81  *                            [other fd: call(client-end)]
82  *                            receives status, exits appropriately
83  *                            (if was bad signal, reports to stderr, exits 127)
84  */
85
86 struct sockaddr_un sun;
87
88 #define ACK_BYTE '\n'
89
90 static struct sockaddr_unix socket_sun;
91 static const char *const *executor_argv;
92
93 static void propagate_exit_status(int status, const char *what) {
94   int r;
95
96   if (WIFEXITED(status)) {
97     _exit(status);
98   }
99
100   if (WIFSIGNALED(status)) {
101     int sig = WTERMSIG(status);
102     char *signame = strsignal(sig);
103     if (signame == 0) signame = "unknown signal";
104
105     if (! WCOREDUMP(status) &&
106         (sig == SIGINT ||
107          sig == SIGHUP ||
108          sig == SIGPIPE ||
109          sig == SIGKILL)) {
110       struct sigaction sa;
111       FILLZERO(sa);
112       sa.sa_handler = SIG_DFL;
113       r = sigaction(sig, &sa, 0);
114       if (r) diee("failed to reset signal handler while propagating %s",
115                   signame);
116       
117       sigset_t sset;
118       sigemptyset(&sset);
119       sigaddset(&sset, sig);
120       r = sigprocmask(SA_UNBLOCK, sset, 0);
121       if (r) diee("failed to reset signal block while propagating %s",
122                   signame);
123
124       raise(sig);
125       die("unexpectedly kept running after raising (to propagate) %s",
126           signame);
127     }
128
129     die("setup failed due to signal %d %s%s", sig, signame,
130         WCOREDUMP(status) ? " (core dumped)" : "");
131   }
132
133   die("setup failed with weird wait status %d 0x%x", status, status);
134 }
135
136 static void die_data_overflow __attribute((noreturn)) {
137   die("cannot handle data with length >2^32");
138 }
139
140 static void prepare_data(size_t *len, char **buf,
141                          const void *data, size_t dl) {
142   if (len) {
143     if (dl >= SIZE_MAX - *len)
144       die_data_overlow();
145     *len += dl;
146   }
147   if (buf) {
148     memcpy(*buf, data, dl);
149     *buf += dl;
150   }
151 }
152   
153 static void prepare_length(size_t *len, char **buf, size_t dl) {
154   if (dl > UINT32_MAX) die_data_overflow();
155   uint32_t dl = htonl(dl);
156   prepare_data(len, buf, &dl, sizeof(dl));
157 }
158
159 static void prepare_string(size_t *len, char **buf, const char *string) {
160   size_t sl = strlen(s);
161   prepare_data(len, buf, s, sl+1);
162 }
163
164 static void prepare_message(size_t *len, char **buf) {
165   const char *s;
166
167   const char *const *p = environ;
168   while ((s = *p++)) {
169     if (strchr(s, '='))
170       prepare_string(len, buf, s);
171   }
172
173   prepare_string(len, buf, "");
174
175   p = executor_argv;
176   while ((s = *p++))
177     prepare_string(len, buf, s);
178 }
179
180 static void send_fd(int via_fd, int payload_fd) {
181   union {
182     struct cmsghdr align;
183     char buf[CMSG_SPACE(sizeof(payload_fd))];
184   } msg;
185   struct msghdr msg;
186   FILLZERO(msg);
187
188   struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
189   cmsg->cmsg_level = SOL_SOCKET;
190   cmsg->cmsg_type = SCM_RIGHTS;
191   cmsg->cmsg_len = CMSG_LEN(sizeof(payload_fd));
192   *(int*)CMSG_DATA(cmsg) = payload_fd;
193
194   char dummy_byte = 0;
195
196   struct iovec iov;
197   FIULLZERO(iov);
198   iov.iov_base = &dummy_byte;
199   iov.iov_len = 1;
200
201   msg.msg_name = 0;
202   msg.msg_iov = &iov;
203   msg.msg_iovlen = 1;
204   msg.msg_control = msg.buf;
205   msg.msg_controllen = sizeof(msg.buf);
206
207   for (;;) {
208     ssize_t r = sendmsg(via_fd, &msg, 0);
209     if (r == -1) {
210       if (errno == EINTR) continue;
211       diee("send fd");
212     }
213     assert!(r == 1);
214     break;
215   }
216 }
217
218 static void send_request(int call_fd, const char *const *argv) {
219   // Sending these first makes it easier for the script to
220   // use buffered IO for the message.
221   send_fd(call_fd, 0);
222   send_fd(call_fd, 1);
223   send_fd(call_fd, 2);
224
225   size_t len = 4;
226   prepare_message(&len, 0, argv);
227   char *m = malloc(len);
228   if (!m) diee("failed to allocate for message");
229   char *p = m;
230   prepare_length(0, &p, len - 4);
231   prepare_message(0, &p, argv);
232   assert(p == m + len);
233
234   p = m;
235   while (len) {
236     ssize_t r = write(call_fd, p, len);
237     if (r==-1) {
238       if (errno == EINTR) continue;
239       diee("write request");
240     }
241     assert(r <= len);
242     assert(r > 0);
243     len -= r;
244     p += r;
245   }
246 }
247
248 // Returns: call(client-end) fd, or -1 to mean "is garbage"
249 // find_socket_path must have been called
250 static int connect_existing(void) {
251   int r;
252   int fd = -1;
253
254   bool isgarbage = check_garbage();
255   if (isgarbage) goto x_garbage;
256
257   fd = socket(AF_UNIX, SOCK_STREAM, 0);
258   if (fd==-1) diee("socket() for client");
259
260   salen_t salen = sizeof(sun);
261   r = connect(client, (const struct sockaddr*)&socket_sun, salen);
262   if (r==-1) {
263     if (errno==ECONNREFUSED || errno==ENOENT) goto x_garbgae;
264     diee("connect() %s", socket_path);
265   }
266
267   for (;;) {
268     char ack;
269     sr = read(fd, &ack, 1);
270     if (sr == -1) {
271       if (errno==ECONNRESET) goto x_garbage;
272       if (errno==EINTR) continue;
273       diee("read() ack byte");
274     }
275     if (sr == 0) { goto x_garbage; }
276     if (ack != '\n') die("got ack byte 0x%02x, not '\n'", ack);
277     break;
278   }
279
280   // We're committed now, send the request (or bail out)
281   send_request(call, argv);
282
283   return fd;
284
285  x_garbage:
286   if (fd >= 0) close(fd);
287   return -1;
288 }
289
290 static void become_setup(int sfd, int fake_pair[2])
291   __attribute__((noreturn))
292 {
293   close(fake_pair[0]);
294   int call_fd = fake_pair[1];
295
296   int fd0_save = dup(0);  if (fd0_save < 0) diee("dup stdin");
297   int fd1_save = dup(1);  if (fd1_save < 0) diee("dup stdin");
298
299   int null_0 = open("/dev/null", O_RDONLY);  if (null_0 < 0) diee("open null");
300   if (dup2(null_0, 0)) diee("dup2 /dev/null onto stdin");
301   if (dup2(2, 1) != 1) die("dup2 stderr onto stdout");
302
303   putenv(asprintf("PREFORK_INTERP=%d,%d,%d,%d,%s",
304                   sfd, call_fd, fd0_save, fd1_save, socket_path));
305
306   execvp(executor_argv[0], executor_argv);
307   diee("execute %s", executor_argv[0]);
308 }
309
310 static int connect_or_spawn(void) {
311   int fd = connect_existing();
312   if (fd >= 0) return fd;
313
314   int lockfd = acquire_lock();
315   fd = connect_existing();
316   if (fd >= 0) { close(lockfd); return fd; }
317
318   // We must start a fresh one, and we hold the lock
319
320   r = unlink(socketpath);
321   if (r<0) diee("failed to remove stale socket %s", socketpath);
322
323   int fake_pair[2];
324   r = socketpair(AF_UNIX, SOCK_STREAM, 0, fake_pair);
325   if (r<0) diee("socketpair() for fake initial connection");
326
327   int sfd = socket(AF_UNIX, SOCK_STREAM, 0);
328   if (sfd<0) diee("socket() for new listener");
329
330   salen_t salen = sizeof(sun);
331   r= bind(sfd, (const struct sockaddr*)&socket_sun, saledn);
332   if (r<0) diee("bind() on new listener");
333
334   // We never want callers to get ECONNREFUSED!.
335   // There is a race here: from my RTFM they may get ECONNREFUSED
336   // if they tr between our bind() and listen().  But if they do, they'll
337   // acquire the lock (serialising with us) and retry, and then it will work.
338   r = listen(sfd, INT_MAX);
339   if (r<0) diee("listen() for new listener");
340
341   pid_t setup_pid = fork();
342   if (setup_pid == (pid_t)-1) diee("fork for spawn setup");
343   if (!setup_pid) become_setup(sfd, fake_pair);
344   close(fake_pair[1]);
345   close(sfd);
346
347   int status;
348   pid_t got = waitpid(setup_pid, &status, 0);
349   if (got == (pid_t)-1) diee("waitpid setup [%ld]", (long)setup_pid);
350   if (got != setup_pid) diee("waitpid setup [%ld] gave [%ld]!",
351                              (long)setup_pid, (long)got);
352   if (status != 0) propagate_exit_status(status);
353
354   close(lockfd);
355   return fake_pair[0];
356 }
357
358 static void make_executor_argv(const char *const *argv) {
359   #define EACH_NEW_ARGV(EACH) {                 \
360     arg = interp; { EACH }                      \
361     if ((arg = script)) { EACH }                \
362     const char *const *walk = argv;             \
363     while ((arg = *walk++)) { EACH }            \
364   }
365
366   size_t count = 1;
367   MAKE_NEW_ARGV( (void)arg; count++; );
368
369   executor_argv = calloc(count, sizeof(char*));
370   if (!executor_argv) diee("allocate for arguments");
371
372   char **out = executor_argv;
373   MAKE_NEW_ARGV( *out++ = arg; );
374   *out++ = 0;
375 }  
376
377 int main(int argc_unused, const char *const *argv) {
378   process_opts(&argv);
379
380   // Now we have
381   //  - possibly interp
382   //  - possibly script
383   //  - remaining args
384   // which ought to be passed on to the actual executor.
385   make_executor_argv(argv);
386
387   find_socket_path();
388   FILLZERO(sun);
389   sun.sun_family = AF_UNIX;
390   assert(strlen(socket_path) <= sizeof(sun.sun_path));
391   strncpy(sun.sun_path, socket_path, sizeof(sun.sun_path));
392
393   int call_fd = connect_or_spawn();
394 }