root/maint/gnulib/lib/popen-safer.c

/* [previous][next][first][last][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. popen_safer

   1 /* Invoke popen, but avoid some glitches.
   2 
   3    Copyright (C) 2009-2021 Free Software Foundation, Inc.
   4 
   5    This program is free software: you can redistribute it and/or modify
   6    it under the terms of the GNU General Public License as published by
   7    the Free Software Foundation; either version 3 of the License, or
   8    (at your option) any later version.
   9 
  10    This program is distributed in the hope that it will be useful,
  11    but WITHOUT ANY WARRANTY; without even the implied warranty of
  12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13    GNU General Public License for more details.
  14 
  15    You should have received a copy of the GNU General Public License
  16    along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
  17 
  18 /* Written by Eric Blake.  */
  19 
  20 #include <config.h>
  21 
  22 #include "stdio-safer.h"
  23 
  24 #include <errno.h>
  25 #include <fcntl.h>
  26 #include <unistd.h>
  27 
  28 /* Like popen, but do not return stdin, stdout, or stderr.  */
  29 
  30 FILE *
  31 popen_safer (char const *cmd, char const *mode)
     /* [previous][next][first][last][top][bottom][index][help] */
  32 {
  33   /* Unfortunately, we cannot use the fopen_safer approach of using
  34      fdopen (dup_safer (fileno (popen (cmd, mode)))), because stdio
  35      libraries maintain hidden state tying the original fd to the pid
  36      to wait on when using pclose (this hidden state is also used to
  37      avoid fd leaks in subsequent popen calls).  So, we instead
  38      guarantee that all standard streams are open prior to the popen
  39      call (even though this puts more pressure on open fds), so that
  40      the original fd created by popen is safe.  */
  41   FILE *fp;
  42   int fd = open ("/dev/null", O_RDONLY | O_CLOEXEC);
  43   if (0 <= fd && fd <= STDERR_FILENO)
  44     {
  45       /* Maximum recursion depth is 3.  */
  46       int saved_errno;
  47       fp = popen_safer (cmd, mode);
  48       saved_errno = errno;
  49       close (fd);
  50       errno = saved_errno;
  51     }
  52   else
  53     {
  54       /* Either all fd's are tied up, or fd is safe and the real popen
  55          will reuse it.  */
  56       close (fd);
  57       fp = popen (cmd, mode);
  58     }
  59   return fp;
  60 }

/* [previous][next][first][last][top][bottom][index][help] */