sapi: Add SpMMAudioOut stub.
[wine.git] / dlls / ws2_32 / socket.c
blob710ec8cbb269f2f3afb19837d3e3692ece94ec90
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 "ws2_32_private.h"
31 #define FILE_USE_FILE_POINTER_POSITION ((LONGLONG)-2)
33 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
34 WINE_DECLARE_DEBUG_CHANNEL(winediag);
36 #define TIMEOUT_INFINITE _I64_MAX
38 #define u64_from_user_ptr(ptr) ((ULONGLONG)(uintptr_t)(ptr))
40 static const WSAPROTOCOL_INFOW supported_protocols[] =
43 .dwServiceFlags1 = XP1_IFS_HANDLES | XP1_EXPEDITED_DATA | XP1_GRACEFUL_CLOSE
44 | XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY,
45 .dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO,
46 .ProviderId = {0xe70f1aa0, 0xab8b, 0x11cf, {0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}},
47 .dwCatalogEntryId = 1001,
48 .ProtocolChain.ChainLen = 1,
49 .iVersion = 2,
50 .iAddressFamily = AF_INET,
51 .iMaxSockAddr = sizeof(struct sockaddr_in),
52 .iMinSockAddr = sizeof(struct sockaddr_in),
53 .iSocketType = SOCK_STREAM,
54 .iProtocol = IPPROTO_TCP,
55 .szProtocol = L"TCP/IP",
58 .dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST
59 | XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED | XP1_CONNECTIONLESS,
60 .dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO,
61 .ProviderId = {0xe70f1aa0, 0xab8b, 0x11cf, {0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}},
62 .dwCatalogEntryId = 1002,
63 .ProtocolChain.ChainLen = 1,
64 .iVersion = 2,
65 .iAddressFamily = AF_INET,
66 .iMaxSockAddr = sizeof(struct sockaddr_in),
67 .iMinSockAddr = sizeof(struct sockaddr_in),
68 .iSocketType = SOCK_DGRAM,
69 .iProtocol = IPPROTO_UDP,
70 .dwMessageSize = 0xffbb,
71 .szProtocol = L"UDP/IP",
74 .dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST
75 | XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED | XP1_CONNECTIONLESS,
76 .dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO | PFL_HIDDEN,
77 .ProviderId = {0xe70f1aa0, 0xab8b, 0x11cf, {0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}},
78 .dwCatalogEntryId = 1003,
79 .ProtocolChain.ChainLen = 1,
80 .iVersion = 2,
81 .iAddressFamily = AF_INET,
82 .iMaxSockAddr = sizeof(struct sockaddr_in),
83 .iMinSockAddr = sizeof(struct sockaddr_in),
84 .iSocketType = SOCK_RAW,
85 .iProtocol = 0,
86 .iProtocolMaxOffset = 255,
87 .dwMessageSize = 0x8000,
88 .szProtocol = L"MSAFD Tcpip [RAW/IP]",
91 .dwServiceFlags1 = XP1_IFS_HANDLES | XP1_EXPEDITED_DATA | XP1_GRACEFUL_CLOSE
92 | XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY,
93 .dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO,
94 .ProviderId = {0xf9eab0c0, 0x26d4, 0x11d0, {0xbb, 0xbf, 0x00, 0xaa, 0x00, 0x6c, 0x34, 0xe4}},
95 .dwCatalogEntryId = 1004,
96 .ProtocolChain.ChainLen = 1,
97 .iVersion = 2,
98 .iAddressFamily = AF_INET6,
99 .iMaxSockAddr = sizeof(struct sockaddr_in6),
100 .iMinSockAddr = sizeof(struct sockaddr_in6),
101 .iSocketType = SOCK_STREAM,
102 .iProtocol = IPPROTO_TCP,
103 .szProtocol = L"TCP/IPv6",
106 .dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST
107 | XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED | XP1_CONNECTIONLESS,
108 .dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO,
109 .ProviderId = {0xf9eab0c0, 0x26d4, 0x11d0, {0xbb, 0xbf, 0x00, 0xaa, 0x00, 0x6c, 0x34, 0xe4}},
110 .dwCatalogEntryId = 1005,
111 .ProtocolChain.ChainLen = 1,
112 .iVersion = 2,
113 .iAddressFamily = AF_INET6,
114 .iMaxSockAddr = sizeof(struct sockaddr_in6),
115 .iMinSockAddr = sizeof(struct sockaddr_in6),
116 .iSocketType = SOCK_DGRAM,
117 .iProtocol = IPPROTO_UDP,
118 .dwMessageSize = 0xffbb,
119 .szProtocol = L"UDP/IPv6",
122 .dwServiceFlags1 = XP1_PARTIAL_MESSAGE | XP1_SUPPORT_BROADCAST
123 | XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED | XP1_CONNECTIONLESS,
124 .dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO,
125 .ProviderId = {0x11058240, 0xbe47, 0x11cf, {0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}},
126 .dwCatalogEntryId = 1030,
127 .ProtocolChain.ChainLen = 1,
128 .iVersion = 2,
129 .iAddressFamily = AF_IPX,
130 .iMaxSockAddr = sizeof(struct sockaddr),
131 .iMinSockAddr = sizeof(struct sockaddr_ipx),
132 .iSocketType = SOCK_DGRAM,
133 .iProtocol = NSPROTO_IPX,
134 .iProtocolMaxOffset = 255,
135 .dwMessageSize = 0x240,
136 .szProtocol = L"IPX",
139 .dwServiceFlags1 = XP1_IFS_HANDLES | XP1_PSEUDO_STREAM | XP1_MESSAGE_ORIENTED
140 | XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY,
141 .dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO,
142 .ProviderId = {0x11058241, 0xbe47, 0x11cf, {0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}},
143 .dwCatalogEntryId = 1031,
144 .ProtocolChain.ChainLen = 1,
145 .iVersion = 2,
146 .iAddressFamily = AF_IPX,
147 .iMaxSockAddr = sizeof(struct sockaddr),
148 .iMinSockAddr = sizeof(struct sockaddr_ipx),
149 .iSocketType = SOCK_SEQPACKET,
150 .iProtocol = NSPROTO_SPX,
151 .dwMessageSize = UINT_MAX,
152 .szProtocol = L"SPX",
155 .dwServiceFlags1 = XP1_IFS_HANDLES | XP1_GRACEFUL_CLOSE | XP1_PSEUDO_STREAM
156 | XP1_MESSAGE_ORIENTED | XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY,
157 .dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO,
158 .ProviderId = {0x11058241, 0xbe47, 0x11cf, {0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}},
159 .dwCatalogEntryId = 1033,
160 .ProtocolChain.ChainLen = 1,
161 .iVersion = 2,
162 .iAddressFamily = AF_IPX,
163 .iMaxSockAddr = sizeof(struct sockaddr),
164 .iMinSockAddr = sizeof(struct sockaddr_ipx),
165 .iSocketType = SOCK_SEQPACKET,
166 .iProtocol = NSPROTO_SPXII,
167 .dwMessageSize = UINT_MAX,
168 .szProtocol = L"SPX II",
172 DECLARE_CRITICAL_SECTION(cs_socket_list);
174 static SOCKET *socket_list;
175 static unsigned int socket_list_size;
177 const char *debugstr_sockaddr( const struct sockaddr *a )
179 if (!a) return "(nil)";
180 switch (a->sa_family)
182 case AF_INET:
184 char buf[16];
185 const char *p;
186 struct sockaddr_in *sin = (struct sockaddr_in *)a;
188 p = inet_ntop( AF_INET, &sin->sin_addr, buf, sizeof(buf) );
189 if (!p)
190 p = "(unknown IPv4 address)";
192 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
193 p, ntohs(sin->sin_port));
195 case AF_INET6:
197 char buf[46];
198 const char *p;
199 struct sockaddr_in6 *sin = (struct sockaddr_in6 *)a;
201 p = inet_ntop( AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
202 if (!p)
203 p = "(unknown IPv6 address)";
204 return wine_dbg_sprintf("{ family AF_INET6, address %s, flow label %#lx, port %d, scope %lu }",
205 p, sin->sin6_flowinfo, ntohs(sin->sin6_port), sin->sin6_scope_id );
207 case AF_IPX:
209 int i;
210 char netnum[16], nodenum[16];
211 struct sockaddr_ipx *sin = (struct sockaddr_ipx *)a;
213 for (i = 0;i < 4; i++) sprintf(netnum + i * 2, "%02X", (unsigned char) sin->sa_netnum[i]);
214 for (i = 0;i < 6; i++) sprintf(nodenum + i * 2, "%02X", (unsigned char) sin->sa_nodenum[i]);
216 return wine_dbg_sprintf("{ family AF_IPX, address %s.%s, ipx socket %d }",
217 netnum, nodenum, sin->sa_socket);
219 case AF_IRDA:
221 DWORD addr;
223 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
224 addr = ntohl( addr );
225 return wine_dbg_sprintf("{ family AF_IRDA, addr %08lx, name %s }",
226 addr,
227 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
229 default:
230 return wine_dbg_sprintf("{ family %d }", a->sa_family);
234 static inline const char *debugstr_sockopt(int level, int optname)
236 const char *stropt = NULL, *strlevel = NULL;
238 #define DEBUG_SOCKLEVEL(x) case (x): strlevel = #x
239 #define DEBUG_SOCKOPT(x) case (x): stropt = #x; break
241 switch(level)
243 DEBUG_SOCKLEVEL(SOL_SOCKET);
244 switch(optname)
246 DEBUG_SOCKOPT(SO_ACCEPTCONN);
247 DEBUG_SOCKOPT(SO_BROADCAST);
248 DEBUG_SOCKOPT(SO_BSP_STATE);
249 DEBUG_SOCKOPT(SO_CONDITIONAL_ACCEPT);
250 DEBUG_SOCKOPT(SO_CONNECT_TIME);
251 DEBUG_SOCKOPT(SO_DEBUG);
252 DEBUG_SOCKOPT(SO_DONTLINGER);
253 DEBUG_SOCKOPT(SO_DONTROUTE);
254 DEBUG_SOCKOPT(SO_ERROR);
255 DEBUG_SOCKOPT(SO_EXCLUSIVEADDRUSE);
256 DEBUG_SOCKOPT(SO_GROUP_ID);
257 DEBUG_SOCKOPT(SO_GROUP_PRIORITY);
258 DEBUG_SOCKOPT(SO_KEEPALIVE);
259 DEBUG_SOCKOPT(SO_LINGER);
260 DEBUG_SOCKOPT(SO_MAX_MSG_SIZE);
261 DEBUG_SOCKOPT(SO_OOBINLINE);
262 DEBUG_SOCKOPT(SO_OPENTYPE);
263 DEBUG_SOCKOPT(SO_PROTOCOL_INFOA);
264 DEBUG_SOCKOPT(SO_PROTOCOL_INFOW);
265 DEBUG_SOCKOPT(SO_RCVBUF);
266 DEBUG_SOCKOPT(SO_RCVTIMEO);
267 DEBUG_SOCKOPT(SO_REUSEADDR);
268 DEBUG_SOCKOPT(SO_SNDBUF);
269 DEBUG_SOCKOPT(SO_SNDTIMEO);
270 DEBUG_SOCKOPT(SO_TYPE);
271 DEBUG_SOCKOPT(SO_UPDATE_CONNECT_CONTEXT);
273 break;
275 DEBUG_SOCKLEVEL(NSPROTO_IPX);
276 switch(optname)
278 DEBUG_SOCKOPT(IPX_PTYPE);
279 DEBUG_SOCKOPT(IPX_FILTERPTYPE);
280 DEBUG_SOCKOPT(IPX_DSTYPE);
281 DEBUG_SOCKOPT(IPX_RECVHDR);
282 DEBUG_SOCKOPT(IPX_MAXSIZE);
283 DEBUG_SOCKOPT(IPX_ADDRESS);
284 DEBUG_SOCKOPT(IPX_MAX_ADAPTER_NUM);
286 break;
288 DEBUG_SOCKLEVEL(SOL_IRLMP);
289 switch(optname)
291 DEBUG_SOCKOPT(IRLMP_ENUMDEVICES);
293 break;
295 DEBUG_SOCKLEVEL(IPPROTO_TCP);
296 switch(optname)
298 DEBUG_SOCKOPT(TCP_BSDURGENT);
299 DEBUG_SOCKOPT(TCP_EXPEDITED_1122);
300 DEBUG_SOCKOPT(TCP_NODELAY);
302 break;
304 DEBUG_SOCKLEVEL(IPPROTO_IP);
305 switch(optname)
307 DEBUG_SOCKOPT(IP_ADD_MEMBERSHIP);
308 DEBUG_SOCKOPT(IP_DONTFRAGMENT);
309 DEBUG_SOCKOPT(IP_DROP_MEMBERSHIP);
310 DEBUG_SOCKOPT(IP_HDRINCL);
311 DEBUG_SOCKOPT(IP_MULTICAST_IF);
312 DEBUG_SOCKOPT(IP_MULTICAST_LOOP);
313 DEBUG_SOCKOPT(IP_MULTICAST_TTL);
314 DEBUG_SOCKOPT(IP_OPTIONS);
315 DEBUG_SOCKOPT(IP_PKTINFO);
316 DEBUG_SOCKOPT(IP_RECEIVE_BROADCAST);
317 DEBUG_SOCKOPT(IP_RECVTOS);
318 DEBUG_SOCKOPT(IP_RECVTTL);
319 DEBUG_SOCKOPT(IP_TOS);
320 DEBUG_SOCKOPT(IP_TTL);
321 DEBUG_SOCKOPT(IP_UNICAST_IF);
323 break;
325 DEBUG_SOCKLEVEL(IPPROTO_IPV6);
326 switch(optname)
328 DEBUG_SOCKOPT(IPV6_ADD_MEMBERSHIP);
329 DEBUG_SOCKOPT(IPV6_DROP_MEMBERSHIP);
330 DEBUG_SOCKOPT(IPV6_HOPLIMIT);
331 DEBUG_SOCKOPT(IPV6_MULTICAST_IF);
332 DEBUG_SOCKOPT(IPV6_MULTICAST_HOPS);
333 DEBUG_SOCKOPT(IPV6_MULTICAST_LOOP);
334 DEBUG_SOCKOPT(IPV6_PKTINFO);
335 DEBUG_SOCKOPT(IPV6_RECVTCLASS);
336 DEBUG_SOCKOPT(IPV6_UNICAST_HOPS);
337 DEBUG_SOCKOPT(IPV6_V6ONLY);
338 DEBUG_SOCKOPT(IPV6_UNICAST_IF);
339 DEBUG_SOCKOPT(IPV6_DONTFRAG);
341 break;
343 #undef DEBUG_SOCKLEVEL
344 #undef DEBUG_SOCKOPT
346 if (!strlevel)
347 strlevel = wine_dbg_sprintf("0x%x", level);
348 if (!stropt)
349 stropt = wine_dbg_sprintf("0x%x", optname);
351 return wine_dbg_sprintf("level %s, name %s", strlevel, stropt);
354 static inline const char *debugstr_optval(const char *optval, int optlenval)
356 if (optval && !IS_INTRESOURCE(optval) && optlenval >= 1 && optlenval <= sizeof(DWORD))
358 DWORD value = 0;
359 memcpy(&value, optval, optlenval);
360 return wine_dbg_sprintf("%p (%lu)", optval, value);
362 return wine_dbg_sprintf("%p", optval);
365 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
366 #define SOCKET2HANDLE(s) ((HANDLE)(s))
367 #define HANDLE2SOCKET(h) ((SOCKET)(h))
369 static BOOL socket_list_add(SOCKET socket)
371 unsigned int i, new_size;
372 SOCKET *new_array;
374 EnterCriticalSection(&cs_socket_list);
375 for (i = 0; i < socket_list_size; ++i)
377 if (!socket_list[i])
379 socket_list[i] = socket;
380 LeaveCriticalSection(&cs_socket_list);
381 return TRUE;
384 new_size = max(socket_list_size * 2, 8);
385 if (!(new_array = realloc( socket_list, new_size * sizeof(*socket_list) )))
387 LeaveCriticalSection(&cs_socket_list);
388 return FALSE;
390 socket_list = new_array;
391 memset(socket_list + socket_list_size, 0, (new_size - socket_list_size) * sizeof(*socket_list));
392 socket_list[socket_list_size] = socket;
393 socket_list_size = new_size;
394 LeaveCriticalSection(&cs_socket_list);
395 return TRUE;
399 static BOOL socket_list_find( SOCKET socket )
401 unsigned int i;
403 if (!socket) return FALSE;
405 EnterCriticalSection( &cs_socket_list );
406 for (i = 0; i < socket_list_size; ++i)
408 if (socket_list[i] == socket)
410 LeaveCriticalSection( &cs_socket_list );
411 return TRUE;
414 LeaveCriticalSection( &cs_socket_list );
415 return FALSE;
419 static BOOL socket_list_remove( SOCKET socket )
421 unsigned int i;
423 if (!socket) return FALSE;
425 EnterCriticalSection(&cs_socket_list);
426 for (i = 0; i < socket_list_size; ++i)
428 if (socket_list[i] == socket)
430 socket_list[i] = 0;
431 LeaveCriticalSection( &cs_socket_list );
432 return TRUE;
435 LeaveCriticalSection(&cs_socket_list);
436 return FALSE;
439 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
441 int num_startup;
442 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
444 /* function prototypes */
445 static int ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size);
447 static DWORD NtStatusToWSAError( NTSTATUS status )
449 static const struct
451 NTSTATUS status;
452 DWORD error;
454 errors[] =
456 {STATUS_PENDING, ERROR_IO_PENDING},
458 {STATUS_BUFFER_OVERFLOW, WSAEMSGSIZE},
460 {STATUS_NOT_IMPLEMENTED, WSAEOPNOTSUPP},
461 {STATUS_ACCESS_VIOLATION, WSAEFAULT},
462 {STATUS_PAGEFILE_QUOTA, WSAENOBUFS},
463 {STATUS_INVALID_HANDLE, WSAENOTSOCK},
464 {STATUS_NO_SUCH_DEVICE, WSAENETDOWN},
465 {STATUS_NO_SUCH_FILE, WSAENETDOWN},
466 {STATUS_NO_MEMORY, WSAENOBUFS},
467 {STATUS_CONFLICTING_ADDRESSES, WSAENOBUFS},
468 {STATUS_ACCESS_DENIED, WSAEACCES},
469 {STATUS_BUFFER_TOO_SMALL, WSAEFAULT},
470 {STATUS_OBJECT_TYPE_MISMATCH, WSAENOTSOCK},
471 {STATUS_OBJECT_NAME_NOT_FOUND, WSAENETDOWN},
472 {STATUS_OBJECT_PATH_NOT_FOUND, WSAENETDOWN},
473 {STATUS_SHARING_VIOLATION, WSAEADDRINUSE},
474 {STATUS_QUOTA_EXCEEDED, WSAENOBUFS},
475 {STATUS_TOO_MANY_PAGING_FILES, WSAENOBUFS},
476 {STATUS_INSUFFICIENT_RESOURCES, WSAENOBUFS},
477 {STATUS_WORKING_SET_QUOTA, WSAENOBUFS},
478 {STATUS_DEVICE_NOT_READY, WSAEWOULDBLOCK},
479 {STATUS_PIPE_DISCONNECTED, WSAESHUTDOWN},
480 {STATUS_IO_TIMEOUT, WSAETIMEDOUT},
481 {STATUS_NOT_SUPPORTED, WSAEOPNOTSUPP},
482 {STATUS_REMOTE_NOT_LISTENING, WSAECONNREFUSED},
483 {STATUS_BAD_NETWORK_PATH, WSAENETUNREACH},
484 {STATUS_NETWORK_BUSY, WSAENETDOWN},
485 {STATUS_INVALID_NETWORK_RESPONSE, WSAENETDOWN},
486 {STATUS_UNEXPECTED_NETWORK_ERROR, WSAENETDOWN},
487 {STATUS_REQUEST_NOT_ACCEPTED, WSAEWOULDBLOCK},
488 {STATUS_CANCELLED, ERROR_OPERATION_ABORTED},
489 {STATUS_COMMITMENT_LIMIT, WSAENOBUFS},
490 {STATUS_LOCAL_DISCONNECT, WSAECONNABORTED},
491 {STATUS_REMOTE_DISCONNECT, WSAECONNRESET},
492 {STATUS_REMOTE_RESOURCES, WSAENOBUFS},
493 {STATUS_LINK_FAILED, WSAECONNRESET},
494 {STATUS_LINK_TIMEOUT, WSAETIMEDOUT},
495 {STATUS_INVALID_CONNECTION, WSAENOTCONN},
496 {STATUS_INVALID_ADDRESS, WSAEADDRNOTAVAIL},
497 {STATUS_INVALID_BUFFER_SIZE, WSAEMSGSIZE},
498 {STATUS_INVALID_ADDRESS_COMPONENT, WSAEADDRNOTAVAIL},
499 {STATUS_TOO_MANY_ADDRESSES, WSAENOBUFS},
500 {STATUS_ADDRESS_ALREADY_EXISTS, WSAEADDRINUSE},
501 {STATUS_CONNECTION_DISCONNECTED, WSAECONNRESET},
502 {STATUS_CONNECTION_RESET, WSAECONNRESET},
503 {STATUS_TRANSACTION_ABORTED, WSAECONNABORTED},
504 {STATUS_CONNECTION_REFUSED, WSAECONNREFUSED},
505 {STATUS_GRACEFUL_DISCONNECT, WSAEDISCON},
506 {STATUS_CONNECTION_ACTIVE, WSAEISCONN},
507 {STATUS_NETWORK_UNREACHABLE, WSAENETUNREACH},
508 {STATUS_HOST_UNREACHABLE, WSAEHOSTUNREACH},
509 {STATUS_PROTOCOL_UNREACHABLE, WSAENETUNREACH},
510 {STATUS_PORT_UNREACHABLE, WSAECONNRESET},
511 {STATUS_REQUEST_ABORTED, WSAEINTR},
512 {STATUS_CONNECTION_ABORTED, WSAECONNABORTED},
513 {STATUS_DATATYPE_MISALIGNMENT_ERROR,WSAEFAULT},
514 {STATUS_HOST_DOWN, WSAEHOSTDOWN},
515 {0x80070000 | ERROR_IO_INCOMPLETE, ERROR_IO_INCOMPLETE},
516 {0xc0010000 | ERROR_IO_INCOMPLETE, ERROR_IO_INCOMPLETE},
517 {0xc0070000 | ERROR_IO_INCOMPLETE, ERROR_IO_INCOMPLETE},
520 unsigned int i;
522 for (i = 0; i < ARRAY_SIZE(errors); ++i)
524 if (errors[i].status == status)
525 return errors[i].error;
528 return NT_SUCCESS(status) ? RtlNtStatusToDosErrorNoTeb(status) : WSAEINVAL;
532 struct per_thread_data *get_per_thread_data(void)
534 struct per_thread_data *data = NtCurrentTeb()->WinSockData;
536 if (!data)
538 data = calloc( 1, sizeof(*data) );
539 NtCurrentTeb()->WinSockData = data;
541 return data;
544 static void free_per_thread_data(void)
546 struct per_thread_data *data = NtCurrentTeb()->WinSockData;
548 if (!data) return;
550 CloseHandle( data->sync_event );
552 /* delete scratch buffers */
553 free( data->he_buffer );
554 free( data->se_buffer );
555 free( data->pe_buffer );
557 free( data );
558 NtCurrentTeb()->WinSockData = NULL;
561 static HANDLE get_sync_event(void)
563 struct per_thread_data *data;
565 if (!(data = get_per_thread_data())) return NULL;
566 if (!data->sync_event)
567 data->sync_event = CreateEventW( NULL, TRUE, FALSE, NULL );
568 return data->sync_event;
571 static DWORD wait_event_alertable( HANDLE event )
573 DWORD ret;
575 while ((ret = WaitForSingleObjectEx( event, INFINITE, TRUE )) == WAIT_IO_COMPLETION)
577 return ret;
580 BOOL WINAPI DllMain( HINSTANCE instance, DWORD reason, void *reserved )
582 switch (reason)
584 case DLL_PROCESS_ATTACH:
585 return !__wine_init_unix_call();
587 case DLL_THREAD_DETACH:
588 free_per_thread_data();
590 return TRUE;
594 /***********************************************************************
595 * WSAStartup (WS2_32.115)
597 int WINAPI WSAStartup( WORD version, WSADATA *data )
599 TRACE( "version %#x\n", version );
601 if (data)
603 if (!LOBYTE(version) || LOBYTE(version) > 2
604 || (LOBYTE(version) == 2 && HIBYTE(version) > 2))
605 data->wVersion = MAKEWORD(2, 2);
606 else if (LOBYTE(version) == 1 && HIBYTE(version) > 1)
607 data->wVersion = MAKEWORD(1, 1);
608 else
609 data->wVersion = version;
610 data->wHighVersion = MAKEWORD(2, 2);
611 strcpy( data->szDescription, "WinSock 2.0" );
612 strcpy( data->szSystemStatus, "Running" );
613 data->iMaxSockets = (LOBYTE(version) == 1 ? 32767 : 0);
614 data->iMaxUdpDg = (LOBYTE(version) == 1 ? 65467 : 0);
615 /* don't fill lpVendorInfo */
618 if (!LOBYTE(version))
619 return WSAVERNOTSUPPORTED;
621 if (!data) return WSAEFAULT;
623 num_startup++;
624 TRACE( "increasing startup count to %d\n", num_startup );
625 return 0;
629 /***********************************************************************
630 * WSACleanup (WS2_32.116)
632 INT WINAPI WSACleanup(void)
634 TRACE("decreasing startup count from %d\n", num_startup);
635 if (num_startup)
637 if (!--num_startup)
639 unsigned int i;
641 for (i = 0; i < socket_list_size; ++i)
642 CloseHandle(SOCKET2HANDLE(socket_list[i]));
643 memset(socket_list, 0, socket_list_size * sizeof(*socket_list));
645 return 0;
647 SetLastError(WSANOTINITIALISED);
648 return SOCKET_ERROR;
652 /***********************************************************************
653 * WSAGetLastError (WS2_32.111)
655 INT WINAPI WSAGetLastError(void)
657 return GetLastError();
660 /***********************************************************************
661 * WSASetLastError (WS2_32.112)
663 void WINAPI WSASetLastError(INT iError) {
664 SetLastError(iError);
667 static INT WS_DuplicateSocket(BOOL unicode, SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo)
669 HANDLE hProcess;
670 int size;
671 WSAPROTOCOL_INFOW infow;
673 TRACE( "unicode %d, socket %#Ix, pid %#lx, info %p\n", unicode, s, dwProcessId, lpProtocolInfo );
675 if (!ws_protocol_info(s, unicode, &infow, &size))
676 return SOCKET_ERROR;
678 if (!(hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId)))
680 SetLastError(WSAEINVAL);
681 return SOCKET_ERROR;
684 if (!lpProtocolInfo)
686 CloseHandle(hProcess);
687 SetLastError(WSAEFAULT);
688 return SOCKET_ERROR;
691 /* I don't know what the real Windoze does next, this is a hack */
692 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
693 * the target use the global duplicate, or we could copy a reference to us to the structure
694 * and let the target duplicate it from us, but let's do it as simple as possible */
695 memcpy(lpProtocolInfo, &infow, size);
696 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
697 hProcess, (LPHANDLE)&lpProtocolInfo->dwServiceFlags3,
698 0, FALSE, DUPLICATE_SAME_ACCESS);
699 CloseHandle(hProcess);
700 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
701 return 0;
704 static BOOL ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size)
706 struct afd_get_info_params params;
707 IO_STATUS_BLOCK io;
708 NTSTATUS status;
709 unsigned int i;
711 *size = unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA);
712 memset(buffer, 0, *size);
714 status = NtDeviceIoControlFile( (HANDLE)s, NULL, NULL, NULL, &io,
715 IOCTL_AFD_WINE_GET_INFO, NULL, 0, &params, sizeof(params) );
716 if (status)
718 SetLastError( NtStatusToWSAError( status ) );
719 return FALSE;
722 for (i = 0; i < ARRAY_SIZE(supported_protocols); ++i)
724 const WSAPROTOCOL_INFOW *info = &supported_protocols[i];
725 if (params.family == info->iAddressFamily &&
726 params.type == info->iSocketType &&
727 params.protocol >= info->iProtocol &&
728 params.protocol <= info->iProtocol + info->iProtocolMaxOffset)
730 if (unicode)
731 *buffer = *info;
732 else
734 WSAPROTOCOL_INFOA *bufferA = (WSAPROTOCOL_INFOA *)buffer;
735 memcpy( bufferA, info, offsetof( WSAPROTOCOL_INFOW, szProtocol ) );
736 WideCharToMultiByte( CP_ACP, 0, info->szProtocol, -1,
737 bufferA->szProtocol, sizeof(bufferA->szProtocol), NULL, NULL );
739 buffer->iProtocol = params.protocol;
740 return TRUE;
743 FIXME( "Could not fill protocol information for family %d, type %d, protocol %d.\n",
744 params.family, params.type, params.protocol );
745 return TRUE;
750 /***********************************************************************
751 * accept (WS2_32.1)
753 SOCKET WINAPI accept( SOCKET s, struct sockaddr *addr, int *len )
755 IO_STATUS_BLOCK io;
756 NTSTATUS status;
757 ULONG accept_handle;
758 HANDLE sync_event;
759 SOCKET ret;
761 TRACE( "socket %#Ix\n", s );
763 if (!(sync_event = get_sync_event())) return INVALID_SOCKET;
764 status = NtDeviceIoControlFile( (HANDLE)s, sync_event, NULL, NULL, &io, IOCTL_AFD_WINE_ACCEPT,
765 NULL, 0, &accept_handle, sizeof(accept_handle) );
766 if (status == STATUS_PENDING)
768 if (wait_event_alertable( sync_event ) == WAIT_FAILED)
769 return SOCKET_ERROR;
770 status = io.u.Status;
772 if (status)
774 TRACE( "failed, status %#lx\n", status );
775 WSASetLastError( NtStatusToWSAError( status ) );
776 return INVALID_SOCKET;
779 ret = accept_handle;
780 if (!socket_list_add( ret ))
782 CloseHandle( SOCKET2HANDLE(ret) );
783 return INVALID_SOCKET;
785 if (addr && len && getpeername( ret, addr, len ))
787 closesocket( ret );
788 return INVALID_SOCKET;
791 TRACE( "returning %#Ix\n", ret );
792 return ret;
795 /***********************************************************************
796 * AcceptEx
798 static BOOL WINAPI WS2_AcceptEx( SOCKET listener, SOCKET acceptor, void *dest, DWORD recv_len,
799 DWORD local_len, DWORD remote_len, DWORD *ret_len, OVERLAPPED *overlapped)
801 struct afd_accept_into_params params =
803 .accept_handle = acceptor,
804 .recv_len = recv_len,
805 .local_len = local_len,
807 void *cvalue = NULL;
808 NTSTATUS status;
810 TRACE( "listener %#Ix, acceptor %#Ix, dest %p, recv_len %lu, local_len %lu, remote_len %lu, ret_len %p, "
811 "overlapped %p\n", listener, acceptor, dest, recv_len, local_len, remote_len, ret_len, overlapped );
813 if (!overlapped)
815 SetLastError(WSA_INVALID_PARAMETER);
816 return FALSE;
819 if (!((ULONG_PTR)overlapped->hEvent & 1)) cvalue = overlapped;
820 overlapped->Internal = STATUS_PENDING;
821 overlapped->InternalHigh = 0;
823 if (!dest)
825 SetLastError(WSAEINVAL);
826 return FALSE;
829 if (!remote_len)
831 SetLastError(WSAEFAULT);
832 return FALSE;
835 status = NtDeviceIoControlFile( SOCKET2HANDLE(listener), overlapped->hEvent, NULL, cvalue,
836 (IO_STATUS_BLOCK *)overlapped, IOCTL_AFD_WINE_ACCEPT_INTO, &params, sizeof(params),
837 dest, recv_len + local_len + remote_len );
839 if (ret_len) *ret_len = overlapped->InternalHigh;
840 WSASetLastError( NtStatusToWSAError(status) );
841 TRACE( "status %#lx.\n", status );
842 return !status;
846 static BOOL WINAPI WS2_TransmitFile( SOCKET s, HANDLE file, DWORD file_len, DWORD buffer_size,
847 OVERLAPPED *overlapped, TRANSMIT_FILE_BUFFERS *buffers, DWORD flags )
849 struct afd_transmit_params params = {{{0}}};
850 IO_STATUS_BLOCK iosb, *piosb = &iosb;
851 HANDLE event = NULL;
852 void *cvalue = NULL;
853 NTSTATUS status;
855 TRACE( "socket %#Ix, file %p, file_len %lu, buffer_size %lu, overlapped %p, buffers %p, flags %#lx\n",
856 s, file, file_len, buffer_size, overlapped, buffers, flags );
858 if (overlapped)
860 piosb = (IO_STATUS_BLOCK *)overlapped;
861 if (!((ULONG_PTR)overlapped->hEvent & 1)) cvalue = overlapped;
862 event = overlapped->hEvent;
863 overlapped->Internal = STATUS_PENDING;
864 overlapped->InternalHigh = 0;
865 params.offset.u.LowPart = overlapped->u.s.Offset;
866 params.offset.u.HighPart = overlapped->u.s.OffsetHigh;
868 else
870 if (!(event = get_sync_event())) return -1;
871 params.offset.QuadPart = FILE_USE_FILE_POINTER_POSITION;
874 params.file = HandleToULong( file );
875 params.file_len = file_len;
876 params.buffer_size = buffer_size;
877 if (buffers)
879 params.head_ptr = u64_from_user_ptr(buffers->Head);
880 params.head_len = buffers->HeadLength;
881 params.tail_ptr = u64_from_user_ptr(buffers->Tail);
882 params.tail_len = buffers->TailLength;
884 params.flags = flags;
886 status = NtDeviceIoControlFile( (HANDLE)s, event, NULL, cvalue, piosb,
887 IOCTL_AFD_WINE_TRANSMIT, &params, sizeof(params), NULL, 0 );
888 if (status == STATUS_PENDING && !overlapped)
890 if (WaitForSingleObject( event, INFINITE ) == WAIT_FAILED)
891 return FALSE;
892 status = piosb->u.Status;
894 SetLastError( NtStatusToWSAError( status ) );
895 TRACE( "status %#lx.\n", status );
896 return !status;
900 /***********************************************************************
901 * GetAcceptExSockaddrs
903 static void WINAPI WS2_GetAcceptExSockaddrs( void *buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
904 struct sockaddr **local_addr, LPINT local_addr_len,
905 struct sockaddr **remote_addr, LPINT remote_addr_len )
907 char *cbuf = buffer;
909 TRACE( "buffer %p, data_size %lu, local_size %lu, remote_size %lu,"
910 " local_addr %p, local_addr_len %p, remote_addr %p, remote_addr_len %p\n",
911 buffer, data_size, local_size, remote_size,
912 local_addr, local_addr_len, remote_addr, remote_addr_len );
914 cbuf += data_size;
916 *local_addr_len = *(int *) cbuf;
917 *local_addr = (struct sockaddr *)(cbuf + sizeof(int));
919 cbuf += local_size;
921 *remote_addr_len = *(int *) cbuf;
922 *remote_addr = (struct sockaddr *)(cbuf + sizeof(int));
926 static void WINAPI socket_apc( void *apc_user, IO_STATUS_BLOCK *io, ULONG reserved )
928 LPWSAOVERLAPPED_COMPLETION_ROUTINE func = apc_user;
929 func( NtStatusToWSAError( io->u.Status ), io->Information, (OVERLAPPED *)io, 0 );
932 static int WS2_recv_base( SOCKET s, WSABUF *buffers, DWORD buffer_count, DWORD *ret_size, DWORD *flags,
933 struct sockaddr *addr, int *addr_len, OVERLAPPED *overlapped,
934 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion, WSABUF *control )
936 IO_STATUS_BLOCK iosb, *piosb = &iosb;
937 struct afd_recvmsg_params params;
938 PIO_APC_ROUTINE apc = NULL;
939 HANDLE event = NULL;
940 void *cvalue = NULL;
941 NTSTATUS status;
943 TRACE( "socket %#Ix, buffers %p, buffer_count %lu, flags %#lx, addr %p, "
944 "addr_len %d, overlapped %p, completion %p, control %p\n",
945 s, buffers, buffer_count, *flags, addr, addr_len ? *addr_len : -1, overlapped, completion, control );
947 if (overlapped)
949 piosb = (IO_STATUS_BLOCK *)overlapped;
950 if (!((ULONG_PTR)overlapped->hEvent & 1)) cvalue = overlapped;
951 event = overlapped->hEvent;
953 else
955 if (!(event = get_sync_event())) return -1;
957 piosb->u.Status = STATUS_PENDING;
959 if (completion)
961 event = NULL;
962 cvalue = completion;
963 apc = socket_apc;
966 params.control_ptr = u64_from_user_ptr(control);
967 params.addr_ptr = u64_from_user_ptr(addr);
968 params.addr_len_ptr = u64_from_user_ptr(addr_len);
969 params.ws_flags_ptr = u64_from_user_ptr(flags);
970 params.force_async = !!overlapped;
971 params.count = buffer_count;
972 params.buffers_ptr = u64_from_user_ptr(buffers);
974 status = NtDeviceIoControlFile( (HANDLE)s, event, apc, cvalue, piosb,
975 IOCTL_AFD_WINE_RECVMSG, &params, sizeof(params), NULL, 0 );
976 if (status == STATUS_PENDING && !overlapped)
978 if (wait_event_alertable( event ) == WAIT_FAILED)
979 return -1;
980 status = piosb->u.Status;
982 if (!status && ret_size) *ret_size = piosb->Information;
983 SetLastError( NtStatusToWSAError( status ) );
984 TRACE( "status %#lx.\n", status );
985 return status ? -1 : 0;
988 static int WS2_sendto( SOCKET s, WSABUF *buffers, DWORD buffer_count, DWORD *ret_size, DWORD flags,
989 const struct sockaddr *addr, int addr_len, OVERLAPPED *overlapped,
990 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
992 IO_STATUS_BLOCK iosb, *piosb = &iosb;
993 struct afd_sendmsg_params params;
994 PIO_APC_ROUTINE apc = NULL;
995 HANDLE event = NULL;
996 void *cvalue = NULL;
997 NTSTATUS status;
999 TRACE( "socket %#Ix, buffers %p, buffer_count %lu, flags %#lx, addr %p, "
1000 "addr_len %d, overlapped %p, completion %p\n",
1001 s, buffers, buffer_count, flags, addr, addr_len, overlapped, completion );
1003 if (!socket_list_find( s ))
1005 SetLastError( WSAENOTSOCK );
1006 return -1;
1009 if (!overlapped && !ret_size)
1011 SetLastError( WSAEFAULT );
1012 return -1;
1015 if (overlapped)
1017 piosb = (IO_STATUS_BLOCK *)overlapped;
1018 if (!((ULONG_PTR)overlapped->hEvent & 1)) cvalue = overlapped;
1019 event = overlapped->hEvent;
1021 else
1023 if (!(event = get_sync_event())) return -1;
1025 piosb->u.Status = STATUS_PENDING;
1027 if (completion)
1029 event = NULL;
1030 cvalue = completion;
1031 apc = socket_apc;
1034 params.addr_ptr = u64_from_user_ptr( addr );
1035 params.addr_len = addr_len;
1036 params.ws_flags = flags;
1037 params.force_async = !!overlapped;
1038 params.count = buffer_count;
1039 params.buffers_ptr = u64_from_user_ptr( buffers );
1041 status = NtDeviceIoControlFile( (HANDLE)s, event, apc, cvalue, piosb,
1042 IOCTL_AFD_WINE_SENDMSG, &params, sizeof(params), NULL, 0 );
1043 if (status == STATUS_PENDING && !overlapped)
1045 if (WaitForSingleObject( event, INFINITE ) == WAIT_FAILED)
1046 return -1;
1047 status = piosb->u.Status;
1049 if (!status && ret_size) *ret_size = piosb->Information;
1050 SetLastError( NtStatusToWSAError( status ) );
1051 TRACE( "status %#lx.\n", status );
1052 return status ? -1 : 0;
1056 /***********************************************************************
1057 * WSASendMsg
1059 int WINAPI WSASendMsg( SOCKET s, LPWSAMSG msg, DWORD dwFlags, LPDWORD lpNumberOfBytesSent,
1060 LPWSAOVERLAPPED lpOverlapped,
1061 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
1063 if (!msg)
1065 SetLastError( WSAEFAULT );
1066 return SOCKET_ERROR;
1069 return WS2_sendto( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesSent,
1070 dwFlags, msg->name, msg->namelen,
1071 lpOverlapped, lpCompletionRoutine );
1074 /***********************************************************************
1075 * WSARecvMsg
1077 * Perform a receive operation that is capable of returning message
1078 * control headers. It is important to note that the WSAMSG parameter
1079 * must remain valid throughout the operation, even when an overlapped
1080 * receive is performed.
1082 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
1083 LPWSAOVERLAPPED lpOverlapped,
1084 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
1086 if (!msg)
1088 SetLastError( WSAEFAULT );
1089 return SOCKET_ERROR;
1092 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
1093 &msg->dwFlags, msg->name, &msg->namelen,
1094 lpOverlapped, lpCompletionRoutine, &msg->Control );
1098 /***********************************************************************
1099 * bind (ws2_32.2)
1101 int WINAPI bind( SOCKET s, const struct sockaddr *addr, int len )
1103 struct afd_bind_params *params;
1104 struct sockaddr *ret_addr;
1105 IO_STATUS_BLOCK io;
1106 HANDLE sync_event;
1107 NTSTATUS status;
1109 TRACE( "socket %#Ix, addr %s\n", s, debugstr_sockaddr(addr) );
1111 if (!addr)
1113 SetLastError( WSAEFAULT );
1114 return -1;
1117 switch (addr->sa_family)
1119 case AF_INET:
1120 if (len < sizeof(struct sockaddr_in))
1122 SetLastError( WSAEFAULT );
1123 return -1;
1125 break;
1127 case AF_INET6:
1128 if (len < sizeof(struct sockaddr_in6))
1130 SetLastError( WSAEFAULT );
1131 return -1;
1133 break;
1135 case AF_IPX:
1136 if (len < sizeof(struct sockaddr_ipx))
1138 SetLastError( WSAEFAULT );
1139 return -1;
1141 break;
1143 case AF_IRDA:
1144 if (len < sizeof(SOCKADDR_IRDA))
1146 SetLastError( WSAEFAULT );
1147 return -1;
1149 break;
1151 default:
1152 FIXME( "unknown protocol %u\n", addr->sa_family );
1153 SetLastError( WSAEAFNOSUPPORT );
1154 return -1;
1157 if (!(sync_event = get_sync_event())) return -1;
1159 params = malloc( sizeof(int) + len );
1160 ret_addr = malloc( len );
1161 if (!params || !ret_addr)
1163 free( params );
1164 free( ret_addr );
1165 SetLastError( WSAENOBUFS );
1166 return -1;
1168 params->unknown = 0;
1169 memcpy( &params->addr, addr, len );
1171 status = NtDeviceIoControlFile( (HANDLE)s, sync_event, NULL, NULL, &io, IOCTL_AFD_BIND,
1172 params, sizeof(int) + len, ret_addr, len );
1173 if (status == STATUS_PENDING)
1175 if (WaitForSingleObject( sync_event, INFINITE ) == WAIT_FAILED)
1176 return -1;
1177 status = io.u.Status;
1180 if (status) TRACE( "failed, status %#lx.\n", status );
1181 else TRACE( "successfully bound to address %s\n", debugstr_sockaddr( ret_addr ));
1183 free( params );
1184 free( ret_addr );
1186 SetLastError( NtStatusToWSAError( status ) );
1187 return status ? -1 : 0;
1191 /***********************************************************************
1192 * closesocket (ws2_32.3)
1194 int WINAPI closesocket( SOCKET s )
1196 TRACE( "%#Ix\n", s );
1198 if (!num_startup)
1200 SetLastError( WSANOTINITIALISED );
1201 return -1;
1204 if (!socket_list_remove( s ))
1206 SetLastError( WSAENOTSOCK );
1207 return -1;
1210 CloseHandle( (HANDLE)s );
1211 return 0;
1215 /***********************************************************************
1216 * connect (ws2_32.4)
1218 int WINAPI connect( SOCKET s, const struct sockaddr *addr, int len )
1220 struct afd_connect_params *params;
1221 IO_STATUS_BLOCK io;
1222 HANDLE sync_event;
1223 NTSTATUS status;
1225 TRACE( "socket %#Ix, addr %s, len %d\n", s, debugstr_sockaddr(addr), len );
1227 if (!(sync_event = get_sync_event())) return -1;
1229 if (!(params = malloc( sizeof(*params) + len )))
1231 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1232 return -1;
1234 params->addr_len = len;
1235 params->synchronous = TRUE;
1236 memcpy( params + 1, addr, len );
1238 status = NtDeviceIoControlFile( (HANDLE)s, sync_event, NULL, NULL, &io, IOCTL_AFD_WINE_CONNECT,
1239 params, sizeof(*params) + len, NULL, 0 );
1240 free( params );
1241 if (status == STATUS_PENDING)
1243 if (wait_event_alertable( sync_event ) == WAIT_FAILED) return -1;
1244 status = io.u.Status;
1246 if (status)
1248 /* NtStatusToWSAError() has no mapping for WSAEALREADY */
1249 SetLastError( status == STATUS_ADDRESS_ALREADY_ASSOCIATED ? WSAEALREADY : NtStatusToWSAError( status ) );
1250 TRACE( "failed, status %#lx.\n", status );
1251 return -1;
1253 return 0;
1257 /***********************************************************************
1258 * WSAConnect (WS2_32.30)
1260 int WINAPI WSAConnect( SOCKET s, const struct sockaddr *name, int namelen,
1261 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1262 LPQOS lpSQOS, LPQOS lpGQOS )
1264 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1265 FIXME("unsupported parameters!\n");
1266 return connect( s, name, namelen );
1270 static BOOL WINAPI WS2_ConnectEx( SOCKET s, const struct sockaddr *name, int namelen,
1271 void *send_buffer, DWORD send_len, DWORD *ret_len, OVERLAPPED *overlapped )
1273 struct afd_connect_params *params;
1274 void *cvalue = NULL;
1275 NTSTATUS status;
1277 TRACE( "socket %#Ix, ptr %p %s, length %d, send_buffer %p, send_len %lu, overlapped %p\n",
1278 s, name, debugstr_sockaddr(name), namelen, send_buffer, send_len, overlapped );
1280 if (!overlapped)
1282 SetLastError( WSA_INVALID_PARAMETER );
1283 return FALSE;
1286 if (!((ULONG_PTR)overlapped->hEvent & 1)) cvalue = overlapped;
1287 overlapped->Internal = STATUS_PENDING;
1288 overlapped->InternalHigh = 0;
1290 if (!(params = malloc( sizeof(*params) + namelen + send_len )))
1292 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1293 return SOCKET_ERROR;
1295 params->addr_len = namelen;
1296 params->synchronous = FALSE;
1297 memcpy( params + 1, name, namelen );
1298 memcpy( (char *)(params + 1) + namelen, send_buffer, send_len );
1300 status = NtDeviceIoControlFile( SOCKET2HANDLE(s), overlapped->hEvent, NULL, cvalue,
1301 (IO_STATUS_BLOCK *)overlapped, IOCTL_AFD_WINE_CONNECT,
1302 params, sizeof(*params) + namelen + send_len, NULL, 0 );
1303 free( params );
1304 if (ret_len) *ret_len = overlapped->InternalHigh;
1305 SetLastError( NtStatusToWSAError( status ) );
1306 TRACE( "status %#lx.\n", status );
1307 return !status;
1311 /***********************************************************************
1312 * WSAConnectByNameA (WS2_32.@)
1314 BOOL WINAPI WSAConnectByNameA(SOCKET s, const char *node_name, const char *service_name,
1315 DWORD *local_addr_len, struct sockaddr *local_addr,
1316 DWORD *remote_addr_len, struct sockaddr *remote_addr,
1317 const struct timeval *timeout, WSAOVERLAPPED *reserved)
1319 WSAPROTOCOL_INFOA proto_info;
1320 WSAPOLLFD pollout;
1321 struct addrinfo *service, hints;
1322 int ret, proto_len, sockaddr_size, sockname_size, sock_err, int_len;
1324 TRACE("socket %#Ix, node_name %s, service_name %s, local_addr_len %p, local_addr %p, \
1325 remote_addr_len %p, remote_addr %p, timeout %p, reserved %p\n",
1326 s, debugstr_a(node_name), debugstr_a(service_name), local_addr_len, local_addr,
1327 remote_addr_len, remote_addr, timeout, reserved );
1329 if (!node_name || !service_name || reserved)
1331 SetLastError(WSAEINVAL);
1332 return FALSE;
1335 if (!s)
1337 SetLastError(WSAENOTSOCK);
1338 return FALSE;
1341 if (timeout)
1342 FIXME("WSAConnectByName timeout stub\n");
1344 proto_len = sizeof(WSAPROTOCOL_INFOA);
1345 ret = getsockopt(s, SOL_SOCKET, SO_PROTOCOL_INFOA, (char *)&proto_info, &proto_len);
1346 if (ret)
1347 return FALSE;
1349 memset(&hints, 0, sizeof(struct addrinfo));
1350 hints.ai_socktype = proto_info.iSocketType;
1351 hints.ai_family = proto_info.iAddressFamily;
1352 hints.ai_protocol = proto_info.iProtocol;
1353 ret = getaddrinfo(node_name, service_name, &hints, &service);
1354 if (ret)
1355 return FALSE;
1357 if (proto_info.iSocketType != SOCK_STREAM)
1359 freeaddrinfo(service);
1360 SetLastError(WSAEFAULT);
1361 return FALSE;
1364 switch (proto_info.iAddressFamily)
1366 case AF_INET:
1367 sockaddr_size = sizeof(SOCKADDR_IN);
1368 break;
1369 case AF_INET6:
1370 sockaddr_size = sizeof(SOCKADDR_IN6);
1371 break;
1372 default:
1373 freeaddrinfo(service);
1374 SetLastError(WSAENOTSOCK);
1375 return FALSE;
1378 ret = connect(s, service->ai_addr, sockaddr_size);
1379 if (ret)
1381 freeaddrinfo(service);
1382 return FALSE;
1385 pollout.fd = s;
1386 pollout.events = POLLWRNORM;
1387 ret = WSAPoll(&pollout, 1, -1);
1388 if (ret == SOCKET_ERROR)
1390 freeaddrinfo(service);
1391 return FALSE;
1393 if (pollout.revents & (POLLERR | POLLHUP | POLLNVAL))
1395 freeaddrinfo(service);
1396 int_len = sizeof(int);
1397 ret = getsockopt(s, SOL_SOCKET, SO_ERROR, (char *)&sock_err, &int_len);
1398 if (ret == SOCKET_ERROR)
1399 return FALSE;
1400 SetLastError(sock_err);
1401 return FALSE;
1404 if (remote_addr_len && remote_addr)
1406 if (*remote_addr_len >= sockaddr_size)
1408 memcpy(remote_addr, service->ai_addr, sockaddr_size);
1409 *remote_addr_len = sockaddr_size;
1411 else
1413 freeaddrinfo(service);
1414 SetLastError(WSAEFAULT);
1415 return FALSE;
1419 freeaddrinfo(service);
1421 if (local_addr_len && local_addr)
1423 if (*local_addr_len >= sockaddr_size)
1425 sockname_size = sockaddr_size;
1426 ret = getsockname(s, local_addr, &sockname_size);
1427 if (ret)
1428 return FALSE;
1429 if (proto_info.iAddressFamily == AF_INET6)
1430 ((SOCKADDR_IN6 *)local_addr)->sin6_port = 0;
1431 else
1432 ((SOCKADDR_IN *)local_addr)->sin_port = 0;
1433 *local_addr_len = sockaddr_size;
1435 else
1437 SetLastError(WSAEFAULT);
1438 return FALSE;
1442 return TRUE;
1446 /***********************************************************************
1447 * WSAConnectByNameW (WS2_32.@)
1449 BOOL WINAPI WSAConnectByNameW(SOCKET s, const WCHAR *node_name, const WCHAR *service_name,
1450 DWORD *local_addr_len, struct sockaddr *local_addr,
1451 DWORD *remote_addr_len, struct sockaddr *remote_addr,
1452 const struct timeval *timeout, WSAOVERLAPPED *reserved)
1454 char *node_nameA, *service_nameA;
1455 BOOL ret;
1457 if (!node_name || !service_name)
1459 SetLastError(WSAEINVAL);
1460 return FALSE;
1463 node_nameA = strdupWtoA(node_name);
1464 service_nameA = strdupWtoA(service_name);
1465 if (!node_nameA || !service_nameA)
1467 SetLastError(WSAENOBUFS);
1468 return FALSE;
1471 ret = WSAConnectByNameA(s, node_nameA, service_nameA, local_addr_len, local_addr,
1472 remote_addr_len, remote_addr, timeout, reserved);
1473 free(node_nameA);
1474 free(service_nameA);
1475 return ret;
1479 static BOOL WINAPI WS2_DisconnectEx( SOCKET s, OVERLAPPED *overlapped, DWORD flags, DWORD reserved )
1481 IO_STATUS_BLOCK iosb, *piosb = &iosb;
1482 void *cvalue = NULL;
1483 int how = SD_SEND;
1484 HANDLE event = 0;
1485 NTSTATUS status;
1487 TRACE( "socket %#Ix, overlapped %p, flags %#lx, reserved %#lx\n", s, overlapped, flags, reserved );
1489 if (flags & TF_REUSE_SOCKET)
1490 FIXME( "Reusing socket not supported yet\n" );
1492 if (overlapped)
1494 piosb = (IO_STATUS_BLOCK *)overlapped;
1495 if (!((ULONG_PTR)overlapped->hEvent & 1)) cvalue = overlapped;
1496 event = overlapped->hEvent;
1497 overlapped->Internal = STATUS_PENDING;
1498 overlapped->InternalHigh = 0;
1501 status = NtDeviceIoControlFile( (HANDLE)s, event, NULL, cvalue, piosb,
1502 IOCTL_AFD_WINE_SHUTDOWN, &how, sizeof(how), NULL, 0 );
1503 if (!status && overlapped) status = STATUS_PENDING;
1504 SetLastError( NtStatusToWSAError( status ) );
1505 TRACE( "status %#lx.\n", status );
1506 return !status;
1510 /***********************************************************************
1511 * getpeername (ws2_32.5)
1513 int WINAPI getpeername( SOCKET s, struct sockaddr *addr, int *len )
1515 IO_STATUS_BLOCK io;
1516 NTSTATUS status;
1518 TRACE( "socket %#Ix, addr %p, len %d\n", s, addr, len ? *len : 0 );
1520 if (!socket_list_find( s ))
1522 WSASetLastError( WSAENOTSOCK );
1523 return -1;
1526 if (!len)
1528 SetLastError( WSAEFAULT );
1529 return -1;
1532 status = NtDeviceIoControlFile( (HANDLE)s, NULL, NULL, NULL, &io,
1533 IOCTL_AFD_WINE_GETPEERNAME, NULL, 0, addr, *len );
1534 if (!status)
1535 *len = io.Information;
1536 SetLastError( NtStatusToWSAError( status ) );
1537 TRACE( "status %#lx.\n", status );
1538 return status ? -1 : 0;
1542 /***********************************************************************
1543 * getsockname (ws2_32.6)
1545 int WINAPI getsockname( SOCKET s, struct sockaddr *addr, int *len )
1547 IO_STATUS_BLOCK io;
1548 NTSTATUS status;
1550 TRACE( "socket %#Ix, addr %p, len %d\n", s, addr, len ? *len : 0 );
1552 if (!addr)
1554 SetLastError( WSAEFAULT );
1555 return -1;
1558 status = NtDeviceIoControlFile( (HANDLE)s, NULL, NULL, NULL, &io, IOCTL_AFD_GETSOCKNAME, NULL, 0, addr, *len );
1559 if (!status)
1560 *len = io.Information;
1561 WSASetLastError( NtStatusToWSAError( status ) );
1562 TRACE( "status %#lx.\n", status );
1563 return status ? -1 : 0;
1567 static int server_getsockopt( SOCKET s, ULONG code, char *optval, int *optlen )
1569 IO_STATUS_BLOCK io;
1570 NTSTATUS status;
1572 status = NtDeviceIoControlFile( (HANDLE)s, NULL, NULL, NULL, &io, code, NULL, 0, optval, *optlen );
1573 if (!status) *optlen = io.Information;
1574 SetLastError( NtStatusToWSAError( status ) );
1575 TRACE( "status %#lx.\n", status );
1576 return status ? -1 : 0;
1580 /***********************************************************************
1581 * getsockopt (WS2_32.7)
1583 int WINAPI getsockopt( SOCKET s, int level, int optname, char *optval, int *optlen )
1585 INT ret = 0;
1587 TRACE( "socket %#Ix, %s, optval %p, optlen %p (%d)\n",
1588 s, debugstr_sockopt(level, optname), optval, optlen, optlen ? *optlen : 0 );
1590 if ((level != SOL_SOCKET || optname != SO_OPENTYPE))
1592 if (!socket_list_find( s ))
1594 SetLastError( WSAENOTSOCK );
1595 return SOCKET_ERROR;
1597 if (!optlen || *optlen <= 0)
1599 SetLastError( WSAEFAULT );
1600 return -1;
1604 switch(level)
1606 case SOL_SOCKET:
1608 switch(optname)
1610 case SO_ACCEPTCONN:
1611 return server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_ACCEPTCONN, optval, optlen );
1613 case SO_BROADCAST:
1614 ret = server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_BROADCAST, optval, optlen );
1615 if (!ret && *optlen < sizeof(DWORD)) *optlen = 1;
1616 return ret;
1618 case SO_BSP_STATE:
1620 CSADDR_INFO *csinfo = (CSADDR_INFO *)optval;
1621 WSAPROTOCOL_INFOW infow;
1622 int addr_size;
1624 if (!ws_protocol_info( s, TRUE, &infow, &addr_size ))
1625 return -1;
1627 if (infow.iAddressFamily == AF_INET)
1628 addr_size = sizeof(struct sockaddr_in);
1629 else if (infow.iAddressFamily == AF_INET6)
1630 addr_size = sizeof(struct sockaddr_in6);
1631 else
1633 FIXME( "family %d is unsupported for SO_BSP_STATE\n", infow.iAddressFamily );
1634 SetLastError( WSAEAFNOSUPPORT );
1635 return -1;
1638 if (*optlen < sizeof(CSADDR_INFO) + addr_size * 2)
1640 ret = 0;
1641 SetLastError( WSAEFAULT );
1642 return -1;
1645 csinfo->LocalAddr.lpSockaddr = (struct sockaddr *)(csinfo + 1);
1646 csinfo->RemoteAddr.lpSockaddr = (struct sockaddr *)((char *)(csinfo + 1) + addr_size);
1648 csinfo->LocalAddr.iSockaddrLength = addr_size;
1649 if (getsockname( s, csinfo->LocalAddr.lpSockaddr, &csinfo->LocalAddr.iSockaddrLength ) < 0)
1651 csinfo->LocalAddr.lpSockaddr = NULL;
1652 csinfo->LocalAddr.iSockaddrLength = 0;
1655 csinfo->RemoteAddr.iSockaddrLength = addr_size;
1656 if (getpeername( s, csinfo->RemoteAddr.lpSockaddr, &csinfo->RemoteAddr.iSockaddrLength ) < 0)
1658 csinfo->RemoteAddr.lpSockaddr = NULL;
1659 csinfo->RemoteAddr.iSockaddrLength = 0;
1662 csinfo->iSocketType = infow.iSocketType;
1663 csinfo->iProtocol = infow.iProtocol;
1664 return 0;
1667 case SO_CONNECT_TIME:
1668 if (!optval)
1670 SetLastError( WSAEFAULT );
1671 return -1;
1673 return server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_CONNECT_TIME, optval, optlen );
1675 case SO_DEBUG:
1676 WARN( "returning 0 for SO_DEBUG\n" );
1677 *(DWORD *)optval = 0;
1678 SetLastError( 0 );
1679 return 0;
1681 case SO_DONTLINGER:
1683 LINGER linger;
1684 int len = sizeof(linger);
1685 BOOL value;
1686 int ret;
1688 if (*optlen < 1 || !optval)
1690 SetLastError(WSAEFAULT);
1691 return SOCKET_ERROR;
1694 if (!(ret = getsockopt( s, SOL_SOCKET, SO_LINGER, (char *)&linger, &len )))
1696 value = !linger.l_onoff;
1697 memcpy( optval, &value, min( sizeof(BOOL), *optlen ));
1698 *optlen = *optlen >= sizeof(BOOL) ? sizeof(BOOL) : 1;
1700 return ret;
1703 /* As mentioned in setsockopt, Windows ignores this, so we
1704 * always return true here */
1705 case SO_DONTROUTE:
1706 if (*optlen < 1 || !optval)
1708 SetLastError( WSAEFAULT );
1709 return SOCKET_ERROR;
1711 *optval = TRUE;
1712 *optlen = 1;
1713 SetLastError( ERROR_SUCCESS );
1714 return 0;
1716 case SO_ERROR:
1717 return server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_ERROR, optval, optlen );
1719 case SO_KEEPALIVE:
1720 if (*optlen < 1 || !optval)
1722 SetLastError( WSAEFAULT );
1723 return SOCKET_ERROR;
1725 *optlen = 1;
1726 return server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_KEEPALIVE, optval, optlen );
1728 case SO_LINGER:
1730 WSAPROTOCOL_INFOW info;
1731 int size;
1733 /* struct linger and LINGER have different sizes */
1734 if (*optlen < sizeof(LINGER) || !optval)
1736 if (optval) memset( optval, 0, *optlen );
1737 SetLastError( WSAEFAULT );
1738 return SOCKET_ERROR;
1741 if (!ws_protocol_info( s, TRUE, &info, &size ))
1742 return -1;
1744 if (info.iSocketType == SOCK_DGRAM)
1746 SetLastError( WSAENOPROTOOPT );
1747 return -1;
1750 return server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_LINGER, optval, optlen );
1753 case SO_MAX_MSG_SIZE:
1754 if (*optlen < sizeof(int) || !optval)
1756 SetLastError(WSAEFAULT);
1757 return SOCKET_ERROR;
1759 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
1760 *(int *)optval = 65507;
1761 *optlen = sizeof(int);
1762 return 0;
1764 case SO_OOBINLINE:
1765 ret = server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_OOBINLINE, optval, optlen );
1766 if (!ret && *optlen < sizeof(DWORD)) *optlen = 1;
1767 return ret;
1769 /* SO_OPENTYPE does not require a valid socket handle. */
1770 case SO_OPENTYPE:
1771 if (!optlen || *optlen < sizeof(int) || !optval)
1773 SetLastError( WSAEFAULT );
1774 return SOCKET_ERROR;
1776 *(int *)optval = get_per_thread_data()->opentype;
1777 *optlen = sizeof(int);
1778 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
1779 SetLastError( ERROR_SUCCESS );
1780 return 0;
1782 case SO_PROTOCOL_INFOA:
1783 case SO_PROTOCOL_INFOW:
1785 int size;
1786 WSAPROTOCOL_INFOW infow;
1788 ret = ws_protocol_info(s, optname == SO_PROTOCOL_INFOW, &infow, &size);
1789 if (ret)
1791 if (!optval || *optlen < size)
1793 *optlen = size;
1794 ret = 0;
1795 SetLastError(WSAEFAULT);
1797 else
1798 memcpy(optval, &infow, size);
1800 return ret ? 0 : SOCKET_ERROR;
1803 case SO_RCVBUF:
1804 if (*optlen < sizeof(DWORD) || !optval)
1806 if (optval) memset( optval, 0, *optlen );
1807 SetLastError( WSAEFAULT );
1808 return SOCKET_ERROR;
1810 return server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_RCVBUF, optval, optlen );
1812 case SO_RCVTIMEO:
1813 return server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_RCVTIMEO, optval, optlen );
1815 case SO_REUSEADDR:
1816 ret = server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_REUSEADDR, optval, optlen );
1817 if (!ret && *optlen < sizeof(DWORD)) *optlen = 1;
1818 return ret;
1820 case SO_EXCLUSIVEADDRUSE:
1821 ret = server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_EXCLUSIVEADDRUSE, optval, optlen );
1822 if (!ret && *optlen < sizeof(DWORD)) *optlen = 1;
1823 return ret;
1825 case SO_SNDBUF:
1826 if (*optlen < sizeof(DWORD) || !optval)
1828 if (optval) memset( optval, 0, *optlen );
1829 SetLastError( WSAEFAULT );
1830 return SOCKET_ERROR;
1832 return server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_SNDBUF, optval, optlen );
1834 case SO_SNDTIMEO:
1835 return server_getsockopt( s, IOCTL_AFD_WINE_GET_SO_SNDTIMEO, optval, optlen );
1837 case SO_TYPE:
1839 WSAPROTOCOL_INFOW info;
1840 int size;
1842 if (*optlen < sizeof(int) || !optval)
1844 SetLastError(WSAEFAULT);
1845 return SOCKET_ERROR;
1848 if (!ws_protocol_info( s, TRUE, &info, &size ))
1849 return -1;
1851 *(int *)optval = info.iSocketType;
1852 return 0;
1855 default:
1856 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
1857 SetLastError(WSAENOPROTOOPT);
1858 return SOCKET_ERROR;
1859 } /* end switch(optname) */
1860 }/* end case SOL_SOCKET */
1862 case NSPROTO_IPX:
1864 struct sockaddr_ipx addr;
1865 IPX_ADDRESS_DATA *data;
1866 int namelen;
1867 switch(optname)
1869 case IPX_ADDRESS:
1871 * On a Win2000 system with one network card there are usually
1872 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
1873 * Using this call you can then retrieve info about this all.
1874 * In case of Linux it is a bit different. Usually you have
1875 * only "one" device active and further it is not possible to
1876 * query things like the linkspeed.
1878 FIXME("IPX_ADDRESS\n");
1879 namelen = sizeof(struct sockaddr_ipx);
1880 memset( &addr, 0, sizeof(struct sockaddr_ipx) );
1881 getsockname( s, (struct sockaddr *)&addr, &namelen );
1883 data = (IPX_ADDRESS_DATA*)optval;
1884 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
1885 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
1886 data->adapternum = 0;
1887 data->wan = FALSE; /* We are not on a wan for now .. */
1888 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
1889 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
1890 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
1891 * note 1MB = 1000kB in this case */
1892 return 0;
1894 case IPX_MAX_ADAPTER_NUM:
1895 FIXME("IPX_MAX_ADAPTER_NUM\n");
1896 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
1897 return 0;
1899 case IPX_PTYPE:
1900 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IPX_PTYPE, optval, optlen );
1902 default:
1903 FIXME("IPX optname:%x\n", optname);
1904 return SOCKET_ERROR;
1905 }/* end switch(optname) */
1906 } /* end case NSPROTO_IPX */
1908 case SOL_IRLMP:
1909 switch(optname)
1911 case IRLMP_ENUMDEVICES:
1912 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IRLMP_ENUMDEVICES, optval, optlen );
1914 default:
1915 FIXME("IrDA optname:0x%x\n", optname);
1916 return SOCKET_ERROR;
1918 break; /* case SOL_IRLMP */
1920 /* Levels IPPROTO_TCP and IPPROTO_IP convert directly */
1921 case IPPROTO_TCP:
1922 switch(optname)
1924 case TCP_NODELAY:
1925 if (*optlen < 1 || !optval)
1927 SetLastError( WSAEFAULT );
1928 return SOCKET_ERROR;
1930 *optlen = 1;
1931 return server_getsockopt( s, IOCTL_AFD_WINE_GET_TCP_NODELAY, optval, optlen );
1933 default:
1934 FIXME( "unrecognized TCP option %#x\n", optname );
1935 SetLastError( WSAENOPROTOOPT );
1936 return -1;
1939 case IPPROTO_IP:
1940 switch(optname)
1942 case IP_DONTFRAGMENT:
1943 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IP_DONTFRAGMENT, optval, optlen );
1945 case IP_HDRINCL:
1946 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IP_HDRINCL, optval, optlen );
1948 case IP_MULTICAST_IF:
1949 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IP_MULTICAST_IF, optval, optlen );
1951 case IP_MULTICAST_LOOP:
1952 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IP_MULTICAST_LOOP, optval, optlen );
1954 case IP_MULTICAST_TTL:
1955 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IP_MULTICAST_TTL, optval, optlen );
1957 case IP_OPTIONS:
1958 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IP_OPTIONS, optval, optlen );
1960 case IP_PKTINFO:
1961 if (*optlen < sizeof(DWORD) || !optval)
1963 *optlen = 0;
1964 SetLastError( WSAEFAULT );
1965 return SOCKET_ERROR;
1967 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IP_PKTINFO, optval, optlen );
1969 case IP_RECVTOS:
1970 if (*optlen < sizeof(DWORD) || !optval)
1972 *optlen = 0;
1973 SetLastError( WSAEFAULT );
1974 return SOCKET_ERROR;
1976 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IP_RECVTOS, optval, optlen );
1978 case IP_RECVTTL:
1979 if (*optlen < sizeof(DWORD) || !optval)
1981 *optlen = 0;
1982 SetLastError( WSAEFAULT );
1983 return SOCKET_ERROR;
1985 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IP_RECVTTL, optval, optlen );
1987 case IP_TOS:
1988 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IP_TOS, optval, optlen );
1990 case IP_TTL:
1991 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IP_TTL, optval, optlen );
1993 case IP_UNICAST_IF:
1994 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IP_UNICAST_IF, optval, optlen );
1996 default:
1997 FIXME( "unrecognized IP option %u\n", optname );
1998 /* fall through */
2000 case IP_ADD_MEMBERSHIP:
2001 case IP_DROP_MEMBERSHIP:
2002 SetLastError( WSAENOPROTOOPT );
2003 return -1;
2006 case IPPROTO_IPV6:
2007 switch(optname)
2009 case IPV6_DONTFRAG:
2010 if (*optlen < 1 || !optval)
2012 SetLastError( WSAEFAULT );
2013 return SOCKET_ERROR;
2015 if (*optlen < sizeof(DWORD)) *optlen = 1;
2016 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IPV6_DONTFRAG, optval, optlen );
2018 case IPV6_HOPLIMIT:
2019 if (*optlen < sizeof(DWORD) || !optval)
2021 *optlen = 0;
2022 SetLastError( WSAEFAULT );
2023 return SOCKET_ERROR;
2025 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IPV6_RECVHOPLIMIT, optval, optlen );
2027 case IPV6_MULTICAST_HOPS:
2028 if (*optlen < 1 || !optval)
2030 SetLastError( WSAEFAULT );
2031 return SOCKET_ERROR;
2033 if (*optlen < sizeof(DWORD)) *optlen = 1;
2034 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IPV6_MULTICAST_HOPS, optval, optlen );
2036 case IPV6_MULTICAST_IF:
2037 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IPV6_MULTICAST_IF, optval, optlen );
2039 case IPV6_MULTICAST_LOOP:
2040 if (*optlen < 1 || !optval)
2042 SetLastError( WSAEFAULT );
2043 return SOCKET_ERROR;
2045 if (*optlen < sizeof(DWORD)) *optlen = 1;
2046 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IPV6_MULTICAST_LOOP, optval, optlen );
2048 case IPV6_PROTECTION_LEVEL:
2049 if (*optlen < sizeof(UINT) || !optval)
2051 SetLastError( WSAEFAULT );
2052 return -1;
2054 *optlen = sizeof(UINT);
2055 *optval = PROTECTION_LEVEL_UNRESTRICTED;
2056 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
2057 return 0;
2059 case IPV6_PKTINFO:
2060 if (*optlen < sizeof(DWORD) || !optval)
2062 *optlen = 0;
2063 SetLastError( WSAEFAULT );
2064 return SOCKET_ERROR;
2066 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IPV6_RECVPKTINFO, optval, optlen );
2068 case IPV6_RECVTCLASS:
2069 if (*optlen < sizeof(DWORD) || !optval)
2071 if (optlen) *optlen = 0;
2072 SetLastError( WSAEFAULT );
2073 return SOCKET_ERROR;
2075 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IPV6_RECVTCLASS, optval, optlen );
2077 case IPV6_UNICAST_HOPS:
2078 if (*optlen < 1 || !optval)
2080 SetLastError( WSAEFAULT );
2081 return SOCKET_ERROR;
2083 if (*optlen < sizeof(DWORD)) *optlen = 1;
2084 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IPV6_UNICAST_HOPS, optval, optlen );
2086 case IPV6_UNICAST_IF:
2087 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IPV6_UNICAST_IF, optval, optlen );
2089 case IPV6_V6ONLY:
2090 if (*optlen < 1 || !optval)
2092 SetLastError( WSAEFAULT );
2093 return SOCKET_ERROR;
2095 *optlen = 1;
2096 return server_getsockopt( s, IOCTL_AFD_WINE_GET_IPV6_V6ONLY, optval, optlen );
2098 default:
2099 FIXME( "unrecognized IPv6 option %u\n", optname );
2100 /* fall through */
2102 case IPV6_ADD_MEMBERSHIP:
2103 case IPV6_DROP_MEMBERSHIP:
2104 SetLastError( WSAENOPROTOOPT );
2105 return -1;
2108 default:
2109 WARN("Unknown level: 0x%08x\n", level);
2110 SetLastError(WSAEINVAL);
2111 return SOCKET_ERROR;
2112 } /* end switch(level) */
2116 static const char *debugstr_wsaioctl(DWORD code)
2118 const char *buf_type, *family;
2120 #define IOCTL_NAME(x) case x: return #x
2121 switch (code)
2123 IOCTL_NAME(FIONBIO);
2124 IOCTL_NAME(FIONREAD);
2125 IOCTL_NAME(SIOCATMARK);
2126 /* IOCTL_NAME(SIO_ACQUIRE_PORT_RESERVATION); */
2127 IOCTL_NAME(SIO_ADDRESS_LIST_CHANGE);
2128 IOCTL_NAME(SIO_ADDRESS_LIST_QUERY);
2129 IOCTL_NAME(SIO_ASSOCIATE_HANDLE);
2130 /* IOCTL_NAME(SIO_ASSOCIATE_PORT_RESERVATION);
2131 IOCTL_NAME(SIO_BASE_HANDLE);
2132 IOCTL_NAME(SIO_BSP_HANDLE);
2133 IOCTL_NAME(SIO_BSP_HANDLE_SELECT);
2134 IOCTL_NAME(SIO_BSP_HANDLE_POLL);
2135 IOCTL_NAME(SIO_CHK_QOS); */
2136 IOCTL_NAME(SIO_ENABLE_CIRCULAR_QUEUEING);
2137 IOCTL_NAME(SIO_FIND_ROUTE);
2138 IOCTL_NAME(SIO_FLUSH);
2139 IOCTL_NAME(SIO_GET_BROADCAST_ADDRESS);
2140 IOCTL_NAME(SIO_GET_EXTENSION_FUNCTION_POINTER);
2141 IOCTL_NAME(SIO_GET_GROUP_QOS);
2142 IOCTL_NAME(SIO_GET_INTERFACE_LIST);
2143 /* IOCTL_NAME(SIO_GET_INTERFACE_LIST_EX); */
2144 IOCTL_NAME(SIO_GET_QOS);
2145 IOCTL_NAME(SIO_IDEAL_SEND_BACKLOG_CHANGE);
2146 IOCTL_NAME(SIO_IDEAL_SEND_BACKLOG_QUERY);
2147 IOCTL_NAME(SIO_KEEPALIVE_VALS);
2148 IOCTL_NAME(SIO_MULTIPOINT_LOOPBACK);
2149 IOCTL_NAME(SIO_MULTICAST_SCOPE);
2150 /* IOCTL_NAME(SIO_QUERY_RSS_SCALABILITY_INFO);
2151 IOCTL_NAME(SIO_QUERY_WFP_ALE_ENDPOINT_HANDLE); */
2152 IOCTL_NAME(SIO_RCVALL);
2153 IOCTL_NAME(SIO_RCVALL_IGMPMCAST);
2154 IOCTL_NAME(SIO_RCVALL_MCAST);
2155 /* IOCTL_NAME(SIO_RELEASE_PORT_RESERVATION); */
2156 IOCTL_NAME(SIO_ROUTING_INTERFACE_CHANGE);
2157 IOCTL_NAME(SIO_ROUTING_INTERFACE_QUERY);
2158 IOCTL_NAME(SIO_SET_COMPATIBILITY_MODE);
2159 IOCTL_NAME(SIO_SET_GROUP_QOS);
2160 IOCTL_NAME(SIO_SET_QOS);
2161 IOCTL_NAME(SIO_TRANSLATE_HANDLE);
2162 IOCTL_NAME(SIO_UDP_CONNRESET);
2164 #undef IOCTL_NAME
2166 /* If this is not a known code split its bits */
2167 switch(code & 0x18000000)
2169 case IOC_WS2:
2170 family = "IOC_WS2";
2171 break;
2172 case IOC_PROTOCOL:
2173 family = "IOC_PROTOCOL";
2174 break;
2175 case IOC_VENDOR:
2176 family = "IOC_VENDOR";
2177 break;
2178 default: /* IOC_UNIX */
2180 BYTE size = (code >> 16) & IOCPARM_MASK;
2181 char x = (code & 0xff00) >> 8;
2182 BYTE y = code & 0xff;
2183 char args[14];
2185 switch (code & (IOC_VOID | IOC_INOUT))
2187 case IOC_VOID:
2188 buf_type = "_IO";
2189 sprintf(args, "%d, %d", x, y);
2190 break;
2191 case IOC_IN:
2192 buf_type = "_IOW";
2193 sprintf(args, "'%c', %d, %d", x, y, size);
2194 break;
2195 case IOC_OUT:
2196 buf_type = "_IOR";
2197 sprintf(args, "'%c', %d, %d", x, y, size);
2198 break;
2199 default:
2200 buf_type = "?";
2201 sprintf(args, "'%c', %d, %d", x, y, size);
2202 break;
2204 return wine_dbg_sprintf("%s(%s)", buf_type, args);
2208 /* We are different from IOC_UNIX. */
2209 switch (code & (IOC_VOID | IOC_INOUT))
2211 case IOC_VOID:
2212 buf_type = "_WSAIO";
2213 break;
2214 case IOC_INOUT:
2215 buf_type = "_WSAIORW";
2216 break;
2217 case IOC_IN:
2218 buf_type = "_WSAIOW";
2219 break;
2220 case IOC_OUT:
2221 buf_type = "_WSAIOR";
2222 break;
2223 default:
2224 buf_type = "?";
2225 break;
2228 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
2229 (USHORT)(code & 0xffff));
2232 /* do an ioctl call through the server */
2233 static DWORD server_ioctl_sock( SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size,
2234 LPVOID out_buff, DWORD out_size, LPDWORD ret_size,
2235 LPWSAOVERLAPPED overlapped,
2236 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
2238 IO_STATUS_BLOCK iosb, *piosb = &iosb;
2239 HANDLE handle = SOCKET2HANDLE( s );
2240 PIO_APC_ROUTINE apc = NULL;
2241 HANDLE event = NULL;
2242 void *cvalue = NULL;
2243 NTSTATUS status;
2245 if (overlapped)
2247 piosb = (IO_STATUS_BLOCK *)overlapped;
2248 if (!((ULONG_PTR)overlapped->hEvent & 1)) cvalue = overlapped;
2249 event = overlapped->hEvent;
2251 else
2253 if (!(event = get_sync_event())) return GetLastError();
2256 if (completion)
2258 event = NULL;
2259 cvalue = completion;
2260 apc = socket_apc;
2263 status = NtDeviceIoControlFile( handle, event, apc, cvalue, piosb, code,
2264 in_buff, in_size, out_buff, out_size );
2265 if (status == STATUS_PENDING && !overlapped)
2267 if (WaitForSingleObject( event, INFINITE ) == WAIT_FAILED)
2268 return -1;
2269 status = piosb->u.Status;
2271 if (status == STATUS_NOT_SUPPORTED)
2273 FIXME("Unsupported ioctl %#lx (device=%#lx access=%#lx func=%#lx method=%#lx)\n",
2274 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
2276 else if (status == STATUS_SUCCESS)
2277 *ret_size = piosb->Information;
2279 TRACE( "status %#lx.\n", status );
2280 return NtStatusToWSAError( status );
2284 /**********************************************************************
2285 * WSAIoctl (WS2_32.50)
2288 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
2289 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
2290 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
2292 TRACE( "socket %#Ix, %s, in_buff %p, in_size %#lx, out_buff %p,"
2293 " out_size %#lx, ret_size %p, overlapped %p, completion %p\n",
2294 s, debugstr_wsaioctl(code), in_buff, in_size, out_buff,
2295 out_size, ret_size, overlapped, completion );
2297 if (!ret_size)
2299 SetLastError( WSAEFAULT );
2300 return -1;
2303 switch (code)
2305 case FIONBIO:
2307 DWORD ret;
2309 if (IS_INTRESOURCE( in_buff ))
2311 SetLastError( WSAEFAULT );
2312 return -1;
2315 /* Explicitly ignore the output buffer; WeChat tries to pass an address
2316 * without write access. */
2317 ret = server_ioctl_sock( s, IOCTL_AFD_WINE_FIONBIO, in_buff, in_size,
2318 NULL, 0, ret_size, overlapped, completion );
2319 SetLastError( ret );
2320 return ret ? -1 : 0;
2323 case FIONREAD:
2325 DWORD ret;
2327 ret = server_ioctl_sock( s, IOCTL_AFD_WINE_FIONREAD, in_buff, in_size,
2328 out_buff, out_size, ret_size, overlapped, completion );
2329 SetLastError( ret );
2330 if (!ret) *ret_size = sizeof(u_long);
2331 return ret ? -1 : 0;
2334 case SIO_IDEAL_SEND_BACKLOG_QUERY:
2336 DWORD ret;
2337 WSAPROTOCOL_INFOA proto_info;
2338 int proto_len, len;
2339 struct sockaddr addr;
2341 if (!out_buff || out_size < sizeof(DWORD))
2343 SetLastError(WSAEFAULT);
2344 return SOCKET_ERROR;
2347 proto_len = sizeof(WSAPROTOCOL_INFOA);
2348 ret = getsockopt(s, SOL_SOCKET, SO_PROTOCOL_INFOA, (char *)&proto_info, &proto_len);
2349 if (ret == SOCKET_ERROR)
2350 return SOCKET_ERROR;
2352 if (proto_info.iSocketType != SOCK_STREAM)
2354 SetLastError( WSAEOPNOTSUPP );
2355 return SOCKET_ERROR;
2358 len = sizeof(addr);
2359 if (getpeername( s, &addr, &len ) == SOCKET_ERROR)
2361 return SOCKET_ERROR;
2364 *(DWORD*)out_buff = 0x10000; /* 64k */
2366 WARN("SIO_IDEAL_SEND_BACKLOG_QUERY Always returning 64k\n");
2368 SetLastError( ret );
2369 *ret_size = sizeof(DWORD);
2370 return 0;
2373 case SIOCATMARK:
2375 DWORD ret;
2377 ret = server_ioctl_sock( s, IOCTL_AFD_WINE_SIOCATMARK, in_buff, in_size,
2378 out_buff, out_size, ret_size, overlapped, completion );
2379 SetLastError( ret );
2380 if (!ret) *ret_size = sizeof(u_long);
2381 return ret ? -1 : 0;
2384 case SIO_GET_INTERFACE_LIST:
2386 DWORD ret;
2388 ret = server_ioctl_sock( s, IOCTL_AFD_WINE_GET_INTERFACE_LIST, in_buff, in_size,
2389 out_buff, out_size, ret_size, overlapped, completion );
2390 SetLastError( ret );
2391 if (ret && ret != ERROR_IO_PENDING) *ret_size = 0;
2392 return ret ? -1 : 0;
2395 case SIO_ADDRESS_LIST_QUERY:
2397 DWORD size, total;
2399 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
2401 if (out_size && out_size < FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[0]))
2403 *ret_size = 0;
2404 SetLastError(WSAEINVAL);
2405 return SOCKET_ERROR;
2408 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
2410 IP_ADAPTER_INFO *p, *table = malloc( size );
2411 NTSTATUS status = STATUS_SUCCESS;
2412 SOCKET_ADDRESS_LIST *sa_list;
2413 SOCKADDR_IN *sockaddr;
2414 SOCKET_ADDRESS *sa;
2415 unsigned int i;
2416 DWORD ret = 0;
2417 DWORD num;
2419 if (!table || GetAdaptersInfo(table, &size))
2421 free( table );
2422 SetLastError( WSAEINVAL );
2423 return -1;
2426 for (p = table, num = 0; p; p = p->Next)
2427 if (p->IpAddressList.IpAddress.String[0]) num++;
2429 total = FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[num]) + num * sizeof(*sockaddr);
2430 if (total > out_size || !out_buff)
2432 *ret_size = total;
2433 free( table );
2434 SetLastError( WSAEFAULT );
2435 return -1;
2438 sa_list = out_buff;
2439 sa = sa_list->Address;
2440 sockaddr = (SOCKADDR_IN *)&sa[num];
2441 sa_list->iAddressCount = num;
2443 for (p = table, i = 0; p; p = p->Next)
2445 if (!p->IpAddressList.IpAddress.String[0]) continue;
2447 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
2448 sa[i].iSockaddrLength = sizeof(SOCKADDR);
2450 sockaddr[i].sin_family = AF_INET;
2451 sockaddr[i].sin_port = 0;
2452 sockaddr[i].sin_addr.s_addr = inet_addr( p->IpAddressList.IpAddress.String );
2453 i++;
2456 free( table );
2458 ret = server_ioctl_sock( s, IOCTL_AFD_WINE_COMPLETE_ASYNC, &status, sizeof(status),
2459 NULL, 0, ret_size, overlapped, completion );
2460 *ret_size = total;
2461 SetLastError( ret );
2462 return ret ? -1 : 0;
2464 else
2466 WARN("unable to get IP address list\n");
2467 SetLastError( WSAEINVAL );
2468 return -1;
2472 case SIO_GET_EXTENSION_FUNCTION_POINTER:
2474 #define EXTENSION_FUNCTION(x, y) { x, y, #y },
2475 static const struct
2477 GUID guid;
2478 void *func_ptr;
2479 const char *name;
2480 } guid_funcs[] = {
2481 EXTENSION_FUNCTION(WSAID_CONNECTEX, WS2_ConnectEx)
2482 EXTENSION_FUNCTION(WSAID_DISCONNECTEX, WS2_DisconnectEx)
2483 EXTENSION_FUNCTION(WSAID_ACCEPTEX, WS2_AcceptEx)
2484 EXTENSION_FUNCTION(WSAID_GETACCEPTEXSOCKADDRS, WS2_GetAcceptExSockaddrs)
2485 EXTENSION_FUNCTION(WSAID_TRANSMITFILE, WS2_TransmitFile)
2486 /* EXTENSION_FUNCTION(WSAID_TRANSMITPACKETS, WS2_TransmitPackets) */
2487 EXTENSION_FUNCTION(WSAID_WSARECVMSG, WS2_WSARecvMsg)
2488 EXTENSION_FUNCTION(WSAID_WSASENDMSG, WSASendMsg)
2490 #undef EXTENSION_FUNCTION
2491 unsigned int i;
2493 for (i = 0; i < ARRAY_SIZE(guid_funcs); i++)
2495 if (IsEqualGUID(&guid_funcs[i].guid, in_buff))
2497 NTSTATUS status = STATUS_SUCCESS;
2498 DWORD ret = 0;
2500 TRACE( "returning %s\n", guid_funcs[i].name );
2501 *(void **)out_buff = guid_funcs[i].func_ptr;
2503 ret = server_ioctl_sock( s, IOCTL_AFD_WINE_COMPLETE_ASYNC, &status, sizeof(status),
2504 NULL, 0, ret_size, overlapped, completion );
2505 *ret_size = sizeof(void *);
2506 SetLastError( ret );
2507 return ret ? -1 : 0;
2511 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
2512 SetLastError( WSAEINVAL );
2513 return -1;
2516 case SIO_KEEPALIVE_VALS:
2518 DWORD ret;
2520 ret = server_ioctl_sock( s, IOCTL_AFD_WINE_KEEPALIVE_VALS, in_buff, in_size,
2521 out_buff, out_size, ret_size, overlapped, completion );
2522 if (!overlapped || completion) *ret_size = 0;
2523 SetLastError( ret );
2524 return ret ? -1 : 0;
2527 case SIO_ROUTING_INTERFACE_QUERY:
2529 struct sockaddr *daddr = (struct sockaddr *)in_buff;
2530 struct sockaddr_in *daddr_in = (struct sockaddr_in *)daddr;
2531 struct sockaddr_in *saddr_in = out_buff;
2532 MIB_IPFORWARDROW row;
2533 PMIB_IPADDRTABLE ipAddrTable = NULL;
2534 DWORD size, i, found_index, ret = 0;
2535 NTSTATUS status = STATUS_SUCCESS;
2537 if (!in_buff || in_size < sizeof(struct sockaddr) ||
2538 !out_buff || out_size < sizeof(struct sockaddr_in))
2540 SetLastError( WSAEFAULT );
2541 return -1;
2543 if (daddr->sa_family != AF_INET)
2545 FIXME("unsupported address family %d\n", daddr->sa_family);
2546 SetLastError( WSAEAFNOSUPPORT );
2547 return -1;
2549 if (GetBestRoute( daddr_in->sin_addr.S_un.S_addr, 0, &row ) != NOERROR ||
2550 GetIpAddrTable( NULL, &size, FALSE ) != ERROR_INSUFFICIENT_BUFFER)
2552 SetLastError( WSAEFAULT );
2553 return -1;
2555 ipAddrTable = malloc( size );
2556 if (GetIpAddrTable( ipAddrTable, &size, FALSE ))
2558 free( ipAddrTable );
2559 SetLastError( WSAEFAULT );
2560 return -1;
2562 for (i = 0, found_index = ipAddrTable->dwNumEntries;
2563 i < ipAddrTable->dwNumEntries; i++)
2565 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
2566 found_index = i;
2568 if (found_index == ipAddrTable->dwNumEntries)
2570 ERR( "no matching IP address for interface %lu\n", row.dwForwardIfIndex );
2571 free( ipAddrTable );
2572 SetLastError( WSAEFAULT );
2573 return -1;
2575 saddr_in->sin_family = AF_INET;
2576 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
2577 saddr_in->sin_port = 0;
2578 free( ipAddrTable );
2580 ret = server_ioctl_sock( s, IOCTL_AFD_WINE_COMPLETE_ASYNC, &status, sizeof(status),
2581 NULL, 0, ret_size, overlapped, completion );
2582 if (!ret) *ret_size = sizeof(struct sockaddr_in);
2583 SetLastError( ret );
2584 return ret ? -1 : 0;
2587 case SIO_ADDRESS_LIST_CHANGE:
2589 int force_async = !!overlapped;
2590 DWORD ret;
2592 ret = server_ioctl_sock( s, IOCTL_AFD_WINE_ADDRESS_LIST_CHANGE, &force_async, sizeof(force_async),
2593 out_buff, out_size, ret_size, overlapped, completion );
2594 SetLastError( ret );
2595 return ret ? -1 : 0;
2598 case SIO_UDP_CONNRESET:
2600 NTSTATUS status = STATUS_SUCCESS;
2601 DWORD ret;
2603 FIXME( "SIO_UDP_CONNRESET stub\n" );
2604 ret = server_ioctl_sock( s, IOCTL_AFD_WINE_COMPLETE_ASYNC, &status, sizeof(status),
2605 NULL, 0, ret_size, overlapped, completion );
2606 SetLastError( ret );
2607 return ret ? -1 : 0;
2610 case SIO_ENABLE_CIRCULAR_QUEUEING:
2612 NTSTATUS status = STATUS_SUCCESS;
2613 DWORD ret;
2615 FIXME( "SIO_ENABLE_CIRCULAR_QUEUEING stub\n" );
2616 ret = server_ioctl_sock( s, IOCTL_AFD_WINE_COMPLETE_ASYNC, &status, sizeof(status),
2617 NULL, 0, ret_size, overlapped, completion );
2618 SetLastError( ret );
2619 return ret ? -1 : 0;
2622 case SIO_BASE_HANDLE:
2624 NTSTATUS status;
2625 DWORD ret;
2627 if (overlapped)
2629 status = STATUS_NOT_SUPPORTED;
2631 else
2633 status = STATUS_SUCCESS;
2634 *(SOCKET *)out_buff = s;
2636 ret = server_ioctl_sock( s, IOCTL_AFD_WINE_COMPLETE_ASYNC, &status, sizeof(status),
2637 NULL, 0, ret_size, overlapped, completion );
2638 if (overlapped) ret = ERROR_IO_PENDING;
2639 if (!ret) *ret_size = sizeof(SOCKET);
2640 SetLastError( ret );
2641 return ret ? -1 : 0;
2644 default:
2645 FIXME( "unimplemented ioctl %s\n", debugstr_wsaioctl( code ) );
2646 /* fall through */
2647 case LOWORD(FIONBIO): /* Netscape tries to use this */
2648 case SIO_SET_COMPATIBILITY_MODE:
2650 NTSTATUS status = STATUS_NOT_SUPPORTED;
2652 server_ioctl_sock( s, IOCTL_AFD_WINE_COMPLETE_ASYNC, &status, sizeof(status),
2653 NULL, 0, ret_size, overlapped, completion );
2654 if (overlapped)
2656 SetLastError( ERROR_IO_PENDING );
2658 else
2660 *ret_size = 0;
2661 SetLastError( WSAEOPNOTSUPP );
2663 return -1;
2669 /***********************************************************************
2670 * ioctlsocket (WS2_32.10)
2672 int WINAPI ioctlsocket( SOCKET s, LONG cmd, u_long *argp )
2674 DWORD ret_size;
2675 return WSAIoctl( s, cmd, argp, sizeof(u_long), argp, sizeof(u_long), &ret_size, NULL, NULL );
2679 /***********************************************************************
2680 * listen (ws2_32.13)
2682 int WINAPI listen( SOCKET s, int backlog )
2684 struct afd_listen_params params = {.backlog = backlog};
2685 IO_STATUS_BLOCK io;
2686 NTSTATUS status;
2688 TRACE( "socket %#Ix, backlog %d\n", s, backlog );
2690 status = NtDeviceIoControlFile( SOCKET2HANDLE(s), NULL, NULL, NULL, &io,
2691 IOCTL_AFD_LISTEN, &params, sizeof(params), NULL, 0 );
2692 SetLastError( NtStatusToWSAError( status ) );
2693 TRACE( "status %#lx.\n", status );
2694 return status ? -1 : 0;
2698 /***********************************************************************
2699 * recv (WS2_32.16)
2701 int WINAPI recv( SOCKET s, char *buf, int len, int flags )
2703 DWORD n, dwFlags = flags;
2704 WSABUF wsabuf;
2706 wsabuf.len = len;
2707 wsabuf.buf = buf;
2709 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2710 return SOCKET_ERROR;
2711 else
2712 return n;
2715 /***********************************************************************
2716 * recvfrom (WS2_32.17)
2718 int WINAPI recvfrom( SOCKET s, char *buf, int len, int flags, struct sockaddr *from, int *fromlen )
2720 DWORD n, dwFlags = flags;
2721 WSABUF wsabuf;
2723 wsabuf.len = len;
2724 wsabuf.buf = buf;
2726 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
2727 return SOCKET_ERROR;
2728 else
2729 return n;
2733 /* as FD_SET(), but returns 1 if the fd was added, 0 otherwise */
2734 static int add_fd_to_set( SOCKET fd, struct fd_set *set )
2736 unsigned int i;
2738 for (i = 0; i < set->fd_count; ++i)
2740 if (set->fd_array[i] == fd)
2741 return 0;
2744 set->fd_array[set->fd_count++] = fd;
2745 return 1;
2749 /***********************************************************************
2750 * select (ws2_32.18)
2752 int WINAPI select( int count, fd_set *read_ptr, fd_set *write_ptr,
2753 fd_set *except_ptr, const struct timeval *timeout)
2755 static const int read_flags = AFD_POLL_READ | AFD_POLL_ACCEPT | AFD_POLL_HUP | AFD_POLL_RESET;
2756 static const int write_flags = AFD_POLL_WRITE;
2757 static const int except_flags = AFD_POLL_OOB | AFD_POLL_CONNECT_ERR;
2759 struct fd_set *read_input = NULL;
2760 struct afd_poll_params *params;
2761 unsigned int poll_count = 0;
2762 ULONG params_size, i, j;
2763 SOCKET poll_socket = 0;
2764 IO_STATUS_BLOCK io;
2765 HANDLE sync_event;
2766 int ret_count = 0;
2767 NTSTATUS status;
2769 TRACE( "read %p, write %p, except %p, timeout %p\n", read_ptr, write_ptr, except_ptr, timeout );
2771 if (!(sync_event = get_sync_event())) return -1;
2773 if (read_ptr) poll_count += read_ptr->fd_count;
2774 if (write_ptr) poll_count += write_ptr->fd_count;
2775 if (except_ptr) poll_count += except_ptr->fd_count;
2777 if (!poll_count)
2779 SetLastError( WSAEINVAL );
2780 return -1;
2783 params_size = offsetof( struct afd_poll_params, sockets[poll_count] );
2784 if (!(params = calloc( params_size, 1 )))
2786 SetLastError( WSAENOBUFS );
2787 return -1;
2790 if (timeout)
2791 params->timeout = (LONGLONG)timeout->tv_sec * -10000000 + (LONGLONG)timeout->tv_usec * -10;
2792 else
2793 params->timeout = TIMEOUT_INFINITE;
2795 if (read_ptr)
2797 unsigned int read_size = offsetof( struct fd_set, fd_array[read_ptr->fd_count] );
2799 if (!(read_input = malloc( read_size )))
2801 free( params );
2802 SetLastError( WSAENOBUFS );
2803 return -1;
2805 memcpy( read_input, read_ptr, read_size );
2807 for (i = 0; i < read_ptr->fd_count; ++i)
2809 params->sockets[params->count].socket = read_ptr->fd_array[i];
2810 params->sockets[params->count].flags = read_flags;
2811 ++params->count;
2812 poll_socket = read_ptr->fd_array[i];
2816 if (write_ptr)
2818 for (i = 0; i < write_ptr->fd_count; ++i)
2820 params->sockets[params->count].socket = write_ptr->fd_array[i];
2821 params->sockets[params->count].flags = write_flags;
2822 ++params->count;
2823 poll_socket = write_ptr->fd_array[i];
2827 if (except_ptr)
2829 for (i = 0; i < except_ptr->fd_count; ++i)
2831 params->sockets[params->count].socket = except_ptr->fd_array[i];
2832 params->sockets[params->count].flags = except_flags;
2833 ++params->count;
2834 poll_socket = except_ptr->fd_array[i];
2838 assert( params->count == poll_count );
2840 status = NtDeviceIoControlFile( (HANDLE)poll_socket, sync_event, NULL, NULL, &io,
2841 IOCTL_AFD_POLL, params, params_size, params, params_size );
2842 if (status == STATUS_PENDING)
2844 if (wait_event_alertable( sync_event ) == WAIT_FAILED)
2846 free( read_input );
2847 free( params );
2848 return -1;
2850 status = io.u.Status;
2852 if (status == STATUS_TIMEOUT) status = STATUS_SUCCESS;
2853 if (!status)
2855 /* pointers may alias, so clear them all first */
2856 if (read_ptr) read_ptr->fd_count = 0;
2857 if (write_ptr) write_ptr->fd_count = 0;
2858 if (except_ptr) except_ptr->fd_count = 0;
2860 for (i = 0; i < params->count; ++i)
2862 unsigned int flags = params->sockets[i].flags;
2863 SOCKET s = params->sockets[i].socket;
2865 if (read_input)
2867 for (j = 0; j < read_input->fd_count; ++j)
2869 if (read_input->fd_array[j] == s && (flags & (read_flags | AFD_POLL_CLOSE)))
2871 ret_count += add_fd_to_set( s, read_ptr );
2872 flags &= ~AFD_POLL_CLOSE;
2877 if (flags & AFD_POLL_CLOSE)
2878 status = STATUS_INVALID_HANDLE;
2880 if (flags & write_flags)
2881 ret_count += add_fd_to_set( s, write_ptr );
2883 if (flags & except_flags)
2884 ret_count += add_fd_to_set( s, except_ptr );
2886 if (flags & ~(read_flags | write_flags | except_flags | AFD_POLL_CLOSE))
2887 FIXME( "not reporting AFD flags %#x\n", flags );
2891 free( read_input );
2892 free( params );
2894 SetLastError( NtStatusToWSAError( status ) );
2895 TRACE( "status %#lx.\n", status );
2896 return status ? -1 : ret_count;
2900 static unsigned int afd_poll_flag_to_win32( unsigned int flags )
2902 static const unsigned int map[] =
2904 FD_READ, /* READ */
2905 FD_OOB, /* OOB */
2906 FD_WRITE, /* WRITE */
2907 FD_CLOSE, /* HUP */
2908 FD_CLOSE, /* RESET */
2909 0, /* CLOSE */
2910 FD_CONNECT, /* CONNECT */
2911 FD_ACCEPT, /* ACCEPT */
2912 FD_CONNECT, /* CONNECT_ERR */
2915 unsigned int i, ret = 0;
2917 for (i = 0; i < ARRAY_SIZE(map); ++i)
2919 if (flags & (1 << i)) ret |= map[i];
2922 return ret;
2926 /***********************************************************************
2927 * WSAPoll (ws2_32.@)
2929 int WINAPI WSAPoll( WSAPOLLFD *fds, ULONG count, int timeout )
2931 struct afd_poll_params *params;
2932 ULONG params_size, i, j;
2933 SOCKET poll_socket = 0;
2934 IO_STATUS_BLOCK io;
2935 HANDLE sync_event;
2936 int ret_count = 0;
2937 NTSTATUS status;
2939 if (!count)
2941 SetLastError(WSAEINVAL);
2942 return SOCKET_ERROR;
2944 if (!fds)
2946 SetLastError(WSAEFAULT);
2947 return SOCKET_ERROR;
2950 if (!(sync_event = get_sync_event())) return -1;
2952 params_size = offsetof( struct afd_poll_params, sockets[count] );
2953 if (!(params = calloc( params_size, 1 )))
2955 SetLastError(WSAENOBUFS);
2956 return SOCKET_ERROR;
2959 params->timeout = (timeout >= 0 ? (LONGLONG)timeout * -10000 : TIMEOUT_INFINITE);
2961 for (i = 0; i < count; ++i)
2963 unsigned int flags = AFD_POLL_HUP | AFD_POLL_RESET | AFD_POLL_CONNECT_ERR;
2965 if ((INT_PTR)fds[i].fd < 0 || !socket_list_find( fds[i].fd ))
2967 fds[i].revents = POLLNVAL;
2968 continue;
2971 poll_socket = fds[i].fd;
2972 params->sockets[params->count].socket = fds[i].fd;
2974 if (fds[i].events & POLLRDNORM)
2975 flags |= AFD_POLL_ACCEPT | AFD_POLL_READ;
2976 if (fds[i].events & POLLRDBAND)
2977 flags |= AFD_POLL_OOB;
2978 if (fds[i].events & POLLWRNORM)
2979 flags |= AFD_POLL_WRITE;
2980 params->sockets[params->count].flags = flags;
2981 ++params->count;
2983 fds[i].revents = 0;
2986 if (!poll_socket)
2988 SetLastError( WSAENOTSOCK );
2989 free( params );
2990 return -1;
2993 status = NtDeviceIoControlFile( (HANDLE)poll_socket, sync_event, NULL, NULL, &io, IOCTL_AFD_POLL,
2994 params, params_size, params, params_size );
2995 if (status == STATUS_PENDING)
2997 if (wait_event_alertable( sync_event ) == WAIT_FAILED)
2999 free( params );
3000 return -1;
3002 status = io.u.Status;
3004 if (!status)
3006 for (i = 0; i < count; ++i)
3008 for (j = 0; j < params->count; ++j)
3010 if (fds[i].fd == params->sockets[j].socket)
3012 unsigned int revents = 0;
3014 if (params->sockets[j].flags & (AFD_POLL_ACCEPT | AFD_POLL_READ))
3015 revents |= POLLRDNORM;
3016 if (params->sockets[j].flags & AFD_POLL_OOB)
3017 revents |= POLLRDBAND;
3018 if (params->sockets[j].flags & AFD_POLL_WRITE)
3019 revents |= POLLWRNORM;
3020 if (params->sockets[j].flags & (AFD_POLL_RESET | AFD_POLL_HUP))
3021 revents |= POLLHUP;
3022 if (params->sockets[j].flags & (AFD_POLL_RESET | AFD_POLL_CONNECT_ERR))
3023 revents |= POLLERR;
3024 if (params->sockets[j].flags & AFD_POLL_CLOSE)
3025 revents |= POLLNVAL;
3027 fds[i].revents = revents & (fds[i].events | POLLHUP | POLLERR | POLLNVAL);
3029 if (fds[i].revents)
3030 ++ret_count;
3035 if (status == STATUS_TIMEOUT) status = STATUS_SUCCESS;
3037 free( params );
3039 SetLastError( NtStatusToWSAError( status ) );
3040 TRACE( "status %#lx.\n", status );
3041 return status ? -1 : ret_count;
3045 /***********************************************************************
3046 * send (WS2_32.19)
3048 int WINAPI send( SOCKET s, const char *buf, int len, int flags )
3050 DWORD n;
3051 WSABUF wsabuf;
3053 wsabuf.len = len;
3054 wsabuf.buf = (char*) buf;
3056 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
3057 return SOCKET_ERROR;
3058 else
3059 return n;
3062 /***********************************************************************
3063 * WSASend (WS2_32.72)
3065 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3066 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3067 LPWSAOVERLAPPED lpOverlapped,
3068 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3070 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
3071 NULL, 0, lpOverlapped, lpCompletionRoutine );
3074 /***********************************************************************
3075 * WSASendDisconnect (WS2_32.73)
3077 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
3079 return shutdown( s, SD_SEND );
3083 /***********************************************************************
3084 * WSASendTo (WS2_32.74)
3086 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3087 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3088 const struct sockaddr *to, int tolen,
3089 LPWSAOVERLAPPED lpOverlapped,
3090 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3092 /* Garena hooks WSASendTo(), so we need a wrapper */
3093 return WS2_sendto( s, lpBuffers, dwBufferCount,
3094 lpNumberOfBytesSent, dwFlags,
3095 to, tolen,
3096 lpOverlapped, lpCompletionRoutine );
3099 /***********************************************************************
3100 * sendto (WS2_32.20)
3102 int WINAPI sendto( SOCKET s, const char *buf, int len, int flags, const struct sockaddr *to, int tolen )
3104 DWORD n;
3105 WSABUF wsabuf;
3107 wsabuf.len = len;
3108 wsabuf.buf = (char*) buf;
3110 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
3111 return SOCKET_ERROR;
3112 else
3113 return n;
3117 static int server_setsockopt( SOCKET s, ULONG code, const char *optval, int optlen )
3119 IO_STATUS_BLOCK io;
3120 NTSTATUS status;
3122 status = NtDeviceIoControlFile( (HANDLE)s, NULL, NULL, NULL, &io, code, (void *)optval, optlen, NULL, 0 );
3123 SetLastError( NtStatusToWSAError( status ) );
3124 TRACE( "status %#lx.\n", status );
3125 return status ? -1 : 0;
3129 /***********************************************************************
3130 * setsockopt (WS2_32.21)
3132 int WINAPI setsockopt( SOCKET s, int level, int optname, const char *optval, int optlen )
3134 DWORD value = 0;
3136 TRACE( "socket %#Ix, %s, optval %s, optlen %d\n",
3137 s, debugstr_sockopt(level, optname), debugstr_optval(optval, optlen), optlen );
3139 /* some broken apps pass the value directly instead of a pointer to it */
3140 if(optlen && IS_INTRESOURCE(optval))
3142 SetLastError(WSAEFAULT);
3143 return SOCKET_ERROR;
3146 switch(level)
3148 case SOL_SOCKET:
3149 switch(optname)
3151 case SO_BROADCAST:
3152 if (!optval)
3154 SetLastError( WSAEFAULT );
3155 return SOCKET_ERROR;
3157 memcpy( &value, optval, min( optlen, sizeof(value) ));
3158 return server_setsockopt( s, IOCTL_AFD_WINE_SET_SO_BROADCAST, (char *)&value, sizeof(value) );
3159 case SO_DONTLINGER:
3161 LINGER linger;
3163 if (!optval)
3165 SetLastError( WSAEFAULT );
3166 return -1;
3169 linger.l_onoff = !*(const BOOL *)optval;
3170 linger.l_linger = 0;
3171 return setsockopt( s, SOL_SOCKET, SO_LINGER, (char *)&linger, sizeof(linger) );
3174 case SO_ERROR:
3175 FIXME( "SO_ERROR, stub.\n" );
3176 SetLastError( ERROR_SUCCESS );
3177 return 0;
3179 case SO_KEEPALIVE:
3180 if (optlen <= 0 || !optval)
3182 SetLastError( optlen ? WSAENOBUFS : WSAEFAULT );
3183 return SOCKET_ERROR;
3185 value = *optval;
3186 return server_setsockopt( s, IOCTL_AFD_WINE_SET_SO_KEEPALIVE, (char *)&value, sizeof(value) );
3188 case SO_LINGER:
3189 if (optlen < sizeof(LINGER) || !optval)
3191 SetLastError( WSAEFAULT );
3192 return SOCKET_ERROR;
3194 return server_setsockopt( s, IOCTL_AFD_WINE_SET_SO_LINGER, optval, optlen );
3196 case SO_OOBINLINE:
3197 if (!optval)
3199 SetLastError( WSAEFAULT );
3200 return SOCKET_ERROR;
3202 memcpy( &value, optval, min( optlen, sizeof(value) ));
3203 return server_setsockopt( s, IOCTL_AFD_WINE_SET_SO_OOBINLINE, (char *)&value, sizeof(value) );
3205 case SO_RCVBUF:
3206 if (optlen < 0) optlen = 4;
3207 return server_setsockopt( s, IOCTL_AFD_WINE_SET_SO_RCVBUF, optval, optlen );
3209 case SO_RCVTIMEO:
3210 if (optlen < 0) optlen = 4;
3211 return server_setsockopt( s, IOCTL_AFD_WINE_SET_SO_RCVTIMEO, optval, optlen );
3213 case SO_REUSEADDR:
3214 if (!optval)
3216 SetLastError( WSAEFAULT );
3217 return SOCKET_ERROR;
3219 memcpy( &value, optval, min( optlen, sizeof(value) ));
3220 return server_setsockopt( s, IOCTL_AFD_WINE_SET_SO_REUSEADDR, (char *)&value, sizeof(value) );
3222 case SO_EXCLUSIVEADDRUSE:
3223 if (!optval)
3225 SetLastError( WSAEFAULT );
3226 return SOCKET_ERROR;
3228 memcpy( &value, optval, min( optlen, sizeof(value) ));
3229 return server_setsockopt( s, IOCTL_AFD_WINE_SET_SO_EXCLUSIVEADDRUSE, (char *)&value, sizeof(value) );
3231 case SO_SNDBUF:
3232 if (optlen < 0) optlen = 4;
3233 return server_setsockopt( s, IOCTL_AFD_WINE_SET_SO_SNDBUF, optval, optlen );
3235 case SO_SNDTIMEO:
3236 if (optlen < 0) optlen = 4;
3237 return server_setsockopt( s, IOCTL_AFD_WINE_SET_SO_SNDTIMEO, optval, optlen );
3239 /* SO_DEBUG is a privileged operation, ignore it. */
3240 case SO_DEBUG:
3241 TRACE("Ignoring SO_DEBUG\n");
3242 return 0;
3244 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
3245 * socket. According to MSDN, this option is silently ignored.*/
3246 case SO_DONTROUTE:
3247 TRACE( "Ignoring SO_DONTROUTE.\n" );
3248 if (optlen <= 0)
3250 SetLastError( optlen ? WSAENOBUFS : WSAEFAULT );
3251 return -1;
3253 SetLastError( ERROR_SUCCESS );
3254 return 0;
3256 /* After a ConnectEx call succeeds, the socket can't be used with half of the
3257 * normal winsock functions on windows. We don't have that problem. */
3258 case SO_UPDATE_CONNECT_CONTEXT:
3259 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
3260 return 0;
3262 /* After a AcceptEx call succeeds, the socket can't be used with half of the
3263 * normal winsock functions on windows. We don't have that problem. */
3264 case SO_UPDATE_ACCEPT_CONTEXT:
3265 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
3266 return 0;
3268 /* SO_OPENTYPE does not require a valid socket handle. */
3269 case SO_OPENTYPE:
3270 if (!optlen || optlen < sizeof(int) || !optval)
3272 SetLastError( WSAEFAULT );
3273 return SOCKET_ERROR;
3275 get_per_thread_data()->opentype = *(const int *)optval;
3276 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
3277 SetLastError( ERROR_SUCCESS );
3278 return 0;
3280 case SO_RANDOMIZE_PORT:
3281 FIXME("Ignoring SO_RANDOMIZE_PORT\n");
3282 return 0;
3284 case SO_PORT_SCALABILITY:
3285 FIXME("Ignoring SO_PORT_SCALABILITY\n");
3286 return 0;
3288 case SO_REUSE_UNICASTPORT:
3289 FIXME("Ignoring SO_REUSE_UNICASTPORT\n");
3290 return 0;
3292 case SO_REUSE_MULTICASTPORT:
3293 FIXME("Ignoring SO_REUSE_MULTICASTPORT\n");
3294 return 0;
3296 default:
3297 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3298 /* fall through */
3300 case SO_ACCEPTCONN:
3301 case SO_TYPE:
3302 SetLastError(WSAENOPROTOOPT);
3303 return SOCKET_ERROR;
3305 break; /* case SOL_SOCKET */
3307 case NSPROTO_IPX:
3308 switch(optname)
3310 case IPX_PTYPE:
3311 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IPX_PTYPE, optval, optlen );
3313 case IPX_FILTERPTYPE:
3314 /* Sets the receive filter packet type, at the moment we don't support it */
3315 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
3316 /* Returning 0 is better for now than returning a SOCKET_ERROR */
3317 return 0;
3319 default:
3320 FIXME("opt_name:%x\n", optname);
3321 SetLastError(WSAENOPROTOOPT);
3322 return SOCKET_ERROR;
3324 break; /* case NSPROTO_IPX */
3326 case IPPROTO_TCP:
3327 switch(optname)
3329 case TCP_NODELAY:
3330 if (optlen <= 0 || !optval)
3332 SetLastError( optlen && optval ? WSAENOBUFS : WSAEFAULT );
3333 return SOCKET_ERROR;
3335 value = *optval;
3336 return server_setsockopt( s, IOCTL_AFD_WINE_SET_TCP_NODELAY, (char*)&value, sizeof(value) );
3338 default:
3339 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3340 SetLastError(WSAENOPROTOOPT);
3341 return SOCKET_ERROR;
3343 break;
3345 case IPPROTO_IP:
3346 if (optlen < 0)
3348 SetLastError(WSAENOBUFS);
3349 return SOCKET_ERROR;
3352 switch(optname)
3354 case IP_ADD_MEMBERSHIP:
3355 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_ADD_MEMBERSHIP, optval, optlen );
3357 case IP_ADD_SOURCE_MEMBERSHIP:
3358 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_ADD_SOURCE_MEMBERSHIP, optval, optlen );
3360 case IP_BLOCK_SOURCE:
3361 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_BLOCK_SOURCE, optval, optlen );
3363 case IP_DONTFRAGMENT:
3364 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_DONTFRAGMENT, optval, optlen );
3366 case IP_DROP_MEMBERSHIP:
3367 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_DROP_MEMBERSHIP, optval, optlen );
3369 case IP_DROP_SOURCE_MEMBERSHIP:
3370 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_DROP_SOURCE_MEMBERSHIP, optval, optlen );
3372 case IP_HDRINCL:
3373 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_HDRINCL, optval, optlen );
3375 case IP_MULTICAST_IF:
3376 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_MULTICAST_IF, optval, optlen );
3378 case IP_MULTICAST_LOOP:
3379 if (!optlen)
3381 SetLastError( WSAEFAULT );
3382 return -1;
3384 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_MULTICAST_LOOP, optval, optlen );
3386 case IP_MULTICAST_TTL:
3387 if (!optlen)
3389 SetLastError( WSAEFAULT );
3390 return -1;
3392 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_MULTICAST_TTL, optval, optlen );
3394 case IP_OPTIONS:
3395 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_OPTIONS, optval, optlen );
3397 case IP_PKTINFO:
3398 if (optlen < sizeof(DWORD) || !optval)
3400 SetLastError( WSAEFAULT );
3401 return SOCKET_ERROR;
3403 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_PKTINFO, optval, optlen );
3405 case IP_RECVTOS:
3406 if (optlen < sizeof(DWORD) || !optval)
3408 SetLastError( WSAEFAULT );
3409 return SOCKET_ERROR;
3411 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_RECVTOS, optval, optlen );
3413 case IP_RECVTTL:
3414 if (optlen < sizeof(DWORD) || !optval)
3416 SetLastError( WSAEFAULT );
3417 return SOCKET_ERROR;
3419 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_RECVTTL, optval, optlen );
3421 case IP_TOS:
3422 if (!optlen || !optval)
3424 SetLastError(WSAEFAULT);
3425 return SOCKET_ERROR;
3427 memcpy( &value, optval, min( optlen, sizeof(value) ));
3428 if (value > 0xff)
3430 SetLastError(WSAEINVAL);
3431 return SOCKET_ERROR;
3433 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_TOS, optval, optlen );
3435 case IP_TTL:
3436 if (!optlen)
3438 SetLastError( WSAEFAULT );
3439 return -1;
3441 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_TTL, optval, optlen );
3443 case IP_UNBLOCK_SOURCE:
3444 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_UNBLOCK_SOURCE, optval, optlen );
3446 case IP_UNICAST_IF:
3447 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IP_UNICAST_IF, optval, optlen );
3449 default:
3450 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3451 SetLastError(WSAENOPROTOOPT);
3452 return SOCKET_ERROR;
3454 break;
3456 case IPPROTO_IPV6:
3457 if (optlen < 0)
3459 SetLastError( WSAENOBUFS );
3460 return SOCKET_ERROR;
3463 switch(optname)
3465 case IPV6_ADD_MEMBERSHIP:
3466 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IPV6_ADD_MEMBERSHIP, optval, optlen );
3468 case IPV6_DONTFRAG:
3469 if (!optlen || !optval)
3471 SetLastError( WSAEFAULT );
3472 return SOCKET_ERROR;
3474 memcpy( &value, optval, min( optlen, sizeof(value) ));
3475 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IPV6_DONTFRAG, (char *)&value, sizeof(value) );
3477 case IPV6_DROP_MEMBERSHIP:
3478 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IPV6_DROP_MEMBERSHIP, optval, optlen );
3480 case IPV6_HOPLIMIT:
3481 if (optlen < sizeof(DWORD) || !optval)
3483 SetLastError( WSAEFAULT );
3484 return SOCKET_ERROR;
3486 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IPV6_RECVHOPLIMIT, optval, optlen );
3488 case IPV6_MULTICAST_HOPS:
3489 if (!optlen || !optval)
3491 SetLastError( WSAEFAULT );
3492 return SOCKET_ERROR;
3494 memcpy( &value, optval, min( optlen, sizeof(value) ));
3495 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IPV6_MULTICAST_HOPS, (char *)&value, sizeof(value) );
3497 case IPV6_MULTICAST_IF:
3498 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IPV6_MULTICAST_IF, optval, optlen );
3500 case IPV6_MULTICAST_LOOP:
3501 if (!optlen || !optval)
3503 SetLastError( WSAEFAULT );
3504 return SOCKET_ERROR;
3506 memcpy( &value, optval, min( optlen, sizeof(value) ));
3507 value = !!value;
3508 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IPV6_MULTICAST_LOOP, (char *)&value, sizeof(value) );
3510 case IPV6_PKTINFO:
3511 if (optlen < sizeof(DWORD) || !optval)
3513 SetLastError( WSAEFAULT );
3514 return SOCKET_ERROR;
3516 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IPV6_RECVPKTINFO, optval, optlen );
3518 case IPV6_PROTECTION_LEVEL:
3519 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
3520 return 0;
3522 case IPV6_RECVTCLASS:
3523 if (optlen < sizeof(DWORD) || !optval)
3525 SetLastError( WSAEFAULT );
3526 return SOCKET_ERROR;
3528 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IPV6_RECVTCLASS, optval, optlen );
3530 case IPV6_UNICAST_HOPS:
3531 if (!optlen || !optval)
3533 SetLastError( WSAEFAULT );
3534 return SOCKET_ERROR;
3536 memcpy( &value, optval, min( optlen, sizeof(value) ));
3537 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IPV6_UNICAST_HOPS, (char *)&value, sizeof(value) );
3539 case IPV6_UNICAST_IF:
3540 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IPV6_UNICAST_IF, optval, optlen );
3542 case IPV6_V6ONLY:
3543 if (!optlen || !optval)
3545 SetLastError( WSAEFAULT );
3546 return SOCKET_ERROR;
3548 value = *optval;
3549 return server_setsockopt( s, IOCTL_AFD_WINE_SET_IPV6_V6ONLY, (char *)&value, sizeof(value) );
3551 default:
3552 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
3553 SetLastError(WSAENOPROTOOPT);
3554 return SOCKET_ERROR;
3556 break;
3558 default:
3559 WARN("Unknown level: 0x%08x\n", level);
3560 SetLastError(WSAEINVAL);
3561 return SOCKET_ERROR;
3562 } /* end switch(level) */
3566 /***********************************************************************
3567 * shutdown (ws2_32.22)
3569 int WINAPI shutdown( SOCKET s, int how )
3571 IO_STATUS_BLOCK io;
3572 NTSTATUS status;
3574 TRACE( "socket %#Ix, how %u\n", s, how );
3576 status = NtDeviceIoControlFile( (HANDLE)s, NULL, NULL, NULL, &io,
3577 IOCTL_AFD_WINE_SHUTDOWN, &how, sizeof(how), NULL, 0 );
3578 SetLastError( NtStatusToWSAError( status ) );
3579 TRACE( "status %#lx.\n", status );
3580 return status ? -1 : 0;
3584 /***********************************************************************
3585 * socket (WS2_32.23)
3587 SOCKET WINAPI socket( int af, int type, int protocol )
3589 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
3591 return WSASocketW( af, type, protocol, NULL, 0,
3592 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
3596 /***********************************************************************
3597 * WSAEnumNetworkEvents (ws2_32.@)
3599 int WINAPI WSAEnumNetworkEvents( SOCKET s, WSAEVENT event, WSANETWORKEVENTS *ret_events )
3601 struct afd_get_events_params params;
3602 IO_STATUS_BLOCK io;
3603 NTSTATUS status;
3605 TRACE( "socket %#Ix, event %p, events %p\n", s, event, ret_events );
3607 ResetEvent( event );
3609 status = NtDeviceIoControlFile( (HANDLE)s, NULL, NULL, NULL, &io, IOCTL_AFD_GET_EVENTS,
3610 NULL, 0, &params, sizeof(params) );
3611 if (!status)
3613 ret_events->lNetworkEvents = afd_poll_flag_to_win32( params.flags );
3615 if (ret_events->lNetworkEvents & FD_READ)
3616 ret_events->iErrorCode[FD_READ_BIT] = NtStatusToWSAError( params.status[AFD_POLL_BIT_READ] );
3618 if (ret_events->lNetworkEvents & FD_WRITE)
3619 ret_events->iErrorCode[FD_WRITE_BIT] = NtStatusToWSAError( params.status[AFD_POLL_BIT_WRITE] );
3621 if (ret_events->lNetworkEvents & FD_OOB)
3622 ret_events->iErrorCode[FD_OOB_BIT] = NtStatusToWSAError( params.status[AFD_POLL_BIT_OOB] );
3624 if (ret_events->lNetworkEvents & FD_ACCEPT)
3625 ret_events->iErrorCode[FD_ACCEPT_BIT] = NtStatusToWSAError( params.status[AFD_POLL_BIT_ACCEPT] );
3627 if (ret_events->lNetworkEvents & FD_CONNECT)
3628 ret_events->iErrorCode[FD_CONNECT_BIT] = NtStatusToWSAError( params.status[AFD_POLL_BIT_CONNECT_ERR] );
3630 if (ret_events->lNetworkEvents & FD_CLOSE)
3632 if (!(ret_events->iErrorCode[FD_CLOSE_BIT] = NtStatusToWSAError( params.status[AFD_POLL_BIT_HUP] )))
3633 ret_events->iErrorCode[FD_CLOSE_BIT] = NtStatusToWSAError( params.status[AFD_POLL_BIT_RESET] );
3636 SetLastError( NtStatusToWSAError( status ) );
3637 TRACE( "status %#lx.\n", status );
3638 return status ? -1 : 0;
3642 static unsigned int afd_poll_flag_from_win32( unsigned int flags )
3644 static const unsigned int map[] =
3646 AFD_POLL_READ,
3647 AFD_POLL_WRITE,
3648 AFD_POLL_OOB,
3649 AFD_POLL_ACCEPT,
3650 AFD_POLL_CONNECT | AFD_POLL_CONNECT_ERR,
3651 AFD_POLL_RESET | AFD_POLL_HUP,
3654 unsigned int i, ret = 0;
3656 for (i = 0; i < ARRAY_SIZE(map); ++i)
3658 if (flags & (1 << i)) ret |= map[i];
3661 return ret;
3665 /***********************************************************************
3666 * WSAEventSelect (ws2_32.@)
3668 int WINAPI WSAEventSelect( SOCKET s, WSAEVENT event, LONG mask )
3670 struct afd_event_select_params params;
3671 IO_STATUS_BLOCK io;
3672 NTSTATUS status;
3674 TRACE( "socket %#Ix, event %p, mask %#lx\n", s, event, mask );
3676 params.event = event;
3677 params.mask = afd_poll_flag_from_win32( mask );
3679 status = NtDeviceIoControlFile( (HANDLE)s, NULL, NULL, NULL, &io, IOCTL_AFD_EVENT_SELECT,
3680 &params, sizeof(params), NULL, 0 );
3681 SetLastError( NtStatusToWSAError( status ) );
3682 TRACE( "status %#lx.\n", status );
3683 return status ? -1 : 0;
3687 /**********************************************************************
3688 * WSAGetOverlappedResult (WS2_32.40)
3690 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
3691 LPDWORD lpcbTransfer, BOOL fWait,
3692 LPDWORD lpdwFlags )
3694 NTSTATUS status;
3696 TRACE( "socket %#Ix, overlapped %p, transfer %p, wait %d, flags %p\n",
3697 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
3699 if ( lpOverlapped == NULL )
3701 ERR( "Invalid pointer\n" );
3702 SetLastError(WSA_INVALID_PARAMETER);
3703 return FALSE;
3706 if (!socket_list_find( s ))
3708 SetLastError( WSAENOTSOCK );
3709 return FALSE;
3712 /* Paired with the write-release in set_async_iosb() in ntdll; see the
3713 * latter for details. */
3714 status = ReadAcquire( (LONG *)&lpOverlapped->Internal );
3715 if (status == STATUS_PENDING)
3717 if (!fWait)
3719 SetLastError( WSA_IO_INCOMPLETE );
3720 return FALSE;
3723 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
3724 INFINITE ) == WAIT_FAILED)
3725 return FALSE;
3726 /* We don't need to give this load acquire semantics; the wait above
3727 * already guarantees that the IOSB and output buffer are filled. */
3728 status = lpOverlapped->Internal;
3731 if ( lpcbTransfer )
3732 *lpcbTransfer = lpOverlapped->InternalHigh;
3734 if ( lpdwFlags )
3735 *lpdwFlags = lpOverlapped->u.s.Offset;
3737 SetLastError( NtStatusToWSAError(status) );
3738 TRACE( "status %#lx.\n", status );
3739 return NT_SUCCESS( status );
3743 /***********************************************************************
3744 * WSAAsyncSelect (ws2_32.@)
3746 int WINAPI WSAAsyncSelect( SOCKET s, HWND window, UINT message, LONG mask )
3748 struct afd_message_select_params params;
3749 IO_STATUS_BLOCK io;
3750 NTSTATUS status;
3752 TRACE( "socket %#Ix, window %p, message %#x, mask %#lx\n", s, window, message, mask );
3754 params.handle = s;
3755 params.window = HandleToULong( window );
3756 params.message = message;
3757 params.mask = afd_poll_flag_from_win32( mask );
3759 status = NtDeviceIoControlFile( (HANDLE)s, NULL, NULL, NULL, &io, IOCTL_AFD_WINE_MESSAGE_SELECT,
3760 &params, sizeof(params), NULL, 0 );
3761 SetLastError( NtStatusToWSAError( status ) );
3762 TRACE( "status %#lx.\n", status );
3763 return status ? -1 : 0;
3767 /***********************************************************************
3768 * WSACreateEvent (WS2_32.31)
3771 WSAEVENT WINAPI WSACreateEvent(void)
3773 /* Create a manual-reset event, with initial state: unsignaled */
3774 TRACE("\n");
3776 return CreateEventW(NULL, TRUE, FALSE, NULL);
3779 /***********************************************************************
3780 * WSACloseEvent (WS2_32.29)
3783 BOOL WINAPI WSACloseEvent(WSAEVENT event)
3785 TRACE ("event=%p\n", event);
3787 return CloseHandle(event);
3790 /***********************************************************************
3791 * WSASocketA (WS2_32.78)
3794 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
3795 LPWSAPROTOCOL_INFOA lpProtocolInfo,
3796 GROUP g, DWORD dwFlags)
3798 INT len;
3799 WSAPROTOCOL_INFOW info;
3801 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
3803 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
3804 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
3805 info.szProtocol, WSAPROTOCOL_LEN + 1);
3807 if (!len)
3809 SetLastError(WSAEINVAL);
3810 return SOCKET_ERROR;
3813 return WSASocketW(af, type, protocol, &info, g, dwFlags);
3816 /***********************************************************************
3817 * WSASocketW (WS2_32.79)
3820 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
3821 LPWSAPROTOCOL_INFOW lpProtocolInfo,
3822 GROUP g, DWORD flags)
3824 struct afd_create_params create_params;
3825 OBJECT_ATTRIBUTES attr;
3826 UNICODE_STRING string = RTL_CONSTANT_STRING(L"\\Device\\Afd");
3827 IO_STATUS_BLOCK io;
3828 NTSTATUS status;
3829 HANDLE handle;
3830 SOCKET ret;
3831 DWORD err;
3834 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
3835 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
3838 TRACE( "family %d, type %d, protocol %d, info %p, group %u, flags %#lx\n",
3839 af, type, protocol, lpProtocolInfo, g, flags );
3841 if (!num_startup)
3843 WARN( "not initialised\n" );
3844 SetLastError( WSANOTINITIALISED );
3845 return -1;
3848 /* hack for WSADuplicateSocket */
3849 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00)
3851 ret = lpProtocolInfo->dwServiceFlags3;
3852 TRACE( "got duplicate %#Ix\n", ret );
3853 if (!socket_list_add(ret))
3855 CloseHandle(SOCKET2HANDLE(ret));
3856 return INVALID_SOCKET;
3858 return ret;
3861 if (lpProtocolInfo)
3863 if (af == FROM_PROTOCOL_INFO || !af)
3864 af = lpProtocolInfo->iAddressFamily;
3865 if (type == FROM_PROTOCOL_INFO || !type)
3866 type = lpProtocolInfo->iSocketType;
3867 if (protocol == FROM_PROTOCOL_INFO || !protocol)
3868 protocol = lpProtocolInfo->iProtocol;
3871 if (!af && !protocol)
3873 WSASetLastError(WSAEINVAL);
3874 return INVALID_SOCKET;
3877 if (!af && lpProtocolInfo)
3879 WSASetLastError(WSAEAFNOSUPPORT);
3880 return INVALID_SOCKET;
3883 if (!af || !type || !protocol)
3885 unsigned int i;
3887 for (i = 0; i < ARRAY_SIZE(supported_protocols); ++i)
3889 const WSAPROTOCOL_INFOW *info = &supported_protocols[i];
3891 if (af && af != info->iAddressFamily) continue;
3892 if (type && type != info->iSocketType) continue;
3893 if (protocol && (protocol < info->iProtocol ||
3894 protocol > info->iProtocol + info->iProtocolMaxOffset)) continue;
3895 if (!protocol && !(info->dwProviderFlags & PFL_MATCHES_PROTOCOL_ZERO)) continue;
3897 if (!af) af = supported_protocols[i].iAddressFamily;
3898 if (!type) type = supported_protocols[i].iSocketType;
3899 if (!protocol) protocol = supported_protocols[i].iProtocol;
3900 break;
3904 InitializeObjectAttributes(&attr, &string, (flags & WSA_FLAG_NO_HANDLE_INHERIT) ? 0 : OBJ_INHERIT, NULL, NULL);
3905 if ((status = NtOpenFile(&handle, GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, &attr,
3906 &io, 0, (flags & WSA_FLAG_OVERLAPPED) ? 0 : FILE_SYNCHRONOUS_IO_NONALERT)))
3908 WARN( "failed to create socket, status %#lx\n", status );
3909 WSASetLastError(NtStatusToWSAError(status));
3910 return INVALID_SOCKET;
3913 create_params.family = af;
3914 create_params.type = type;
3915 create_params.protocol = protocol;
3916 create_params.flags = flags & ~(WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
3917 if ((status = NtDeviceIoControlFile(handle, NULL, NULL, NULL, &io,
3918 IOCTL_AFD_WINE_CREATE, &create_params, sizeof(create_params), NULL, 0)))
3920 WARN( "failed to initialize socket, status %#lx\n", status );
3921 err = RtlNtStatusToDosError( status );
3922 if (err == WSAEACCES) /* raw socket denied */
3924 if (type == SOCK_RAW)
3925 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
3926 else
3927 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
3929 WSASetLastError(err);
3930 NtClose(handle);
3931 return INVALID_SOCKET;
3934 ret = HANDLE2SOCKET(handle);
3935 TRACE( "created %#Ix\n", ret );
3937 if (!socket_list_add(ret))
3939 CloseHandle(handle);
3940 return INVALID_SOCKET;
3942 WSASetLastError(0);
3943 return ret;
3946 /***********************************************************************
3947 * WSAJoinLeaf (WS2_32.58)
3950 SOCKET WINAPI WSAJoinLeaf( SOCKET s, const struct sockaddr *addr, int addrlen, WSABUF *caller_data,
3951 WSABUF *callee_data, QOS *socket_qos, QOS *group_qos, DWORD flags)
3953 FIXME("stub.\n");
3954 return INVALID_SOCKET;
3957 /***********************************************************************
3958 * __WSAFDIsSet (WS2_32.151)
3960 int WINAPI __WSAFDIsSet( SOCKET s, fd_set *set )
3962 int i = set->fd_count, ret = 0;
3964 while (i--)
3965 if (set->fd_array[i] == s)
3967 ret = 1;
3968 break;
3971 return ret;
3974 /***********************************************************************
3975 * WSAIsBlocking (WS2_32.114)
3977 BOOL WINAPI WSAIsBlocking(void)
3979 /* By default WinSock should set all its sockets to non-blocking mode
3980 * and poll in PeekMessage loop when processing "blocking" ones. This
3981 * function is supposed to tell if the program is in this loop. Our
3982 * blocking calls are truly blocking so we always return FALSE.
3984 * Note: It is allowed to call this function without prior WSAStartup().
3987 TRACE("\n");
3988 return FALSE;
3991 /***********************************************************************
3992 * WSACancelBlockingCall (WS2_32.113)
3994 INT WINAPI WSACancelBlockingCall(void)
3996 TRACE("\n");
3997 return 0;
4000 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
4002 FIXME("How was this called?\n");
4003 return x();
4007 /***********************************************************************
4008 * WSASetBlockingHook (WS2_32.109)
4010 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
4012 FARPROC prev = blocking_hook;
4013 blocking_hook = lpBlockFunc;
4014 TRACE("hook %p\n", lpBlockFunc);
4015 return prev;
4019 /***********************************************************************
4020 * WSAUnhookBlockingHook (WS2_32.110)
4022 INT WINAPI WSAUnhookBlockingHook(void)
4024 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
4025 return 0;
4029 /***********************************************************************
4030 * WSARecv (WS2_32.67)
4032 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4033 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
4034 LPWSAOVERLAPPED lpOverlapped,
4035 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
4037 if (!dwBufferCount)
4039 SetLastError( WSAEINVAL );
4040 return -1;
4043 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
4044 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
4048 /***********************************************************************
4049 * WSARecvFrom (WS2_32.69)
4051 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4052 DWORD *lpNumberOfBytesRecvd, DWORD *lpFlags, struct sockaddr *lpFrom,
4053 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
4054 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4057 /* Garena hooks WSARecvFrom(), so we need a wrapper */
4058 return WS2_recv_base( s, lpBuffers, dwBufferCount,
4059 lpNumberOfBytesRecvd, lpFlags,
4060 lpFrom, lpFromlen,
4061 lpOverlapped, lpCompletionRoutine, NULL );
4065 /***********************************************************************
4066 * WSAAccept (ws2_32.@)
4068 SOCKET WINAPI WSAAccept( SOCKET s, struct sockaddr *addr, int *addrlen,
4069 LPCONDITIONPROC callback, DWORD_PTR context )
4071 int ret = 0, size;
4072 WSABUF caller_id, caller_data, callee_id, callee_data;
4073 struct sockaddr src_addr, dst_addr;
4074 GROUP group;
4075 SOCKET cs;
4077 TRACE( "socket %#Ix, addr %p, addrlen %p, callback %p, context %#Ix\n",
4078 s, addr, addrlen, callback, context );
4080 cs = accept( s, addr, addrlen );
4081 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
4082 if (!callback) return cs;
4084 if (addr && addrlen)
4086 caller_id.buf = (char *)addr;
4087 caller_id.len = *addrlen;
4089 else
4091 size = sizeof(src_addr);
4092 getpeername( cs, &src_addr, &size );
4093 caller_id.buf = (char *)&src_addr;
4094 caller_id.len = size;
4096 caller_data.buf = NULL;
4097 caller_data.len = 0;
4099 size = sizeof(dst_addr);
4100 getsockname( cs, &dst_addr, &size );
4102 callee_id.buf = (char *)&dst_addr;
4103 callee_id.len = sizeof(dst_addr);
4105 ret = (*callback)( &caller_id, &caller_data, NULL, NULL,
4106 &callee_id, &callee_data, &group, context );
4107 TRACE( "callback returned %d.\n", ret );
4108 switch (ret)
4110 case CF_ACCEPT:
4111 return cs;
4113 case CF_DEFER:
4115 ULONG server_handle = cs;
4116 IO_STATUS_BLOCK io;
4117 NTSTATUS status;
4119 status = NtDeviceIoControlFile( (HANDLE)s, NULL, NULL, NULL, &io, IOCTL_AFD_WINE_DEFER,
4120 &server_handle, sizeof(server_handle), NULL, 0 );
4121 closesocket( cs );
4122 SetLastError( status ? RtlNtStatusToDosError( status ) : WSATRY_AGAIN );
4123 TRACE( "status %#lx.\n", status );
4124 return -1;
4127 case CF_REJECT:
4128 closesocket( cs );
4129 SetLastError( WSAECONNREFUSED );
4130 return SOCKET_ERROR;
4132 default:
4133 FIXME( "Unknown return type from Condition function\n" );
4134 SetLastError( WSAENOTSOCK );
4135 return SOCKET_ERROR;
4140 /***********************************************************************
4141 * WSADuplicateSocketA (WS2_32.32)
4143 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
4145 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
4148 /***********************************************************************
4149 * WSADuplicateSocketW (WS2_32.33)
4151 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
4153 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
4157 /***********************************************************************
4158 * WSAGetQOSByName (WS2_32.41)
4160 BOOL WINAPI WSAGetQOSByName( SOCKET s, WSABUF *name, QOS *qos )
4162 FIXME( "socket %#Ix, name %p, qos %p, stub!\n", s, name, qos );
4163 return FALSE;
4167 /***********************************************************************
4168 * WSARecvDisconnect (WS2_32.68)
4170 int WINAPI WSARecvDisconnect( SOCKET s, WSABUF *data )
4172 TRACE( "socket %#Ix, data %p\n", s, data );
4174 return shutdown( s, SD_RECEIVE );
4178 static BOOL protocol_matches_filter( const int *filter, unsigned int index )
4180 if (supported_protocols[index].dwProviderFlags & PFL_HIDDEN) return FALSE;
4181 if (!filter) return TRUE;
4182 while (*filter)
4184 if (supported_protocols[index].iProtocol == *filter++) return TRUE;
4186 return FALSE;
4189 /*****************************************************************************
4190 * WSAEnumProtocolsA [WS2_32.@]
4192 * see function WSAEnumProtocolsW
4194 int WINAPI WSAEnumProtocolsA( int *filter, WSAPROTOCOL_INFOA *protocols, DWORD *size )
4196 DWORD i, count = 0;
4198 TRACE("filter %p, protocols %p, size %p\n", filter, protocols, size);
4200 for (i = 0; i < ARRAY_SIZE(supported_protocols); ++i)
4202 if (protocol_matches_filter( filter, i ))
4203 ++count;
4206 if (!protocols || *size < count * sizeof(WSAPROTOCOL_INFOA))
4208 *size = count * sizeof(WSAPROTOCOL_INFOA);
4209 WSASetLastError( WSAENOBUFS );
4210 return SOCKET_ERROR;
4213 count = 0;
4214 for (i = 0; i < ARRAY_SIZE(supported_protocols); ++i)
4216 if (protocol_matches_filter( filter, i ))
4218 memcpy( &protocols[count], &supported_protocols[i], offsetof( WSAPROTOCOL_INFOW, szProtocol ) );
4219 WideCharToMultiByte( CP_ACP, 0, supported_protocols[i].szProtocol, -1,
4220 protocols[count].szProtocol, sizeof(protocols[count].szProtocol), NULL, NULL );
4221 ++count;
4224 return count;
4227 /*****************************************************************************
4228 * WSAEnumProtocolsW [WS2_32.@]
4230 * Retrieves information about specified set of active network protocols.
4232 * PARAMS
4233 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
4234 * retrieves information on all available protocols.
4235 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
4236 * structures.
4237 * len [I/O] Pointer to a variable specifying buffer size. On output
4238 * the variable holds the number of bytes needed when the
4239 * specified size is too small.
4241 * RETURNS
4242 * Success: number of WSAPROTOCOL_INFO structures in buffer.
4243 * Failure: SOCKET_ERROR
4245 * NOTES
4246 * NT4SP5 does not return SPX if protocols == NULL
4248 * BUGS
4249 * - NT4SP5 returns in addition these list of NETBIOS protocols
4250 * (address family 17), each entry two times one for socket type 2 and 5
4252 * iProtocol szProtocol
4253 * 0x80000000 \Device\NwlnkNb
4254 * 0xfffffffa \Device\NetBT_CBENT7
4255 * 0xfffffffb \Device\Nbf_CBENT7
4256 * 0xfffffffc \Device\NetBT_NdisWan5
4257 * 0xfffffffd \Device\NetBT_El9202
4258 * 0xfffffffe \Device\Nbf_El9202
4259 * 0xffffffff \Device\Nbf_NdisWan4
4261 * - there is no check that the operating system supports the returned
4262 * protocols
4264 int WINAPI WSAEnumProtocolsW( int *filter, WSAPROTOCOL_INFOW *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, i ))
4273 ++count;
4276 if (!protocols || *size < count * sizeof(WSAPROTOCOL_INFOW))
4278 *size = count * sizeof(WSAPROTOCOL_INFOW);
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, i ))
4287 protocols[count++] = supported_protocols[i];
4289 return count;