Add `gnutls/dtls.h' to the distribution.
[gnutls.git] / gl / sockets.c
blobb946c7e63deca8440e6816abe4000cddeea381bc
1 /* sockets.c --- wrappers for Windows socket functions
3 Copyright (C) 2008-2010 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 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 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
18 /* Written by Simon Josefsson */
20 #include <config.h>
22 /* Specification. */
23 #include "sockets.h"
25 #if WINDOWS_SOCKETS
27 /* This includes winsock2.h on MinGW. */
28 # include <sys/socket.h>
30 # include "close-hook.h"
32 /* Get set_winsock_errno, FD_TO_SOCKET etc. */
33 # include "w32sock.h"
35 static int
36 close_fd_maybe_socket (int fd, const struct close_hook *remaining_list)
38 SOCKET sock;
39 WSANETWORKEVENTS ev;
41 /* Test whether fd refers to a socket. */
42 sock = FD_TO_SOCKET (fd);
43 ev.lNetworkEvents = 0xDEADBEEF;
44 WSAEnumNetworkEvents (sock, NULL, &ev);
45 if (ev.lNetworkEvents != 0xDEADBEEF)
47 /* fd refers to a socket. */
48 /* FIXME: other applications, like squid, use an undocumented
49 _free_osfhnd free function. But this is not enough: The 'osfile'
50 flags for fd also needs to be cleared, but it is hard to access it.
51 Instead, here we just close twice the file descriptor. */
52 if (closesocket (sock))
54 set_winsock_errno ();
55 return -1;
57 else
59 /* This call frees the file descriptor and does a
60 CloseHandle ((HANDLE) _get_osfhandle (fd)), which fails. */
61 _close (fd);
62 return 0;
65 else
66 /* Some other type of file descriptor. */
67 return execute_close_hooks (fd, remaining_list);
70 static struct close_hook close_sockets_hook;
72 static int initialized_sockets_version /* = 0 */;
74 #endif /* WINDOWS_SOCKETS */
76 int
77 gl_sockets_startup (int version _GL_UNUSED)
79 #if WINDOWS_SOCKETS
80 if (version > initialized_sockets_version)
82 WSADATA data;
83 int err;
85 err = WSAStartup (version, &data);
86 if (err != 0)
87 return 1;
89 if (data.wVersion < version)
90 return 2;
92 if (initialized_sockets_version == 0)
93 register_close_hook (close_fd_maybe_socket, &close_sockets_hook);
95 initialized_sockets_version = version;
97 #endif
99 return 0;
103 gl_sockets_cleanup (void)
105 #if WINDOWS_SOCKETS
106 int err;
108 initialized_sockets_version = 0;
110 unregister_close_hook (&close_sockets_hook);
112 err = WSACleanup ();
113 if (err != 0)
114 return 1;
115 #endif
117 return 0;