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