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