glib/gconvert.c glib/gspawn-win32.c some minor documentation fixes.
[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   gssize 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   gsize bytes = 0;    
883   
884   while (TRUE)
885     {
886       gssize 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 /* chunk > 0 */
915         bytes += chunk;
916     }
917
918   *n_ints_read = (gint)(bytes / sizeof(gint));
919
920   return TRUE;
921 }
922
923 static gboolean
924 fork_exec_with_pipes (gboolean              intermediate_child,
925                       const gchar          *working_directory,
926                       gchar               **argv,
927                       gchar               **envp,
928                       gboolean              close_descriptors,
929                       gboolean              search_path,
930                       gboolean              stdout_to_null,
931                       gboolean              stderr_to_null,
932                       gboolean              child_inherits_stdin,
933                       gboolean              file_and_argv_zero,
934                       GSpawnChildSetupFunc  child_setup,
935                       gpointer              user_data,
936                       gint                 *child_pid,
937                       gint                 *standard_input,
938                       gint                 *standard_output,
939                       gint                 *standard_error,
940                       GError              **error)     
941 {
942   gint pid;
943   gint stdin_pipe[2] = { -1, -1 };
944   gint stdout_pipe[2] = { -1, -1 };
945   gint stderr_pipe[2] = { -1, -1 };
946   gint child_err_report_pipe[2] = { -1, -1 };
947   gint child_pid_report_pipe[2] = { -1, -1 };
948   gint status;
949   
950   if (!make_pipe (child_err_report_pipe, error))
951     return FALSE;
952
953   if (intermediate_child && !make_pipe (child_pid_report_pipe, error))
954     goto cleanup_and_fail;
955   
956   if (standard_input && !make_pipe (stdin_pipe, error))
957     goto cleanup_and_fail;
958   
959   if (standard_output && !make_pipe (stdout_pipe, error))
960     goto cleanup_and_fail;
961
962   if (standard_error && !make_pipe (stderr_pipe, error))
963     goto cleanup_and_fail;
964
965   pid = fork ();
966
967   if (pid < 0)
968     {      
969       g_set_error (error,
970                    G_SPAWN_ERROR,
971                    G_SPAWN_ERROR_FORK,
972                    _("Failed to fork (%s)"),
973                    g_strerror (errno));
974
975       goto cleanup_and_fail;
976     }
977   else if (pid == 0)
978     {
979       /* Immediate child. This may or may not be the child that
980        * actually execs the new process.
981        */
982       
983       /* Be sure we crash if the parent exits
984        * and we write to the err_report_pipe
985        */
986       signal (SIGPIPE, SIG_DFL);
987
988       /* Close the parent's end of the pipes;
989        * not needed in the close_descriptors case,
990        * though
991        */
992       close_and_invalidate (&child_err_report_pipe[0]);
993       close_and_invalidate (&child_pid_report_pipe[0]);
994       close_and_invalidate (&stdin_pipe[1]);
995       close_and_invalidate (&stdout_pipe[0]);
996       close_and_invalidate (&stderr_pipe[0]);
997       
998       if (intermediate_child)
999         {
1000           /* We need to fork an intermediate child that launches the
1001            * final child. The purpose of the intermediate child
1002            * is to exit, so we can waitpid() it immediately.
1003            * Then the grandchild will not become a zombie.
1004            */
1005           gint grandchild_pid;
1006
1007           grandchild_pid = fork ();
1008
1009           if (grandchild_pid < 0)
1010             {
1011               /* report -1 as child PID */
1012               write (child_pid_report_pipe[1], &grandchild_pid,
1013                      sizeof(grandchild_pid));
1014               
1015               write_err_and_exit (child_err_report_pipe[1],
1016                                   CHILD_FORK_FAILED);              
1017             }
1018           else if (grandchild_pid == 0)
1019             {
1020               do_exec (child_err_report_pipe[1],
1021                        stdin_pipe[0],
1022                        stdout_pipe[1],
1023                        stderr_pipe[1],
1024                        working_directory,
1025                        argv,
1026                        envp,
1027                        close_descriptors,
1028                        search_path,
1029                        stdout_to_null,
1030                        stderr_to_null,
1031                        child_inherits_stdin,
1032                        file_and_argv_zero,
1033                        child_setup,
1034                        user_data);
1035             }
1036           else
1037             {
1038               write (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1039               close_and_invalidate (&child_pid_report_pipe[1]);
1040               
1041               _exit (0);
1042             }
1043         }
1044       else
1045         {
1046           /* Just run the child.
1047            */
1048
1049           do_exec (child_err_report_pipe[1],
1050                    stdin_pipe[0],
1051                    stdout_pipe[1],
1052                    stderr_pipe[1],
1053                    working_directory,
1054                    argv,
1055                    envp,
1056                    close_descriptors,
1057                    search_path,
1058                    stdout_to_null,
1059                    stderr_to_null,
1060                    child_inherits_stdin,
1061                    file_and_argv_zero,
1062                    child_setup,
1063                    user_data);
1064         }
1065     }
1066   else
1067     {
1068       /* Parent */
1069       
1070       gint buf[2];
1071       gint n_ints = 0;    
1072
1073       /* Close the uncared-about ends of the pipes */
1074       close_and_invalidate (&child_err_report_pipe[1]);
1075       close_and_invalidate (&child_pid_report_pipe[1]);
1076       close_and_invalidate (&stdin_pipe[0]);
1077       close_and_invalidate (&stdout_pipe[1]);
1078       close_and_invalidate (&stderr_pipe[1]);
1079
1080       /* If we had an intermediate child, reap it */
1081       if (intermediate_child)
1082         {
1083         wait_again:
1084           if (waitpid (pid, &status, 0) < 0)
1085             {
1086               if (errno == EINTR)
1087                 goto wait_again;
1088               else if (errno == ECHILD)
1089                 ; /* do nothing, child already reaped */
1090               else
1091                 g_warning ("waitpid() should not fail in "
1092                            "'fork_exec_with_pipes'");
1093             }
1094         }
1095       
1096
1097       if (!read_ints (child_err_report_pipe[0],
1098                       buf, 2, &n_ints,
1099                       error))
1100         goto cleanup_and_fail;
1101         
1102       if (n_ints >= 2)
1103         {
1104           /* Error from the child. */
1105
1106           switch (buf[0])
1107             {
1108             case CHILD_CHDIR_FAILED:
1109               g_set_error (error,
1110                            G_SPAWN_ERROR,
1111                            G_SPAWN_ERROR_CHDIR,
1112                            _("Failed to change to directory '%s' (%s)"),
1113                            working_directory,
1114                            g_strerror (buf[1]));
1115
1116               break;
1117               
1118             case CHILD_EXEC_FAILED:
1119               g_set_error (error,
1120                            G_SPAWN_ERROR,
1121                            exec_err_to_g_error (buf[1]),
1122                            _("Failed to execute child process (%s)"),
1123                            g_strerror (buf[1]));
1124
1125               break;
1126               
1127             case CHILD_DUP2_FAILED:
1128               g_set_error (error,
1129                            G_SPAWN_ERROR,
1130                            G_SPAWN_ERROR_FAILED,
1131                            _("Failed to redirect output or input of child process (%s)"),
1132                            g_strerror (buf[1]));
1133
1134               break;
1135
1136             case CHILD_FORK_FAILED:
1137               g_set_error (error,
1138                            G_SPAWN_ERROR,
1139                            G_SPAWN_ERROR_FORK,
1140                            _("Failed to fork child process (%s)"),
1141                            g_strerror (buf[1]));
1142               break;
1143               
1144             default:
1145               g_set_error (error,
1146                            G_SPAWN_ERROR,
1147                            G_SPAWN_ERROR_FAILED,
1148                            _("Unknown error executing child process"));
1149               break;
1150             }
1151
1152           goto cleanup_and_fail;
1153         }
1154
1155       /* Get child pid from intermediate child pipe. */
1156       if (intermediate_child)
1157         {
1158           n_ints = 0;
1159           
1160           if (!read_ints (child_pid_report_pipe[0],
1161                           buf, 1, &n_ints, error))
1162             goto cleanup_and_fail;
1163
1164           if (n_ints < 1)
1165             {
1166               g_set_error (error,
1167                            G_SPAWN_ERROR,
1168                            G_SPAWN_ERROR_FAILED,
1169                            _("Failed to read enough data from child pid pipe (%s)"),
1170                            g_strerror (errno));
1171               goto cleanup_and_fail;
1172             }
1173           else
1174             {
1175               /* we have the child pid */
1176               pid = buf[0];
1177             }
1178         }
1179       
1180       /* Success against all odds! return the information */
1181       
1182       if (child_pid)
1183         *child_pid = pid;
1184
1185       if (standard_input)
1186         *standard_input = stdin_pipe[1];
1187       if (standard_output)
1188         *standard_output = stdout_pipe[0];
1189       if (standard_error)
1190         *standard_error = stderr_pipe[0];
1191       
1192       return TRUE;
1193     }
1194
1195  cleanup_and_fail:
1196   close_and_invalidate (&child_err_report_pipe[0]);
1197   close_and_invalidate (&child_err_report_pipe[1]);
1198   close_and_invalidate (&child_pid_report_pipe[0]);
1199   close_and_invalidate (&child_pid_report_pipe[1]);
1200   close_and_invalidate (&stdin_pipe[0]);
1201   close_and_invalidate (&stdin_pipe[1]);
1202   close_and_invalidate (&stdout_pipe[0]);
1203   close_and_invalidate (&stdout_pipe[1]);
1204   close_and_invalidate (&stderr_pipe[0]);
1205   close_and_invalidate (&stderr_pipe[1]);
1206
1207   return FALSE;
1208 }
1209
1210 static gboolean
1211 make_pipe (gint     p[2],
1212            GError **error)
1213 {
1214   if (pipe (p) < 0)
1215     {
1216       g_set_error (error,
1217                    G_SPAWN_ERROR,
1218                    G_SPAWN_ERROR_FAILED,
1219                    _("Failed to create pipe for communicating with child process (%s)"),
1220                    g_strerror (errno));
1221       return FALSE;
1222     }
1223   else
1224     return TRUE;
1225 }
1226
1227 /* Based on execvp from GNU C Library */
1228
1229 static void
1230 script_execute (const gchar *file,
1231                 gchar      **argv,
1232                 gchar      **envp,
1233                 gboolean     search_path)
1234 {
1235   /* Count the arguments.  */
1236   int argc = 0;
1237   while (argv[argc])
1238     ++argc;
1239   
1240   /* Construct an argument list for the shell.  */
1241   {
1242     gchar **new_argv;
1243
1244     new_argv = g_new0 (gchar*, argc + 1);
1245     
1246     new_argv[0] = (char *) "/bin/sh";
1247     new_argv[1] = (char *) file;
1248     while (argc > 1)
1249       {
1250         new_argv[argc] = argv[argc - 1];
1251         --argc;
1252       }
1253
1254     /* Execute the shell. */
1255     if (envp)
1256       execve (new_argv[0], new_argv, envp);
1257     else
1258       execv (new_argv[0], new_argv);
1259     
1260     g_free (new_argv);
1261   }
1262 }
1263
1264 static gchar*
1265 my_strchrnul (const gchar *str, gchar c)
1266 {
1267   gchar *p = (gchar*) str;
1268   while (*p && (*p != c))
1269     ++p;
1270
1271   return p;
1272 }
1273
1274 static gint
1275 g_execute (const gchar *file,
1276            gchar      **argv,
1277            gchar      **envp,
1278            gboolean     search_path)
1279 {
1280   if (*file == '\0')
1281     {
1282       /* We check the simple case first. */
1283       errno = ENOENT;
1284       return -1;
1285     }
1286
1287   if (!search_path || strchr (file, '/') != NULL)
1288     {
1289       /* Don't search when it contains a slash. */
1290       if (envp)
1291         execve (file, argv, envp);
1292       else
1293         execv (file, argv);
1294       
1295       if (errno == ENOEXEC)
1296         script_execute (file, argv, envp, FALSE);
1297     }
1298   else
1299     {
1300       gboolean got_eacces = 0;
1301       const gchar *path, *p;
1302       gchar *name, *freeme;
1303       size_t len;
1304       size_t pathlen;
1305
1306       path = g_getenv ("PATH");
1307       if (path == NULL)
1308         {
1309           /* There is no `PATH' in the environment.  The default
1310            * search path in libc is the current directory followed by
1311            * the path `confstr' returns for `_CS_PATH'.
1312            */
1313
1314           /* In GLib we put . last, for security, and don't use the
1315            * unportable confstr(); UNIX98 does not actually specify
1316            * what to search if PATH is unset. POSIX may, dunno.
1317            */
1318           
1319           path = "/bin:/usr/bin:.";
1320         }
1321
1322       len = strlen (file) + 1;
1323       pathlen = strlen (path);
1324       freeme = name = g_malloc (pathlen + len + 1);
1325       
1326       /* Copy the file name at the top, including '\0'  */
1327       memcpy (name + pathlen + 1, file, len);
1328       name = name + pathlen;
1329       /* And add the slash before the filename  */
1330       *name = '/';
1331
1332       p = path;
1333       do
1334         {
1335           char *startp;
1336
1337           path = p;
1338           p = my_strchrnul (path, ':');
1339
1340           if (p == path)
1341             /* Two adjacent colons, or a colon at the beginning or the end
1342              * of `PATH' means to search the current directory.
1343              */
1344             startp = name + 1;
1345           else
1346             startp = memcpy (name - (p - path), path, p - path);
1347
1348           /* Try to execute this name.  If it works, execv will not return.  */
1349           if (envp)
1350             execve (startp, argv, envp);
1351           else
1352             execv (startp, argv);
1353           
1354           if (errno == ENOEXEC)
1355             script_execute (startp, argv, envp, search_path);
1356
1357           switch (errno)
1358             {
1359             case EACCES:
1360               /* Record the we got a `Permission denied' error.  If we end
1361                * up finding no executable we can use, we want to diagnose
1362                * that we did find one but were denied access.
1363                */
1364               got_eacces = TRUE;
1365
1366               /* FALL THRU */
1367               
1368             case ENOENT:
1369 #ifdef ESTALE
1370             case ESTALE:
1371 #endif
1372 #ifdef ENOTDIR
1373             case ENOTDIR:
1374 #endif
1375               /* Those errors indicate the file is missing or not executable
1376                * by us, in which case we want to just try the next path
1377                * directory.
1378                */
1379               break;
1380
1381             default:
1382               /* Some other error means we found an executable file, but
1383                * something went wrong executing it; return the error to our
1384                * caller.
1385                */
1386               g_free (freeme);
1387               return -1;
1388             }
1389         }
1390       while (*p++ != '\0');
1391
1392       /* We tried every element and none of them worked.  */
1393       if (got_eacces)
1394         /* At least one failure was due to permissions, so report that
1395          * error.
1396          */
1397         errno = EACCES;
1398
1399       g_free (freeme);
1400     }
1401
1402   /* Return the error from the last attempt (probably ENOENT).  */
1403   return -1;
1404 }