1cf28ed85SJohn Marino /* Return a safer copy of a file descriptor. 2cf28ed85SJohn Marino 3*09d4459fSDaniel Fojt Copyright (C) 2005-2006, 2009-2020 Free Software Foundation, Inc. 4cf28ed85SJohn Marino 5cf28ed85SJohn Marino This program is free software: you can redistribute it and/or modify 6cf28ed85SJohn Marino it under the terms of the GNU General Public License as published by 7cf28ed85SJohn Marino the Free Software Foundation; either version 3 of the License, or 8cf28ed85SJohn Marino (at your option) any later version. 9cf28ed85SJohn Marino 10cf28ed85SJohn Marino This program is distributed in the hope that it will be useful, 11cf28ed85SJohn Marino but WITHOUT ANY WARRANTY; without even the implied warranty of 12cf28ed85SJohn Marino MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13cf28ed85SJohn Marino GNU General Public License for more details. 14cf28ed85SJohn Marino 15cf28ed85SJohn Marino You should have received a copy of the GNU General Public License 16*09d4459fSDaniel Fojt along with this program. If not, see <https://www.gnu.org/licenses/>. */ 17cf28ed85SJohn Marino 18cf28ed85SJohn Marino /* Written by Paul Eggert. */ 19cf28ed85SJohn Marino 20cf28ed85SJohn Marino #include <config.h> 21cf28ed85SJohn Marino 22cf28ed85SJohn Marino #include "unistd-safer.h" 23cf28ed85SJohn Marino 24cf28ed85SJohn Marino #include <errno.h> 25cf28ed85SJohn Marino #include <unistd.h> 26cf28ed85SJohn Marino 27cf28ed85SJohn Marino /* Return FD, unless FD would be a copy of standard input, output, or 28cf28ed85SJohn Marino error; in that case, return a duplicate of FD, closing FD. On 29cf28ed85SJohn Marino failure to duplicate, close FD, set errno, and return -1. Preserve 30cf28ed85SJohn Marino errno if FD is negative, so that the caller can always inspect 31cf28ed85SJohn Marino errno when the returned value is negative. 32cf28ed85SJohn Marino 33cf28ed85SJohn Marino This function is usefully wrapped around functions that return file 34cf28ed85SJohn Marino descriptors, e.g., fd_safer (open ("file", O_RDONLY)). */ 35cf28ed85SJohn Marino 36cf28ed85SJohn Marino int 37cf28ed85SJohn Marino fd_safer (int fd) 38cf28ed85SJohn Marino { 39cf28ed85SJohn Marino if (STDIN_FILENO <= fd && fd <= STDERR_FILENO) 40cf28ed85SJohn Marino { 41cf28ed85SJohn Marino int f = dup_safer (fd); 42cf28ed85SJohn Marino int e = errno; 43cf28ed85SJohn Marino close (fd); 44cf28ed85SJohn Marino errno = e; 45cf28ed85SJohn Marino fd = f; 46cf28ed85SJohn Marino } 47cf28ed85SJohn Marino 48cf28ed85SJohn Marino return fd; 49cf28ed85SJohn Marino } 50