Unref callback->cb_data if it was still set when the source is freed.
[platform/upstream/glib.git] / gspawn.c
1 /* gspawn.c - Process launching
2  *
3  *  Copyright 2000 Red Hat, Inc.
4  *  g_execvpe implementation based on GNU libc execvp:
5  *   Copyright 1991, 92, 95, 96, 97, 98, 99 Free Software Foundation, Inc.
6  *
7  * GLib is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public License as
9  * published by the Free Software Foundation; either version 2 of the
10  * License, or (at your option) any later version.
11  *
12  * GLib is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with GLib; see the file COPYING.LIB.  If not, write
19  * to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 #include "glib.h"
24 #include <sys/time.h>
25 #include <sys/types.h>
26 #include <sys/wait.h>
27 #include <unistd.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <signal.h>
31 #include <string.h>
32
33 #ifdef HAVE_SYS_SELECT_H
34 #include <sys/select.h>
35 #endif /* HAVE_SYS_SELECT_H */
36
37 #ifdef _
38 #warning "FIXME remove gettext hack"
39 #endif
40
41 #define _(x) x
42
43 static gint g_execute (const gchar  *file,
44                        gchar **argv,
45                        gchar **envp,
46                        gboolean search_path);
47
48 static gboolean make_pipe            (gint                  p[2],
49                                       GError              **error);
50 static gboolean fork_exec_with_pipes (gboolean              intermediate_child,
51                                       const gchar          *working_directory,
52                                       gchar               **argv,
53                                       gchar               **envp,
54                                       gboolean              close_descriptors,
55                                       gboolean              search_path,
56                                       gboolean              stdout_to_null,
57                                       gboolean              stderr_to_null,
58                                       gboolean              child_inherits_stdin,
59                                       GSpawnChildSetupFunc  child_setup,
60                                       gpointer              user_data,
61                                       gint                 *child_pid,
62                                       gint                 *standard_input,
63                                       gint                 *standard_output,
64                                       gint                 *standard_error,
65                                       GError              **error);
66
67 GQuark
68 g_spawn_error_quark (void)
69 {
70   static GQuark quark = 0;
71   if (quark == 0)
72     quark = g_quark_from_static_string ("g-exec-error-quark");
73   return quark;
74 }
75
76 /**
77  * g_spawn_async:
78  * @working_directory: child's current working directory, or NULL to inherit parent's
79  * @argv: child's argument vector
80  * @envp: child's environment, or NULL to inherit parent's
81  * @flags: flags from #GSpawnFlags
82  * @child_setup: function to run in the child just before exec()
83  * @user_data: user data for @child_setup
84  * @child_pid: return location for child process ID, or NULL
85  * @error: return location for error
86  * 
87  * See g_spawn_async_with_pipes() for a full description; this function
88  * simply calls the g_spawn_async_with_pipes() without any pipes.
89  * 
90  * Return value: TRUE on success, FALSE if error is set
91  **/
92 gboolean
93 g_spawn_async (const gchar          *working_directory,
94                gchar               **argv,
95                gchar               **envp,
96                GSpawnFlags           flags,
97                GSpawnChildSetupFunc  child_setup,
98                gpointer              user_data,
99                gint                 *child_pid,
100                GError              **error)
101 {
102   g_return_val_if_fail (argv != NULL, FALSE);
103   
104   return g_spawn_async_with_pipes (working_directory,
105                                    argv, envp,
106                                    flags,
107                                    child_setup,
108                                    user_data,
109                                    child_pid,
110                                    NULL, NULL, NULL,
111                                    error);
112 }
113
114 /* Avoids a danger in threaded situations (calling close()
115  * on a file descriptor twice, and another thread has
116  * re-opened it since the first close)
117  */
118 static gint
119 close_and_invalidate (gint *fd)
120 {
121   gint ret;
122
123   ret = close (*fd);
124   *fd = -1;
125
126   return ret;
127 }
128
129 typedef enum
130 {
131   READ_FAILED = 0, /* FALSE */
132   READ_OK,
133   READ_EOF
134 } ReadResult;
135
136 static ReadResult
137 read_data (GString *str,
138            gint     fd,
139            GError **error)
140 {
141   gint bytes;
142   gchar buf[4096];
143
144  again:
145   
146   bytes = read (fd, &buf, 4096);
147
148   if (bytes == 0)
149     return READ_EOF;
150   else if (bytes > 0)
151     {
152       g_string_append_len (str, buf, bytes);
153       return READ_OK;
154     }
155   else if (bytes < 0 && errno == EINTR)
156     goto again;
157   else if (bytes < 0)
158     {
159       g_set_error (error,
160                    G_SPAWN_ERROR,
161                    G_SPAWN_ERROR_READ,
162                    _("Failed to read data from child process (%s)"),
163                    g_strerror (errno));
164       
165       return READ_FAILED;
166     }
167   else
168     return READ_OK;
169 }
170
171 /**
172  * g_spawn_sync:
173  * @working_directory: child's current working directory, or NULL to inherit parent's
174  * @argv: child's argument vector
175  * @envp: child's environment, or NULL to inherit parent's
176  * @flags: flags from #GSpawnFlags
177  * @child_setup: function to run in the child just before exec()
178  * @user_data: user data for @child_setup
179  * @standard_output: return location for child output 
180  * @standard_error: return location for child error messages
181  * @exit_status: child exit status, as returned by waitpid()
182  * @error: return location for error
183  *
184  * Executes a child synchronously (waits for the child to exit before returning).
185  * All output from the child is stored in @standard_output and @standard_error,
186  * if those parameters are non-NULL. If @exit_status is non-NULL, the exit status
187  * of the child is stored there as it would be by waitpid(); standard UNIX
188  * macros such as WIFEXITED() and WEXITSTATUS() must be used to evaluate the
189  * exit status. If an error occurs, no data is returned in @standard_output,
190  * @standard_error, or @exit_status.
191  * 
192  * This function calls g_spawn_async_with_pipes() internally; see that function
193  * for full details on the other parameters.
194  * 
195  * Return value: TRUE on success, FALSE if an error was set.
196  **/
197 gboolean
198 g_spawn_sync (const gchar          *working_directory,
199               gchar               **argv,
200               gchar               **envp,
201               GSpawnFlags           flags,
202               GSpawnChildSetupFunc  child_setup,
203               gpointer              user_data,
204               gchar               **standard_output,
205               gchar               **standard_error,
206               gint                 *exit_status,
207               GError              **error)     
208 {
209   gint outpipe = -1;
210   gint errpipe = -1;
211   gint pid;
212   fd_set fds;
213   gint ret;
214   GString *outstr = NULL;
215   GString *errstr = NULL;
216   gboolean failed;
217   gint status;
218   
219   g_return_val_if_fail (argv != NULL, FALSE);
220   g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
221   g_return_val_if_fail (standard_output == NULL ||
222                         !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
223   g_return_val_if_fail (standard_error == NULL ||
224                         !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
225   
226   /* Just to ensure segfaults if callers try to use
227    * these when an error is reported.
228    */
229   if (standard_output)
230     *standard_output = NULL;
231
232   if (standard_error)
233     *standard_error = NULL;
234   
235   if (!fork_exec_with_pipes (FALSE,
236                              working_directory,
237                              argv,
238                              envp,
239                              !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
240                              (flags & G_SPAWN_SEARCH_PATH) != 0,
241                              (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
242                              (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
243                              (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
244                              child_setup,
245                              user_data,
246                              &pid,
247                              NULL,
248                              standard_output ? &outpipe : NULL,
249                              standard_error ? &errpipe : NULL,
250                              error))
251     return FALSE;
252
253   /* Read data from child. */
254   
255   failed = FALSE;
256
257   if (outpipe >= 0)
258     {
259       outstr = g_string_new ("");
260     }
261       
262   if (errpipe >= 0)
263     {
264       errstr = g_string_new ("");
265     }
266
267   /* Read data until we get EOF on both pipes. */
268   while (!failed &&
269          (outpipe >= 0 ||
270           errpipe >= 0))
271     {
272       ret = 0;
273           
274       FD_ZERO (&fds);
275       if (outpipe >= 0)
276         FD_SET (outpipe, &fds);
277       if (errpipe >= 0)
278         FD_SET (errpipe, &fds);
279           
280       ret = select (MAX (outpipe, errpipe) + 1,
281                     &fds,
282                     NULL, NULL,
283                     NULL /* no timeout */);
284
285       if (ret < 0 && errno != EINTR)
286         {
287           failed = TRUE;
288
289           g_set_error (error,
290                        G_SPAWN_ERROR,
291                        G_SPAWN_ERROR_READ,
292                        _("Unexpected error in select() reading data from a child process (%s)"),
293                        g_strerror (errno));
294               
295           break;
296         }
297
298       if (outpipe >= 0 && FD_ISSET (outpipe, &fds))
299         {
300           switch (read_data (outstr, outpipe, error))
301             {
302             case READ_FAILED:
303               failed = TRUE;
304               break;
305             case READ_EOF:
306               close_and_invalidate (&outpipe);
307               outpipe = -1;
308               break;
309             default:
310               break;
311             }
312
313           if (failed)
314             break;
315         }
316
317       if (errpipe >= 0 && FD_ISSET (errpipe, &fds))
318         {
319           switch (read_data (errstr, errpipe, error))
320             {
321             case READ_FAILED:
322               failed = TRUE;
323               break;
324             case READ_EOF:
325               close_and_invalidate (&errpipe);
326               errpipe = -1;
327               break;
328             default:
329               break;
330             }
331
332           if (failed)
333             break;
334         }
335     }
336
337   /* These should only be open still if we had an error.  */
338   
339   if (outpipe >= 0)
340     close_and_invalidate (&outpipe);
341   if (errpipe >= 0)
342     close_and_invalidate (&errpipe);
343   
344   /* Wait for child to exit, even if we have
345    * an error pending.
346    */
347  again:
348       
349   ret = waitpid (pid, &status, 0);
350
351   if (ret < 0)
352     {
353       if (errno == EINTR)
354         goto again;
355       else if (errno == ECHILD)
356         {
357           if (exit_status)
358             {
359               g_warning ("In call to g_spawn_sync(), exit status of a child process was requested but SIGCHLD action was set to SIG_IGN and ECHILD was received by waitpid(), so exit status can't be returned. This is a bug in the program calling g_spawn_sync(); either don't request the exit status, or don't set the SIGCHLD action.");
360             }
361           else
362             {
363               /* We don't need the exit status. */
364             }
365         }
366       else
367         {
368           if (!failed) /* avoid error pileups */
369             {
370               failed = TRUE;
371                   
372               g_set_error (error,
373                            G_SPAWN_ERROR,
374                            G_SPAWN_ERROR_READ,
375                            _("Unexpected error in waitpid() (%s)"),
376                            g_strerror (errno));
377             }
378         }
379     }
380   
381   if (failed)
382     {
383       if (outstr)
384         g_string_free (outstr, TRUE);
385       if (errstr)
386         g_string_free (errstr, TRUE);
387
388       return FALSE;
389     }
390   else
391     {
392       if (exit_status)
393         *exit_status = status;
394       
395       if (standard_output)        
396         *standard_output = g_string_free (outstr, FALSE);
397
398       if (standard_error)
399         *standard_error = g_string_free (errstr, FALSE);
400
401       return TRUE;
402     }
403 }
404
405 /**
406  * g_spawn_async_with_pipes:
407  * @working_directory: child's current working directory, or NULL to inherit parent's
408  * @argv: child's argument vector
409  * @envp: child's environment, or NULL to inherit parent's
410  * @flags: flags from #GSpawnFlags
411  * @child_setup: function to run in the child just before exec()
412  * @user_data: user data for @child_setup
413  * @child_pid: return location for child process ID, or NULL
414  * @standard_input: return location for file descriptor to write to child's stdin, or NULL
415  * @standard_output: return location for file descriptor to read child's stdout, or NULL
416  * @standard_error: return location for file descriptor to read child's stderr, or NULL
417  * @error: return location for error
418  *
419  * Executes a child program asynchronously (your program will not
420  * block waiting for the child to exit). The child program is
421  * specified by the only argument that must be provided, @argv. @argv
422  * should be a NULL-terminated array of strings, to be passed as the
423  * argument vector for the child. The first string in @argv is of
424  * course the name of the program to execute. By default, the name of
425  * the program must be a full path; the PATH shell variable will only
426  * be searched if you pass the %G_SPAWN_SEARCH_PATH flag.
427  *
428  * @envp is a NULL-terminated array of strings, where each string
429  * has the form <literal>KEY=VALUE</literal>. This will become
430  * the child's environment. If @envp is NULL, the child inherits its
431  * parent's environment.
432  *
433  * @flags should be the bitwise OR of any flags you want to affect the
434  * function's behavior. The %G_SPAWN_DO_NOT_REAP_CHILD means that the
435  * child will not be automatically reaped; you must call waitpid() or
436  * handle SIGCHLD yourself, or the child will become a zombie.
437  * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
438  * descriptors will be inherited by the child; otherwise all
439  * descriptors except stdin/stdout/stderr will be closed before
440  * calling exec() in the child. %G_SPAWN_SEARCH_PATH means that
441  * <literal>argv[0]</literal> need not be an absolute path, it
442  * will be looked for in the user's PATH. %G_SPAWN_STDOUT_TO_DEV_NULL
443  * means that the child's standad output will be discarded, instead
444  * of going to the same location as the parent's standard output.
445  * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
446  * will be discarded. %G_SPAWN_CHILD_INHERITS_STDIN means that
447  * the child will inherit the parent's standard input (by default,
448  * the child's standard input is attached to /dev/null).
449  *
450  * @child_setup and @user_data are a function and user data to be
451  * called in the child after GLib has performed all the setup it plans
452  * to perform (including creating pipes, closing file descriptors,
453  * etc.) but before calling exec(). That is, @child_setup is called
454  * just before calling exec() in the child. Obviously actions taken in
455  * this function will only affect the child, not the parent. 
456  *
457  * If non-NULL, @child_pid will be filled with the child's process
458  * ID. You can use the process ID to send signals to the child, or
459  * to waitpid() if you specified the %G_SPAWN_DO_NOT_REAP_CHILD flag.
460  *
461  * If non-NULL, the @standard_input, @standard_output, @standard_error
462  * locations will be filled with file descriptors for writing to the child's
463  * standard input or reading from its standard output or standard error.
464  * The caller of g_spawn_async_with_pipes() must close these file descriptors
465  * when they are no longer in use. If these parameters are NULL, the
466  * corresponding pipe won't be created.
467  *
468  * @error can be NULL to ignore errors, or non-NULL to report errors.
469  * If an error is set, the function returns FALSE. Errors
470  * are reported even if they occur in the child (for example if the
471  * executable in <literal>argv[0]</literal> is not found). Typically
472  * the <literal>message</literal> field of returned errors should be displayed
473  * to users. Possible errors are those from the #G_SPAWN_ERROR domain.
474  *
475  * If an error occurs, @child_pid, @standard_input, @standard_output,
476  * and @standard_error will not be filled with valid values.
477  * 
478  * Return value: TRUE on success, FALSE if an error was set
479  **/
480 gboolean
481 g_spawn_async_with_pipes (const gchar          *working_directory,
482                           gchar               **argv,
483                           gchar               **envp,
484                           GSpawnFlags           flags,
485                           GSpawnChildSetupFunc  child_setup,
486                           gpointer              user_data,
487                           gint                 *child_pid,
488                           gint                 *standard_input,
489                           gint                 *standard_output,
490                           gint                 *standard_error,
491                           GError              **error)
492 {
493   g_return_val_if_fail (argv != NULL, FALSE);
494   g_return_val_if_fail (standard_output == NULL ||
495                         !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
496   g_return_val_if_fail (standard_error == NULL ||
497                         !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
498   /* can't inherit stdin if we have an input pipe. */
499   g_return_val_if_fail (standard_input == NULL ||
500                         !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
501   
502   return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
503                                working_directory,
504                                argv,
505                                envp,
506                                !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
507                                (flags & G_SPAWN_SEARCH_PATH) != 0,
508                                (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
509                                (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
510                                (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
511                                child_setup,
512                                user_data,
513                                child_pid,
514                                standard_input,
515                                standard_output,
516                                standard_error,
517                                error);
518 }
519
520 /**
521  * g_spawn_command_line_sync:
522  * @command_line: a command line 
523  * @standard_output: return location for child output
524  * @standard_error: return location for child errors
525  * @exit_status: return location for child exit status
526  * @error: return location for errors
527  *
528  * A simple version of g_spawn_sync() with little-used parameters
529  * removed, taking a command line instead of an argument vector.  See
530  * g_spawn_sync() for full details. @command_line will be parsed by
531  * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
532  * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
533  * implications, so consider using g_spawn_sync() directly if
534  * appropriate. Possible errors are those from g_spawn_sync() and those
535  * from g_shell_parse_argv().
536  * 
537  * Return value: TRUE on success, FALSE if an error was set
538  **/
539 gboolean
540 g_spawn_command_line_sync (const gchar  *command_line,
541                            gchar       **standard_output,
542                            gchar       **standard_error,
543                            gint         *exit_status,
544                            GError      **error)
545 {
546   gboolean retval;
547   gchar **argv = 0;
548
549   g_return_val_if_fail (command_line != NULL, FALSE);
550   
551   if (!g_shell_parse_argv (command_line,
552                            NULL, &argv,
553                            error))
554     return FALSE;
555   
556   retval = g_spawn_sync (NULL,
557                          argv,
558                          NULL,
559                          G_SPAWN_SEARCH_PATH,
560                          NULL,
561                          NULL,
562                          standard_output,
563                          standard_error,
564                          exit_status,
565                          error);
566   g_strfreev (argv);
567
568   return retval;
569 }
570
571 /**
572  * g_spawn_command_line_async:
573  * @command_line: a command line
574  * @error: return location for errors
575  * 
576  * A simple version of g_spawn_async() that parses a command line with
577  * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
578  * command line in the background. Unlike g_spawn_async(), the
579  * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
580  * that %G_SPAWN_SEARCH_PATH can have security implications, so
581  * consider using g_spawn_async() directly if appropriate. Possible
582  * errors are those from g_shell_parse_argv() and g_spawn_async().
583  * 
584  * Return value: TRUE on success, FALSE if error is set.
585  **/
586 gboolean
587 g_spawn_command_line_async (const gchar *command_line,
588                             GError     **error)
589 {
590   gboolean retval;
591   gchar **argv = 0;
592
593   g_return_val_if_fail (command_line != NULL, FALSE);
594
595   if (!g_shell_parse_argv (command_line,
596                            NULL, &argv,
597                            error))
598     return FALSE;
599   
600   retval = g_spawn_async (NULL,
601                           argv,
602                           NULL,
603                           G_SPAWN_SEARCH_PATH,
604                           NULL,
605                           NULL,
606                           NULL,
607                           error);
608   g_strfreev (argv);
609
610   return retval;
611 }
612
613 static gint
614 exec_err_to_g_error (gint en)
615 {
616   switch (en)
617     {
618 #ifdef EACCES
619     case EACCES:
620       return G_SPAWN_ERROR_ACCES;
621       break;
622 #endif
623
624 #ifdef EPERM
625     case EPERM:
626       return G_SPAWN_ERROR_PERM;
627       break;
628 #endif
629
630 #ifdef E2BIG
631     case E2BIG:
632       return G_SPAWN_ERROR_2BIG;
633       break;
634 #endif
635
636 #ifdef ENOEXEC
637     case ENOEXEC:
638       return G_SPAWN_ERROR_NOEXEC;
639       break;
640 #endif
641
642 #ifdef ENAMETOOLONG
643     case ENAMETOOLONG:
644       return G_SPAWN_ERROR_NAMETOOLONG;
645       break;
646 #endif
647
648 #ifdef ENOENT
649     case ENOENT:
650       return G_SPAWN_ERROR_NOENT;
651       break;
652 #endif
653
654 #ifdef ENOMEM
655     case ENOMEM:
656       return G_SPAWN_ERROR_NOMEM;
657       break;
658 #endif
659
660 #ifdef ENOTDIR
661     case ENOTDIR:
662       return G_SPAWN_ERROR_NOTDIR;
663       break;
664 #endif
665
666 #ifdef ELOOP
667     case ELOOP:
668       return G_SPAWN_ERROR_LOOP;
669       break;
670 #endif
671       
672 #ifdef ETXTBUSY
673     case ETXTBUSY:
674       return G_SPAWN_ERROR_TXTBUSY;
675       break;
676 #endif
677
678 #ifdef EIO
679     case EIO:
680       return G_SPAWN_ERROR_IO;
681       break;
682 #endif
683
684 #ifdef ENFILE
685     case ENFILE:
686       return G_SPAWN_ERROR_NFILE;
687       break;
688 #endif
689
690 #ifdef EMFILE
691     case EMFILE:
692       return G_SPAWN_ERROR_MFILE;
693       break;
694 #endif
695
696 #ifdef EINVAL
697     case EINVAL:
698       return G_SPAWN_ERROR_INVAL;
699       break;
700 #endif
701
702 #ifdef EISDIR
703     case EISDIR:
704       return G_SPAWN_ERROR_ISDIR;
705       break;
706 #endif
707
708 #ifdef ELIBBAD
709     case ELIBBAD:
710       return G_SPAWN_ERROR_LIBBAD;
711       break;
712 #endif
713       
714     default:
715       return G_SPAWN_ERROR_FAILED;
716       break;
717     }
718 }
719
720 static void
721 write_err_and_exit (gint fd, gint msg)
722 {
723   gint en = errno;
724   
725   write (fd, &msg, sizeof(msg));
726   write (fd, &en, sizeof(en));
727   
728   _exit (1);
729 }
730
731 static void
732 set_cloexec (gint fd)
733 {
734   fcntl (fd, F_SETFD, FD_CLOEXEC);
735 }
736
737 static gint
738 sane_dup2 (gint fd1, gint fd2)
739 {
740   gint ret;
741
742  retry:
743   ret = dup2 (fd1, fd2);
744   if (ret < 0 && errno == EINTR)
745     goto retry;
746
747   return ret;
748 }
749
750 enum
751 {
752   CHILD_CHDIR_FAILED,
753   CHILD_EXEC_FAILED,
754   CHILD_DUP2_FAILED,
755   CHILD_FORK_FAILED
756 };
757
758 static void
759 do_exec (gint                  child_err_report_fd,
760          gint                  stdin_fd,
761          gint                  stdout_fd,
762          gint                  stderr_fd,
763          const gchar          *working_directory,
764          gchar               **argv,
765          gchar               **envp,
766          gboolean              close_descriptors,
767          gboolean              search_path,
768          gboolean              stdout_to_null,
769          gboolean              stderr_to_null,
770          gboolean              child_inherits_stdin,
771          GSpawnChildSetupFunc  child_setup,
772          gpointer              user_data)
773 {
774   if (working_directory && chdir (working_directory) < 0)
775     write_err_and_exit (child_err_report_fd,
776                         CHILD_CHDIR_FAILED);
777
778   /* Close all file descriptors but stdin stdout and stderr as
779    * soon as we exec. Note that this includes
780    * child_err_report_fd, which keeps the parent from blocking
781    * forever on the other end of that pipe.
782    */
783   if (close_descriptors)
784     {
785       gint open_max;
786       gint i;
787       
788       open_max = sysconf (_SC_OPEN_MAX);
789       for (i = 3; i < open_max; i++)
790         set_cloexec (i);
791     }
792   else
793     {
794       /* We need to do child_err_report_fd anyway */
795       set_cloexec (child_err_report_fd);
796     }
797   
798   /* Redirect pipes as required */
799   
800   if (stdin_fd >= 0)
801     {
802       /* dup2 can't actually fail here I don't think */
803           
804       if (sane_dup2 (stdin_fd, 0) < 0)
805         write_err_and_exit (child_err_report_fd,
806                             CHILD_DUP2_FAILED);
807
808       /* ignore this if it doesn't work */
809       close_and_invalidate (&stdin_fd);
810     }
811   else if (!child_inherits_stdin)
812     {
813       /* Keep process from blocking on a read of stdin */
814       gint read_null = open ("/dev/null", O_RDONLY);
815       sane_dup2 (read_null, 0);
816       close_and_invalidate (&read_null);
817     }
818
819   if (stdout_fd >= 0)
820     {
821       /* dup2 can't actually fail here I don't think */
822           
823       if (sane_dup2 (stdout_fd, 1) < 0)
824         write_err_and_exit (child_err_report_fd,
825                             CHILD_DUP2_FAILED);
826
827       /* ignore this if it doesn't work */
828       close_and_invalidate (&stdout_fd);
829     }
830   else if (stdout_to_null)
831     {
832       gint write_null = open ("/dev/null", O_WRONLY);
833       sane_dup2 (write_null, 1);
834       close_and_invalidate (&write_null);
835     }
836
837   if (stderr_fd >= 0)
838     {
839       /* dup2 can't actually fail here I don't think */
840           
841       if (sane_dup2 (stderr_fd, 2) < 0)
842         write_err_and_exit (child_err_report_fd,
843                             CHILD_DUP2_FAILED);
844
845       /* ignore this if it doesn't work */
846       close_and_invalidate (&stderr_fd);
847     }
848   else if (stderr_to_null)
849     {
850       gint write_null = open ("/dev/null", O_WRONLY);
851       sane_dup2 (write_null, 2);
852       close_and_invalidate (&write_null);
853     }
854   
855   /* Call user function just before we exec */
856   if (child_setup)
857     {
858       (* child_setup) (user_data);
859     }
860
861   g_execute (argv[0], argv, envp, search_path);
862
863   /* Exec failed */
864   write_err_and_exit (child_err_report_fd,
865                       CHILD_EXEC_FAILED);
866 }
867
868 static gboolean
869 read_ints (int      fd,
870            gint*    buf,
871            gint     n_ints_in_buf,
872            gint    *n_ints_read,
873            GError **error)
874 {
875   gint bytes = 0;
876   
877   while (TRUE)
878     {
879       gint chunk;
880
881       if (bytes >= sizeof(gint)*2)
882         break; /* give up, who knows what happened, should not be
883                 * possible.
884                 */
885           
886     again:
887       chunk = read (fd,
888                     ((gchar*)buf) + bytes,
889                     sizeof(gint)*n_ints_in_buf - bytes);
890       if (chunk < 0 && errno == EINTR)
891         goto again;
892           
893       if (chunk < 0)
894         {
895           /* Some weird shit happened, bail out */
896               
897           g_set_error (error,
898                        G_SPAWN_ERROR,
899                        G_SPAWN_ERROR_FAILED,
900                        _("Failed to read from child pipe (%s)"),
901                        g_strerror (errno));
902
903           return FALSE;
904         }
905       else if (chunk == 0)
906         break; /* EOF */
907       else
908         {
909           g_assert (chunk > 0);
910               
911           bytes += chunk;
912         }
913     }
914
915   *n_ints_read = bytes/4;
916
917   return TRUE;
918 }
919
920 static gboolean
921 fork_exec_with_pipes (gboolean              intermediate_child,
922                       const gchar          *working_directory,
923                       gchar               **argv,
924                       gchar               **envp,
925                       gboolean              close_descriptors,
926                       gboolean              search_path,
927                       gboolean              stdout_to_null,
928                       gboolean              stderr_to_null,
929                       gboolean              child_inherits_stdin,
930                       GSpawnChildSetupFunc  child_setup,
931                       gpointer              user_data,
932                       gint                 *child_pid,
933                       gint                 *standard_input,
934                       gint                 *standard_output,
935                       gint                 *standard_error,
936                       GError              **error)     
937 {
938   gint pid;
939   gint stdin_pipe[2] = { -1, -1 };
940   gint stdout_pipe[2] = { -1, -1 };
941   gint stderr_pipe[2] = { -1, -1 };
942   gint child_err_report_pipe[2] = { -1, -1 };
943   gint child_pid_report_pipe[2] = { -1, -1 };
944   gint status;
945   
946   if (!make_pipe (child_err_report_pipe, error))
947     return FALSE;
948
949   if (intermediate_child && !make_pipe (child_pid_report_pipe, error))
950     goto cleanup_and_fail;
951   
952   if (standard_input && !make_pipe (stdin_pipe, error))
953     goto cleanup_and_fail;
954   
955   if (standard_output && !make_pipe (stdout_pipe, error))
956     goto cleanup_and_fail;
957
958   if (standard_error && !make_pipe (stderr_pipe, error))
959     goto cleanup_and_fail;
960
961   pid = fork ();
962
963   if (pid < 0)
964     {      
965       g_set_error (error,
966                    G_SPAWN_ERROR,
967                    G_SPAWN_ERROR_FORK,
968                    _("Failed to fork (%s)"),
969                    g_strerror (errno));
970
971       goto cleanup_and_fail;
972     }
973   else if (pid == 0)
974     {
975       /* Immediate child. This may or may not be the child that
976        * actually execs the new process.
977        */
978       
979       /* Be sure we crash if the parent exits
980        * and we write to the err_report_pipe
981        */
982       signal (SIGPIPE, SIG_DFL);
983
984       /* Close the parent's end of the pipes;
985        * not needed in the close_descriptors case,
986        * though
987        */
988       close_and_invalidate (&child_err_report_pipe[0]);
989       close_and_invalidate (&child_pid_report_pipe[0]);
990       close_and_invalidate (&stdin_pipe[1]);
991       close_and_invalidate (&stdout_pipe[0]);
992       close_and_invalidate (&stderr_pipe[0]);
993       
994       if (intermediate_child)
995         {
996           /* We need to fork an intermediate child that launches the
997            * final child. The purpose of the intermediate child
998            * is to exit, so we can waitpid() it immediately.
999            * Then the grandchild will not become a zombie.
1000            */
1001           gint grandchild_pid;
1002
1003           grandchild_pid = fork ();
1004
1005           if (grandchild_pid < 0)
1006             {
1007               /* report -1 as child PID */
1008               write (child_pid_report_pipe[1], &grandchild_pid,
1009                      sizeof(grandchild_pid));
1010               
1011               write_err_and_exit (child_err_report_pipe[1],
1012                                   CHILD_FORK_FAILED);              
1013             }
1014           else if (grandchild_pid == 0)
1015             {
1016               do_exec (child_err_report_pipe[1],
1017                        stdin_pipe[0],
1018                        stdout_pipe[1],
1019                        stderr_pipe[1],
1020                        working_directory,
1021                        argv,
1022                        envp,
1023                        close_descriptors,
1024                        search_path,
1025                        stdout_to_null,
1026                        stderr_to_null,
1027                        child_inherits_stdin,
1028                        child_setup,
1029                        user_data);
1030             }
1031           else
1032             {
1033               write (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1034               close_and_invalidate (&child_pid_report_pipe[1]);
1035               
1036               _exit (0);
1037             }
1038         }
1039       else
1040         {
1041           /* Just run the child.
1042            */
1043
1044           do_exec (child_err_report_pipe[1],
1045                    stdin_pipe[0],
1046                    stdout_pipe[1],
1047                    stderr_pipe[1],
1048                    working_directory,
1049                    argv,
1050                    envp,
1051                    close_descriptors,
1052                    search_path,
1053                    stdout_to_null,
1054                    stderr_to_null,
1055                    child_inherits_stdin,
1056                    child_setup,
1057                    user_data);
1058         }
1059     }
1060   else
1061     {
1062       /* Parent */
1063       
1064       gint buf[2];
1065       gint n_ints = 0;
1066
1067       /* Close the uncared-about ends of the pipes */
1068       close_and_invalidate (&child_err_report_pipe[1]);
1069       close_and_invalidate (&child_pid_report_pipe[1]);
1070       close_and_invalidate (&stdin_pipe[0]);
1071       close_and_invalidate (&stdout_pipe[1]);
1072       close_and_invalidate (&stderr_pipe[1]);
1073
1074       /* If we had an intermediate child, reap it */
1075       if (intermediate_child)
1076         {
1077         wait_again:
1078           if (waitpid (pid, &status, 0) < 0)
1079             {
1080               if (errno == EINTR)
1081                 goto wait_again;
1082               else if (errno == ECHILD)
1083                 ; /* do nothing, child already reaped */
1084               else
1085                 g_warning ("waitpid() should not fail in "
1086                            "'fork_exec_with_pipes'");
1087             }
1088         }
1089       
1090
1091       if (!read_ints (child_err_report_pipe[0],
1092                       buf, 2, &n_ints,
1093                       error))
1094         goto cleanup_and_fail;
1095         
1096       if (n_ints >= 2)
1097         {
1098           /* Error from the child. */
1099
1100           switch (buf[0])
1101             {
1102             case CHILD_CHDIR_FAILED:
1103               g_set_error (error,
1104                            G_SPAWN_ERROR,
1105                            G_SPAWN_ERROR_CHDIR,
1106                            _("Failed to change to directory '%s' (%s)"),
1107                            working_directory,
1108                            g_strerror (buf[1]));
1109
1110               break;
1111               
1112             case CHILD_EXEC_FAILED:
1113               g_set_error (error,
1114                            G_SPAWN_ERROR,
1115                            exec_err_to_g_error (buf[1]),
1116                            _("Failed to execute child process (%s)"),
1117                            g_strerror (buf[1]));
1118
1119               break;
1120               
1121             case CHILD_DUP2_FAILED:
1122               g_set_error (error,
1123                            G_SPAWN_ERROR,
1124                            G_SPAWN_ERROR_FAILED,
1125                            _("Failed to redirect output or input of child process (%s)"),
1126                            g_strerror (buf[1]));
1127
1128               break;
1129
1130             case CHILD_FORK_FAILED:
1131               g_set_error (error,
1132                            G_SPAWN_ERROR,
1133                            G_SPAWN_ERROR_FORK,
1134                            _("Failed to fork child process (%s)"),
1135                            g_strerror (buf[1]));
1136               break;
1137               
1138             default:
1139               g_set_error (error,
1140                            G_SPAWN_ERROR,
1141                            G_SPAWN_ERROR_FAILED,
1142                            _("Unknown error executing child process"));
1143               break;
1144             }
1145
1146           goto cleanup_and_fail;
1147         }
1148
1149       /* Get child pid from intermediate child pipe. */
1150       if (intermediate_child)
1151         {
1152           n_ints = 0;
1153           
1154           if (!read_ints (child_pid_report_pipe[0],
1155                           buf, 1, &n_ints, error))
1156             goto cleanup_and_fail;
1157
1158           if (n_ints < 1)
1159             {
1160               g_set_error (error,
1161                            G_SPAWN_ERROR,
1162                            G_SPAWN_ERROR_FAILED,
1163                            _("Failed to read enough data from child pid pipe (%s)"),
1164                            g_strerror (errno));
1165               goto cleanup_and_fail;
1166             }
1167           else
1168             {
1169               /* we have the child pid */
1170               pid = buf[0];
1171             }
1172         }
1173       
1174       /* Success against all odds! return the information */
1175       
1176       if (child_pid)
1177         *child_pid = pid;
1178
1179       if (standard_input)
1180         *standard_input = stdin_pipe[1];
1181       if (standard_output)
1182         *standard_output = stdout_pipe[0];
1183       if (standard_error)
1184         *standard_error = stderr_pipe[0];
1185       
1186       return TRUE;
1187     }
1188
1189  cleanup_and_fail:
1190   close_and_invalidate (&child_err_report_pipe[0]);
1191   close_and_invalidate (&child_err_report_pipe[1]);
1192   close_and_invalidate (&child_pid_report_pipe[0]);
1193   close_and_invalidate (&child_pid_report_pipe[1]);
1194   close_and_invalidate (&stdin_pipe[0]);
1195   close_and_invalidate (&stdin_pipe[1]);
1196   close_and_invalidate (&stdout_pipe[0]);
1197   close_and_invalidate (&stdout_pipe[1]);
1198   close_and_invalidate (&stderr_pipe[0]);
1199   close_and_invalidate (&stderr_pipe[1]);
1200
1201   return FALSE;
1202 }
1203
1204 static gboolean
1205 make_pipe (gint     p[2],
1206            GError **error)
1207 {
1208   if (pipe (p) < 0)
1209     {
1210       g_set_error (error,
1211                    G_SPAWN_ERROR,
1212                    G_SPAWN_ERROR_FAILED,
1213                    _("Failed to create pipe for communicating with child process (%s)"),
1214                    g_strerror (errno));
1215       return FALSE;
1216     }
1217   else
1218     return TRUE;
1219 }
1220
1221 /* Based on execvp from GNU C Library */
1222
1223 static void
1224 script_execute (const gchar *file,
1225                 gchar      **argv,
1226                 gchar      **envp,
1227                 gboolean     search_path)
1228 {
1229   /* Count the arguments.  */
1230   int argc = 0;
1231   while (argv[argc])
1232     ++argc;
1233   
1234   /* Construct an argument list for the shell.  */
1235   {
1236     gchar **new_argv;
1237
1238     new_argv = g_new0 (gchar*, argc + 1);
1239     
1240     new_argv[0] = (char *) "/bin/sh";
1241     new_argv[1] = (char *) file;
1242     while (argc > 1)
1243       {
1244         new_argv[argc] = argv[argc - 1];
1245         --argc;
1246       }
1247
1248     /* Execute the shell. */
1249     if (envp)
1250       execve (new_argv[0], new_argv, envp);
1251     else
1252       execv (new_argv[0], new_argv);
1253     
1254     g_free (new_argv);
1255   }
1256 }
1257
1258 static gchar*
1259 my_strchrnul (const gchar *str, gchar c)
1260 {
1261   gchar *p = (gchar*) str;
1262   while (*p && (*p != c))
1263     ++p;
1264
1265   return p;
1266 }
1267
1268 static gint
1269 g_execute (const gchar *file,
1270            gchar      **argv,
1271            gchar      **envp,
1272            gboolean     search_path)
1273 {
1274   if (*file == '\0')
1275     {
1276       /* We check the simple case first. */
1277       errno = ENOENT;
1278       return -1;
1279     }
1280
1281   if (!search_path || strchr (file, '/') != NULL)
1282     {
1283       /* Don't search when it contains a slash. */
1284       if (envp)
1285         execve (file, argv, envp);
1286       else
1287         execv (file, argv);
1288       
1289       if (errno == ENOEXEC)
1290         script_execute (file, argv, envp, FALSE);
1291     }
1292   else
1293     {
1294       gboolean got_eacces = 0;
1295       char *path, *p, *name, *freeme;
1296       size_t len;
1297       size_t pathlen;
1298
1299       path = g_getenv ("PATH");
1300       if (path == NULL)
1301         {
1302           /* There is no `PATH' in the environment.  The default
1303            * search path in libc is the current directory followed by
1304            * the path `confstr' returns for `_CS_PATH'.
1305            */
1306
1307           /* In GLib we put . last, for security, and don't use the
1308            * unportable confstr(); UNIX98 does not actually specify
1309            * what to search if PATH is unset. POSIX may, dunno.
1310            */
1311           
1312           path = "/bin:/usr/bin:.";
1313         }
1314
1315       len = strlen (file) + 1;
1316       pathlen = strlen (path);
1317       freeme = name = g_malloc (pathlen + len + 1);
1318       
1319       /* Copy the file name at the top, including '\0'  */
1320       memcpy (name + pathlen + 1, file, len);
1321       name = name + pathlen;
1322       /* And add the slash before the filename  */
1323       *name = '/';
1324
1325       p = path;
1326       do
1327         {
1328           char *startp;
1329
1330           path = p;
1331           p = my_strchrnul (path, ':');
1332
1333           if (p == path)
1334             /* Two adjacent colons, or a colon at the beginning or the end
1335              * of `PATH' means to search the current directory.
1336              */
1337             startp = name + 1;
1338           else
1339             startp = memcpy (name - (p - path), path, p - path);
1340
1341           /* Try to execute this name.  If it works, execv will not return.  */
1342           if (envp)
1343             execve (startp, argv, envp);
1344           else
1345             execv (startp, argv);
1346           
1347           if (errno == ENOEXEC)
1348             script_execute (startp, argv, envp, search_path);
1349
1350           switch (errno)
1351             {
1352             case EACCES:
1353               /* Record the we got a `Permission denied' error.  If we end
1354                * up finding no executable we can use, we want to diagnose
1355                * that we did find one but were denied access.
1356                */
1357               got_eacces = TRUE;
1358
1359               /* FALL THRU */
1360               
1361             case ENOENT:
1362 #ifdef ESTALE
1363             case ESTALE:
1364 #endif
1365 #ifdef ENOTDIR
1366             case ENOTDIR:
1367 #endif
1368               /* Those errors indicate the file is missing or not executable
1369                * by us, in which case we want to just try the next path
1370                * directory.
1371                */
1372               break;
1373
1374             default:
1375               /* Some other error means we found an executable file, but
1376                * something went wrong executing it; return the error to our
1377                * caller.
1378                */
1379               g_free (freeme);
1380               return -1;
1381             }
1382         }
1383       while (*p++ != '\0');
1384
1385       /* We tried every element and none of them worked.  */
1386       if (got_eacces)
1387         /* At least one failure was due to permissions, so report that
1388          * error.
1389          */
1390         errno = EACCES;
1391
1392       g_free (freeme);
1393     }
1394
1395   /* Return the error from the last attempt (probably ENOENT).  */
1396   return -1;
1397 }