1 /* Accept a connection on a socket, with specific opening flags.
2 Copyright (C) 2009-2019 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along
15 with this program; if not, see <https://www.gnu.org/licenses/>. */
20 #include <sys/socket.h>
24 #include "binary-io.h"
25 #if GNULIB_MSVC_NOTHROW
26 # include "msvc-nothrow.h"
32 # define SOCK_CLOEXEC 0
36 accept4 (int sockfd
, struct sockaddr
*addr
, socklen_t
*addrlen
, int flags
)
42 /* Try the system call first, if it exists. (We may be running with a glibc
43 that has the function but with an older kernel that lacks it.) */
45 /* Cache the information whether the system call really exists. */
46 static int have_accept4_really
; /* 0 = unknown, 1 = yes, -1 = no */
47 if (have_accept4_really
>= 0)
49 int result
= accept4 (sockfd
, addr
, addrlen
, flags
);
50 if (!(result
< 0 && errno
== ENOSYS
))
52 have_accept4_really
= 1;
55 have_accept4_really
= -1;
60 /* Check the supported flags. */
61 if ((flags
& ~(SOCK_CLOEXEC
| O_TEXT
| O_BINARY
)) != 0)
67 fd
= accept (sockfd
, addr
, addrlen
);
72 # if defined _WIN32 && ! defined __CYGWIN__
73 /* Native Windows API. */
74 if (flags
& SOCK_CLOEXEC
)
76 HANDLE curr_process
= GetCurrentProcess ();
77 HANDLE old_handle
= (HANDLE
) _get_osfhandle (fd
);
81 if (!DuplicateHandle (curr_process
, /* SourceProcessHandle */
82 old_handle
, /* SourceHandle */
83 curr_process
, /* TargetProcessHandle */
84 (PHANDLE
) &new_handle
, /* TargetHandle */
85 (DWORD
) 0, /* DesiredAccess */
86 FALSE
, /* InheritHandle */
87 DUPLICATE_SAME_ACCESS
)) /* Options */
90 errno
= EBADF
; /* arbitrary */
94 /* Closing fd before allocating the new fd ensures that the new fd will
95 have the minimum possible value. */
97 nfd
= _open_osfhandle ((intptr_t) new_handle
,
98 O_NOINHERIT
| (flags
& (O_TEXT
| O_BINARY
)));
101 CloseHandle (new_handle
);
108 if (flags
& SOCK_CLOEXEC
)
112 if ((fcntl_flags
= fcntl (fd
, F_GETFD
, 0)) < 0
113 || fcntl (fd
, F_SETFD
, fcntl_flags
| FD_CLOEXEC
) == -1)
115 int saved_errno
= errno
;
125 if (flags
& O_BINARY
)
126 set_binary_mode (fd
, O_BINARY
);
127 else if (flags
& O_TEXT
)
128 set_binary_mode (fd
, O_TEXT
);