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