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