1 /* sockets.c --- wrappers for Windows socket functions
3 Copyright (C) 2008-2011 Free Software Foundation, Inc.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
18 /* Written by Simon Josefsson */
27 /* This includes winsock2.h on MinGW. */
28 # include <sys/socket.h>
32 /* Get set_winsock_errno, FD_TO_SOCKET etc. */
36 close_fd_maybe_socket (const struct fd_hook
*remaining_list
,
43 /* Test whether fd refers to a socket. */
44 sock
= FD_TO_SOCKET (fd
);
45 ev
.lNetworkEvents
= 0xDEADBEEF;
46 WSAEnumNetworkEvents (sock
, NULL
, &ev
);
47 if (ev
.lNetworkEvents
!= 0xDEADBEEF)
49 /* fd refers to a socket. */
50 /* FIXME: other applications, like squid, use an undocumented
51 _free_osfhnd free function. But this is not enough: The 'osfile'
52 flags for fd also needs to be cleared, but it is hard to access it.
53 Instead, here we just close twice the file descriptor. */
54 if (closesocket (sock
))
61 /* This call frees the file descriptor and does a
62 CloseHandle ((HANDLE) _get_osfhandle (fd)), which fails. */
68 /* Some other type of file descriptor. */
69 return execute_close_hooks (remaining_list
, primary
, fd
);
73 ioctl_fd_maybe_socket (const struct fd_hook
*remaining_list
,
75 int fd
, int request
, void *arg
)
80 /* Test whether fd refers to a socket. */
81 sock
= FD_TO_SOCKET (fd
);
82 ev
.lNetworkEvents
= 0xDEADBEEF;
83 WSAEnumNetworkEvents (sock
, NULL
, &ev
);
84 if (ev
.lNetworkEvents
!= 0xDEADBEEF)
86 /* fd refers to a socket. */
87 if (ioctlsocket (sock
, request
, arg
) < 0)
96 /* Some other type of file descriptor. */
97 return execute_ioctl_hooks (remaining_list
, primary
, fd
, request
, arg
);
100 static struct fd_hook fd_sockets_hook
;
102 static int initialized_sockets_version
/* = 0 */;
104 #endif /* WINDOWS_SOCKETS */
107 gl_sockets_startup (int version _GL_UNUSED
)
110 if (version
> initialized_sockets_version
)
115 err
= WSAStartup (version
, &data
);
119 if (data
.wVersion
< version
)
122 if (initialized_sockets_version
== 0)
123 register_fd_hook (close_fd_maybe_socket
, ioctl_fd_maybe_socket
,
126 initialized_sockets_version
= version
;
134 gl_sockets_cleanup (void)
139 initialized_sockets_version
= 0;
141 unregister_fd_hook (&fd_sockets_hook
);