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