chiark / gitweb /
prefork-interp: diagrams
[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 /*
18                                    
19                                                  
20                                                  
21   State during service execution, process parentage and key fds
22
23     ---- pipes, sockets   
24     012  descriptors      
25     -==- fds shared       
26     ||   process parentage
27     &&   session leader (daemon) 
28     &    process group leader    
29                              
30       CALLER                 
31         ||                   
32         ||                   
33         ||                               listen     watch-err/in
34         ||       call                 (accept) \     ,------2          
35         || ,-----------------------------.     SERVER -----0 WATCHER(C) 
36       CLIENT 2--=fdpassed>=---------.     \      || &&          |      &&
37        (C)  1--=fdpassed>=---------. \     \     ||           inotify    
38            0--=fdpassed>=---------. \ \     \    ||           sockpath   
39                                    \ \ \     \   ||                      
40                                    | | |\     |  || 
41                                    | | | \    |  || 
42                                    | \ |  \   \  ||
43                                     \ \ \  \   MONITOR &
44                                      \ \ \  `12  ||  |  
45                                       \ \ \      ||  |  
46                                        \ \ \     ||  |execterm
47                                         \ \ \    ||  |  
48                                          \ \ \   ||  |  
49                                           \ \ 2  ||  |  
50                                            \ 1 EXECUTOR 
51                                             0           
52                                                         
53  Control flow and causality                             
54                                                         
55     | - \ /    process control flow                     
56     ...        causes mediated by fds or other IPC etc. 
57     &&         session leader (daemon)
58     &          process group leader
59                                              
60      CALLER                                  
61          |                                   
62          |fork/exec                          
63          |                                   
64      CLIENT(C)                               
65       tidy up stale sockets etc.             
66       acquire lock                           
67       create listening socket                
68          |                                   
69       fork/daemonise                         
70          |    `------------------.           
71          |                      WATCHER(C) &&
72          |                                  
73        make "fake" initial call socketpair  
74          |                                  
75        fork/exec                            
76          |      `------.                    
77          |           SCRIPT (setup)         
78          |             |                    
79          |          script initialisation   
80          |             |                    
81          |          identify fds from envirnment
82          |          open syslog                 
83          |             |                           
84          |          dzemonize
85          |   ,...../   |                           
86       waitpid          |                           
87          |           fork for initial service            
88          |             |child        |parent                 
89          |             |             |                       
90          |             |         SCRIPT [server] &&
91          |             |             |                       
92          |             |         ** accept / event loop **   
93          |             |            /            \ \ \                   
94          |             |        accepted?         \ \ \idle timeout?     
95          |             |           |               \ \ \                 
96          |             |        fork child          \ \ \                
97          |             | _________/            watch | |watch stderr eof?
98          |             |/                      stderr| | |          
99          |        SCRIPT [monitor]                   | | |   
100          |             |                      log msg  | |   
101          |        send greeting                      | | |   
102       read greeting    |                             | | |   
103          |             |                             exit    
104       release lock     |                                     
105          |             |                                     
106       send fds....     |                                     
107          |        receive fds                                
108          |             |                                     
109          |         fork for executor                         
110          |             |       \                             
111          |             |        \child
112          |             |         \                       
113          |             |        setpgrp &                
114          |             |        execute service          
115          |             |            |                    
116          |       wait for read      |    
117          |         (select)         |    
118          |           |   |          |          
119          |               |        exits  
120          |               |        kernel closes execterm
121          |               | ,......./|                   
122          |         execterm?        |    
123          |               |        zombie 
124          |               | ,....../      
125          |          waitpid              
126          |               |               
127          |          send exit status     
128       read exit status                   
129                                          
130                                          
131   Or, if client is killed                
132                                          
133          |             |            |          
134          |       wait for read      |    
135          |         (select)         |    
136          |           |   |          |          
137        exits         |              |    
138          |           |              |    
139      kernel closes   |              |    
140                 \....|              |    
141                      call?          |    
142                      |              |    
143                kill whole pgrp...   |    
144                          |       killled
145                          |        zombie
146                          | ,....../
147                     waitpid
148                          |  
149                     send exit status
150                     die due to SIGPIPE
151          
152                 
153  */                 
154 /*
155  * Process structure:
156  *  client (C wrapper)        connects to server
157  *                              (including reading ack byte)
158  *                            if fails or garbage
159  *                            === acquires lock ===
160  *                            makes new listening socket
161  *                            makes watcher pipes
162  *                            forks watcher and awaits
163  *                            makes first-instance socketpair
164  *                            forks setup (script, sock fds indicated in env)
165  *                            fd0, fd1, fd2: from-outer
166  *                            other fd: call(client-end)(fake)
167  *                            reaps setup (and reports error)
168  *                            (implicitly releases lock)
169  *
170  *     watcher                fd[012]: watcher pipes
171  *                            starts watch on socket path
172  *                            sets stderr to line buffered
173  *                            sets stdin to nonblocking
174  *                            daemonises (one fork, becomes session leader)
175  *                            when socket stat changes, quit
176  *
177  *     setup (pre-exec)       fd0: null,
178  *                            fd[12]: fd2-from-outer
179  *                            env fds: listener, call(server-end)(fake),
180  *                                      watcher read, watcher write
181  *                            close fd: lockfile
182  *                            possibly clean env, argv
183  *
184  *     setup (script)         runs initialisation parts of the script
185  *                            at prefork establishment point:
186  *     setup (pm) [1]         opens syslog
187  *                            forks for server
188  *                [2]         exits
189  *
190  *        server (pm) [1]     [fd0: null],
191  *                            [fd[12]: fd2-from-outer]
192  *                            setsid
193  *                            right away, forks init monitor
194  *                    [2]     closes outer caller fds and call(fake)
195  *        [server (pm)]       fd[012]: null
196  *                            other fds: listener, syslog
197  *                            runs in loop accepting and forking,
198  *                            reaping and limiting children (incl init monitor)
199  *                            reports failures of monitors to syslog
200  *
201  *  [client (C wrapper)]      if client connect succeeds:
202  *                            now fd: call(client-end)
203  *                               sends message with: cmdline, env
204  *                               sends fds
205  *
206  *        [server (script)]   accepts, forks subseq monitor
207  *
208  *          monitor [1]       [fd0: null]
209  *           (init            [fd[12]: init: fd2-from-outer; subseq: null]
210  *             or             errors: init: fd2; subseq: syslog
211  *            subseq)         other fds: syslog, call(server-end)
212  *                            sends ack byte
213  *                            receives args, env, fds
214  *                            forks executor
215  *
216  *            executor        sorts out fds:
217  *                            fd0, fd1, fd2: from-outer
218  *                            close fds: call(server-end)
219  *                            retained fds: syslog
220  *
221  *                            sets cmdline, env
222  *                            runs main part of script
223  *                            exits normally
224  *
225  *          [monitor]         [fd[012]: null]
226  *                            [fd[12]: init: fd2-from-outer; subseq: null]
227  *                            [errors: init: fd2; subseq: syslog]
228  *                            reaps executor
229  *                            reports status via socket
230  *
231  *    [client (C wrapper)]    [fd0, fd1, fd2: from-outer]
232  *                            [other fd: call(client-end)]
233  *                            receives status, exits appropriately
234  *                            (if was bad signal, reports to stderr, exits 127)
235  */
236
237 #include <arpa/inet.h>
238
239 #include <uv.h>
240
241 #include "prefork.h"
242
243 const char our_name[] = "prefork-interp";
244
245 static struct sockaddr_un sockaddr_sun;
246 static FILE *call_sock;
247
248 #define ACK_BYTE '\n'
249
250 static const char *const *executor_argv;
251
252 static const char header_magic[4] = "PFI\n";
253
254 void fusagemessage(FILE *f) {
255   fprintf(f, "usage: #!/usr/bin/prefork-interp [<options>]\n");
256 }
257
258 static int laundering;
259 static int max_sockets = 100; // maximum entries in the run dir is 2x this
260
261 static struct stat initial_stab;
262
263 const struct cmdinfo cmdinfos[]= {
264   PREFORK_CMDINFOS
265   { 0, 'U',   0,                    .iassignto= &laundering,    .arg= 'U' },
266   { 0 }
267 };
268
269 void ident_addinit(void) {
270   char ident_magic[1] = { 0 };
271   sha256_update(&identsc, sizeof(ident_magic), ident_magic);
272 }
273
274 static void propagate_exit_status(int status, const char *what) {
275   int r;
276
277   if (WIFEXITED(status)) {
278     _exit(status);
279   }
280
281   if (WIFSIGNALED(status)) {
282     int sig = WTERMSIG(status);
283     const char *signame = strsignal(sig);
284     if (signame == 0) signame = "unknown signal";
285
286     if (! WCOREDUMP(status) &&
287         (sig == SIGINT ||
288          sig == SIGHUP ||
289          sig == SIGPIPE ||
290          sig == SIGKILL)) {
291       struct sigaction sa;
292       FILLZERO(sa);
293       sa.sa_handler = SIG_DFL;
294       r = sigaction(sig, &sa, 0);
295       if (r) diee("failed to reset signal handler while propagating %s",
296                   signame);
297
298       sigset_t sset;
299       sigemptyset(&sset);
300       sigaddset(&sset, sig);
301       r = sigprocmask(SIG_UNBLOCK, &sset, 0);
302       if (r) diee("failed to reset signal block while propagating %s",
303                   signame);
304
305       raise(sig);
306       die("unexpectedly kept running after raising (to propagate) %s",
307           signame);
308     }
309
310     die("%s failed due to signal %d %s%s", what, sig, signame,
311         WCOREDUMP(status) ? " (core dumped)" : "");
312   }
313
314   die("%s failed with weird wait status %d 0x%x", what, status, status);
315 }
316
317 typedef struct {
318   char *name_hash;
319   time_t atime;
320 } PrecleanEntry;
321
322 static int preclean_entry_compar_name(const void *av, const void *bv) {
323   const PrecleanEntry *a = av;
324   const PrecleanEntry *b = bv;
325   return strcmp(a->name_hash, b->name_hash);
326 }
327
328 static int preclean_entry_compar_atime(const void *av, const void *bv) {
329   const PrecleanEntry *ae = av;  time_t a = ae->atime;
330   const PrecleanEntry *be = bv;  time_t b = be->atime;
331   return (a > b ? +1 :
332           a < b ? -1 : 0);
333 }
334
335 static time_t preclean_stat_atime(const char *s_path) {
336   struct stat stab;
337   int r= lstat(s_path, &stab);
338   if (r) {
339     if (errno!=ENOENT) diee("pre-cleanup: stat socket (%s)", s_path);
340     return 0;
341   }
342   return stab.st_atime;
343 }
344
345 static void preclean(void) {
346   DIR *dir = opendir(run_base);
347   if (!dir) {
348     if (errno == ENOENT) return;
349     diee("pre-cleanup: open run dir (%s)", run_base);
350   }
351
352   PrecleanEntry *entries=0;
353   size_t avail_entries=0;
354   size_t used_entries=0;
355
356   struct dirent *de;
357   while ((errno = 0, de = readdir(dir))) {
358     char c0 = de->d_name[0];
359     if (!(c0 == 'l' || c0 == 's')) continue;
360     char *name_hash = m_asprintf("%s", de->d_name+1);
361     char *s_path = m_asprintf("%s/s%s", run_base, name_hash);
362     time_t atime = preclean_stat_atime(s_path);
363
364     if (avail_entries == used_entries) {
365       assert(avail_entries < INT_MAX / 4 / sizeof(PrecleanEntry));
366       avail_entries <<= 1;
367       avail_entries += 10;
368       entries = realloc(entries, avail_entries * sizeof(PrecleanEntry));
369     }
370     entries[used_entries].name_hash = name_hash;
371     entries[used_entries].atime = atime;
372     used_entries++;
373   }
374   if (errno) diee("pre-cleanup: read run dir (%s)", run_base);
375
376   // First we dedupe (after sorting by path)
377   qsort(entries, used_entries, sizeof(PrecleanEntry),
378         preclean_entry_compar_name);
379   PrecleanEntry *p, *q;
380   for (p=entries, q=entries; p < entries + used_entries; p++) {
381     if (q > entries && !strcmp(p->name_hash, (q-1)->name_hash))
382       continue;
383     *q++ = *p;
384   }
385   used_entries = q - entries;
386
387   // Now maybe delete some things
388   //
389   // Actually this has an off-by-one error since we are about
390   // to create a socket, so the actual number of sockets is one more.
391   // But, *actually*, since there might be multiple of us running at once,
392   // we might have even more than that.  This doesn't really matter.
393   if (used_entries > max_sockets) {
394     qsort(entries, used_entries, sizeof(PrecleanEntry),
395           preclean_entry_compar_atime);
396     for (p=entries; p < entries + max_sockets; p++) {
397       char *l_path = m_asprintf("%s/l%s", run_base, p->name_hash);
398       char *s_path = m_asprintf("%s/s%s", run_base, p->name_hash);
399       int lock_fd = flock_file(l_path);
400       // Recheck atime - we might have raced!
401       time_t atime = preclean_stat_atime(s_path);
402       if (atime != p->atime) {
403         // Raced.  This will leave use deleting too few things.  Whatever.
404       } else {
405         int r= unlink(s_path);
406         if (r && errno!=ENOENT) diee("preclean: delete stale (%s)", s_path);
407         r= unlink(l_path);
408         if (r) diee("preclean: delete stale lock (%s)", s_path);
409         // NB we don't hold the lock any more now.
410       }
411       close(lock_fd);
412       free(l_path);
413       free(s_path);
414     }
415   }
416
417   for (p=entries; p < entries + used_entries; p++)
418     free(p->name_hash);
419   free(entries);
420 }
421
422 static __attribute((noreturn)) void die_data_overflow(void) {
423   die("cannot handle data with length >2^32");
424 }
425
426 static void prepare_data(size_t *len, char **buf,
427                          const void *data, size_t dl) {
428   if (len) {
429     if (dl >= SIZE_MAX - *len)
430       die_data_overflow();
431     *len += dl;
432   }
433   if (buf) {
434     memcpy(*buf, data, dl);
435     *buf += dl;
436   }
437 }
438
439 static void prepare_length(size_t *len, char **buf, size_t dl_sz) {
440   if (dl_sz > UINT32_MAX) die_data_overflow();
441   uint32_t dl = htonl(dl_sz);
442   prepare_data(len, buf, &dl, sizeof(dl));
443 }
444
445 static void prepare_string(size_t *len, char **buf, const char *s) {
446   size_t sl = strlen(s);
447   prepare_data(len, buf, s, sl+1);
448 }
449
450 static void prepare_message(size_t *len, char **buf) {
451   const char *s;
452
453   const char *const *p = (void*)environ;
454   while ((s = *p++)) {
455     if (strchr(s, '='))
456       prepare_string(len, buf, s);
457   }
458
459   prepare_string(len, buf, "");
460
461   p = executor_argv;
462   while ((s = *p++))
463     prepare_string(len, buf, s);
464 }
465
466 static void send_fd(int payload_fd) {
467   int via_fd = fileno(call_sock);
468
469   union {
470     struct cmsghdr align;
471     char buf[CMSG_SPACE(sizeof(payload_fd))];
472   } cmsg_buf;
473
474   struct msghdr msg;
475   FILLZERO(msg);
476   FILLZERO(cmsg_buf);
477
478   char dummy_byte = 0;
479   struct iovec iov;
480   FILLZERO(iov);
481   iov.iov_base = &dummy_byte;
482   iov.iov_len = 1;
483
484   msg.msg_name = 0;
485   msg.msg_iov = &iov;
486   msg.msg_iovlen = 1;
487   msg.msg_control = cmsg_buf.buf;
488   msg.msg_controllen = sizeof(cmsg_buf.buf);
489
490   struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
491   cmsg->cmsg_level = SOL_SOCKET;
492   cmsg->cmsg_type = SCM_RIGHTS;
493   cmsg->cmsg_len = CMSG_LEN(sizeof(payload_fd));
494   *(int*)CMSG_DATA(cmsg) = payload_fd;
495
496   msg.msg_controllen = sizeof(cmsg_buf.buf);
497
498   for (;;) {
499     ssize_t r = sendmsg(via_fd, &msg, 0);
500     if (r == -1) {
501       if (errno == EINTR) continue;
502       diee("send fd");
503     }
504     assert(r == 1);
505     break;
506   }
507 }
508
509 static void send_request(void) {
510   // Sending these first makes it easier for the script to
511   // use buffered IO for the message.
512   send_fd(0);
513   send_fd(1);
514   send_fd(2);
515
516   size_t len = 0;
517   prepare_message(&len, 0);
518
519   size_t tlen = len + 4;
520   char *m = xmalloc(tlen);
521   char *p = m;
522   prepare_length(0, &p, len);
523   prepare_message(0, &p);
524   assert(p == m + tlen);
525
526   ssize_t sr = fwrite(m, tlen, 1, call_sock);
527   if (sr != 1) diee("write request (buffer)");
528
529   if (fflush(call_sock)) diee("write request");
530 }
531
532 static FILE *call_sock_from_fd(int fd) {
533   int r;
534
535   FILE *call_sock = fdopen(fd, "r+");
536   if (!call_sock) diee("fdopen socket");
537
538   r = setvbuf(call_sock, 0, _IONBF, 0);
539   if (r) die("setvbuf socket");
540
541   return call_sock;
542 }
543
544 static bool was_eof(FILE *call_sock) {
545   return feof(call_sock) || errno==ECONNRESET;
546 }
547
548 // Returns -1 on EOF
549 static int protocol_read_maybe(void *data, size_t sz) {
550   if (!sz) return 0;
551   size_t sr = fread(data, sz, 1, call_sock);
552   if (sr != 1) {
553     if (was_eof(call_sock)) return -1;
554     diee("read() on monitor call socket (%zd)", sz);
555   }
556   return 0;
557 }
558
559 static void protocol_read(void *data, size_t sz) {
560   if (protocol_read_maybe(data, sz) < 0)
561     die("monitor process quit unexpectedly");
562 }
563
564 // Returns 0 if OK, error msg if peer was garbage.
565 static const char *read_greeting(void) {
566   char got_magic[sizeof(header_magic)];
567
568   if (protocol_read_maybe(&got_magic, sizeof(got_magic)) < 0)
569     return "initial monitor process quit";
570
571   if (memcmp(got_magic, header_magic, sizeof(header_magic)))
572     die("got unexpected protocol magic 0x%02x%02x%02x%02x",
573         got_magic[0], got_magic[1], got_magic[2], got_magic[3]);
574
575   uint32_t xdata_len;
576   protocol_read(&xdata_len, sizeof(xdata_len));
577   void *xdata = xmalloc(xdata_len);
578   protocol_read(xdata, xdata_len);
579
580   return 0;
581 }
582
583 // Returns: call(client-end), or 0 to mean "is garbage"
584 // find_socket_path must have been called
585 static FILE *connect_existing(void) {
586   int r;
587   int fd = -1;
588
589   fd = socket(AF_UNIX, SOCK_STREAM, 0);
590   if (fd==-1) diee("socket() for client");
591
592   socklen_t salen = sizeof(sockaddr_sun);
593   r = connect(fd, (const struct sockaddr*)&sockaddr_sun, salen);
594   if (r==-1) {
595     if (errno==ECONNREFUSED || errno==ENOENT) goto x_garbage;
596     diee("connect() %s", socket_path);
597   }
598
599   call_sock = call_sock_from_fd(fd);
600   fd = -1;
601
602   if (read_greeting())
603     goto x_garbage;
604
605   return call_sock;
606
607  x_garbage:
608   if (call_sock) { fclose(call_sock); call_sock=0; }
609   if (fd >= 0) close(fd);
610   return 0;
611 }
612
613 static void watcher_cb_stdin(uv_poll_t *handle, int status, int events) {
614   char c;
615   int r;
616
617   if ((errno = -status)) diee("watcher: poll stdin");
618   for (;;) {
619     r= read(0, &c, 1);
620     if (r!=-1) _exit(0);
621     if (!(errno==EINTR || errno==EWOULDBLOCK || errno==EAGAIN))
622       diee("watcher: read sentinel stdin");
623   }
624 }
625
626 static void watcher_cb_sockpath(uv_fs_event_t *handle, const char *filename,
627                                 int events, int status) {
628   int r;
629   struct stat now_stab;
630
631   if ((errno = -status)) diee("watcher: poll stdin");
632   for (;;) {
633     r= stat(socket_path, &now_stab);
634     if (r==-1) {
635       if (errno==ENOENT) _exit(0);
636       if (errno==EINTR) continue;
637       diee("stat socket: %s", socket_path);
638     }
639     if (!stabs_same_inode(&now_stab, &initial_stab))
640       _exit(0);
641   }
642 }
643
644 // On entry, stderr is still inherited, but 0 and 1 are the pipes
645 static __attribute__((noreturn))
646 void become_watcher(void) {
647   uv_loop_t loop;
648   uv_poll_t uvhandle_stdin;
649   uv_fs_event_t uvhandle_sockpath;
650   int r;
651
652   nonblock(0);
653
654   errno= -uv_loop_init(&loop);
655   if (errno) diee("watcher: uv_loop_init");
656
657   errno= -uv_poll_init(&loop, &uvhandle_stdin, 0);
658   if (errno) diee("watcher: uv_poll_init");
659   errno= -uv_poll_start(&uvhandle_stdin,
660                         UV_READABLE | UV_WRITABLE | UV_DISCONNECT,
661                         watcher_cb_stdin);
662   if (errno) diee("watcher: uv_poll_start");
663
664   errno= -uv_fs_event_init(&loop, &uvhandle_sockpath);
665   if (errno) diee("watcher: uv_fs_event_init");
666
667   errno= -uv_fs_event_start(&uvhandle_sockpath, watcher_cb_sockpath,
668                             socket_path, 0);
669   if (errno) diee("watcher: uv_fs_event_start");
670
671   // OK everything is set up, let us daemonise
672   if (dup2(1,2) != 2) diee("watcher: set daemonised stderr");
673   r= setvbuf(stderr, 0, _IOLBF, BUFSIZ);
674   if (r) diee("watcher: setvbuf stderr");
675
676   pid_t child = fork();
677   if (child == (pid_t)-1) diee("watcher: fork");
678   if (child) _exit(0);
679
680   if (setsid() == (pid_t)-1) diee("watcher: setsid");
681
682   r= uv_run(&loop, UV_RUN_DEFAULT);
683   die("uv_run returned (%d)", r);
684 }
685
686 static __attribute__((noreturn))
687 void become_setup(int sfd, int fake_pair[2],
688                   int watcher_stdin, int watcher_stderr) {
689   close(fake_pair[0]);
690   int call_fd = fake_pair[1];
691
692   int null_0 = open("/dev/null", O_RDONLY);  if (null_0 < 0) diee("open null");
693   if (dup2(null_0, 0)) diee("dup2 /dev/null onto stdin");
694   close(null_0);
695   if (dup2(2, 1) != 1) die("dup2 stderr onto stdout");
696
697   nonblock(sfd);
698
699   // Extension could work like this:
700   //
701   // We advertise a new protocol (perhaps one which is nearly entirely
702   // different after the connect) by putting a name for it comma-separated
703   // next to "v1".  Simple extension can be done by having the script
704   // side say something about it in the ack xdata, which we currently ignore.
705   putenv(m_asprintf("PREFORK_INTERP=v1 %d,%d,%d,%d",
706                     sfd, call_fd, watcher_stdin, watcher_stderr));
707
708   execvp(executor_argv[0], (char**)executor_argv);
709   diee("execute %s", executor_argv[0]);
710 }
711
712 static void connect_or_spawn(void) {
713   int r;
714
715   call_sock = connect_existing();
716   if (call_sock) return;
717
718   // We're going to make a new one, so clean out old ones
719   preclean();
720
721   int lockfd = acquire_lock();
722   call_sock = connect_existing();
723   if (call_sock) { close(lockfd); return; }
724
725   // We must start a fresh one, and we hold the lock
726
727   r = unlink(socket_path);
728   if (r<0 && errno!=ENOENT)
729     diee("failed to remove stale socket %s", socket_path);
730
731   int sfd = socket(AF_UNIX, SOCK_STREAM, 0);
732   if (sfd<0) diee("socket() for new listener");
733
734   socklen_t salen = sizeof(sockaddr_sun);
735   r= bind(sfd, (const struct sockaddr*)&sockaddr_sun, salen);
736   if (r<0) diee("bind() on new listener");
737
738   r= stat(socket_path, &initial_stab);
739   if (r<0) diee("stat() fresh socket");
740
741   // We never want callers to get ECONNREFUSED.  But:
742   // There is a race here: from my RTFM they may get ECONNREFUSED
743   // if they try between our bind() and listen().  But if they do, they'll
744   // acquire the lock (serialising with us) and retry, and then it will work.
745   r = listen(sfd, INT_MAX);
746   if (r<0) diee("listen() for new listener");
747
748   // Fork watcher
749
750   int watcher_stdin[2];
751   int watcher_stderr[2];
752   if (pipe(watcher_stdin) || pipe(watcher_stderr))
753     diee("pipe() for socket inode watcher");
754
755   pid_t watcher = fork();
756   if (watcher == (pid_t)-1) diee("fork for watcher");
757   if (!watcher) {
758     close(sfd);
759     close(lockfd);
760     close(watcher_stdin[1]);
761     close(watcher_stderr[0]);
762     if (dup2(watcher_stdin[0], 0) != 0 ||
763         dup2(watcher_stderr[1], 1) != 1)
764       diee("initial dup2() for watcher");
765     close(watcher_stdin[0]);
766     close(watcher_stderr[1]);
767     become_watcher();
768   }
769
770   close(watcher_stdin[0]);
771   close(watcher_stderr[1]);
772   nonblock(watcher_stderr[0]);
773
774   // Fork setup
775
776   int fake_pair[2];
777   r = socketpair(AF_UNIX, SOCK_STREAM, 0, fake_pair);
778   if (r<0) diee("socketpair() for fake initial connection");
779
780   pid_t setup_pid = fork();
781   if (setup_pid == (pid_t)-1) diee("fork for spawn setup");
782   if (!setup_pid) become_setup(sfd, fake_pair,
783                                watcher_stdin[1], watcher_stderr[0]);
784   close(fake_pair[1]);
785   close(sfd);
786
787   call_sock = call_sock_from_fd(fake_pair[0]);
788
789   int status;
790   pid_t got = waitpid(setup_pid, &status, 0);
791   if (got == (pid_t)-1) diee("waitpid setup [%ld]", (long)setup_pid);
792   if (got != setup_pid) diee("waitpid setup [%ld] gave [%ld]!",
793                              (long)setup_pid, (long)got);
794   if (status != 0) propagate_exit_status(status, "setup");
795
796   const char *emsg = read_greeting();
797   if (emsg) die("setup failed: %s", emsg);
798
799   close(lockfd);
800   return;
801 }
802
803 static void make_executor_argv(const char *const *argv) {
804   switch (laundering) {
805   case 'U': break;
806   default: die("need -U (specifying unlaundered argument handling)");
807   }
808
809   const char *arg;
810   #define EACH_NEW_ARG(EACH) {                  \
811     arg = interp; { EACH }                      \
812     if ((arg = script)) { EACH }                \
813     const char *const *walk = argv;             \
814     while ((arg = *walk++)) { EACH }            \
815   }
816
817   size_t count = 1;
818   EACH_NEW_ARG( (void)arg; count++; );
819
820   const char **out = calloc(count, sizeof(char*));
821   executor_argv = (const char* const*)out;
822   if (!executor_argv) diee("allocate for arguments");
823
824   EACH_NEW_ARG( *out++ = arg; );
825   *out++ = 0;
826 }
827
828 int main(int argc_unused, const char *const *argv) {
829   process_opts(&argv);
830
831   // Now we have
832   //  - possibly interp
833   //  - possibly script
834   //  - remaining args
835   // which ought to be passed on to the actual executor.
836   make_executor_argv(argv);
837
838   find_socket_path();
839   FILLZERO(sockaddr_sun);
840   sockaddr_sun.sun_family = AF_UNIX;
841   assert(strlen(socket_path) <= sizeof(sockaddr_sun.sun_path));
842   strncpy(sockaddr_sun.sun_path, socket_path, sizeof(sockaddr_sun.sun_path));
843
844   connect_or_spawn();
845
846   // We're committed now, send the request (or bail out)
847   send_request();
848
849   uint32_t status;
850   protocol_read(&status, sizeof(status));
851
852   status = ntohl(status);
853   if (status > INT_MAX) die("status 0x%lx does not fit in an int",
854                             (unsigned long)status);
855
856   propagate_exit_status(status, "invocation");
857 }