OpenVPN
fdmisc.c
Go to the documentation of this file.
1/*
2 * OpenVPN -- An application to securely tunnel IP networks
3 * over a single UDP port, with support for SSL/TLS-based
4 * session authentication and key exchange,
5 * packet encryption, packet authentication, and
6 * packet compression.
7 *
8 * Copyright (C) 2002-2026 OpenVPN Inc <sales@openvpn.net>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2
12 * as published by the Free Software Foundation.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, see <https://www.gnu.org/licenses/>.
21 */
22
23#ifdef HAVE_CONFIG_H
24#include "config.h"
25#endif
26
27#include "syshead.h"
28
29#include "fdmisc.h"
30#include "error.h"
31
32#include "memdbg.h"
33
34#if defined(_WIN32) && (defined(__GNUC__) || defined(__clang__))
35#pragma GCC diagnostic push
36#pragma GCC diagnostic ignored "-Wsign-conversion"
37#endif
38
39/* Set a file descriptor to non-blocking */
40bool
42{
43#ifdef _WIN32
44 u_long arg = 1;
45 if (ioctlsocket(fd, FIONBIO, &arg))
46 {
47 return false;
48 }
49#else /* ifdef _WIN32 */
50 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
51 {
52 return false;
53 }
54#endif
55 return true;
56}
57
58#if defined(_WIN32) && (defined(__GNUC__) || defined(__clang__))
59#pragma GCC diagnostic pop
60#endif
61
62/* Set a file descriptor to not be passed across execs */
63bool
65{
66#ifndef _WIN32
67 if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0)
68 {
69 return false;
70 }
71#endif
72 return true;
73}
74
75/* Set a file descriptor to non-blocking */
76void
78{
79 if (!set_nonblock_action(fd))
80 {
81 msg(M_ERR, "Set socket to non-blocking mode failed");
82 }
83}
84
85/* Set a file descriptor to not be passed across execs */
86void
88{
89 if (!set_cloexec_action(fd))
90 {
91 msg(M_ERR, "Set FD_CLOEXEC flag on file descriptor failed");
92 }
93}
void set_nonblock(socket_descriptor_t fd)
Definition fdmisc.c:77
bool set_cloexec_action(socket_descriptor_t fd)
Definition fdmisc.c:64
void set_cloexec(socket_descriptor_t fd)
Definition fdmisc.c:87
bool set_nonblock_action(socket_descriptor_t fd)
Definition fdmisc.c:41
#define M_ERR
Definition error.h:106
#define msg(flags,...)
Definition error.h:152
SOCKET socket_descriptor_t
Definition syshead.h:441