/*1* SPDX-License-Identifier: ISC2*3* Copyright (c) 2013 Todd C. Miller <[email protected]>4*5* Permission to use, copy, modify, and distribute this software for any6* purpose with or without fee is hereby granted, provided that the above7* copyright notice and this permission notice appear in all copies.8*9* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES10* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF11* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR12* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES13* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN14* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF15* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.16*/1718#include <config.h>1920#ifndef HAVE_DUP32122#include <errno.h>23#include <fcntl.h>24#include <unistd.h>2526#include <sudo_compat.h>2728int29sudo_dup3(int oldd, int newd, int flags)30{31int oflags;3233if (oldd == newd) {34errno = EINVAL;35return -1;36}3738if (dup2(oldd, newd) == -1)39return -1;4041oflags = fcntl(newd, F_GETFL, 0);42if (oflags == -1)43goto bad;4445if (ISSET(flags, O_NONBLOCK)) {46if (!ISSET(oflags, O_NONBLOCK)) {47SET(oflags, O_NONBLOCK);48if (fcntl(newd, F_SETFL, oflags) == -1)49goto bad;50}51} else {52if (ISSET(oflags, O_NONBLOCK)) {53CLR(oflags, O_NONBLOCK);54if (fcntl(newd, F_SETFL, oflags) == -1)55goto bad;56}57}58if (ISSET(flags, O_CLOEXEC)) {59if (fcntl(newd, F_SETFD, FD_CLOEXEC) == -1)60goto bad;61}62return 0;63bad:64close(newd);65return -1;66}6768#endif /* HAVE_DUP3 */697071