Do handle G_SPAWN_DO_NOT_REAP_CHILD after all, similarily as on Unix. If
[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. On Unix, the %G_SPAWN_DO_NOT_REAP_CHILD means
441  * that the 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. On Windows, the flag means that a
444  * handle to the child will be returned @child_pid. You must call
445  * <function>CloseHandle()</function> on it eventually (or exit the
446  * process), or the child processs will continue to take up some table
447  * space even after its death. Quite similar to zombies on Unix,
448  * actually.
449  *
450  * %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that the parent's open file
451  * descriptors will be inherited by the child; otherwise all
452  * descriptors except stdin/stdout/stderr will be closed before
453  * calling <function>exec()</function> in the child. %G_SPAWN_SEARCH_PATH 
454  * means that <literal>argv[0]</literal> need not be an absolute path, it
455  * will be looked for in the user's <envar>PATH</envar>. 
456  * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output will 
457  * be discarded, instead of going to the same location as the parent's 
458  * standard output. If you use this flag, @standard_output must be %NULL.
459  * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
460  * will be discarded, instead of going to the same location as the parent's
461  * standard error. If you use this flag, @standard_error must be %NULL.
462  * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
463  * standard input (by default, the child's standard input is attached to
464  * /dev/null). If you use this flag, @standard_input must be %NULL.
465  * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
466  * the file to execute, while the remaining elements are the
467  * actual argument vector to pass to the file. Normally
468  * g_spawn_async_with_pipes() uses @argv[0] as the file to execute, and
469  * passes all of @argv to the child.
470  *
471  * @child_setup and @user_data are a function and user data. On POSIX
472  * platforms, the function is called in the child after GLib has
473  * performed all the setup it plans to perform (including creating
474  * pipes, closing file descriptors, etc.) but before calling
475  * <function>exec()</function>. That is, @child_setup is called just
476  * before calling <function>exec()</function> in the child. Obviously
477  * actions taken in this function will only affect the child, not the
478  * parent. On Windows, there is no separate
479  * <function>fork()</function> and <function>exec()</function>
480  * functionality. Child processes are created and run right away with
481  * one API call, <function>CreateProcess()</function>. @child_setup is
482  * called in the parent process just before creating the child
483  * process. You should carefully consider what you do in @child_setup
484  * if you intend your software to be portable to Windows.
485  *
486  * If non-%NULL, @child_pid will on Unix be filled with the child's
487  * process ID. You can use the process ID to send signals to the
488  * child, or to <function>waitpid()</function> if you specified the
489  * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
490  * filled with a handle to the child process only if you specified the
491  * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
492  * process using the Win32 API, for example wait for its termination
493  * with the <function>WaitFor*()</function> functions, or examine its
494  * exit code with <function>GetExitCodeProcess()</function>. You
495  * should close the handle with <function>CloseHandle()</function>
496  * when you no longer need it.
497  *
498  * If non-%NULL, the @standard_input, @standard_output, @standard_error
499  * locations will be filled with file descriptors for writing to the child's
500  * standard input or reading from its standard output or standard error.
501  * The caller of g_spawn_async_with_pipes() must close these file descriptors
502  * when they are no longer in use. If these parameters are %NULL, the corresponding
503  * pipe won't be created.
504  *
505  * If @standard_input is NULL, the child's standard input is attached to /dev/null
506  * unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
507  *
508  * If @standard_error is NULL, the child's standard error goes to the same location
509  * as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL is set.
510  *
511  * If @standard_output is NULL, the child's standard output goes to the same location
512  * as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL is set.
513  *
514  * @error can be %NULL to ignore errors, or non-%NULL to report errors.
515  * If an error is set, the function returns %FALSE. Errors
516  * are reported even if they occur in the child (for example if the
517  * executable in <literal>argv[0]</literal> is not found). Typically
518  * the <literal>message</literal> field of returned errors should be displayed
519  * to users. Possible errors are those from the #G_SPAWN_ERROR domain.
520  *
521  * If an error occurs, @child_pid, @standard_input, @standard_output,
522  * and @standard_error will not be filled with valid values.
523  * 
524  * Return value: %TRUE on success, %FALSE if an error was set
525  **/
526 gboolean
527 g_spawn_async_with_pipes (const gchar          *working_directory,
528                           gchar               **argv,
529                           gchar               **envp,
530                           GSpawnFlags           flags,
531                           GSpawnChildSetupFunc  child_setup,
532                           gpointer              user_data,
533                           gint                 *child_pid,
534                           gint                 *standard_input,
535                           gint                 *standard_output,
536                           gint                 *standard_error,
537                           GError              **error)
538 {
539   g_return_val_if_fail (argv != NULL, FALSE);
540   g_return_val_if_fail (standard_output == NULL ||
541                         !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
542   g_return_val_if_fail (standard_error == NULL ||
543                         !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
544   /* can't inherit stdin if we have an input pipe. */
545   g_return_val_if_fail (standard_input == NULL ||
546                         !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
547   
548   return fork_exec_with_pipes (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
549                                working_directory,
550                                argv,
551                                envp,
552                                !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
553                                (flags & G_SPAWN_SEARCH_PATH) != 0,
554                                (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
555                                (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
556                                (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
557                                (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
558                                child_setup,
559                                user_data,
560                                child_pid,
561                                standard_input,
562                                standard_output,
563                                standard_error,
564                                error);
565 }
566
567 /**
568  * g_spawn_command_line_sync:
569  * @command_line: a command line 
570  * @standard_output: return location for child output
571  * @standard_error: return location for child errors
572  * @exit_status: return location for child exit status
573  * @error: return location for errors
574  *
575  * A simple version of g_spawn_sync() with little-used parameters
576  * removed, taking a command line instead of an argument vector.  See
577  * g_spawn_sync() for full details. @command_line will be parsed by
578  * g_shell_parse_argv(). Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag
579  * is enabled. Note that %G_SPAWN_SEARCH_PATH can have security
580  * implications, so consider using g_spawn_sync() directly if
581  * appropriate. Possible errors are those from g_spawn_sync() and those
582  * from g_shell_parse_argv().
583  * 
584  * On Windows, please note the implications of g_shell_parse_argv()
585  * parsing @command_line. Space is a separator, and backslashes are
586  * special. Thus you cannot simply pass a @command_line consisting of
587  * a canonical Windows path, like "c:\\program files\\app\\app.exe",
588  * as the backslashes will be eaten, and the space will act as a
589  * separator. You need to enclose the path with single quotes, like
590  * "'c:\\program files\\app\\app.exe'".
591  *
592  * Return value: %TRUE on success, %FALSE if an error was set
593  **/
594 gboolean
595 g_spawn_command_line_sync (const gchar  *command_line,
596                            gchar       **standard_output,
597                            gchar       **standard_error,
598                            gint         *exit_status,
599                            GError      **error)
600 {
601   gboolean retval;
602   gchar **argv = 0;
603
604   g_return_val_if_fail (command_line != NULL, FALSE);
605   
606   if (!g_shell_parse_argv (command_line,
607                            NULL, &argv,
608                            error))
609     return FALSE;
610   
611   retval = g_spawn_sync (NULL,
612                          argv,
613                          NULL,
614                          G_SPAWN_SEARCH_PATH,
615                          NULL,
616                          NULL,
617                          standard_output,
618                          standard_error,
619                          exit_status,
620                          error);
621   g_strfreev (argv);
622
623   return retval;
624 }
625
626 /**
627  * g_spawn_command_line_async:
628  * @command_line: a command line
629  * @error: return location for errors
630  * 
631  * A simple version of g_spawn_async() that parses a command line with
632  * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
633  * command line in the background. Unlike g_spawn_async(), the
634  * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
635  * that %G_SPAWN_SEARCH_PATH can have security implications, so
636  * consider using g_spawn_async() directly if appropriate. Possible
637  * errors are those from g_shell_parse_argv() and g_spawn_async().
638  * 
639  * The same concerns on Windows apply as for g_spawn_command_line_sync().
640  *
641  * Return value: %TRUE on success, %FALSE if error is set.
642  **/
643 gboolean
644 g_spawn_command_line_async (const gchar *command_line,
645                             GError     **error)
646 {
647   gboolean retval;
648   gchar **argv = 0;
649
650   g_return_val_if_fail (command_line != NULL, FALSE);
651
652   if (!g_shell_parse_argv (command_line,
653                            NULL, &argv,
654                            error))
655     return FALSE;
656   
657   retval = g_spawn_async (NULL,
658                           argv,
659                           NULL,
660                           G_SPAWN_SEARCH_PATH,
661                           NULL,
662                           NULL,
663                           NULL,
664                           error);
665   g_strfreev (argv);
666
667   return retval;
668 }
669
670 static gint
671 exec_err_to_g_error (gint en)
672 {
673   switch (en)
674     {
675 #ifdef EACCES
676     case EACCES:
677       return G_SPAWN_ERROR_ACCES;
678       break;
679 #endif
680
681 #ifdef EPERM
682     case EPERM:
683       return G_SPAWN_ERROR_PERM;
684       break;
685 #endif
686
687 #ifdef E2BIG
688     case E2BIG:
689       return G_SPAWN_ERROR_2BIG;
690       break;
691 #endif
692
693 #ifdef ENOEXEC
694     case ENOEXEC:
695       return G_SPAWN_ERROR_NOEXEC;
696       break;
697 #endif
698
699 #ifdef ENAMETOOLONG
700     case ENAMETOOLONG:
701       return G_SPAWN_ERROR_NAMETOOLONG;
702       break;
703 #endif
704
705 #ifdef ENOENT
706     case ENOENT:
707       return G_SPAWN_ERROR_NOENT;
708       break;
709 #endif
710
711 #ifdef ENOMEM
712     case ENOMEM:
713       return G_SPAWN_ERROR_NOMEM;
714       break;
715 #endif
716
717 #ifdef ENOTDIR
718     case ENOTDIR:
719       return G_SPAWN_ERROR_NOTDIR;
720       break;
721 #endif
722
723 #ifdef ELOOP
724     case ELOOP:
725       return G_SPAWN_ERROR_LOOP;
726       break;
727 #endif
728       
729 #ifdef ETXTBUSY
730     case ETXTBUSY:
731       return G_SPAWN_ERROR_TXTBUSY;
732       break;
733 #endif
734
735 #ifdef EIO
736     case EIO:
737       return G_SPAWN_ERROR_IO;
738       break;
739 #endif
740
741 #ifdef ENFILE
742     case ENFILE:
743       return G_SPAWN_ERROR_NFILE;
744       break;
745 #endif
746
747 #ifdef EMFILE
748     case EMFILE:
749       return G_SPAWN_ERROR_MFILE;
750       break;
751 #endif
752
753 #ifdef EINVAL
754     case EINVAL:
755       return G_SPAWN_ERROR_INVAL;
756       break;
757 #endif
758
759 #ifdef EISDIR
760     case EISDIR:
761       return G_SPAWN_ERROR_ISDIR;
762       break;
763 #endif
764
765 #ifdef ELIBBAD
766     case ELIBBAD:
767       return G_SPAWN_ERROR_LIBBAD;
768       break;
769 #endif
770       
771     default:
772       return G_SPAWN_ERROR_FAILED;
773       break;
774     }
775 }
776
777 static void
778 write_err_and_exit (gint fd, gint msg)
779 {
780   gint en = errno;
781   
782   write (fd, &msg, sizeof(msg));
783   write (fd, &en, sizeof(en));
784   
785   _exit (1);
786 }
787
788 static void
789 set_cloexec (gint fd)
790 {
791   fcntl (fd, F_SETFD, FD_CLOEXEC);
792 }
793
794 static gint
795 sane_dup2 (gint fd1, gint fd2)
796 {
797   gint ret;
798
799  retry:
800   ret = dup2 (fd1, fd2);
801   if (ret < 0 && errno == EINTR)
802     goto retry;
803
804   return ret;
805 }
806
807 enum
808 {
809   CHILD_CHDIR_FAILED,
810   CHILD_EXEC_FAILED,
811   CHILD_DUP2_FAILED,
812   CHILD_FORK_FAILED
813 };
814
815 static void
816 do_exec (gint                  child_err_report_fd,
817          gint                  stdin_fd,
818          gint                  stdout_fd,
819          gint                  stderr_fd,
820          const gchar          *working_directory,
821          gchar               **argv,
822          gchar               **envp,
823          gboolean              close_descriptors,
824          gboolean              search_path,
825          gboolean              stdout_to_null,
826          gboolean              stderr_to_null,
827          gboolean              child_inherits_stdin,
828          gboolean              file_and_argv_zero,
829          GSpawnChildSetupFunc  child_setup,
830          gpointer              user_data)
831 {
832   if (working_directory && chdir (working_directory) < 0)
833     write_err_and_exit (child_err_report_fd,
834                         CHILD_CHDIR_FAILED);
835
836   /* Close all file descriptors but stdin stdout and stderr as
837    * soon as we exec. Note that this includes
838    * child_err_report_fd, which keeps the parent from blocking
839    * forever on the other end of that pipe.
840    */
841   if (close_descriptors)
842     {
843       gint open_max;
844       gint i;
845       
846       open_max = sysconf (_SC_OPEN_MAX);
847       for (i = 3; i < open_max; i++)
848         set_cloexec (i);
849     }
850   else
851     {
852       /* We need to do child_err_report_fd anyway */
853       set_cloexec (child_err_report_fd);
854     }
855   
856   /* Redirect pipes as required */
857   
858   if (stdin_fd >= 0)
859     {
860       /* dup2 can't actually fail here I don't think */
861           
862       if (sane_dup2 (stdin_fd, 0) < 0)
863         write_err_and_exit (child_err_report_fd,
864                             CHILD_DUP2_FAILED);
865
866       /* ignore this if it doesn't work */
867       close_and_invalidate (&stdin_fd);
868     }
869   else if (!child_inherits_stdin)
870     {
871       /* Keep process from blocking on a read of stdin */
872       gint read_null = open ("/dev/null", O_RDONLY);
873       sane_dup2 (read_null, 0);
874       close_and_invalidate (&read_null);
875     }
876
877   if (stdout_fd >= 0)
878     {
879       /* dup2 can't actually fail here I don't think */
880           
881       if (sane_dup2 (stdout_fd, 1) < 0)
882         write_err_and_exit (child_err_report_fd,
883                             CHILD_DUP2_FAILED);
884
885       /* ignore this if it doesn't work */
886       close_and_invalidate (&stdout_fd);
887     }
888   else if (stdout_to_null)
889     {
890       gint write_null = open ("/dev/null", O_WRONLY);
891       sane_dup2 (write_null, 1);
892       close_and_invalidate (&write_null);
893     }
894
895   if (stderr_fd >= 0)
896     {
897       /* dup2 can't actually fail here I don't think */
898           
899       if (sane_dup2 (stderr_fd, 2) < 0)
900         write_err_and_exit (child_err_report_fd,
901                             CHILD_DUP2_FAILED);
902
903       /* ignore this if it doesn't work */
904       close_and_invalidate (&stderr_fd);
905     }
906   else if (stderr_to_null)
907     {
908       gint write_null = open ("/dev/null", O_WRONLY);
909       sane_dup2 (write_null, 2);
910       close_and_invalidate (&write_null);
911     }
912   
913   /* Call user function just before we exec */
914   if (child_setup)
915     {
916       (* child_setup) (user_data);
917     }
918
919   g_execute (argv[0],
920              file_and_argv_zero ? argv + 1 : argv,
921              envp, search_path);
922
923   /* Exec failed */
924   write_err_and_exit (child_err_report_fd,
925                       CHILD_EXEC_FAILED);
926 }
927
928 static gboolean
929 read_ints (int      fd,
930            gint*    buf,
931            gint     n_ints_in_buf,    
932            gint    *n_ints_read,      
933            GError **error)
934 {
935   gsize bytes = 0;    
936   
937   while (TRUE)
938     {
939       gssize chunk;    
940
941       if (bytes >= sizeof(gint)*2)
942         break; /* give up, who knows what happened, should not be
943                 * possible.
944                 */
945           
946     again:
947       chunk = read (fd,
948                     ((gchar*)buf) + bytes,
949                     sizeof(gint) * n_ints_in_buf - bytes);
950       if (chunk < 0 && errno == EINTR)
951         goto again;
952           
953       if (chunk < 0)
954         {
955           /* Some weird shit happened, bail out */
956               
957           g_set_error (error,
958                        G_SPAWN_ERROR,
959                        G_SPAWN_ERROR_FAILED,
960                        _("Failed to read from child pipe (%s)"),
961                        g_strerror (errno));
962
963           return FALSE;
964         }
965       else if (chunk == 0)
966         break; /* EOF */
967       else /* chunk > 0 */
968         bytes += chunk;
969     }
970
971   *n_ints_read = (gint)(bytes / sizeof(gint));
972
973   return TRUE;
974 }
975
976 static gboolean
977 fork_exec_with_pipes (gboolean              intermediate_child,
978                       const gchar          *working_directory,
979                       gchar               **argv,
980                       gchar               **envp,
981                       gboolean              close_descriptors,
982                       gboolean              search_path,
983                       gboolean              stdout_to_null,
984                       gboolean              stderr_to_null,
985                       gboolean              child_inherits_stdin,
986                       gboolean              file_and_argv_zero,
987                       GSpawnChildSetupFunc  child_setup,
988                       gpointer              user_data,
989                       gint                 *child_pid,
990                       gint                 *standard_input,
991                       gint                 *standard_output,
992                       gint                 *standard_error,
993                       GError              **error)     
994 {
995   gint pid = -1;
996   gint stdin_pipe[2] = { -1, -1 };
997   gint stdout_pipe[2] = { -1, -1 };
998   gint stderr_pipe[2] = { -1, -1 };
999   gint child_err_report_pipe[2] = { -1, -1 };
1000   gint child_pid_report_pipe[2] = { -1, -1 };
1001   gint status;
1002   
1003   if (!make_pipe (child_err_report_pipe, error))
1004     return FALSE;
1005
1006   if (intermediate_child && !make_pipe (child_pid_report_pipe, error))
1007     goto cleanup_and_fail;
1008   
1009   if (standard_input && !make_pipe (stdin_pipe, error))
1010     goto cleanup_and_fail;
1011   
1012   if (standard_output && !make_pipe (stdout_pipe, error))
1013     goto cleanup_and_fail;
1014
1015   if (standard_error && !make_pipe (stderr_pipe, error))
1016     goto cleanup_and_fail;
1017
1018   pid = fork ();
1019
1020   if (pid < 0)
1021     {      
1022       g_set_error (error,
1023                    G_SPAWN_ERROR,
1024                    G_SPAWN_ERROR_FORK,
1025                    _("Failed to fork (%s)"),
1026                    g_strerror (errno));
1027
1028       goto cleanup_and_fail;
1029     }
1030   else if (pid == 0)
1031     {
1032       /* Immediate child. This may or may not be the child that
1033        * actually execs the new process.
1034        */
1035       
1036       /* Be sure we crash if the parent exits
1037        * and we write to the err_report_pipe
1038        */
1039       signal (SIGPIPE, SIG_DFL);
1040
1041       /* Close the parent's end of the pipes;
1042        * not needed in the close_descriptors case,
1043        * though
1044        */
1045       close_and_invalidate (&child_err_report_pipe[0]);
1046       close_and_invalidate (&child_pid_report_pipe[0]);
1047       close_and_invalidate (&stdin_pipe[1]);
1048       close_and_invalidate (&stdout_pipe[0]);
1049       close_and_invalidate (&stderr_pipe[0]);
1050       
1051       if (intermediate_child)
1052         {
1053           /* We need to fork an intermediate child that launches the
1054            * final child. The purpose of the intermediate child
1055            * is to exit, so we can waitpid() it immediately.
1056            * Then the grandchild will not become a zombie.
1057            */
1058           gint grandchild_pid;
1059
1060           grandchild_pid = fork ();
1061
1062           if (grandchild_pid < 0)
1063             {
1064               /* report -1 as child PID */
1065               write (child_pid_report_pipe[1], &grandchild_pid,
1066                      sizeof(grandchild_pid));
1067               
1068               write_err_and_exit (child_err_report_pipe[1],
1069                                   CHILD_FORK_FAILED);              
1070             }
1071           else if (grandchild_pid == 0)
1072             {
1073               do_exec (child_err_report_pipe[1],
1074                        stdin_pipe[0],
1075                        stdout_pipe[1],
1076                        stderr_pipe[1],
1077                        working_directory,
1078                        argv,
1079                        envp,
1080                        close_descriptors,
1081                        search_path,
1082                        stdout_to_null,
1083                        stderr_to_null,
1084                        child_inherits_stdin,
1085                        file_and_argv_zero,
1086                        child_setup,
1087                        user_data);
1088             }
1089           else
1090             {
1091               write (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1092               close_and_invalidate (&child_pid_report_pipe[1]);
1093               
1094               _exit (0);
1095             }
1096         }
1097       else
1098         {
1099           /* Just run the child.
1100            */
1101
1102           do_exec (child_err_report_pipe[1],
1103                    stdin_pipe[0],
1104                    stdout_pipe[1],
1105                    stderr_pipe[1],
1106                    working_directory,
1107                    argv,
1108                    envp,
1109                    close_descriptors,
1110                    search_path,
1111                    stdout_to_null,
1112                    stderr_to_null,
1113                    child_inherits_stdin,
1114                    file_and_argv_zero,
1115                    child_setup,
1116                    user_data);
1117         }
1118     }
1119   else
1120     {
1121       /* Parent */
1122       
1123       gint buf[2];
1124       gint n_ints = 0;    
1125
1126       /* Close the uncared-about ends of the pipes */
1127       close_and_invalidate (&child_err_report_pipe[1]);
1128       close_and_invalidate (&child_pid_report_pipe[1]);
1129       close_and_invalidate (&stdin_pipe[0]);
1130       close_and_invalidate (&stdout_pipe[1]);
1131       close_and_invalidate (&stderr_pipe[1]);
1132
1133       /* If we had an intermediate child, reap it */
1134       if (intermediate_child)
1135         {
1136         wait_again:
1137           if (waitpid (pid, &status, 0) < 0)
1138             {
1139               if (errno == EINTR)
1140                 goto wait_again;
1141               else if (errno == ECHILD)
1142                 ; /* do nothing, child already reaped */
1143               else
1144                 g_warning ("waitpid() should not fail in "
1145                            "'fork_exec_with_pipes'");
1146             }
1147         }
1148       
1149
1150       if (!read_ints (child_err_report_pipe[0],
1151                       buf, 2, &n_ints,
1152                       error))
1153         goto cleanup_and_fail;
1154         
1155       if (n_ints >= 2)
1156         {
1157           /* Error from the child. */
1158
1159           switch (buf[0])
1160             {
1161             case CHILD_CHDIR_FAILED:
1162               g_set_error (error,
1163                            G_SPAWN_ERROR,
1164                            G_SPAWN_ERROR_CHDIR,
1165                            _("Failed to change to directory '%s' (%s)"),
1166                            working_directory,
1167                            g_strerror (buf[1]));
1168
1169               break;
1170               
1171             case CHILD_EXEC_FAILED:
1172               g_set_error (error,
1173                            G_SPAWN_ERROR,
1174                            exec_err_to_g_error (buf[1]),
1175                            _("Failed to execute child process \"%s\" (%s)"),
1176                            argv[0],
1177                            g_strerror (buf[1]));
1178
1179               break;
1180               
1181             case CHILD_DUP2_FAILED:
1182               g_set_error (error,
1183                            G_SPAWN_ERROR,
1184                            G_SPAWN_ERROR_FAILED,
1185                            _("Failed to redirect output or input of child process (%s)"),
1186                            g_strerror (buf[1]));
1187
1188               break;
1189
1190             case CHILD_FORK_FAILED:
1191               g_set_error (error,
1192                            G_SPAWN_ERROR,
1193                            G_SPAWN_ERROR_FORK,
1194                            _("Failed to fork child process (%s)"),
1195                            g_strerror (buf[1]));
1196               break;
1197               
1198             default:
1199               g_set_error (error,
1200                            G_SPAWN_ERROR,
1201                            G_SPAWN_ERROR_FAILED,
1202                            _("Unknown error executing child process \"%s\""),
1203                            argv[0]);
1204               break;
1205             }
1206
1207           goto cleanup_and_fail;
1208         }
1209
1210       /* Get child pid from intermediate child pipe. */
1211       if (intermediate_child)
1212         {
1213           n_ints = 0;
1214           
1215           if (!read_ints (child_pid_report_pipe[0],
1216                           buf, 1, &n_ints, error))
1217             goto cleanup_and_fail;
1218
1219           if (n_ints < 1)
1220             {
1221               g_set_error (error,
1222                            G_SPAWN_ERROR,
1223                            G_SPAWN_ERROR_FAILED,
1224                            _("Failed to read enough data from child pid pipe (%s)"),
1225                            g_strerror (errno));
1226               goto cleanup_and_fail;
1227             }
1228           else
1229             {
1230               /* we have the child pid */
1231               pid = buf[0];
1232             }
1233         }
1234       
1235       /* Success against all odds! return the information */
1236       close_and_invalidate (&child_err_report_pipe[0]);
1237       close_and_invalidate (&child_pid_report_pipe[0]);
1238  
1239       if (child_pid)
1240         *child_pid = pid;
1241
1242       if (standard_input)
1243         *standard_input = stdin_pipe[1];
1244       if (standard_output)
1245         *standard_output = stdout_pipe[0];
1246       if (standard_error)
1247         *standard_error = stderr_pipe[0];
1248       
1249       return TRUE;
1250     }
1251
1252  cleanup_and_fail:
1253
1254   /* There was an error from the Child, reap the child to avoid it being
1255      a zombie.
1256    */
1257
1258   if (pid > 0)
1259   {
1260     wait_failed:
1261      if (waitpid (pid, NULL, 0) < 0)
1262        {
1263           if (errno == EINTR)
1264             goto wait_failed;
1265           else if (errno == ECHILD)
1266             ; /* do nothing, child already reaped */
1267           else
1268             g_warning ("waitpid() should not fail in "
1269                        "'fork_exec_with_pipes'");
1270        }
1271    }
1272
1273   close_and_invalidate (&child_err_report_pipe[0]);
1274   close_and_invalidate (&child_err_report_pipe[1]);
1275   close_and_invalidate (&child_pid_report_pipe[0]);
1276   close_and_invalidate (&child_pid_report_pipe[1]);
1277   close_and_invalidate (&stdin_pipe[0]);
1278   close_and_invalidate (&stdin_pipe[1]);
1279   close_and_invalidate (&stdout_pipe[0]);
1280   close_and_invalidate (&stdout_pipe[1]);
1281   close_and_invalidate (&stderr_pipe[0]);
1282   close_and_invalidate (&stderr_pipe[1]);
1283
1284   return FALSE;
1285 }
1286
1287 static gboolean
1288 make_pipe (gint     p[2],
1289            GError **error)
1290 {
1291   if (pipe (p) < 0)
1292     {
1293       g_set_error (error,
1294                    G_SPAWN_ERROR,
1295                    G_SPAWN_ERROR_FAILED,
1296                    _("Failed to create pipe for communicating with child process (%s)"),
1297                    g_strerror (errno));
1298       return FALSE;
1299     }
1300   else
1301     return TRUE;
1302 }
1303
1304 /* Based on execvp from GNU C Library */
1305
1306 static void
1307 script_execute (const gchar *file,
1308                 gchar      **argv,
1309                 gchar      **envp,
1310                 gboolean     search_path)
1311 {
1312   /* Count the arguments.  */
1313   int argc = 0;
1314   while (argv[argc])
1315     ++argc;
1316   
1317   /* Construct an argument list for the shell.  */
1318   {
1319     gchar **new_argv;
1320
1321     new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1322     
1323     new_argv[0] = (char *) "/bin/sh";
1324     new_argv[1] = (char *) file;
1325     while (argc > 0)
1326       {
1327         new_argv[argc + 1] = argv[argc];
1328         --argc;
1329       }
1330
1331     /* Execute the shell. */
1332     if (envp)
1333       execve (new_argv[0], new_argv, envp);
1334     else
1335       execv (new_argv[0], new_argv);
1336     
1337     g_free (new_argv);
1338   }
1339 }
1340
1341 static gchar*
1342 my_strchrnul (const gchar *str, gchar c)
1343 {
1344   gchar *p = (gchar*) str;
1345   while (*p && (*p != c))
1346     ++p;
1347
1348   return p;
1349 }
1350
1351 static gint
1352 g_execute (const gchar *file,
1353            gchar      **argv,
1354            gchar      **envp,
1355            gboolean     search_path)
1356 {
1357   if (*file == '\0')
1358     {
1359       /* We check the simple case first. */
1360       errno = ENOENT;
1361       return -1;
1362     }
1363
1364   if (!search_path || strchr (file, '/') != NULL)
1365     {
1366       /* Don't search when it contains a slash. */
1367       if (envp)
1368         execve (file, argv, envp);
1369       else
1370         execv (file, argv);
1371       
1372       if (errno == ENOEXEC)
1373         script_execute (file, argv, envp, FALSE);
1374     }
1375   else
1376     {
1377       gboolean got_eacces = 0;
1378       const gchar *path, *p;
1379       gchar *name, *freeme;
1380       size_t len;
1381       size_t pathlen;
1382
1383       path = g_getenv ("PATH");
1384       if (path == NULL)
1385         {
1386           /* There is no `PATH' in the environment.  The default
1387            * search path in libc is the current directory followed by
1388            * the path `confstr' returns for `_CS_PATH'.
1389            */
1390
1391           /* In GLib we put . last, for security, and don't use the
1392            * unportable confstr(); UNIX98 does not actually specify
1393            * what to search if PATH is unset. POSIX may, dunno.
1394            */
1395           
1396           path = "/bin:/usr/bin:.";
1397         }
1398
1399       len = strlen (file) + 1;
1400       pathlen = strlen (path);
1401       freeme = name = g_malloc (pathlen + len + 1);
1402       
1403       /* Copy the file name at the top, including '\0'  */
1404       memcpy (name + pathlen + 1, file, len);
1405       name = name + pathlen;
1406       /* And add the slash before the filename  */
1407       *name = '/';
1408
1409       p = path;
1410       do
1411         {
1412           char *startp;
1413
1414           path = p;
1415           p = my_strchrnul (path, ':');
1416
1417           if (p == path)
1418             /* Two adjacent colons, or a colon at the beginning or the end
1419              * of `PATH' means to search the current directory.
1420              */
1421             startp = name + 1;
1422           else
1423             startp = memcpy (name - (p - path), path, p - path);
1424
1425           /* Try to execute this name.  If it works, execv will not return.  */
1426           if (envp)
1427             execve (startp, argv, envp);
1428           else
1429             execv (startp, argv);
1430           
1431           if (errno == ENOEXEC)
1432             script_execute (startp, argv, envp, search_path);
1433
1434           switch (errno)
1435             {
1436             case EACCES:
1437               /* Record the we got a `Permission denied' error.  If we end
1438                * up finding no executable we can use, we want to diagnose
1439                * that we did find one but were denied access.
1440                */
1441               got_eacces = TRUE;
1442
1443               /* FALL THRU */
1444               
1445             case ENOENT:
1446 #ifdef ESTALE
1447             case ESTALE:
1448 #endif
1449 #ifdef ENOTDIR
1450             case ENOTDIR:
1451 #endif
1452               /* Those errors indicate the file is missing or not executable
1453                * by us, in which case we want to just try the next path
1454                * directory.
1455                */
1456               break;
1457
1458             default:
1459               /* Some other error means we found an executable file, but
1460                * something went wrong executing it; return the error to our
1461                * caller.
1462                */
1463               g_free (freeme);
1464               return -1;
1465             }
1466         }
1467       while (*p++ != '\0');
1468
1469       /* We tried every element and none of them worked.  */
1470       if (got_eacces)
1471         /* At least one failure was due to permissions, so report that
1472          * error.
1473          */
1474         errno = EACCES;
1475
1476       g_free (freeme);
1477     }
1478
1479   /* Return the error from the last attempt (probably ENOENT).  */
1480   return -1;
1481 }