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