1 /* Accept a connection on a socket, with specific opening flags.
2 Copyright (C) 2009-2011 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, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
21 #include <sys/socket.h>
25 #include "binary-io.h"
26 #include "msvc-nothrow.h"
29 # define SOCK_CLOEXEC 0
33 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
39 /* Try the system call first, if it exists. (We may be running with a glibc
40 that has the function but with an older kernel that lacks it.) */
42 /* Cache the information whether the system call really exists. */
43 static int have_accept4_really; /* 0 = unknown, 1 = yes, -1 = no */
44 if (have_accept4_really >= 0)
46 int result = accept4 (sockfd, addr, addrlen, flags);
47 if (!(result < 0 && errno == ENOSYS))
49 have_accept4_really = 1;
52 have_accept4_really = -1;
57 /* Check the supported flags. */
58 if ((flags & ~(SOCK_CLOEXEC | O_TEXT | O_BINARY)) != 0)
64 fd = accept (sockfd, addr, addrlen);
69 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
70 /* Native Woe32 API. */
71 if (flags & SOCK_CLOEXEC)
73 HANDLE curr_process = GetCurrentProcess ();
74 HANDLE old_handle = (HANDLE) _get_osfhandle (fd);
78 if (!DuplicateHandle (curr_process, /* SourceProcessHandle */
79 old_handle, /* SourceHandle */
80 curr_process, /* TargetProcessHandle */
81 (PHANDLE) &new_handle, /* TargetHandle */
82 (DWORD) 0, /* DesiredAccess */
83 FALSE, /* InheritHandle */
84 DUPLICATE_SAME_ACCESS)) /* Options */
87 errno = EBADF; /* arbitrary */
91 /* Closing fd before allocating the new fd ensures that the new fd will
92 have the minimum possible value. */
94 nfd = _open_osfhandle ((long) new_handle,
95 O_NOINHERIT | (flags & (O_TEXT | O_BINARY)));
98 CloseHandle (new_handle);
105 if (flags & SOCK_CLOEXEC)
109 if ((fcntl_flags = fcntl (fd, F_GETFD, 0)) < 0
110 || fcntl (fd, F_SETFD, fcntl_flags | FD_CLOEXEC) == -1)
112 int saved_errno = errno;
122 if (flags & O_BINARY)
123 setmode (fd, O_BINARY);
124 else if (flags & O_TEXT)
125 setmode (fd, O_TEXT);