1 /*
2  * SPDX-License-Identifier: ISC
3  *
4  * Copyright (c) 2013 Todd C. Miller <Todd.Miller@sudo.ws>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 /*
20  * This is an open source non-commercial project. Dear PVS-Studio, please check it.
21  * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
22  */
23 
24 #include <config.h>
25 
26 #ifndef HAVE_DUP3
27 
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <unistd.h>
31 
32 #include "sudo_compat.h"
33 
34 int
sudo_dup3(int oldd,int newd,int flags)35 sudo_dup3(int oldd, int newd, int flags)
36 {
37     int oflags;
38 
39     if (oldd == newd) {
40 	errno = EINVAL;
41 	return -1;
42     }
43 
44     if (dup2(oldd, newd) == -1)
45 	return -1;
46 
47     oflags = fcntl(newd, F_GETFL, 0);
48     if (oflags == -1)
49 	goto bad;
50 
51     if (ISSET(flags, O_NONBLOCK)) {
52 	if (!ISSET(oflags, O_NONBLOCK)) {
53 	    SET(oflags, O_NONBLOCK);
54 	    if (fcntl(newd, F_SETFL, oflags) == -1)
55 		goto bad;
56 	}
57     } else {
58 	if (ISSET(oflags, O_NONBLOCK)) {
59 	    CLR(oflags, O_NONBLOCK);
60 	    if (fcntl(newd, F_SETFL, oflags) == -1)
61 		goto bad;
62 	}
63     }
64     if (ISSET(flags, O_CLOEXEC)) {
65 	if (fcntl(newd, F_SETFD, FD_CLOEXEC) == -1)
66 	    goto bad;
67     }
68     return 0;
69 bad:
70     close(newd);
71     return -1;
72 }
73 
74 #endif /* HAVE_DUP3 */
75