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