ws2_32: Move the setsockopt(IPV6_V6ONLY) implementation to ntdll.
[wine.git] / dlls / ws2_32 / socket.c
bloba28c25ec697eac0012f8fdc32655e4014cc9968f
1 /*
2 * based on Windows Sockets 1.1 specs
4 * Copyright (C) 1993,1994,1996,1997 John Brezak, Erik Bos, Alex Korobka.
5 * Copyright (C) 2001 Stefan Leichter
6 * Copyright (C) 2004 Hans Leidekker
7 * Copyright (C) 2005 Marcus Meissner
8 * Copyright (C) 2006-2008 Kai Blin
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 * NOTE: If you make any changes to fix a particular app, make sure
25 * they don't break something else like Netscape or telnet and ftp
26 * clients and servers (www.winsite.com got a lot of those).
29 #include "config.h"
30 #include "wine/port.h"
32 #include "ws2_32_private.h"
34 #if defined(linux) && !defined(IP_UNICAST_IF)
35 #define IP_UNICAST_IF 50
36 #endif
38 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
39 # define sipx_network sipx_addr.x_net
40 # define sipx_node sipx_addr.x_host.c_host
41 #endif /* __FreeBSD__ */
43 #define FILE_USE_FILE_POINTER_POSITION ((LONGLONG)-2)
45 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
46 WINE_DECLARE_DEBUG_CHANNEL(winediag);
48 static const WSAPROTOCOL_INFOW supported_protocols[] =
51 .dwServiceFlags1 = XP1_IFS_HANDLES | XP1_EXPEDITED_DATA | XP1_GRACEFUL_CLOSE
52 | XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY,
53 .dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO,
54 .ProviderId = {0xe70f1aa0, 0xab8b, 0x11cf, {0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}},
55 .dwCatalogEntryId = 1001,
56 .ProtocolChain.ChainLen = 1,
57 .iVersion = 2,
58 .iAddressFamily = WS_AF_INET,
59 .iMaxSockAddr = sizeof(struct WS_sockaddr_in),
60 .iMinSockAddr = sizeof(struct WS_sockaddr_in),
61 .iSocketType = WS_SOCK_STREAM,
62 .iProtocol = WS_IPPROTO_TCP,
63 .szProtocol = {'T','C','P','/','I','P',0},
66 .dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST
67 | XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED | XP1_CONNECTIONLESS,
68 .dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO,
69 .ProviderId = {0xe70f1aa0, 0xab8b, 0x11cf, {0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}},
70 .dwCatalogEntryId = 1002,
71 .ProtocolChain.ChainLen = 1,
72 .iVersion = 2,
73 .iAddressFamily = WS_AF_INET,
74 .iMaxSockAddr = sizeof(struct WS_sockaddr_in),
75 .iMinSockAddr = sizeof(struct WS_sockaddr_in),
76 .iSocketType = WS_SOCK_DGRAM,
77 .iProtocol = WS_IPPROTO_UDP,
78 .dwMessageSize = 0xffbb,
79 .szProtocol = {'U','D','P','/','I','P',0},
82 .dwServiceFlags1 = XP1_IFS_HANDLES | XP1_EXPEDITED_DATA | XP1_GRACEFUL_CLOSE
83 | XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY,
84 .dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO,
85 .ProviderId = {0xf9eab0c0, 0x26d4, 0x11d0, {0xbb, 0xbf, 0x00, 0xaa, 0x00, 0x6c, 0x34, 0xe4}},
86 .dwCatalogEntryId = 1004,
87 .ProtocolChain.ChainLen = 1,
88 .iVersion = 2,
89 .iAddressFamily = WS_AF_INET6,
90 .iMaxSockAddr = sizeof(struct WS_sockaddr_in6),
91 .iMinSockAddr = sizeof(struct WS_sockaddr_in6),
92 .iSocketType = WS_SOCK_STREAM,
93 .iProtocol = WS_IPPROTO_TCP,
94 .szProtocol = {'T','C','P','/','I','P','v','6',0},
97 .dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST
98 | XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED | XP1_CONNECTIONLESS,
99 .dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO,
100 .ProviderId = {0xf9eab0c0, 0x26d4, 0x11d0, {0xbb, 0xbf, 0x00, 0xaa, 0x00, 0x6c, 0x34, 0xe4}},
101 .dwCatalogEntryId = 1005,
102 .ProtocolChain.ChainLen = 1,
103 .iVersion = 2,
104 .iAddressFamily = WS_AF_INET6,
105 .iMaxSockAddr = sizeof(struct WS_sockaddr_in6),
106 .iMinSockAddr = sizeof(struct WS_sockaddr_in6),
107 .iSocketType = WS_SOCK_DGRAM,
108 .iProtocol = WS_IPPROTO_UDP,
109 .dwMessageSize = 0xffbb,
110 .szProtocol = {'U','D','P','/','I','P','v','6',0},
113 .dwServiceFlags1 = XP1_PARTIAL_MESSAGE | XP1_SUPPORT_BROADCAST
114 | XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED | XP1_CONNECTIONLESS,
115 .dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO,
116 .ProviderId = {0x11058240, 0xbe47, 0x11cf, {0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}},
117 .dwCatalogEntryId = 1030,
118 .ProtocolChain.ChainLen = 1,
119 .iVersion = 2,
120 .iAddressFamily = WS_AF_IPX,
121 .iMaxSockAddr = sizeof(struct WS_sockaddr),
122 .iMinSockAddr = sizeof(struct WS_sockaddr_ipx),
123 .iSocketType = WS_SOCK_DGRAM,
124 .iProtocol = WS_NSPROTO_IPX,
125 .iProtocolMaxOffset = 255,
126 .dwMessageSize = 0x240,
127 .szProtocol = {'I','P','X',0},
130 .dwServiceFlags1 = XP1_IFS_HANDLES | XP1_PSEUDO_STREAM | XP1_MESSAGE_ORIENTED
131 | XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY,
132 .dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO,
133 .ProviderId = {0x11058241, 0xbe47, 0x11cf, {0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}},
134 .dwCatalogEntryId = 1031,
135 .ProtocolChain.ChainLen = 1,
136 .iVersion = 2,
137 .iAddressFamily = WS_AF_IPX,
138 .iMaxSockAddr = sizeof(struct WS_sockaddr),
139 .iMinSockAddr = sizeof(struct WS_sockaddr_ipx),
140 .iSocketType = WS_SOCK_SEQPACKET,
141 .iProtocol = WS_NSPROTO_SPX,
142 .dwMessageSize = UINT_MAX,
143 .szProtocol = {'S','P','X',0},
146 .dwServiceFlags1 = XP1_IFS_HANDLES | XP1_GRACEFUL_CLOSE | XP1_PSEUDO_STREAM
147 | XP1_MESSAGE_ORIENTED | XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY,
148 .dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO,
149 .ProviderId = {0x11058241, 0xbe47, 0x11cf, {0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}},
150 .dwCatalogEntryId = 1033,
151 .ProtocolChain.ChainLen = 1,
152 .iVersion = 2,
153 .iAddressFamily = WS_AF_IPX,
154 .iMaxSockAddr = sizeof(struct WS_sockaddr),
155 .iMinSockAddr = sizeof(struct WS_sockaddr_ipx),
156 .iSocketType = WS_SOCK_SEQPACKET,
157 .iProtocol = WS_NSPROTO_SPXII,
158 .dwMessageSize = UINT_MAX,
159 .szProtocol = {'S','P','X',' ','I','I',0},
163 DECLARE_CRITICAL_SECTION(cs_socket_list);
165 static SOCKET *socket_list;
166 static unsigned int socket_list_size;
168 const char *debugstr_sockaddr( const struct WS_sockaddr *a )
170 if (!a) return "(nil)";
171 switch (a->sa_family)
173 case WS_AF_INET:
175 char buf[16];
176 const char *p;
177 struct WS_sockaddr_in *sin = (struct WS_sockaddr_in *)a;
179 p = WS_inet_ntop( WS_AF_INET, &sin->sin_addr, buf, sizeof(buf) );
180 if (!p)
181 p = "(unknown IPv4 address)";
183 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
184 p, ntohs(sin->sin_port));
186 case WS_AF_INET6:
188 char buf[46];
189 const char *p;
190 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
192 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
193 if (!p)
194 p = "(unknown IPv6 address)";
195 return wine_dbg_sprintf("{ family AF_INET6, address %s, flow label %#x, port %d, scope %u }",
196 p, sin->sin6_flowinfo, ntohs(sin->sin6_port), sin->sin6_scope_id );
198 case WS_AF_IPX:
200 int i;
201 char netnum[16], nodenum[16];
202 struct WS_sockaddr_ipx *sin = (struct WS_sockaddr_ipx *)a;
204 for (i = 0;i < 4; i++) sprintf(netnum + i * 2, "%02X", (unsigned char) sin->sa_netnum[i]);
205 for (i = 0;i < 6; i++) sprintf(nodenum + i * 2, "%02X", (unsigned char) sin->sa_nodenum[i]);
207 return wine_dbg_sprintf("{ family AF_IPX, address %s.%s, ipx socket %d }",
208 netnum, nodenum, sin->sa_socket);
210 case WS_AF_IRDA:
212 DWORD addr;
214 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
215 addr = ntohl( addr );
216 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
217 addr,
218 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
220 default:
221 return wine_dbg_sprintf("{ family %d }", a->sa_family);
225 static inline const char *debugstr_sockopt(int level, int optname)
227 const char *stropt = NULL, *strlevel = NULL;
229 #define DEBUG_SOCKLEVEL(x) case (x): strlevel = #x
230 #define DEBUG_SOCKOPT(x) case (x): stropt = #x; break
232 switch(level)
234 DEBUG_SOCKLEVEL(WS_SOL_SOCKET);
235 switch(optname)
237 DEBUG_SOCKOPT(WS_SO_ACCEPTCONN);
238 DEBUG_SOCKOPT(WS_SO_BROADCAST);
239 DEBUG_SOCKOPT(WS_SO_BSP_STATE);
240 DEBUG_SOCKOPT(WS_SO_CONDITIONAL_ACCEPT);
241 DEBUG_SOCKOPT(WS_SO_CONNECT_TIME);
242 DEBUG_SOCKOPT(WS_SO_DEBUG);
243 DEBUG_SOCKOPT(WS_SO_DONTLINGER);
244 DEBUG_SOCKOPT(WS_SO_DONTROUTE);
245 DEBUG_SOCKOPT(WS_SO_ERROR);
246 DEBUG_SOCKOPT(WS_SO_EXCLUSIVEADDRUSE);
247 DEBUG_SOCKOPT(WS_SO_GROUP_ID);
248 DEBUG_SOCKOPT(WS_SO_GROUP_PRIORITY);
249 DEBUG_SOCKOPT(WS_SO_KEEPALIVE);
250 DEBUG_SOCKOPT(WS_SO_LINGER);
251 DEBUG_SOCKOPT(WS_SO_MAX_MSG_SIZE);
252 DEBUG_SOCKOPT(WS_SO_OOBINLINE);
253 DEBUG_SOCKOPT(WS_SO_OPENTYPE);
254 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOA);
255 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOW);
256 DEBUG_SOCKOPT(WS_SO_RCVBUF);
257 DEBUG_SOCKOPT(WS_SO_RCVTIMEO);
258 DEBUG_SOCKOPT(WS_SO_REUSEADDR);
259 DEBUG_SOCKOPT(WS_SO_SNDBUF);
260 DEBUG_SOCKOPT(WS_SO_SNDTIMEO);
261 DEBUG_SOCKOPT(WS_SO_TYPE);
262 DEBUG_SOCKOPT(WS_SO_UPDATE_CONNECT_CONTEXT);
264 break;
266 DEBUG_SOCKLEVEL(WS_NSPROTO_IPX);
267 switch(optname)
269 DEBUG_SOCKOPT(WS_IPX_PTYPE);
270 DEBUG_SOCKOPT(WS_IPX_FILTERPTYPE);
271 DEBUG_SOCKOPT(WS_IPX_DSTYPE);
272 DEBUG_SOCKOPT(WS_IPX_RECVHDR);
273 DEBUG_SOCKOPT(WS_IPX_MAXSIZE);
274 DEBUG_SOCKOPT(WS_IPX_ADDRESS);
275 DEBUG_SOCKOPT(WS_IPX_MAX_ADAPTER_NUM);
277 break;
279 DEBUG_SOCKLEVEL(WS_SOL_IRLMP);
280 switch(optname)
282 DEBUG_SOCKOPT(WS_IRLMP_ENUMDEVICES);
284 break;
286 DEBUG_SOCKLEVEL(WS_IPPROTO_TCP);
287 switch(optname)
289 DEBUG_SOCKOPT(WS_TCP_BSDURGENT);
290 DEBUG_SOCKOPT(WS_TCP_EXPEDITED_1122);
291 DEBUG_SOCKOPT(WS_TCP_NODELAY);
293 break;
295 DEBUG_SOCKLEVEL(WS_IPPROTO_IP);
296 switch(optname)
298 DEBUG_SOCKOPT(WS_IP_ADD_MEMBERSHIP);
299 DEBUG_SOCKOPT(WS_IP_DONTFRAGMENT);
300 DEBUG_SOCKOPT(WS_IP_DROP_MEMBERSHIP);
301 DEBUG_SOCKOPT(WS_IP_HDRINCL);
302 DEBUG_SOCKOPT(WS_IP_MULTICAST_IF);
303 DEBUG_SOCKOPT(WS_IP_MULTICAST_LOOP);
304 DEBUG_SOCKOPT(WS_IP_MULTICAST_TTL);
305 DEBUG_SOCKOPT(WS_IP_OPTIONS);
306 DEBUG_SOCKOPT(WS_IP_PKTINFO);
307 DEBUG_SOCKOPT(WS_IP_RECEIVE_BROADCAST);
308 DEBUG_SOCKOPT(WS_IP_TOS);
309 DEBUG_SOCKOPT(WS_IP_TTL);
310 DEBUG_SOCKOPT(WS_IP_UNICAST_IF);
312 break;
314 DEBUG_SOCKLEVEL(WS_IPPROTO_IPV6);
315 switch(optname)
317 DEBUG_SOCKOPT(WS_IPV6_ADD_MEMBERSHIP);
318 DEBUG_SOCKOPT(WS_IPV6_DROP_MEMBERSHIP);
319 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_IF);
320 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_HOPS);
321 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_LOOP);
322 DEBUG_SOCKOPT(WS_IPV6_UNICAST_HOPS);
323 DEBUG_SOCKOPT(WS_IPV6_V6ONLY);
324 DEBUG_SOCKOPT(WS_IPV6_UNICAST_IF);
325 DEBUG_SOCKOPT(WS_IPV6_DONTFRAG);
327 break;
329 #undef DEBUG_SOCKLEVEL
330 #undef DEBUG_SOCKOPT
332 if (!strlevel)
333 strlevel = wine_dbg_sprintf("WS_0x%x", level);
334 if (!stropt)
335 stropt = wine_dbg_sprintf("WS_0x%x", optname);
337 return wine_dbg_sprintf("level %s, name %s", strlevel + 3, stropt + 3);
340 static inline const char *debugstr_optval(const char *optval, int optlenval)
342 if (optval && !IS_INTRESOURCE(optval) && optlenval >= 1 && optlenval <= sizeof(DWORD))
344 DWORD value = 0;
345 memcpy(&value, optval, optlenval);
346 return wine_dbg_sprintf("%p (%u)", optval, value);
348 return wine_dbg_sprintf("%p", optval);
351 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
352 #define SOCKET2HANDLE(s) ((HANDLE)(s))
353 #define HANDLE2SOCKET(h) ((SOCKET)(h))
355 static BOOL socket_list_add(SOCKET socket)
357 unsigned int i, new_size;
358 SOCKET *new_array;
360 EnterCriticalSection(&cs_socket_list);
361 for (i = 0; i < socket_list_size; ++i)
363 if (!socket_list[i])
365 socket_list[i] = socket;
366 LeaveCriticalSection(&cs_socket_list);
367 return TRUE;
370 new_size = max(socket_list_size * 2, 8);
371 if (!(new_array = heap_realloc(socket_list, new_size * sizeof(*socket_list))))
373 LeaveCriticalSection(&cs_socket_list);
374 return FALSE;
376 socket_list = new_array;
377 memset(socket_list + socket_list_size, 0, (new_size - socket_list_size) * sizeof(*socket_list));
378 socket_list[socket_list_size] = socket;
379 socket_list_size = new_size;
380 LeaveCriticalSection(&cs_socket_list);
381 return TRUE;
385 static BOOL socket_list_find( SOCKET socket )
387 unsigned int i;
389 EnterCriticalSection( &cs_socket_list );
390 for (i = 0; i < socket_list_size; ++i)
392 if (socket_list[i] == socket)
394 LeaveCriticalSection( &cs_socket_list );
395 return TRUE;
398 LeaveCriticalSection( &cs_socket_list );
399 return FALSE;
403 static void socket_list_remove(SOCKET socket)
405 unsigned int i;
407 EnterCriticalSection(&cs_socket_list);
408 for (i = 0; i < socket_list_size; ++i)
410 if (socket_list[i] == socket)
412 socket_list[i] = 0;
413 break;
416 LeaveCriticalSection(&cs_socket_list);
419 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
420 #define WS_MAX_UDP_DATAGRAM 1024
421 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
423 int num_startup;
424 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
426 /* function prototypes */
427 static int ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size);
429 #define MAP_OPTION(opt) { WS_##opt, opt }
431 static const int ws_sock_map[][2] =
433 MAP_OPTION( SO_DEBUG ),
434 MAP_OPTION( SO_ACCEPTCONN ),
435 MAP_OPTION( SO_REUSEADDR ),
436 MAP_OPTION( SO_KEEPALIVE ),
437 MAP_OPTION( SO_DONTROUTE ),
438 MAP_OPTION( SO_BROADCAST ),
439 MAP_OPTION( SO_LINGER ),
440 MAP_OPTION( SO_OOBINLINE ),
441 MAP_OPTION( SO_SNDBUF ),
442 MAP_OPTION( SO_RCVBUF ),
443 MAP_OPTION( SO_ERROR ),
444 MAP_OPTION( SO_TYPE ),
445 #ifdef SO_RCVTIMEO
446 MAP_OPTION( SO_RCVTIMEO ),
447 #endif
448 #ifdef SO_SNDTIMEO
449 MAP_OPTION( SO_SNDTIMEO ),
450 #endif
453 static const int ws_tcp_map[][2] =
455 #ifdef TCP_NODELAY
456 MAP_OPTION( TCP_NODELAY ),
457 #endif
460 static const int ws_ip_map[][2] =
462 MAP_OPTION( IP_MULTICAST_IF ),
463 MAP_OPTION( IP_MULTICAST_TTL ),
464 MAP_OPTION( IP_MULTICAST_LOOP ),
465 MAP_OPTION( IP_ADD_MEMBERSHIP ),
466 MAP_OPTION( IP_DROP_MEMBERSHIP ),
467 MAP_OPTION( IP_ADD_SOURCE_MEMBERSHIP ),
468 MAP_OPTION( IP_DROP_SOURCE_MEMBERSHIP ),
469 MAP_OPTION( IP_BLOCK_SOURCE ),
470 MAP_OPTION( IP_UNBLOCK_SOURCE ),
471 MAP_OPTION( IP_OPTIONS ),
472 #ifdef IP_HDRINCL
473 MAP_OPTION( IP_HDRINCL ),
474 #endif
475 MAP_OPTION( IP_TOS ),
476 MAP_OPTION( IP_TTL ),
477 #if defined(IP_PKTINFO)
478 MAP_OPTION( IP_PKTINFO ),
479 #elif defined(IP_RECVDSTADDR)
480 { WS_IP_PKTINFO, IP_RECVDSTADDR },
481 #endif
482 #ifdef IP_UNICAST_IF
483 MAP_OPTION( IP_UNICAST_IF ),
484 #endif
487 static const int ws_ipv6_map[][2] =
489 #ifdef IPV6_ADD_MEMBERSHIP
490 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
491 #endif
492 #ifdef IPV6_DROP_MEMBERSHIP
493 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
494 #endif
495 MAP_OPTION( IPV6_MULTICAST_IF ),
496 MAP_OPTION( IPV6_MULTICAST_HOPS ),
497 MAP_OPTION( IPV6_MULTICAST_LOOP ),
498 MAP_OPTION( IPV6_UNICAST_HOPS ),
499 MAP_OPTION( IPV6_V6ONLY ),
500 #ifdef IPV6_UNICAST_IF
501 MAP_OPTION( IPV6_UNICAST_IF ),
502 #endif
505 static const int ws_socktype_map[][2] =
507 MAP_OPTION( SOCK_DGRAM ),
508 MAP_OPTION( SOCK_STREAM ),
509 MAP_OPTION( SOCK_RAW ),
510 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
513 UINT sock_get_error( int err )
515 switch(err)
517 case EINTR: return WSAEINTR;
518 case EPERM:
519 case EACCES: return WSAEACCES;
520 case EFAULT: return WSAEFAULT;
521 case EINVAL: return WSAEINVAL;
522 case EMFILE: return WSAEMFILE;
523 case EINPROGRESS:
524 case EWOULDBLOCK: return WSAEWOULDBLOCK;
525 case EALREADY: return WSAEALREADY;
526 case EBADF:
527 case ENOTSOCK: return WSAENOTSOCK;
528 case EDESTADDRREQ: return WSAEDESTADDRREQ;
529 case EMSGSIZE: return WSAEMSGSIZE;
530 case EPROTOTYPE: return WSAEPROTOTYPE;
531 case ENOPROTOOPT: return WSAENOPROTOOPT;
532 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
533 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
534 case EOPNOTSUPP: return WSAEOPNOTSUPP;
535 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
536 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
537 case EADDRINUSE: return WSAEADDRINUSE;
538 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
539 case ENETDOWN: return WSAENETDOWN;
540 case ENETUNREACH: return WSAENETUNREACH;
541 case ENETRESET: return WSAENETRESET;
542 case ECONNABORTED: return WSAECONNABORTED;
543 case EPIPE:
544 case ECONNRESET: return WSAECONNRESET;
545 case ENOBUFS: return WSAENOBUFS;
546 case EISCONN: return WSAEISCONN;
547 case ENOTCONN: return WSAENOTCONN;
548 case ESHUTDOWN: return WSAESHUTDOWN;
549 case ETOOMANYREFS: return WSAETOOMANYREFS;
550 case ETIMEDOUT: return WSAETIMEDOUT;
551 case ECONNREFUSED: return WSAECONNREFUSED;
552 case ELOOP: return WSAELOOP;
553 case ENAMETOOLONG: return WSAENAMETOOLONG;
554 case EHOSTDOWN: return WSAEHOSTDOWN;
555 case EHOSTUNREACH: return WSAEHOSTUNREACH;
556 case ENOTEMPTY: return WSAENOTEMPTY;
557 #ifdef EPROCLIM
558 case EPROCLIM: return WSAEPROCLIM;
559 #endif
560 #ifdef EUSERS
561 case EUSERS: return WSAEUSERS;
562 #endif
563 #ifdef EDQUOT
564 case EDQUOT: return WSAEDQUOT;
565 #endif
566 #ifdef ESTALE
567 case ESTALE: return WSAESTALE;
568 #endif
569 #ifdef EREMOTE
570 case EREMOTE: return WSAEREMOTE;
571 #endif
573 /* just in case we ever get here and there are no problems */
574 case 0: return 0;
575 default:
576 WARN("Unknown errno %d!\n", err);
577 return WSAEOPNOTSUPP;
581 static UINT wsaErrno(void)
583 int loc_errno = errno;
584 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
586 return sock_get_error( loc_errno );
589 static DWORD NtStatusToWSAError( NTSTATUS status )
591 static const struct
593 NTSTATUS status;
594 DWORD error;
596 errors[] =
598 {STATUS_PENDING, ERROR_IO_PENDING},
600 {STATUS_BUFFER_OVERFLOW, WSAEMSGSIZE},
602 {STATUS_NOT_IMPLEMENTED, WSAEOPNOTSUPP},
603 {STATUS_ACCESS_VIOLATION, WSAEFAULT},
604 {STATUS_PAGEFILE_QUOTA, WSAENOBUFS},
605 {STATUS_INVALID_HANDLE, WSAENOTSOCK},
606 {STATUS_NO_SUCH_DEVICE, WSAENETDOWN},
607 {STATUS_NO_SUCH_FILE, WSAENETDOWN},
608 {STATUS_NO_MEMORY, WSAENOBUFS},
609 {STATUS_CONFLICTING_ADDRESSES, WSAENOBUFS},
610 {STATUS_ACCESS_DENIED, WSAEACCES},
611 {STATUS_BUFFER_TOO_SMALL, WSAEFAULT},
612 {STATUS_OBJECT_TYPE_MISMATCH, WSAENOTSOCK},
613 {STATUS_OBJECT_NAME_NOT_FOUND, WSAENETDOWN},
614 {STATUS_OBJECT_PATH_NOT_FOUND, WSAENETDOWN},
615 {STATUS_SHARING_VIOLATION, WSAEADDRINUSE},
616 {STATUS_QUOTA_EXCEEDED, WSAENOBUFS},
617 {STATUS_TOO_MANY_PAGING_FILES, WSAENOBUFS},
618 {STATUS_INSUFFICIENT_RESOURCES, WSAENOBUFS},
619 {STATUS_WORKING_SET_QUOTA, WSAENOBUFS},
620 {STATUS_DEVICE_NOT_READY, WSAEWOULDBLOCK},
621 {STATUS_PIPE_DISCONNECTED, WSAESHUTDOWN},
622 {STATUS_IO_TIMEOUT, WSAETIMEDOUT},
623 {STATUS_NOT_SUPPORTED, WSAEOPNOTSUPP},
624 {STATUS_REMOTE_NOT_LISTENING, WSAECONNREFUSED},
625 {STATUS_BAD_NETWORK_PATH, WSAENETUNREACH},
626 {STATUS_NETWORK_BUSY, WSAENETDOWN},
627 {STATUS_INVALID_NETWORK_RESPONSE, WSAENETDOWN},
628 {STATUS_UNEXPECTED_NETWORK_ERROR, WSAENETDOWN},
629 {STATUS_REQUEST_NOT_ACCEPTED, WSAEWOULDBLOCK},
630 {STATUS_CANCELLED, ERROR_OPERATION_ABORTED},
631 {STATUS_COMMITMENT_LIMIT, WSAENOBUFS},
632 {STATUS_LOCAL_DISCONNECT, WSAECONNABORTED},
633 {STATUS_REMOTE_DISCONNECT, WSAECONNRESET},
634 {STATUS_REMOTE_RESOURCES, WSAENOBUFS},
635 {STATUS_LINK_FAILED, WSAECONNRESET},
636 {STATUS_LINK_TIMEOUT, WSAETIMEDOUT},
637 {STATUS_INVALID_CONNECTION, WSAENOTCONN},
638 {STATUS_INVALID_ADDRESS, WSAEADDRNOTAVAIL},
639 {STATUS_INVALID_BUFFER_SIZE, WSAEMSGSIZE},
640 {STATUS_INVALID_ADDRESS_COMPONENT, WSAEADDRNOTAVAIL},
641 {STATUS_TOO_MANY_ADDRESSES, WSAENOBUFS},
642 {STATUS_ADDRESS_ALREADY_EXISTS, WSAEADDRINUSE},
643 {STATUS_CONNECTION_DISCONNECTED, WSAECONNRESET},
644 {STATUS_CONNECTION_RESET, WSAECONNRESET},
645 {STATUS_TRANSACTION_ABORTED, WSAECONNABORTED},
646 {STATUS_CONNECTION_REFUSED, WSAECONNREFUSED},
647 {STATUS_GRACEFUL_DISCONNECT, WSAEDISCON},
648 {STATUS_CONNECTION_ACTIVE, WSAEISCONN},
649 {STATUS_NETWORK_UNREACHABLE, WSAENETUNREACH},
650 {STATUS_HOST_UNREACHABLE, WSAEHOSTUNREACH},
651 {STATUS_PROTOCOL_UNREACHABLE, WSAENETUNREACH},
652 {STATUS_PORT_UNREACHABLE, WSAECONNRESET},
653 {STATUS_REQUEST_ABORTED, WSAEINTR},
654 {STATUS_CONNECTION_ABORTED, WSAECONNABORTED},
655 {STATUS_DATATYPE_MISALIGNMENT_ERROR,WSAEFAULT},
656 {STATUS_HOST_DOWN, WSAEHOSTDOWN},
657 {0x80070000 | ERROR_IO_INCOMPLETE, ERROR_IO_INCOMPLETE},
658 {0xc0010000 | ERROR_IO_INCOMPLETE, ERROR_IO_INCOMPLETE},
659 {0xc0070000 | ERROR_IO_INCOMPLETE, ERROR_IO_INCOMPLETE},
662 unsigned int i;
664 for (i = 0; i < ARRAY_SIZE(errors); ++i)
666 if (errors[i].status == status)
667 return errors[i].error;
670 return NT_SUCCESS(status) ? RtlNtStatusToDosErrorNoTeb(status) : WSAEINVAL;
673 /* set last error code from NT status without mapping WSA errors */
674 static inline unsigned int set_error( unsigned int err )
676 if (err)
678 err = NtStatusToWSAError( err );
679 SetLastError( err );
681 return err;
684 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
686 int fd;
687 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
688 return -1;
689 return fd;
692 static inline void release_sock_fd( SOCKET s, int fd )
694 close( fd );
697 struct per_thread_data *get_per_thread_data(void)
699 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
700 /* lazy initialization */
701 if (!ptb)
703 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
704 NtCurrentTeb()->WinSockData = ptb;
706 return ptb;
709 static void free_per_thread_data(void)
711 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
713 if (!ptb) return;
715 CloseHandle( ptb->sync_event );
717 /* delete scratch buffers */
718 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
719 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
720 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
722 HeapFree( GetProcessHeap(), 0, ptb );
723 NtCurrentTeb()->WinSockData = NULL;
726 static HANDLE get_sync_event(void)
728 struct per_thread_data *data;
730 if (!(data = get_per_thread_data())) return NULL;
731 if (!data->sync_event)
732 data->sync_event = CreateEventW( NULL, TRUE, FALSE, NULL );
733 return data->sync_event;
736 /***********************************************************************
737 * DllMain (WS2_32.init)
739 BOOL WINAPI DllMain( HINSTANCE instance, DWORD reason, void *reserved )
741 if (reason == DLL_THREAD_DETACH)
742 free_per_thread_data();
743 return TRUE;
746 /***********************************************************************
747 * convert_sockopt()
749 * Converts socket flags from Windows format.
750 * Return 1 if converted, 0 if not (error).
752 static int convert_sockopt(INT *level, INT *optname)
754 unsigned int i;
755 switch (*level)
757 case WS_SOL_SOCKET:
758 *level = SOL_SOCKET;
759 for(i = 0; i < ARRAY_SIZE(ws_sock_map); i++) {
760 if( ws_sock_map[i][0] == *optname )
762 *optname = ws_sock_map[i][1];
763 return 1;
766 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
767 break;
768 case WS_IPPROTO_TCP:
769 *level = IPPROTO_TCP;
770 for(i = 0; i < ARRAY_SIZE(ws_tcp_map); i++) {
771 if ( ws_tcp_map[i][0] == *optname )
773 *optname = ws_tcp_map[i][1];
774 return 1;
777 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
778 break;
779 case WS_IPPROTO_IP:
780 *level = IPPROTO_IP;
781 for(i = 0; i < ARRAY_SIZE(ws_ip_map); i++) {
782 if (ws_ip_map[i][0] == *optname )
784 *optname = ws_ip_map[i][1];
785 return 1;
788 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
789 break;
790 case WS_IPPROTO_IPV6:
791 *level = IPPROTO_IPV6;
792 for(i = 0; i < ARRAY_SIZE(ws_ipv6_map); i++) {
793 if (ws_ipv6_map[i][0] == *optname )
795 *optname = ws_ipv6_map[i][1];
796 return 1;
799 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
800 break;
801 default: FIXME("Unimplemented or unknown socket level\n");
803 return 0;
807 convert_socktype_w2u(int windowssocktype) {
808 unsigned int i;
810 for (i = 0; i < ARRAY_SIZE(ws_socktype_map); i++)
811 if (ws_socktype_map[i][0] == windowssocktype)
812 return ws_socktype_map[i][1];
813 FIXME("unhandled Windows socket type %d\n", windowssocktype);
814 return -1;
818 convert_socktype_u2w(int unixsocktype) {
819 unsigned int i;
821 for (i = 0; i < ARRAY_SIZE(ws_socktype_map); i++)
822 if (ws_socktype_map[i][1] == unixsocktype)
823 return ws_socktype_map[i][0];
824 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
825 return -1;
828 static int set_ipx_packettype(int sock, int ptype)
830 #ifdef HAS_IPX
831 int fd = get_sock_fd( sock, 0, NULL ), ret = 0;
832 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype, fd);
834 if (fd == -1) return SOCKET_ERROR;
836 /* We try to set the ipx type on ipx socket level. */
837 #ifdef SOL_IPX
838 if(setsockopt(fd, SOL_IPX, IPX_TYPE, &ptype, sizeof(ptype)) == -1)
840 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
841 ret = SOCKET_ERROR;
843 #else
845 struct ipx val;
846 /* Should we retrieve val using a getsockopt call and then
847 * set the modified one? */
848 val.ipx_pt = ptype;
849 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
851 #endif
852 release_sock_fd( sock, fd );
853 return ret;
854 #else
855 WARN("IPX support is not enabled, can't set packet type\n");
856 return SOCKET_ERROR;
857 #endif
860 /* ----------------------------------- API -----
862 * Init / cleanup / error checking.
865 /***********************************************************************
866 * WSAStartup (WS2_32.115)
868 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
870 TRACE("verReq=%x\n", wVersionRequested);
872 if (LOBYTE(wVersionRequested) < 1)
873 return WSAVERNOTSUPPORTED;
875 if (!lpWSAData) return WSAEINVAL;
877 num_startup++;
879 /* that's the whole of the negotiation for now */
880 lpWSAData->wVersion = wVersionRequested;
881 /* return winsock information */
882 lpWSAData->wHighVersion = 0x0202;
883 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
884 strcpy(lpWSAData->szSystemStatus, "Running" );
885 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
886 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
887 /* don't do anything with lpWSAData->lpVendorInfo */
888 /* (some apps don't allocate the space for this field) */
890 TRACE("succeeded starts: %d\n", num_startup);
891 return 0;
895 /***********************************************************************
896 * WSACleanup (WS2_32.116)
898 INT WINAPI WSACleanup(void)
900 TRACE("decreasing startup count from %d\n", num_startup);
901 if (num_startup)
903 if (!--num_startup)
905 unsigned int i;
907 for (i = 0; i < socket_list_size; ++i)
908 CloseHandle(SOCKET2HANDLE(socket_list[i]));
909 memset(socket_list, 0, socket_list_size * sizeof(*socket_list));
911 return 0;
913 SetLastError(WSANOTINITIALISED);
914 return SOCKET_ERROR;
918 /***********************************************************************
919 * WSAGetLastError (WS2_32.111)
921 INT WINAPI WSAGetLastError(void)
923 return GetLastError();
926 /***********************************************************************
927 * WSASetLastError (WS2_32.112)
929 void WINAPI WSASetLastError(INT iError) {
930 SetLastError(iError);
933 static inline BOOL supported_pf(int pf)
935 switch (pf)
937 case WS_AF_INET:
938 case WS_AF_INET6:
939 return TRUE;
940 #ifdef HAS_IPX
941 case WS_AF_IPX:
942 return TRUE;
943 #endif
944 #ifdef HAS_IRDA
945 case WS_AF_IRDA:
946 return TRUE;
947 #endif
948 default:
949 return FALSE;
953 /**********************************************************************/
955 /* Returns the length of the converted address if successful, 0 if it was too
956 * small to start with or unknown family or invalid address buffer.
958 unsigned int ws_sockaddr_ws2u( const struct WS_sockaddr *wsaddr, int wsaddrlen,
959 union generic_unix_sockaddr *uaddr )
961 unsigned int uaddrlen = 0;
963 if (!wsaddr)
964 return 0;
966 switch (wsaddr->sa_family)
968 #ifdef HAS_IPX
969 case WS_AF_IPX:
971 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
972 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
974 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
975 return 0;
977 uaddrlen = sizeof(struct sockaddr_ipx);
978 memset( uaddr, 0, uaddrlen );
979 uipx->sipx_family=AF_IPX;
980 uipx->sipx_port=wsipx->sa_socket;
981 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
982 * in one go
984 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
985 #ifdef IPX_FRAME_NONE
986 uipx->sipx_type=IPX_FRAME_NONE;
987 #endif
988 break;
990 #endif
991 case WS_AF_INET6: {
992 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
993 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
995 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
996 * scope_id, one without.
998 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
999 uaddrlen = sizeof(struct sockaddr_in6);
1000 memset( uaddr, 0, uaddrlen );
1001 uin6->sin6_family = AF_INET6;
1002 uin6->sin6_port = win6->sin6_port;
1003 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1004 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1005 uin6->sin6_scope_id = win6->sin6_scope_id;
1006 #endif
1007 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1008 break;
1010 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1011 return 0;
1013 case WS_AF_INET: {
1014 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1015 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1017 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1018 return 0;
1019 uaddrlen = sizeof(struct sockaddr_in);
1020 memset( uaddr, 0, uaddrlen );
1021 uin->sin_family = AF_INET;
1022 uin->sin_port = win->sin_port;
1023 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1024 break;
1026 #ifdef HAS_IRDA
1027 case WS_AF_IRDA: {
1028 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1029 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1031 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1032 return 0;
1033 uaddrlen = sizeof(struct sockaddr_irda);
1034 memset( uaddr, 0, uaddrlen );
1035 uin->sir_family = AF_IRDA;
1036 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1038 unsigned int lsap_sel = 0;
1040 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1041 uin->sir_lsap_sel = lsap_sel;
1043 else
1045 uin->sir_lsap_sel = LSAP_ANY;
1046 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1048 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1049 break;
1051 #endif
1052 case WS_AF_UNSPEC: {
1053 /* Try to determine the needed space by the passed windows sockaddr space */
1054 switch (wsaddrlen) {
1055 default: /* likely an ipv4 address */
1056 case sizeof(struct WS_sockaddr_in):
1057 uaddrlen = sizeof(struct sockaddr_in);
1058 break;
1059 #ifdef HAS_IPX
1060 case sizeof(struct WS_sockaddr_ipx):
1061 uaddrlen = sizeof(struct sockaddr_ipx);
1062 break;
1063 #endif
1064 #ifdef HAS_IRDA
1065 case sizeof(SOCKADDR_IRDA):
1066 uaddrlen = sizeof(struct sockaddr_irda);
1067 break;
1068 #endif
1069 case sizeof(struct WS_sockaddr_in6):
1070 case sizeof(struct WS_sockaddr_in6_old):
1071 uaddrlen = sizeof(struct sockaddr_in6);
1072 break;
1074 memset( uaddr, 0, uaddrlen );
1075 break;
1077 default:
1078 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1079 return 0;
1081 return uaddrlen;
1084 /* Returns 0 if successful, -1 if the buffer is too small */
1085 int ws_sockaddr_u2ws(const struct sockaddr *uaddr, struct WS_sockaddr *wsaddr, int *wsaddrlen)
1087 int res;
1089 switch(uaddr->sa_family)
1091 #ifdef HAS_IPX
1092 case AF_IPX:
1094 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1095 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1097 res=-1;
1098 switch (*wsaddrlen) /* how much can we copy? */
1100 default:
1101 res=0; /* enough */
1102 *wsaddrlen = sizeof(*wsipx);
1103 wsipx->sa_socket=uipx->sipx_port;
1104 /* fall through */
1105 case 13:
1106 case 12:
1107 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1108 /* fall through */
1109 case 11:
1110 case 10:
1111 case 9:
1112 case 8:
1113 case 7:
1114 case 6:
1115 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1116 /* fall through */
1117 case 5:
1118 case 4:
1119 case 3:
1120 case 2:
1121 wsipx->sa_family=WS_AF_IPX;
1122 /* fall through */
1123 case 1:
1124 case 0:
1125 /* way too small */
1126 break;
1129 break;
1130 #endif
1131 #ifdef HAS_IRDA
1132 case AF_IRDA: {
1133 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1134 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1136 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1137 return -1;
1138 win->irdaAddressFamily = WS_AF_IRDA;
1139 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1140 if (uin->sir_lsap_sel != LSAP_ANY)
1141 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1142 else
1143 memcpy( win->irdaServiceName, uin->sir_name,
1144 sizeof(win->irdaServiceName) );
1145 return 0;
1147 #endif
1148 case AF_INET6: {
1149 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1150 struct WS_sockaddr_in6 *win6 = (struct WS_sockaddr_in6 *)wsaddr;
1152 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6))
1153 return -1;
1154 win6->sin6_family = WS_AF_INET6;
1155 win6->sin6_port = uin6->sin6_port;
1156 win6->sin6_flowinfo = uin6->sin6_flowinfo;
1157 memcpy(&win6->sin6_addr, &uin6->sin6_addr, 16); /* 16 bytes = 128 address bits */
1158 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1159 win6->sin6_scope_id = uin6->sin6_scope_id;
1160 #else
1161 win6->sin6_scope_id = 0;
1162 #endif
1163 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1164 return 0;
1166 case AF_INET: {
1167 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1168 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1170 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1171 return -1;
1172 win->sin_family = WS_AF_INET;
1173 win->sin_port = uin->sin_port;
1174 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1175 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1176 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1177 return 0;
1179 case AF_UNSPEC: {
1180 memset(wsaddr,0,*wsaddrlen);
1181 return 0;
1183 default:
1184 FIXME("Unknown address family %d\n", uaddr->sa_family);
1185 return -1;
1187 return res;
1190 static INT WS_DuplicateSocket(BOOL unicode, SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo)
1192 HANDLE hProcess;
1193 int size;
1194 WSAPROTOCOL_INFOW infow;
1196 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
1197 unicode, s, dwProcessId, lpProtocolInfo);
1199 if (!ws_protocol_info(s, unicode, &infow, &size))
1200 return SOCKET_ERROR;
1202 if (!(hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId)))
1204 SetLastError(WSAEINVAL);
1205 return SOCKET_ERROR;
1208 if (!lpProtocolInfo)
1210 CloseHandle(hProcess);
1211 SetLastError(WSAEFAULT);
1212 return SOCKET_ERROR;
1215 /* I don't know what the real Windoze does next, this is a hack */
1216 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
1217 * the target use the global duplicate, or we could copy a reference to us to the structure
1218 * and let the target duplicate it from us, but let's do it as simple as possible */
1219 memcpy(lpProtocolInfo, &infow, size);
1220 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
1221 hProcess, (LPHANDLE)&lpProtocolInfo->dwServiceFlags3,
1222 0, FALSE, DUPLICATE_SAME_ACCESS);
1223 CloseHandle(hProcess);
1224 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
1225 return 0;
1228 static BOOL ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size)
1230 struct afd_get_info_params params;
1231 IO_STATUS_BLOCK io;
1232 NTSTATUS status;
1233 unsigned int i;
1235 *size = unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA);
1236 memset(buffer, 0, *size);
1238 status = NtDeviceIoControlFile( (HANDLE)s, NULL, NULL, NULL, &io,
1239 IOCTL_AFD_WINE_GET_INFO, NULL, 0, &params, sizeof(params) );
1240 if (status)
1242 SetLastError( NtStatusToWSAError( status ) );
1243 return FALSE;
1246 for (i = 0; i < ARRAY_SIZE(supported_protocols); ++i)
1248 const WSAPROTOCOL_INFOW *info = &supported_protocols[i];
1249 if (params.family == info->iAddressFamily &&
1250 params.type == info->iSocketType &&
1251 params.protocol >= info->iProtocol &&
1252 params.protocol <= info->iProtocol + info->iProtocolMaxOffset)
1254 if (unicode)
1255 *buffer = *info;
1256 else
1258 WSAPROTOCOL_INFOA *bufferA = (WSAPROTOCOL_INFOA *)buffer;
1259 memcpy( bufferA, info, offsetof( WSAPROTOCOL_INFOW, szProtocol ) );
1260 WideCharToMultiByte( CP_ACP, 0, info->szProtocol, -1,
1261 bufferA->szProtocol, sizeof(bufferA->szProtocol), NULL, NULL );
1263 buffer->iProtocol = params.protocol;
1264 return TRUE;
1267 FIXME( "Could not fill protocol information for family %d, type %d, protocol %d.\n",
1268 params.family, params.type, params.protocol );
1269 return TRUE;
1274 /***********************************************************************
1275 * accept (WS2_32.1)
1277 SOCKET WINAPI WS_accept( SOCKET s, struct WS_sockaddr *addr, int *len )
1279 IO_STATUS_BLOCK io;
1280 NTSTATUS status;
1281 obj_handle_t accept_handle;
1282 HANDLE sync_event;
1283 SOCKET ret;
1285 TRACE("%#lx\n", s);
1287 if (!(sync_event = get_sync_event())) return INVALID_SOCKET;
1288 status = NtDeviceIoControlFile( (HANDLE)s, sync_event, NULL, NULL, &io, IOCTL_AFD_WINE_ACCEPT,
1289 NULL, 0, &accept_handle, sizeof(accept_handle) );
1290 if (status == STATUS_PENDING)
1292 if (WaitForSingleObject( sync_event, INFINITE ) == WAIT_FAILED)
1293 return SOCKET_ERROR;
1294 status = io.u.Status;
1296 if (status)
1298 WARN("failed; status %#x\n", status);
1299 WSASetLastError( NtStatusToWSAError( status ) );
1300 return INVALID_SOCKET;
1303 ret = HANDLE2SOCKET(wine_server_ptr_handle( accept_handle ));
1304 if (!socket_list_add( ret ))
1306 CloseHandle( SOCKET2HANDLE(ret) );
1307 return INVALID_SOCKET;
1309 if (addr && len && WS_getpeername( ret, addr, len ))
1311 WS_closesocket( ret );
1312 return INVALID_SOCKET;
1315 TRACE("returning %#lx\n", ret);
1316 return ret;
1319 /***********************************************************************
1320 * AcceptEx
1322 static BOOL WINAPI WS2_AcceptEx( SOCKET listener, SOCKET acceptor, void *dest, DWORD recv_len,
1323 DWORD local_len, DWORD remote_len, DWORD *ret_len, OVERLAPPED *overlapped)
1325 struct afd_accept_into_params params =
1327 .accept_handle = acceptor,
1328 .recv_len = recv_len,
1329 .local_len = local_len,
1331 void *cvalue = NULL;
1332 NTSTATUS status;
1334 TRACE( "listener %#lx, acceptor %#lx, dest %p, recv_len %u, local_len %u, remote_len %u, ret_len %p, "
1335 "overlapped %p\n", listener, acceptor, dest, recv_len, local_len, remote_len, ret_len, overlapped );
1337 if (!overlapped)
1339 SetLastError(WSA_INVALID_PARAMETER);
1340 return FALSE;
1343 if (!((ULONG_PTR)overlapped->hEvent & 1)) cvalue = overlapped;
1344 overlapped->Internal = STATUS_PENDING;
1345 overlapped->InternalHigh = 0;
1347 if (!dest)
1349 SetLastError(WSAEINVAL);
1350 return FALSE;
1353 if (!remote_len)
1355 SetLastError(WSAEFAULT);
1356 return FALSE;
1359 status = NtDeviceIoControlFile( SOCKET2HANDLE(listener), overlapped->hEvent, NULL, cvalue,
1360 (IO_STATUS_BLOCK *)overlapped, IOCTL_AFD_WINE_ACCEPT_INTO, &params, sizeof(params),
1361 dest, recv_len + local_len + remote_len );
1363 if (ret_len) *ret_len = overlapped->InternalHigh;
1364 WSASetLastError( NtStatusToWSAError(status) );
1365 return !status;
1369 static BOOL WINAPI WS2_TransmitFile( SOCKET s, HANDLE file, DWORD file_len, DWORD buffer_size,
1370 OVERLAPPED *overlapped, TRANSMIT_FILE_BUFFERS *buffers, DWORD flags )
1372 struct afd_transmit_params params = {0};
1373 IO_STATUS_BLOCK iosb, *piosb = &iosb;
1374 HANDLE event = NULL;
1375 void *cvalue = NULL;
1376 NTSTATUS status;
1378 TRACE( "socket %#lx, file %p, file_len %u, buffer_size %u, overlapped %p, buffers %p, flags %#x\n",
1379 s, file, file_len, buffer_size, overlapped, buffers, flags );
1381 if (overlapped)
1383 piosb = (IO_STATUS_BLOCK *)overlapped;
1384 if (!((ULONG_PTR)overlapped->hEvent & 1)) cvalue = overlapped;
1385 event = overlapped->hEvent;
1386 overlapped->Internal = STATUS_PENDING;
1387 overlapped->InternalHigh = 0;
1388 params.offset.u.LowPart = overlapped->u.s.Offset;
1389 params.offset.u.HighPart = overlapped->u.s.OffsetHigh;
1391 else
1393 if (!(event = get_sync_event())) return -1;
1394 params.offset.QuadPart = FILE_USE_FILE_POINTER_POSITION;
1397 params.file = file;
1398 params.file_len = file_len;
1399 params.buffer_size = buffer_size;
1400 if (buffers) params.buffers = *buffers;
1401 params.flags = flags;
1403 status = NtDeviceIoControlFile( (HANDLE)s, event, NULL, cvalue, piosb,
1404 IOCTL_AFD_WINE_TRANSMIT, &params, sizeof(params), NULL, 0 );
1405 if (status == STATUS_PENDING && !overlapped)
1407 if (WaitForSingleObject( event, INFINITE ) == WAIT_FAILED)
1408 return FALSE;
1409 status = piosb->u.Status;
1411 SetLastError( NtStatusToWSAError( status ) );
1412 return !status;
1416 /***********************************************************************
1417 * GetAcceptExSockaddrs
1419 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
1420 struct WS_sockaddr **local_addr, LPINT local_addr_len,
1421 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
1423 char *cbuf = buffer;
1424 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
1425 local_addr_len, remote_addr, remote_addr_len );
1426 cbuf += data_size;
1428 *local_addr_len = *(int *) cbuf;
1429 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
1431 cbuf += local_size;
1433 *remote_addr_len = *(int *) cbuf;
1434 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
1438 static void WINAPI socket_apc( void *apc_user, IO_STATUS_BLOCK *io, ULONG reserved )
1440 LPWSAOVERLAPPED_COMPLETION_ROUTINE func = apc_user;
1441 func( NtStatusToWSAError( io->u.Status ), io->Information, (OVERLAPPED *)io, 0 );
1444 static int WS2_recv_base( SOCKET s, WSABUF *buffers, DWORD buffer_count, DWORD *ret_size, DWORD *flags,
1445 struct WS_sockaddr *addr, int *addr_len, OVERLAPPED *overlapped,
1446 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion, WSABUF *control )
1448 IO_STATUS_BLOCK iosb, *piosb = &iosb;
1449 struct afd_recvmsg_params params;
1450 PIO_APC_ROUTINE apc = NULL;
1451 HANDLE event = NULL;
1452 void *cvalue = NULL;
1453 NTSTATUS status;
1455 TRACE( "socket %#lx, buffers %p, buffer_count %u, flags %#x, addr %p, "
1456 "addr_len %d, overlapped %p, completion %p, control %p\n",
1457 s, buffers, buffer_count, *flags, addr, addr_len ? *addr_len : -1, overlapped, completion, control );
1459 if (overlapped)
1461 piosb = (IO_STATUS_BLOCK *)overlapped;
1462 if (!((ULONG_PTR)overlapped->hEvent & 1)) cvalue = overlapped;
1463 event = overlapped->hEvent;
1465 else
1467 if (!(event = get_sync_event())) return -1;
1469 piosb->u.Status = STATUS_PENDING;
1471 if (completion)
1473 event = NULL;
1474 cvalue = completion;
1475 apc = socket_apc;
1478 params.control = control;
1479 params.addr = addr;
1480 params.addr_len = addr_len;
1481 params.ws_flags = flags;
1482 params.force_async = !!overlapped;
1483 params.count = buffer_count;
1484 params.buffers = buffers;
1486 status = NtDeviceIoControlFile( (HANDLE)s, event, apc, cvalue, piosb,
1487 IOCTL_AFD_WINE_RECVMSG, &params, sizeof(params), NULL, 0 );
1488 if (status == STATUS_PENDING && !overlapped)
1490 if (WaitForSingleObject( event, INFINITE ) == WAIT_FAILED)
1491 return -1;
1492 status = piosb->u.Status;
1494 if (!status && ret_size) *ret_size = piosb->Information;
1495 SetLastError( NtStatusToWSAError( status ) );
1496 return status ? -1 : 0;
1499 static int WS2_sendto( SOCKET s, WSABUF *buffers, DWORD buffer_count, DWORD *ret_size, DWORD flags,
1500 const struct WS_sockaddr *addr, int addr_len, OVERLAPPED *overlapped,
1501 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
1503 IO_STATUS_BLOCK iosb, *piosb = &iosb;
1504 struct afd_sendmsg_params params;
1505 PIO_APC_ROUTINE apc = NULL;
1506 HANDLE event = NULL;
1507 void *cvalue = NULL;
1508 NTSTATUS status;
1510 TRACE( "socket %#lx, buffers %p, buffer_count %u, flags %#x, addr %p, "
1511 "addr_len %d, overlapped %p, completion %p\n",
1512 s, buffers, buffer_count, flags, addr, addr_len, overlapped, completion );
1514 if (!socket_list_find( s ))
1516 SetLastError( WSAENOTSOCK );
1517 return -1;
1520 if (!overlapped && !ret_size)
1522 SetLastError( WSAEFAULT );
1523 return -1;
1526 if (overlapped)
1528 piosb = (IO_STATUS_BLOCK *)overlapped;
1529 if (!((ULONG_PTR)overlapped->hEvent & 1)) cvalue = overlapped;
1530 event = overlapped->hEvent;
1532 else
1534 if (!(event = get_sync_event())) return -1;
1536 piosb->u.Status = STATUS_PENDING;
1538 if (completion)
1540 event = NULL;
1541 cvalue = completion;
1542 apc = socket_apc;
1545 params.addr = addr;
1546 params.addr_len = addr_len;
1547 params.ws_flags = flags;
1548 params.force_async = !!overlapped;
1549 params.count = buffer_count;
1550 params.buffers = buffers;
1552 status = NtDeviceIoControlFile( (HANDLE)s, event, apc, cvalue, piosb,
1553 IOCTL_AFD_WINE_SENDMSG, &params, sizeof(params), NULL, 0 );
1554 if (status == STATUS_PENDING && !overlapped)
1556 if (WaitForSingleObject( event, INFINITE ) == WAIT_FAILED)
1557 return -1;
1558 status = piosb->u.Status;
1560 if (!status && ret_size) *ret_size = piosb->Information;
1561 SetLastError( NtStatusToWSAError( status ) );
1562 return status ? -1 : 0;
1566 /***********************************************************************
1567 * WSASendMsg
1569 int WINAPI WSASendMsg( SOCKET s, LPWSAMSG msg, DWORD dwFlags, LPDWORD lpNumberOfBytesSent,
1570 LPWSAOVERLAPPED lpOverlapped,
1571 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
1573 if (!msg)
1575 SetLastError( WSAEFAULT );
1576 return SOCKET_ERROR;
1579 return WS2_sendto( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesSent,
1580 dwFlags, msg->name, msg->namelen,
1581 lpOverlapped, lpCompletionRoutine );
1584 /***********************************************************************
1585 * WSARecvMsg
1587 * Perform a receive operation that is capable of returning message
1588 * control headers. It is important to note that the WSAMSG parameter
1589 * must remain valid throughout the operation, even when an overlapped
1590 * receive is performed.
1592 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
1593 LPWSAOVERLAPPED lpOverlapped,
1594 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
1596 if (!msg)
1598 SetLastError( WSAEFAULT );
1599 return SOCKET_ERROR;
1602 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
1603 &msg->dwFlags, msg->name, &msg->namelen,
1604 lpOverlapped, lpCompletionRoutine, &msg->Control );
1608 /***********************************************************************
1609 * bind (ws2_32.2)
1611 int WINAPI WS_bind( SOCKET s, const struct WS_sockaddr *addr, int len )
1613 struct afd_bind_params *params;
1614 struct WS_sockaddr *ret_addr;
1615 IO_STATUS_BLOCK io;
1616 HANDLE sync_event;
1617 NTSTATUS status;
1619 TRACE( "socket %#lx, addr %s\n", s, debugstr_sockaddr(addr) );
1621 if (!addr)
1623 SetLastError( WSAEAFNOSUPPORT );
1624 return -1;
1627 switch (addr->sa_family)
1629 case WS_AF_INET:
1630 if (len < sizeof(struct WS_sockaddr_in))
1632 SetLastError( WSAEFAULT );
1633 return -1;
1635 break;
1637 case WS_AF_INET6:
1638 if (len < sizeof(struct WS_sockaddr_in6))
1640 SetLastError( WSAEFAULT );
1641 return -1;
1643 break;
1645 case WS_AF_IPX:
1646 if (len < sizeof(struct WS_sockaddr_ipx))
1648 SetLastError( WSAEFAULT );
1649 return -1;
1651 break;
1653 case WS_AF_IRDA:
1654 if (len < sizeof(SOCKADDR_IRDA))
1656 SetLastError( WSAEFAULT );
1657 return -1;
1659 break;
1661 default:
1662 FIXME( "unknown protocol %u\n", addr->sa_family );
1663 SetLastError( WSAEAFNOSUPPORT );
1664 return -1;
1667 if (!(sync_event = get_sync_event())) return -1;
1669 params = HeapAlloc( GetProcessHeap(), 0, sizeof(int) + len );
1670 ret_addr = HeapAlloc( GetProcessHeap(), 0, len );
1671 if (!params || !ret_addr)
1673 HeapFree( GetProcessHeap(), 0, params );
1674 HeapFree( GetProcessHeap(), 0, ret_addr );
1675 SetLastError( WSAENOBUFS );
1676 return -1;
1678 params->unknown = 0;
1679 memcpy( &params->addr, addr, len );
1681 status = NtDeviceIoControlFile( (HANDLE)s, sync_event, NULL, NULL, &io, IOCTL_AFD_BIND,
1682 params, sizeof(int) + len, ret_addr, len );
1683 if (status == STATUS_PENDING)
1685 if (WaitForSingleObject( sync_event, INFINITE ) == WAIT_FAILED)
1686 return -1;
1687 status = io.u.Status;
1690 HeapFree( GetProcessHeap(), 0, params );
1691 HeapFree( GetProcessHeap(), 0, ret_addr );
1693 SetLastError( NtStatusToWSAError( status ) );
1694 return status ? -1 : 0;
1698 /***********************************************************************
1699 * closesocket (WS2_32.3)
1701 int WINAPI WS_closesocket(SOCKET s)
1703 int res = SOCKET_ERROR, fd;
1704 if (num_startup)
1706 fd = get_sock_fd(s, FILE_READ_DATA, NULL);
1707 if (fd >= 0)
1709 release_sock_fd(s, fd);
1710 socket_list_remove(s);
1711 if (CloseHandle(SOCKET2HANDLE(s)))
1712 res = 0;
1715 else
1716 SetLastError(WSANOTINITIALISED);
1717 TRACE("(socket %04lx) -> %d\n", s, res);
1718 return res;
1722 /***********************************************************************
1723 * connect (ws2_32.4)
1725 int WINAPI WS_connect( SOCKET s, const struct WS_sockaddr *addr, int len )
1727 struct afd_connect_params *params;
1728 IO_STATUS_BLOCK io;
1729 HANDLE sync_event;
1730 NTSTATUS status;
1732 TRACE( "socket %#lx, addr %s, len %d\n", s, debugstr_sockaddr(addr), len );
1734 if (!(sync_event = get_sync_event())) return -1;
1736 if (!(params = HeapAlloc( GetProcessHeap(), 0, sizeof(*params) + len )))
1738 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1739 return -1;
1741 params->addr_len = len;
1742 params->synchronous = TRUE;
1743 memcpy( params + 1, addr, len );
1745 status = NtDeviceIoControlFile( (HANDLE)s, sync_event, NULL, NULL, &io, IOCTL_AFD_WINE_CONNECT,
1746 params, sizeof(*params) + len, NULL, 0 );
1747 HeapFree( GetProcessHeap(), 0, params );
1748 if (status == STATUS_PENDING)
1750 if (WaitForSingleObject( sync_event, INFINITE ) == WAIT_FAILED) return -1;
1751 status = io.u.Status;
1753 if (status)
1755 /* NtStatusToWSAError() has no mapping for WSAEALREADY */
1756 SetLastError( status == STATUS_ADDRESS_ALREADY_ASSOCIATED ? WSAEALREADY : NtStatusToWSAError( status ) );
1757 return -1;
1759 return 0;
1763 /***********************************************************************
1764 * WSAConnect (WS2_32.30)
1766 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
1767 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1768 LPQOS lpSQOS, LPQOS lpGQOS )
1770 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1771 FIXME("unsupported parameters!\n");
1772 return WS_connect( s, name, namelen );
1776 static BOOL WINAPI WS2_ConnectEx( SOCKET s, const struct WS_sockaddr *name, int namelen,
1777 void *send_buffer, DWORD send_len, DWORD *ret_len, OVERLAPPED *overlapped )
1779 struct afd_connect_params *params;
1780 void *cvalue = NULL;
1781 NTSTATUS status;
1783 TRACE( "socket %#lx, ptr %p %s, length %d, send_buffer %p, send_len %u, overlapped %p\n",
1784 s, name, debugstr_sockaddr(name), namelen, send_buffer, send_len, overlapped );
1786 if (!overlapped)
1788 SetLastError( WSA_INVALID_PARAMETER );
1789 return FALSE;
1792 if (!((ULONG_PTR)overlapped->hEvent & 1)) cvalue = overlapped;
1793 overlapped->Internal = STATUS_PENDING;
1794 overlapped->InternalHigh = 0;
1796 if (!(params = HeapAlloc( GetProcessHeap(), 0, sizeof(*params) + namelen + send_len )))
1798 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1799 return SOCKET_ERROR;
1801 params->addr_len = namelen;
1802 params->synchronous = FALSE;
1803 memcpy( params + 1, name, namelen );
1804 memcpy( (char *)(params + 1) + namelen, send_buffer, send_len );
1806 status = NtDeviceIoControlFile( SOCKET2HANDLE(s), overlapped->hEvent, NULL, cvalue,
1807 (IO_STATUS_BLOCK *)overlapped, IOCTL_AFD_WINE_CONNECT,
1808 params, sizeof(*params) + namelen + send_len, NULL, 0 );
1809 HeapFree( GetProcessHeap(), 0, params );
1810 if (ret_len) *ret_len = overlapped->InternalHigh;
1811 SetLastError( NtStatusToWSAError( status ) );
1812 return !status;
1816 static BOOL WINAPI WS2_DisconnectEx( SOCKET s, OVERLAPPED *overlapped, DWORD flags, DWORD reserved )
1818 IO_STATUS_BLOCK iosb, *piosb = &iosb;
1819 void *cvalue = NULL;
1820 int how = SD_SEND;
1821 HANDLE event = 0;
1822 NTSTATUS status;
1824 TRACE( "socket %#lx, overlapped %p, flags %#x, reserved %#x\n", s, overlapped, flags, reserved );
1826 if (flags & TF_REUSE_SOCKET)
1827 FIXME( "Reusing socket not supported yet\n" );
1829 if (overlapped)
1831 piosb = (IO_STATUS_BLOCK *)overlapped;
1832 if (!((ULONG_PTR)overlapped->hEvent & 1)) cvalue = overlapped;
1833 event = overlapped->hEvent;
1834 overlapped->Internal = STATUS_PENDING;
1835 overlapped->InternalHigh = 0;
1838 status = NtDeviceIoControlFile( (HANDLE)s, event, NULL, cvalue, piosb,
1839 IOCTL_AFD_WINE_SHUTDOWN, &how, sizeof(how), NULL, 0 );
1840 if (!status && overlapped) status = STATUS_PENDING;
1841 SetLastError( NtStatusToWSAError( status ) );
1842 return !status;
1846 /***********************************************************************
1847 * getpeername (ws2_32.5)
1849 int WINAPI WS_getpeername( SOCKET s, struct WS_sockaddr *addr, int *len )
1851 IO_STATUS_BLOCK io;
1852 NTSTATUS status;
1854 TRACE( "socket %#lx, addr %p, len %d\n", s, addr, len ? *len : 0 );
1856 if (!socket_list_find( s ))
1858 WSASetLastError( WSAENOTSOCK );
1859 return -1;
1862 if (!len)
1864 SetLastError( WSAEFAULT );
1865 return -1;
1868 status = NtDeviceIoControlFile( (HANDLE)s, NULL, NULL, NULL, &io,
1869 IOCTL_AFD_WINE_GETPEERNAME, NULL, 0, addr, *len );
1870 if (!status)
1871 *len = io.Information;
1872 SetLastError( NtStatusToWSAError( status ) );
1873 return status ? -1 : 0;
1877 /***********************************************************************
1878 * getsockname (ws2_32.6)
1880 int WINAPI WS_getsockname( SOCKET s, struct WS_sockaddr *addr, int *len )
1882 IO_STATUS_BLOCK io;
1883 NTSTATUS status;
1885 TRACE( "socket %#lx, addr %p, len %d\n", s, addr, len ? *len : 0 );
1887 if (!addr)
1889 SetLastError( WSAEFAULT );
1890 return -1;
1893 status = NtDeviceIoControlFile( (HANDLE)s, NULL, NULL, NULL, &io, IOCTL_AFD_GETSOCKNAME, NULL, 0, addr, *len );
1894 if (!status)
1895 *len = io.Information;
1896 WSASetLastError( NtStatusToWSAError( status ) );
1897 return status ? -1 : 0;
1901 static int server_getsockopt( SOCKET s, ULONG code, char *optval, int *optlen )
1903 IO_STATUS_BLOCK io;
1904 NTSTATUS status;
1906 status = NtDeviceIoControlFile( (HANDLE)s, NULL, NULL, NULL, &io, code, NULL, 0, optval, *optlen );
1907 if (!status) *optlen = io.Information;
1908 SetLastError( NtStatusToWSAError( status ) );
1909 return status ? -1 : 0;
1913 /***********************************************************************
1914 * getsockopt (WS2_32.7)
1916 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1917 INT optname, char *optval, INT *optlen)
1919 int fd;
1920 INT ret = 0;
1922 TRACE("(socket %04lx, %s, optval %s, optlen %p (%d))\n", s,
1923 debugstr_sockopt(level, optname), debugstr_optval(optval, 0),
1924 optlen, optlen ? *optlen : 0);
1926 switch(level)
1928 case WS_SOL_SOCKET:
1930 switch(optname)
1932 case WS_SO_ACCEPTCONN:
1933 return server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_ACCEPTCONN, optval, optlen );
1935 case WS_SO_BROADCAST:
1936 return server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_BROADCAST, optval, optlen );
1938 case WS_SO_BSP_STATE:
1940 CSADDR_INFO *csinfo = (CSADDR_INFO *)optval;
1941 WSAPROTOCOL_INFOW infow;
1942 int addr_size;
1944 if (!ws_protocol_info( s, TRUE, &infow, &addr_size ))
1945 return -1;
1947 if (infow.iAddressFamily == WS_AF_INET)
1948 addr_size = sizeof(struct sockaddr_in);
1949 else if (infow.iAddressFamily == WS_AF_INET6)
1950 addr_size = sizeof(struct sockaddr_in6);
1951 else
1953 FIXME( "family %d is unsupported for SO_BSP_STATE\n", infow.iAddressFamily );
1954 SetLastError( WSAEAFNOSUPPORT );
1955 return -1;
1958 if (*optlen < sizeof(CSADDR_INFO) + addr_size * 2)
1960 ret = 0;
1961 SetLastError( WSAEFAULT );
1962 return -1;
1965 csinfo->LocalAddr.lpSockaddr = (struct WS_sockaddr *)(csinfo + 1);
1966 csinfo->RemoteAddr.lpSockaddr = (struct WS_sockaddr *)((char *)(csinfo + 1) + addr_size);
1968 csinfo->LocalAddr.iSockaddrLength = addr_size;
1969 if (WS_getsockname( s, csinfo->LocalAddr.lpSockaddr, &csinfo->LocalAddr.iSockaddrLength ) < 0)
1971 csinfo->LocalAddr.lpSockaddr = NULL;
1972 csinfo->LocalAddr.iSockaddrLength = 0;
1975 csinfo->RemoteAddr.iSockaddrLength = addr_size;
1976 if (WS_getpeername( s, csinfo->RemoteAddr.lpSockaddr, &csinfo->RemoteAddr.iSockaddrLength ) < 0)
1978 csinfo->RemoteAddr.lpSockaddr = NULL;
1979 csinfo->RemoteAddr.iSockaddrLength = 0;
1982 csinfo->iSocketType = infow.iSocketType;
1983 csinfo->iProtocol = infow.iProtocol;
1984 return 0;
1987 case WS_SO_DEBUG:
1988 WARN( "returning 0 for SO_DEBUG\n" );
1989 *(DWORD *)optval = 0;
1990 SetLastError( 0 );
1991 return 0;
1993 case WS_SO_DONTLINGER:
1995 struct WS_linger linger;
1996 int len = sizeof(linger);
1997 int ret;
1999 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
2001 SetLastError(WSAEFAULT);
2002 return SOCKET_ERROR;
2005 if (!(ret = WS_getsockopt( s, WS_SOL_SOCKET, WS_SO_LINGER, (char *)&linger, &len )))
2007 *(BOOL *)optval = !linger.l_onoff;
2008 *optlen = sizeof(BOOL);
2010 return ret;
2013 case WS_SO_CONNECT_TIME:
2015 static int pretendtime = 0;
2016 struct WS_sockaddr addr;
2017 int len = sizeof(addr);
2019 if (!optlen || *optlen < sizeof(DWORD) || !optval)
2021 SetLastError(WSAEFAULT);
2022 return SOCKET_ERROR;
2024 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
2025 *(DWORD *)optval = ~0u;
2026 else
2028 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
2029 *(DWORD *)optval = pretendtime++;
2031 *optlen = sizeof(DWORD);
2032 return ret;
2034 /* As mentioned in setsockopt, Windows ignores this, so we
2035 * always return true here */
2036 case WS_SO_DONTROUTE:
2037 if (!optlen || *optlen < sizeof(BOOL) || !optval)
2039 SetLastError(WSAEFAULT);
2040 return SOCKET_ERROR;
2042 *(BOOL *)optval = TRUE;
2043 *optlen = sizeof(BOOL);
2044 return 0;
2046 case WS_SO_ERROR:
2047 return server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_ERROR, optval, optlen );
2049 case WS_SO_KEEPALIVE:
2050 return server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_KEEPALIVE, optval, optlen );
2052 case WS_SO_LINGER:
2054 WSAPROTOCOL_INFOW info;
2055 int size;
2057 /* struct linger and LINGER have different sizes */
2058 if (!optlen || *optlen < sizeof(LINGER) || !optval)
2060 SetLastError(WSAEFAULT);
2061 return SOCKET_ERROR;
2064 if (!ws_protocol_info( s, TRUE, &info, &size ))
2065 return -1;
2067 if (info.iSocketType == SOCK_DGRAM)
2069 SetLastError( WSAENOPROTOOPT );
2070 return -1;
2073 return server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_LINGER, optval, optlen );
2076 case WS_SO_MAX_MSG_SIZE:
2077 if (!optlen || *optlen < sizeof(int) || !optval)
2079 SetLastError(WSAEFAULT);
2080 return SOCKET_ERROR;
2082 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
2083 *(int *)optval = 65507;
2084 *optlen = sizeof(int);
2085 return 0;
2087 case WS_SO_OOBINLINE:
2088 return server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_OOBINLINE, optval, optlen );
2090 /* SO_OPENTYPE does not require a valid socket handle. */
2091 case WS_SO_OPENTYPE:
2092 if (!optlen || *optlen < sizeof(int) || !optval)
2094 SetLastError(WSAEFAULT);
2095 return SOCKET_ERROR;
2097 *(int *)optval = get_per_thread_data()->opentype;
2098 *optlen = sizeof(int);
2099 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2100 return 0;
2101 case WS_SO_PROTOCOL_INFOA:
2102 case WS_SO_PROTOCOL_INFOW:
2104 int size;
2105 WSAPROTOCOL_INFOW infow;
2107 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
2108 if (ret)
2110 if (!optlen || !optval || *optlen < size)
2112 if(optlen) *optlen = size;
2113 ret = 0;
2114 SetLastError(WSAEFAULT);
2116 else
2117 memcpy(optval, &infow, size);
2119 return ret ? 0 : SOCKET_ERROR;
2122 case WS_SO_RCVBUF:
2123 return server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_RCVBUF, optval, optlen );
2125 case WS_SO_RCVTIMEO:
2126 return server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_RCVTIMEO, optval, optlen );
2128 case WS_SO_REUSEADDR:
2129 return server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_REUSEADDR, optval, optlen );
2131 case WS_SO_SNDBUF:
2132 return server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_SNDBUF, optval, optlen );
2134 case WS_SO_SNDTIMEO:
2135 return server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_SNDTIMEO, optval, optlen );
2137 case WS_SO_TYPE:
2139 WSAPROTOCOL_INFOW info;
2140 int size;
2142 if (!optlen || *optlen < sizeof(int) || !optval)
2144 SetLastError(WSAEFAULT);
2145 return SOCKET_ERROR;
2148 if (!ws_protocol_info( s, TRUE, &info, &size ))
2149 return -1;
2151 *(int *)optval = info.iSocketType;
2152 return 0;
2155 default:
2156 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
2157 SetLastError(WSAENOPROTOOPT);
2158 return SOCKET_ERROR;
2159 } /* end switch(optname) */
2160 }/* end case WS_SOL_SOCKET */
2161 #ifdef HAS_IPX
2162 case WS_NSPROTO_IPX:
2164 struct WS_sockaddr_ipx addr;
2165 IPX_ADDRESS_DATA *data;
2166 int namelen;
2167 switch(optname)
2169 case WS_IPX_PTYPE:
2170 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
2171 #ifdef SOL_IPX
2172 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
2174 ret = SOCKET_ERROR;
2176 #else
2178 struct ipx val;
2179 socklen_t len=sizeof(struct ipx);
2180 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
2181 ret = SOCKET_ERROR;
2182 else
2183 *optval = (int)val.ipx_pt;
2185 #endif
2186 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
2187 release_sock_fd( s, fd );
2188 return ret;
2190 case WS_IPX_ADDRESS:
2192 * On a Win2000 system with one network card there are usually
2193 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
2194 * Using this call you can then retrieve info about this all.
2195 * In case of Linux it is a bit different. Usually you have
2196 * only "one" device active and further it is not possible to
2197 * query things like the linkspeed.
2199 FIXME("IPX_ADDRESS\n");
2200 namelen = sizeof(struct WS_sockaddr_ipx);
2201 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
2202 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
2204 data = (IPX_ADDRESS_DATA*)optval;
2205 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
2206 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
2207 data->adapternum = 0;
2208 data->wan = FALSE; /* We are not on a wan for now .. */
2209 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
2210 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
2211 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
2212 * note 1MB = 1000kB in this case */
2213 return 0;
2215 case WS_IPX_MAX_ADAPTER_NUM:
2216 FIXME("IPX_MAX_ADAPTER_NUM\n");
2217 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
2218 return 0;
2220 default:
2221 FIXME("IPX optname:%x\n", optname);
2222 return SOCKET_ERROR;
2223 }/* end switch(optname) */
2224 } /* end case WS_NSPROTO_IPX */
2225 #endif
2227 #ifdef HAS_IRDA
2228 #define MAX_IRDA_DEVICES 10
2230 case WS_SOL_IRLMP:
2231 switch(optname)
2233 case WS_IRLMP_ENUMDEVICES:
2235 char buf[sizeof(struct irda_device_list) +
2236 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
2237 int res;
2238 socklen_t len = sizeof(buf);
2240 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2241 return SOCKET_ERROR;
2242 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
2243 release_sock_fd( s, fd );
2244 if (res < 0)
2246 SetLastError(wsaErrno());
2247 return SOCKET_ERROR;
2249 else
2251 struct irda_device_list *src = (struct irda_device_list *)buf;
2252 DEVICELIST *dst = (DEVICELIST *)optval;
2253 INT needed = sizeof(DEVICELIST);
2254 unsigned int i;
2256 if (src->len > 0)
2257 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
2258 if (*optlen < needed)
2260 SetLastError(WSAEFAULT);
2261 return SOCKET_ERROR;
2263 *optlen = needed;
2264 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
2265 dst->numDevice = src->len;
2266 for (i = 0; i < src->len; i++)
2268 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
2269 src->dev[i].saddr, src->dev[i].daddr,
2270 src->dev[i].info, src->dev[i].hints[0],
2271 src->dev[i].hints[1]);
2272 memcpy( dst->Device[i].irdaDeviceID,
2273 &src->dev[i].daddr,
2274 sizeof(dst->Device[i].irdaDeviceID) ) ;
2275 memcpy( dst->Device[i].irdaDeviceName,
2276 src->dev[i].info,
2277 sizeof(dst->Device[i].irdaDeviceName) ) ;
2278 memcpy( &dst->Device[i].irdaDeviceHints1,
2279 &src->dev[i].hints[0],
2280 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
2281 memcpy( &dst->Device[i].irdaDeviceHints2,
2282 &src->dev[i].hints[1],
2283 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
2284 dst->Device[i].irdaCharSet = src->dev[i].charset;
2286 return 0;
2289 default:
2290 FIXME("IrDA optname:0x%x\n", optname);
2291 return SOCKET_ERROR;
2293 break; /* case WS_SOL_IRLMP */
2294 #undef MAX_IRDA_DEVICES
2295 #endif
2297 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
2298 case WS_IPPROTO_TCP:
2299 switch(optname)
2301 case WS_TCP_NODELAY:
2302 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2303 return SOCKET_ERROR;
2304 convert_sockopt(&level, &optname);
2305 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
2307 SetLastError(wsaErrno());
2308 ret = SOCKET_ERROR;
2310 release_sock_fd( s, fd );
2311 return ret;
2313 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
2314 return SOCKET_ERROR;
2316 case WS_IPPROTO_IP:
2317 switch(optname)
2319 case WS_IP_DONTFRAGMENT:
2320 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IP_DONTFRAGMENT, optval, optlen );
2322 case WS_IP_HDRINCL:
2323 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IP_HDRINCL, optval, optlen );
2325 case WS_IP_MULTICAST_IF:
2326 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IP_MULTICAST_IF, optval, optlen );
2328 case WS_IP_MULTICAST_LOOP:
2329 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IP_MULTICAST_LOOP, optval, optlen );
2331 case WS_IP_MULTICAST_TTL:
2332 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IP_MULTICAST_TTL, optval, optlen );
2334 case WS_IP_OPTIONS:
2335 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IP_OPTIONS, optval, optlen );
2337 case WS_IP_PKTINFO:
2338 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IP_PKTINFO, optval, optlen );
2340 case WS_IP_TOS:
2341 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IP_TOS, optval, optlen );
2343 case WS_IP_TTL:
2344 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IP_TTL, optval, optlen );
2346 case WS_IP_UNICAST_IF:
2347 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IP_UNICAST_IF, optval, optlen );
2349 default:
2350 FIXME( "unrecognized IP option %u\n", optname );
2351 /* fall through */
2353 case WS_IP_ADD_MEMBERSHIP:
2354 case WS_IP_DROP_MEMBERSHIP:
2355 SetLastError( WSAENOPROTOOPT );
2356 return -1;
2359 case WS_IPPROTO_IPV6:
2360 switch(optname)
2362 case WS_IPV6_DONTFRAG:
2363 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IPV6_DONTFRAG, optval, optlen );
2365 case WS_IPV6_MULTICAST_HOPS:
2366 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IPV6_MULTICAST_HOPS, optval, optlen );
2368 case WS_IPV6_MULTICAST_IF:
2369 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IPV6_MULTICAST_IF, optval, optlen );
2371 case WS_IPV6_MULTICAST_LOOP:
2372 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IPV6_MULTICAST_LOOP, optval, optlen );
2374 case WS_IPV6_UNICAST_HOPS:
2375 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IPV6_UNICAST_HOPS, optval, optlen );
2377 case WS_IPV6_UNICAST_IF:
2378 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IPV6_UNICAST_IF, optval, optlen );
2380 case WS_IPV6_V6ONLY:
2381 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IPV6_V6ONLY, optval, optlen );
2383 default:
2384 FIXME( "unrecognized IPv6 option %u\n", optname );
2385 /* fall through */
2387 case WS_IPV6_ADD_MEMBERSHIP:
2388 case WS_IPV6_DROP_MEMBERSHIP:
2389 SetLastError( WSAENOPROTOOPT );
2390 return -1;
2393 default:
2394 WARN("Unknown level: 0x%08x\n", level);
2395 SetLastError(WSAEINVAL);
2396 return SOCKET_ERROR;
2397 } /* end switch(level) */
2401 static const char *debugstr_wsaioctl(DWORD code)
2403 const char *name = NULL, *buf_type, *family;
2405 #define IOCTL_NAME(x) case x: name = #x; break
2406 switch (code)
2408 IOCTL_NAME(WS_FIONBIO);
2409 IOCTL_NAME(WS_FIONREAD);
2410 IOCTL_NAME(WS_SIOCATMARK);
2411 /* IOCTL_NAME(WS_SIO_ACQUIRE_PORT_RESERVATION); */
2412 IOCTL_NAME(WS_SIO_ADDRESS_LIST_CHANGE);
2413 IOCTL_NAME(WS_SIO_ADDRESS_LIST_QUERY);
2414 IOCTL_NAME(WS_SIO_ASSOCIATE_HANDLE);
2415 /* IOCTL_NAME(WS_SIO_ASSOCIATE_PORT_RESERVATION);
2416 IOCTL_NAME(WS_SIO_BASE_HANDLE);
2417 IOCTL_NAME(WS_SIO_BSP_HANDLE);
2418 IOCTL_NAME(WS_SIO_BSP_HANDLE_SELECT);
2419 IOCTL_NAME(WS_SIO_BSP_HANDLE_POLL);
2420 IOCTL_NAME(WS_SIO_CHK_QOS); */
2421 IOCTL_NAME(WS_SIO_ENABLE_CIRCULAR_QUEUEING);
2422 IOCTL_NAME(WS_SIO_FIND_ROUTE);
2423 IOCTL_NAME(WS_SIO_FLUSH);
2424 IOCTL_NAME(WS_SIO_GET_BROADCAST_ADDRESS);
2425 IOCTL_NAME(WS_SIO_GET_EXTENSION_FUNCTION_POINTER);
2426 IOCTL_NAME(WS_SIO_GET_GROUP_QOS);
2427 IOCTL_NAME(WS_SIO_GET_INTERFACE_LIST);
2428 /* IOCTL_NAME(WS_SIO_GET_INTERFACE_LIST_EX); */
2429 IOCTL_NAME(WS_SIO_GET_QOS);
2430 IOCTL_NAME(WS_SIO_IDEAL_SEND_BACKLOG_CHANGE);
2431 IOCTL_NAME(WS_SIO_IDEAL_SEND_BACKLOG_QUERY);
2432 IOCTL_NAME(WS_SIO_KEEPALIVE_VALS);
2433 IOCTL_NAME(WS_SIO_MULTIPOINT_LOOPBACK);
2434 IOCTL_NAME(WS_SIO_MULTICAST_SCOPE);
2435 /* IOCTL_NAME(WS_SIO_QUERY_RSS_SCALABILITY_INFO);
2436 IOCTL_NAME(WS_SIO_QUERY_WFP_ALE_ENDPOINT_HANDLE); */
2437 IOCTL_NAME(WS_SIO_RCVALL);
2438 IOCTL_NAME(WS_SIO_RCVALL_IGMPMCAST);
2439 IOCTL_NAME(WS_SIO_RCVALL_MCAST);
2440 /* IOCTL_NAME(WS_SIO_RELEASE_PORT_RESERVATION); */
2441 IOCTL_NAME(WS_SIO_ROUTING_INTERFACE_CHANGE);
2442 IOCTL_NAME(WS_SIO_ROUTING_INTERFACE_QUERY);
2443 IOCTL_NAME(WS_SIO_SET_COMPATIBILITY_MODE);
2444 IOCTL_NAME(WS_SIO_SET_GROUP_QOS);
2445 IOCTL_NAME(WS_SIO_SET_QOS);
2446 IOCTL_NAME(WS_SIO_TRANSLATE_HANDLE);
2447 IOCTL_NAME(WS_SIO_UDP_CONNRESET);
2449 #undef IOCTL_NAME
2451 if (name)
2452 return name + 3;
2454 /* If this is not a known code split its bits */
2455 switch(code & 0x18000000)
2457 case WS_IOC_WS2:
2458 family = "IOC_WS2";
2459 break;
2460 case WS_IOC_PROTOCOL:
2461 family = "IOC_PROTOCOL";
2462 break;
2463 case WS_IOC_VENDOR:
2464 family = "IOC_VENDOR";
2465 break;
2466 default: /* WS_IOC_UNIX */
2468 BYTE size = (code >> 16) & WS_IOCPARM_MASK;
2469 char x = (code & 0xff00) >> 8;
2470 BYTE y = code & 0xff;
2471 char args[14];
2473 switch (code & (WS_IOC_VOID|WS_IOC_INOUT))
2475 case WS_IOC_VOID:
2476 buf_type = "_IO";
2477 sprintf(args, "%d, %d", x, y);
2478 break;
2479 case WS_IOC_IN:
2480 buf_type = "_IOW";
2481 sprintf(args, "'%c', %d, %d", x, y, size);
2482 break;
2483 case WS_IOC_OUT:
2484 buf_type = "_IOR";
2485 sprintf(args, "'%c', %d, %d", x, y, size);
2486 break;
2487 default:
2488 buf_type = "?";
2489 sprintf(args, "'%c', %d, %d", x, y, size);
2490 break;
2492 return wine_dbg_sprintf("%s(%s)", buf_type, args);
2496 /* We are different from WS_IOC_UNIX. */
2497 switch (code & (WS_IOC_VOID|WS_IOC_INOUT))
2499 case WS_IOC_VOID:
2500 buf_type = "_WSAIO";
2501 break;
2502 case WS_IOC_INOUT:
2503 buf_type = "_WSAIORW";
2504 break;
2505 case WS_IOC_IN:
2506 buf_type = "_WSAIOW";
2507 break;
2508 case WS_IOC_OUT:
2509 buf_type = "_WSAIOR";
2510 break;
2511 default:
2512 buf_type = "?";
2513 break;
2516 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
2517 (USHORT)(code & 0xffff));
2520 /* do an ioctl call through the server */
2521 static DWORD server_ioctl_sock( SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size,
2522 LPVOID out_buff, DWORD out_size, LPDWORD ret_size,
2523 LPWSAOVERLAPPED overlapped,
2524 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
2526 IO_STATUS_BLOCK iosb, *piosb = &iosb;
2527 HANDLE handle = SOCKET2HANDLE( s );
2528 PIO_APC_ROUTINE apc = NULL;
2529 HANDLE event = NULL;
2530 void *cvalue = NULL;
2531 NTSTATUS status;
2533 if (overlapped)
2535 piosb = (IO_STATUS_BLOCK *)overlapped;
2536 if (!((ULONG_PTR)overlapped->hEvent & 1)) cvalue = overlapped;
2537 event = overlapped->hEvent;
2539 else
2541 if (!(event = get_sync_event())) return GetLastError();
2544 if (completion)
2546 event = NULL;
2547 cvalue = completion;
2548 apc = socket_apc;
2551 status = NtDeviceIoControlFile( handle, event, apc, cvalue, piosb, code,
2552 in_buff, in_size, out_buff, out_size );
2553 if (status == STATUS_PENDING && !overlapped)
2555 if (WaitForSingleObject( event, INFINITE ) == WAIT_FAILED)
2556 return -1;
2557 status = piosb->u.Status;
2559 if (status == STATUS_NOT_SUPPORTED)
2561 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
2562 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
2564 else if (status == STATUS_SUCCESS)
2565 *ret_size = piosb->Information;
2567 return NtStatusToWSAError( status );
2571 /**********************************************************************
2572 * WSAIoctl (WS2_32.50)
2575 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
2576 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
2577 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
2579 TRACE("%04lx, %s, %p, %d, %p, %d, %p, %p, %p\n",
2580 s, debugstr_wsaioctl(code), in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
2582 if (!ret_size)
2584 SetLastError( WSAEFAULT );
2585 return -1;
2588 switch (code)
2590 case WS_FIONBIO:
2592 DWORD ret;
2594 if (IS_INTRESOURCE( in_buff ))
2596 SetLastError( WSAEFAULT );
2597 return -1;
2600 /* Explicitly ignore the output buffer; WeChat tries to pass an address
2601 * without write access. */
2602 ret = server_ioctl_sock( s, IOCTL_AFD_WINE_FIONBIO, in_buff, in_size,
2603 NULL, 0, ret_size, overlapped, completion );
2604 SetLastError( ret );
2605 return ret ? -1 : 0;
2608 case WS_FIONREAD:
2610 DWORD ret;
2612 ret = server_ioctl_sock( s, IOCTL_AFD_WINE_FIONREAD, in_buff, in_size,
2613 out_buff, out_size, ret_size, overlapped, completion );
2614 SetLastError( ret );
2615 if (!ret) *ret_size = sizeof(WS_u_long);
2616 return ret ? -1 : 0;
2619 case WS_SIOCATMARK:
2621 DWORD ret;
2623 ret = server_ioctl_sock( s, IOCTL_AFD_WINE_SIOCATMARK, in_buff, in_size,
2624 out_buff, out_size, ret_size, overlapped, completion );
2625 SetLastError( ret );
2626 if (!ret) *ret_size = sizeof(WS_u_long);
2627 return ret ? -1 : 0;
2630 case WS_SIO_GET_INTERFACE_LIST:
2632 DWORD ret;
2634 ret = server_ioctl_sock( s, IOCTL_AFD_WINE_GET_INTERFACE_LIST, in_buff, in_size,
2635 out_buff, out_size, ret_size, overlapped, completion );
2636 SetLastError( ret );
2637 if (ret && ret != ERROR_IO_PENDING) *ret_size = 0;
2638 return ret ? -1 : 0;
2641 case WS_SIO_ADDRESS_LIST_QUERY:
2643 DWORD size, total;
2645 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
2647 if (out_size && out_size < FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[0]))
2649 *ret_size = 0;
2650 SetLastError(WSAEINVAL);
2651 return SOCKET_ERROR;
2654 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
2656 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
2657 NTSTATUS status = STATUS_SUCCESS;
2658 SOCKET_ADDRESS_LIST *sa_list;
2659 SOCKADDR_IN *sockaddr;
2660 SOCKET_ADDRESS *sa;
2661 unsigned int i;
2662 DWORD ret = 0;
2663 DWORD num;
2665 if (!table || GetAdaptersInfo(table, &size))
2667 HeapFree(GetProcessHeap(), 0, table);
2668 SetLastError( WSAEINVAL );
2669 return -1;
2672 for (p = table, num = 0; p; p = p->Next)
2673 if (p->IpAddressList.IpAddress.String[0]) num++;
2675 total = FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[num]) + num * sizeof(*sockaddr);
2676 if (total > out_size || !out_buff)
2678 *ret_size = total;
2679 HeapFree(GetProcessHeap(), 0, table);
2680 SetLastError( WSAEFAULT );
2681 return -1;
2684 sa_list = out_buff;
2685 sa = sa_list->Address;
2686 sockaddr = (SOCKADDR_IN *)&sa[num];
2687 sa_list->iAddressCount = num;
2689 for (p = table, i = 0; p; p = p->Next)
2691 if (!p->IpAddressList.IpAddress.String[0]) continue;
2693 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
2694 sa[i].iSockaddrLength = sizeof(SOCKADDR);
2696 sockaddr[i].sin_family = WS_AF_INET;
2697 sockaddr[i].sin_port = 0;
2698 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
2699 i++;
2702 HeapFree(GetProcessHeap(), 0, table);
2704 ret = server_ioctl_sock( s, IOCTL_AFD_WINE_COMPLETE_ASYNC, &status, sizeof(status),
2705 NULL, 0, ret_size, overlapped, completion );
2706 *ret_size = total;
2707 SetLastError( ret );
2708 return ret ? -1 : 0;
2710 else
2712 WARN("unable to get IP address list\n");
2713 SetLastError( WSAEINVAL );
2714 return -1;
2718 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
2720 #define EXTENSION_FUNCTION(x, y) { x, y, #y },
2721 static const struct
2723 GUID guid;
2724 void *func_ptr;
2725 const char *name;
2726 } guid_funcs[] = {
2727 EXTENSION_FUNCTION(WSAID_CONNECTEX, WS2_ConnectEx)
2728 EXTENSION_FUNCTION(WSAID_DISCONNECTEX, WS2_DisconnectEx)
2729 EXTENSION_FUNCTION(WSAID_ACCEPTEX, WS2_AcceptEx)
2730 EXTENSION_FUNCTION(WSAID_GETACCEPTEXSOCKADDRS, WS2_GetAcceptExSockaddrs)
2731 EXTENSION_FUNCTION(WSAID_TRANSMITFILE, WS2_TransmitFile)
2732 /* EXTENSION_FUNCTION(WSAID_TRANSMITPACKETS, WS2_TransmitPackets) */
2733 EXTENSION_FUNCTION(WSAID_WSARECVMSG, WS2_WSARecvMsg)
2734 EXTENSION_FUNCTION(WSAID_WSASENDMSG, WSASendMsg)
2736 #undef EXTENSION_FUNCTION
2737 unsigned int i;
2739 for (i = 0; i < ARRAY_SIZE(guid_funcs); i++)
2741 if (IsEqualGUID(&guid_funcs[i].guid, in_buff))
2743 NTSTATUS status = STATUS_SUCCESS;
2744 DWORD ret = 0;
2746 TRACE( "returning %s\n", guid_funcs[i].name );
2747 *(void **)out_buff = guid_funcs[i].func_ptr;
2749 ret = server_ioctl_sock( s, IOCTL_AFD_WINE_COMPLETE_ASYNC, &status, sizeof(status),
2750 NULL, 0, ret_size, overlapped, completion );
2751 *ret_size = sizeof(void *);
2752 SetLastError( ret );
2753 return ret ? -1 : 0;
2757 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
2758 SetLastError( WSAEINVAL );
2759 return -1;
2762 case WS_SIO_KEEPALIVE_VALS:
2764 DWORD ret;
2766 ret = server_ioctl_sock( s, IOCTL_AFD_WINE_KEEPALIVE_VALS, in_buff, in_size,
2767 out_buff, out_size, ret_size, overlapped, completion );
2768 if (!overlapped || completion) *ret_size = 0;
2769 SetLastError( ret );
2770 return ret ? -1 : 0;
2773 case WS_SIO_ROUTING_INTERFACE_QUERY:
2775 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
2776 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
2777 struct WS_sockaddr_in *saddr_in = out_buff;
2778 MIB_IPFORWARDROW row;
2779 PMIB_IPADDRTABLE ipAddrTable = NULL;
2780 DWORD size, i, found_index, ret = 0;
2781 NTSTATUS status = STATUS_SUCCESS;
2783 TRACE( "-> WS_SIO_ROUTING_INTERFACE_QUERY request\n" );
2785 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
2786 !out_buff || out_size < sizeof(struct WS_sockaddr_in))
2788 SetLastError( WSAEFAULT );
2789 return -1;
2791 if (daddr->sa_family != WS_AF_INET)
2793 FIXME("unsupported address family %d\n", daddr->sa_family);
2794 SetLastError( WSAEAFNOSUPPORT );
2795 return -1;
2797 if (GetBestRoute( daddr_in->sin_addr.S_un.S_addr, 0, &row ) != NOERROR ||
2798 GetIpAddrTable( NULL, &size, FALSE ) != ERROR_INSUFFICIENT_BUFFER)
2800 SetLastError( WSAEFAULT );
2801 return -1;
2803 ipAddrTable = HeapAlloc( GetProcessHeap(), 0, size );
2804 if (GetIpAddrTable( ipAddrTable, &size, FALSE ))
2806 HeapFree( GetProcessHeap(), 0, ipAddrTable );
2807 SetLastError( WSAEFAULT );
2808 return -1;
2810 for (i = 0, found_index = ipAddrTable->dwNumEntries;
2811 i < ipAddrTable->dwNumEntries; i++)
2813 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
2814 found_index = i;
2816 if (found_index == ipAddrTable->dwNumEntries)
2818 ERR("no matching IP address for interface %d\n",
2819 row.dwForwardIfIndex);
2820 HeapFree( GetProcessHeap(), 0, ipAddrTable );
2821 SetLastError( WSAEFAULT );
2822 return -1;
2824 saddr_in->sin_family = WS_AF_INET;
2825 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
2826 saddr_in->sin_port = 0;
2827 HeapFree( GetProcessHeap(), 0, ipAddrTable );
2829 ret = server_ioctl_sock( s, IOCTL_AFD_WINE_COMPLETE_ASYNC, &status, sizeof(status),
2830 NULL, 0, ret_size, overlapped, completion );
2831 if (!ret) *ret_size = sizeof(struct WS_sockaddr_in);
2832 SetLastError( ret );
2833 return ret ? -1 : 0;
2836 case WS_SIO_ADDRESS_LIST_CHANGE:
2838 int force_async = !!overlapped;
2839 DWORD ret;
2841 ret = server_ioctl_sock( s, IOCTL_AFD_WINE_ADDRESS_LIST_CHANGE, &force_async, sizeof(force_async),
2842 out_buff, out_size, ret_size, overlapped, completion );
2843 SetLastError( ret );
2844 return ret ? -1 : 0;
2847 case WS_SIO_UDP_CONNRESET:
2849 NTSTATUS status = STATUS_SUCCESS;
2850 DWORD ret;
2852 FIXME( "WS_SIO_UDP_CONNRESET stub\n" );
2853 ret = server_ioctl_sock( s, IOCTL_AFD_WINE_COMPLETE_ASYNC, &status, sizeof(status),
2854 NULL, 0, ret_size, overlapped, completion );
2855 SetLastError( ret );
2856 return ret ? -1 : 0;
2859 case WS_SIO_BASE_HANDLE:
2861 NTSTATUS status;
2862 DWORD ret;
2864 if (overlapped)
2866 status = STATUS_NOT_SUPPORTED;
2868 else
2870 status = STATUS_SUCCESS;
2871 *(SOCKET *)out_buff = s;
2873 ret = server_ioctl_sock( s, IOCTL_AFD_WINE_COMPLETE_ASYNC, &status, sizeof(status),
2874 NULL, 0, ret_size, overlapped, completion );
2875 if (overlapped) ret = ERROR_IO_PENDING;
2876 if (!ret) *ret_size = sizeof(SOCKET);
2877 SetLastError( ret );
2878 return ret ? -1 : 0;
2881 default:
2882 FIXME( "unimplemented ioctl %s\n", debugstr_wsaioctl( code ) );
2883 /* fall through */
2884 case LOWORD(WS_FIONBIO): /* Netscape tries to use this */
2885 case WS_SIO_SET_COMPATIBILITY_MODE:
2887 NTSTATUS status = STATUS_NOT_SUPPORTED;
2889 server_ioctl_sock( s, IOCTL_AFD_WINE_COMPLETE_ASYNC, &status, sizeof(status),
2890 NULL, 0, ret_size, overlapped, completion );
2891 if (overlapped)
2893 SetLastError( ERROR_IO_PENDING );
2895 else
2897 *ret_size = 0;
2898 SetLastError( WSAEOPNOTSUPP );
2900 return -1;
2906 /***********************************************************************
2907 * ioctlsocket (WS2_32.10)
2909 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
2911 DWORD ret_size;
2912 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
2916 /***********************************************************************
2917 * listen (ws2_32.13)
2919 int WINAPI WS_listen( SOCKET s, int backlog )
2921 struct afd_listen_params params = {.backlog = backlog};
2922 IO_STATUS_BLOCK io;
2923 NTSTATUS status;
2925 TRACE( "socket %#lx, backlog %d\n", s, backlog );
2927 status = NtDeviceIoControlFile( SOCKET2HANDLE(s), NULL, NULL, NULL, &io,
2928 IOCTL_AFD_LISTEN, &params, sizeof(params), NULL, 0 );
2929 SetLastError( NtStatusToWSAError( status ) );
2930 return status ? -1 : 0;
2934 /***********************************************************************
2935 * recv (WS2_32.16)
2937 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2939 DWORD n, dwFlags = flags;
2940 WSABUF wsabuf;
2942 wsabuf.len = len;
2943 wsabuf.buf = buf;
2945 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2946 return SOCKET_ERROR;
2947 else
2948 return n;
2951 /***********************************************************************
2952 * recvfrom (WS2_32.17)
2954 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2955 struct WS_sockaddr *from, int *fromlen)
2957 DWORD n, dwFlags = flags;
2958 WSABUF wsabuf;
2960 wsabuf.len = len;
2961 wsabuf.buf = buf;
2963 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
2964 return SOCKET_ERROR;
2965 else
2966 return n;
2970 /* as FD_SET(), but returns 1 if the fd was added, 0 otherwise */
2971 static int add_fd_to_set( SOCKET fd, struct WS_fd_set *set )
2973 unsigned int i;
2975 for (i = 0; i < set->fd_count; ++i)
2977 if (set->fd_array[i] == fd)
2978 return 0;
2981 if (set->fd_count < WS_FD_SETSIZE)
2983 set->fd_array[set->fd_count++] = fd;
2984 return 1;
2987 return 0;
2991 /***********************************************************************
2992 * select (ws2_32.18)
2994 int WINAPI WS_select( int count, WS_fd_set *read_ptr, WS_fd_set *write_ptr,
2995 WS_fd_set *except_ptr, const struct WS_timeval *timeout)
2997 char buffer[offsetof( struct afd_poll_params, sockets[WS_FD_SETSIZE * 3] )] = {0};
2998 struct afd_poll_params *params = (struct afd_poll_params *)buffer;
2999 struct WS_fd_set read, write, except;
3000 ULONG params_size, i, j;
3001 SOCKET poll_socket = 0;
3002 IO_STATUS_BLOCK io;
3003 HANDLE sync_event;
3004 int ret_count = 0;
3005 NTSTATUS status;
3007 TRACE( "read %p, write %p, except %p, timeout %p\n", read_ptr, write_ptr, except_ptr, timeout );
3009 WS_FD_ZERO( &read );
3010 WS_FD_ZERO( &write );
3011 WS_FD_ZERO( &except );
3012 if (read_ptr) read = *read_ptr;
3013 if (write_ptr) write = *write_ptr;
3014 if (except_ptr) except = *except_ptr;
3016 if (!(sync_event = get_sync_event())) return -1;
3018 if (timeout)
3019 params->timeout = timeout->tv_sec * -10000000 + timeout->tv_usec * -10;
3020 else
3021 params->timeout = TIMEOUT_INFINITE;
3023 for (i = 0; i < read.fd_count; ++i)
3025 params->sockets[params->count].socket = read.fd_array[i];
3026 params->sockets[params->count].flags = AFD_POLL_READ | AFD_POLL_ACCEPT | AFD_POLL_HUP;
3027 ++params->count;
3028 poll_socket = read.fd_array[i];
3031 for (i = 0; i < write.fd_count; ++i)
3033 params->sockets[params->count].socket = write.fd_array[i];
3034 params->sockets[params->count].flags = AFD_POLL_WRITE;
3035 ++params->count;
3036 poll_socket = write.fd_array[i];
3039 for (i = 0; i < except.fd_count; ++i)
3041 params->sockets[params->count].socket = except.fd_array[i];
3042 params->sockets[params->count].flags = AFD_POLL_OOB | AFD_POLL_CONNECT_ERR;
3043 ++params->count;
3044 poll_socket = except.fd_array[i];
3047 if (!params->count)
3049 SetLastError( WSAEINVAL );
3050 return -1;
3053 params_size = offsetof( struct afd_poll_params, sockets[params->count] );
3055 status = NtDeviceIoControlFile( (HANDLE)poll_socket, sync_event, NULL, NULL, &io,
3056 IOCTL_AFD_POLL, params, params_size, params, params_size );
3057 if (status == STATUS_PENDING)
3059 if (WaitForSingleObject( sync_event, INFINITE ) == WAIT_FAILED)
3060 return -1;
3061 status = io.u.Status;
3063 if (status == STATUS_TIMEOUT) status = STATUS_SUCCESS;
3064 if (!status)
3066 /* pointers may alias, so clear them all first */
3067 if (read_ptr) WS_FD_ZERO( read_ptr );
3068 if (write_ptr) WS_FD_ZERO( write_ptr );
3069 if (except_ptr) WS_FD_ZERO( except_ptr );
3071 for (i = 0; i < params->count; ++i)
3073 unsigned int flags = params->sockets[i].flags;
3074 SOCKET s = params->sockets[i].socket;
3076 for (j = 0; j < read.fd_count; ++j)
3078 if (read.fd_array[j] == s
3079 && (flags & (AFD_POLL_READ | AFD_POLL_ACCEPT | AFD_POLL_HUP | AFD_POLL_CLOSE)))
3081 ret_count += add_fd_to_set( s, read_ptr );
3082 flags &= ~AFD_POLL_CLOSE;
3086 if (flags & AFD_POLL_CLOSE)
3087 status = STATUS_INVALID_HANDLE;
3089 for (j = 0; j < write.fd_count; ++j)
3091 if (write.fd_array[j] == s && (flags & AFD_POLL_WRITE))
3092 ret_count += add_fd_to_set( s, write_ptr );
3095 for (j = 0; j < except.fd_count; ++j)
3097 if (except.fd_array[j] == s && (flags & (AFD_POLL_OOB | AFD_POLL_CONNECT_ERR)))
3098 ret_count += add_fd_to_set( s, except_ptr );
3103 SetLastError( NtStatusToWSAError( status ) );
3104 return status ? -1 : ret_count;
3108 static unsigned int afd_poll_flag_to_win32( unsigned int flags )
3110 static const unsigned int map[] =
3112 FD_READ, /* READ */
3113 FD_OOB, /* OOB */
3114 FD_WRITE, /* WRITE */
3115 FD_CLOSE, /* HUP */
3116 FD_CLOSE, /* RESET */
3117 0, /* CLOSE */
3118 FD_CONNECT, /* CONNECT */
3119 FD_ACCEPT, /* ACCEPT */
3120 FD_CONNECT, /* CONNECT_ERR */
3123 unsigned int i, ret = 0;
3125 for (i = 0; i < ARRAY_SIZE(map); ++i)
3127 if (flags & (1 << i)) ret |= map[i];
3130 return ret;
3134 /***********************************************************************
3135 * WSAPoll (ws2_32.@)
3137 int WINAPI WSAPoll( WSAPOLLFD *fds, ULONG count, int timeout )
3139 struct afd_poll_params *params;
3140 ULONG params_size, i, j;
3141 SOCKET poll_socket = 0;
3142 IO_STATUS_BLOCK io;
3143 HANDLE sync_event;
3144 int ret_count = 0;
3145 NTSTATUS status;
3147 if (!count)
3149 SetLastError(WSAEINVAL);
3150 return SOCKET_ERROR;
3152 if (!fds)
3154 SetLastError(WSAEFAULT);
3155 return SOCKET_ERROR;
3158 if (!(sync_event = get_sync_event())) return -1;
3160 params_size = offsetof( struct afd_poll_params, sockets[count] );
3161 if (!(params = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, params_size )))
3163 SetLastError(WSAENOBUFS);
3164 return SOCKET_ERROR;
3167 params->timeout = (timeout >= 0 ? timeout * -10000 : TIMEOUT_INFINITE);
3169 for (i = 0; i < count; ++i)
3171 unsigned int flags = AFD_POLL_HUP | AFD_POLL_RESET | AFD_POLL_CONNECT_ERR;
3173 if ((INT_PTR)fds[i].fd < 0 || !socket_list_find( fds[i].fd ))
3175 fds[i].revents = WS_POLLNVAL;
3176 continue;
3179 poll_socket = fds[i].fd;
3180 params->sockets[params->count].socket = fds[i].fd;
3182 if (fds[i].events & WS_POLLRDNORM)
3183 flags |= AFD_POLL_ACCEPT | AFD_POLL_READ;
3184 if (fds[i].events & WS_POLLRDBAND)
3185 flags |= AFD_POLL_OOB;
3186 if (fds[i].events & WS_POLLWRNORM)
3187 flags |= AFD_POLL_WRITE;
3188 params->sockets[params->count].flags = flags;
3189 ++params->count;
3191 fds[i].revents = 0;
3194 if (!poll_socket)
3196 SetLastError( WSAENOTSOCK );
3197 HeapFree( GetProcessHeap(), 0, params );
3198 return -1;
3201 status = NtDeviceIoControlFile( (HANDLE)poll_socket, sync_event, NULL, NULL, &io, IOCTL_AFD_POLL,
3202 params, params_size, params, params_size );
3203 if (status == STATUS_PENDING)
3205 if (WaitForSingleObject( sync_event, INFINITE ) == WAIT_FAILED)
3207 HeapFree( GetProcessHeap(), 0, params );
3208 return -1;
3210 status = io.u.Status;
3212 if (!status)
3214 for (i = 0; i < count; ++i)
3216 for (j = 0; j < params->count; ++j)
3218 if (fds[i].fd == params->sockets[j].socket)
3220 unsigned int revents = 0;
3222 if (params->sockets[j].flags & (AFD_POLL_ACCEPT | AFD_POLL_READ))
3223 revents |= WS_POLLRDNORM;
3224 if (params->sockets[j].flags & AFD_POLL_OOB)
3225 revents |= WS_POLLRDBAND;
3226 if (params->sockets[j].flags & AFD_POLL_WRITE)
3227 revents |= WS_POLLWRNORM;
3228 if (params->sockets[j].flags & AFD_POLL_HUP)
3229 revents |= WS_POLLHUP;
3230 if (params->sockets[j].flags & (AFD_POLL_RESET | AFD_POLL_CONNECT_ERR))
3231 revents |= WS_POLLERR;
3232 if (params->sockets[j].flags & AFD_POLL_CLOSE)
3233 revents |= WS_POLLNVAL;
3235 fds[i].revents = revents & (fds[i].events | WS_POLLHUP | WS_POLLERR | WS_POLLNVAL);
3237 if (fds[i].revents)
3238 ++ret_count;
3243 if (status == STATUS_TIMEOUT) status = STATUS_SUCCESS;
3245 HeapFree( GetProcessHeap(), 0, params );
3247 SetLastError( NtStatusToWSAError( status ) );
3248 return status ? -1 : ret_count;
3252 /***********************************************************************
3253 * send (WS2_32.19)
3255 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
3257 DWORD n;
3258 WSABUF wsabuf;
3260 wsabuf.len = len;
3261 wsabuf.buf = (char*) buf;
3263 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
3264 return SOCKET_ERROR;
3265 else
3266 return n;
3269 /***********************************************************************
3270 * WSASend (WS2_32.72)
3272 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3273 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3274 LPWSAOVERLAPPED lpOverlapped,
3275 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3277 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
3278 NULL, 0, lpOverlapped, lpCompletionRoutine );
3281 /***********************************************************************
3282 * WSASendDisconnect (WS2_32.73)
3284 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
3286 return WS_shutdown( s, SD_SEND );
3290 /***********************************************************************
3291 * WSASendTo (WS2_32.74)
3293 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3294 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3295 const struct WS_sockaddr *to, int tolen,
3296 LPWSAOVERLAPPED lpOverlapped,
3297 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3299 /* Garena hooks WSASendTo(), so we need a wrapper */
3300 return WS2_sendto( s, lpBuffers, dwBufferCount,
3301 lpNumberOfBytesSent, dwFlags,
3302 to, tolen,
3303 lpOverlapped, lpCompletionRoutine );
3306 /***********************************************************************
3307 * sendto (WS2_32.20)
3309 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
3310 const struct WS_sockaddr *to, int tolen)
3312 DWORD n;
3313 WSABUF wsabuf;
3315 wsabuf.len = len;
3316 wsabuf.buf = (char*) buf;
3318 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
3319 return SOCKET_ERROR;
3320 else
3321 return n;
3325 static int server_setsockopt( SOCKET s, ULONG code, const char *optval, int optlen )
3327 IO_STATUS_BLOCK io;
3328 NTSTATUS status;
3330 status = NtDeviceIoControlFile( (HANDLE)s, NULL, NULL, NULL, &io, code, (void *)optval, optlen, NULL, 0 );
3331 SetLastError( NtStatusToWSAError( status ) );
3332 return status ? -1 : 0;
3336 /***********************************************************************
3337 * setsockopt (WS2_32.21)
3339 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
3340 const char *optval, int optlen)
3342 int fd;
3343 int woptval;
3345 TRACE("(socket %04lx, %s, optval %s, optlen %d)\n", s,
3346 debugstr_sockopt(level, optname), debugstr_optval(optval, optlen),
3347 optlen);
3349 /* some broken apps pass the value directly instead of a pointer to it */
3350 if(optlen && IS_INTRESOURCE(optval))
3352 SetLastError(WSAEFAULT);
3353 return SOCKET_ERROR;
3356 switch(level)
3358 case WS_SOL_SOCKET:
3359 switch(optname)
3361 case WS_SO_BROADCAST:
3362 return server_setsockopt( s, IOCTL_AFD_WINE_SET_SO_BROADCAST, optval, optlen );
3364 case WS_SO_DONTLINGER:
3366 struct WS_linger linger;
3368 if (!optval)
3370 SetLastError( WSAEFAULT );
3371 return -1;
3374 linger.l_onoff = !*(const BOOL *)optval;
3375 linger.l_linger = 0;
3376 return WS_setsockopt( s, WS_SOL_SOCKET, WS_SO_LINGER, (char *)&linger, sizeof(linger) );
3379 case WS_SO_ERROR:
3380 FIXME( "SO_ERROR, stub!\n" );
3381 SetLastError( WSAENOPROTOOPT );
3382 return -1;
3384 case WS_SO_KEEPALIVE:
3385 return server_setsockopt( s, IOCTL_AFD_WINE_SET_SO_KEEPALIVE, optval, optlen );
3387 case WS_SO_LINGER:
3388 return server_setsockopt( s, IOCTL_AFD_WINE_SET_SO_LINGER, optval, optlen );
3390 case WS_SO_OOBINLINE:
3391 return server_setsockopt( s, IOCTL_AFD_WINE_SET_SO_OOBINLINE, optval, optlen );
3393 case WS_SO_RCVBUF:
3394 return server_setsockopt( s, IOCTL_AFD_WINE_SET_SO_RCVBUF, optval, optlen );
3396 case WS_SO_RCVTIMEO:
3397 return server_setsockopt( s, IOCTL_AFD_WINE_SET_SO_RCVTIMEO, optval, optlen );
3399 case WS_SO_REUSEADDR:
3400 return server_setsockopt( s, IOCTL_AFD_WINE_SET_SO_REUSEADDR, optval, optlen );
3402 case WS_SO_SNDBUF:
3403 return server_setsockopt( s, IOCTL_AFD_WINE_SET_SO_SNDBUF, optval, optlen );
3405 case WS_SO_SNDTIMEO:
3406 return server_setsockopt( s, IOCTL_AFD_WINE_SET_SO_SNDTIMEO, optval, optlen );
3408 /* SO_DEBUG is a privileged operation, ignore it. */
3409 case WS_SO_DEBUG:
3410 TRACE("Ignoring SO_DEBUG\n");
3411 return 0;
3413 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
3414 * socket. According to MSDN, this option is silently ignored.*/
3415 case WS_SO_DONTROUTE:
3416 TRACE("Ignoring SO_DONTROUTE\n");
3417 return 0;
3419 /* Stops two sockets from being bound to the same port. Always happens
3420 * on unix systems, so just drop it. */
3421 case WS_SO_EXCLUSIVEADDRUSE:
3422 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
3423 return 0;
3425 /* After a ConnectEx call succeeds, the socket can't be used with half of the
3426 * normal winsock functions on windows. We don't have that problem. */
3427 case WS_SO_UPDATE_CONNECT_CONTEXT:
3428 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
3429 return 0;
3431 /* After a AcceptEx call succeeds, the socket can't be used with half of the
3432 * normal winsock functions on windows. We don't have that problem. */
3433 case WS_SO_UPDATE_ACCEPT_CONTEXT:
3434 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
3435 return 0;
3437 /* SO_OPENTYPE does not require a valid socket handle. */
3438 case WS_SO_OPENTYPE:
3439 if (!optlen || optlen < sizeof(int) || !optval)
3441 SetLastError(WSAEFAULT);
3442 return SOCKET_ERROR;
3444 get_per_thread_data()->opentype = *(const int *)optval;
3445 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
3446 return 0;
3448 case WS_SO_RANDOMIZE_PORT:
3449 FIXME("Ignoring WS_SO_RANDOMIZE_PORT\n");
3450 return 0;
3452 case WS_SO_PORT_SCALABILITY:
3453 FIXME("Ignoring WS_SO_PORT_SCALABILITY\n");
3454 return 0;
3456 case WS_SO_REUSE_UNICASTPORT:
3457 FIXME("Ignoring WS_SO_REUSE_UNICASTPORT\n");
3458 return 0;
3460 case WS_SO_REUSE_MULTICASTPORT:
3461 FIXME("Ignoring WS_SO_REUSE_MULTICASTPORT\n");
3462 return 0;
3464 default:
3465 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3466 /* fall through */
3468 case WS_SO_ACCEPTCONN:
3469 case WS_SO_TYPE:
3470 SetLastError(WSAENOPROTOOPT);
3471 return SOCKET_ERROR;
3473 break; /* case WS_SOL_SOCKET */
3475 #ifdef HAS_IPX
3476 case WS_NSPROTO_IPX:
3477 switch(optname)
3479 case WS_IPX_PTYPE:
3480 return set_ipx_packettype(s, *(int*)optval);
3482 case WS_IPX_FILTERPTYPE:
3483 /* Sets the receive filter packet type, at the moment we don't support it */
3484 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
3485 /* Returning 0 is better for now than returning a SOCKET_ERROR */
3486 return 0;
3488 default:
3489 FIXME("opt_name:%x\n", optname);
3490 return SOCKET_ERROR;
3492 break; /* case WS_NSPROTO_IPX */
3493 #endif
3495 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3496 case WS_IPPROTO_TCP:
3497 switch(optname)
3499 case WS_TCP_NODELAY:
3500 convert_sockopt(&level, &optname);
3501 break;
3502 default:
3503 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3504 return SOCKET_ERROR;
3506 break;
3508 case WS_IPPROTO_IP:
3509 switch(optname)
3511 case WS_IP_ADD_MEMBERSHIP:
3512 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_ADD_MEMBERSHIP, optval, optlen );
3514 case WS_IP_ADD_SOURCE_MEMBERSHIP:
3515 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_ADD_SOURCE_MEMBERSHIP, optval, optlen );
3517 case WS_IP_BLOCK_SOURCE:
3518 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_BLOCK_SOURCE, optval, optlen );
3520 case WS_IP_DONTFRAGMENT:
3521 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_DONTFRAGMENT, optval, optlen );
3523 case WS_IP_DROP_MEMBERSHIP:
3524 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_DROP_MEMBERSHIP, optval, optlen );
3526 case WS_IP_DROP_SOURCE_MEMBERSHIP:
3527 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_DROP_SOURCE_MEMBERSHIP, optval, optlen );
3529 case WS_IP_HDRINCL:
3530 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_HDRINCL, optval, optlen );
3532 case WS_IP_MULTICAST_IF:
3533 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_MULTICAST_IF, optval, optlen );
3535 case WS_IP_MULTICAST_LOOP:
3536 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_MULTICAST_LOOP, optval, optlen );
3538 case WS_IP_MULTICAST_TTL:
3539 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_MULTICAST_TTL, optval, optlen );
3541 case WS_IP_OPTIONS:
3542 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_OPTIONS, optval, optlen );
3544 case WS_IP_PKTINFO:
3545 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_PKTINFO, optval, optlen );
3547 case WS_IP_TOS:
3548 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_TOS, optval, optlen );
3550 case WS_IP_TTL:
3551 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_TTL, optval, optlen );
3553 case WS_IP_UNBLOCK_SOURCE:
3554 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_UNBLOCK_SOURCE, optval, optlen );
3556 case WS_IP_UNICAST_IF:
3557 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_UNICAST_IF, optval, optlen );
3559 default:
3560 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3561 return SOCKET_ERROR;
3563 break;
3565 case WS_IPPROTO_IPV6:
3566 switch(optname)
3568 case WS_IPV6_ADD_MEMBERSHIP:
3569 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IPV6_ADD_MEMBERSHIP, optval, optlen );
3571 case WS_IPV6_DONTFRAG:
3572 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IPV6_DONTFRAG, optval, optlen );
3574 case WS_IPV6_DROP_MEMBERSHIP:
3575 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IPV6_DROP_MEMBERSHIP, optval, optlen );
3577 case WS_IPV6_MULTICAST_HOPS:
3578 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IPV6_MULTICAST_HOPS, optval, optlen );
3580 case WS_IPV6_MULTICAST_IF:
3581 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IPV6_MULTICAST_IF, optval, optlen );
3583 case WS_IPV6_MULTICAST_LOOP:
3584 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IPV6_MULTICAST_LOOP, optval, optlen );
3586 case WS_IPV6_PROTECTION_LEVEL:
3587 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
3588 return 0;
3590 case WS_IPV6_UNICAST_HOPS:
3591 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IPV6_UNICAST_HOPS, optval, optlen );
3593 case WS_IPV6_UNICAST_IF:
3594 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IPV6_UNICAST_IF, optval, optlen );
3596 case WS_IPV6_V6ONLY:
3597 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IPV6_V6ONLY, optval, optlen );
3599 default:
3600 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
3601 return SOCKET_ERROR;
3603 break;
3605 default:
3606 WARN("Unknown level: 0x%08x\n", level);
3607 SetLastError(WSAEINVAL);
3608 return SOCKET_ERROR;
3609 } /* end switch(level) */
3611 /* avoid endianness issues if argument is a 16-bit int */
3612 if (optval && optlen < sizeof(int))
3614 woptval= *((const INT16 *) optval);
3615 optval= (char*) &woptval;
3616 woptval&= (1 << optlen * 8) - 1;
3617 optlen=sizeof(int);
3619 fd = get_sock_fd( s, 0, NULL );
3620 if (fd == -1) return SOCKET_ERROR;
3622 if (setsockopt(fd, level, optname, optval, optlen) == 0)
3624 #ifdef __APPLE__
3625 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
3626 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
3628 SetLastError(wsaErrno());
3629 release_sock_fd( s, fd );
3630 return SOCKET_ERROR;
3632 #endif
3633 release_sock_fd( s, fd );
3634 return 0;
3636 TRACE("Setting socket error, %d\n", wsaErrno());
3637 SetLastError(wsaErrno());
3638 release_sock_fd( s, fd );
3640 return SOCKET_ERROR;
3644 /***********************************************************************
3645 * shutdown (ws2_32.22)
3647 int WINAPI WS_shutdown( SOCKET s, int how )
3649 IO_STATUS_BLOCK io;
3650 NTSTATUS status;
3652 TRACE( "socket %#lx, how %u\n", s, how );
3654 status = NtDeviceIoControlFile( (HANDLE)s, NULL, NULL, NULL, &io,
3655 IOCTL_AFD_WINE_SHUTDOWN, &how, sizeof(how), NULL, 0 );
3656 SetLastError( NtStatusToWSAError( status ) );
3657 return status ? -1 : 0;
3661 /***********************************************************************
3662 * socket (WS2_32.23)
3664 SOCKET WINAPI WS_socket(int af, int type, int protocol)
3666 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
3668 return WSASocketW( af, type, protocol, NULL, 0,
3669 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
3673 /***********************************************************************
3674 * WSAEnumNetworkEvents (ws2_32.@)
3676 int WINAPI WSAEnumNetworkEvents( SOCKET s, WSAEVENT event, WSANETWORKEVENTS *ret_events )
3678 struct afd_get_events_params params;
3679 IO_STATUS_BLOCK io;
3680 NTSTATUS status;
3682 TRACE( "socket %#lx, event %p, events %p\n", s, event, ret_events );
3684 ResetEvent( event );
3686 status = NtDeviceIoControlFile( (HANDLE)s, NULL, NULL, NULL, &io, IOCTL_AFD_GET_EVENTS,
3687 NULL, 0, &params, sizeof(params) );
3688 if (!status)
3690 ret_events->lNetworkEvents = afd_poll_flag_to_win32( params.flags );
3692 if (ret_events->lNetworkEvents & FD_READ)
3693 ret_events->iErrorCode[FD_READ_BIT] = NtStatusToWSAError( params.status[AFD_POLL_BIT_READ] );
3695 if (ret_events->lNetworkEvents & FD_WRITE)
3696 ret_events->iErrorCode[FD_WRITE_BIT] = NtStatusToWSAError( params.status[AFD_POLL_BIT_WRITE] );
3698 if (ret_events->lNetworkEvents & FD_OOB)
3699 ret_events->iErrorCode[FD_OOB_BIT] = NtStatusToWSAError( params.status[AFD_POLL_BIT_OOB] );
3701 if (ret_events->lNetworkEvents & FD_ACCEPT)
3702 ret_events->iErrorCode[FD_ACCEPT_BIT] = NtStatusToWSAError( params.status[AFD_POLL_BIT_ACCEPT] );
3704 if (ret_events->lNetworkEvents & FD_CONNECT)
3705 ret_events->iErrorCode[FD_CONNECT_BIT] = NtStatusToWSAError( params.status[AFD_POLL_BIT_CONNECT_ERR] );
3707 if (ret_events->lNetworkEvents & FD_CLOSE)
3709 if (!(ret_events->iErrorCode[FD_CLOSE_BIT] = NtStatusToWSAError( params.status[AFD_POLL_BIT_HUP] )))
3710 ret_events->iErrorCode[FD_CLOSE_BIT] = NtStatusToWSAError( params.status[AFD_POLL_BIT_RESET] );
3713 SetLastError( NtStatusToWSAError( status ) );
3714 return status ? -1 : 0;
3718 static unsigned int afd_poll_flag_from_win32( unsigned int flags )
3720 static const unsigned int map[] =
3722 AFD_POLL_READ,
3723 AFD_POLL_WRITE,
3724 AFD_POLL_OOB,
3725 AFD_POLL_ACCEPT,
3726 AFD_POLL_CONNECT | AFD_POLL_CONNECT_ERR,
3727 AFD_POLL_RESET | AFD_POLL_HUP,
3730 unsigned int i, ret = 0;
3732 for (i = 0; i < ARRAY_SIZE(map); ++i)
3734 if (flags & (1 << i)) ret |= map[i];
3737 return ret;
3741 /***********************************************************************
3742 * WSAEventSelect (ws2_32.@)
3744 int WINAPI WSAEventSelect( SOCKET s, WSAEVENT event, LONG mask )
3746 struct afd_event_select_params params;
3747 IO_STATUS_BLOCK io;
3748 NTSTATUS status;
3750 TRACE( "socket %#lx, event %p, mask %#x\n", s, event, mask );
3752 params.event = event;
3753 params.mask = afd_poll_flag_from_win32( mask );
3755 status = NtDeviceIoControlFile( (HANDLE)s, NULL, NULL, NULL, &io, IOCTL_AFD_EVENT_SELECT,
3756 &params, sizeof(params), NULL, 0 );
3757 SetLastError( NtStatusToWSAError( status ) );
3758 return status ? -1 : 0;
3762 /**********************************************************************
3763 * WSAGetOverlappedResult (WS2_32.40)
3765 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
3766 LPDWORD lpcbTransfer, BOOL fWait,
3767 LPDWORD lpdwFlags )
3769 NTSTATUS status;
3771 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
3772 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
3774 if ( lpOverlapped == NULL )
3776 ERR( "Invalid pointer\n" );
3777 SetLastError(WSA_INVALID_PARAMETER);
3778 return FALSE;
3781 status = lpOverlapped->Internal;
3782 if (status == STATUS_PENDING)
3784 if (!fWait)
3786 SetLastError( WSA_IO_INCOMPLETE );
3787 return FALSE;
3790 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
3791 INFINITE ) == WAIT_FAILED)
3792 return FALSE;
3793 status = lpOverlapped->Internal;
3796 if ( lpcbTransfer )
3797 *lpcbTransfer = lpOverlapped->InternalHigh;
3799 if ( lpdwFlags )
3800 *lpdwFlags = lpOverlapped->u.s.Offset;
3802 SetLastError( NtStatusToWSAError(status) );
3803 return NT_SUCCESS( status );
3807 /***********************************************************************
3808 * WSAAsyncSelect (ws2_32.@)
3810 int WINAPI WSAAsyncSelect( SOCKET s, HWND window, UINT message, LONG mask )
3812 struct afd_message_select_params params;
3813 IO_STATUS_BLOCK io;
3814 NTSTATUS status;
3816 TRACE( "socket %#lx, window %p, message %#x, mask %#x\n", s, window, message, mask );
3818 params.handle = wine_server_obj_handle( (HANDLE)s );
3819 params.window = wine_server_user_handle( window );
3820 params.message = message;
3821 params.mask = afd_poll_flag_from_win32( mask );
3823 status = NtDeviceIoControlFile( (HANDLE)s, NULL, NULL, NULL, &io, IOCTL_AFD_WINE_MESSAGE_SELECT,
3824 &params, sizeof(params), NULL, 0 );
3825 SetLastError( NtStatusToWSAError( status ) );
3826 return status ? -1 : 0;
3830 /***********************************************************************
3831 * WSACreateEvent (WS2_32.31)
3834 WSAEVENT WINAPI WSACreateEvent(void)
3836 /* Create a manual-reset event, with initial state: unsignaled */
3837 TRACE("\n");
3839 return CreateEventW(NULL, TRUE, FALSE, NULL);
3842 /***********************************************************************
3843 * WSACloseEvent (WS2_32.29)
3846 BOOL WINAPI WSACloseEvent(WSAEVENT event)
3848 TRACE ("event=%p\n", event);
3850 return CloseHandle(event);
3853 /***********************************************************************
3854 * WSASocketA (WS2_32.78)
3857 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
3858 LPWSAPROTOCOL_INFOA lpProtocolInfo,
3859 GROUP g, DWORD dwFlags)
3861 INT len;
3862 WSAPROTOCOL_INFOW info;
3864 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
3865 af, type, protocol, lpProtocolInfo, g, dwFlags);
3867 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
3869 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
3870 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
3871 info.szProtocol, WSAPROTOCOL_LEN + 1);
3873 if (!len)
3875 SetLastError(WSAEINVAL);
3876 return SOCKET_ERROR;
3879 return WSASocketW(af, type, protocol, &info, g, dwFlags);
3882 /***********************************************************************
3883 * WSASocketW (WS2_32.79)
3886 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
3887 LPWSAPROTOCOL_INFOW lpProtocolInfo,
3888 GROUP g, DWORD flags)
3890 static const WCHAR afdW[] = {'\\','D','e','v','i','c','e','\\','A','f','d',0};
3891 struct afd_create_params create_params;
3892 OBJECT_ATTRIBUTES attr;
3893 UNICODE_STRING string;
3894 IO_STATUS_BLOCK io;
3895 NTSTATUS status;
3896 HANDLE handle;
3897 SOCKET ret;
3898 DWORD err;
3901 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
3902 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
3905 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
3906 af, type, protocol, lpProtocolInfo, g, flags );
3908 if (!num_startup)
3910 err = WSANOTINITIALISED;
3911 goto done;
3914 /* hack for WSADuplicateSocket */
3915 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00)
3917 ret = lpProtocolInfo->dwServiceFlags3;
3918 TRACE("\tgot duplicate %04lx\n", ret);
3919 if (!socket_list_add(ret))
3921 CloseHandle(SOCKET2HANDLE(ret));
3922 return INVALID_SOCKET;
3924 return ret;
3927 if (lpProtocolInfo)
3929 if (af == FROM_PROTOCOL_INFO || !af)
3930 af = lpProtocolInfo->iAddressFamily;
3931 if (type == FROM_PROTOCOL_INFO || !type)
3932 type = lpProtocolInfo->iSocketType;
3933 if (protocol == FROM_PROTOCOL_INFO || !protocol)
3934 protocol = lpProtocolInfo->iProtocol;
3937 if (!af && !protocol)
3939 WSASetLastError(WSAEINVAL);
3940 return INVALID_SOCKET;
3943 if (!af && lpProtocolInfo)
3945 WSASetLastError(WSAEAFNOSUPPORT);
3946 return INVALID_SOCKET;
3949 if (!af || !type || !protocol)
3951 unsigned int i;
3953 for (i = 0; i < ARRAY_SIZE(supported_protocols); ++i)
3955 const WSAPROTOCOL_INFOW *info = &supported_protocols[i];
3957 if (af && af != info->iAddressFamily) continue;
3958 if (type && type != info->iSocketType) continue;
3959 if (protocol && (protocol < info->iProtocol ||
3960 protocol > info->iProtocol + info->iProtocolMaxOffset)) continue;
3961 if (!protocol && !(info->dwProviderFlags & PFL_MATCHES_PROTOCOL_ZERO)) continue;
3963 if (!af) af = supported_protocols[i].iAddressFamily;
3964 if (!type) type = supported_protocols[i].iSocketType;
3965 if (!protocol) protocol = supported_protocols[i].iProtocol;
3966 break;
3970 RtlInitUnicodeString(&string, afdW);
3971 InitializeObjectAttributes(&attr, &string, (flags & WSA_FLAG_NO_HANDLE_INHERIT) ? 0 : OBJ_INHERIT, NULL, NULL);
3972 if ((status = NtOpenFile(&handle, GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, &attr,
3973 &io, 0, (flags & WSA_FLAG_OVERLAPPED) ? 0 : FILE_SYNCHRONOUS_IO_NONALERT)))
3975 WARN("Failed to create socket, status %#x.\n", status);
3976 WSASetLastError(NtStatusToWSAError(status));
3977 return INVALID_SOCKET;
3980 create_params.family = af;
3981 create_params.type = type;
3982 create_params.protocol = protocol;
3983 create_params.flags = flags & ~(WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
3984 if ((status = NtDeviceIoControlFile(handle, NULL, NULL, NULL, &io,
3985 IOCTL_AFD_WINE_CREATE, &create_params, sizeof(create_params), NULL, 0)))
3987 WARN("Failed to initialize socket, status %#x.\n", status);
3988 err = RtlNtStatusToDosError( status );
3989 if (err == WSAEACCES) /* raw socket denied */
3991 if (type == SOCK_RAW)
3992 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
3993 else
3994 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
3996 WSASetLastError(err);
3997 NtClose(handle);
3998 return INVALID_SOCKET;
4001 ret = HANDLE2SOCKET(handle);
4002 TRACE("\tcreated %04lx\n", ret );
4004 if (!socket_list_add(ret))
4006 CloseHandle(handle);
4007 return INVALID_SOCKET;
4009 return ret;
4011 done:
4012 WARN("\t\tfailed, error %d!\n", err);
4013 SetLastError(err);
4014 return INVALID_SOCKET;
4017 /***********************************************************************
4018 * WSAJoinLeaf (WS2_32.58)
4021 SOCKET WINAPI WSAJoinLeaf(
4022 SOCKET s,
4023 const struct WS_sockaddr *addr,
4024 int addrlen,
4025 LPWSABUF lpCallerData,
4026 LPWSABUF lpCalleeData,
4027 LPQOS lpSQOS,
4028 LPQOS lpGQOS,
4029 DWORD dwFlags)
4031 FIXME("stub.\n");
4032 return INVALID_SOCKET;
4035 /***********************************************************************
4036 * __WSAFDIsSet (WS2_32.151)
4038 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
4040 int i = set->fd_count, ret = 0;
4042 while (i--)
4043 if (set->fd_array[i] == s)
4045 ret = 1;
4046 break;
4049 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s, set, set->fd_count, ret);
4050 return ret;
4053 /***********************************************************************
4054 * WSAIsBlocking (WS2_32.114)
4056 BOOL WINAPI WSAIsBlocking(void)
4058 /* By default WinSock should set all its sockets to non-blocking mode
4059 * and poll in PeekMessage loop when processing "blocking" ones. This
4060 * function is supposed to tell if the program is in this loop. Our
4061 * blocking calls are truly blocking so we always return FALSE.
4063 * Note: It is allowed to call this function without prior WSAStartup().
4066 TRACE("\n");
4067 return FALSE;
4070 /***********************************************************************
4071 * WSACancelBlockingCall (WS2_32.113)
4073 INT WINAPI WSACancelBlockingCall(void)
4075 TRACE("\n");
4076 return 0;
4079 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
4081 FIXME("How was this called?\n");
4082 return x();
4086 /***********************************************************************
4087 * WSASetBlockingHook (WS2_32.109)
4089 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
4091 FARPROC prev = blocking_hook;
4092 blocking_hook = lpBlockFunc;
4093 TRACE("hook %p\n", lpBlockFunc);
4094 return prev;
4098 /***********************************************************************
4099 * WSAUnhookBlockingHook (WS2_32.110)
4101 INT WINAPI WSAUnhookBlockingHook(void)
4103 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
4104 return 0;
4108 /***********************************************************************
4109 * WSARecv (WS2_32.67)
4111 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4112 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
4113 LPWSAOVERLAPPED lpOverlapped,
4114 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
4116 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
4117 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
4121 /***********************************************************************
4122 * WSARecvFrom (WS2_32.69)
4124 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4125 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
4126 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
4127 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4130 /* Garena hooks WSARecvFrom(), so we need a wrapper */
4131 return WS2_recv_base( s, lpBuffers, dwBufferCount,
4132 lpNumberOfBytesRecvd, lpFlags,
4133 lpFrom, lpFromlen,
4134 lpOverlapped, lpCompletionRoutine, NULL );
4138 /***********************************************************************
4139 * WSAAccept (ws2_32.@)
4141 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, int *addrlen,
4142 LPCONDITIONPROC callback, DWORD_PTR context )
4144 int ret = 0, size;
4145 WSABUF caller_id, caller_data, callee_id, callee_data;
4146 struct WS_sockaddr src_addr, dst_addr;
4147 GROUP group;
4148 SOCKET cs;
4150 TRACE( "socket %#lx, addr %p, addrlen %p, callback %p, context %#lx\n",
4151 s, addr, addrlen, callback, context );
4153 cs = WS_accept(s, addr, addrlen);
4154 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
4155 if (!callback) return cs;
4157 if (addr && addrlen)
4159 caller_id.buf = (char *)addr;
4160 caller_id.len = *addrlen;
4162 else
4164 size = sizeof(src_addr);
4165 WS_getpeername( cs, &src_addr, &size );
4166 caller_id.buf = (char *)&src_addr;
4167 caller_id.len = size;
4169 caller_data.buf = NULL;
4170 caller_data.len = 0;
4172 size = sizeof(dst_addr);
4173 WS_getsockname( cs, &dst_addr, &size );
4175 callee_id.buf = (char *)&dst_addr;
4176 callee_id.len = sizeof(dst_addr);
4178 ret = (*callback)( &caller_id, &caller_data, NULL, NULL,
4179 &callee_id, &callee_data, &group, context );
4181 switch (ret)
4183 case CF_ACCEPT:
4184 return cs;
4186 case CF_DEFER:
4188 obj_handle_t server_handle = cs;
4189 IO_STATUS_BLOCK io;
4190 NTSTATUS status;
4192 status = NtDeviceIoControlFile( (HANDLE)s, NULL, NULL, NULL, &io, IOCTL_AFD_WINE_DEFER,
4193 &server_handle, sizeof(server_handle), NULL, 0 );
4194 SetLastError( status ? RtlNtStatusToDosError( status ) : WSATRY_AGAIN );
4195 return -1;
4198 case CF_REJECT:
4199 WS_closesocket( cs );
4200 SetLastError( WSAECONNREFUSED );
4201 return SOCKET_ERROR;
4203 default:
4204 FIXME( "Unknown return type from Condition function\n" );
4205 SetLastError( WSAENOTSOCK );
4206 return SOCKET_ERROR;
4211 /***********************************************************************
4212 * WSADuplicateSocketA (WS2_32.32)
4214 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
4216 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
4219 /***********************************************************************
4220 * WSADuplicateSocketW (WS2_32.33)
4222 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
4224 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
4228 /***********************************************************************
4229 * WSAGetQOSByName (WS2_32.41)
4231 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
4233 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
4234 return FALSE;
4238 /***********************************************************************
4239 * WSARecvDisconnect (WS2_32.68)
4241 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
4243 TRACE( "(%04lx %p)\n", s, disconnectdata );
4245 return WS_shutdown( s, SD_RECEIVE );
4249 static BOOL protocol_matches_filter( const int *filter, int protocol )
4251 if (!filter) return TRUE;
4252 while (*filter)
4254 if (protocol == *filter++) return TRUE;
4256 return FALSE;
4259 /*****************************************************************************
4260 * WSAEnumProtocolsA [WS2_32.@]
4262 * see function WSAEnumProtocolsW
4264 int WINAPI WSAEnumProtocolsA( int *filter, WSAPROTOCOL_INFOA *protocols, DWORD *size )
4266 DWORD i, count = 0;
4268 TRACE("filter %p, protocols %p, size %p\n", filter, protocols, size);
4270 for (i = 0; i < ARRAY_SIZE(supported_protocols); ++i)
4272 if (protocol_matches_filter( filter, supported_protocols[i].iProtocol ))
4273 ++count;
4276 if (!protocols || *size < count * sizeof(WSAPROTOCOL_INFOA))
4278 *size = count * sizeof(WSAPROTOCOL_INFOA);
4279 WSASetLastError( WSAENOBUFS );
4280 return SOCKET_ERROR;
4283 count = 0;
4284 for (i = 0; i < ARRAY_SIZE(supported_protocols); ++i)
4286 if (protocol_matches_filter( filter, supported_protocols[i].iProtocol ))
4288 memcpy( &protocols[count], &supported_protocols[i], offsetof( WSAPROTOCOL_INFOW, szProtocol ) );
4289 WideCharToMultiByte( CP_ACP, 0, supported_protocols[i].szProtocol, -1,
4290 protocols[count].szProtocol, sizeof(protocols[count].szProtocol), NULL, NULL );
4291 ++count;
4294 return count;
4297 /*****************************************************************************
4298 * WSAEnumProtocolsW [WS2_32.@]
4300 * Retrieves information about specified set of active network protocols.
4302 * PARAMS
4303 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
4304 * retrieves information on all available protocols.
4305 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
4306 * structures.
4307 * len [I/O] Pointer to a variable specifying buffer size. On output
4308 * the variable holds the number of bytes needed when the
4309 * specified size is too small.
4311 * RETURNS
4312 * Success: number of WSAPROTOCOL_INFO structures in buffer.
4313 * Failure: SOCKET_ERROR
4315 * NOTES
4316 * NT4SP5 does not return SPX if protocols == NULL
4318 * BUGS
4319 * - NT4SP5 returns in addition these list of NETBIOS protocols
4320 * (address family 17), each entry two times one for socket type 2 and 5
4322 * iProtocol szProtocol
4323 * 0x80000000 \Device\NwlnkNb
4324 * 0xfffffffa \Device\NetBT_CBENT7
4325 * 0xfffffffb \Device\Nbf_CBENT7
4326 * 0xfffffffc \Device\NetBT_NdisWan5
4327 * 0xfffffffd \Device\NetBT_El9202
4328 * 0xfffffffe \Device\Nbf_El9202
4329 * 0xffffffff \Device\Nbf_NdisWan4
4331 * - there is no check that the operating system supports the returned
4332 * protocols
4334 int WINAPI WSAEnumProtocolsW( int *filter, WSAPROTOCOL_INFOW *protocols, DWORD *size )
4336 DWORD i, count = 0;
4338 TRACE("filter %p, protocols %p, size %p\n", filter, protocols, size);
4340 for (i = 0; i < ARRAY_SIZE(supported_protocols); ++i)
4342 if (protocol_matches_filter( filter, supported_protocols[i].iProtocol ))
4343 ++count;
4346 if (!protocols || *size < count * sizeof(WSAPROTOCOL_INFOW))
4348 *size = count * sizeof(WSAPROTOCOL_INFOW);
4349 WSASetLastError( WSAENOBUFS );
4350 return SOCKET_ERROR;
4353 count = 0;
4354 for (i = 0; i < ARRAY_SIZE(supported_protocols); ++i)
4356 if (protocol_matches_filter( filter, supported_protocols[i].iProtocol ))
4357 protocols[count++] = supported_protocols[i];
4359 return count;