1 /* Accept a connection on a socket, with specific opening flags.
2 Copyright (C) 2009-2016 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 <http://www.gnu.org/licenses/>. */
20 #include <sys/socket.h>
24 #include "binary-io.h"
25 #include "msvc-nothrow.h"
28 # define SOCK_CLOEXEC 0
32 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
38 /* Try the system call first, if it exists. (We may be running with a glibc
39 that has the function but with an older kernel that lacks it.) */
41 /* Cache the information whether the system call really exists. */
42 static int have_accept4_really; /* 0 = unknown, 1 = yes, -1 = no */
43 if (have_accept4_really >= 0)
45 int result = accept4 (sockfd, addr, addrlen, flags);
46 if (!(result < 0 && errno == ENOSYS))
48 have_accept4_really = 1;
51 have_accept4_really = -1;
56 /* Check the supported flags. */
57 if ((flags & ~(SOCK_CLOEXEC | O_TEXT | O_BINARY)) != 0)
63 fd = accept (sockfd, addr, addrlen);
68 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
69 /* Native Windows API. */
70 if (flags & SOCK_CLOEXEC)
72 HANDLE curr_process = GetCurrentProcess ();
73 HANDLE old_handle = (HANDLE) _get_osfhandle (fd);
77 if (!DuplicateHandle (curr_process, /* SourceProcessHandle */
78 old_handle, /* SourceHandle */
79 curr_process, /* TargetProcessHandle */
80 (PHANDLE) &new_handle, /* TargetHandle */
81 (DWORD) 0, /* DesiredAccess */
82 FALSE, /* InheritHandle */
83 DUPLICATE_SAME_ACCESS)) /* Options */
86 errno = EBADF; /* arbitrary */
90 /* Closing fd before allocating the new fd ensures that the new fd will
91 have the minimum possible value. */
93 nfd = _open_osfhandle ((intptr_t) new_handle,
94 O_NOINHERIT | (flags & (O_TEXT | O_BINARY)));
97 CloseHandle (new_handle);
104 if (flags & SOCK_CLOEXEC)
108 if ((fcntl_flags = fcntl (fd, F_GETFD, 0)) < 0
109 || fcntl (fd, F_SETFD, fcntl_flags | FD_CLOEXEC) == -1)
111 int saved_errno = errno;
121 if (flags & O_BINARY)
122 set_binary_mode (fd, O_BINARY);
123 else if (flags & O_TEXT)
124 set_binary_mode (fd, O_TEXT);