1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-spawn.c Wrapper around fork/exec
3 *
4 * Copyright (C) 2002, 2003, 2004 Red Hat, Inc.
5 * Copyright (C) 2003 CodeFactory AB
6 *
7 * Licensed under the Academic Free License version 2.1
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 *
23 */
24 #include "dbus-spawn.h"
25 #include "dbus-sysdeps.h"
26 #include "dbus-internals.h"
27 #include "dbus-test.h"
28 #include "dbus-protocol.h"
29
30 #include <unistd.h>
31 #include <fcntl.h>
32 #include <signal.h>
33 #include <sys/wait.h>
34 #include <errno.h>
35 #include <stdlib.h>
36
37 /**
38 * @addtogroup DBusInternalsUtils
39 * @{
40 */
41
42 /*
43 * I'm pretty sure this whole spawn file could be made simpler,
44 * if you thought about it a bit.
45 */
46
47 /**
48 * Enumeration for status of a read()
49 */
50 typedef enum
51 {
52 READ_STATUS_OK, /**< Read succeeded */
53 READ_STATUS_ERROR, /**< Some kind of error */
54 READ_STATUS_EOF /**< EOF returned */
55 } ReadStatus;
56
57 static ReadStatus
read_ints(int fd,int * buf,int n_ints_in_buf,int * n_ints_read,DBusError * error)58 read_ints (int fd,
59 int *buf,
60 int n_ints_in_buf,
61 int *n_ints_read,
62 DBusError *error)
63 {
64 size_t bytes = 0;
65 ReadStatus retval;
66
67 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
68
69 retval = READ_STATUS_OK;
70
71 while (TRUE)
72 {
73 ssize_t chunk;
74 size_t to_read;
75
76 to_read = sizeof (int) * n_ints_in_buf - bytes;
77
78 if (to_read == 0)
79 break;
80
81 again:
82
83 chunk = read (fd,
84 ((char*)buf) + bytes,
85 to_read);
86
87 if (chunk < 0 && errno == EINTR)
88 goto again;
89
90 if (chunk < 0)
91 {
92 dbus_set_error (error,
93 DBUS_ERROR_SPAWN_FAILED,
94 "Failed to read from child pipe (%s)",
95 _dbus_strerror (errno));
96
97 retval = READ_STATUS_ERROR;
98 break;
99 }
100 else if (chunk == 0)
101 {
102 retval = READ_STATUS_EOF;
103 break; /* EOF */
104 }
105 else /* chunk > 0 */
106 bytes += chunk;
107 }
108
109 *n_ints_read = (int)(bytes / sizeof(int));
110
111 return retval;
112 }
113
114 static ReadStatus
read_pid(int fd,pid_t * buf,DBusError * error)115 read_pid (int fd,
116 pid_t *buf,
117 DBusError *error)
118 {
119 size_t bytes = 0;
120 ReadStatus retval;
121
122 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
123
124 retval = READ_STATUS_OK;
125
126 while (TRUE)
127 {
128 ssize_t chunk;
129 size_t to_read;
130
131 to_read = sizeof (pid_t) - bytes;
132
133 if (to_read == 0)
134 break;
135
136 again:
137
138 chunk = read (fd,
139 ((char*)buf) + bytes,
140 to_read);
141 if (chunk < 0 && errno == EINTR)
142 goto again;
143
144 if (chunk < 0)
145 {
146 dbus_set_error (error,
147 DBUS_ERROR_SPAWN_FAILED,
148 "Failed to read from child pipe (%s)",
149 _dbus_strerror (errno));
150
151 retval = READ_STATUS_ERROR;
152 break;
153 }
154 else if (chunk == 0)
155 {
156 retval = READ_STATUS_EOF;
157 break; /* EOF */
158 }
159 else /* chunk > 0 */
160 bytes += chunk;
161 }
162
163 return retval;
164 }
165
166 /* The implementation uses an intermediate child between the main process
167 * and the grandchild. The grandchild is our spawned process. The intermediate
168 * child is a babysitter process; it keeps track of when the grandchild
169 * exits/crashes, and reaps the grandchild.
170 */
171
172 /* Messages from children to parents */
173 enum
174 {
175 CHILD_EXITED, /* This message is followed by the exit status int */
176 CHILD_FORK_FAILED, /* Followed by errno */
177 CHILD_EXEC_FAILED, /* Followed by errno */
178 CHILD_PID /* Followed by pid_t */
179 };
180
181 /**
182 * Babysitter implementation details
183 */
184 struct DBusBabysitter
185 {
186 int refcount; /**< Reference count */
187
188 char *executable; /**< executable name to use in error messages */
189
190 int socket_to_babysitter; /**< Connection to the babysitter process */
191 int error_pipe_from_child; /**< Connection to the process that does the exec() */
192
193 pid_t sitter_pid; /**< PID Of the babysitter */
194 pid_t grandchild_pid; /**< PID of the grandchild */
195
196 DBusWatchList *watches; /**< Watches */
197
198 DBusWatch *error_watch; /**< Error pipe watch */
199 DBusWatch *sitter_watch; /**< Sitter pipe watch */
200
201 int errnum; /**< Error number */
202 int status; /**< Exit status code */
203 unsigned int have_child_status : 1; /**< True if child status has been reaped */
204 unsigned int have_fork_errnum : 1; /**< True if we have an error code from fork() */
205 unsigned int have_exec_errnum : 1; /**< True if we have an error code from exec() */
206 };
207
208 static DBusBabysitter*
_dbus_babysitter_new(void)209 _dbus_babysitter_new (void)
210 {
211 DBusBabysitter *sitter;
212
213 sitter = dbus_new0 (DBusBabysitter, 1);
214 if (sitter == NULL)
215 return NULL;
216
217 sitter->refcount = 1;
218
219 sitter->socket_to_babysitter = -1;
220 sitter->error_pipe_from_child = -1;
221
222 sitter->sitter_pid = -1;
223 sitter->grandchild_pid = -1;
224
225 sitter->watches = _dbus_watch_list_new ();
226 if (sitter->watches == NULL)
227 goto failed;
228
229 return sitter;
230
231 failed:
232 _dbus_babysitter_unref (sitter);
233 return NULL;
234 }
235
236 /**
237 * Increment the reference count on the babysitter object.
238 *
239 * @param sitter the babysitter
240 * @returns the babysitter
241 */
242 DBusBabysitter *
_dbus_babysitter_ref(DBusBabysitter * sitter)243 _dbus_babysitter_ref (DBusBabysitter *sitter)
244 {
245 _dbus_assert (sitter != NULL);
246 _dbus_assert (sitter->refcount > 0);
247
248 sitter->refcount += 1;
249
250 return sitter;
251 }
252
253 /**
254 * Decrement the reference count on the babysitter object.
255 * When the reference count of the babysitter object reaches
256 * zero, the babysitter is killed and the child that was being
257 * babysat gets emancipated.
258 *
259 * @param sitter the babysitter
260 */
261 void
_dbus_babysitter_unref(DBusBabysitter * sitter)262 _dbus_babysitter_unref (DBusBabysitter *sitter)
263 {
264 _dbus_assert (sitter != NULL);
265 _dbus_assert (sitter->refcount > 0);
266
267 sitter->refcount -= 1;
268 if (sitter->refcount == 0)
269 {
270 if (sitter->socket_to_babysitter >= 0)
271 {
272 /* If we haven't forked other babysitters
273 * since this babysitter and socket were
274 * created then this close will cause the
275 * babysitter to wake up from poll with
276 * a hangup and then the babysitter will
277 * quit itself.
278 */
279 _dbus_close_socket (sitter->socket_to_babysitter, NULL);
280 sitter->socket_to_babysitter = -1;
281 }
282
283 if (sitter->error_pipe_from_child >= 0)
284 {
285 _dbus_close_socket (sitter->error_pipe_from_child, NULL);
286 sitter->error_pipe_from_child = -1;
287 }
288
289 if (sitter->sitter_pid > 0)
290 {
291 int status;
292 int ret;
293
294 /* It's possible the babysitter died on its own above
295 * from the close, or was killed randomly
296 * by some other process, so first try to reap it
297 */
298 ret = waitpid (sitter->sitter_pid, &status, WNOHANG);
299
300 /* If we couldn't reap the child then kill it, and
301 * try again
302 */
303 if (ret == 0)
304 kill (sitter->sitter_pid, SIGKILL);
305
306 again:
307 if (ret == 0)
308 ret = waitpid (sitter->sitter_pid, &status, 0);
309
310 if (ret < 0)
311 {
312 if (errno == EINTR)
313 goto again;
314 else if (errno == ECHILD)
315 _dbus_warn ("Babysitter process not available to be reaped; should not happen\n");
316 else
317 _dbus_warn ("Unexpected error %d in waitpid() for babysitter: %s\n",
318 errno, _dbus_strerror (errno));
319 }
320 else
321 {
322 _dbus_verbose ("Reaped %ld, waiting for babysitter %ld\n",
323 (long) ret, (long) sitter->sitter_pid);
324
325 if (WIFEXITED (sitter->status))
326 _dbus_verbose ("Babysitter exited with status %d\n",
327 WEXITSTATUS (sitter->status));
328 else if (WIFSIGNALED (sitter->status))
329 _dbus_verbose ("Babysitter received signal %d\n",
330 WTERMSIG (sitter->status));
331 else
332 _dbus_verbose ("Babysitter exited abnormally\n");
333 }
334
335 sitter->sitter_pid = -1;
336 }
337
338 if (sitter->error_watch)
339 {
340 _dbus_watch_invalidate (sitter->error_watch);
341 _dbus_watch_unref (sitter->error_watch);
342 sitter->error_watch = NULL;
343 }
344
345 if (sitter->sitter_watch)
346 {
347 _dbus_watch_invalidate (sitter->sitter_watch);
348 _dbus_watch_unref (sitter->sitter_watch);
349 sitter->sitter_watch = NULL;
350 }
351
352 if (sitter->watches)
353 _dbus_watch_list_free (sitter->watches);
354
355 dbus_free (sitter->executable);
356
357 dbus_free (sitter);
358 }
359 }
360
361 static ReadStatus
read_data(DBusBabysitter * sitter,int fd)362 read_data (DBusBabysitter *sitter,
363 int fd)
364 {
365 int what;
366 int got;
367 DBusError error;
368 ReadStatus r;
369
370 dbus_error_init (&error);
371
372 r = read_ints (fd, &what, 1, &got, &error);
373
374 switch (r)
375 {
376 case READ_STATUS_ERROR:
377 _dbus_warn ("Failed to read data from fd %d: %s\n", fd, error.message);
378 dbus_error_free (&error);
379 return r;
380
381 case READ_STATUS_EOF:
382 return r;
383
384 case READ_STATUS_OK:
385 break;
386 }
387
388 if (got == 1)
389 {
390 switch (what)
391 {
392 case CHILD_EXITED:
393 case CHILD_FORK_FAILED:
394 case CHILD_EXEC_FAILED:
395 {
396 int arg;
397
398 r = read_ints (fd, &arg, 1, &got, &error);
399
400 switch (r)
401 {
402 case READ_STATUS_ERROR:
403 _dbus_warn ("Failed to read arg from fd %d: %s\n", fd, error.message);
404 dbus_error_free (&error);
405 return r;
406 case READ_STATUS_EOF:
407 return r;
408 case READ_STATUS_OK:
409 break;
410 }
411
412 if (got == 1)
413 {
414 if (what == CHILD_EXITED)
415 {
416 sitter->have_child_status = TRUE;
417 sitter->status = arg;
418 _dbus_verbose ("recorded child status exited = %d signaled = %d exitstatus = %d termsig = %d\n",
419 WIFEXITED (sitter->status), WIFSIGNALED (sitter->status),
420 WEXITSTATUS (sitter->status), WTERMSIG (sitter->status));
421 }
422 else if (what == CHILD_FORK_FAILED)
423 {
424 sitter->have_fork_errnum = TRUE;
425 sitter->errnum = arg;
426 _dbus_verbose ("recorded fork errnum %d\n", sitter->errnum);
427 }
428 else if (what == CHILD_EXEC_FAILED)
429 {
430 sitter->have_exec_errnum = TRUE;
431 sitter->errnum = arg;
432 _dbus_verbose ("recorded exec errnum %d\n", sitter->errnum);
433 }
434 }
435 }
436 break;
437 case CHILD_PID:
438 {
439 pid_t pid = -1;
440
441 r = read_pid (fd, &pid, &error);
442
443 switch (r)
444 {
445 case READ_STATUS_ERROR:
446 _dbus_warn ("Failed to read PID from fd %d: %s\n", fd, error.message);
447 dbus_error_free (&error);
448 return r;
449 case READ_STATUS_EOF:
450 return r;
451 case READ_STATUS_OK:
452 break;
453 }
454
455 sitter->grandchild_pid = pid;
456
457 _dbus_verbose ("recorded grandchild pid %d\n", sitter->grandchild_pid);
458 }
459 break;
460 default:
461 _dbus_warn ("Unknown message received from babysitter process\n");
462 break;
463 }
464 }
465
466 return r;
467 }
468
469 static void
close_socket_to_babysitter(DBusBabysitter * sitter)470 close_socket_to_babysitter (DBusBabysitter *sitter)
471 {
472 _dbus_verbose ("Closing babysitter\n");
473 _dbus_close_socket (sitter->socket_to_babysitter, NULL);
474 sitter->socket_to_babysitter = -1;
475 }
476
477 static void
close_error_pipe_from_child(DBusBabysitter * sitter)478 close_error_pipe_from_child (DBusBabysitter *sitter)
479 {
480 _dbus_verbose ("Closing child error\n");
481 _dbus_close_socket (sitter->error_pipe_from_child, NULL);
482 sitter->error_pipe_from_child = -1;
483 }
484
485 static void
handle_babysitter_socket(DBusBabysitter * sitter,int revents)486 handle_babysitter_socket (DBusBabysitter *sitter,
487 int revents)
488 {
489 /* Even if we have POLLHUP, we want to keep reading
490 * data until POLLIN goes away; so this function only
491 * looks at HUP/ERR if no IN is set.
492 */
493 if (revents & _DBUS_POLLIN)
494 {
495 _dbus_verbose ("Reading data from babysitter\n");
496 if (read_data (sitter, sitter->socket_to_babysitter) != READ_STATUS_OK)
497 close_socket_to_babysitter (sitter);
498 }
499 else if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
500 {
501 close_socket_to_babysitter (sitter);
502 }
503 }
504
505 static void
handle_error_pipe(DBusBabysitter * sitter,int revents)506 handle_error_pipe (DBusBabysitter *sitter,
507 int revents)
508 {
509 if (revents & _DBUS_POLLIN)
510 {
511 _dbus_verbose ("Reading data from child error\n");
512 if (read_data (sitter, sitter->error_pipe_from_child) != READ_STATUS_OK)
513 close_error_pipe_from_child (sitter);
514 }
515 else if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
516 {
517 close_error_pipe_from_child (sitter);
518 }
519 }
520
521 /* returns whether there were any poll events handled */
522 static dbus_bool_t
babysitter_iteration(DBusBabysitter * sitter,dbus_bool_t block)523 babysitter_iteration (DBusBabysitter *sitter,
524 dbus_bool_t block)
525 {
526 DBusPollFD fds[2];
527 int i;
528 dbus_bool_t descriptors_ready;
529
530 descriptors_ready = FALSE;
531
532 i = 0;
533
534 if (sitter->error_pipe_from_child >= 0)
535 {
536 fds[i].fd = sitter->error_pipe_from_child;
537 fds[i].events = _DBUS_POLLIN;
538 fds[i].revents = 0;
539 ++i;
540 }
541
542 if (sitter->socket_to_babysitter >= 0)
543 {
544 fds[i].fd = sitter->socket_to_babysitter;
545 fds[i].events = _DBUS_POLLIN;
546 fds[i].revents = 0;
547 ++i;
548 }
549
550 if (i > 0)
551 {
552 int ret;
553
554 ret = _dbus_poll (fds, i, 0);
555 if (ret == 0 && block)
556 ret = _dbus_poll (fds, i, -1);
557
558 if (ret > 0)
559 {
560 descriptors_ready = TRUE;
561
562 while (i > 0)
563 {
564 --i;
565 if (fds[i].fd == sitter->error_pipe_from_child)
566 handle_error_pipe (sitter, fds[i].revents);
567 else if (fds[i].fd == sitter->socket_to_babysitter)
568 handle_babysitter_socket (sitter, fds[i].revents);
569 }
570 }
571 }
572
573 return descriptors_ready;
574 }
575
576 /**
577 * Macro returns #TRUE if the babysitter still has live sockets open to the
578 * babysitter child or the grandchild.
579 */
580 #define LIVE_CHILDREN(sitter) ((sitter)->socket_to_babysitter >= 0 || (sitter)->error_pipe_from_child >= 0)
581
582 /**
583 * Blocks until the babysitter process gives us the PID of the spawned grandchild,
584 * then kills the spawned grandchild.
585 *
586 * @param sitter the babysitter object
587 */
588 void
_dbus_babysitter_kill_child(DBusBabysitter * sitter)589 _dbus_babysitter_kill_child (DBusBabysitter *sitter)
590 {
591 /* be sure we have the PID of the child */
592 while (LIVE_CHILDREN (sitter) &&
593 sitter->grandchild_pid == -1)
594 babysitter_iteration (sitter, TRUE);
595
596 _dbus_verbose ("Got child PID %ld for killing\n",
597 (long) sitter->grandchild_pid);
598
599 if (sitter->grandchild_pid == -1)
600 return; /* child is already dead, or we're so hosed we'll never recover */
601
602 kill (sitter->grandchild_pid, SIGKILL);
603 }
604
605 /**
606 * Checks whether the child has exited, without blocking.
607 *
608 * @param sitter the babysitter
609 */
610 dbus_bool_t
_dbus_babysitter_get_child_exited(DBusBabysitter * sitter)611 _dbus_babysitter_get_child_exited (DBusBabysitter *sitter)
612 {
613
614 /* Be sure we're up-to-date */
615 while (LIVE_CHILDREN (sitter) &&
616 babysitter_iteration (sitter, FALSE))
617 ;
618
619 /* We will have exited the babysitter when the child has exited */
620 return sitter->socket_to_babysitter < 0;
621 }
622
623 /**
624 * Sets the #DBusError with an explanation of why the spawned
625 * child process exited (on a signal, or whatever). If
626 * the child process has not exited, does nothing (error
627 * will remain unset).
628 *
629 * @param sitter the babysitter
630 * @param error an error to fill in
631 */
632 void
_dbus_babysitter_set_child_exit_error(DBusBabysitter * sitter,DBusError * error)633 _dbus_babysitter_set_child_exit_error (DBusBabysitter *sitter,
634 DBusError *error)
635 {
636 if (!_dbus_babysitter_get_child_exited (sitter))
637 return;
638
639 /* Note that if exec fails, we will also get a child status
640 * from the babysitter saying the child exited,
641 * so we need to give priority to the exec error
642 */
643 if (sitter->have_exec_errnum)
644 {
645 dbus_set_error (error, DBUS_ERROR_SPAWN_EXEC_FAILED,
646 "Failed to execute program %s: %s",
647 sitter->executable, _dbus_strerror (sitter->errnum));
648 }
649 else if (sitter->have_fork_errnum)
650 {
651 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
652 "Failed to fork a new process %s: %s",
653 sitter->executable, _dbus_strerror (sitter->errnum));
654 }
655 else if (sitter->have_child_status)
656 {
657 if (WIFEXITED (sitter->status))
658 dbus_set_error (error, DBUS_ERROR_SPAWN_CHILD_EXITED,
659 "Process %s exited with status %d",
660 sitter->executable, WEXITSTATUS (sitter->status));
661 else if (WIFSIGNALED (sitter->status))
662 dbus_set_error (error, DBUS_ERROR_SPAWN_CHILD_SIGNALED,
663 "Process %s received signal %d",
664 sitter->executable, WTERMSIG (sitter->status));
665 else
666 dbus_set_error (error, DBUS_ERROR_FAILED,
667 "Process %s exited abnormally",
668 sitter->executable);
669 }
670 else
671 {
672 dbus_set_error (error, DBUS_ERROR_FAILED,
673 "Process %s exited, reason unknown",
674 sitter->executable);
675 }
676 }
677
678 /**
679 * Sets watch functions to notify us when the
680 * babysitter object needs to read/write file descriptors.
681 *
682 * @param sitter the babysitter
683 * @param add_function function to begin monitoring a new descriptor.
684 * @param remove_function function to stop monitoring a descriptor.
685 * @param toggled_function function to notify when the watch is enabled/disabled
686 * @param data data to pass to add_function and remove_function.
687 * @param free_data_function function to be called to free the data.
688 * @returns #FALSE on failure (no memory)
689 */
690 dbus_bool_t
_dbus_babysitter_set_watch_functions(DBusBabysitter * sitter,DBusAddWatchFunction add_function,DBusRemoveWatchFunction remove_function,DBusWatchToggledFunction toggled_function,void * data,DBusFreeFunction free_data_function)691 _dbus_babysitter_set_watch_functions (DBusBabysitter *sitter,
692 DBusAddWatchFunction add_function,
693 DBusRemoveWatchFunction remove_function,
694 DBusWatchToggledFunction toggled_function,
695 void *data,
696 DBusFreeFunction free_data_function)
697 {
698 return _dbus_watch_list_set_functions (sitter->watches,
699 add_function,
700 remove_function,
701 toggled_function,
702 data,
703 free_data_function);
704 }
705
706 static dbus_bool_t
handle_watch(DBusWatch * watch,unsigned int condition,void * data)707 handle_watch (DBusWatch *watch,
708 unsigned int condition,
709 void *data)
710 {
711 DBusBabysitter *sitter = data;
712 int revents;
713 int fd;
714
715 revents = 0;
716 if (condition & DBUS_WATCH_READABLE)
717 revents |= _DBUS_POLLIN;
718 if (condition & DBUS_WATCH_ERROR)
719 revents |= _DBUS_POLLERR;
720 if (condition & DBUS_WATCH_HANGUP)
721 revents |= _DBUS_POLLHUP;
722
723 fd = dbus_watch_get_fd (watch);
724
725 if (fd == sitter->error_pipe_from_child)
726 handle_error_pipe (sitter, revents);
727 else if (fd == sitter->socket_to_babysitter)
728 handle_babysitter_socket (sitter, revents);
729
730 while (LIVE_CHILDREN (sitter) &&
731 babysitter_iteration (sitter, FALSE))
732 ;
733
734 return TRUE;
735 }
736
737 /** Helps remember which end of the pipe is which */
738 #define READ_END 0
739 /** Helps remember which end of the pipe is which */
740 #define WRITE_END 1
741
742
743 /* Avoids a danger in threaded situations (calling close()
744 * on a file descriptor twice, and another thread has
745 * re-opened it since the first close)
746 */
747 static int
close_and_invalidate(int * fd)748 close_and_invalidate (int *fd)
749 {
750 int ret;
751
752 if (*fd < 0)
753 return -1;
754 else
755 {
756 ret = _dbus_close_socket (*fd, NULL);
757 *fd = -1;
758 }
759
760 return ret;
761 }
762
763 static dbus_bool_t
make_pipe(int p[2],DBusError * error)764 make_pipe (int p[2],
765 DBusError *error)
766 {
767 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
768
769 if (pipe (p) < 0)
770 {
771 dbus_set_error (error,
772 DBUS_ERROR_SPAWN_FAILED,
773 "Failed to create pipe for communicating with child process (%s)",
774 _dbus_strerror (errno));
775 return FALSE;
776 }
777
778 return TRUE;
779 }
780
781 static void
do_write(int fd,const void * buf,size_t count)782 do_write (int fd, const void *buf, size_t count)
783 {
784 size_t bytes_written;
785 int ret;
786
787 bytes_written = 0;
788
789 again:
790
791 ret = write (fd, ((const char*)buf) + bytes_written, count - bytes_written);
792
793 if (ret < 0)
794 {
795 if (errno == EINTR)
796 goto again;
797 else
798 {
799 _dbus_warn ("Failed to write data to pipe!\n");
800 exit (1); /* give up, we suck */
801 }
802 }
803 else
804 bytes_written += ret;
805
806 if (bytes_written < count)
807 goto again;
808 }
809
810 static void
write_err_and_exit(int fd,int msg)811 write_err_and_exit (int fd, int msg)
812 {
813 int en = errno;
814
815 do_write (fd, &msg, sizeof (msg));
816 do_write (fd, &en, sizeof (en));
817
818 exit (1);
819 }
820
821 static void
write_pid(int fd,pid_t pid)822 write_pid (int fd, pid_t pid)
823 {
824 int msg = CHILD_PID;
825
826 do_write (fd, &msg, sizeof (msg));
827 do_write (fd, &pid, sizeof (pid));
828 }
829
830 static void
write_status_and_exit(int fd,int status)831 write_status_and_exit (int fd, int status)
832 {
833 int msg = CHILD_EXITED;
834
835 do_write (fd, &msg, sizeof (msg));
836 do_write (fd, &status, sizeof (status));
837
838 exit (0);
839 }
840
841 static void
do_exec(int child_err_report_fd,char ** argv,DBusSpawnChildSetupFunc child_setup,void * user_data)842 do_exec (int child_err_report_fd,
843 char **argv,
844 DBusSpawnChildSetupFunc child_setup,
845 void *user_data)
846 {
847 #ifdef DBUS_BUILD_TESTS
848 int i, max_open;
849 #endif
850
851 _dbus_verbose_reset ();
852 _dbus_verbose ("Child process has PID %lu\n",
853 _dbus_getpid ());
854
855 if (child_setup)
856 (* child_setup) (user_data);
857
858 #ifdef DBUS_BUILD_TESTS
859 max_open = sysconf (_SC_OPEN_MAX);
860
861 for (i = 3; i < max_open; i++)
862 {
863 int retval;
864
865 if (i == child_err_report_fd)
866 continue;
867
868 retval = fcntl (i, F_GETFD);
869
870 if (retval != -1 && !(retval & FD_CLOEXEC))
871 _dbus_warn ("Fd %d did not have the close-on-exec flag set!\n", i);
872 }
873 #endif
874
875 execv (argv[0], argv);
876
877 /* Exec failed */
878 write_err_and_exit (child_err_report_fd,
879 CHILD_EXEC_FAILED);
880 }
881
882 static void
check_babysit_events(pid_t grandchild_pid,int parent_pipe,int revents)883 check_babysit_events (pid_t grandchild_pid,
884 int parent_pipe,
885 int revents)
886 {
887 pid_t ret;
888 int status;
889
890 do
891 {
892 ret = waitpid (grandchild_pid, &status, WNOHANG);
893 /* The man page says EINTR can't happen with WNOHANG,
894 * but there are reports of it (maybe only with valgrind?)
895 */
896 }
897 while (ret < 0 && errno == EINTR);
898
899 if (ret == 0)
900 {
901 _dbus_verbose ("no child exited\n");
902
903 ; /* no child exited */
904 }
905 else if (ret < 0)
906 {
907 /* This isn't supposed to happen. */
908 _dbus_warn ("unexpected waitpid() failure in check_babysit_events(): %s\n",
909 _dbus_strerror (errno));
910 exit (1);
911 }
912 else if (ret == grandchild_pid)
913 {
914 /* Child exited */
915 _dbus_verbose ("reaped child pid %ld\n", (long) ret);
916
917 write_status_and_exit (parent_pipe, status);
918 }
919 else
920 {
921 _dbus_warn ("waitpid() reaped pid %d that we've never heard of\n",
922 (int) ret);
923 exit (1);
924 }
925
926 if (revents & _DBUS_POLLIN)
927 {
928 _dbus_verbose ("babysitter got POLLIN from parent pipe\n");
929 }
930
931 if (revents & (_DBUS_POLLERR | _DBUS_POLLHUP))
932 {
933 /* Parent is gone, so we just exit */
934 _dbus_verbose ("babysitter got POLLERR or POLLHUP from parent\n");
935 exit (0);
936 }
937 }
938
939 static int babysit_sigchld_pipe = -1;
940
941 static void
babysit_signal_handler(int signo)942 babysit_signal_handler (int signo)
943 {
944 char b = '\0';
945 again:
946 write (babysit_sigchld_pipe, &b, 1);
947 if (errno == EINTR)
948 goto again;
949 }
950
951 static void
babysit(pid_t grandchild_pid,int parent_pipe)952 babysit (pid_t grandchild_pid,
953 int parent_pipe)
954 {
955 int sigchld_pipe[2];
956
957 /* We don't exec, so we keep parent state, such as the pid that
958 * _dbus_verbose() uses. Reset the pid here.
959 */
960 _dbus_verbose_reset ();
961
962 /* I thought SIGCHLD would just wake up the poll, but
963 * that didn't seem to work, so added this pipe.
964 * Probably the pipe is more likely to work on busted
965 * operating systems anyhow.
966 */
967 if (pipe (sigchld_pipe) < 0)
968 {
969 _dbus_warn ("Not enough file descriptors to create pipe in babysitter process\n");
970 exit (1);
971 }
972
973 babysit_sigchld_pipe = sigchld_pipe[WRITE_END];
974
975 _dbus_set_signal_handler (SIGCHLD, babysit_signal_handler);
976
977 write_pid (parent_pipe, grandchild_pid);
978
979 check_babysit_events (grandchild_pid, parent_pipe, 0);
980
981 while (TRUE)
982 {
983 DBusPollFD pfds[2];
984
985 pfds[0].fd = parent_pipe;
986 pfds[0].events = _DBUS_POLLIN;
987 pfds[0].revents = 0;
988
989 pfds[1].fd = sigchld_pipe[READ_END];
990 pfds[1].events = _DBUS_POLLIN;
991 pfds[1].revents = 0;
992
993 _dbus_poll (pfds, _DBUS_N_ELEMENTS (pfds), -1);
994
995 if (pfds[0].revents != 0)
996 {
997 check_babysit_events (grandchild_pid, parent_pipe, pfds[0].revents);
998 }
999 else if (pfds[1].revents & _DBUS_POLLIN)
1000 {
1001 char b;
1002 read (sigchld_pipe[READ_END], &b, 1);
1003 /* do waitpid check */
1004 check_babysit_events (grandchild_pid, parent_pipe, 0);
1005 }
1006 }
1007
1008 exit (1);
1009 }
1010
1011 /**
1012 * Spawns a new process. The executable name and argv[0]
1013 * are the same, both are provided in argv[0]. The child_setup
1014 * function is passed the given user_data and is run in the child
1015 * just before calling exec().
1016 *
1017 * Also creates a "babysitter" which tracks the status of the
1018 * child process, advising the parent if the child exits.
1019 * If the spawn fails, no babysitter is created.
1020 * If sitter_p is #NULL, no babysitter is kept.
1021 *
1022 * @param sitter_p return location for babysitter or #NULL
1023 * @param argv the executable and arguments
1024 * @param child_setup function to call in child pre-exec()
1025 * @param user_data user data for setup function
1026 * @param error error object to be filled in if function fails
1027 * @returns #TRUE on success, #FALSE if error is filled in
1028 */
1029 dbus_bool_t
_dbus_spawn_async_with_babysitter(DBusBabysitter ** sitter_p,char ** argv,DBusSpawnChildSetupFunc child_setup,void * user_data,DBusError * error)1030 _dbus_spawn_async_with_babysitter (DBusBabysitter **sitter_p,
1031 char **argv,
1032 DBusSpawnChildSetupFunc child_setup,
1033 void *user_data,
1034 DBusError *error)
1035 {
1036 DBusBabysitter *sitter;
1037 int child_err_report_pipe[2] = { -1, -1 };
1038 int babysitter_pipe[2] = { -1, -1 };
1039 pid_t pid;
1040
1041 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1042
1043 *sitter_p = NULL;
1044 sitter = NULL;
1045
1046 sitter = _dbus_babysitter_new ();
1047 if (sitter == NULL)
1048 {
1049 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1050 return FALSE;
1051 }
1052
1053 sitter->executable = _dbus_strdup (argv[0]);
1054 if (sitter->executable == NULL)
1055 {
1056 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1057 goto cleanup_and_fail;
1058 }
1059
1060 if (!make_pipe (child_err_report_pipe, error))
1061 goto cleanup_and_fail;
1062
1063 _dbus_fd_set_close_on_exec (child_err_report_pipe[READ_END]);
1064 _dbus_fd_set_close_on_exec (child_err_report_pipe[WRITE_END]);
1065
1066 if (!_dbus_full_duplex_pipe (&babysitter_pipe[0], &babysitter_pipe[1], TRUE, error))
1067 goto cleanup_and_fail;
1068
1069 _dbus_fd_set_close_on_exec (babysitter_pipe[0]);
1070 _dbus_fd_set_close_on_exec (babysitter_pipe[1]);
1071
1072 /* Setting up the babysitter is only useful in the parent,
1073 * but we don't want to run out of memory and fail
1074 * after we've already forked, since then we'd leak
1075 * child processes everywhere.
1076 */
1077 sitter->error_watch = _dbus_watch_new (child_err_report_pipe[READ_END],
1078 DBUS_WATCH_READABLE,
1079 TRUE, handle_watch, sitter, NULL);
1080 if (sitter->error_watch == NULL)
1081 {
1082 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1083 goto cleanup_and_fail;
1084 }
1085
1086 if (!_dbus_watch_list_add_watch (sitter->watches, sitter->error_watch))
1087 {
1088 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1089 goto cleanup_and_fail;
1090 }
1091
1092 sitter->sitter_watch = _dbus_watch_new (babysitter_pipe[0],
1093 DBUS_WATCH_READABLE,
1094 TRUE, handle_watch, sitter, NULL);
1095 if (sitter->sitter_watch == NULL)
1096 {
1097 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1098 goto cleanup_and_fail;
1099 }
1100
1101 if (!_dbus_watch_list_add_watch (sitter->watches, sitter->sitter_watch))
1102 {
1103 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1104 goto cleanup_and_fail;
1105 }
1106
1107 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1108
1109 pid = fork ();
1110
1111 if (pid < 0)
1112 {
1113 dbus_set_error (error,
1114 DBUS_ERROR_SPAWN_FORK_FAILED,
1115 "Failed to fork (%s)",
1116 _dbus_strerror (errno));
1117 goto cleanup_and_fail;
1118 }
1119 else if (pid == 0)
1120 {
1121 /* Immediate child, this is the babysitter process. */
1122 int grandchild_pid;
1123
1124 /* Be sure we crash if the parent exits
1125 * and we write to the err_report_pipe
1126 */
1127 signal (SIGPIPE, SIG_DFL);
1128
1129 /* Close the parent's end of the pipes. */
1130 close_and_invalidate (&child_err_report_pipe[READ_END]);
1131 close_and_invalidate (&babysitter_pipe[0]);
1132
1133 /* Create the child that will exec () */
1134 grandchild_pid = fork ();
1135
1136 if (grandchild_pid < 0)
1137 {
1138 write_err_and_exit (babysitter_pipe[1],
1139 CHILD_FORK_FAILED);
1140 _dbus_assert_not_reached ("Got to code after write_err_and_exit()");
1141 }
1142 else if (grandchild_pid == 0)
1143 {
1144 do_exec (child_err_report_pipe[WRITE_END],
1145 argv,
1146 child_setup, user_data);
1147 _dbus_assert_not_reached ("Got to code after exec() - should have exited on error");
1148 }
1149 else
1150 {
1151 babysit (grandchild_pid, babysitter_pipe[1]);
1152 _dbus_assert_not_reached ("Got to code after babysit()");
1153 }
1154 }
1155 else
1156 {
1157 /* Close the uncared-about ends of the pipes */
1158 close_and_invalidate (&child_err_report_pipe[WRITE_END]);
1159 close_and_invalidate (&babysitter_pipe[1]);
1160
1161 sitter->socket_to_babysitter = babysitter_pipe[0];
1162 babysitter_pipe[0] = -1;
1163
1164 sitter->error_pipe_from_child = child_err_report_pipe[READ_END];
1165 child_err_report_pipe[READ_END] = -1;
1166
1167 sitter->sitter_pid = pid;
1168
1169 if (sitter_p != NULL)
1170 *sitter_p = sitter;
1171 else
1172 _dbus_babysitter_unref (sitter);
1173
1174 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1175
1176 return TRUE;
1177 }
1178
1179 cleanup_and_fail:
1180
1181 _DBUS_ASSERT_ERROR_IS_SET (error);
1182
1183 close_and_invalidate (&child_err_report_pipe[READ_END]);
1184 close_and_invalidate (&child_err_report_pipe[WRITE_END]);
1185 close_and_invalidate (&babysitter_pipe[0]);
1186 close_and_invalidate (&babysitter_pipe[1]);
1187
1188 if (sitter != NULL)
1189 _dbus_babysitter_unref (sitter);
1190
1191 return FALSE;
1192 }
1193
1194 /** @} */
1195
1196 #ifdef DBUS_BUILD_TESTS
1197
1198 static void
_dbus_babysitter_block_for_child_exit(DBusBabysitter * sitter)1199 _dbus_babysitter_block_for_child_exit (DBusBabysitter *sitter)
1200 {
1201 while (LIVE_CHILDREN (sitter))
1202 babysitter_iteration (sitter, TRUE);
1203 }
1204
1205 static dbus_bool_t
check_spawn_nonexistent(void * data)1206 check_spawn_nonexistent (void *data)
1207 {
1208 char *argv[4] = { NULL, NULL, NULL, NULL };
1209 DBusBabysitter *sitter;
1210 DBusError error;
1211
1212 sitter = NULL;
1213
1214 dbus_error_init (&error);
1215
1216 /*** Test launching nonexistent binary */
1217
1218 argv[0] = "/this/does/not/exist/32542sdgafgafdg";
1219 if (_dbus_spawn_async_with_babysitter (&sitter, argv,
1220 NULL, NULL,
1221 &error))
1222 {
1223 _dbus_babysitter_block_for_child_exit (sitter);
1224 _dbus_babysitter_set_child_exit_error (sitter, &error);
1225 }
1226
1227 if (sitter)
1228 _dbus_babysitter_unref (sitter);
1229
1230 if (!dbus_error_is_set (&error))
1231 {
1232 _dbus_warn ("Did not get an error launching nonexistent executable\n");
1233 return FALSE;
1234 }
1235
1236 if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1237 dbus_error_has_name (&error, DBUS_ERROR_SPAWN_EXEC_FAILED)))
1238 {
1239 _dbus_warn ("Not expecting error when launching nonexistent executable: %s: %s\n",
1240 error.name, error.message);
1241 dbus_error_free (&error);
1242 return FALSE;
1243 }
1244
1245 dbus_error_free (&error);
1246
1247 return TRUE;
1248 }
1249
1250 static dbus_bool_t
check_spawn_segfault(void * data)1251 check_spawn_segfault (void *data)
1252 {
1253 char *argv[4] = { NULL, NULL, NULL, NULL };
1254 DBusBabysitter *sitter;
1255 DBusError error;
1256
1257 sitter = NULL;
1258
1259 dbus_error_init (&error);
1260
1261 /*** Test launching segfault binary */
1262
1263 argv[0] = TEST_SEGFAULT_BINARY;
1264 if (_dbus_spawn_async_with_babysitter (&sitter, argv,
1265 NULL, NULL,
1266 &error))
1267 {
1268 _dbus_babysitter_block_for_child_exit (sitter);
1269 _dbus_babysitter_set_child_exit_error (sitter, &error);
1270 }
1271
1272 if (sitter)
1273 _dbus_babysitter_unref (sitter);
1274
1275 if (!dbus_error_is_set (&error))
1276 {
1277 _dbus_warn ("Did not get an error launching segfaulting binary\n");
1278 return FALSE;
1279 }
1280
1281 if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1282 dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_SIGNALED)))
1283 {
1284 _dbus_warn ("Not expecting error when launching segfaulting executable: %s: %s\n",
1285 error.name, error.message);
1286 dbus_error_free (&error);
1287 return FALSE;
1288 }
1289
1290 dbus_error_free (&error);
1291
1292 return TRUE;
1293 }
1294
1295 static dbus_bool_t
check_spawn_exit(void * data)1296 check_spawn_exit (void *data)
1297 {
1298 char *argv[4] = { NULL, NULL, NULL, NULL };
1299 DBusBabysitter *sitter;
1300 DBusError error;
1301
1302 sitter = NULL;
1303
1304 dbus_error_init (&error);
1305
1306 /*** Test launching exit failure binary */
1307
1308 argv[0] = TEST_EXIT_BINARY;
1309 if (_dbus_spawn_async_with_babysitter (&sitter, argv,
1310 NULL, NULL,
1311 &error))
1312 {
1313 _dbus_babysitter_block_for_child_exit (sitter);
1314 _dbus_babysitter_set_child_exit_error (sitter, &error);
1315 }
1316
1317 if (sitter)
1318 _dbus_babysitter_unref (sitter);
1319
1320 if (!dbus_error_is_set (&error))
1321 {
1322 _dbus_warn ("Did not get an error launching binary that exited with failure code\n");
1323 return FALSE;
1324 }
1325
1326 if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1327 dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_EXITED)))
1328 {
1329 _dbus_warn ("Not expecting error when launching exiting executable: %s: %s\n",
1330 error.name, error.message);
1331 dbus_error_free (&error);
1332 return FALSE;
1333 }
1334
1335 dbus_error_free (&error);
1336
1337 return TRUE;
1338 }
1339
1340 static dbus_bool_t
check_spawn_and_kill(void * data)1341 check_spawn_and_kill (void *data)
1342 {
1343 char *argv[4] = { NULL, NULL, NULL, NULL };
1344 DBusBabysitter *sitter;
1345 DBusError error;
1346
1347 sitter = NULL;
1348
1349 dbus_error_init (&error);
1350
1351 /*** Test launching sleeping binary then killing it */
1352
1353 argv[0] = TEST_SLEEP_FOREVER_BINARY;
1354 if (_dbus_spawn_async_with_babysitter (&sitter, argv,
1355 NULL, NULL,
1356 &error))
1357 {
1358 _dbus_babysitter_kill_child (sitter);
1359
1360 _dbus_babysitter_block_for_child_exit (sitter);
1361
1362 _dbus_babysitter_set_child_exit_error (sitter, &error);
1363 }
1364
1365 if (sitter)
1366 _dbus_babysitter_unref (sitter);
1367
1368 if (!dbus_error_is_set (&error))
1369 {
1370 _dbus_warn ("Did not get an error after killing spawned binary\n");
1371 return FALSE;
1372 }
1373
1374 if (!(dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY) ||
1375 dbus_error_has_name (&error, DBUS_ERROR_SPAWN_CHILD_SIGNALED)))
1376 {
1377 _dbus_warn ("Not expecting error when killing executable: %s: %s\n",
1378 error.name, error.message);
1379 dbus_error_free (&error);
1380 return FALSE;
1381 }
1382
1383 dbus_error_free (&error);
1384
1385 return TRUE;
1386 }
1387
1388 dbus_bool_t
_dbus_spawn_test(const char * test_data_dir)1389 _dbus_spawn_test (const char *test_data_dir)
1390 {
1391 if (!_dbus_test_oom_handling ("spawn_nonexistent",
1392 check_spawn_nonexistent,
1393 NULL))
1394 return FALSE;
1395
1396 if (!_dbus_test_oom_handling ("spawn_segfault",
1397 check_spawn_segfault,
1398 NULL))
1399 return FALSE;
1400
1401 if (!_dbus_test_oom_handling ("spawn_exit",
1402 check_spawn_exit,
1403 NULL))
1404 return FALSE;
1405
1406 if (!_dbus_test_oom_handling ("spawn_and_kill",
1407 check_spawn_and_kill,
1408 NULL))
1409 return FALSE;
1410
1411 return TRUE;
1412 }
1413 #endif
1414