1.3.14
[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  * Return value: %TRUE on success, %FALSE if an error was set
549  **/
550 gboolean
551 g_spawn_command_line_sync (const gchar  *command_line,
552                            gchar       **standard_output,
553                            gchar       **standard_error,
554                            gint         *exit_status,
555                            GError      **error)
556 {
557   gboolean retval;
558   gchar **argv = 0;
559
560   g_return_val_if_fail (command_line != NULL, FALSE);
561   
562   if (!g_shell_parse_argv (command_line,
563                            NULL, &argv,
564                            error))
565     return FALSE;
566   
567   retval = g_spawn_sync (NULL,
568                          argv,
569                          NULL,
570                          G_SPAWN_SEARCH_PATH,
571                          NULL,
572                          NULL,
573                          standard_output,
574                          standard_error,
575                          exit_status,
576                          error);
577   g_strfreev (argv);
578
579   return retval;
580 }
581
582 /**
583  * g_spawn_command_line_async:
584  * @command_line: a command line
585  * @error: return location for errors
586  * 
587  * A simple version of g_spawn_async() that parses a command line with
588  * g_shell_parse_argv() and passes it to g_spawn_async(). Runs a
589  * command line in the background. Unlike g_spawn_async(), the
590  * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
591  * that %G_SPAWN_SEARCH_PATH can have security implications, so
592  * consider using g_spawn_async() directly if appropriate. Possible
593  * errors are those from g_shell_parse_argv() and g_spawn_async().
594  * 
595  * Return value: %TRUE on success, %FALSE if error is set.
596  **/
597 gboolean
598 g_spawn_command_line_async (const gchar *command_line,
599                             GError     **error)
600 {
601   gboolean retval;
602   gchar **argv = 0;
603
604   g_return_val_if_fail (command_line != NULL, FALSE);
605
606   if (!g_shell_parse_argv (command_line,
607                            NULL, &argv,
608                            error))
609     return FALSE;
610   
611   retval = g_spawn_async (NULL,
612                           argv,
613                           NULL,
614                           G_SPAWN_SEARCH_PATH,
615                           NULL,
616                           NULL,
617                           NULL,
618                           error);
619   g_strfreev (argv);
620
621   return retval;
622 }
623
624 static gint
625 exec_err_to_g_error (gint en)
626 {
627   switch (en)
628     {
629 #ifdef EACCES
630     case EACCES:
631       return G_SPAWN_ERROR_ACCES;
632       break;
633 #endif
634
635 #ifdef EPERM
636     case EPERM:
637       return G_SPAWN_ERROR_PERM;
638       break;
639 #endif
640
641 #ifdef E2BIG
642     case E2BIG:
643       return G_SPAWN_ERROR_2BIG;
644       break;
645 #endif
646
647 #ifdef ENOEXEC
648     case ENOEXEC:
649       return G_SPAWN_ERROR_NOEXEC;
650       break;
651 #endif
652
653 #ifdef ENAMETOOLONG
654     case ENAMETOOLONG:
655       return G_SPAWN_ERROR_NAMETOOLONG;
656       break;
657 #endif
658
659 #ifdef ENOENT
660     case ENOENT:
661       return G_SPAWN_ERROR_NOENT;
662       break;
663 #endif
664
665 #ifdef ENOMEM
666     case ENOMEM:
667       return G_SPAWN_ERROR_NOMEM;
668       break;
669 #endif
670
671 #ifdef ENOTDIR
672     case ENOTDIR:
673       return G_SPAWN_ERROR_NOTDIR;
674       break;
675 #endif
676
677 #ifdef ELOOP
678     case ELOOP:
679       return G_SPAWN_ERROR_LOOP;
680       break;
681 #endif
682       
683 #ifdef ETXTBUSY
684     case ETXTBUSY:
685       return G_SPAWN_ERROR_TXTBUSY;
686       break;
687 #endif
688
689 #ifdef EIO
690     case EIO:
691       return G_SPAWN_ERROR_IO;
692       break;
693 #endif
694
695 #ifdef ENFILE
696     case ENFILE:
697       return G_SPAWN_ERROR_NFILE;
698       break;
699 #endif
700
701 #ifdef EMFILE
702     case EMFILE:
703       return G_SPAWN_ERROR_MFILE;
704       break;
705 #endif
706
707 #ifdef EINVAL
708     case EINVAL:
709       return G_SPAWN_ERROR_INVAL;
710       break;
711 #endif
712
713 #ifdef EISDIR
714     case EISDIR:
715       return G_SPAWN_ERROR_ISDIR;
716       break;
717 #endif
718
719 #ifdef ELIBBAD
720     case ELIBBAD:
721       return G_SPAWN_ERROR_LIBBAD;
722       break;
723 #endif
724       
725     default:
726       return G_SPAWN_ERROR_FAILED;
727       break;
728     }
729 }
730
731 static void
732 write_err_and_exit (gint fd, gint msg)
733 {
734   gint en = errno;
735   
736   write (fd, &msg, sizeof(msg));
737   write (fd, &en, sizeof(en));
738   
739   _exit (1);
740 }
741
742 static void
743 set_cloexec (gint fd)
744 {
745   fcntl (fd, F_SETFD, FD_CLOEXEC);
746 }
747
748 static gint
749 sane_dup2 (gint fd1, gint fd2)
750 {
751   gint ret;
752
753  retry:
754   ret = dup2 (fd1, fd2);
755   if (ret < 0 && errno == EINTR)
756     goto retry;
757
758   return ret;
759 }
760
761 enum
762 {
763   CHILD_CHDIR_FAILED,
764   CHILD_EXEC_FAILED,
765   CHILD_DUP2_FAILED,
766   CHILD_FORK_FAILED
767 };
768
769 static void
770 do_exec (gint                  child_err_report_fd,
771          gint                  stdin_fd,
772          gint                  stdout_fd,
773          gint                  stderr_fd,
774          const gchar          *working_directory,
775          gchar               **argv,
776          gchar               **envp,
777          gboolean              close_descriptors,
778          gboolean              search_path,
779          gboolean              stdout_to_null,
780          gboolean              stderr_to_null,
781          gboolean              child_inherits_stdin,
782          gboolean              file_and_argv_zero,
783          GSpawnChildSetupFunc  child_setup,
784          gpointer              user_data)
785 {
786   if (working_directory && chdir (working_directory) < 0)
787     write_err_and_exit (child_err_report_fd,
788                         CHILD_CHDIR_FAILED);
789
790   /* Close all file descriptors but stdin stdout and stderr as
791    * soon as we exec. Note that this includes
792    * child_err_report_fd, which keeps the parent from blocking
793    * forever on the other end of that pipe.
794    */
795   if (close_descriptors)
796     {
797       gint open_max;
798       gint i;
799       
800       open_max = sysconf (_SC_OPEN_MAX);
801       for (i = 3; i < open_max; i++)
802         set_cloexec (i);
803     }
804   else
805     {
806       /* We need to do child_err_report_fd anyway */
807       set_cloexec (child_err_report_fd);
808     }
809   
810   /* Redirect pipes as required */
811   
812   if (stdin_fd >= 0)
813     {
814       /* dup2 can't actually fail here I don't think */
815           
816       if (sane_dup2 (stdin_fd, 0) < 0)
817         write_err_and_exit (child_err_report_fd,
818                             CHILD_DUP2_FAILED);
819
820       /* ignore this if it doesn't work */
821       close_and_invalidate (&stdin_fd);
822     }
823   else if (!child_inherits_stdin)
824     {
825       /* Keep process from blocking on a read of stdin */
826       gint read_null = open ("/dev/null", O_RDONLY);
827       sane_dup2 (read_null, 0);
828       close_and_invalidate (&read_null);
829     }
830
831   if (stdout_fd >= 0)
832     {
833       /* dup2 can't actually fail here I don't think */
834           
835       if (sane_dup2 (stdout_fd, 1) < 0)
836         write_err_and_exit (child_err_report_fd,
837                             CHILD_DUP2_FAILED);
838
839       /* ignore this if it doesn't work */
840       close_and_invalidate (&stdout_fd);
841     }
842   else if (stdout_to_null)
843     {
844       gint write_null = open ("/dev/null", O_WRONLY);
845       sane_dup2 (write_null, 1);
846       close_and_invalidate (&write_null);
847     }
848
849   if (stderr_fd >= 0)
850     {
851       /* dup2 can't actually fail here I don't think */
852           
853       if (sane_dup2 (stderr_fd, 2) < 0)
854         write_err_and_exit (child_err_report_fd,
855                             CHILD_DUP2_FAILED);
856
857       /* ignore this if it doesn't work */
858       close_and_invalidate (&stderr_fd);
859     }
860   else if (stderr_to_null)
861     {
862       gint write_null = open ("/dev/null", O_WRONLY);
863       sane_dup2 (write_null, 2);
864       close_and_invalidate (&write_null);
865     }
866   
867   /* Call user function just before we exec */
868   if (child_setup)
869     {
870       (* child_setup) (user_data);
871     }
872
873   g_execute (argv[0],
874              file_and_argv_zero ? argv + 1 : argv,
875              envp, search_path);
876
877   /* Exec failed */
878   write_err_and_exit (child_err_report_fd,
879                       CHILD_EXEC_FAILED);
880 }
881
882 static gboolean
883 read_ints (int      fd,
884            gint*    buf,
885            gint     n_ints_in_buf,    
886            gint    *n_ints_read,      
887            GError **error)
888 {
889   gsize bytes = 0;    
890   
891   while (TRUE)
892     {
893       gssize chunk;    
894
895       if (bytes >= sizeof(gint)*2)
896         break; /* give up, who knows what happened, should not be
897                 * possible.
898                 */
899           
900     again:
901       chunk = read (fd,
902                     ((gchar*)buf) + bytes,
903                     sizeof(gint) * n_ints_in_buf - bytes);
904       if (chunk < 0 && errno == EINTR)
905         goto again;
906           
907       if (chunk < 0)
908         {
909           /* Some weird shit happened, bail out */
910               
911           g_set_error (error,
912                        G_SPAWN_ERROR,
913                        G_SPAWN_ERROR_FAILED,
914                        _("Failed to read from child pipe (%s)"),
915                        g_strerror (errno));
916
917           return FALSE;
918         }
919       else if (chunk == 0)
920         break; /* EOF */
921       else /* chunk > 0 */
922         bytes += chunk;
923     }
924
925   *n_ints_read = (gint)(bytes / sizeof(gint));
926
927   return TRUE;
928 }
929
930 static gboolean
931 fork_exec_with_pipes (gboolean              intermediate_child,
932                       const gchar          *working_directory,
933                       gchar               **argv,
934                       gchar               **envp,
935                       gboolean              close_descriptors,
936                       gboolean              search_path,
937                       gboolean              stdout_to_null,
938                       gboolean              stderr_to_null,
939                       gboolean              child_inherits_stdin,
940                       gboolean              file_and_argv_zero,
941                       GSpawnChildSetupFunc  child_setup,
942                       gpointer              user_data,
943                       gint                 *child_pid,
944                       gint                 *standard_input,
945                       gint                 *standard_output,
946                       gint                 *standard_error,
947                       GError              **error)     
948 {
949   gint pid;
950   gint stdin_pipe[2] = { -1, -1 };
951   gint stdout_pipe[2] = { -1, -1 };
952   gint stderr_pipe[2] = { -1, -1 };
953   gint child_err_report_pipe[2] = { -1, -1 };
954   gint child_pid_report_pipe[2] = { -1, -1 };
955   gint status;
956   
957   if (!make_pipe (child_err_report_pipe, error))
958     return FALSE;
959
960   if (intermediate_child && !make_pipe (child_pid_report_pipe, error))
961     goto cleanup_and_fail;
962   
963   if (standard_input && !make_pipe (stdin_pipe, error))
964     goto cleanup_and_fail;
965   
966   if (standard_output && !make_pipe (stdout_pipe, error))
967     goto cleanup_and_fail;
968
969   if (standard_error && !make_pipe (stderr_pipe, error))
970     goto cleanup_and_fail;
971
972   pid = fork ();
973
974   if (pid < 0)
975     {      
976       g_set_error (error,
977                    G_SPAWN_ERROR,
978                    G_SPAWN_ERROR_FORK,
979                    _("Failed to fork (%s)"),
980                    g_strerror (errno));
981
982       goto cleanup_and_fail;
983     }
984   else if (pid == 0)
985     {
986       /* Immediate child. This may or may not be the child that
987        * actually execs the new process.
988        */
989       
990       /* Be sure we crash if the parent exits
991        * and we write to the err_report_pipe
992        */
993       signal (SIGPIPE, SIG_DFL);
994
995       /* Close the parent's end of the pipes;
996        * not needed in the close_descriptors case,
997        * though
998        */
999       close_and_invalidate (&child_err_report_pipe[0]);
1000       close_and_invalidate (&child_pid_report_pipe[0]);
1001       close_and_invalidate (&stdin_pipe[1]);
1002       close_and_invalidate (&stdout_pipe[0]);
1003       close_and_invalidate (&stderr_pipe[0]);
1004       
1005       if (intermediate_child)
1006         {
1007           /* We need to fork an intermediate child that launches the
1008            * final child. The purpose of the intermediate child
1009            * is to exit, so we can waitpid() it immediately.
1010            * Then the grandchild will not become a zombie.
1011            */
1012           gint grandchild_pid;
1013
1014           grandchild_pid = fork ();
1015
1016           if (grandchild_pid < 0)
1017             {
1018               /* report -1 as child PID */
1019               write (child_pid_report_pipe[1], &grandchild_pid,
1020                      sizeof(grandchild_pid));
1021               
1022               write_err_and_exit (child_err_report_pipe[1],
1023                                   CHILD_FORK_FAILED);              
1024             }
1025           else if (grandchild_pid == 0)
1026             {
1027               do_exec (child_err_report_pipe[1],
1028                        stdin_pipe[0],
1029                        stdout_pipe[1],
1030                        stderr_pipe[1],
1031                        working_directory,
1032                        argv,
1033                        envp,
1034                        close_descriptors,
1035                        search_path,
1036                        stdout_to_null,
1037                        stderr_to_null,
1038                        child_inherits_stdin,
1039                        file_and_argv_zero,
1040                        child_setup,
1041                        user_data);
1042             }
1043           else
1044             {
1045               write (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
1046               close_and_invalidate (&child_pid_report_pipe[1]);
1047               
1048               _exit (0);
1049             }
1050         }
1051       else
1052         {
1053           /* Just run the child.
1054            */
1055
1056           do_exec (child_err_report_pipe[1],
1057                    stdin_pipe[0],
1058                    stdout_pipe[1],
1059                    stderr_pipe[1],
1060                    working_directory,
1061                    argv,
1062                    envp,
1063                    close_descriptors,
1064                    search_path,
1065                    stdout_to_null,
1066                    stderr_to_null,
1067                    child_inherits_stdin,
1068                    file_and_argv_zero,
1069                    child_setup,
1070                    user_data);
1071         }
1072     }
1073   else
1074     {
1075       /* Parent */
1076       
1077       gint buf[2];
1078       gint n_ints = 0;    
1079
1080       /* Close the uncared-about ends of the pipes */
1081       close_and_invalidate (&child_err_report_pipe[1]);
1082       close_and_invalidate (&child_pid_report_pipe[1]);
1083       close_and_invalidate (&stdin_pipe[0]);
1084       close_and_invalidate (&stdout_pipe[1]);
1085       close_and_invalidate (&stderr_pipe[1]);
1086
1087       /* If we had an intermediate child, reap it */
1088       if (intermediate_child)
1089         {
1090         wait_again:
1091           if (waitpid (pid, &status, 0) < 0)
1092             {
1093               if (errno == EINTR)
1094                 goto wait_again;
1095               else if (errno == ECHILD)
1096                 ; /* do nothing, child already reaped */
1097               else
1098                 g_warning ("waitpid() should not fail in "
1099                            "'fork_exec_with_pipes'");
1100             }
1101         }
1102       
1103
1104       if (!read_ints (child_err_report_pipe[0],
1105                       buf, 2, &n_ints,
1106                       error))
1107         goto cleanup_and_fail;
1108         
1109       if (n_ints >= 2)
1110         {
1111           /* Error from the child. */
1112
1113           switch (buf[0])
1114             {
1115             case CHILD_CHDIR_FAILED:
1116               g_set_error (error,
1117                            G_SPAWN_ERROR,
1118                            G_SPAWN_ERROR_CHDIR,
1119                            _("Failed to change to directory '%s' (%s)"),
1120                            working_directory,
1121                            g_strerror (buf[1]));
1122
1123               break;
1124               
1125             case CHILD_EXEC_FAILED:
1126               g_set_error (error,
1127                            G_SPAWN_ERROR,
1128                            exec_err_to_g_error (buf[1]),
1129                            _("Failed to execute child process \"%s\" (%s)"),
1130                            argv[0],
1131                            g_strerror (buf[1]));
1132
1133               break;
1134               
1135             case CHILD_DUP2_FAILED:
1136               g_set_error (error,
1137                            G_SPAWN_ERROR,
1138                            G_SPAWN_ERROR_FAILED,
1139                            _("Failed to redirect output or input of child process (%s)"),
1140                            g_strerror (buf[1]));
1141
1142               break;
1143
1144             case CHILD_FORK_FAILED:
1145               g_set_error (error,
1146                            G_SPAWN_ERROR,
1147                            G_SPAWN_ERROR_FORK,
1148                            _("Failed to fork child process (%s)"),
1149                            g_strerror (buf[1]));
1150               break;
1151               
1152             default:
1153               g_set_error (error,
1154                            G_SPAWN_ERROR,
1155                            G_SPAWN_ERROR_FAILED,
1156                            _("Unknown error executing child process \"%s\""),
1157                            argv[0]);
1158               break;
1159             }
1160
1161           goto cleanup_and_fail;
1162         }
1163
1164       /* Get child pid from intermediate child pipe. */
1165       if (intermediate_child)
1166         {
1167           n_ints = 0;
1168           
1169           if (!read_ints (child_pid_report_pipe[0],
1170                           buf, 1, &n_ints, error))
1171             goto cleanup_and_fail;
1172
1173           if (n_ints < 1)
1174             {
1175               g_set_error (error,
1176                            G_SPAWN_ERROR,
1177                            G_SPAWN_ERROR_FAILED,
1178                            _("Failed to read enough data from child pid pipe (%s)"),
1179                            g_strerror (errno));
1180               goto cleanup_and_fail;
1181             }
1182           else
1183             {
1184               /* we have the child pid */
1185               pid = buf[0];
1186             }
1187         }
1188       
1189       /* Success against all odds! return the information */
1190       
1191       if (child_pid)
1192         *child_pid = pid;
1193
1194       if (standard_input)
1195         *standard_input = stdin_pipe[1];
1196       if (standard_output)
1197         *standard_output = stdout_pipe[0];
1198       if (standard_error)
1199         *standard_error = stderr_pipe[0];
1200       
1201       return TRUE;
1202     }
1203
1204  cleanup_and_fail:
1205   close_and_invalidate (&child_err_report_pipe[0]);
1206   close_and_invalidate (&child_err_report_pipe[1]);
1207   close_and_invalidate (&child_pid_report_pipe[0]);
1208   close_and_invalidate (&child_pid_report_pipe[1]);
1209   close_and_invalidate (&stdin_pipe[0]);
1210   close_and_invalidate (&stdin_pipe[1]);
1211   close_and_invalidate (&stdout_pipe[0]);
1212   close_and_invalidate (&stdout_pipe[1]);
1213   close_and_invalidate (&stderr_pipe[0]);
1214   close_and_invalidate (&stderr_pipe[1]);
1215
1216   return FALSE;
1217 }
1218
1219 static gboolean
1220 make_pipe (gint     p[2],
1221            GError **error)
1222 {
1223   if (pipe (p) < 0)
1224     {
1225       g_set_error (error,
1226                    G_SPAWN_ERROR,
1227                    G_SPAWN_ERROR_FAILED,
1228                    _("Failed to create pipe for communicating with child process (%s)"),
1229                    g_strerror (errno));
1230       return FALSE;
1231     }
1232   else
1233     return TRUE;
1234 }
1235
1236 /* Based on execvp from GNU C Library */
1237
1238 static void
1239 script_execute (const gchar *file,
1240                 gchar      **argv,
1241                 gchar      **envp,
1242                 gboolean     search_path)
1243 {
1244   /* Count the arguments.  */
1245   int argc = 0;
1246   while (argv[argc])
1247     ++argc;
1248   
1249   /* Construct an argument list for the shell.  */
1250   {
1251     gchar **new_argv;
1252
1253     new_argv = g_new0 (gchar*, argc + 2); /* /bin/sh and NULL */
1254     
1255     new_argv[0] = (char *) "/bin/sh";
1256     new_argv[1] = (char *) file;
1257     while (argc > 0)
1258       {
1259         new_argv[argc + 1] = argv[argc];
1260         --argc;
1261       }
1262
1263     /* Execute the shell. */
1264     if (envp)
1265       execve (new_argv[0], new_argv, envp);
1266     else
1267       execv (new_argv[0], new_argv);
1268     
1269     g_free (new_argv);
1270   }
1271 }
1272
1273 static gchar*
1274 my_strchrnul (const gchar *str, gchar c)
1275 {
1276   gchar *p = (gchar*) str;
1277   while (*p && (*p != c))
1278     ++p;
1279
1280   return p;
1281 }
1282
1283 static gint
1284 g_execute (const gchar *file,
1285            gchar      **argv,
1286            gchar      **envp,
1287            gboolean     search_path)
1288 {
1289   if (*file == '\0')
1290     {
1291       /* We check the simple case first. */
1292       errno = ENOENT;
1293       return -1;
1294     }
1295
1296   if (!search_path || strchr (file, '/') != NULL)
1297     {
1298       /* Don't search when it contains a slash. */
1299       if (envp)
1300         execve (file, argv, envp);
1301       else
1302         execv (file, argv);
1303       
1304       if (errno == ENOEXEC)
1305         script_execute (file, argv, envp, FALSE);
1306     }
1307   else
1308     {
1309       gboolean got_eacces = 0;
1310       const gchar *path, *p;
1311       gchar *name, *freeme;
1312       size_t len;
1313       size_t pathlen;
1314
1315       path = g_getenv ("PATH");
1316       if (path == NULL)
1317         {
1318           /* There is no `PATH' in the environment.  The default
1319            * search path in libc is the current directory followed by
1320            * the path `confstr' returns for `_CS_PATH'.
1321            */
1322
1323           /* In GLib we put . last, for security, and don't use the
1324            * unportable confstr(); UNIX98 does not actually specify
1325            * what to search if PATH is unset. POSIX may, dunno.
1326            */
1327           
1328           path = "/bin:/usr/bin:.";
1329         }
1330
1331       len = strlen (file) + 1;
1332       pathlen = strlen (path);
1333       freeme = name = g_malloc (pathlen + len + 1);
1334       
1335       /* Copy the file name at the top, including '\0'  */
1336       memcpy (name + pathlen + 1, file, len);
1337       name = name + pathlen;
1338       /* And add the slash before the filename  */
1339       *name = '/';
1340
1341       p = path;
1342       do
1343         {
1344           char *startp;
1345
1346           path = p;
1347           p = my_strchrnul (path, ':');
1348
1349           if (p == path)
1350             /* Two adjacent colons, or a colon at the beginning or the end
1351              * of `PATH' means to search the current directory.
1352              */
1353             startp = name + 1;
1354           else
1355             startp = memcpy (name - (p - path), path, p - path);
1356
1357           /* Try to execute this name.  If it works, execv will not return.  */
1358           if (envp)
1359             execve (startp, argv, envp);
1360           else
1361             execv (startp, argv);
1362           
1363           if (errno == ENOEXEC)
1364             script_execute (startp, argv, envp, search_path);
1365
1366           switch (errno)
1367             {
1368             case EACCES:
1369               /* Record the we got a `Permission denied' error.  If we end
1370                * up finding no executable we can use, we want to diagnose
1371                * that we did find one but were denied access.
1372                */
1373               got_eacces = TRUE;
1374
1375               /* FALL THRU */
1376               
1377             case ENOENT:
1378 #ifdef ESTALE
1379             case ESTALE:
1380 #endif
1381 #ifdef ENOTDIR
1382             case ENOTDIR:
1383 #endif
1384               /* Those errors indicate the file is missing or not executable
1385                * by us, in which case we want to just try the next path
1386                * directory.
1387                */
1388               break;
1389
1390             default:
1391               /* Some other error means we found an executable file, but
1392                * something went wrong executing it; return the error to our
1393                * caller.
1394                */
1395               g_free (freeme);
1396               return -1;
1397             }
1398         }
1399       while (*p++ != '\0');
1400
1401       /* We tried every element and none of them worked.  */
1402       if (got_eacces)
1403         /* At least one failure was due to permissions, so report that
1404          * error.
1405          */
1406         errno = EACCES;
1407
1408       g_free (freeme);
1409     }
1410
1411   /* Return the error from the last attempt (probably ENOENT).  */
1412   return -1;
1413 }