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