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