xref: /freebsd/contrib/capsicum-test/procdesc.cc (revision cfd6422a5217410fbd66f7a7a8a64d9d85e61229)
1 // Tests for the process descriptor API for Linux.
2 #include <sys/types.h>
3 #include <sys/resource.h>
4 #include <sys/select.h>
5 #include <sys/socket.h>
6 #include <sys/stat.h>
7 #include <sys/time.h>
8 #include <sys/wait.h>
9 #include <fcntl.h>
10 #include <poll.h>
11 #include <pthread.h>
12 #include <signal.h>
13 #include <stdlib.h>
14 #include <unistd.h>
15 
16 #include <iomanip>
17 #include <map>
18 
19 #include "capsicum.h"
20 #include "syscalls.h"
21 #include "capsicum-test.h"
22 
23 #ifndef __WALL
24 // Linux requires __WALL in order for waitpid(specific_pid,...) to
25 // see and reap any specific pid.  Define this to nothing for platforms
26 // (FreeBSD) where it doesn't exist, to reduce macroing.
27 #define __WALL 0
28 #endif
29 
30 // TODO(drysdale): it would be nice to use proper synchronization between
31 // processes, rather than synchronization-via-sleep; faster too.
32 
33 
34 //------------------------------------------------
35 // Utilities for the tests.
36 
37 static pid_t pdwait4_(int pd, int *status, int options, struct rusage *ru) {
38 #ifdef HAVE_PDWAIT4
39   return pdwait4(pd, status, options, ru);
40 #else
41   // Simulate pdwait4() with wait4(pdgetpid()); this won't work in capability mode.
42   pid_t pid = -1;
43   int rc = pdgetpid(pd, &pid);
44   if (rc < 0) {
45     return rc;
46   }
47   options |= __WALL;
48   return wait4(pid, status, options, ru);
49 #endif
50 }
51 
52 static void print_rusage(FILE *f, struct rusage *ru) {
53   fprintf(f, "  User CPU time=%ld.%06ld\n", (long)ru->ru_utime.tv_sec, (long)ru->ru_utime.tv_usec);
54   fprintf(f, "  System CPU time=%ld.%06ld\n", (long)ru->ru_stime.tv_sec, (long)ru->ru_stime.tv_usec);
55   fprintf(f, "  Max RSS=%ld\n", ru->ru_maxrss);
56 }
57 
58 static void print_stat(FILE *f, const struct stat *stat) {
59   fprintf(f,
60           "{ .st_dev=%ld, st_ino=%ld, st_mode=%04o, st_nlink=%ld, st_uid=%d, st_gid=%d,\n"
61           "  .st_rdev=%ld, .st_size=%ld, st_blksize=%ld, .st_block=%ld,\n  "
62 #ifdef HAVE_STAT_BIRTHTIME
63           ".st_birthtime=%ld, "
64 #endif
65           ".st_atime=%ld, .st_mtime=%ld, .st_ctime=%ld}\n",
66           (long)stat->st_dev, (long)stat->st_ino, stat->st_mode,
67           (long)stat->st_nlink, stat->st_uid, stat->st_gid,
68           (long)stat->st_rdev, (long)stat->st_size, (long)stat->st_blksize,
69           (long)stat->st_blocks,
70 #ifdef HAVE_STAT_BIRTHTIME
71           (long)stat->st_birthtime,
72 #endif
73           (long)stat->st_atime, (long)stat->st_mtime, (long)stat->st_ctime);
74 }
75 
76 static std::map<int,bool> had_signal;
77 static void handle_signal(int x) {
78   had_signal[x] = true;
79 }
80 
81 // Check that the given child process terminates as expected.
82 void CheckChildFinished(pid_t pid, bool signaled=false) {
83   // Wait for the child to finish.
84   int rc;
85   int status = 0;
86   do {
87     rc = waitpid(pid, &status, __WALL);
88     if (rc < 0) {
89       fprintf(stderr, "Warning: waitpid error %s (%d)\n", strerror(errno), errno);
90       ADD_FAILURE() << "Failed to wait for child";
91       break;
92     } else if (rc == pid) {
93       break;
94     }
95   } while (true);
96   EXPECT_EQ(pid, rc);
97   if (rc == pid) {
98     if (signaled) {
99       EXPECT_TRUE(WIFSIGNALED(status));
100     } else {
101       EXPECT_TRUE(WIFEXITED(status)) << std::hex << status;
102       EXPECT_EQ(0, WEXITSTATUS(status));
103     }
104   }
105 }
106 
107 //------------------------------------------------
108 // Basic tests of process descriptor functionality
109 
110 TEST(Pdfork, Simple) {
111   int pd = -1;
112   pid_t parent = getpid_();
113   int pid = pdfork(&pd, 0);
114   EXPECT_OK(pid);
115   if (pid == 0) {
116     // Child: check pid values.
117     EXPECT_EQ(-1, pd);
118     EXPECT_NE(parent, getpid_());
119     EXPECT_EQ(parent, getppid());
120     sleep(1);
121     exit(0);
122   }
123   usleep(100);  // ensure the child has a chance to run
124   EXPECT_NE(-1, pd);
125   EXPECT_PID_ALIVE(pid);
126   int pid_got;
127   EXPECT_OK(pdgetpid(pd, &pid_got));
128   EXPECT_EQ(pid, pid_got);
129 
130   // Wait long enough for the child to exit().
131   sleep(2);
132   EXPECT_PID_ZOMBIE(pid);
133 
134   // Wait for the the child.
135   int status;
136   struct rusage ru;
137   memset(&ru, 0, sizeof(ru));
138   int waitrc = pdwait4_(pd, &status, 0, &ru);
139   EXPECT_EQ(pid, waitrc);
140   if (verbose) {
141     fprintf(stderr, "For pd %d pid %d:\n", pd, pid);
142     print_rusage(stderr, &ru);
143   }
144   EXPECT_PID_GONE(pid);
145 
146   // Can only pdwait4(pd) once (as initial call reaps zombie).
147   memset(&ru, 0, sizeof(ru));
148   EXPECT_EQ(-1, pdwait4_(pd, &status, 0, &ru));
149   EXPECT_EQ(ECHILD, errno);
150 
151   EXPECT_OK(close(pd));
152 }
153 
154 TEST(Pdfork, InvalidFlag) {
155   int pd = -1;
156   int pid = pdfork(&pd, PD_DAEMON<<5);
157   if (pid == 0) {
158     exit(1);
159   }
160   EXPECT_EQ(-1, pid);
161   EXPECT_EQ(EINVAL, errno);
162   if (pid > 0) waitpid(pid, NULL, __WALL);
163 }
164 
165 TEST(Pdfork, TimeCheck) {
166   time_t now = time(NULL);  // seconds since epoch
167   EXPECT_NE(-1, now);
168   if (verbose) fprintf(stderr, "Calling pdfork around %ld\n", (long)(long)now);
169 
170   int pd = -1;
171   pid_t pid = pdfork(&pd, 0);
172   EXPECT_OK(pid);
173   if (pid == 0) {
174     // Child: check we didn't get a valid process descriptor then exit.
175     EXPECT_EQ(-1, pdgetpid(pd, &pid));
176     EXPECT_EQ(EBADF, errno);
177     exit(HasFailure());
178   }
179 
180 #ifdef HAVE_PROCDESC_FSTAT
181   // Parent process. Ensure that [acm]times have been set correctly.
182   struct stat stat;
183   memset(&stat, 0, sizeof(stat));
184   EXPECT_OK(fstat(pd, &stat));
185   if (verbose) print_stat(stderr, &stat);
186 
187 #ifdef HAVE_STAT_BIRTHTIME
188   EXPECT_GE(now, stat.st_birthtime);
189   EXPECT_EQ(stat.st_birthtime, stat.st_atime);
190 #endif
191   EXPECT_LT((now - stat.st_atime), 2);
192   EXPECT_EQ(stat.st_atime, stat.st_ctime);
193   EXPECT_EQ(stat.st_ctime, stat.st_mtime);
194 #endif
195 
196   // Wait for the child to finish.
197   pid_t pd_pid = -1;
198   EXPECT_OK(pdgetpid(pd, &pd_pid));
199   EXPECT_EQ(pid, pd_pid);
200   CheckChildFinished(pid);
201 }
202 
203 TEST(Pdfork, UseDescriptor) {
204   int pd = -1;
205   pid_t pid = pdfork(&pd, 0);
206   EXPECT_OK(pid);
207   if (pid == 0) {
208     // Child: immediately exit
209     exit(0);
210   }
211   CheckChildFinished(pid);
212 }
213 
214 TEST(Pdfork, NonProcessDescriptor) {
215   int fd = open("/etc/passwd", O_RDONLY);
216   EXPECT_OK(fd);
217   // pd*() operations should fail on a non-process descriptor.
218   EXPECT_EQ(-1, pdkill(fd, SIGUSR1));
219   int status;
220   EXPECT_EQ(-1, pdwait4_(fd, &status, 0, NULL));
221   pid_t pid;
222   EXPECT_EQ(-1, pdgetpid(fd, &pid));
223   close(fd);
224 }
225 
226 static void *SubThreadMain(void *) {
227   while (true) {
228     if (verbose) fprintf(stderr, "      subthread: \"I aten't dead\"\n");
229     usleep(100000);
230   }
231   return NULL;
232 }
233 
234 static void *ThreadMain(void *) {
235   int pd;
236   pid_t child = pdfork(&pd, 0);
237   if (child == 0) {
238     // Child: start a subthread then loop
239     pthread_t child_subthread;
240     EXPECT_OK(pthread_create(&child_subthread, NULL, SubThreadMain, NULL));
241     while (true) {
242       if (verbose) fprintf(stderr, "    pdforked process %d: \"I aten't dead\"\n", getpid());
243       usleep(100000);
244     }
245     exit(0);
246   }
247   if (verbose) fprintf(stderr, "  thread generated pd %d\n", pd);
248   sleep(2);
249 
250   // Pass the process descriptor back to the main thread.
251   return reinterpret_cast<void *>(pd);
252 }
253 
254 TEST(Pdfork, FromThread) {
255   // Fire off a new thread to do all of the creation work.
256   pthread_t child_thread;
257   EXPECT_OK(pthread_create(&child_thread, NULL, ThreadMain, NULL));
258   void *data;
259   EXPECT_OK(pthread_join(child_thread, &data));
260   int pd = reinterpret_cast<intptr_t>(data);
261   if (verbose) fprintf(stderr, "retrieved pd %d from terminated thread\n", pd);
262 
263   // Kill and reap.
264   pid_t pid;
265   EXPECT_OK(pdgetpid(pd, &pid));
266   EXPECT_OK(pdkill(pd, SIGKILL));
267   int status;
268   EXPECT_EQ(pid, pdwait4_(pd, &status, 0, NULL));
269   EXPECT_TRUE(WIFSIGNALED(status));
270 }
271 
272 //------------------------------------------------
273 // More complicated tests.
274 
275 
276 // Test fixture that pdfork()s off a child process, which terminates
277 // when it receives anything on a pipe.
278 class PipePdforkBase : public ::testing::Test {
279  public:
280   PipePdforkBase(int pdfork_flags) : pd_(-1), pid_(-1) {
281     had_signal.clear();
282     int pipes[2];
283     EXPECT_OK(pipe(pipes));
284     pipe_ = pipes[1];
285     int parent = getpid_();
286     if (verbose) fprintf(stderr, "[%d] about to pdfork()\n", getpid_());
287     int rc = pdfork(&pd_, pdfork_flags);
288     EXPECT_OK(rc);
289     if (rc == 0) {
290       // Child process: blocking-read an int from the pipe then exit with that value.
291       EXPECT_NE(parent, getpid_());
292       EXPECT_EQ(parent, getppid());
293       if (verbose) fprintf(stderr, "  [%d] child of %d waiting for value on pipe\n", getpid_(), getppid());
294       read(pipes[0], &rc, sizeof(rc));
295       if (verbose) fprintf(stderr, "  [%d] got value %d on pipe, exiting\n", getpid_(), rc);
296       exit(rc);
297     }
298     pid_ = rc;
299     usleep(100);  // ensure the child has a chance to run
300   }
301   ~PipePdforkBase() {
302     // Terminate by any means necessary.
303     if (pd_ > 0) {
304       pdkill(pd_, SIGKILL);
305       close(pd_);
306     }
307     if (pid_ > 0) {
308       kill(pid_, SIGKILL);
309       waitpid(pid_, NULL, __WALL|WNOHANG);
310     }
311     // Check signal expectations.
312     EXPECT_FALSE(had_signal[SIGCHLD]);
313   }
314   int TerminateChild() {
315     // Tell the child to exit.
316     int zero = 0;
317     if (verbose) fprintf(stderr, "[%d] write 0 to pipe\n", getpid_());
318     return write(pipe_, &zero, sizeof(zero));
319   }
320  protected:
321   int pd_;
322   int pipe_;
323   pid_t pid_;
324 };
325 
326 class PipePdfork : public PipePdforkBase {
327  public:
328   PipePdfork() : PipePdforkBase(0) {}
329 };
330 
331 class PipePdforkDaemon : public PipePdforkBase {
332  public:
333   PipePdforkDaemon() : PipePdforkBase(PD_DAEMON) {}
334 };
335 
336 // Can we poll a process descriptor?
337 TEST_F(PipePdfork, Poll) {
338   // Poll the process descriptor, nothing happening.
339   struct pollfd fdp;
340   fdp.fd = pd_;
341   fdp.events = POLLIN | POLLERR | POLLHUP;
342   fdp.revents = 0;
343   EXPECT_EQ(0, poll(&fdp, 1, 0));
344 
345   TerminateChild();
346 
347   // Poll again, should have activity on the process descriptor.
348   EXPECT_EQ(1, poll(&fdp, 1, 2000));
349   EXPECT_TRUE(fdp.revents & POLLHUP);
350 
351   // Poll a third time, still have POLLHUP.
352   fdp.revents = 0;
353   EXPECT_EQ(1, poll(&fdp, 1, 0));
354   EXPECT_TRUE(fdp.revents & POLLHUP);
355 }
356 
357 // Can multiple processes poll on the same descriptor?
358 TEST_F(PipePdfork, PollMultiple) {
359   int child = fork();
360   EXPECT_OK(child);
361   if (child == 0) {
362     // Child: wait to give time for setup, then write to the pipe (which will
363     // induce exit of the pdfork()ed process) and exit.
364     sleep(1);
365     TerminateChild();
366     exit(0);
367   }
368   usleep(100);  // ensure the child has a chance to run
369 
370   // Fork again
371   int doppel = fork();
372   EXPECT_OK(doppel);
373   // We now have:
374   //   pid A: main process, here
375   //   |--pid B: pdfork()ed process, blocked on read()
376   //   |--pid C: fork()ed process, in sleep(1) above
377   //   +--pid D: doppel process, here
378 
379   // Both A and D execute the following code.
380   // First, check no activity on the process descriptor yet.
381   struct pollfd fdp;
382   fdp.fd = pd_;
383   fdp.events = POLLIN | POLLERR | POLLHUP;
384   fdp.revents = 0;
385   EXPECT_EQ(0, poll(&fdp, 1, 0));
386 
387   // Now, wait (indefinitely) for activity on the process descriptor.
388   // We expect:
389   //  - pid C will finish its sleep, write to the pipe and exit
390   //  - pid B will unblock from read(), and exit
391   //  - this will generate an event on the process descriptor...
392   //  - ...in both process A and process D.
393   EXPECT_EQ(1, poll(&fdp, 1, 2000));
394   EXPECT_TRUE(fdp.revents & POLLHUP);
395 
396   if (doppel == 0) {
397     // Child: process D exits.
398     exit(0);
399   } else {
400     // Parent: wait on process D.
401     int rc = 0;
402     waitpid(doppel, &rc, __WALL);
403     EXPECT_TRUE(WIFEXITED(rc));
404     EXPECT_EQ(0, WEXITSTATUS(rc));
405     // Also wait on process B.
406     CheckChildFinished(child);
407   }
408 }
409 
410 // Check that exit status/rusage for a dead pdfork()ed child can be retrieved
411 // via any process descriptor, multiple times.
412 TEST_F(PipePdfork, MultipleRetrieveExitStatus) {
413   EXPECT_PID_ALIVE(pid_);
414   int pd_copy = dup(pd_);
415   EXPECT_LT(0, TerminateChild());
416 
417   int status;
418   struct rusage ru;
419   memset(&ru, 0, sizeof(ru));
420   int waitrc = pdwait4_(pd_copy, &status, 0, &ru);
421   EXPECT_EQ(pid_, waitrc);
422   if (verbose) {
423     fprintf(stderr, "For pd %d -> pid %d:\n", pd_, pid_);
424     print_rusage(stderr, &ru);
425   }
426   EXPECT_PID_GONE(pid_);
427 
428 #ifdef NOTYET
429   // Child has been reaped, so original process descriptor dangles but
430   // still has access to rusage information.
431   memset(&ru, 0, sizeof(ru));
432   EXPECT_EQ(0, pdwait4_(pd_, &status, 0, &ru));
433 #endif
434   close(pd_copy);
435 }
436 
437 TEST_F(PipePdfork, ChildExit) {
438   EXPECT_PID_ALIVE(pid_);
439   EXPECT_LT(0, TerminateChild());
440   EXPECT_PID_DEAD(pid_);
441 
442   int status;
443   int rc = pdwait4_(pd_, &status, 0, NULL);
444   EXPECT_OK(rc);
445   EXPECT_EQ(pid_, rc);
446   pid_ = 0;
447 }
448 
449 #ifdef HAVE_PROC_FDINFO
450 TEST_F(PipePdfork, FdInfo) {
451   char buffer[1024];
452   sprintf(buffer, "/proc/%d/fdinfo/%d", getpid_(), pd_);
453   int procfd = open(buffer, O_RDONLY);
454   EXPECT_OK(procfd);
455 
456   EXPECT_OK(read(procfd, buffer, sizeof(buffer)));
457   // The fdinfo should include the file pos of the underlying file
458   EXPECT_NE((char*)NULL, strstr(buffer, "pos:\t0")) << buffer;
459   // ...and the underlying pid
460   char pidline[256];
461   sprintf(pidline, "pid:\t%d", pid_);
462   EXPECT_NE((char*)NULL, strstr(buffer, pidline)) << buffer;
463   close(procfd);
464 }
465 #endif
466 
467 // Closing a normal process descriptor terminates the underlying process.
468 TEST_F(PipePdfork, Close) {
469   sighandler_t original = signal(SIGCHLD, handle_signal);
470   EXPECT_PID_ALIVE(pid_);
471   int status;
472   EXPECT_EQ(0, waitpid(pid_, &status, __WALL|WNOHANG));
473 
474   EXPECT_OK(close(pd_));
475   pd_ = -1;
476   EXPECT_FALSE(had_signal[SIGCHLD]);
477   EXPECT_PID_DEAD(pid_);
478 
479 #ifdef __FreeBSD__
480   EXPECT_EQ(-1, waitpid(pid_, NULL, __WALL));
481   EXPECT_EQ(errno, ECHILD);
482 #else
483   // Having closed the process descriptor means that pdwait4(pd) now doesn't work.
484   int rc = pdwait4_(pd_, &status, 0, NULL);
485   EXPECT_EQ(-1, rc);
486   EXPECT_EQ(EBADF, errno);
487 
488   // Closing all process descriptors means the the child can only be reaped via pid.
489   EXPECT_EQ(pid_, waitpid(pid_, &status, __WALL|WNOHANG));
490 #endif
491   signal(SIGCHLD, original);
492 }
493 
494 TEST_F(PipePdfork, CloseLast) {
495   sighandler_t original = signal(SIGCHLD, handle_signal);
496   // Child should only die when last process descriptor is closed.
497   EXPECT_PID_ALIVE(pid_);
498   int pd_other = dup(pd_);
499 
500   EXPECT_OK(close(pd_));
501   pd_ = -1;
502 
503   EXPECT_PID_ALIVE(pid_);
504   int status;
505   EXPECT_EQ(0, waitpid(pid_, &status, __WALL|WNOHANG));
506 
507   // Can no longer pdwait4() the closed process descriptor...
508   EXPECT_EQ(-1, pdwait4_(pd_, &status, WNOHANG, NULL));
509   EXPECT_EQ(EBADF, errno);
510   // ...but can pdwait4() the still-open process descriptor.
511   errno = 0;
512   EXPECT_EQ(0, pdwait4_(pd_other, &status, WNOHANG, NULL));
513   EXPECT_EQ(0, errno);
514 
515   EXPECT_OK(close(pd_other));
516   EXPECT_PID_DEAD(pid_);
517 
518   EXPECT_FALSE(had_signal[SIGCHLD]);
519   signal(SIGCHLD, original);
520 }
521 
522 FORK_TEST(Pdfork, OtherUser) {
523   REQUIRE_ROOT();
524   int pd;
525   pid_t pid = pdfork(&pd, 0);
526   EXPECT_OK(pid);
527   if (pid == 0) {
528     // Child process: loop forever.
529     while (true) usleep(100000);
530   }
531   usleep(100);
532 
533   // Now that the second process has been pdfork()ed, change euid.
534   setuid(other_uid);
535   if (verbose) fprintf(stderr, "uid=%d euid=%d\n", getuid(), geteuid());
536 
537   // Fail to kill child with normal PID operation.
538   EXPECT_EQ(-1, kill(pid, SIGKILL));
539   EXPECT_EQ(EPERM, errno);
540   EXPECT_PID_ALIVE(pid);
541 
542   // Succeed with pdkill though.
543   EXPECT_OK(pdkill(pd, SIGKILL));
544   EXPECT_PID_ZOMBIE(pid);
545 
546   int status;
547   int rc = pdwait4_(pd, &status, WNOHANG, NULL);
548   EXPECT_OK(rc);
549   EXPECT_EQ(pid, rc);
550   EXPECT_TRUE(WIFSIGNALED(status));
551 }
552 
553 TEST_F(PipePdfork, WaitPidThenPd) {
554   TerminateChild();
555   int status;
556   // If we waitpid(pid) first...
557   int rc = waitpid(pid_, &status, __WALL);
558   EXPECT_OK(rc);
559   EXPECT_EQ(pid_, rc);
560 
561 #ifdef NOTYET
562   // ...the zombie is reaped but we can still subsequently pdwait4(pd).
563   EXPECT_EQ(0, pdwait4_(pd_, &status, 0, NULL));
564 #endif
565 }
566 
567 TEST_F(PipePdfork, WaitPdThenPid) {
568   TerminateChild();
569   int status;
570   // If we pdwait4(pd) first...
571   int rc = pdwait4_(pd_, &status, 0, NULL);
572   EXPECT_OK(rc);
573   EXPECT_EQ(pid_, rc);
574 
575   // ...the zombie is reaped and cannot subsequently waitpid(pid).
576   EXPECT_EQ(-1, waitpid(pid_, &status, __WALL));
577   EXPECT_EQ(ECHILD, errno);
578 }
579 
580 // Setting PD_DAEMON prevents close() from killing the child.
581 TEST_F(PipePdforkDaemon, Close) {
582   EXPECT_OK(close(pd_));
583   pd_ = -1;
584   EXPECT_PID_ALIVE(pid_);
585 
586   // Can still explicitly kill it via the pid.
587   if (pid_ > 0) {
588     EXPECT_OK(kill(pid_, SIGKILL));
589     EXPECT_PID_DEAD(pid_);
590   }
591 }
592 
593 static void TestPdkill(pid_t pid, int pd) {
594   EXPECT_PID_ALIVE(pid);
595   // SIGCONT is ignored by default.
596   EXPECT_OK(pdkill(pd, SIGCONT));
597   EXPECT_PID_ALIVE(pid);
598 
599   // SIGINT isn't
600   EXPECT_OK(pdkill(pd, SIGINT));
601   EXPECT_PID_DEAD(pid);
602 
603   // pdkill() on zombie is no-op.
604   errno = 0;
605   EXPECT_EQ(0, pdkill(pd, SIGINT));
606   EXPECT_EQ(0, errno);
607 
608   // pdkill() on reaped process gives -ESRCH.
609   CheckChildFinished(pid, true);
610   EXPECT_EQ(-1, pdkill(pd, SIGINT));
611   EXPECT_EQ(ESRCH, errno);
612 }
613 
614 TEST_F(PipePdfork, Pdkill) {
615   TestPdkill(pid_, pd_);
616 }
617 
618 TEST_F(PipePdforkDaemon, Pdkill) {
619   TestPdkill(pid_, pd_);
620 }
621 
622 TEST(Pdfork, PdkillOtherSignal) {
623   int pd = -1;
624   int pid = pdfork(&pd, 0);
625   EXPECT_OK(pid);
626   if (pid == 0) {
627     // Child: watch for SIGUSR1 forever.
628     had_signal.clear();
629     signal(SIGUSR1, handle_signal);
630     while (!had_signal[SIGUSR1]) {
631       usleep(100000);
632     }
633     exit(123);
634   }
635   sleep(1);
636 
637   // Send an invalid signal.
638   EXPECT_EQ(-1, pdkill(pd, 0xFFFF));
639   EXPECT_EQ(EINVAL, errno);
640 
641   // Send an expected SIGUSR1 to the pdfork()ed child.
642   EXPECT_PID_ALIVE(pid);
643   pdkill(pd, SIGUSR1);
644   EXPECT_PID_DEAD(pid);
645 
646   // Child's exit status confirms whether it received the signal.
647   int status;
648   int rc = waitpid(pid, &status, __WALL);
649   EXPECT_OK(rc);
650   EXPECT_EQ(pid, rc);
651   EXPECT_TRUE(WIFEXITED(status)) << "0x" << std::hex << rc;
652   EXPECT_EQ(123, WEXITSTATUS(status));
653 }
654 
655 pid_t PdforkParentDeath(int pdfork_flags) {
656   // Set up:
657   //   pid A: main process, here
658   //   +--pid B: fork()ed process, sleep(4)s then exits
659   //      +--pid C: pdfork()ed process, looping forever
660   int sock_fds[2];
661   EXPECT_OK(socketpair(AF_UNIX, SOCK_STREAM, 0, sock_fds));
662   if (verbose) fprintf(stderr, "[%d] parent about to fork()...\n", getpid_());
663   pid_t child = fork();
664   EXPECT_OK(child);
665   if (child == 0) {
666     int pd;
667     if (verbose) fprintf(stderr, "  [%d] child about to pdfork()...\n", getpid_());
668     pid_t grandchild = pdfork(&pd, pdfork_flags);
669     if (grandchild == 0) {
670       while (true) {
671         if (verbose) fprintf(stderr, "    [%d] grandchild: \"I aten't dead\"\n", getpid_());
672         sleep(1);
673       }
674     }
675     if (verbose) fprintf(stderr, "  [%d] pdfork()ed grandchild %d, sending ID to parent\n", getpid_(), grandchild);
676     // send grandchild pid to parent
677     write(sock_fds[1], &grandchild, sizeof(grandchild));
678     sleep(4);
679     if (verbose) fprintf(stderr, "  [%d] child terminating\n", getpid_());
680     exit(0);
681   }
682   if (verbose) fprintf(stderr, "[%d] fork()ed child is %d\n", getpid_(), child);
683   pid_t grandchild;
684   read(sock_fds[0], &grandchild, sizeof(grandchild));
685   if (verbose) fprintf(stderr, "[%d] receive grandchild id %d\n", getpid_(), grandchild);
686   EXPECT_PID_ALIVE(child);
687   EXPECT_PID_ALIVE(grandchild);
688   sleep(6);
689   // Child dies, closing its process descriptor for the grandchild.
690   EXPECT_PID_DEAD(child);
691   CheckChildFinished(child);
692   return grandchild;
693 }
694 
695 TEST(Pdfork, Bagpuss) {
696   // "And of course when Bagpuss goes to sleep, all his friends go to sleep too"
697   pid_t grandchild = PdforkParentDeath(0);
698   // By default: child death => closed process descriptor => grandchild death.
699   EXPECT_PID_DEAD(grandchild);
700 }
701 
702 TEST(Pdfork, BagpussDaemon) {
703   pid_t grandchild = PdforkParentDeath(PD_DAEMON);
704   // With PD_DAEMON: child death => closed process descriptor => no effect on grandchild.
705   EXPECT_PID_ALIVE(grandchild);
706   if (grandchild > 0) {
707     EXPECT_OK(kill(grandchild, SIGKILL));
708   }
709 }
710 
711 // The exit of a pdfork()ed process should not generate SIGCHLD.
712 TEST_F(PipePdfork, NoSigchld) {
713   had_signal.clear();
714   sighandler_t original = signal(SIGCHLD, handle_signal);
715   TerminateChild();
716   int rc = 0;
717   // Can waitpid() for the specific pid of the pdfork()ed child.
718   EXPECT_EQ(pid_, waitpid(pid_, &rc, __WALL));
719   EXPECT_TRUE(WIFEXITED(rc)) << "0x" << std::hex << rc;
720   EXPECT_FALSE(had_signal[SIGCHLD]);
721   signal(SIGCHLD, original);
722 }
723 
724 // The exit of a pdfork()ed process whose process descriptors have
725 // all been closed should generate SIGCHLD.  The child process needs
726 // PD_DAEMON to survive the closure of the process descriptors.
727 TEST_F(PipePdforkDaemon, NoPDSigchld) {
728   had_signal.clear();
729   sighandler_t original = signal(SIGCHLD, handle_signal);
730 
731   EXPECT_OK(close(pd_));
732   TerminateChild();
733 #ifdef __FreeBSD__
734   EXPECT_EQ(-1, waitpid(pid_, NULL, __WALL));
735   EXPECT_EQ(errno, ECHILD);
736 #else
737   int rc = 0;
738   // Can waitpid() for the specific pid of the pdfork()ed child.
739   EXPECT_EQ(pid_, waitpid(pid_, &rc, __WALL));
740   EXPECT_TRUE(WIFEXITED(rc)) << "0x" << std::hex << rc;
741 #endif
742   EXPECT_FALSE(had_signal[SIGCHLD]);
743   signal(SIGCHLD, original);
744 }
745 
746 #ifdef HAVE_PROCDESC_FSTAT
747 TEST_F(PipePdfork, ModeBits) {
748   // Owner rwx bits indicate liveness of child
749   struct stat stat;
750   memset(&stat, 0, sizeof(stat));
751   EXPECT_OK(fstat(pd_, &stat));
752   if (verbose) print_stat(stderr, &stat);
753   EXPECT_EQ(S_IRWXU, (long)(stat.st_mode & S_IRWXU));
754 
755   TerminateChild();
756   usleep(100000);
757 
758   memset(&stat, 0, sizeof(stat));
759   EXPECT_OK(fstat(pd_, &stat));
760   if (verbose) print_stat(stderr, &stat);
761   EXPECT_EQ(0, (int)(stat.st_mode & S_IRWXU));
762 }
763 #endif
764 
765 TEST_F(PipePdfork, WildcardWait) {
766   // TODO(FreeBSD): make wildcard wait ignore pdfork()ed children
767   // https://bugs.freebsd.org/201054
768   TerminateChild();
769   sleep(1);  // Ensure child is truly dead.
770 
771   // Wildcard waitpid(-1) should not see the pdfork()ed child because
772   // there is still a process descriptor for it.
773   int rc;
774   EXPECT_EQ(-1, waitpid(-1, &rc, WNOHANG));
775   EXPECT_EQ(ECHILD, errno);
776 
777   EXPECT_OK(close(pd_));
778   pd_ = -1;
779 }
780 
781 FORK_TEST(Pdfork, Pdkill) {
782   had_signal.clear();
783   int pd;
784   pid_t pid = pdfork(&pd, 0);
785   EXPECT_OK(pid);
786 
787   if (pid == 0) {
788     // Child: set a SIGINT handler and sleep.
789     had_signal.clear();
790     signal(SIGINT, handle_signal);
791     if (verbose) fprintf(stderr, "[%d] child about to sleep(10)\n", getpid_());
792     int left = sleep(10);
793     if (verbose) fprintf(stderr, "[%d] child slept, %d sec left, had[SIGINT]=%d\n",
794                          getpid_(), left, had_signal[SIGINT]);
795     // Expect this sleep to be interrupted by the signal (and so left > 0).
796     exit(left == 0);
797   }
798 
799   // Parent: get child's PID.
800   pid_t pd_pid;
801   EXPECT_OK(pdgetpid(pd, &pd_pid));
802   EXPECT_EQ(pid, pd_pid);
803 
804   // Interrupt the child after a second.
805   sleep(1);
806   EXPECT_OK(pdkill(pd, SIGINT));
807 
808   // Make sure the child finished properly (caught signal then exited).
809   CheckChildFinished(pid);
810 }
811 
812 FORK_TEST(Pdfork, PdkillSignal) {
813   int pd;
814   pid_t pid = pdfork(&pd, 0);
815   EXPECT_OK(pid);
816 
817   if (pid == 0) {
818     // Child: sleep.  No SIGINT handler.
819     if (verbose) fprintf(stderr, "[%d] child about to sleep(10)\n", getpid_());
820     int left = sleep(10);
821     if (verbose) fprintf(stderr, "[%d] child slept, %d sec left\n", getpid_(), left);
822     exit(99);
823   }
824 
825   // Kill the child (as it doesn't handle SIGINT).
826   sleep(1);
827   EXPECT_OK(pdkill(pd, SIGINT));
828 
829   // Make sure the child finished properly (terminated by signal).
830   CheckChildFinished(pid, true);
831 }
832 
833 //------------------------------------------------
834 // Test interactions with other parts of Capsicum:
835 //  - capability mode
836 //  - capabilities
837 
838 FORK_TEST(Pdfork, DaemonUnrestricted) {
839   EXPECT_OK(cap_enter());
840   int fd;
841 
842   // Capability mode leaves pdfork() available, with and without flag.
843   int rc;
844   rc = pdfork(&fd, PD_DAEMON);
845   EXPECT_OK(rc);
846   if (rc == 0) {
847     // Child: immediately terminate.
848     exit(0);
849   }
850 
851   rc = pdfork(&fd, 0);
852   EXPECT_OK(rc);
853   if (rc == 0) {
854     // Child: immediately terminate.
855     exit(0);
856   }
857 }
858 
859 TEST(Pdfork, MissingRights) {
860   pid_t parent = getpid_();
861   int pd = -1;
862   pid_t pid = pdfork(&pd, 0);
863   EXPECT_OK(pid);
864   if (pid == 0) {
865     // Child: loop forever.
866     EXPECT_NE(parent, getpid_());
867     while (true) sleep(1);
868   }
869   // Create two capabilities from the process descriptor.
870   cap_rights_t r_ro;
871   cap_rights_init(&r_ro, CAP_READ, CAP_LOOKUP);
872   int cap_incapable = dup(pd);
873   EXPECT_OK(cap_incapable);
874   EXPECT_OK(cap_rights_limit(cap_incapable, &r_ro));
875   cap_rights_t r_pdall;
876   cap_rights_init(&r_pdall, CAP_PDGETPID, CAP_PDWAIT, CAP_PDKILL);
877   int cap_capable = dup(pd);
878   EXPECT_OK(cap_capable);
879   EXPECT_OK(cap_rights_limit(cap_capable, &r_pdall));
880 
881   pid_t other_pid;
882   EXPECT_NOTCAPABLE(pdgetpid(cap_incapable, &other_pid));
883   EXPECT_NOTCAPABLE(pdkill(cap_incapable, SIGINT));
884   int status;
885   EXPECT_NOTCAPABLE(pdwait4_(cap_incapable, &status, 0, NULL));
886 
887   EXPECT_OK(pdgetpid(cap_capable, &other_pid));
888   EXPECT_EQ(pid, other_pid);
889   EXPECT_OK(pdkill(cap_capable, SIGINT));
890   int rc = pdwait4_(pd, &status, 0, NULL);
891   EXPECT_OK(rc);
892   EXPECT_EQ(pid, rc);
893 }
894 
895 
896 //------------------------------------------------
897 // Passing process descriptors between processes.
898 
899 TEST_F(PipePdfork, PassProcessDescriptor) {
900   int sock_fds[2];
901   EXPECT_OK(socketpair(AF_UNIX, SOCK_STREAM, 0, sock_fds));
902 
903   struct msghdr mh;
904   mh.msg_name = NULL;  // No address needed
905   mh.msg_namelen = 0;
906   char buffer1[1024];
907   struct iovec iov[1];
908   iov[0].iov_base = buffer1;
909   iov[0].iov_len = sizeof(buffer1);
910   mh.msg_iov = iov;
911   mh.msg_iovlen = 1;
912   char buffer2[1024];
913   mh.msg_control = buffer2;
914   mh.msg_controllen = sizeof(buffer2);
915   struct cmsghdr *cmptr;
916 
917   if (verbose) fprintf(stderr, "[%d] about to fork()\n", getpid_());
918   pid_t child2 = fork();
919   if (child2 == 0) {
920     // Child: close our copy of the original process descriptor.
921     close(pd_);
922 
923     // Child: wait to receive process descriptor over socket
924     if (verbose) fprintf(stderr, "  [%d] child of %d waiting for process descriptor on socket\n", getpid_(), getppid());
925     int rc = recvmsg(sock_fds[0], &mh, 0);
926     EXPECT_OK(rc);
927     EXPECT_LE(CMSG_LEN(sizeof(int)), mh.msg_controllen);
928     cmptr = CMSG_FIRSTHDR(&mh);
929     int pd = *(int*)CMSG_DATA(cmptr);
930     EXPECT_EQ(CMSG_LEN(sizeof(int)), cmptr->cmsg_len);
931     cmptr = CMSG_NXTHDR(&mh, cmptr);
932     EXPECT_TRUE(cmptr == NULL);
933     if (verbose) fprintf(stderr, "  [%d] got process descriptor %d on socket\n", getpid_(), pd);
934 
935     // Child: confirm we can do pd*() operations on the process descriptor
936     pid_t other;
937     EXPECT_OK(pdgetpid(pd, &other));
938     if (verbose) fprintf(stderr, "  [%d] process descriptor %d is pid %d\n", getpid_(), pd, other);
939 
940     sleep(2);
941     if (verbose) fprintf(stderr, "  [%d] close process descriptor %d\n", getpid_(), pd);
942     close(pd);
943 
944     // Last process descriptor closed, expect death
945     EXPECT_PID_DEAD(other);
946 
947     exit(HasFailure());
948   }
949   usleep(1000);  // Ensure subprocess runs
950 
951   // Send the process descriptor over the pipe to the sub-process
952   mh.msg_controllen = CMSG_LEN(sizeof(int));
953   cmptr = CMSG_FIRSTHDR(&mh);
954   cmptr->cmsg_level = SOL_SOCKET;
955   cmptr->cmsg_type = SCM_RIGHTS;
956   cmptr->cmsg_len = CMSG_LEN(sizeof(int));
957   *(int *)CMSG_DATA(cmptr) = pd_;
958   buffer1[0] = 0;
959   iov[0].iov_len = 1;
960   sleep(1);
961   if (verbose) fprintf(stderr, "[%d] send process descriptor %d on socket\n", getpid_(), pd_);
962   int rc = sendmsg(sock_fds[1], &mh, 0);
963   EXPECT_OK(rc);
964 
965   if (verbose) fprintf(stderr, "[%d] close process descriptor %d\n", getpid_(), pd_);
966   close(pd_);  // Not last open process descriptor
967 
968   // wait for child2
969   int status;
970   EXPECT_EQ(child2, waitpid(child2, &status, __WALL));
971   rc = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
972   EXPECT_EQ(0, rc);
973 
974   // confirm death all round
975   EXPECT_PID_DEAD(child2);
976   EXPECT_PID_DEAD(pid_);
977 }
978