source: trunk/third/glib2/glib/gspawn.c @ 18159

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