1 /*
2  * SPDX-License-Identifier: ISC
3  *
4  * Copyright (c) 2017 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_PIPE2
27 
28 #include <fcntl.h>
29 #include <unistd.h>
30 
31 #include "sudo_compat.h"
32 
33 int
sudo_pipe2(int fildes[2],int flags)34 sudo_pipe2(int fildes[2], int flags)
35 {
36     if (pipe(fildes) != 0)
37 	return -1;
38 
39     if (ISSET(flags, O_CLOEXEC)) {
40 	if (fcntl(fildes[0], F_SETFD, FD_CLOEXEC) == -1)
41 	    goto bad;
42 	if (fcntl(fildes[1], F_SETFD, FD_CLOEXEC) == -1)
43 	    goto bad;
44     }
45     if (ISSET(flags, O_NONBLOCK)) {
46 	int oflags = fcntl(fildes[0], F_GETFL, 0);
47 	if (oflags == -1)
48 	    goto bad;
49 	if (fcntl(fildes[0], F_SETFL, oflags | O_NONBLOCK) == -1)
50 	    goto bad;
51 	oflags = fcntl(fildes[1], F_GETFL, 0);
52 	if (oflags == -1)
53 	    goto bad;
54 	if (fcntl(fildes[1], F_SETFL, oflags | O_NONBLOCK) == -1)
55 	    goto bad;
56     }
57     return 0;
58 bad:
59     close(fildes[0]);
60     close(fildes[1]);
61     return -1;
62 }
63 
64 #endif /* HAVE_PIPE2 */
65