Include sys/select.h (some platforms need it for select).
[platform/upstream/glib.git] / glib / 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 %s", __FUNCTION__);
1086             }
1087         }
1088       
1089
1090       if (!read_ints (child_err_report_pipe[0],
1091                       buf, 2, &n_ints,
1092                       error))
1093         goto cleanup_and_fail;
1094         
1095       if (n_ints >= 2)
1096         {
1097           /* Error from the child. */
1098
1099           switch (buf[0])
1100             {
1101             case CHILD_CHDIR_FAILED:
1102               g_set_error (error,
1103                            G_SPAWN_ERROR,
1104                            G_SPAWN_ERROR_CHDIR,
1105                            _("Failed to change to directory '%s' (%s)"),
1106                            working_directory,
1107                            g_strerror (buf[1]));
1108
1109               break;
1110               
1111             case CHILD_EXEC_FAILED:
1112               g_set_error (error,
1113                            G_SPAWN_ERROR,
1114                            exec_err_to_g_error (buf[1]),
1115                            _("Failed to execute child process (%s)"),
1116                            g_strerror (buf[1]));
1117
1118               break;
1119               
1120             case CHILD_DUP2_FAILED:
1121               g_set_error (error,
1122                            G_SPAWN_ERROR,
1123                            G_SPAWN_ERROR_FAILED,
1124                            _("Failed to redirect output or input of child process (%s)"),
1125                            g_strerror (buf[1]));
1126
1127               break;
1128
1129             case CHILD_FORK_FAILED:
1130               g_set_error (error,
1131                            G_SPAWN_ERROR,
1132                            G_SPAWN_ERROR_FORK,
1133                            _("Failed to fork child process (%s)"),
1134                            g_strerror (buf[1]));
1135               break;
1136               
1137             default:
1138               g_set_error (error,
1139                            G_SPAWN_ERROR,
1140                            G_SPAWN_ERROR_FAILED,
1141                            _("Unknown error executing child process"));
1142               break;
1143             }
1144
1145           goto cleanup_and_fail;
1146         }
1147
1148       /* Get child pid from intermediate child pipe. */
1149       if (intermediate_child)
1150         {
1151           n_ints = 0;
1152           
1153           if (!read_ints (child_pid_report_pipe[0],
1154                           buf, 1, &n_ints, error))
1155             goto cleanup_and_fail;
1156
1157           if (n_ints < 1)
1158             {
1159               g_set_error (error,
1160                            G_SPAWN_ERROR,
1161                            G_SPAWN_ERROR_FAILED,
1162                            _("Failed to read enough data from child pid pipe (%s)"),
1163                            g_strerror (errno));
1164               goto cleanup_and_fail;
1165             }
1166           else
1167             {
1168               /* we have the child pid */
1169               pid = buf[0];
1170             }
1171         }
1172       
1173       /* Success against all odds! return the information */
1174       
1175       if (child_pid)
1176         *child_pid = pid;
1177
1178       if (standard_input)
1179         *standard_input = stdin_pipe[1];
1180       if (standard_output)
1181         *standard_output = stdout_pipe[0];
1182       if (standard_error)
1183         *standard_error = stderr_pipe[0];
1184       
1185       return TRUE;
1186     }
1187
1188  cleanup_and_fail:
1189   close_and_invalidate (&child_err_report_pipe[0]);
1190   close_and_invalidate (&child_err_report_pipe[1]);
1191   close_and_invalidate (&child_pid_report_pipe[0]);
1192   close_and_invalidate (&child_pid_report_pipe[1]);
1193   close_and_invalidate (&stdin_pipe[0]);
1194   close_and_invalidate (&stdin_pipe[1]);
1195   close_and_invalidate (&stdout_pipe[0]);
1196   close_and_invalidate (&stdout_pipe[1]);
1197   close_and_invalidate (&stderr_pipe[0]);
1198   close_and_invalidate (&stderr_pipe[1]);
1199
1200   return FALSE;
1201 }
1202
1203 static gboolean
1204 make_pipe (gint     p[2],
1205            GError **error)
1206 {
1207   if (pipe (p) < 0)
1208     {
1209       g_set_error (error,
1210                    G_SPAWN_ERROR,
1211                    G_SPAWN_ERROR_FAILED,
1212                    _("Failed to create pipe for communicating with child process (%s)"),
1213                    g_strerror (errno));
1214       return FALSE;
1215     }
1216   else
1217     return TRUE;
1218 }
1219
1220 /* Based on execvp from GNU C Library */
1221
1222 static void
1223 script_execute (const gchar *file,
1224                 gchar      **argv,
1225                 gchar      **envp,
1226                 gboolean     search_path)
1227 {
1228   /* Count the arguments.  */
1229   int argc = 0;
1230   while (argv[argc])
1231     ++argc;
1232   
1233   /* Construct an argument list for the shell.  */
1234   {
1235     gchar **new_argv;
1236
1237     new_argv = g_new0 (gchar*, argc + 1);
1238     
1239     new_argv[0] = (char *) "/bin/sh";
1240     new_argv[1] = (char *) file;
1241     while (argc > 1)
1242       {
1243         new_argv[argc] = argv[argc - 1];
1244         --argc;
1245       }
1246
1247     /* Execute the shell. */
1248     if (envp)
1249       execve (new_argv[0], new_argv, envp);
1250     else
1251       execv (new_argv[0], new_argv);
1252     
1253     g_free (new_argv);
1254   }
1255 }
1256
1257 static gchar*
1258 my_strchrnul (const gchar *str, gchar c)
1259 {
1260   gchar *p = (gchar*) str;
1261   while (*p && (*p != c))
1262     ++p;
1263
1264   return p;
1265 }
1266
1267 static gint
1268 g_execute (const gchar *file,
1269            gchar      **argv,
1270            gchar      **envp,
1271            gboolean     search_path)
1272 {
1273   if (*file == '\0')
1274     {
1275       /* We check the simple case first. */
1276       errno = ENOENT;
1277       return -1;
1278     }
1279
1280   if (!search_path || strchr (file, '/') != NULL)
1281     {
1282       /* Don't search when it contains a slash. */
1283       if (envp)
1284         execve (file, argv, envp);
1285       else
1286         execv (file, argv);
1287       
1288       if (errno == ENOEXEC)
1289         script_execute (file, argv, envp, FALSE);
1290     }
1291   else
1292     {
1293       gboolean got_eacces = 0;
1294       char *path, *p, *name, *freeme;
1295       size_t len;
1296       size_t pathlen;
1297
1298       path = g_getenv ("PATH");
1299       if (path == NULL)
1300         {
1301           /* There is no `PATH' in the environment.  The default
1302            * search path in libc is the current directory followed by
1303            * the path `confstr' returns for `_CS_PATH'.
1304            */
1305
1306           /* In GLib we put . last, for security, and don't use the
1307            * unportable confstr(); UNIX98 does not actually specify
1308            * what to search if PATH is unset. POSIX may, dunno.
1309            */
1310           
1311           path = "/bin:/usr/bin:.";
1312         }
1313
1314       len = strlen (file) + 1;
1315       pathlen = strlen (path);
1316       freeme = name = g_malloc (pathlen + len + 1);
1317       
1318       /* Copy the file name at the top, including '\0'  */
1319       memcpy (name + pathlen + 1, file, len);
1320       name = name + pathlen;
1321       /* And add the slash before the filename  */
1322       *name = '/';
1323
1324       p = path;
1325       do
1326         {
1327           char *startp;
1328
1329           path = p;
1330           p = my_strchrnul (path, ':');
1331
1332           if (p == path)
1333             /* Two adjacent colons, or a colon at the beginning or the end
1334              * of `PATH' means to search the current directory.
1335              */
1336             startp = name + 1;
1337           else
1338             startp = memcpy (name - (p - path), path, p - path);
1339
1340           /* Try to execute this name.  If it works, execv will not return.  */
1341           if (envp)
1342             execve (startp, argv, envp);
1343           else
1344             execv (startp, argv);
1345           
1346           if (errno == ENOEXEC)
1347             script_execute (startp, argv, envp, search_path);
1348
1349           switch (errno)
1350             {
1351             case EACCES:
1352               /* Record the we got a `Permission denied' error.  If we end
1353                * up finding no executable we can use, we want to diagnose
1354                * that we did find one but were denied access.
1355                */
1356               got_eacces = TRUE;
1357
1358               /* FALL THRU */
1359               
1360             case ENOENT:
1361 #ifdef ESTALE
1362             case ESTALE:
1363 #endif
1364 #ifdef ENOTDIR
1365             case ENOTDIR:
1366 #endif
1367               /* Those errors indicate the file is missing or not executable
1368                * by us, in which case we want to just try the next path
1369                * directory.
1370                */
1371               break;
1372
1373             default:
1374               /* Some other error means we found an executable file, but
1375                * something went wrong executing it; return the error to our
1376                * caller.
1377                */
1378               g_free (freeme);
1379               return -1;
1380             }
1381         }
1382       while (*p++ != '\0');
1383
1384       /* We tried every element and none of them worked.  */
1385       if (got_eacces)
1386         /* At least one failure was due to permissions, so report that
1387          * error.
1388          */
1389         errno = EACCES;
1390
1391       g_free (freeme);
1392     }
1393
1394   /* Return the error from the last attempt (probably ENOENT).  */
1395   return -1;
1396 }