ws2_32: Set WSAEINVAL in InetPtonW if the address string is unparsable.
[wine.git] / dlls / ws2_32 / socket.c
blobd57fc9ecd2a06bf87ab04dfa6f92cb4bc5638a2e
1 /*
2 * based on Windows Sockets 1.1 specs
4 * Copyright (C) 1993,1994,1996,1997 John Brezak, Erik Bos, Alex Korobka.
5 * Copyright (C) 2001 Stefan Leichter
6 * Copyright (C) 2004 Hans Leidekker
7 * Copyright (C) 2005 Marcus Meissner
8 * Copyright (C) 2006-2008 Kai Blin
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 * NOTE: If you make any changes to fix a particular app, make sure
25 * they don't break something else like Netscape or telnet and ftp
26 * clients and servers (www.winsite.com got a lot of those).
29 #include "config.h"
30 #include "wine/port.h"
32 #include <stdarg.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <sys/types.h>
36 #include <limits.h>
37 #ifdef HAVE_SYS_IPC_H
38 # include <sys/ipc.h>
39 #endif
40 #ifdef HAVE_SYS_IOCTL_H
41 # include <sys/ioctl.h>
42 #endif
43 #ifdef HAVE_SYS_FILIO_H
44 # include <sys/filio.h>
45 #endif
46 #ifdef HAVE_SYS_SOCKIO_H
47 # include <sys/sockio.h>
48 #endif
50 #if defined(__EMX__)
51 # include <sys/so_ioctl.h>
52 #endif
54 #ifdef HAVE_SYS_PARAM_H
55 # include <sys/param.h>
56 #endif
58 #ifdef HAVE_SYS_MSG_H
59 # include <sys/msg.h>
60 #endif
61 #ifdef HAVE_SYS_WAIT_H
62 # include <sys/wait.h>
63 #endif
64 #ifdef HAVE_SYS_UIO_H
65 # include <sys/uio.h>
66 #endif
67 #ifdef HAVE_SYS_SOCKET_H
68 #include <sys/socket.h>
69 #endif
70 #ifdef HAVE_NETINET_IN_H
71 # include <netinet/in.h>
72 #endif
73 #ifdef HAVE_NETINET_TCP_H
74 # include <netinet/tcp.h>
75 #endif
76 #ifdef HAVE_ARPA_INET_H
77 # include <arpa/inet.h>
78 #endif
79 #include <ctype.h>
80 #include <fcntl.h>
81 #include <errno.h>
82 #ifdef HAVE_NETDB_H
83 #include <netdb.h>
84 #endif
85 #ifdef HAVE_UNISTD_H
86 # include <unistd.h>
87 #endif
88 #include <stdlib.h>
89 #ifdef HAVE_ARPA_NAMESER_H
90 # include <arpa/nameser.h>
91 #endif
92 #ifdef HAVE_RESOLV_H
93 # include <resolv.h>
94 #endif
95 #ifdef HAVE_NET_IF_H
96 # include <net/if.h>
97 #endif
98 #ifdef HAVE_LINUX_FILTER_H
99 # include <linux/filter.h>
100 #endif
102 #ifdef HAVE_NETIPX_IPX_H
103 # include <netipx/ipx.h>
104 #elif defined(HAVE_LINUX_IPX_H)
105 # ifdef HAVE_ASM_TYPES_H
106 # include <asm/types.h>
107 # endif
108 # ifdef HAVE_LINUX_TYPES_H
109 # include <linux/types.h>
110 # endif
111 # include <linux/ipx.h>
112 #endif
113 #if defined(SOL_IPX) || defined(SO_DEFAULT_HEADERS)
114 # define HAS_IPX
115 #endif
117 #ifdef HAVE_LINUX_IRDA_H
118 # ifdef HAVE_LINUX_TYPES_H
119 # include <linux/types.h>
120 # endif
121 # include <linux/irda.h>
122 # define HAS_IRDA
123 #endif
125 #ifdef HAVE_POLL_H
126 #include <poll.h>
127 #endif
128 #ifdef HAVE_SYS_POLL_H
129 # include <sys/poll.h>
130 #endif
131 #ifdef HAVE_SYS_TIME_H
132 # include <sys/time.h>
133 #endif
135 #define NONAMELESSUNION
136 #define NONAMELESSSTRUCT
137 #include "ntstatus.h"
138 #define WIN32_NO_STATUS
139 #include "windef.h"
140 #include "winbase.h"
141 #include "wingdi.h"
142 #include "winuser.h"
143 #include "winerror.h"
144 #include "winnls.h"
145 #include "winsock2.h"
146 #include "mswsock.h"
147 #include "ws2tcpip.h"
148 #include "ws2spi.h"
149 #include "wsipx.h"
150 #include "wsnwlink.h"
151 #include "wshisotp.h"
152 #include "mstcpip.h"
153 #include "af_irda.h"
154 #include "winnt.h"
155 #define USE_WC_PREFIX /* For CMSG_DATA */
156 #include "iphlpapi.h"
157 #include "ip2string.h"
158 #include "wine/server.h"
159 #include "wine/debug.h"
160 #include "wine/exception.h"
161 #include "wine/unicode.h"
162 #include "wine/heap.h"
164 #if defined(linux) && !defined(IP_UNICAST_IF)
165 #define IP_UNICAST_IF 50
166 #endif
168 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
169 # define sipx_network sipx_addr.x_net
170 # define sipx_node sipx_addr.x_host.c_host
171 #endif /* __FreeBSD__ */
173 #ifndef INADDR_NONE
174 #define INADDR_NONE ~0UL
175 #endif
177 #if !defined(TCP_KEEPIDLE) && defined(TCP_KEEPALIVE)
178 /* TCP_KEEPALIVE is the Mac OS name for TCP_KEEPIDLE */
179 #define TCP_KEEPIDLE TCP_KEEPALIVE
180 #endif
182 #define FILE_USE_FILE_POINTER_POSITION ((LONGLONG)-2)
184 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
185 WINE_DECLARE_DEBUG_CHANNEL(winediag);
187 /* names of the protocols */
188 static const WCHAR NameIpxW[] = {'I', 'P', 'X', '\0'};
189 static const WCHAR NameSpxW[] = {'S', 'P', 'X', '\0'};
190 static const WCHAR NameSpxIIW[] = {'S', 'P', 'X', ' ', 'I', 'I', '\0'};
191 static const WCHAR NameTcpW[] = {'T', 'C', 'P', '/', 'I', 'P', '\0'};
192 static const WCHAR NameUdpW[] = {'U', 'D', 'P', '/', 'I', 'P', '\0'};
194 /* Taken from Win2k */
195 static const GUID ProviderIdIP = { 0xe70f1aa0, 0xab8b, 0x11cf,
196 { 0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
197 static const GUID ProviderIdIPX = { 0x11058240, 0xbe47, 0x11cf,
198 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
199 static const GUID ProviderIdSPX = { 0x11058241, 0xbe47, 0x11cf,
200 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
202 static const INT valid_protocols[] =
204 WS_IPPROTO_TCP,
205 WS_IPPROTO_UDP,
206 WS_NSPROTO_IPX,
207 WS_NSPROTO_SPX,
208 WS_NSPROTO_SPXII,
212 #define IS_IPX_PROTO(X) ((X) >= WS_NSPROTO_IPX && (X) <= WS_NSPROTO_IPX + 255)
214 #if defined(IP_UNICAST_IF) && defined(SO_ATTACH_FILTER)
215 # define LINUX_BOUND_IF
216 struct interface_filter {
217 struct sock_filter iface_memaddr;
218 struct sock_filter iface_rule;
219 struct sock_filter ip_memaddr;
220 struct sock_filter ip_rule;
221 struct sock_filter return_keep;
222 struct sock_filter return_dump;
224 # define FILTER_JUMP_DUMP(here) (u_char)(offsetof(struct interface_filter, return_dump) \
225 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
226 /sizeof(struct sock_filter)
227 # define FILTER_JUMP_KEEP(here) (u_char)(offsetof(struct interface_filter, return_keep) \
228 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
229 /sizeof(struct sock_filter)
230 # define FILTER_JUMP_NEXT() (u_char)(0)
231 # define SKF_NET_DESTIP 16 /* offset in the network header to the destination IP */
232 static struct interface_filter generic_interface_filter = {
233 /* This filter rule allows incoming packets on the specified interface, which works for all
234 * remotely generated packets and for locally generated broadcast packets. */
235 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_AD_OFF+SKF_AD_IFINDEX),
236 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(iface_rule), FILTER_JUMP_NEXT()),
237 /* This rule allows locally generated packets targeted at the specific IP address of the chosen
238 * adapter (local packets not destined for the broadcast address do not have IFINDEX set) */
239 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_NET_OFF+SKF_NET_DESTIP),
240 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(ip_rule), FILTER_JUMP_DUMP(ip_rule)),
241 BPF_STMT(BPF_RET+BPF_K, (u_int)-1), /* keep packet */
242 BPF_STMT(BPF_RET+BPF_K, 0) /* dump packet */
244 #endif /* LINUX_BOUND_IF */
246 extern ssize_t CDECL __wine_locked_recvmsg( int fd, struct msghdr *hdr, int flags );
249 * The actual definition of WSASendTo, wrapped in a different function name
250 * so that internal calls from ws2_32 itself will not trigger programs like
251 * Garena, which hooks WSASendTo/WSARecvFrom calls.
253 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
254 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
255 const struct WS_sockaddr *to, int tolen,
256 LPWSAOVERLAPPED lpOverlapped,
257 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine );
260 * Internal fundamental receive function, essentially WSARecvFrom with an
261 * additional parameter to support message control headers.
263 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
264 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
265 struct WS_sockaddr *lpFrom,
266 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
267 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
268 LPWSABUF lpControlBuffer );
270 /* critical section to protect some non-reentrant net function */
271 static CRITICAL_SECTION csWSgetXXXbyYYY;
272 static CRITICAL_SECTION_DEBUG critsect_debug =
274 0, 0, &csWSgetXXXbyYYY,
275 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
276 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
278 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
280 union generic_unix_sockaddr
282 struct sockaddr addr;
283 char data[128]; /* should be big enough for all families */
286 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
288 if (!a) return "(nil)";
289 switch (a->sa_family)
291 case WS_AF_INET:
293 char buf[16];
294 const char *p;
295 struct WS_sockaddr_in *sin = (struct WS_sockaddr_in *)a;
297 p = WS_inet_ntop( WS_AF_INET, &sin->sin_addr, buf, sizeof(buf) );
298 if (!p)
299 p = "(unknown IPv4 address)";
301 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
302 p, ntohs(sin->sin_port));
304 case WS_AF_INET6:
306 char buf[46];
307 const char *p;
308 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
310 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
311 if (!p)
312 p = "(unknown IPv6 address)";
313 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
314 p, ntohs(sin->sin6_port));
316 case WS_AF_IPX:
318 int i;
319 char netnum[16], nodenum[16];
320 struct WS_sockaddr_ipx *sin = (struct WS_sockaddr_ipx *)a;
322 for (i = 0;i < 4; i++) sprintf(netnum + i * 2, "%02X", (unsigned char) sin->sa_netnum[i]);
323 for (i = 0;i < 6; i++) sprintf(nodenum + i * 2, "%02X", (unsigned char) sin->sa_nodenum[i]);
325 return wine_dbg_sprintf("{ family AF_IPX, address %s.%s, ipx socket %d }",
326 netnum, nodenum, sin->sa_socket);
328 case WS_AF_IRDA:
330 DWORD addr;
332 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
333 addr = ntohl( addr );
334 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
335 addr,
336 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
338 default:
339 return wine_dbg_sprintf("{ family %d }", a->sa_family);
343 static inline const char *debugstr_sockopt(int level, int optname)
345 const char *stropt = NULL, *strlevel = NULL;
347 #define DEBUG_SOCKLEVEL(x) case (x): strlevel = #x
348 #define DEBUG_SOCKOPT(x) case (x): stropt = #x; break
350 switch(level)
352 DEBUG_SOCKLEVEL(WS_SOL_SOCKET);
353 switch(optname)
355 DEBUG_SOCKOPT(WS_SO_ACCEPTCONN);
356 DEBUG_SOCKOPT(WS_SO_BROADCAST);
357 DEBUG_SOCKOPT(WS_SO_BSP_STATE);
358 DEBUG_SOCKOPT(WS_SO_CONDITIONAL_ACCEPT);
359 DEBUG_SOCKOPT(WS_SO_CONNECT_TIME);
360 DEBUG_SOCKOPT(WS_SO_DEBUG);
361 DEBUG_SOCKOPT(WS_SO_DONTLINGER);
362 DEBUG_SOCKOPT(WS_SO_DONTROUTE);
363 DEBUG_SOCKOPT(WS_SO_ERROR);
364 DEBUG_SOCKOPT(WS_SO_EXCLUSIVEADDRUSE);
365 DEBUG_SOCKOPT(WS_SO_GROUP_ID);
366 DEBUG_SOCKOPT(WS_SO_GROUP_PRIORITY);
367 DEBUG_SOCKOPT(WS_SO_KEEPALIVE);
368 DEBUG_SOCKOPT(WS_SO_LINGER);
369 DEBUG_SOCKOPT(WS_SO_MAX_MSG_SIZE);
370 DEBUG_SOCKOPT(WS_SO_OOBINLINE);
371 DEBUG_SOCKOPT(WS_SO_OPENTYPE);
372 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOA);
373 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOW);
374 DEBUG_SOCKOPT(WS_SO_RCVBUF);
375 DEBUG_SOCKOPT(WS_SO_RCVTIMEO);
376 DEBUG_SOCKOPT(WS_SO_REUSEADDR);
377 DEBUG_SOCKOPT(WS_SO_SNDBUF);
378 DEBUG_SOCKOPT(WS_SO_SNDTIMEO);
379 DEBUG_SOCKOPT(WS_SO_TYPE);
380 DEBUG_SOCKOPT(WS_SO_UPDATE_CONNECT_CONTEXT);
382 break;
384 DEBUG_SOCKLEVEL(WS_NSPROTO_IPX);
385 switch(optname)
387 DEBUG_SOCKOPT(WS_IPX_PTYPE);
388 DEBUG_SOCKOPT(WS_IPX_FILTERPTYPE);
389 DEBUG_SOCKOPT(WS_IPX_DSTYPE);
390 DEBUG_SOCKOPT(WS_IPX_RECVHDR);
391 DEBUG_SOCKOPT(WS_IPX_MAXSIZE);
392 DEBUG_SOCKOPT(WS_IPX_ADDRESS);
393 DEBUG_SOCKOPT(WS_IPX_MAX_ADAPTER_NUM);
395 break;
397 DEBUG_SOCKLEVEL(WS_SOL_IRLMP);
398 switch(optname)
400 DEBUG_SOCKOPT(WS_IRLMP_ENUMDEVICES);
402 break;
404 DEBUG_SOCKLEVEL(WS_IPPROTO_TCP);
405 switch(optname)
407 DEBUG_SOCKOPT(WS_TCP_BSDURGENT);
408 DEBUG_SOCKOPT(WS_TCP_EXPEDITED_1122);
409 DEBUG_SOCKOPT(WS_TCP_NODELAY);
411 break;
413 DEBUG_SOCKLEVEL(WS_IPPROTO_IP);
414 switch(optname)
416 DEBUG_SOCKOPT(WS_IP_ADD_MEMBERSHIP);
417 DEBUG_SOCKOPT(WS_IP_DONTFRAGMENT);
418 DEBUG_SOCKOPT(WS_IP_DROP_MEMBERSHIP);
419 DEBUG_SOCKOPT(WS_IP_HDRINCL);
420 DEBUG_SOCKOPT(WS_IP_MULTICAST_IF);
421 DEBUG_SOCKOPT(WS_IP_MULTICAST_LOOP);
422 DEBUG_SOCKOPT(WS_IP_MULTICAST_TTL);
423 DEBUG_SOCKOPT(WS_IP_OPTIONS);
424 DEBUG_SOCKOPT(WS_IP_PKTINFO);
425 DEBUG_SOCKOPT(WS_IP_RECEIVE_BROADCAST);
426 DEBUG_SOCKOPT(WS_IP_TOS);
427 DEBUG_SOCKOPT(WS_IP_TTL);
428 DEBUG_SOCKOPT(WS_IP_UNICAST_IF);
430 break;
432 DEBUG_SOCKLEVEL(WS_IPPROTO_IPV6);
433 switch(optname)
435 DEBUG_SOCKOPT(WS_IPV6_ADD_MEMBERSHIP);
436 DEBUG_SOCKOPT(WS_IPV6_DROP_MEMBERSHIP);
437 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_IF);
438 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_HOPS);
439 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_LOOP);
440 DEBUG_SOCKOPT(WS_IPV6_UNICAST_HOPS);
441 DEBUG_SOCKOPT(WS_IPV6_V6ONLY);
442 DEBUG_SOCKOPT(WS_IPV6_UNICAST_IF);
443 DEBUG_SOCKOPT(WS_IPV6_DONTFRAG);
445 break;
447 #undef DEBUG_SOCKLEVEL
448 #undef DEBUG_SOCKOPT
450 if (!strlevel)
451 strlevel = wine_dbg_sprintf("WS_0x%x", level);
452 if (!stropt)
453 stropt = wine_dbg_sprintf("WS_0x%x", optname);
455 return wine_dbg_sprintf("level %s, name %s", strlevel + 3, stropt + 3);
458 static inline const char *debugstr_optval(const char *optval, int optlenval)
460 if (optval && !IS_INTRESOURCE(optval) && optlenval >= 1 && optlenval <= sizeof(DWORD))
462 DWORD value = 0;
463 memcpy(&value, optval, optlenval);
464 return wine_dbg_sprintf("%p (%u)", optval, value);
466 return wine_dbg_sprintf("%p", optval);
469 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
470 #define SOCKET2HANDLE(s) ((HANDLE)(s))
471 #define HANDLE2SOCKET(h) ((SOCKET)(h))
473 /****************************************************************
474 * Async IO declarations
475 ****************************************************************/
477 typedef NTSTATUS async_callback_t( void *user, IO_STATUS_BLOCK *io, NTSTATUS status );
479 struct ws2_async_io
481 async_callback_t *callback; /* must be the first field */
482 struct ws2_async_io *next;
485 struct ws2_async_shutdown
487 struct ws2_async_io io;
488 HANDLE hSocket;
489 IO_STATUS_BLOCK iosb;
490 int type;
493 struct ws2_async
495 struct ws2_async_io io;
496 HANDLE hSocket;
497 LPWSAOVERLAPPED user_overlapped;
498 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
499 IO_STATUS_BLOCK local_iosb;
500 struct WS_sockaddr *addr;
501 union
503 int val; /* for send operations */
504 int *ptr; /* for recv operations */
505 } addrlen;
506 DWORD flags;
507 DWORD *lpFlags;
508 WSABUF *control;
509 unsigned int n_iovecs;
510 unsigned int first_iovec;
511 struct iovec iovec[1];
514 struct ws2_accept_async
516 struct ws2_async_io io;
517 HANDLE listen_socket;
518 HANDLE accept_socket;
519 LPOVERLAPPED user_overlapped;
520 ULONG_PTR cvalue;
521 PVOID buf; /* buffer to write data to */
522 int data_len;
523 int local_len;
524 int remote_len;
525 struct ws2_async *read;
528 struct ws2_transmitfile_async
530 struct ws2_async_io io;
531 char *buffer;
532 HANDLE file;
533 DWORD file_read;
534 DWORD file_bytes;
535 DWORD bytes_per_send;
536 TRANSMIT_FILE_BUFFERS buffers;
537 DWORD flags;
538 LARGE_INTEGER offset;
539 struct ws2_async write;
542 static struct ws2_async_io *async_io_freelist;
544 static void release_async_io( struct ws2_async_io *io )
546 for (;;)
548 struct ws2_async_io *next = async_io_freelist;
549 io->next = next;
550 if (InterlockedCompareExchangePointer( (void **)&async_io_freelist, io, next ) == next) return;
554 static struct ws2_async_io *alloc_async_io( DWORD size, async_callback_t callback )
556 /* first free remaining previous fileinfos */
558 struct ws2_async_io *io = InterlockedExchangePointer( (void **)&async_io_freelist, NULL );
560 while (io)
562 struct ws2_async_io *next = io->next;
563 HeapFree( GetProcessHeap(), 0, io );
564 io = next;
567 io = HeapAlloc( GetProcessHeap(), 0, size );
568 if (io) io->callback = callback;
569 return io;
572 static NTSTATUS register_async( int type, HANDLE handle, struct ws2_async_io *async, HANDLE event,
573 PIO_APC_ROUTINE apc, void *apc_context, IO_STATUS_BLOCK *io )
575 NTSTATUS status;
577 SERVER_START_REQ( register_async )
579 req->type = type;
580 req->async.handle = wine_server_obj_handle( handle );
581 req->async.user = wine_server_client_ptr( async );
582 req->async.iosb = wine_server_client_ptr( io );
583 req->async.event = wine_server_obj_handle( event );
584 req->async.apc = wine_server_client_ptr( apc );
585 req->async.apc_context = wine_server_client_ptr( apc_context );
586 status = wine_server_call( req );
588 SERVER_END_REQ;
590 return status;
593 /****************************************************************/
595 /* ----------------------------------- internal data */
597 /* ws_... struct conversion flags */
599 typedef struct /* WSAAsyncSelect() control struct */
601 HANDLE service, event, sock;
602 HWND hWnd;
603 UINT uMsg;
604 LONG lEvent;
605 } ws_select_info;
607 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
608 #define WS_MAX_UDP_DATAGRAM 1024
609 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
611 /* hostent's, servent's and protent's are stored in one buffer per thread,
612 * as documented on MSDN for the functions that return any of the buffers */
613 struct per_thread_data
615 int opentype;
616 struct WS_hostent *he_buffer;
617 struct WS_servent *se_buffer;
618 struct WS_protoent *pe_buffer;
619 struct pollfd *fd_cache;
620 unsigned int fd_count;
621 int he_len;
622 int se_len;
623 int pe_len;
624 char ntoa_buffer[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
627 /* internal: routing description information */
628 struct route {
629 struct in_addr addr;
630 IF_INDEX interface;
631 DWORD metric, default_route;
634 static INT num_startup; /* reference counter */
635 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
637 /* function prototypes */
638 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length);
639 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
640 static struct WS_protoent *WS_create_pe( const char *name, char **aliases, int prot );
641 static struct WS_servent *WS_dup_se(const struct servent* p_se);
642 static int ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size);
644 int WSAIOCTL_GetInterfaceCount(void);
645 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
647 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG Information, BOOL force );
649 #define MAP_OPTION(opt) { WS_##opt, opt }
651 static const int ws_flags_map[][2] =
653 MAP_OPTION( MSG_OOB ),
654 MAP_OPTION( MSG_PEEK ),
655 MAP_OPTION( MSG_DONTROUTE ),
656 MAP_OPTION( MSG_WAITALL ),
657 { WS_MSG_PARTIAL, 0 },
660 static const int ws_sock_map[][2] =
662 MAP_OPTION( SO_DEBUG ),
663 MAP_OPTION( SO_ACCEPTCONN ),
664 MAP_OPTION( SO_REUSEADDR ),
665 MAP_OPTION( SO_KEEPALIVE ),
666 MAP_OPTION( SO_DONTROUTE ),
667 MAP_OPTION( SO_BROADCAST ),
668 MAP_OPTION( SO_LINGER ),
669 MAP_OPTION( SO_OOBINLINE ),
670 MAP_OPTION( SO_SNDBUF ),
671 MAP_OPTION( SO_RCVBUF ),
672 MAP_OPTION( SO_ERROR ),
673 MAP_OPTION( SO_TYPE ),
674 #ifdef SO_RCVTIMEO
675 MAP_OPTION( SO_RCVTIMEO ),
676 #endif
677 #ifdef SO_SNDTIMEO
678 MAP_OPTION( SO_SNDTIMEO ),
679 #endif
682 static const int ws_tcp_map[][2] =
684 #ifdef TCP_NODELAY
685 MAP_OPTION( TCP_NODELAY ),
686 #endif
689 static const int ws_ip_map[][2] =
691 MAP_OPTION( IP_MULTICAST_IF ),
692 MAP_OPTION( IP_MULTICAST_TTL ),
693 MAP_OPTION( IP_MULTICAST_LOOP ),
694 MAP_OPTION( IP_ADD_MEMBERSHIP ),
695 MAP_OPTION( IP_DROP_MEMBERSHIP ),
696 MAP_OPTION( IP_ADD_SOURCE_MEMBERSHIP ),
697 MAP_OPTION( IP_DROP_SOURCE_MEMBERSHIP ),
698 MAP_OPTION( IP_BLOCK_SOURCE ),
699 MAP_OPTION( IP_UNBLOCK_SOURCE ),
700 MAP_OPTION( IP_OPTIONS ),
701 #ifdef IP_HDRINCL
702 MAP_OPTION( IP_HDRINCL ),
703 #endif
704 MAP_OPTION( IP_TOS ),
705 MAP_OPTION( IP_TTL ),
706 #if defined(IP_PKTINFO)
707 MAP_OPTION( IP_PKTINFO ),
708 #elif defined(IP_RECVDSTADDR)
709 { WS_IP_PKTINFO, IP_RECVDSTADDR },
710 #endif
711 #ifdef IP_UNICAST_IF
712 MAP_OPTION( IP_UNICAST_IF ),
713 #endif
716 static const int ws_ipv6_map[][2] =
718 #ifdef IPV6_ADD_MEMBERSHIP
719 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
720 #endif
721 #ifdef IPV6_DROP_MEMBERSHIP
722 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
723 #endif
724 MAP_OPTION( IPV6_MULTICAST_IF ),
725 MAP_OPTION( IPV6_MULTICAST_HOPS ),
726 MAP_OPTION( IPV6_MULTICAST_LOOP ),
727 MAP_OPTION( IPV6_UNICAST_HOPS ),
728 MAP_OPTION( IPV6_V6ONLY ),
729 #ifdef IPV6_UNICAST_IF
730 MAP_OPTION( IPV6_UNICAST_IF ),
731 #endif
734 static const int ws_af_map[][2] =
736 MAP_OPTION( AF_UNSPEC ),
737 MAP_OPTION( AF_INET ),
738 MAP_OPTION( AF_INET6 ),
739 #ifdef HAS_IPX
740 MAP_OPTION( AF_IPX ),
741 #endif
742 #ifdef AF_IRDA
743 MAP_OPTION( AF_IRDA ),
744 #endif
745 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
748 static const int ws_socktype_map[][2] =
750 MAP_OPTION( SOCK_DGRAM ),
751 MAP_OPTION( SOCK_STREAM ),
752 MAP_OPTION( SOCK_RAW ),
753 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
756 static const int ws_proto_map[][2] =
758 MAP_OPTION( IPPROTO_IP ),
759 MAP_OPTION( IPPROTO_TCP ),
760 MAP_OPTION( IPPROTO_UDP ),
761 MAP_OPTION( IPPROTO_IPV6 ),
762 MAP_OPTION( IPPROTO_ICMP ),
763 MAP_OPTION( IPPROTO_IGMP ),
764 MAP_OPTION( IPPROTO_RAW ),
765 MAP_OPTION( IPPROTO_IPIP ),
766 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
769 static const int ws_aiflag_map[][2] =
771 MAP_OPTION( AI_PASSIVE ),
772 MAP_OPTION( AI_CANONNAME ),
773 MAP_OPTION( AI_NUMERICHOST ),
774 #ifdef AI_NUMERICSERV
775 MAP_OPTION( AI_NUMERICSERV ),
776 #endif
777 #ifdef AI_V4MAPPED
778 MAP_OPTION( AI_V4MAPPED ),
779 #endif
780 MAP_OPTION( AI_ADDRCONFIG ),
783 static const int ws_niflag_map[][2] =
785 MAP_OPTION( NI_NOFQDN ),
786 MAP_OPTION( NI_NUMERICHOST ),
787 MAP_OPTION( NI_NAMEREQD ),
788 MAP_OPTION( NI_NUMERICSERV ),
789 MAP_OPTION( NI_DGRAM ),
792 static const int ws_eai_map[][2] =
794 MAP_OPTION( EAI_AGAIN ),
795 MAP_OPTION( EAI_BADFLAGS ),
796 MAP_OPTION( EAI_FAIL ),
797 MAP_OPTION( EAI_FAMILY ),
798 MAP_OPTION( EAI_MEMORY ),
799 /* Note: EAI_NODATA is deprecated, but still
800 * used by Windows and Linux... We map the newer
801 * EAI_NONAME to EAI_NODATA for now until Windows
802 * changes too.
804 #ifdef EAI_NODATA
805 MAP_OPTION( EAI_NODATA ),
806 #endif
807 #ifdef EAI_NONAME
808 { WS_EAI_NODATA, EAI_NONAME },
809 #endif
811 MAP_OPTION( EAI_SERVICE ),
812 MAP_OPTION( EAI_SOCKTYPE ),
813 { 0, 0 }
816 static const int ws_poll_map[][2] =
818 MAP_OPTION( POLLERR ),
819 MAP_OPTION( POLLHUP ),
820 MAP_OPTION( POLLNVAL ),
821 MAP_OPTION( POLLWRNORM ),
822 MAP_OPTION( POLLWRBAND ),
823 MAP_OPTION( POLLRDNORM ),
824 { WS_POLLRDBAND, POLLPRI }
827 static const char magic_loopback_addr[] = {127, 12, 34, 56};
829 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
830 #if defined(IP_PKTINFO) || defined(IP_RECVDSTADDR)
831 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
833 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
834 char *ptr = (char *) current + sizeof(WSACMSGHDR);
836 /* Make sure there is at least enough room for this entry */
837 if (msgsize > *maxsize)
838 return NULL;
839 *maxsize -= msgsize;
840 /* Fill in the entry */
841 current->cmsg_len = sizeof(WSACMSGHDR) + len;
842 current->cmsg_level = level;
843 current->cmsg_type = type;
844 memcpy(ptr, data, len);
845 /* Return the pointer to where next entry should go */
846 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
848 #endif /* defined(IP_PKTINFO) || defined(IP_RECVDSTADDR) */
850 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
852 #if defined(IP_PKTINFO) || defined(IP_RECVDSTADDR)
853 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
854 ULONG ctlsize = control->len;
855 struct cmsghdr *cmsg_unix;
857 ptr = cmsg_win;
858 /* Loop over all the headers, converting as appropriate */
859 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
861 switch(cmsg_unix->cmsg_level)
863 case IPPROTO_IP:
864 switch(cmsg_unix->cmsg_type)
866 #if defined(IP_PKTINFO)
867 case IP_PKTINFO:
869 /* Convert the Unix IP_PKTINFO structure to the Windows version */
870 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
871 struct WS_in_pktinfo data_win;
873 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
874 data_win.ipi_ifindex = data_unix->ipi_ifindex;
875 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
876 (void*)&data_win, sizeof(data_win));
877 if (!ptr) goto error;
878 } break;
879 #elif defined(IP_RECVDSTADDR)
880 case IP_RECVDSTADDR:
882 struct in_addr *addr_unix = (struct in_addr *) CMSG_DATA(cmsg_unix);
883 struct WS_in_pktinfo data_win;
885 memcpy(&data_win.ipi_addr, &addr_unix->s_addr, 4); /* 4 bytes = 32 address bits */
886 data_win.ipi_ifindex = 0; /* FIXME */
887 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
888 (void*)&data_win, sizeof(data_win));
889 if (!ptr) goto error;
890 } break;
891 #endif /* IP_PKTINFO */
892 default:
893 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
894 break;
896 break;
897 default:
898 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
899 break;
903 /* Set the length of the returned control headers */
904 control->len = (char*)ptr - (char*)cmsg_win;
905 return 1;
906 error:
907 control->len = 0;
908 return 0;
909 #else /* defined(IP_PKTINFO) || defined(IP_RECVDSTADDR) */
910 control->len = 0;
911 return 1;
912 #endif /* defined(IP_PKTINFO) || defined(IP_RECVDSTADDR) */
914 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
916 /* ----------------------------------- error handling */
918 static NTSTATUS sock_get_ntstatus( int err )
920 switch ( err )
922 case EBADF: return STATUS_INVALID_HANDLE;
923 case EBUSY: return STATUS_DEVICE_BUSY;
924 case EPERM:
925 case EACCES: return STATUS_ACCESS_DENIED;
926 case EFAULT: return STATUS_NO_MEMORY;
927 case EINVAL: return STATUS_INVALID_PARAMETER;
928 case ENFILE:
929 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
930 case EWOULDBLOCK: return STATUS_CANT_WAIT;
931 case EINPROGRESS: return STATUS_PENDING;
932 case EALREADY: return STATUS_NETWORK_BUSY;
933 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
934 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
935 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
936 case EPROTONOSUPPORT:
937 case ESOCKTNOSUPPORT:
938 case EPFNOSUPPORT:
939 case EAFNOSUPPORT:
940 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
941 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
942 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
943 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
944 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
945 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
946 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
947 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
948 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
949 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
950 case ENETDOWN: return STATUS_NETWORK_BUSY;
951 case EPIPE:
952 case ECONNRESET: return STATUS_CONNECTION_RESET;
953 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
955 case 0: return STATUS_SUCCESS;
956 default:
957 WARN("Unknown errno %d!\n", err);
958 return STATUS_UNSUCCESSFUL;
962 static UINT sock_get_error( int err )
964 switch(err)
966 case EINTR: return WSAEINTR;
967 case EPERM:
968 case EACCES: return WSAEACCES;
969 case EFAULT: return WSAEFAULT;
970 case EINVAL: return WSAEINVAL;
971 case EMFILE: return WSAEMFILE;
972 case EWOULDBLOCK: return WSAEWOULDBLOCK;
973 case EINPROGRESS: return WSAEINPROGRESS;
974 case EALREADY: return WSAEALREADY;
975 case EBADF:
976 case ENOTSOCK: return WSAENOTSOCK;
977 case EDESTADDRREQ: return WSAEDESTADDRREQ;
978 case EMSGSIZE: return WSAEMSGSIZE;
979 case EPROTOTYPE: return WSAEPROTOTYPE;
980 case ENOPROTOOPT: return WSAENOPROTOOPT;
981 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
982 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
983 case EOPNOTSUPP: return WSAEOPNOTSUPP;
984 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
985 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
986 case EADDRINUSE: return WSAEADDRINUSE;
987 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
988 case ENETDOWN: return WSAENETDOWN;
989 case ENETUNREACH: return WSAENETUNREACH;
990 case ENETRESET: return WSAENETRESET;
991 case ECONNABORTED: return WSAECONNABORTED;
992 case EPIPE:
993 case ECONNRESET: return WSAECONNRESET;
994 case ENOBUFS: return WSAENOBUFS;
995 case EISCONN: return WSAEISCONN;
996 case ENOTCONN: return WSAENOTCONN;
997 case ESHUTDOWN: return WSAESHUTDOWN;
998 case ETOOMANYREFS: return WSAETOOMANYREFS;
999 case ETIMEDOUT: return WSAETIMEDOUT;
1000 case ECONNREFUSED: return WSAECONNREFUSED;
1001 case ELOOP: return WSAELOOP;
1002 case ENAMETOOLONG: return WSAENAMETOOLONG;
1003 case EHOSTDOWN: return WSAEHOSTDOWN;
1004 case EHOSTUNREACH: return WSAEHOSTUNREACH;
1005 case ENOTEMPTY: return WSAENOTEMPTY;
1006 #ifdef EPROCLIM
1007 case EPROCLIM: return WSAEPROCLIM;
1008 #endif
1009 #ifdef EUSERS
1010 case EUSERS: return WSAEUSERS;
1011 #endif
1012 #ifdef EDQUOT
1013 case EDQUOT: return WSAEDQUOT;
1014 #endif
1015 #ifdef ESTALE
1016 case ESTALE: return WSAESTALE;
1017 #endif
1018 #ifdef EREMOTE
1019 case EREMOTE: return WSAEREMOTE;
1020 #endif
1022 /* just in case we ever get here and there are no problems */
1023 case 0: return 0;
1024 default:
1025 WARN("Unknown errno %d!\n", err);
1026 return WSAEOPNOTSUPP;
1030 static UINT wsaErrno(void)
1032 int loc_errno = errno;
1033 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
1035 return sock_get_error( loc_errno );
1038 /* most ws2 overlapped functions return an ntstatus-based error code */
1039 static NTSTATUS wsaErrStatus(void)
1041 int loc_errno = errno;
1042 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
1044 return sock_get_ntstatus(loc_errno);
1047 static UINT wsaHerrno(int loc_errno)
1049 WARN("h_errno %d.\n", loc_errno);
1051 switch(loc_errno)
1053 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
1054 case TRY_AGAIN: return WSATRY_AGAIN;
1055 case NO_RECOVERY: return WSANO_RECOVERY;
1056 case NO_DATA: return WSANO_DATA;
1057 case ENOBUFS: return WSAENOBUFS;
1059 case 0: return 0;
1060 default:
1061 WARN("Unknown h_errno %d!\n", loc_errno);
1062 return WSAEOPNOTSUPP;
1066 static NTSTATUS sock_error_to_ntstatus( DWORD err )
1068 switch (err)
1070 case 0: return STATUS_SUCCESS;
1071 case WSAEBADF: return STATUS_INVALID_HANDLE;
1072 case WSAEACCES: return STATUS_ACCESS_DENIED;
1073 case WSAEFAULT: return STATUS_NO_MEMORY;
1074 case WSAEINVAL: return STATUS_INVALID_PARAMETER;
1075 case WSAEMFILE: return STATUS_TOO_MANY_OPENED_FILES;
1076 case WSAEWOULDBLOCK: return STATUS_CANT_WAIT;
1077 case WSAEINPROGRESS: return STATUS_PENDING;
1078 case WSAEALREADY: return STATUS_NETWORK_BUSY;
1079 case WSAENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
1080 case WSAEDESTADDRREQ: return STATUS_INVALID_PARAMETER;
1081 case WSAEMSGSIZE: return STATUS_BUFFER_OVERFLOW;
1082 case WSAEPROTONOSUPPORT:
1083 case WSAESOCKTNOSUPPORT:
1084 case WSAEPFNOSUPPORT:
1085 case WSAEAFNOSUPPORT:
1086 case WSAEPROTOTYPE: return STATUS_NOT_SUPPORTED;
1087 case WSAENOPROTOOPT: return STATUS_INVALID_PARAMETER;
1088 case WSAEOPNOTSUPP: return STATUS_NOT_SUPPORTED;
1089 case WSAEADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
1090 case WSAEADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
1091 case WSAECONNREFUSED: return STATUS_CONNECTION_REFUSED;
1092 case WSAESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
1093 case WSAENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
1094 case WSAETIMEDOUT: return STATUS_IO_TIMEOUT;
1095 case WSAENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
1096 case WSAENETDOWN: return STATUS_NETWORK_BUSY;
1097 case WSAECONNRESET: return STATUS_CONNECTION_RESET;
1098 case WSAECONNABORTED: return STATUS_CONNECTION_ABORTED;
1099 default:
1100 FIXME("unmapped error %u\n", err);
1101 return STATUS_UNSUCCESSFUL;
1105 static DWORD NtStatusToWSAError( DWORD status )
1107 switch ( status )
1109 case STATUS_SUCCESS: return 0;
1110 case STATUS_PENDING: return WSA_IO_PENDING;
1111 case STATUS_OBJECT_TYPE_MISMATCH: return WSAENOTSOCK;
1112 case STATUS_INVALID_HANDLE: return WSAEBADF;
1113 case STATUS_INVALID_PARAMETER: return WSAEINVAL;
1114 case STATUS_PIPE_DISCONNECTED: return WSAESHUTDOWN;
1115 case STATUS_NETWORK_BUSY: return WSAEALREADY;
1116 case STATUS_NETWORK_UNREACHABLE: return WSAENETUNREACH;
1117 case STATUS_CONNECTION_REFUSED: return WSAECONNREFUSED;
1118 case STATUS_CONNECTION_DISCONNECTED: return WSAENOTCONN;
1119 case STATUS_CONNECTION_RESET: return WSAECONNRESET;
1120 case STATUS_CONNECTION_ABORTED: return WSAECONNABORTED;
1121 case STATUS_CANCELLED: return WSA_OPERATION_ABORTED;
1122 case STATUS_ADDRESS_ALREADY_ASSOCIATED: return WSAEADDRINUSE;
1123 case STATUS_IO_TIMEOUT:
1124 case STATUS_TIMEOUT: return WSAETIMEDOUT;
1125 case STATUS_NO_MEMORY: return WSAEFAULT;
1126 case STATUS_ACCESS_DENIED: return WSAEACCES;
1127 case STATUS_TOO_MANY_OPENED_FILES: return WSAEMFILE;
1128 case STATUS_CANT_WAIT: return WSAEWOULDBLOCK;
1129 case STATUS_BUFFER_OVERFLOW: return WSAEMSGSIZE;
1130 case STATUS_NOT_SUPPORTED: return WSAEOPNOTSUPP;
1131 case STATUS_HOST_UNREACHABLE: return WSAEHOSTUNREACH;
1132 default: return RtlNtStatusToDosError( status );
1136 /* set last error code from NT status without mapping WSA errors */
1137 static inline unsigned int set_error( unsigned int err )
1139 if (err)
1141 err = NtStatusToWSAError( err );
1142 SetLastError( err );
1144 return err;
1147 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
1149 int fd;
1150 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
1151 return -1;
1152 return fd;
1155 static inline void release_sock_fd( SOCKET s, int fd )
1157 wine_server_release_fd( SOCKET2HANDLE(s), fd );
1160 static void _enable_event( HANDLE s, unsigned int event,
1161 unsigned int sstate, unsigned int cstate )
1163 SERVER_START_REQ( enable_socket_event )
1165 req->handle = wine_server_obj_handle( s );
1166 req->mask = event;
1167 req->sstate = sstate;
1168 req->cstate = cstate;
1169 wine_server_call( req );
1171 SERVER_END_REQ;
1174 static DWORD sock_is_blocking(SOCKET s, BOOL *ret)
1176 DWORD err;
1177 SERVER_START_REQ( get_socket_event )
1179 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1180 req->service = FALSE;
1181 req->c_event = 0;
1182 err = NtStatusToWSAError( wine_server_call( req ));
1183 *ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
1185 SERVER_END_REQ;
1186 return err;
1189 static unsigned int _get_sock_mask(SOCKET s)
1191 unsigned int ret;
1192 SERVER_START_REQ( get_socket_event )
1194 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1195 req->service = FALSE;
1196 req->c_event = 0;
1197 wine_server_call( req );
1198 ret = reply->mask;
1200 SERVER_END_REQ;
1201 return ret;
1204 static void _sync_sock_state(SOCKET s)
1206 BOOL dummy;
1207 /* do a dummy wineserver request in order to let
1208 the wineserver run through its select loop once */
1209 sock_is_blocking(s, &dummy);
1212 static void _get_sock_errors(SOCKET s, int *events)
1214 SERVER_START_REQ( get_socket_event )
1216 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1217 req->service = FALSE;
1218 req->c_event = 0;
1219 wine_server_set_reply( req, events, sizeof(int) * FD_MAX_EVENTS );
1220 wine_server_call( req );
1222 SERVER_END_REQ;
1225 static int get_sock_error(SOCKET s, unsigned int bit)
1227 int events[FD_MAX_EVENTS];
1228 _get_sock_errors(s, events);
1229 return events[bit];
1232 static int _get_fd_type(int fd)
1234 int sock_type = -1;
1235 socklen_t optlen = sizeof(sock_type);
1236 getsockopt(fd, SOL_SOCKET, SO_TYPE, (char*) &sock_type, &optlen);
1237 return sock_type;
1240 static BOOL set_dont_fragment(SOCKET s, int level, BOOL value)
1242 int fd, optname;
1244 if (level == IPPROTO_IP)
1246 #ifdef IP_DONTFRAG
1247 optname = IP_DONTFRAG;
1248 #elif defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO) && defined(IP_PMTUDISC_DONT)
1249 optname = IP_MTU_DISCOVER;
1250 value = value ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
1251 #else
1252 static int once;
1253 if (!once++)
1254 FIXME("IP_DONTFRAGMENT for IPv4 not supported in this platform\n");
1255 return TRUE; /* fake success */
1256 #endif
1258 else
1260 #ifdef IPV6_DONTFRAG
1261 optname = IPV6_DONTFRAG;
1262 #elif defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO) && defined(IPV6_PMTUDISC_DONT)
1263 optname = IPV6_MTU_DISCOVER;
1264 value = value ? IPV6_PMTUDISC_DO : IPV6_PMTUDISC_DONT;
1265 #else
1266 static int once;
1267 if (!once++)
1268 FIXME("IP_DONTFRAGMENT for IPv6 not supported in this platform\n");
1269 return TRUE; /* fake success */
1270 #endif
1273 fd = get_sock_fd(s, 0, NULL);
1274 if (fd == -1) return FALSE;
1276 if (!setsockopt(fd, level, optname, &value, sizeof(value)))
1277 value = TRUE;
1278 else
1280 WSASetLastError(wsaErrno());
1281 value = FALSE;
1284 release_sock_fd(s, fd);
1285 return value;
1288 static BOOL get_dont_fragment(SOCKET s, int level, BOOL *out)
1290 int fd, optname, value, not_expected;
1291 socklen_t optlen = sizeof(value);
1293 if (level == IPPROTO_IP)
1295 #ifdef IP_DONTFRAG
1296 optname = IP_DONTFRAG;
1297 not_expected = 0;
1298 #elif defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
1299 optname = IP_MTU_DISCOVER;
1300 not_expected = IP_PMTUDISC_DONT;
1301 #else
1302 static int once;
1303 if (!once++)
1304 FIXME("IP_DONTFRAGMENT for IPv4 not supported in this platform\n");
1305 return TRUE; /* fake success */
1306 #endif
1308 else
1310 #ifdef IPV6_DONTFRAG
1311 optname = IPV6_DONTFRAG;
1312 not_expected = 0;
1313 #elif defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DONT)
1314 optname = IPV6_MTU_DISCOVER;
1315 not_expected = IPV6_PMTUDISC_DONT;
1316 #else
1317 static int once;
1318 if (!once++)
1319 FIXME("IP_DONTFRAGMENT for IPv6 not supported in this platform\n");
1320 return TRUE; /* fake success */
1321 #endif
1324 fd = get_sock_fd(s, 0, NULL);
1325 if (fd == -1) return FALSE;
1327 if (!getsockopt(fd, level, optname, &value, &optlen))
1329 *out = value != not_expected;
1330 value = TRUE;
1332 else
1334 WSASetLastError(wsaErrno());
1335 value = FALSE;
1338 release_sock_fd(s, fd);
1339 return value;
1342 static struct per_thread_data *get_per_thread_data(void)
1344 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
1345 /* lazy initialization */
1346 if (!ptb)
1348 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
1349 NtCurrentTeb()->WinSockData = ptb;
1351 return ptb;
1354 static void free_per_thread_data(void)
1356 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
1358 if (!ptb) return;
1360 /* delete scratch buffers */
1361 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1362 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1363 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1364 HeapFree( GetProcessHeap(), 0, ptb->fd_cache );
1366 HeapFree( GetProcessHeap(), 0, ptb );
1367 NtCurrentTeb()->WinSockData = NULL;
1370 /***********************************************************************
1371 * DllMain (WS2_32.init)
1373 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
1375 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
1376 switch (fdwReason) {
1377 case DLL_PROCESS_ATTACH:
1378 break;
1379 case DLL_PROCESS_DETACH:
1380 if (fImpLoad) break;
1381 free_per_thread_data();
1382 DeleteCriticalSection(&csWSgetXXXbyYYY);
1383 break;
1384 case DLL_THREAD_DETACH:
1385 free_per_thread_data();
1386 break;
1388 return TRUE;
1391 /***********************************************************************
1392 * convert_flags()
1394 * Converts send/recv flags from Windows format.
1395 * Return the converted flag bits, unsupported flags remain unchanged.
1397 static int convert_flags(int flags)
1399 int i, out;
1400 if (!flags) return 0;
1402 for (out = i = 0; flags && i < ARRAY_SIZE(ws_flags_map); i++)
1404 if (ws_flags_map[i][0] & flags)
1406 out |= ws_flags_map[i][1];
1407 flags &= ~ws_flags_map[i][0];
1410 if (flags)
1412 FIXME("Unknown send/recv flags 0x%x, using anyway...\n", flags);
1413 out |= flags;
1415 return out;
1418 /***********************************************************************
1419 * convert_sockopt()
1421 * Converts socket flags from Windows format.
1422 * Return 1 if converted, 0 if not (error).
1424 static int convert_sockopt(INT *level, INT *optname)
1426 unsigned int i;
1427 switch (*level)
1429 case WS_SOL_SOCKET:
1430 *level = SOL_SOCKET;
1431 for(i = 0; i < ARRAY_SIZE(ws_sock_map); i++) {
1432 if( ws_sock_map[i][0] == *optname )
1434 *optname = ws_sock_map[i][1];
1435 return 1;
1438 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
1439 break;
1440 case WS_IPPROTO_TCP:
1441 *level = IPPROTO_TCP;
1442 for(i = 0; i < ARRAY_SIZE(ws_tcp_map); i++) {
1443 if ( ws_tcp_map[i][0] == *optname )
1445 *optname = ws_tcp_map[i][1];
1446 return 1;
1449 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
1450 break;
1451 case WS_IPPROTO_IP:
1452 *level = IPPROTO_IP;
1453 for(i = 0; i < ARRAY_SIZE(ws_ip_map); i++) {
1454 if (ws_ip_map[i][0] == *optname )
1456 *optname = ws_ip_map[i][1];
1457 return 1;
1460 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
1461 break;
1462 case WS_IPPROTO_IPV6:
1463 *level = IPPROTO_IPV6;
1464 for(i = 0; i < ARRAY_SIZE(ws_ipv6_map); i++) {
1465 if (ws_ipv6_map[i][0] == *optname )
1467 *optname = ws_ipv6_map[i][1];
1468 return 1;
1471 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
1472 break;
1473 default: FIXME("Unimplemented or unknown socket level\n");
1475 return 0;
1478 /* ----------------------------------- Per-thread info (or per-process?) */
1480 static char *strdup_lower(const char *str)
1482 int i;
1483 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
1485 if (ret)
1487 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
1488 ret[i] = 0;
1490 else SetLastError(WSAENOBUFS);
1491 return ret;
1494 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1495 * from an fd and return the value converted to milli seconds
1496 * or 0 if there is an infinite time out */
1497 static inline INT64 get_rcvsnd_timeo( int fd, BOOL is_recv)
1499 struct timeval tv;
1500 socklen_t len = sizeof(tv);
1501 int optname, res;
1503 if (is_recv)
1504 #ifdef SO_RCVTIMEO
1505 optname = SO_RCVTIMEO;
1506 #else
1507 return 0;
1508 #endif
1509 else
1510 #ifdef SO_SNDTIMEO
1511 optname = SO_SNDTIMEO;
1512 #else
1513 return 0;
1514 #endif
1516 res = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
1517 if (res < 0)
1518 return 0;
1519 return (UINT64)tv.tv_sec * 1000 + tv.tv_usec / 1000;
1522 /* utility: given an fd, will block until one of the events occurs */
1523 static inline int do_block( int fd, int events, int timeout )
1525 struct pollfd pfd;
1526 int ret;
1528 pfd.fd = fd;
1529 pfd.events = events;
1531 while ((ret = poll(&pfd, 1, timeout)) < 0)
1533 if (errno != EINTR)
1534 return -1;
1536 if( ret == 0 )
1537 return 0;
1538 return pfd.revents;
1541 static int
1542 convert_af_w2u(int windowsaf) {
1543 unsigned int i;
1545 for (i = 0; i < ARRAY_SIZE(ws_af_map); i++)
1546 if (ws_af_map[i][0] == windowsaf)
1547 return ws_af_map[i][1];
1548 FIXME("unhandled Windows address family %d\n", windowsaf);
1549 return -1;
1552 static int
1553 convert_af_u2w(int unixaf) {
1554 unsigned int i;
1556 for (i = 0; i < ARRAY_SIZE(ws_af_map); i++)
1557 if (ws_af_map[i][1] == unixaf)
1558 return ws_af_map[i][0];
1559 FIXME("unhandled UNIX address family %d\n", unixaf);
1560 return -1;
1563 static int
1564 convert_proto_w2u(int windowsproto) {
1565 unsigned int i;
1567 for (i = 0; i < ARRAY_SIZE(ws_proto_map); i++)
1568 if (ws_proto_map[i][0] == windowsproto)
1569 return ws_proto_map[i][1];
1571 /* check for extended IPX */
1572 if (IS_IPX_PROTO(windowsproto))
1573 return windowsproto;
1575 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1576 return -1;
1579 static int
1580 convert_proto_u2w(int unixproto) {
1581 unsigned int i;
1583 for (i = 0; i < ARRAY_SIZE(ws_proto_map); i++)
1584 if (ws_proto_map[i][1] == unixproto)
1585 return ws_proto_map[i][0];
1587 /* if value is inside IPX range just return it - the kernel simply
1588 * echoes the value used in the socket() function */
1589 if (IS_IPX_PROTO(unixproto))
1590 return unixproto;
1592 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1593 return -1;
1596 static int
1597 convert_socktype_w2u(int windowssocktype) {
1598 unsigned int i;
1600 for (i = 0; i < ARRAY_SIZE(ws_socktype_map); i++)
1601 if (ws_socktype_map[i][0] == windowssocktype)
1602 return ws_socktype_map[i][1];
1603 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1604 return -1;
1607 static int
1608 convert_socktype_u2w(int unixsocktype) {
1609 unsigned int i;
1611 for (i = 0; i < ARRAY_SIZE(ws_socktype_map); i++)
1612 if (ws_socktype_map[i][1] == unixsocktype)
1613 return ws_socktype_map[i][0];
1614 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1615 return -1;
1618 static int convert_poll_w2u(int events)
1620 int i, ret;
1621 for (i = ret = 0; events && i < ARRAY_SIZE(ws_poll_map); i++)
1623 if (ws_poll_map[i][0] & events)
1625 ret |= ws_poll_map[i][1];
1626 events &= ~ws_poll_map[i][0];
1630 if (events)
1631 FIXME("Unsupported WSAPoll() flags 0x%x\n", events);
1632 return ret;
1635 static int convert_poll_u2w(int events)
1637 int i, ret;
1638 for (i = ret = 0; events && i < ARRAY_SIZE(ws_poll_map); i++)
1640 if (ws_poll_map[i][1] & events)
1642 ret |= ws_poll_map[i][0];
1643 events &= ~ws_poll_map[i][1];
1647 if (events)
1648 FIXME("Unsupported poll() flags 0x%x\n", events);
1649 return ret;
1652 static int set_ipx_packettype(int sock, int ptype)
1654 #ifdef HAS_IPX
1655 int fd = get_sock_fd( sock, 0, NULL ), ret = 0;
1656 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype, fd);
1658 if (fd == -1) return SOCKET_ERROR;
1660 /* We try to set the ipx type on ipx socket level. */
1661 #ifdef SOL_IPX
1662 if(setsockopt(fd, SOL_IPX, IPX_TYPE, &ptype, sizeof(ptype)) == -1)
1664 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1665 ret = SOCKET_ERROR;
1667 #else
1669 struct ipx val;
1670 /* Should we retrieve val using a getsockopt call and then
1671 * set the modified one? */
1672 val.ipx_pt = ptype;
1673 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
1675 #endif
1676 release_sock_fd( sock, fd );
1677 return ret;
1678 #else
1679 WARN("IPX support is not enabled, can't set packet type\n");
1680 return SOCKET_ERROR;
1681 #endif
1684 /* ----------------------------------- API -----
1686 * Init / cleanup / error checking.
1689 /***********************************************************************
1690 * WSAStartup (WS2_32.115)
1692 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1694 TRACE("verReq=%x\n", wVersionRequested);
1696 if (LOBYTE(wVersionRequested) < 1)
1697 return WSAVERNOTSUPPORTED;
1699 if (!lpWSAData) return WSAEINVAL;
1701 num_startup++;
1703 /* that's the whole of the negotiation for now */
1704 lpWSAData->wVersion = wVersionRequested;
1705 /* return winsock information */
1706 lpWSAData->wHighVersion = 0x0202;
1707 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1708 strcpy(lpWSAData->szSystemStatus, "Running" );
1709 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1710 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1711 /* don't do anything with lpWSAData->lpVendorInfo */
1712 /* (some apps don't allocate the space for this field) */
1714 TRACE("succeeded starts: %d\n", num_startup);
1715 return 0;
1719 /***********************************************************************
1720 * WSACleanup (WS2_32.116)
1722 INT WINAPI WSACleanup(void)
1724 if (num_startup) {
1725 num_startup--;
1726 TRACE("pending cleanups: %d\n", num_startup);
1727 return 0;
1729 SetLastError(WSANOTINITIALISED);
1730 return SOCKET_ERROR;
1734 /***********************************************************************
1735 * WSAGetLastError (WS2_32.111)
1737 INT WINAPI WSAGetLastError(void)
1739 return GetLastError();
1742 /***********************************************************************
1743 * WSASetLastError (WS2_32.112)
1745 void WINAPI WSASetLastError(INT iError) {
1746 SetLastError(iError);
1749 static struct WS_hostent *check_buffer_he(int size)
1751 struct per_thread_data * ptb = get_per_thread_data();
1752 if (ptb->he_buffer)
1754 if (ptb->he_len >= size ) return ptb->he_buffer;
1755 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1757 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1758 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1759 return ptb->he_buffer;
1762 static struct WS_servent *check_buffer_se(int size)
1764 struct per_thread_data * ptb = get_per_thread_data();
1765 if (ptb->se_buffer)
1767 if (ptb->se_len >= size ) return ptb->se_buffer;
1768 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1770 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1771 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1772 return ptb->se_buffer;
1775 static struct WS_protoent *check_buffer_pe(int size)
1777 struct per_thread_data * ptb = get_per_thread_data();
1778 if (ptb->pe_buffer)
1780 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1781 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1783 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1784 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1785 return ptb->pe_buffer;
1788 /* ----------------------------------- i/o APIs */
1790 static inline BOOL supported_pf(int pf)
1792 switch (pf)
1794 case WS_AF_INET:
1795 case WS_AF_INET6:
1796 return TRUE;
1797 #ifdef HAS_IPX
1798 case WS_AF_IPX:
1799 return TRUE;
1800 #endif
1801 #ifdef HAS_IRDA
1802 case WS_AF_IRDA:
1803 return TRUE;
1804 #endif
1805 default:
1806 return FALSE;
1810 static inline BOOL supported_protocol(int protocol)
1812 int i;
1813 for (i = 0; i < ARRAY_SIZE(valid_protocols); i++)
1814 if (protocol == valid_protocols[i])
1815 return TRUE;
1816 return FALSE;
1819 /**********************************************************************/
1821 /* Returns the length of the converted address if successful, 0 if it was too
1822 * small to start with or unknown family or invalid address buffer.
1824 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1825 union generic_unix_sockaddr *uaddr)
1827 unsigned int uaddrlen = 0;
1829 if (!wsaddr)
1830 return 0;
1832 switch (wsaddr->sa_family)
1834 #ifdef HAS_IPX
1835 case WS_AF_IPX:
1837 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1838 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1840 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1841 return 0;
1843 uaddrlen = sizeof(struct sockaddr_ipx);
1844 memset( uaddr, 0, uaddrlen );
1845 uipx->sipx_family=AF_IPX;
1846 uipx->sipx_port=wsipx->sa_socket;
1847 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1848 * in one go
1850 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1851 #ifdef IPX_FRAME_NONE
1852 uipx->sipx_type=IPX_FRAME_NONE;
1853 #endif
1854 break;
1856 #endif
1857 case WS_AF_INET6: {
1858 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1859 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1861 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1862 * scope_id, one without.
1864 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1865 uaddrlen = sizeof(struct sockaddr_in6);
1866 memset( uaddr, 0, uaddrlen );
1867 uin6->sin6_family = AF_INET6;
1868 uin6->sin6_port = win6->sin6_port;
1869 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1870 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1871 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1872 #endif
1873 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1874 break;
1876 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1877 return 0;
1879 case WS_AF_INET: {
1880 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1881 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1883 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1884 return 0;
1885 uaddrlen = sizeof(struct sockaddr_in);
1886 memset( uaddr, 0, uaddrlen );
1887 uin->sin_family = AF_INET;
1888 uin->sin_port = win->sin_port;
1889 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1890 break;
1892 #ifdef HAS_IRDA
1893 case WS_AF_IRDA: {
1894 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1895 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1897 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1898 return 0;
1899 uaddrlen = sizeof(struct sockaddr_irda);
1900 memset( uaddr, 0, uaddrlen );
1901 uin->sir_family = AF_IRDA;
1902 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1904 unsigned int lsap_sel = 0;
1906 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1907 uin->sir_lsap_sel = lsap_sel;
1909 else
1911 uin->sir_lsap_sel = LSAP_ANY;
1912 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1914 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1915 break;
1917 #endif
1918 case WS_AF_UNSPEC: {
1919 /* Try to determine the needed space by the passed windows sockaddr space */
1920 switch (wsaddrlen) {
1921 default: /* likely an ipv4 address */
1922 case sizeof(struct WS_sockaddr_in):
1923 uaddrlen = sizeof(struct sockaddr_in);
1924 break;
1925 #ifdef HAS_IPX
1926 case sizeof(struct WS_sockaddr_ipx):
1927 uaddrlen = sizeof(struct sockaddr_ipx);
1928 break;
1929 #endif
1930 #ifdef HAS_IRDA
1931 case sizeof(SOCKADDR_IRDA):
1932 uaddrlen = sizeof(struct sockaddr_irda);
1933 break;
1934 #endif
1935 case sizeof(struct WS_sockaddr_in6):
1936 case sizeof(struct WS_sockaddr_in6_old):
1937 uaddrlen = sizeof(struct sockaddr_in6);
1938 break;
1940 memset( uaddr, 0, uaddrlen );
1941 break;
1943 default:
1944 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1945 return 0;
1947 return uaddrlen;
1950 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1952 switch (uaddr->sa_family)
1954 #ifdef HAS_IPX
1955 case AF_IPX:
1957 static const struct sockaddr_ipx emptyAddr;
1958 struct sockaddr_ipx *ipx = (struct sockaddr_ipx*) uaddr;
1959 return ipx->sipx_port
1960 || memcmp(&ipx->sipx_network, &emptyAddr.sipx_network, sizeof(emptyAddr.sipx_network))
1961 || memcmp(&ipx->sipx_node, &emptyAddr.sipx_node, sizeof(emptyAddr.sipx_node));
1963 #endif
1964 case AF_INET6:
1966 static const struct sockaddr_in6 emptyAddr;
1967 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1968 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1970 case AF_INET:
1972 static const struct sockaddr_in emptyAddr;
1973 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1974 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1976 case AF_UNSPEC:
1977 return FALSE;
1978 default:
1979 FIXME("unknown address family %d\n", uaddr->sa_family);
1980 return TRUE;
1984 /* Returns -1 if getsockname fails, 0 if not bound, 1 otherwise */
1985 static int is_fd_bound(int fd, union generic_unix_sockaddr *uaddr, socklen_t *uaddrlen)
1987 union generic_unix_sockaddr inaddr;
1988 socklen_t inlen;
1989 int res;
1991 if (!uaddr) uaddr = &inaddr;
1992 if (!uaddrlen) uaddrlen = &inlen;
1994 *uaddrlen = sizeof(inaddr);
1995 res = getsockname(fd, &uaddr->addr, uaddrlen);
1996 if (!res) res = is_sockaddr_bound(&uaddr->addr, *uaddrlen);
1997 return res;
2000 /* Returns 0 if successful, -1 if the buffer is too small */
2001 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
2003 int res;
2005 switch(uaddr->sa_family)
2007 #ifdef HAS_IPX
2008 case AF_IPX:
2010 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
2011 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
2013 res=-1;
2014 switch (*wsaddrlen) /* how much can we copy? */
2016 default:
2017 res=0; /* enough */
2018 *wsaddrlen = sizeof(*wsipx);
2019 wsipx->sa_socket=uipx->sipx_port;
2020 /* fall through */
2021 case 13:
2022 case 12:
2023 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
2024 /* fall through */
2025 case 11:
2026 case 10:
2027 case 9:
2028 case 8:
2029 case 7:
2030 case 6:
2031 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
2032 /* fall through */
2033 case 5:
2034 case 4:
2035 case 3:
2036 case 2:
2037 wsipx->sa_family=WS_AF_IPX;
2038 /* fall through */
2039 case 1:
2040 case 0:
2041 /* way too small */
2042 break;
2045 break;
2046 #endif
2047 #ifdef HAS_IRDA
2048 case AF_IRDA: {
2049 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
2050 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
2052 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
2053 return -1;
2054 win->irdaAddressFamily = WS_AF_IRDA;
2055 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
2056 if (uin->sir_lsap_sel != LSAP_ANY)
2057 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
2058 else
2059 memcpy( win->irdaServiceName, uin->sir_name,
2060 sizeof(win->irdaServiceName) );
2061 return 0;
2063 #endif
2064 case AF_INET6: {
2065 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
2066 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
2068 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
2069 return -1;
2070 win6old->sin6_family = WS_AF_INET6;
2071 win6old->sin6_port = uin6->sin6_port;
2072 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
2073 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
2074 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
2075 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
2076 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
2077 win6->sin6_scope_id = uin6->sin6_scope_id;
2078 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
2080 else
2081 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
2082 #else
2083 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
2084 #endif
2085 return 0;
2087 case AF_INET: {
2088 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
2089 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
2091 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
2092 return -1;
2093 win->sin_family = WS_AF_INET;
2094 win->sin_port = uin->sin_port;
2095 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
2096 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
2097 *wsaddrlen = sizeof(struct WS_sockaddr_in);
2098 return 0;
2100 case AF_UNSPEC: {
2101 memset(wsaddr,0,*wsaddrlen);
2102 return 0;
2104 default:
2105 FIXME("Unknown address family %d\n", uaddr->sa_family);
2106 return -1;
2108 return res;
2111 static INT WS_DuplicateSocket(BOOL unicode, SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo)
2113 HANDLE hProcess;
2114 int size;
2115 WSAPROTOCOL_INFOW infow;
2117 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
2118 unicode, s, dwProcessId, lpProtocolInfo);
2120 if (!ws_protocol_info(s, unicode, &infow, &size))
2121 return SOCKET_ERROR;
2123 if (!(hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId)))
2125 SetLastError(WSAEINVAL);
2126 return SOCKET_ERROR;
2129 if (!lpProtocolInfo)
2131 CloseHandle(hProcess);
2132 SetLastError(WSAEFAULT);
2133 return SOCKET_ERROR;
2136 /* I don't know what the real Windoze does next, this is a hack */
2137 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
2138 * the target use the global duplicate, or we could copy a reference to us to the structure
2139 * and let the target duplicate it from us, but let's do it as simple as possible */
2140 memcpy(lpProtocolInfo, &infow, size);
2141 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
2142 hProcess, (LPHANDLE)&lpProtocolInfo->dwServiceFlags3,
2143 0, FALSE, DUPLICATE_SAME_ACCESS);
2144 CloseHandle(hProcess);
2145 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
2146 return 0;
2149 /*****************************************************************************
2150 * WS_EnterSingleProtocolW [internal]
2152 * enters the protocol information of one given protocol into the given
2153 * buffer.
2155 * RETURNS
2156 * TRUE if a protocol was entered into the buffer.
2158 * BUGS
2159 * - only implemented for IPX, SPX, SPXII, TCP, UDP
2160 * - there is no check that the operating system supports the returned
2161 * protocols
2163 static BOOL WS_EnterSingleProtocolW( INT protocol, WSAPROTOCOL_INFOW* info )
2165 memset( info, 0, sizeof(WSAPROTOCOL_INFOW) );
2166 info->iProtocol = protocol;
2168 switch (protocol)
2170 case WS_IPPROTO_TCP:
2171 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_EXPEDITED_DATA |
2172 XP1_GRACEFUL_CLOSE | XP1_GUARANTEED_ORDER |
2173 XP1_GUARANTEED_DELIVERY;
2174 info->ProviderId = ProviderIdIP;
2175 info->dwCatalogEntryId = 0x3e9;
2176 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2177 info->ProtocolChain.ChainLen = 1;
2178 info->iVersion = 2;
2179 info->iAddressFamily = WS_AF_INET;
2180 info->iMaxSockAddr = 0x10;
2181 info->iMinSockAddr = 0x10;
2182 info->iSocketType = WS_SOCK_STREAM;
2183 strcpyW( info->szProtocol, NameTcpW );
2184 break;
2186 case WS_IPPROTO_UDP:
2187 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST |
2188 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
2189 XP1_CONNECTIONLESS;
2190 info->ProviderId = ProviderIdIP;
2191 info->dwCatalogEntryId = 0x3ea;
2192 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2193 info->ProtocolChain.ChainLen = 1;
2194 info->iVersion = 2;
2195 info->iAddressFamily = WS_AF_INET;
2196 info->iMaxSockAddr = 0x10;
2197 info->iMinSockAddr = 0x10;
2198 info->iSocketType = WS_SOCK_DGRAM;
2199 info->dwMessageSize = 0xffbb;
2200 strcpyW( info->szProtocol, NameUdpW );
2201 break;
2203 case WS_NSPROTO_IPX:
2204 info->dwServiceFlags1 = XP1_PARTIAL_MESSAGE | XP1_SUPPORT_BROADCAST |
2205 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
2206 XP1_CONNECTIONLESS;
2207 info->ProviderId = ProviderIdIPX;
2208 info->dwCatalogEntryId = 0x406;
2209 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2210 info->ProtocolChain.ChainLen = 1;
2211 info->iVersion = 2;
2212 info->iAddressFamily = WS_AF_IPX;
2213 info->iMaxSockAddr = 0x10;
2214 info->iMinSockAddr = 0x0e;
2215 info->iSocketType = WS_SOCK_DGRAM;
2216 info->iProtocolMaxOffset = 0xff;
2217 info->dwMessageSize = 0x240;
2218 strcpyW( info->szProtocol, NameIpxW );
2219 break;
2221 case WS_NSPROTO_SPX:
2222 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_PSEUDO_STREAM |
2223 XP1_MESSAGE_ORIENTED | XP1_GUARANTEED_ORDER |
2224 XP1_GUARANTEED_DELIVERY;
2225 info->ProviderId = ProviderIdSPX;
2226 info->dwCatalogEntryId = 0x407;
2227 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2228 info->ProtocolChain.ChainLen = 1;
2229 info->iVersion = 2;
2230 info->iAddressFamily = WS_AF_IPX;
2231 info->iMaxSockAddr = 0x10;
2232 info->iMinSockAddr = 0x0e;
2233 info->iSocketType = WS_SOCK_SEQPACKET;
2234 info->dwMessageSize = 0xffffffff;
2235 strcpyW( info->szProtocol, NameSpxW );
2236 break;
2238 case WS_NSPROTO_SPXII:
2239 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_GRACEFUL_CLOSE |
2240 XP1_PSEUDO_STREAM | XP1_MESSAGE_ORIENTED |
2241 XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY;
2242 info->ProviderId = ProviderIdSPX;
2243 info->dwCatalogEntryId = 0x409;
2244 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2245 info->ProtocolChain.ChainLen = 1;
2246 info->iVersion = 2;
2247 info->iAddressFamily = WS_AF_IPX;
2248 info->iMaxSockAddr = 0x10;
2249 info->iMinSockAddr = 0x0e;
2250 info->iSocketType = WS_SOCK_SEQPACKET;
2251 info->dwMessageSize = 0xffffffff;
2252 strcpyW( info->szProtocol, NameSpxIIW );
2253 break;
2255 default:
2256 FIXME("unknown Protocol <0x%08x>\n", protocol);
2257 return FALSE;
2259 return TRUE;
2262 /*****************************************************************************
2263 * WS_EnterSingleProtocolA [internal]
2265 * see function WS_EnterSingleProtocolW
2268 static BOOL WS_EnterSingleProtocolA( INT protocol, WSAPROTOCOL_INFOA* info )
2270 WSAPROTOCOL_INFOW infow;
2271 INT ret;
2272 memset( info, 0, sizeof(WSAPROTOCOL_INFOA) );
2274 ret = WS_EnterSingleProtocolW( protocol, &infow );
2275 if (ret)
2277 /* convert the structure from W to A */
2278 memcpy( info, &infow, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
2279 WideCharToMultiByte( CP_ACP, 0, infow.szProtocol, -1,
2280 info->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL );
2283 return ret;
2286 static INT WS_EnumProtocols( BOOL unicode, const INT *protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
2288 INT i = 0, items = 0;
2289 DWORD size = 0;
2290 union _info
2292 LPWSAPROTOCOL_INFOA a;
2293 LPWSAPROTOCOL_INFOW w;
2294 } info;
2295 info.w = buffer;
2297 if (!protocols) protocols = valid_protocols;
2299 while (protocols[i])
2301 if(supported_protocol(protocols[i++]))
2302 items++;
2305 size = items * (unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA));
2307 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
2308 unicode, protocols, buffer, len, len ? *len : 0, items, size);
2310 if (*len < size || !buffer)
2312 *len = size;
2313 SetLastError(WSAENOBUFS);
2314 return SOCKET_ERROR;
2317 for (i = items = 0; protocols[i]; i++)
2319 if (!supported_protocol(protocols[i])) continue;
2320 if (unicode)
2322 if (WS_EnterSingleProtocolW( protocols[i], &info.w[items] ))
2323 items++;
2325 else
2327 if (WS_EnterSingleProtocolA( protocols[i], &info.a[items] ))
2328 items++;
2331 return items;
2334 static BOOL ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size)
2336 NTSTATUS status;
2337 int address_family;
2338 int socket_type;
2339 int protocol;
2341 *size = unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA);
2342 memset(buffer, 0, *size);
2344 SERVER_START_REQ( get_socket_info )
2346 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2347 status = wine_server_call( req );
2348 if (!status)
2350 address_family = convert_af_u2w(reply->family);
2351 socket_type = convert_socktype_u2w(reply->type);
2352 protocol = convert_proto_u2w(reply->protocol);
2355 SERVER_END_REQ;
2357 if (status)
2359 unsigned int err = NtStatusToWSAError( status );
2360 SetLastError( err == WSAEBADF ? WSAENOTSOCK : err );
2361 return FALSE;
2364 if (unicode)
2365 WS_EnterSingleProtocolW( protocol, buffer);
2366 else
2367 WS_EnterSingleProtocolA( protocol, (WSAPROTOCOL_INFOA *)buffer);
2368 buffer->iAddressFamily = address_family;
2369 buffer->iSocketType = socket_type;
2370 buffer->iProtocol = protocol;
2372 return TRUE;
2375 /**************************************************************************
2376 * Functions for handling overlapped I/O
2377 **************************************************************************/
2379 /* user APC called upon async completion */
2380 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
2382 struct ws2_async *wsa = arg;
2384 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
2385 iosb->Information, wsa->user_overlapped,
2386 wsa->flags );
2387 release_async_io( &wsa->io );
2390 /***********************************************************************
2391 * WS2_recv (INTERNAL)
2393 * Workhorse for both synchronous and asynchronous recv() operations.
2395 static int WS2_recv( int fd, struct ws2_async *wsa, int flags )
2397 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2398 char pktbuf[512];
2399 #endif
2400 struct msghdr hdr;
2401 union generic_unix_sockaddr unix_sockaddr;
2402 int n;
2404 hdr.msg_name = NULL;
2406 if (wsa->addr)
2408 hdr.msg_namelen = sizeof(unix_sockaddr);
2409 hdr.msg_name = &unix_sockaddr;
2411 else
2412 hdr.msg_namelen = 0;
2414 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2415 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2416 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2417 hdr.msg_accrights = NULL;
2418 hdr.msg_accrightslen = 0;
2419 #else
2420 hdr.msg_control = pktbuf;
2421 hdr.msg_controllen = sizeof(pktbuf);
2422 hdr.msg_flags = 0;
2423 #endif
2425 while ((n = __wine_locked_recvmsg( fd, &hdr, flags )) == -1)
2427 if (errno != EINTR)
2428 return -1;
2431 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2432 if (wsa->control)
2434 ERR("Message control headers cannot be properly supported on this system.\n");
2435 wsa->control->len = 0;
2437 #else
2438 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
2440 WARN("Application passed insufficient room for control headers.\n");
2441 *wsa->lpFlags |= WS_MSG_CTRUNC;
2442 errno = EMSGSIZE;
2443 return -1;
2445 #endif
2447 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
2448 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
2450 * quoting linux 2.6 net/ipv4/tcp.c:
2451 * "According to UNIX98, msg_name/msg_namelen are ignored
2452 * on connected socket. I was just happy when found this 8) --ANK"
2454 * likewise MSDN says that lpFrom and lpFromlen are ignored for
2455 * connection-oriented sockets, so don't try to update lpFrom.
2457 if (wsa->addr && hdr.msg_namelen)
2458 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
2460 return n;
2463 /***********************************************************************
2464 * WS2_async_recv (INTERNAL)
2466 * Handler for overlapped recv() operations.
2468 static NTSTATUS WS2_async_recv( void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status )
2470 struct ws2_async *wsa = user;
2471 int result = 0, fd;
2473 switch (status)
2475 case STATUS_ALERTED:
2476 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
2477 break;
2479 result = WS2_recv( fd, wsa, convert_flags(wsa->flags) );
2480 wine_server_release_fd( wsa->hSocket, fd );
2481 if (result >= 0)
2483 status = STATUS_SUCCESS;
2484 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
2486 else
2488 if (errno == EAGAIN)
2490 status = STATUS_PENDING;
2491 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
2493 else
2495 result = 0;
2496 status = wsaErrStatus();
2499 break;
2501 if (status != STATUS_PENDING)
2503 iosb->u.Status = status;
2504 iosb->Information = result;
2505 if (!wsa->completion_func)
2506 release_async_io( &wsa->io );
2508 return status;
2511 /***********************************************************************
2512 * WS2_async_accept_recv (INTERNAL)
2514 * This function is used to finish the read part of an accept request. It is
2515 * needed to place the completion on the correct socket (listener).
2517 static NTSTATUS WS2_async_accept_recv( void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status )
2519 struct ws2_accept_async *wsa = user;
2521 status = WS2_async_recv( wsa->read, iosb, status );
2522 if (status == STATUS_PENDING)
2523 return status;
2525 if (wsa->cvalue)
2526 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information, TRUE );
2528 release_async_io( &wsa->io );
2529 return status;
2532 /***********************************************************************
2533 * WS2_async_accept (INTERNAL)
2535 * This is the function called to satisfy the AcceptEx callback
2537 static NTSTATUS WS2_async_accept( void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status )
2539 struct ws2_accept_async *wsa = user;
2540 int len;
2541 char *addr;
2543 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
2545 if (status == STATUS_ALERTED)
2547 SERVER_START_REQ( accept_into_socket )
2549 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
2550 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
2551 status = wine_server_call( req );
2553 SERVER_END_REQ;
2555 if (NtStatusToWSAError( status ) == WSAEWOULDBLOCK)
2556 return STATUS_PENDING;
2558 if (status == STATUS_INVALID_HANDLE)
2560 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2561 status = STATUS_CANCELLED;
2564 else if (status == STATUS_HANDLES_CLOSED)
2565 status = STATUS_CANCELLED; /* strange windows behavior */
2567 if (status != STATUS_SUCCESS)
2568 goto finish;
2570 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2571 addr = ((char *)wsa->buf) + wsa->data_len;
2572 len = wsa->local_len - sizeof(int);
2573 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
2574 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2575 *(int *)addr = len;
2577 addr += wsa->local_len;
2578 len = wsa->remote_len - sizeof(int);
2579 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
2580 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2581 *(int *)addr = len;
2583 if (!wsa->read)
2584 goto finish;
2586 wsa->io.callback = WS2_async_accept_recv;
2587 status = register_async( ASYNC_TYPE_READ, wsa->accept_socket, &wsa->io,
2588 wsa->user_overlapped->hEvent, NULL, NULL, iosb);
2590 if (status != STATUS_PENDING)
2591 goto finish;
2593 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2594 * needs to be performed by WS2_async_accept_recv() first. */
2595 return STATUS_MORE_PROCESSING_REQUIRED;
2597 finish:
2598 iosb->u.Status = status;
2599 iosb->Information = 0;
2601 if (wsa->read) release_async_io( &wsa->read->io );
2602 release_async_io( &wsa->io );
2603 return status;
2606 /***********************************************************************
2607 * WS2_send (INTERNAL)
2609 * Workhorse for both synchronous and asynchronous send() operations.
2611 static int WS2_send( int fd, struct ws2_async *wsa, int flags )
2613 struct msghdr hdr;
2614 union generic_unix_sockaddr unix_addr;
2615 int n, ret;
2617 hdr.msg_name = NULL;
2618 hdr.msg_namelen = 0;
2620 if (wsa->addr)
2622 hdr.msg_name = &unix_addr;
2623 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
2624 if ( !hdr.msg_namelen )
2626 errno = EFAULT;
2627 return -1;
2630 #if defined(HAS_IPX) && defined(SOL_IPX)
2631 if(wsa->addr->sa_family == WS_AF_IPX)
2633 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
2634 int val=0;
2635 socklen_t len = sizeof(int);
2637 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2638 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2639 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2640 * ipx type in the sockaddr_opx structure with the stored value.
2642 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
2643 uipx->sipx_type = val;
2645 #endif
2648 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2649 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2650 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2651 hdr.msg_accrights = NULL;
2652 hdr.msg_accrightslen = 0;
2653 #else
2654 hdr.msg_control = NULL;
2655 hdr.msg_controllen = 0;
2656 hdr.msg_flags = 0;
2657 #endif
2659 while ((ret = sendmsg(fd, &hdr, flags)) == -1)
2661 if (errno == EISCONN)
2663 hdr.msg_name = 0;
2664 hdr.msg_namelen = 0;
2665 continue;
2667 if (errno != EINTR)
2668 return -1;
2671 n = ret;
2672 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
2673 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2674 if (wsa->first_iovec < wsa->n_iovecs)
2676 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2677 wsa->iovec[wsa->first_iovec].iov_len -= n;
2679 return ret;
2682 /***********************************************************************
2683 * WS2_async_send (INTERNAL)
2685 * Handler for overlapped send() operations.
2687 static NTSTATUS WS2_async_send( void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status )
2689 struct ws2_async *wsa = user;
2690 int result = 0, fd;
2692 switch (status)
2694 case STATUS_ALERTED:
2695 if ( wsa->n_iovecs <= wsa->first_iovec )
2697 /* Nothing to do */
2698 status = STATUS_SUCCESS;
2699 break;
2701 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
2702 break;
2704 /* check to see if the data is ready (non-blocking) */
2705 result = WS2_send( fd, wsa, convert_flags(wsa->flags) );
2706 wine_server_release_fd( wsa->hSocket, fd );
2708 if (result >= 0)
2710 if (wsa->first_iovec < wsa->n_iovecs)
2711 status = STATUS_PENDING;
2712 else
2713 status = STATUS_SUCCESS;
2715 iosb->Information += result;
2717 else if (errno == EAGAIN)
2719 status = STATUS_PENDING;
2721 else
2723 status = wsaErrStatus();
2725 break;
2727 if (status != STATUS_PENDING)
2729 iosb->u.Status = status;
2730 if (!wsa->completion_func)
2731 release_async_io( &wsa->io );
2733 return status;
2736 /***********************************************************************
2737 * WS2_async_shutdown (INTERNAL)
2739 * Handler for shutdown() operations on overlapped sockets.
2741 static NTSTATUS WS2_async_shutdown( void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status )
2743 struct ws2_async_shutdown *wsa = user;
2744 int fd, err = 1;
2746 switch (status)
2748 case STATUS_ALERTED:
2749 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
2750 break;
2752 switch ( wsa->type )
2754 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
2755 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
2757 status = err ? wsaErrStatus() : STATUS_SUCCESS;
2758 wine_server_release_fd( wsa->hSocket, fd );
2759 break;
2761 iosb->u.Status = status;
2762 iosb->Information = 0;
2763 release_async_io( &wsa->io );
2764 return status;
2767 /***********************************************************************
2768 * WS2_register_async_shutdown (INTERNAL)
2770 * Helper function for WS_shutdown() on overlapped sockets.
2772 static int WS2_register_async_shutdown( SOCKET s, int type )
2774 struct ws2_async_shutdown *wsa;
2775 NTSTATUS status;
2777 TRACE("socket %04lx type %d\n", s, type);
2779 wsa = (struct ws2_async_shutdown *)alloc_async_io( sizeof(*wsa), WS2_async_shutdown );
2780 if ( !wsa )
2781 return WSAEFAULT;
2783 wsa->hSocket = SOCKET2HANDLE(s);
2784 wsa->type = type;
2786 status = register_async( type, wsa->hSocket, &wsa->io, 0, NULL, NULL, &wsa->iosb );
2787 if (status != STATUS_PENDING)
2789 HeapFree( GetProcessHeap(), 0, wsa );
2790 return NtStatusToWSAError( status );
2792 return 0;
2795 /***********************************************************************
2796 * accept (WS2_32.1)
2798 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr, int *addrlen32)
2800 DWORD err;
2801 SOCKET as;
2802 int fd;
2803 BOOL is_blocking;
2805 TRACE("socket %04lx\n", s );
2806 err = sock_is_blocking(s, &is_blocking);
2807 if (err)
2808 goto error;
2810 for (;;)
2812 /* try accepting first (if there is a deferred connection) */
2813 SERVER_START_REQ( accept_socket )
2815 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2816 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
2817 req->attributes = OBJ_INHERIT;
2818 err = NtStatusToWSAError( wine_server_call( req ));
2819 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
2821 SERVER_END_REQ;
2822 if (!err)
2824 if (addr && addrlen32 && WS_getpeername(as, addr, addrlen32))
2826 WS_closesocket(as);
2827 return SOCKET_ERROR;
2829 TRACE("\taccepted %04lx\n", as);
2830 return as;
2832 if (!is_blocking) break;
2833 if (err != WSAEWOULDBLOCK) break;
2834 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2835 /* block here */
2836 do_block(fd, POLLIN, -1);
2837 _sync_sock_state(s); /* let wineserver notice connection */
2838 release_sock_fd( s, fd );
2841 error:
2842 WARN(" -> ERROR %d\n", err);
2843 SetLastError(err);
2844 return INVALID_SOCKET;
2847 /***********************************************************************
2848 * AcceptEx
2850 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
2851 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
2852 LPOVERLAPPED overlapped)
2854 DWORD status;
2855 struct ws2_accept_async *wsa;
2856 int fd;
2858 TRACE("(%04lx, %04lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
2859 rem_addr_len, received, overlapped);
2861 if (!overlapped)
2863 SetLastError(WSA_INVALID_PARAMETER);
2864 return FALSE;
2866 overlapped->Internal = STATUS_PENDING;
2868 if (!dest)
2870 SetLastError(WSAEINVAL);
2871 return FALSE;
2874 if (!rem_addr_len)
2876 SetLastError(WSAEFAULT);
2877 return FALSE;
2880 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
2881 if (fd == -1)
2883 SetLastError(WSAENOTSOCK);
2884 return FALSE;
2886 release_sock_fd( listener, fd );
2888 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
2889 if (fd == -1)
2891 SetLastError(WSAENOTSOCK);
2892 return FALSE;
2894 release_sock_fd( acceptor, fd );
2896 wsa = (struct ws2_accept_async *)alloc_async_io( sizeof(*wsa), WS2_async_accept );
2897 if(!wsa)
2899 SetLastError(WSAEFAULT);
2900 return FALSE;
2903 wsa->listen_socket = SOCKET2HANDLE(listener);
2904 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2905 wsa->user_overlapped = overlapped;
2906 wsa->cvalue = !((ULONG_PTR)overlapped->hEvent & 1) ? (ULONG_PTR)overlapped : 0;
2907 wsa->buf = dest;
2908 wsa->data_len = dest_len;
2909 wsa->local_len = local_addr_len;
2910 wsa->remote_len = rem_addr_len;
2911 wsa->read = NULL;
2913 if (wsa->data_len)
2915 /* set up a read request if we need it */
2916 wsa->read = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[1]), WS2_async_accept_recv );
2917 if (!wsa->read)
2919 HeapFree( GetProcessHeap(), 0, wsa );
2920 SetLastError(WSAEFAULT);
2921 return FALSE;
2924 wsa->read->hSocket = wsa->accept_socket;
2925 wsa->read->flags = 0;
2926 wsa->read->lpFlags = &wsa->read->flags;
2927 wsa->read->addr = NULL;
2928 wsa->read->addrlen.ptr = NULL;
2929 wsa->read->control = NULL;
2930 wsa->read->n_iovecs = 1;
2931 wsa->read->first_iovec = 0;
2932 wsa->read->completion_func = NULL;
2933 wsa->read->iovec[0].iov_base = wsa->buf;
2934 wsa->read->iovec[0].iov_len = wsa->data_len;
2937 status = register_async( ASYNC_TYPE_READ, SOCKET2HANDLE(listener), &wsa->io,
2938 overlapped->hEvent, NULL, (void *)wsa->cvalue, (IO_STATUS_BLOCK *)overlapped );
2940 if(status != STATUS_PENDING)
2942 HeapFree( GetProcessHeap(), 0, wsa->read );
2943 HeapFree( GetProcessHeap(), 0, wsa );
2946 SetLastError( NtStatusToWSAError(status) );
2947 return FALSE;
2950 /***********************************************************************
2951 * WS2_ReadFile (INTERNAL)
2953 * Perform an APC-safe ReadFile operation
2955 static NTSTATUS WS2_ReadFile(HANDLE hFile, PIO_STATUS_BLOCK io_status, char* buffer, ULONG length,
2956 PLARGE_INTEGER offset)
2958 int result = -1, unix_handle;
2959 unsigned int options;
2960 NTSTATUS status;
2962 TRACE( "(%p,%p,0x%08x)\n", hFile, buffer,length );
2964 status = wine_server_handle_to_fd( hFile, FILE_READ_DATA, &unix_handle, &options );
2965 if (status) return status;
2967 while (result == -1)
2969 if (offset->QuadPart != FILE_USE_FILE_POINTER_POSITION)
2970 result = pread( unix_handle, buffer, length, offset->QuadPart );
2971 else
2972 result = read( unix_handle, buffer, length );
2973 if (errno != EINTR)
2974 break;
2977 if (!result)
2978 status = (length ? STATUS_END_OF_FILE : STATUS_SUCCESS);
2979 else if (result != -1)
2980 status = STATUS_SUCCESS;
2981 else if (errno != EAGAIN)
2982 status = wsaErrStatus();
2983 else
2984 status = STATUS_PENDING;
2986 wine_server_release_fd( hFile, unix_handle );
2987 TRACE("= 0x%08x (%d)\n", status, result);
2988 if (status == STATUS_SUCCESS || status == STATUS_END_OF_FILE)
2990 io_status->u.Status = status;
2991 io_status->Information = result;
2994 return status;
2997 /***********************************************************************
2998 * WS2_transmitfile_getbuffer (INTERNAL)
3000 * Pick the appropriate buffer for a TransmitFile send operation.
3002 static NTSTATUS WS2_transmitfile_getbuffer( int fd, struct ws2_transmitfile_async *wsa )
3004 /* send any incomplete writes from a previous iteration */
3005 if (wsa->write.first_iovec < wsa->write.n_iovecs)
3006 return STATUS_PENDING;
3008 /* process the header (if applicable) */
3009 if (wsa->buffers.Head)
3011 wsa->write.first_iovec = 0;
3012 wsa->write.n_iovecs = 1;
3013 wsa->write.iovec[0].iov_base = wsa->buffers.Head;
3014 wsa->write.iovec[0].iov_len = wsa->buffers.HeadLength;
3015 wsa->buffers.Head = NULL;
3016 return STATUS_PENDING;
3019 /* process the main file */
3020 if (wsa->file)
3022 DWORD bytes_per_send = wsa->bytes_per_send;
3023 IO_STATUS_BLOCK iosb;
3024 NTSTATUS status;
3026 iosb.Information = 0;
3027 /* when the size of the transfer is limited ensure that we don't go past that limit */
3028 if (wsa->file_bytes != 0)
3029 bytes_per_send = min(bytes_per_send, wsa->file_bytes - wsa->file_read);
3030 status = WS2_ReadFile( wsa->file, &iosb, wsa->buffer, bytes_per_send, &wsa->offset );
3031 if (wsa->offset.QuadPart != FILE_USE_FILE_POINTER_POSITION)
3032 wsa->offset.QuadPart += iosb.Information;
3033 if (status == STATUS_END_OF_FILE)
3034 wsa->file = NULL; /* continue on to the footer */
3035 else if (status != STATUS_SUCCESS)
3036 return status;
3037 else
3039 if (iosb.Information)
3041 wsa->write.first_iovec = 0;
3042 wsa->write.n_iovecs = 1;
3043 wsa->write.iovec[0].iov_base = wsa->buffer;
3044 wsa->write.iovec[0].iov_len = iosb.Information;
3045 wsa->file_read += iosb.Information;
3048 if (wsa->file_bytes != 0 && wsa->file_read >= wsa->file_bytes)
3049 wsa->file = NULL;
3051 return STATUS_PENDING;
3055 /* send the footer (if applicable) */
3056 if (wsa->buffers.Tail)
3058 wsa->write.first_iovec = 0;
3059 wsa->write.n_iovecs = 1;
3060 wsa->write.iovec[0].iov_base = wsa->buffers.Tail;
3061 wsa->write.iovec[0].iov_len = wsa->buffers.TailLength;
3062 wsa->buffers.Tail = NULL;
3063 return STATUS_PENDING;
3066 return STATUS_SUCCESS;
3069 /***********************************************************************
3070 * WS2_transmitfile_base (INTERNAL)
3072 * Shared implementation for both synchronous and asynchronous TransmitFile.
3074 static NTSTATUS WS2_transmitfile_base( int fd, struct ws2_transmitfile_async *wsa )
3076 NTSTATUS status;
3078 status = WS2_transmitfile_getbuffer( fd, wsa );
3079 if (status == STATUS_PENDING)
3081 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)wsa->write.user_overlapped;
3082 int n;
3084 n = WS2_send( fd, &wsa->write, convert_flags(wsa->write.flags) );
3085 if (n >= 0)
3087 if (iosb) iosb->Information += n;
3089 else if (errno != EAGAIN)
3090 return wsaErrStatus();
3093 return status;
3096 /***********************************************************************
3097 * WS2_async_transmitfile (INTERNAL)
3099 * Asynchronous callback for overlapped TransmitFile operations.
3101 static NTSTATUS WS2_async_transmitfile( void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status )
3103 struct ws2_transmitfile_async *wsa = user;
3104 int fd;
3106 if (status == STATUS_ALERTED)
3108 if (!(status = wine_server_handle_to_fd( wsa->write.hSocket, FILE_WRITE_DATA, &fd, NULL )))
3110 status = WS2_transmitfile_base( fd, wsa );
3111 wine_server_release_fd( wsa->write.hSocket, fd );
3113 if (status == STATUS_PENDING)
3114 return status;
3117 iosb->u.Status = status;
3118 release_async_io( &wsa->io );
3119 return status;
3122 /***********************************************************************
3123 * TransmitFile
3125 static BOOL WINAPI WS2_TransmitFile( SOCKET s, HANDLE h, DWORD file_bytes, DWORD bytes_per_send,
3126 LPOVERLAPPED overlapped, LPTRANSMIT_FILE_BUFFERS buffers,
3127 DWORD flags )
3129 union generic_unix_sockaddr uaddr;
3130 socklen_t uaddrlen = sizeof(uaddr);
3131 struct ws2_transmitfile_async *wsa;
3132 NTSTATUS status;
3133 int fd;
3135 TRACE("(%lx, %p, %d, %d, %p, %p, %d)\n", s, h, file_bytes, bytes_per_send, overlapped,
3136 buffers, flags );
3138 fd = get_sock_fd( s, FILE_WRITE_DATA, NULL );
3139 if (fd == -1)
3141 WSASetLastError( WSAENOTSOCK );
3142 return FALSE;
3144 if (getpeername( fd, &uaddr.addr, &uaddrlen ) != 0)
3146 release_sock_fd( s, fd );
3147 WSASetLastError( WSAENOTCONN );
3148 return FALSE;
3150 if (flags)
3151 FIXME("Flags are not currently supported (0x%x).\n", flags);
3153 if (h && GetFileType( h ) != FILE_TYPE_DISK)
3155 FIXME("Non-disk file handles are not currently supported.\n");
3156 release_sock_fd( s, fd );
3157 WSASetLastError( WSAEOPNOTSUPP );
3158 return FALSE;
3161 /* set reasonable defaults when requested */
3162 if (!bytes_per_send)
3163 bytes_per_send = (1 << 16); /* Depends on OS version: PAGE_SIZE, 2*PAGE_SIZE, or 2^16 */
3165 if (!(wsa = (struct ws2_transmitfile_async *)alloc_async_io( sizeof(*wsa) + bytes_per_send,
3166 WS2_async_transmitfile )))
3168 release_sock_fd( s, fd );
3169 WSASetLastError( WSAEFAULT );
3170 return FALSE;
3172 if (buffers)
3173 wsa->buffers = *buffers;
3174 else
3175 memset(&wsa->buffers, 0x0, sizeof(wsa->buffers));
3176 wsa->buffer = (char *)(wsa + 1);
3177 wsa->file = h;
3178 wsa->file_read = 0;
3179 wsa->file_bytes = file_bytes;
3180 wsa->bytes_per_send = bytes_per_send;
3181 wsa->flags = flags;
3182 wsa->offset.QuadPart = FILE_USE_FILE_POINTER_POSITION;
3183 wsa->write.hSocket = SOCKET2HANDLE(s);
3184 wsa->write.addr = NULL;
3185 wsa->write.addrlen.val = 0;
3186 wsa->write.flags = 0;
3187 wsa->write.lpFlags = &wsa->flags;
3188 wsa->write.control = NULL;
3189 wsa->write.n_iovecs = 0;
3190 wsa->write.first_iovec = 0;
3191 wsa->write.user_overlapped = overlapped;
3192 if (overlapped)
3194 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)overlapped;
3195 int status;
3197 wsa->offset.u.LowPart = overlapped->u.s.Offset;
3198 wsa->offset.u.HighPart = overlapped->u.s.OffsetHigh;
3199 iosb->u.Status = STATUS_PENDING;
3200 iosb->Information = 0;
3201 status = register_async( ASYNC_TYPE_WRITE, SOCKET2HANDLE(s), &wsa->io,
3202 overlapped->hEvent, NULL, NULL, iosb );
3203 if(status != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
3204 release_sock_fd( s, fd );
3205 WSASetLastError( NtStatusToWSAError(status) );
3206 return FALSE;
3211 status = WS2_transmitfile_base( fd, wsa );
3212 if (status == STATUS_PENDING)
3214 /* block here */
3215 do_block(fd, POLLOUT, -1);
3216 _sync_sock_state(s); /* let wineserver notice connection */
3219 while (status == STATUS_PENDING);
3220 release_sock_fd( s, fd );
3222 if (status != STATUS_SUCCESS)
3223 WSASetLastError( NtStatusToWSAError(status) );
3224 HeapFree( GetProcessHeap(), 0, wsa );
3225 return (status == STATUS_SUCCESS);
3228 /***********************************************************************
3229 * GetAcceptExSockaddrs
3231 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
3232 struct WS_sockaddr **local_addr, LPINT local_addr_len,
3233 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
3235 char *cbuf = buffer;
3236 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
3237 local_addr_len, remote_addr, remote_addr_len );
3238 cbuf += data_size;
3240 *local_addr_len = *(int *) cbuf;
3241 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
3243 cbuf += local_size;
3245 *remote_addr_len = *(int *) cbuf;
3246 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
3249 /***********************************************************************
3250 * WSASendMsg
3252 int WINAPI WSASendMsg( SOCKET s, LPWSAMSG msg, DWORD dwFlags, LPDWORD lpNumberOfBytesSent,
3253 LPWSAOVERLAPPED lpOverlapped,
3254 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
3256 if (!msg)
3258 SetLastError( WSAEFAULT );
3259 return SOCKET_ERROR;
3262 return WS2_sendto( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesSent,
3263 dwFlags, msg->name, msg->namelen,
3264 lpOverlapped, lpCompletionRoutine );
3267 /***********************************************************************
3268 * WSARecvMsg
3270 * Perform a receive operation that is capable of returning message
3271 * control headers. It is important to note that the WSAMSG parameter
3272 * must remain valid throughout the operation, even when an overlapped
3273 * receive is performed.
3275 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
3276 LPWSAOVERLAPPED lpOverlapped,
3277 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3279 if (!msg)
3281 SetLastError( WSAEFAULT );
3282 return SOCKET_ERROR;
3285 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
3286 &msg->dwFlags, msg->name, &msg->namelen,
3287 lpOverlapped, lpCompletionRoutine, &msg->Control );
3290 /***********************************************************************
3291 * interface_bind (INTERNAL)
3293 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
3294 * operating only on the specified interface. This restriction consists of two components:
3295 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
3296 * 2) An incoming packet restriction dropping packets not meant for the interface.
3297 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
3298 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
3299 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
3300 * to receive broadcast packets on a socket that is bound to a specific network interface.
3302 static BOOL interface_bind( SOCKET s, int fd, struct sockaddr *addr )
3304 struct sockaddr_in *in_sock = (struct sockaddr_in *) addr;
3305 in_addr_t bind_addr = in_sock->sin_addr.s_addr;
3306 PIP_ADAPTER_INFO adapters = NULL, adapter;
3307 BOOL ret = FALSE;
3308 DWORD adap_size;
3309 int enable = 1;
3311 if (bind_addr == htonl(INADDR_ANY) || bind_addr == htonl(INADDR_LOOPBACK))
3312 return FALSE; /* Not binding to a network adapter, special interface binding unnecessary. */
3313 if (_get_fd_type(fd) != SOCK_DGRAM)
3314 return FALSE; /* Special interface binding is only necessary for UDP datagrams. */
3315 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
3316 goto cleanup;
3317 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
3318 if (adapters == NULL || GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
3319 goto cleanup;
3320 /* Search the IPv4 adapter list for the appropriate binding interface */
3321 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
3323 in_addr_t adapter_addr = (in_addr_t) inet_addr(adapter->IpAddressList.IpAddress.String);
3325 if (bind_addr == adapter_addr)
3327 #if defined(IP_BOUND_IF)
3328 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
3329 if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &adapter->Index, sizeof(adapter->Index)) != 0)
3330 goto cleanup;
3331 ret = TRUE;
3332 #elif defined(LINUX_BOUND_IF)
3333 in_addr_t ifindex = (in_addr_t) htonl(adapter->Index);
3334 struct interface_filter specific_interface_filter;
3335 struct sock_fprog filter_prog;
3337 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex)) != 0)
3338 goto cleanup; /* Failed to suggest egress interface */
3339 specific_interface_filter = generic_interface_filter;
3340 specific_interface_filter.iface_rule.k = adapter->Index;
3341 specific_interface_filter.ip_rule.k = htonl(adapter_addr);
3342 filter_prog.len = sizeof(generic_interface_filter)/sizeof(struct sock_filter);
3343 filter_prog.filter = (struct sock_filter *) &specific_interface_filter;
3344 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) != 0)
3345 goto cleanup; /* Failed to specify incoming packet filter */
3346 ret = TRUE;
3347 #else
3348 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
3349 "receiving broadcast packets will not work on socket %04lx.\n", s);
3350 #endif
3351 break;
3354 /* Will soon be switching to INADDR_ANY: permit address reuse */
3355 if (ret && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == 0)
3356 TRACE("Socket %04lx bound to interface index %d\n", s, adapter->Index);
3357 else
3358 ret = FALSE;
3360 cleanup:
3361 if(!ret)
3362 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s);
3363 HeapFree(GetProcessHeap(), 0, adapters);
3364 return ret;
3367 /***********************************************************************
3368 * bind (WS2_32.2)
3370 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
3372 int fd = get_sock_fd( s, 0, NULL );
3373 int res = SOCKET_ERROR;
3375 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
3377 if (fd != -1)
3379 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
3381 SetLastError(WSAEAFNOSUPPORT);
3383 else
3385 union generic_unix_sockaddr uaddr;
3386 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
3387 if (!uaddrlen)
3389 SetLastError(WSAEFAULT);
3391 else
3393 if (name->sa_family == WS_AF_INET)
3395 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
3396 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
3398 /* Trying to bind to the default host interface, using
3399 * INADDR_ANY instead*/
3400 WARN("Trying to bind to magic IP address, using "
3401 "INADDR_ANY instead.\n");
3402 in4->sin_addr.s_addr = htonl(INADDR_ANY);
3404 else if (interface_bind(s, fd, &uaddr.addr))
3405 in4->sin_addr.s_addr = htonl(INADDR_ANY);
3407 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
3409 int loc_errno = errno;
3410 WARN("\tfailure - errno = %i\n", errno);
3411 errno = loc_errno;
3412 switch (errno)
3414 case EADDRNOTAVAIL:
3415 SetLastError(WSAEINVAL);
3416 break;
3417 case EADDRINUSE:
3419 int optval = 0;
3420 socklen_t optlen = sizeof(optval);
3421 /* Windows >= 2003 will return different results depending on
3422 * SO_REUSEADDR, WSAEACCES may be returned representing that
3423 * the socket hijacking protection prevented the bind */
3424 if (!getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, &optlen) && optval)
3426 SetLastError(WSAEACCES);
3427 break;
3429 /* fall through */
3431 default:
3432 SetLastError(wsaErrno());
3433 break;
3436 else
3438 res=0; /* success */
3442 release_sock_fd( s, fd );
3444 return res;
3447 /***********************************************************************
3448 * closesocket (WS2_32.3)
3450 int WINAPI WS_closesocket(SOCKET s)
3452 int res = SOCKET_ERROR, fd;
3453 if (num_startup)
3455 fd = get_sock_fd(s, FILE_READ_DATA, NULL);
3456 if (fd >= 0)
3458 release_sock_fd(s, fd);
3459 if (CloseHandle(SOCKET2HANDLE(s)))
3460 res = 0;
3462 else
3463 SetLastError(WSAENOTSOCK);
3465 else
3466 SetLastError(WSANOTINITIALISED);
3467 TRACE("(socket %04lx) -> %d\n", s, res);
3468 return res;
3471 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
3473 union generic_unix_sockaddr uaddr;
3474 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
3476 if (!uaddrlen)
3477 return WSAEFAULT;
3479 if (name->sa_family == WS_AF_INET)
3481 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
3482 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
3484 /* Trying to connect to magic replace-loopback address,
3485 * assuming we really want to connect to localhost */
3486 TRACE("Trying to connect to magic IP address, using "
3487 "INADDR_LOOPBACK instead.\n");
3488 in4->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
3492 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
3493 return 0;
3495 return wsaErrno();
3498 /***********************************************************************
3499 * connect (WS2_32.4)
3501 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
3503 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3505 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
3507 if (fd != -1)
3509 BOOL is_blocking;
3510 int ret = do_connect(fd, name, namelen);
3511 if (ret == 0)
3512 goto connect_success;
3514 if (ret == WSAEINPROGRESS)
3516 /* tell wineserver that a connection is in progress */
3517 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3518 FD_CONNECT,
3519 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3520 ret = sock_is_blocking( s, &is_blocking );
3521 if (!ret)
3523 if (is_blocking)
3525 do_block(fd, POLLIN | POLLOUT, -1);
3526 _sync_sock_state(s); /* let wineserver notice connection */
3527 /* retrieve any error codes from it */
3528 if (!(ret = get_sock_error(s, FD_CONNECT_BIT))) goto connect_success;
3530 else ret = WSAEWOULDBLOCK;
3533 release_sock_fd( s, fd );
3534 SetLastError(ret);
3536 return SOCKET_ERROR;
3538 connect_success:
3539 release_sock_fd( s, fd );
3540 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3541 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3542 FD_CONNECT|FD_WINE_LISTENING);
3543 TRACE("\tconnected %04lx\n", s);
3544 return 0;
3547 /***********************************************************************
3548 * WSAConnect (WS2_32.30)
3550 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
3551 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
3552 LPQOS lpSQOS, LPQOS lpGQOS )
3554 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
3555 FIXME("unsupported parameters!\n");
3556 return WS_connect( s, name, namelen );
3559 /***********************************************************************
3560 * ConnectEx
3562 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
3563 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
3565 int fd, ret, status;
3567 if (!ov)
3569 SetLastError( ERROR_INVALID_PARAMETER );
3570 return FALSE;
3573 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3574 if (fd == -1)
3576 SetLastError( WSAENOTSOCK );
3577 return FALSE;
3580 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
3581 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
3583 ret = is_fd_bound(fd, NULL, NULL);
3584 if (ret <= 0)
3586 SetLastError(ret == -1 ? wsaErrno() : WSAEINVAL);
3587 release_sock_fd( s, fd );
3588 return FALSE;
3591 ret = do_connect(fd, name, namelen);
3592 if (ret == 0)
3594 WSABUF wsabuf;
3596 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3597 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3598 FD_CONNECT|FD_WINE_LISTENING);
3600 wsabuf.len = sendBufLen;
3601 wsabuf.buf = (char*) sendBuf;
3603 /* WSASend takes care of completion if need be */
3604 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
3605 goto connection_success;
3607 else if (ret == WSAEINPROGRESS)
3609 struct ws2_async *wsa;
3610 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
3612 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3613 FD_CONNECT,
3614 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3616 /* Indirectly call WSASend */
3617 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof( struct ws2_async, iovec[1] ), WS2_async_send )))
3619 SetLastError(WSAEFAULT);
3621 else
3623 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
3624 iosb->u.Status = STATUS_PENDING;
3625 iosb->Information = 0;
3627 wsa->hSocket = SOCKET2HANDLE(s);
3628 wsa->addr = NULL;
3629 wsa->addrlen.val = 0;
3630 wsa->flags = 0;
3631 wsa->lpFlags = &wsa->flags;
3632 wsa->control = NULL;
3633 wsa->n_iovecs = sendBuf ? 1 : 0;
3634 wsa->first_iovec = 0;
3635 wsa->completion_func = NULL;
3636 wsa->iovec[0].iov_base = sendBuf;
3637 wsa->iovec[0].iov_len = sendBufLen;
3639 status = register_async( ASYNC_TYPE_WRITE, wsa->hSocket, &wsa->io, ov->hEvent,
3640 NULL, (void *)cvalue, iosb );
3641 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
3643 /* If the connect already failed */
3644 if (status == STATUS_PIPE_DISCONNECTED)
3646 ov->Internal = sock_error_to_ntstatus( get_sock_error( s, FD_CONNECT_BIT ));
3647 ov->InternalHigh = 0;
3648 if (cvalue) WS_AddCompletion( s, cvalue, ov->Internal, ov->InternalHigh, FALSE );
3649 if (ov->hEvent) NtSetEvent( ov->hEvent, NULL );
3650 status = STATUS_PENDING;
3652 SetLastError( NtStatusToWSAError(status) );
3655 else
3657 SetLastError(ret);
3660 release_sock_fd( s, fd );
3661 return FALSE;
3663 connection_success:
3664 release_sock_fd( s, fd );
3665 return TRUE;
3668 /***********************************************************************
3669 * DisconnectEx
3671 static BOOL WINAPI WS2_DisconnectEx( SOCKET s, LPOVERLAPPED ov, DWORD flags, DWORD reserved )
3673 TRACE( "socket %04lx, ov %p, flags 0x%x, reserved 0x%x\n", s, ov, flags, reserved );
3675 if (flags & TF_REUSE_SOCKET)
3676 FIXME( "Reusing socket not supported yet\n" );
3678 if (ov)
3680 ov->Internal = STATUS_PENDING;
3681 ov->InternalHigh = 0;
3684 return !WS_shutdown( s, SD_BOTH );
3687 /***********************************************************************
3688 * getpeername (WS2_32.5)
3690 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
3692 int fd;
3693 int res;
3695 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3697 fd = get_sock_fd( s, 0, NULL );
3698 res = SOCKET_ERROR;
3700 if (fd != -1)
3702 union generic_unix_sockaddr uaddr;
3703 socklen_t uaddrlen = sizeof(uaddr);
3705 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
3707 if (!name || !namelen)
3708 SetLastError(WSAEFAULT);
3709 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3710 /* The buffer was too small */
3711 SetLastError(WSAEFAULT);
3712 else
3714 res = 0;
3715 TRACE("=> %s\n", debugstr_sockaddr(name));
3718 else
3719 SetLastError(wsaErrno());
3720 release_sock_fd( s, fd );
3722 return res;
3725 /* When binding to an UDP address with filter support the getsockname call on the socket
3726 * will always return 0.0.0.0 instead of the filtered interface address. This function
3727 * checks if the socket is interface-bound on UDP and return the correct address.
3728 * This is required because applications often do a bind() with port zero followed by a
3729 * getsockname() to retrieve the port and address acquired.
3731 static void interface_bind_check(int fd, struct sockaddr_in *addr)
3733 #if !defined(IP_BOUND_IF) && !defined(LINUX_BOUND_IF)
3734 return;
3735 #else
3736 unsigned int ifindex;
3737 int ret;
3738 socklen_t len;
3740 /* Check for IPv4, address 0.0.0.0 and UDP socket */
3741 if (addr->sin_family != AF_INET || addr->sin_addr.s_addr != 0)
3742 return;
3743 if (_get_fd_type(fd) != SOCK_DGRAM)
3744 return;
3746 len = sizeof(ifindex);
3747 #if defined(IP_BOUND_IF)
3748 ret = getsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &ifindex, &len);
3749 #elif defined(LINUX_BOUND_IF)
3750 ret = getsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, &len);
3751 if (!ret) ifindex = ntohl(ifindex);
3752 #endif
3753 if (!ret)
3755 PIP_ADAPTER_INFO adapters, adapter;
3756 DWORD adap_size;
3758 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
3759 return;
3760 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
3761 if (adapters && GetAdaptersInfo(adapters, &adap_size) == NO_ERROR)
3763 /* Search the IPv4 adapter list for the appropriate bound interface */
3764 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
3766 in_addr_t adapter_addr;
3767 if (adapter->Index != ifindex) continue;
3769 adapter_addr = inet_addr(adapter->IpAddressList.IpAddress.String);
3770 addr->sin_addr.s_addr = adapter_addr;
3771 TRACE("reporting interface address from adapter %d\n", ifindex);
3772 break;
3775 HeapFree(GetProcessHeap(), 0, adapters);
3777 #endif
3780 /***********************************************************************
3781 * getsockname (WS2_32.6)
3783 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
3785 int fd;
3786 int res;
3788 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3790 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3791 if( (name == NULL) || (namelen == NULL) )
3793 SetLastError( WSAEFAULT );
3794 return SOCKET_ERROR;
3797 fd = get_sock_fd( s, 0, NULL );
3798 res = SOCKET_ERROR;
3800 if (fd != -1)
3802 union generic_unix_sockaddr uaddr;
3803 socklen_t uaddrlen;
3804 int bound = is_fd_bound(fd, &uaddr, &uaddrlen);
3806 if (bound <= 0)
3808 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
3810 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3812 /* The buffer was too small */
3813 SetLastError(WSAEFAULT);
3815 else
3817 interface_bind_check(fd, (struct sockaddr_in*) &uaddr);
3818 if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3820 /* The buffer was too small */
3821 SetLastError(WSAEFAULT);
3823 else
3825 res = 0;
3826 TRACE("=> %s\n", debugstr_sockaddr(name));
3829 release_sock_fd( s, fd );
3831 return res;
3834 /***********************************************************************
3835 * getsockopt (WS2_32.7)
3837 INT WINAPI WS_getsockopt(SOCKET s, INT level,
3838 INT optname, char *optval, INT *optlen)
3840 int fd;
3841 INT ret = 0;
3843 TRACE("(socket %04lx, %s, optval %s, optlen %p (%d))\n", s,
3844 debugstr_sockopt(level, optname), debugstr_optval(optval, 0),
3845 optlen, optlen ? *optlen : 0);
3847 switch(level)
3849 case WS_SOL_SOCKET:
3851 switch(optname)
3853 /* Handle common cases. The special cases are below, sorted
3854 * alphabetically */
3855 case WS_SO_BROADCAST:
3856 case WS_SO_DEBUG:
3857 case WS_SO_KEEPALIVE:
3858 case WS_SO_OOBINLINE:
3859 case WS_SO_RCVBUF:
3860 case WS_SO_REUSEADDR:
3861 case WS_SO_SNDBUF:
3862 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3863 return SOCKET_ERROR;
3864 convert_sockopt(&level, &optname);
3865 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3867 SetLastError(wsaErrno());
3868 ret = SOCKET_ERROR;
3870 release_sock_fd( s, fd );
3871 return ret;
3872 case WS_SO_ACCEPTCONN:
3873 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3874 return SOCKET_ERROR;
3875 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, optval, (socklen_t *)optlen) != 0 )
3877 SetLastError(wsaErrno());
3878 ret = SOCKET_ERROR;
3880 else
3882 /* BSD returns != 0 while Windows return exact == 1 */
3883 if (*(int *)optval) *(int *)optval = 1;
3885 release_sock_fd( s, fd );
3886 return ret;
3887 case WS_SO_BSP_STATE:
3889 int req_size, addr_size;
3890 WSAPROTOCOL_INFOW infow;
3891 CSADDR_INFO *csinfo;
3893 ret = ws_protocol_info(s, TRUE, &infow, &addr_size);
3894 if (ret)
3896 if (infow.iAddressFamily == WS_AF_INET)
3897 addr_size = sizeof(struct sockaddr_in);
3898 else if (infow.iAddressFamily == WS_AF_INET6)
3899 addr_size = sizeof(struct sockaddr_in6);
3900 else
3902 FIXME("Family %d is unsupported for SO_BSP_STATE\n", infow.iAddressFamily);
3903 SetLastError(WSAEAFNOSUPPORT);
3904 return SOCKET_ERROR;
3907 req_size = sizeof(CSADDR_INFO) + addr_size * 2;
3908 if (*optlen < req_size)
3910 ret = 0;
3911 SetLastError(WSAEFAULT);
3913 else
3915 union generic_unix_sockaddr uaddr;
3916 socklen_t uaddrlen;
3918 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3919 return SOCKET_ERROR;
3921 csinfo = (CSADDR_INFO*) optval;
3923 /* Check if the sock is bound */
3924 if (is_fd_bound(fd, &uaddr, &uaddrlen) == 1)
3926 csinfo->LocalAddr.lpSockaddr =
3927 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO));
3928 ws_sockaddr_u2ws(&uaddr.addr, csinfo->LocalAddr.lpSockaddr, &addr_size);
3929 csinfo->LocalAddr.iSockaddrLength = addr_size;
3931 else
3933 csinfo->LocalAddr.lpSockaddr = NULL;
3934 csinfo->LocalAddr.iSockaddrLength = 0;
3937 /* Check if the sock is connected */
3938 if (!getpeername(fd, &uaddr.addr, &uaddrlen) &&
3939 is_sockaddr_bound(&uaddr.addr, uaddrlen))
3941 csinfo->RemoteAddr.lpSockaddr =
3942 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO) + addr_size);
3943 ws_sockaddr_u2ws(&uaddr.addr, csinfo->RemoteAddr.lpSockaddr, &addr_size);
3944 csinfo->RemoteAddr.iSockaddrLength = addr_size;
3946 else
3948 csinfo->RemoteAddr.lpSockaddr = NULL;
3949 csinfo->RemoteAddr.iSockaddrLength = 0;
3952 csinfo->iSocketType = infow.iSocketType;
3953 csinfo->iProtocol = infow.iProtocol;
3954 release_sock_fd( s, fd );
3957 return ret ? 0 : SOCKET_ERROR;
3959 case WS_SO_DONTLINGER:
3961 struct linger lingval;
3962 socklen_t len = sizeof(struct linger);
3964 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
3966 SetLastError(WSAEFAULT);
3967 return SOCKET_ERROR;
3969 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3970 return SOCKET_ERROR;
3972 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
3974 SetLastError(wsaErrno());
3975 ret = SOCKET_ERROR;
3977 else
3979 *(BOOL *)optval = !lingval.l_onoff;
3980 *optlen = sizeof(BOOL);
3983 release_sock_fd( s, fd );
3984 return ret;
3987 case WS_SO_CONNECT_TIME:
3989 static int pretendtime = 0;
3990 struct WS_sockaddr addr;
3991 int len = sizeof(addr);
3993 if (!optlen || *optlen < sizeof(DWORD) || !optval)
3995 SetLastError(WSAEFAULT);
3996 return SOCKET_ERROR;
3998 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
3999 *(DWORD *)optval = ~0u;
4000 else
4002 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
4003 *(DWORD *)optval = pretendtime++;
4005 *optlen = sizeof(DWORD);
4006 return ret;
4008 /* As mentioned in setsockopt, Windows ignores this, so we
4009 * always return true here */
4010 case WS_SO_DONTROUTE:
4011 if (!optlen || *optlen < sizeof(BOOL) || !optval)
4013 SetLastError(WSAEFAULT);
4014 return SOCKET_ERROR;
4016 *(BOOL *)optval = TRUE;
4017 *optlen = sizeof(BOOL);
4018 return 0;
4020 case WS_SO_ERROR:
4022 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4023 return SOCKET_ERROR;
4024 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, optval, (socklen_t *)optlen) != 0 )
4026 SetLastError(wsaErrno());
4027 ret = SOCKET_ERROR;
4029 release_sock_fd( s, fd );
4031 /* The wineserver may have swallowed the error before us */
4032 if (!ret && *(int*) optval == 0)
4034 int i, events[FD_MAX_EVENTS];
4035 _get_sock_errors(s, events);
4036 for (i = 0; i < FD_MAX_EVENTS; i++)
4038 if(events[i])
4040 TRACE("returning SO_ERROR %d from wine server\n", events[i]);
4041 *(int*) optval = events[i];
4042 break;
4046 return ret;
4049 case WS_SO_LINGER:
4051 struct linger lingval;
4052 socklen_t len = sizeof(struct linger);
4054 /* struct linger and LINGER have different sizes */
4055 if (!optlen || *optlen < sizeof(LINGER) || !optval)
4057 SetLastError(WSAEFAULT);
4058 return SOCKET_ERROR;
4060 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4061 return SOCKET_ERROR;
4063 if (_get_fd_type(fd) == SOCK_DGRAM)
4065 SetLastError(WSAENOPROTOOPT);
4066 ret = SOCKET_ERROR;
4068 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
4070 SetLastError(wsaErrno());
4071 ret = SOCKET_ERROR;
4073 else
4075 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
4076 ((LINGER *)optval)->l_linger = lingval.l_linger;
4077 *optlen = sizeof(struct linger);
4080 release_sock_fd( s, fd );
4081 return ret;
4084 case WS_SO_MAX_MSG_SIZE:
4085 if (!optlen || *optlen < sizeof(int) || !optval)
4087 SetLastError(WSAEFAULT);
4088 return SOCKET_ERROR;
4090 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
4091 *(int *)optval = 65507;
4092 *optlen = sizeof(int);
4093 return 0;
4095 /* SO_OPENTYPE does not require a valid socket handle. */
4096 case WS_SO_OPENTYPE:
4097 if (!optlen || *optlen < sizeof(int) || !optval)
4099 SetLastError(WSAEFAULT);
4100 return SOCKET_ERROR;
4102 *(int *)optval = get_per_thread_data()->opentype;
4103 *optlen = sizeof(int);
4104 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
4105 return 0;
4106 case WS_SO_PROTOCOL_INFOA:
4107 case WS_SO_PROTOCOL_INFOW:
4109 int size;
4110 WSAPROTOCOL_INFOW infow;
4112 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
4113 if (ret)
4115 if (!optlen || !optval || *optlen < size)
4117 if(optlen) *optlen = size;
4118 ret = 0;
4119 SetLastError(WSAEFAULT);
4121 else
4122 memcpy(optval, &infow, size);
4124 return ret ? 0 : SOCKET_ERROR;
4126 case WS_SO_RCVTIMEO:
4127 case WS_SO_SNDTIMEO:
4129 INT64 timeout;
4131 if (!optlen || *optlen < sizeof(int)|| !optval)
4133 SetLastError(WSAEFAULT);
4134 return SOCKET_ERROR;
4136 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4137 return SOCKET_ERROR;
4139 timeout = get_rcvsnd_timeo(fd, optname == WS_SO_RCVTIMEO);
4140 *(int *)optval = timeout <= UINT_MAX ? timeout : UINT_MAX;
4142 release_sock_fd( s, fd );
4143 return ret;
4145 case WS_SO_TYPE:
4147 int sock_type;
4148 if (!optlen || *optlen < sizeof(int) || !optval)
4150 SetLastError(WSAEFAULT);
4151 return SOCKET_ERROR;
4153 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4154 return SOCKET_ERROR;
4156 sock_type = _get_fd_type(fd);
4157 if (sock_type == -1)
4159 SetLastError(wsaErrno());
4160 ret = SOCKET_ERROR;
4162 else
4163 (*(int *)optval) = convert_socktype_u2w(sock_type);
4165 release_sock_fd( s, fd );
4166 return ret;
4168 default:
4169 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4170 SetLastError(WSAENOPROTOOPT);
4171 return SOCKET_ERROR;
4172 } /* end switch(optname) */
4173 }/* end case WS_SOL_SOCKET */
4174 #ifdef HAS_IPX
4175 case WS_NSPROTO_IPX:
4177 struct WS_sockaddr_ipx addr;
4178 IPX_ADDRESS_DATA *data;
4179 int namelen;
4180 switch(optname)
4182 case WS_IPX_PTYPE:
4183 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4184 #ifdef SOL_IPX
4185 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
4187 ret = SOCKET_ERROR;
4189 #else
4191 struct ipx val;
4192 socklen_t len=sizeof(struct ipx);
4193 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
4194 ret = SOCKET_ERROR;
4195 else
4196 *optval = (int)val.ipx_pt;
4198 #endif
4199 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
4200 release_sock_fd( s, fd );
4201 return ret;
4203 case WS_IPX_ADDRESS:
4205 * On a Win2000 system with one network card there are usually
4206 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
4207 * Using this call you can then retrieve info about this all.
4208 * In case of Linux it is a bit different. Usually you have
4209 * only "one" device active and further it is not possible to
4210 * query things like the linkspeed.
4212 FIXME("IPX_ADDRESS\n");
4213 namelen = sizeof(struct WS_sockaddr_ipx);
4214 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
4215 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
4217 data = (IPX_ADDRESS_DATA*)optval;
4218 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
4219 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
4220 data->adapternum = 0;
4221 data->wan = FALSE; /* We are not on a wan for now .. */
4222 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
4223 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
4224 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
4225 * note 1MB = 1000kB in this case */
4226 return 0;
4228 case WS_IPX_MAX_ADAPTER_NUM:
4229 FIXME("IPX_MAX_ADAPTER_NUM\n");
4230 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
4231 return 0;
4233 default:
4234 FIXME("IPX optname:%x\n", optname);
4235 return SOCKET_ERROR;
4236 }/* end switch(optname) */
4237 } /* end case WS_NSPROTO_IPX */
4238 #endif
4240 #ifdef HAS_IRDA
4241 #define MAX_IRDA_DEVICES 10
4243 case WS_SOL_IRLMP:
4244 switch(optname)
4246 case WS_IRLMP_ENUMDEVICES:
4248 char buf[sizeof(struct irda_device_list) +
4249 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
4250 int res;
4251 socklen_t len = sizeof(buf);
4253 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4254 return SOCKET_ERROR;
4255 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
4256 release_sock_fd( s, fd );
4257 if (res < 0)
4259 SetLastError(wsaErrno());
4260 return SOCKET_ERROR;
4262 else
4264 struct irda_device_list *src = (struct irda_device_list *)buf;
4265 DEVICELIST *dst = (DEVICELIST *)optval;
4266 INT needed = sizeof(DEVICELIST);
4267 unsigned int i;
4269 if (src->len > 0)
4270 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
4271 if (*optlen < needed)
4273 SetLastError(WSAEFAULT);
4274 return SOCKET_ERROR;
4276 *optlen = needed;
4277 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
4278 dst->numDevice = src->len;
4279 for (i = 0; i < src->len; i++)
4281 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
4282 src->dev[i].saddr, src->dev[i].daddr,
4283 src->dev[i].info, src->dev[i].hints[0],
4284 src->dev[i].hints[1]);
4285 memcpy( dst->Device[i].irdaDeviceID,
4286 &src->dev[i].daddr,
4287 sizeof(dst->Device[i].irdaDeviceID) ) ;
4288 memcpy( dst->Device[i].irdaDeviceName,
4289 src->dev[i].info,
4290 sizeof(dst->Device[i].irdaDeviceName) ) ;
4291 memcpy( &dst->Device[i].irdaDeviceHints1,
4292 &src->dev[i].hints[0],
4293 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
4294 memcpy( &dst->Device[i].irdaDeviceHints2,
4295 &src->dev[i].hints[1],
4296 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
4297 dst->Device[i].irdaCharSet = src->dev[i].charset;
4299 return 0;
4302 default:
4303 FIXME("IrDA optname:0x%x\n", optname);
4304 return SOCKET_ERROR;
4306 break; /* case WS_SOL_IRLMP */
4307 #undef MAX_IRDA_DEVICES
4308 #endif
4310 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4311 case WS_IPPROTO_TCP:
4312 switch(optname)
4314 case WS_TCP_NODELAY:
4315 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4316 return SOCKET_ERROR;
4317 convert_sockopt(&level, &optname);
4318 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4320 SetLastError(wsaErrno());
4321 ret = SOCKET_ERROR;
4323 release_sock_fd( s, fd );
4324 return ret;
4326 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4327 return SOCKET_ERROR;
4329 case WS_IPPROTO_IP:
4330 switch(optname)
4332 case WS_IP_ADD_MEMBERSHIP:
4333 case WS_IP_DROP_MEMBERSHIP:
4334 #ifdef IP_HDRINCL
4335 case WS_IP_HDRINCL:
4336 #endif
4337 case WS_IP_MULTICAST_IF:
4338 case WS_IP_MULTICAST_LOOP:
4339 case WS_IP_MULTICAST_TTL:
4340 case WS_IP_OPTIONS:
4341 #if defined(IP_PKTINFO) || defined(IP_RECVDSTADDR)
4342 case WS_IP_PKTINFO:
4343 #endif
4344 case WS_IP_TOS:
4345 case WS_IP_TTL:
4346 #ifdef IP_UNICAST_IF
4347 case WS_IP_UNICAST_IF:
4348 #endif
4349 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4350 return SOCKET_ERROR;
4351 convert_sockopt(&level, &optname);
4352 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4354 SetLastError(wsaErrno());
4355 ret = SOCKET_ERROR;
4357 release_sock_fd( s, fd );
4358 return ret;
4359 case WS_IP_DONTFRAGMENT:
4360 return get_dont_fragment(s, IPPROTO_IP, (BOOL *)optval) ? 0 : SOCKET_ERROR;
4362 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4363 return SOCKET_ERROR;
4365 case WS_IPPROTO_IPV6:
4366 switch(optname)
4368 #ifdef IPV6_ADD_MEMBERSHIP
4369 case WS_IPV6_ADD_MEMBERSHIP:
4370 #endif
4371 #ifdef IPV6_DROP_MEMBERSHIP
4372 case WS_IPV6_DROP_MEMBERSHIP:
4373 #endif
4374 case WS_IPV6_MULTICAST_IF:
4375 case WS_IPV6_MULTICAST_HOPS:
4376 case WS_IPV6_MULTICAST_LOOP:
4377 case WS_IPV6_UNICAST_HOPS:
4378 case WS_IPV6_V6ONLY:
4379 #ifdef IPV6_UNICAST_IF
4380 case WS_IPV6_UNICAST_IF:
4381 #endif
4382 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4383 return SOCKET_ERROR;
4384 convert_sockopt(&level, &optname);
4385 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4387 SetLastError(wsaErrno());
4388 ret = SOCKET_ERROR;
4390 release_sock_fd( s, fd );
4391 return ret;
4392 case WS_IPV6_DONTFRAG:
4393 return get_dont_fragment(s, IPPROTO_IPV6, (BOOL *)optval) ? 0 : SOCKET_ERROR;
4395 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4396 return SOCKET_ERROR;
4398 default:
4399 WARN("Unknown level: 0x%08x\n", level);
4400 SetLastError(WSAEINVAL);
4401 return SOCKET_ERROR;
4402 } /* end switch(level) */
4405 /***********************************************************************
4406 * htonl (WS2_32.8)
4408 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
4410 return htonl(hostlong);
4414 /***********************************************************************
4415 * htons (WS2_32.9)
4417 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
4419 return htons(hostshort);
4422 /***********************************************************************
4423 * WSAHtonl (WS2_32.46)
4424 * From MSDN description of error codes, this function should also
4425 * check if WinSock has been initialized and the socket is a valid
4426 * socket. But why? This function only translates a host byte order
4427 * u_long into a network byte order u_long...
4429 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
4431 if (lpnetlong)
4433 *lpnetlong = htonl(hostlong);
4434 return 0;
4436 SetLastError(WSAEFAULT);
4437 return SOCKET_ERROR;
4440 /***********************************************************************
4441 * WSAHtons (WS2_32.47)
4442 * From MSDN description of error codes, this function should also
4443 * check if WinSock has been initialized and the socket is a valid
4444 * socket. But why? This function only translates a host byte order
4445 * u_short into a network byte order u_short...
4447 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
4450 if (lpnetshort)
4452 *lpnetshort = htons(hostshort);
4453 return 0;
4455 SetLastError(WSAEFAULT);
4456 return SOCKET_ERROR;
4460 /***********************************************************************
4461 * inet_addr (WS2_32.11)
4463 WS_u_long WINAPI WS_inet_addr(const char *cp)
4465 if (!cp) return INADDR_NONE;
4466 return inet_addr(cp);
4470 /***********************************************************************
4471 * ntohl (WS2_32.14)
4473 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
4475 return ntohl(netlong);
4479 /***********************************************************************
4480 * ntohs (WS2_32.15)
4482 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
4484 return ntohs(netshort);
4488 /***********************************************************************
4489 * inet_ntoa (WS2_32.12)
4491 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
4493 unsigned int long_ip = ntohl(in.WS_s_addr);
4494 struct per_thread_data *data = get_per_thread_data();
4496 sprintf( data->ntoa_buffer, "%u.%u.%u.%u",
4497 (long_ip >> 24) & 0xff,
4498 (long_ip >> 16) & 0xff,
4499 (long_ip >> 8) & 0xff,
4500 long_ip & 0xff);
4502 return data->ntoa_buffer;
4505 static const char *debugstr_wsaioctl(DWORD code)
4507 const char *name = NULL, *buf_type, *family;
4509 #define IOCTL_NAME(x) case x: name = #x; break
4510 switch (code)
4512 IOCTL_NAME(WS_FIONBIO);
4513 IOCTL_NAME(WS_FIONREAD);
4514 IOCTL_NAME(WS_SIOCATMARK);
4515 /* IOCTL_NAME(WS_SIO_ACQUIRE_PORT_RESERVATION); */
4516 IOCTL_NAME(WS_SIO_ADDRESS_LIST_CHANGE);
4517 IOCTL_NAME(WS_SIO_ADDRESS_LIST_QUERY);
4518 IOCTL_NAME(WS_SIO_ASSOCIATE_HANDLE);
4519 /* IOCTL_NAME(WS_SIO_ASSOCIATE_PORT_RESERVATION);
4520 IOCTL_NAME(WS_SIO_BASE_HANDLE);
4521 IOCTL_NAME(WS_SIO_BSP_HANDLE);
4522 IOCTL_NAME(WS_SIO_BSP_HANDLE_SELECT);
4523 IOCTL_NAME(WS_SIO_BSP_HANDLE_POLL);
4524 IOCTL_NAME(WS_SIO_CHK_QOS); */
4525 IOCTL_NAME(WS_SIO_ENABLE_CIRCULAR_QUEUEING);
4526 IOCTL_NAME(WS_SIO_FIND_ROUTE);
4527 IOCTL_NAME(WS_SIO_FLUSH);
4528 IOCTL_NAME(WS_SIO_GET_BROADCAST_ADDRESS);
4529 IOCTL_NAME(WS_SIO_GET_EXTENSION_FUNCTION_POINTER);
4530 IOCTL_NAME(WS_SIO_GET_GROUP_QOS);
4531 IOCTL_NAME(WS_SIO_GET_INTERFACE_LIST);
4532 /* IOCTL_NAME(WS_SIO_GET_INTERFACE_LIST_EX); */
4533 IOCTL_NAME(WS_SIO_GET_QOS);
4534 /* IOCTL_NAME(WS_SIO_IDEAL_SEND_BACKLOG_CHANGE);
4535 IOCTL_NAME(WS_SIO_IDEAL_SEND_BACKLOG_QUERY); */
4536 IOCTL_NAME(WS_SIO_KEEPALIVE_VALS);
4537 IOCTL_NAME(WS_SIO_MULTIPOINT_LOOPBACK);
4538 IOCTL_NAME(WS_SIO_MULTICAST_SCOPE);
4539 /* IOCTL_NAME(WS_SIO_QUERY_RSS_SCALABILITY_INFO);
4540 IOCTL_NAME(WS_SIO_QUERY_WFP_ALE_ENDPOINT_HANDLE); */
4541 IOCTL_NAME(WS_SIO_RCVALL);
4542 IOCTL_NAME(WS_SIO_RCVALL_IGMPMCAST);
4543 IOCTL_NAME(WS_SIO_RCVALL_MCAST);
4544 /* IOCTL_NAME(WS_SIO_RELEASE_PORT_RESERVATION); */
4545 IOCTL_NAME(WS_SIO_ROUTING_INTERFACE_CHANGE);
4546 IOCTL_NAME(WS_SIO_ROUTING_INTERFACE_QUERY);
4547 IOCTL_NAME(WS_SIO_SET_COMPATIBILITY_MODE);
4548 IOCTL_NAME(WS_SIO_SET_GROUP_QOS);
4549 IOCTL_NAME(WS_SIO_SET_QOS);
4550 IOCTL_NAME(WS_SIO_TRANSLATE_HANDLE);
4551 IOCTL_NAME(WS_SIO_UDP_CONNRESET);
4553 #undef IOCTL_NAME
4555 if (name)
4556 return name + 3;
4558 /* If this is not a known code split its bits */
4559 switch(code & 0x18000000)
4561 case WS_IOC_WS2:
4562 family = "IOC_WS2";
4563 break;
4564 case WS_IOC_PROTOCOL:
4565 family = "IOC_PROTOCOL";
4566 break;
4567 case WS_IOC_VENDOR:
4568 family = "IOC_VENDOR";
4569 break;
4570 default: /* WS_IOC_UNIX */
4572 BYTE size = (code >> 16) & WS_IOCPARM_MASK;
4573 char x = (code & 0xff00) >> 8;
4574 BYTE y = code & 0xff;
4575 char args[14];
4577 switch (code & (WS_IOC_VOID|WS_IOC_INOUT))
4579 case WS_IOC_VOID:
4580 buf_type = "_IO";
4581 sprintf(args, "%d, %d", x, y);
4582 break;
4583 case WS_IOC_IN:
4584 buf_type = "_IOW";
4585 sprintf(args, "'%c', %d, %d", x, y, size);
4586 break;
4587 case WS_IOC_OUT:
4588 buf_type = "_IOR";
4589 sprintf(args, "'%c', %d, %d", x, y, size);
4590 break;
4591 default:
4592 buf_type = "?";
4593 sprintf(args, "'%c', %d, %d", x, y, size);
4594 break;
4596 return wine_dbg_sprintf("%s(%s)", buf_type, args);
4600 /* We are different from WS_IOC_UNIX. */
4601 switch (code & (WS_IOC_VOID|WS_IOC_INOUT))
4603 case WS_IOC_VOID:
4604 buf_type = "_WSAIO";
4605 break;
4606 case WS_IOC_INOUT:
4607 buf_type = "_WSAIORW";
4608 break;
4609 case WS_IOC_IN:
4610 buf_type = "_WSAIOW";
4611 break;
4612 case WS_IOC_OUT:
4613 buf_type = "_WSAIOR";
4614 break;
4615 default:
4616 buf_type = "?";
4617 break;
4620 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
4621 (USHORT)(code & 0xffff));
4624 /* do an ioctl call through the server */
4625 static DWORD server_ioctl_sock( SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size,
4626 LPVOID out_buff, DWORD out_size, LPDWORD ret_size,
4627 LPWSAOVERLAPPED overlapped,
4628 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4630 HANDLE event = overlapped ? overlapped->hEvent : 0;
4631 HANDLE handle = SOCKET2HANDLE( s );
4632 struct ws2_async *wsa = NULL;
4633 IO_STATUS_BLOCK *io = (PIO_STATUS_BLOCK)overlapped, iosb;
4634 void *cvalue = NULL;
4635 NTSTATUS status;
4637 if (completion)
4639 if (!(wsa = (struct ws2_async *)alloc_async_io( sizeof(*wsa), NULL )))
4640 return WSA_NOT_ENOUGH_MEMORY;
4641 wsa->hSocket = handle;
4642 wsa->user_overlapped = overlapped;
4643 wsa->completion_func = completion;
4644 if (!io) io = &wsa->local_iosb;
4645 cvalue = wsa;
4647 else if (!io)
4648 io = &iosb;
4649 else if (!((ULONG_PTR)overlapped->hEvent & 1))
4650 cvalue = overlapped;
4652 status = NtDeviceIoControlFile( handle, event, wsa ? ws2_async_apc : NULL, cvalue, io, code,
4653 in_buff, in_size, out_buff, out_size );
4654 if (status == STATUS_NOT_SUPPORTED)
4656 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
4657 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
4659 else if (status == STATUS_SUCCESS)
4660 *ret_size = io->Information; /* "Information" is the size written to the output buffer */
4662 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, wsa );
4664 return NtStatusToWSAError( status );
4667 /**********************************************************************
4668 * WSAIoctl (WS2_32.50)
4671 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
4672 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
4673 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4675 int fd;
4676 DWORD status = 0, total = 0;
4678 TRACE("%04lx, %s, %p, %d, %p, %d, %p, %p, %p\n",
4679 s, debugstr_wsaioctl(code), in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
4681 switch (code)
4683 case WS_FIONBIO:
4684 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
4686 SetLastError(WSAEFAULT);
4687 return SOCKET_ERROR;
4689 TRACE("-> FIONBIO (%x)\n", *(WS_u_long*)in_buff);
4690 if (_get_sock_mask(s))
4692 /* AsyncSelect()'ed sockets are always nonblocking */
4693 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
4694 break;
4696 if (*(WS_u_long *)in_buff)
4697 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
4698 else
4699 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
4700 break;
4702 case WS_FIONREAD:
4704 #if defined(linux)
4705 int listening = 0;
4706 socklen_t len = sizeof(listening);
4707 #endif
4708 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4710 SetLastError(WSAEFAULT);
4711 return SOCKET_ERROR;
4713 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4715 #if defined(linux)
4716 /* On Linux, FIONREAD on listening socket always fails (see tcp(7)).
4717 However, it succeeds on native. */
4718 if (!getsockopt( fd, SOL_SOCKET, SO_ACCEPTCONN, &listening, &len ) && listening)
4719 (*(WS_u_long *) out_buff) = 0;
4720 else
4721 #endif
4722 if (ioctl(fd, FIONREAD, out_buff ) == -1)
4723 status = wsaErrno();
4724 release_sock_fd( s, fd );
4725 break;
4728 case WS_SIOCATMARK:
4730 unsigned int oob = 0, atmark = 0;
4731 socklen_t oobsize = sizeof(int);
4732 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4734 SetLastError(WSAEFAULT);
4735 return SOCKET_ERROR;
4737 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4738 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
4739 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
4740 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
4741 status = wsaErrno();
4742 else
4744 /* The SIOCATMARK value read from ioctl() is reversed
4745 * because BSD returns TRUE if it's in the OOB mark
4746 * while Windows returns TRUE if there are NO OOB bytes.
4748 (*(WS_u_long *) out_buff) = oob || !atmark;
4751 release_sock_fd( s, fd );
4752 break;
4755 case WS_FIOASYNC:
4756 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
4757 SetLastError(WSAEINVAL);
4758 return SOCKET_ERROR;
4760 case WS_SIO_GET_INTERFACE_LIST:
4762 INTERFACE_INFO* intArray = out_buff;
4763 DWORD size, numInt = 0, apiReturn;
4765 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
4767 if (!out_buff || !ret_size)
4769 SetLastError(WSAEFAULT);
4770 return SOCKET_ERROR;
4773 fd = get_sock_fd( s, 0, NULL );
4774 if (fd == -1) return SOCKET_ERROR;
4776 apiReturn = GetAdaptersInfo(NULL, &size);
4777 if (apiReturn == ERROR_BUFFER_OVERFLOW)
4779 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
4781 if (table)
4783 if (GetAdaptersInfo(table, &size) == NO_ERROR)
4785 PIP_ADAPTER_INFO ptr;
4787 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
4789 unsigned int addr, mask, bcast;
4790 struct ifreq ifInfo;
4792 /* Skip interfaces without an IPv4 address. */
4793 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
4794 continue;
4796 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
4798 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
4799 status = WSAEFAULT;
4800 break;
4803 /* Socket Status Flags */
4804 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
4805 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
4807 ERR("Error obtaining status flags for socket!\n");
4808 status = WSAEINVAL;
4809 break;
4811 else
4813 /* set flags; the values of IFF_* are not the same
4814 under Linux and Windows, therefore must generate
4815 new flags */
4816 intArray->iiFlags = 0;
4817 if (ifInfo.ifr_flags & IFF_BROADCAST)
4818 intArray->iiFlags |= WS_IFF_BROADCAST;
4819 #ifdef IFF_POINTOPOINT
4820 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
4821 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
4822 #endif
4823 if (ifInfo.ifr_flags & IFF_LOOPBACK)
4824 intArray->iiFlags |= WS_IFF_LOOPBACK;
4825 if (ifInfo.ifr_flags & IFF_UP)
4826 intArray->iiFlags |= WS_IFF_UP;
4827 if (ifInfo.ifr_flags & IFF_MULTICAST)
4828 intArray->iiFlags |= WS_IFF_MULTICAST;
4831 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
4832 mask = inet_addr(ptr->IpAddressList.IpMask.String);
4833 bcast = addr | ~mask;
4834 intArray->iiAddress.AddressIn.sin_family = WS_AF_INET;
4835 intArray->iiAddress.AddressIn.sin_port = 0;
4836 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr = addr;
4838 intArray->iiNetmask.AddressIn.sin_family = WS_AF_INET;
4839 intArray->iiNetmask.AddressIn.sin_port = 0;
4840 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr = mask;
4842 intArray->iiBroadcastAddress.AddressIn.sin_family = WS_AF_INET;
4843 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
4844 intArray->iiBroadcastAddress.AddressIn.sin_addr.WS_s_addr = bcast;
4845 intArray++;
4846 numInt++;
4849 else
4851 ERR("Unable to get interface table!\n");
4852 status = WSAEINVAL;
4854 HeapFree(GetProcessHeap(),0,table);
4856 else status = WSAEINVAL;
4858 else if (apiReturn != ERROR_NO_DATA)
4860 ERR("Unable to get interface table!\n");
4861 status = WSAEINVAL;
4863 /* Calculate the size of the array being returned */
4864 total = sizeof(INTERFACE_INFO) * numInt;
4865 release_sock_fd( s, fd );
4866 break;
4869 case WS_SIO_ADDRESS_LIST_QUERY:
4871 DWORD size;
4873 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
4875 if (!ret_size)
4877 SetLastError(WSAEFAULT);
4878 return SOCKET_ERROR;
4881 if (out_size && out_size < FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[0]))
4883 *ret_size = 0;
4884 SetLastError(WSAEINVAL);
4885 return SOCKET_ERROR;
4888 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
4890 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
4891 SOCKET_ADDRESS_LIST *sa_list;
4892 SOCKADDR_IN *sockaddr;
4893 SOCKET_ADDRESS *sa;
4894 unsigned int i;
4895 DWORD num;
4897 if (!table || GetAdaptersInfo(table, &size))
4899 HeapFree(GetProcessHeap(), 0, table);
4900 status = WSAEINVAL;
4901 break;
4904 for (p = table, num = 0; p; p = p->Next)
4905 if (p->IpAddressList.IpAddress.String[0]) num++;
4907 total = FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[num]) + num * sizeof(*sockaddr);
4908 if (total > out_size || !out_buff)
4910 *ret_size = total;
4911 HeapFree(GetProcessHeap(), 0, table);
4912 status = WSAEFAULT;
4913 break;
4916 sa_list = out_buff;
4917 sa = sa_list->Address;
4918 sockaddr = (SOCKADDR_IN *)&sa[num];
4919 sa_list->iAddressCount = num;
4921 for (p = table, i = 0; p; p = p->Next)
4923 if (!p->IpAddressList.IpAddress.String[0]) continue;
4925 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
4926 sa[i].iSockaddrLength = sizeof(SOCKADDR);
4928 sockaddr[i].sin_family = WS_AF_INET;
4929 sockaddr[i].sin_port = 0;
4930 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
4931 i++;
4934 HeapFree(GetProcessHeap(), 0, table);
4936 else
4938 WARN("unable to get IP address list\n");
4939 status = WSAEINVAL;
4941 break;
4944 case WS_SIO_FLUSH:
4945 FIXME("SIO_FLUSH: stub.\n");
4946 break;
4948 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
4950 #define EXTENSION_FUNCTION(x, y) { x, y, #y },
4951 static const struct
4953 GUID guid;
4954 void *func_ptr;
4955 const char *name;
4956 } guid_funcs[] = {
4957 EXTENSION_FUNCTION(WSAID_CONNECTEX, WS2_ConnectEx)
4958 EXTENSION_FUNCTION(WSAID_DISCONNECTEX, WS2_DisconnectEx)
4959 EXTENSION_FUNCTION(WSAID_ACCEPTEX, WS2_AcceptEx)
4960 EXTENSION_FUNCTION(WSAID_GETACCEPTEXSOCKADDRS, WS2_GetAcceptExSockaddrs)
4961 EXTENSION_FUNCTION(WSAID_TRANSMITFILE, WS2_TransmitFile)
4962 /* EXTENSION_FUNCTION(WSAID_TRANSMITPACKETS, WS2_TransmitPackets) */
4963 EXTENSION_FUNCTION(WSAID_WSARECVMSG, WS2_WSARecvMsg)
4964 EXTENSION_FUNCTION(WSAID_WSASENDMSG, WSASendMsg)
4966 #undef EXTENSION_FUNCTION
4967 BOOL found = FALSE;
4968 unsigned int i;
4970 for (i = 0; i < ARRAY_SIZE(guid_funcs); i++)
4972 if (IsEqualGUID(&guid_funcs[i].guid, in_buff))
4974 found = TRUE;
4975 break;
4979 if (found)
4981 TRACE("-> got %s\n", guid_funcs[i].name);
4982 *(void **)out_buff = guid_funcs[i].func_ptr;
4983 total = sizeof(void *);
4984 break;
4987 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
4988 status = WSAEOPNOTSUPP;
4989 break;
4991 case WS_SIO_KEEPALIVE_VALS:
4993 struct tcp_keepalive *k;
4994 int keepalive, keepidle, keepintvl;
4996 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
4998 SetLastError(WSAEFAULT);
4999 return SOCKET_ERROR;
5002 k = in_buff;
5003 keepalive = k->onoff ? 1 : 0;
5004 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
5005 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
5007 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
5009 fd = get_sock_fd(s, 0, NULL);
5010 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
5011 status = WSAEINVAL;
5012 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPINTVL)
5013 /* these values need to be set only if SO_KEEPALIVE is enabled */
5014 else if(keepalive)
5016 #ifndef TCP_KEEPIDLE
5017 FIXME("ignoring keepalive timeout\n");
5018 #else
5019 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
5020 status = WSAEINVAL;
5021 else
5022 #endif
5023 #ifdef TCP_KEEPINTVL
5024 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
5025 status = WSAEINVAL;
5026 #else
5027 FIXME("ignoring keepalive interval\n");
5028 #endif
5030 #else
5031 else
5032 FIXME("ignoring keepalive interval and timeout\n");
5033 #endif
5034 release_sock_fd(s, fd);
5035 break;
5037 case WS_SIO_ROUTING_INTERFACE_QUERY:
5039 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
5040 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
5041 struct WS_sockaddr_in *saddr_in = out_buff;
5042 MIB_IPFORWARDROW row;
5043 PMIB_IPADDRTABLE ipAddrTable = NULL;
5044 DWORD size, i, found_index;
5046 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
5048 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
5049 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
5051 SetLastError(WSAEFAULT);
5052 return SOCKET_ERROR;
5054 if (daddr->sa_family != WS_AF_INET)
5056 FIXME("unsupported address family %d\n", daddr->sa_family);
5057 status = WSAEAFNOSUPPORT;
5058 break;
5060 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
5061 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
5063 status = WSAEFAULT;
5064 break;
5066 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
5067 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
5069 HeapFree(GetProcessHeap(), 0, ipAddrTable);
5070 status = WSAEFAULT;
5071 break;
5073 for (i = 0, found_index = ipAddrTable->dwNumEntries;
5074 i < ipAddrTable->dwNumEntries; i++)
5076 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
5077 found_index = i;
5079 if (found_index == ipAddrTable->dwNumEntries)
5081 ERR("no matching IP address for interface %d\n",
5082 row.dwForwardIfIndex);
5083 HeapFree(GetProcessHeap(), 0, ipAddrTable);
5084 status = WSAEFAULT;
5085 break;
5087 saddr_in->sin_family = WS_AF_INET;
5088 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
5089 saddr_in->sin_port = 0;
5090 total = sizeof(struct WS_sockaddr_in);
5091 HeapFree(GetProcessHeap(), 0, ipAddrTable);
5092 break;
5094 case WS_SIO_SET_COMPATIBILITY_MODE:
5095 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
5096 status = WSAEOPNOTSUPP;
5097 break;
5098 case WS_SIO_UDP_CONNRESET:
5099 FIXME("WS_SIO_UDP_CONNRESET stub\n");
5100 break;
5101 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
5102 SetLastError(WSAEOPNOTSUPP);
5103 return SOCKET_ERROR;
5104 default:
5105 status = WSAEOPNOTSUPP;
5106 break;
5109 if (status == WSAEOPNOTSUPP)
5111 status = server_ioctl_sock(s, code, in_buff, in_size, out_buff, out_size, &total,
5112 overlapped, completion);
5113 if (status != WSAEOPNOTSUPP)
5115 if (status == 0 || status == WSA_IO_PENDING)
5116 TRACE("-> %s request\n", debugstr_wsaioctl(code));
5117 else
5118 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code), status);
5120 /* overlapped and completion operations will be handled by the server */
5121 completion = NULL;
5122 overlapped = NULL;
5124 else
5125 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
5128 if (completion)
5130 FIXME( "completion routine %p not supported\n", completion );
5132 else if (overlapped)
5134 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
5135 overlapped->Internal = sock_error_to_ntstatus( status );
5136 overlapped->InternalHigh = total;
5137 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, overlapped->Internal, total, FALSE );
5138 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
5141 if (!status)
5143 if (ret_size) *ret_size = total;
5144 return 0;
5146 SetLastError( status );
5147 return SOCKET_ERROR;
5151 /***********************************************************************
5152 * ioctlsocket (WS2_32.10)
5154 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
5156 DWORD ret_size;
5157 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
5160 /***********************************************************************
5161 * listen (WS2_32.13)
5163 int WINAPI WS_listen(SOCKET s, int backlog)
5165 int fd = get_sock_fd( s, FILE_READ_DATA, NULL ), ret = SOCKET_ERROR;
5167 TRACE("socket %04lx, backlog %d\n", s, backlog);
5168 if (fd != -1)
5170 int bound = is_fd_bound(fd, NULL, NULL);
5172 if (bound <= 0)
5174 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
5176 else if (listen(fd, backlog) == 0)
5178 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
5179 FD_WINE_LISTENING,
5180 FD_CONNECT|FD_WINE_CONNECTED);
5181 ret = 0;
5183 else
5184 SetLastError(wsaErrno());
5185 release_sock_fd( s, fd );
5187 else
5188 SetLastError(WSAENOTSOCK);
5189 return ret;
5192 /***********************************************************************
5193 * recv (WS2_32.16)
5195 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
5197 DWORD n, dwFlags = flags;
5198 WSABUF wsabuf;
5200 wsabuf.len = len;
5201 wsabuf.buf = buf;
5203 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
5204 return SOCKET_ERROR;
5205 else
5206 return n;
5209 /***********************************************************************
5210 * recvfrom (WS2_32.17)
5212 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
5213 struct WS_sockaddr *from, int *fromlen)
5215 DWORD n, dwFlags = flags;
5216 WSABUF wsabuf;
5218 wsabuf.len = len;
5219 wsabuf.buf = buf;
5221 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
5222 return SOCKET_ERROR;
5223 else
5224 return n;
5227 /* allocate a poll array for the corresponding fd sets */
5228 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
5229 const WS_fd_set *exceptfds, int *count_ptr )
5231 unsigned int i, j = 0, count = 0;
5232 struct pollfd *fds;
5233 struct per_thread_data *ptb = get_per_thread_data();
5235 if (readfds) count += readfds->fd_count;
5236 if (writefds) count += writefds->fd_count;
5237 if (exceptfds) count += exceptfds->fd_count;
5238 *count_ptr = count;
5239 if (!count)
5241 SetLastError(WSAEINVAL);
5242 return NULL;
5245 /* check if the cache can hold all descriptors, if not do the resizing */
5246 if (ptb->fd_count < count)
5248 if (!(fds = HeapAlloc(GetProcessHeap(), 0, count * sizeof(fds[0]))))
5250 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
5251 return NULL;
5253 HeapFree(GetProcessHeap(), 0, ptb->fd_cache);
5254 ptb->fd_cache = fds;
5255 ptb->fd_count = count;
5257 else
5258 fds = ptb->fd_cache;
5260 if (readfds)
5261 for (i = 0; i < readfds->fd_count; i++, j++)
5263 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
5264 if (fds[j].fd == -1) goto failed;
5265 fds[j].revents = 0;
5266 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
5268 fds[j].events = POLLIN;
5270 else
5272 release_sock_fd( readfds->fd_array[i], fds[j].fd );
5273 fds[j].fd = -1;
5274 fds[j].events = 0;
5277 if (writefds)
5278 for (i = 0; i < writefds->fd_count; i++, j++)
5280 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
5281 if (fds[j].fd == -1) goto failed;
5282 fds[j].revents = 0;
5283 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1 ||
5284 _get_fd_type(fds[j].fd) == SOCK_DGRAM)
5286 fds[j].events = POLLOUT;
5288 else
5290 release_sock_fd( writefds->fd_array[i], fds[j].fd );
5291 fds[j].fd = -1;
5292 fds[j].events = 0;
5295 if (exceptfds)
5296 for (i = 0; i < exceptfds->fd_count; i++, j++)
5298 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
5299 if (fds[j].fd == -1) goto failed;
5300 fds[j].revents = 0;
5301 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
5303 int oob_inlined = 0;
5304 socklen_t olen = sizeof(oob_inlined);
5306 fds[j].events = POLLHUP;
5308 /* Check if we need to test for urgent data or not */
5309 getsockopt(fds[j].fd, SOL_SOCKET, SO_OOBINLINE, (char*) &oob_inlined, &olen);
5310 if (!oob_inlined)
5311 fds[j].events |= POLLPRI;
5313 else
5315 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5316 fds[j].fd = -1;
5317 fds[j].events = 0;
5320 return fds;
5322 failed:
5323 count = j;
5324 j = 0;
5325 if (readfds)
5326 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
5327 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
5328 if (writefds)
5329 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
5330 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
5331 if (exceptfds)
5332 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
5333 if (fds[j].fd != -1) release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5334 return NULL;
5337 /* release the file descriptor obtained in fd_sets_to_poll */
5338 /* must be called with the original fd_set arrays, before calling get_poll_results */
5339 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
5340 const WS_fd_set *exceptfds, struct pollfd *fds )
5342 unsigned int i, j = 0;
5344 if (readfds)
5346 for (i = 0; i < readfds->fd_count; i++, j++)
5347 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
5349 if (writefds)
5351 for (i = 0; i < writefds->fd_count; i++, j++)
5352 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
5354 if (exceptfds)
5356 for (i = 0; i < exceptfds->fd_count; i++, j++)
5358 if (fds[j].fd == -1) continue;
5359 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5360 if (fds[j].revents & POLLHUP)
5362 int fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
5363 if (fd != -1)
5364 release_sock_fd( exceptfds->fd_array[i], fd );
5365 else
5366 fds[j].revents = 0;
5372 static int do_poll(struct pollfd *pollfds, int count, int timeout)
5374 struct timeval tv1, tv2;
5375 int ret, torig = timeout;
5377 if (timeout > 0) gettimeofday( &tv1, 0 );
5379 while ((ret = poll( pollfds, count, timeout )) < 0)
5381 if (errno != EINTR) break;
5382 if (timeout < 0) continue;
5383 if (timeout == 0) return 0;
5385 gettimeofday( &tv2, 0 );
5387 tv2.tv_sec -= tv1.tv_sec;
5388 tv2.tv_usec -= tv1.tv_usec;
5389 if (tv2.tv_usec < 0)
5391 tv2.tv_usec += 1000000;
5392 tv2.tv_sec -= 1;
5395 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
5396 if (timeout <= 0) return 0;
5398 return ret;
5401 /* map the poll results back into the Windows fd sets */
5402 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
5403 const struct pollfd *fds )
5405 const struct pollfd *poll_writefds = fds + (readfds ? readfds->fd_count : 0);
5406 const struct pollfd *poll_exceptfds = poll_writefds + (writefds ? writefds->fd_count : 0);
5407 unsigned int i, k, total = 0;
5409 if (readfds)
5411 for (i = k = 0; i < readfds->fd_count; i++)
5413 if (fds[i].revents ||
5414 (readfds == writefds && (poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
5415 (readfds == exceptfds && poll_exceptfds[i].revents))
5416 readfds->fd_array[k++] = readfds->fd_array[i];
5418 readfds->fd_count = k;
5419 total += k;
5421 if (writefds && writefds != readfds)
5423 for (i = k = 0; i < writefds->fd_count; i++)
5425 if (((poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
5426 (writefds == exceptfds && poll_exceptfds[i].revents))
5427 writefds->fd_array[k++] = writefds->fd_array[i];
5429 writefds->fd_count = k;
5430 total += k;
5432 if (exceptfds && exceptfds != readfds && exceptfds != writefds)
5434 for (i = k = 0; i < exceptfds->fd_count; i++)
5435 if (poll_exceptfds[i].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
5436 exceptfds->fd_count = k;
5437 total += k;
5439 return total;
5442 /***********************************************************************
5443 * select (WS2_32.18)
5445 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
5446 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
5447 const struct WS_timeval* ws_timeout)
5449 struct pollfd *pollfds;
5450 int count, ret, timeout = -1;
5452 TRACE("read %p, write %p, excp %p timeout %p\n",
5453 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
5455 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
5456 return SOCKET_ERROR;
5458 if (ws_timeout)
5459 timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
5461 ret = do_poll(pollfds, count, timeout);
5462 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
5464 if (ret == -1) SetLastError(wsaErrno());
5465 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
5466 return ret;
5469 /***********************************************************************
5470 * WSAPoll
5472 int WINAPI WSAPoll(WSAPOLLFD *wfds, ULONG count, int timeout)
5474 int i, ret;
5475 struct pollfd *ufds;
5477 if (!count)
5479 SetLastError(WSAEINVAL);
5480 return SOCKET_ERROR;
5482 if (!wfds)
5484 SetLastError(WSAEFAULT);
5485 return SOCKET_ERROR;
5488 if (!(ufds = HeapAlloc(GetProcessHeap(), 0, count * sizeof(ufds[0]))))
5490 SetLastError(WSAENOBUFS);
5491 return SOCKET_ERROR;
5494 for (i = 0; i < count; i++)
5496 ufds[i].fd = get_sock_fd(wfds[i].fd, 0, NULL);
5497 ufds[i].events = convert_poll_w2u(wfds[i].events);
5498 ufds[i].revents = 0;
5501 ret = do_poll(ufds, count, timeout);
5503 for (i = 0; i < count; i++)
5505 if (ufds[i].fd != -1)
5507 release_sock_fd(wfds[i].fd, ufds[i].fd);
5508 if (ufds[i].revents & POLLHUP)
5510 /* Check if the socket still exists */
5511 int fd = get_sock_fd(wfds[i].fd, 0, NULL);
5512 if (fd != -1)
5514 wfds[i].revents = WS_POLLHUP;
5515 release_sock_fd(wfds[i].fd, fd);
5517 else
5518 wfds[i].revents = WS_POLLNVAL;
5520 else
5521 wfds[i].revents = convert_poll_u2w(ufds[i].revents);
5523 else
5524 wfds[i].revents = WS_POLLNVAL;
5527 HeapFree(GetProcessHeap(), 0, ufds);
5528 return ret;
5531 /* helper to send completion messages for client-only i/o operation case */
5532 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
5533 ULONG Information, BOOL async )
5535 SERVER_START_REQ( add_fd_completion )
5537 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
5538 req->cvalue = CompletionValue;
5539 req->status = CompletionStatus;
5540 req->information = Information;
5541 req->async = async;
5542 wine_server_call( req );
5544 SERVER_END_REQ;
5548 /***********************************************************************
5549 * send (WS2_32.19)
5551 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
5553 DWORD n;
5554 WSABUF wsabuf;
5556 wsabuf.len = len;
5557 wsabuf.buf = (char*) buf;
5559 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
5560 return SOCKET_ERROR;
5561 else
5562 return n;
5565 /***********************************************************************
5566 * WSASend (WS2_32.72)
5568 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5569 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5570 LPWSAOVERLAPPED lpOverlapped,
5571 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5573 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
5574 NULL, 0, lpOverlapped, lpCompletionRoutine );
5577 /***********************************************************************
5578 * WSASendDisconnect (WS2_32.73)
5580 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
5582 return WS_shutdown( s, SD_SEND );
5586 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5587 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5588 const struct WS_sockaddr *to, int tolen,
5589 LPWSAOVERLAPPED lpOverlapped,
5590 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5592 unsigned int i, options;
5593 int n, fd, err, overlapped, flags;
5594 struct ws2_async *wsa = NULL, localwsa;
5595 int totalLength = 0;
5596 DWORD bytes_sent;
5597 BOOL is_blocking;
5599 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
5600 s, lpBuffers, dwBufferCount, dwFlags,
5601 to, tolen, lpOverlapped, lpCompletionRoutine);
5603 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
5604 TRACE( "fd=%d, options=%x\n", fd, options );
5606 if ( fd == -1 ) return SOCKET_ERROR;
5608 if (!lpOverlapped && !lpNumberOfBytesSent)
5610 err = WSAEFAULT;
5611 goto error;
5614 overlapped = (lpOverlapped || lpCompletionRoutine) &&
5615 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
5616 if (overlapped || dwBufferCount > 1)
5618 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]),
5619 WS2_async_send )))
5621 err = WSAEFAULT;
5622 goto error;
5625 else
5626 wsa = &localwsa;
5628 wsa->hSocket = SOCKET2HANDLE(s);
5629 wsa->addr = (struct WS_sockaddr *)to;
5630 wsa->addrlen.val = tolen;
5631 wsa->flags = dwFlags;
5632 wsa->lpFlags = &wsa->flags;
5633 wsa->control = NULL;
5634 wsa->n_iovecs = dwBufferCount;
5635 wsa->first_iovec = 0;
5636 for ( i = 0; i < dwBufferCount; i++ )
5638 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5639 wsa->iovec[i].iov_len = lpBuffers[i].len;
5640 totalLength += lpBuffers[i].len;
5643 flags = convert_flags(dwFlags);
5644 n = WS2_send( fd, wsa, flags );
5645 if (n == -1 && errno != EAGAIN)
5647 err = wsaErrno();
5648 goto error;
5651 if (overlapped)
5653 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5654 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5656 wsa->user_overlapped = lpOverlapped;
5657 wsa->completion_func = lpCompletionRoutine;
5658 release_sock_fd( s, fd );
5660 if (n == -1 || n < totalLength)
5662 iosb->u.Status = STATUS_PENDING;
5663 iosb->Information = n == -1 ? 0 : n;
5665 if (wsa->completion_func)
5666 err = register_async( ASYNC_TYPE_WRITE, wsa->hSocket, &wsa->io, NULL,
5667 ws2_async_apc, wsa, iosb );
5668 else
5669 err = register_async( ASYNC_TYPE_WRITE, wsa->hSocket, &wsa->io, lpOverlapped->hEvent,
5670 NULL, (void *)cvalue, iosb );
5672 /* Enable the event only after starting the async. The server will deliver it as soon as
5673 the async is done. */
5674 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5676 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5677 SetLastError(NtStatusToWSAError( err ));
5678 return SOCKET_ERROR;
5681 iosb->u.Status = STATUS_SUCCESS;
5682 iosb->Information = n;
5683 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
5684 if (!wsa->completion_func)
5686 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n, FALSE );
5687 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5688 HeapFree( GetProcessHeap(), 0, wsa );
5690 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5691 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5692 SetLastError(ERROR_SUCCESS);
5693 return 0;
5696 if ((err = sock_is_blocking( s, &is_blocking ))) goto error;
5698 if ( is_blocking )
5700 /* On a blocking non-overlapped stream socket,
5701 * sending blocks until the entire buffer is sent. */
5702 DWORD timeout_start = GetTickCount();
5704 bytes_sent = n == -1 ? 0 : n;
5706 while (wsa->first_iovec < wsa->n_iovecs)
5708 struct pollfd pfd;
5709 int poll_timeout = -1;
5710 INT64 timeout = get_rcvsnd_timeo(fd, FALSE);
5712 if (timeout)
5714 timeout -= GetTickCount() - timeout_start;
5715 if (timeout < 0) poll_timeout = 0;
5716 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
5719 pfd.fd = fd;
5720 pfd.events = POLLOUT;
5722 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
5724 err = WSAETIMEDOUT;
5725 goto error; /* msdn says a timeout in send is fatal */
5728 n = WS2_send( fd, wsa, flags );
5729 if (n == -1 && errno != EAGAIN)
5731 err = wsaErrno();
5732 goto error;
5735 if (n >= 0)
5736 bytes_sent += n;
5739 else /* non-blocking */
5741 if (n < totalLength)
5742 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5743 if (n == -1)
5745 err = WSAEWOULDBLOCK;
5746 goto error;
5748 bytes_sent = n;
5751 TRACE(" -> %i bytes\n", bytes_sent);
5753 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
5754 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5755 release_sock_fd( s, fd );
5756 SetLastError(ERROR_SUCCESS);
5757 return 0;
5759 error:
5760 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5761 release_sock_fd( s, fd );
5762 WARN(" -> ERROR %d\n", err);
5763 SetLastError(err);
5764 return SOCKET_ERROR;
5767 /***********************************************************************
5768 * WSASendTo (WS2_32.74)
5770 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5771 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5772 const struct WS_sockaddr *to, int tolen,
5773 LPWSAOVERLAPPED lpOverlapped,
5774 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5776 return WS2_sendto( s, lpBuffers, dwBufferCount,
5777 lpNumberOfBytesSent, dwFlags,
5778 to, tolen,
5779 lpOverlapped, lpCompletionRoutine );
5782 /***********************************************************************
5783 * sendto (WS2_32.20)
5785 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
5786 const struct WS_sockaddr *to, int tolen)
5788 DWORD n;
5789 WSABUF wsabuf;
5791 wsabuf.len = len;
5792 wsabuf.buf = (char*) buf;
5794 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
5795 return SOCKET_ERROR;
5796 else
5797 return n;
5800 /***********************************************************************
5801 * setsockopt (WS2_32.21)
5803 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
5804 const char *optval, int optlen)
5806 int fd;
5807 int woptval;
5808 struct linger linger;
5809 struct timeval tval;
5810 struct ip_mreq_source mreq_source;
5812 TRACE("(socket %04lx, %s, optval %s, optlen %d)\n", s,
5813 debugstr_sockopt(level, optname), debugstr_optval(optval, optlen),
5814 optlen);
5816 /* some broken apps pass the value directly instead of a pointer to it */
5817 if(optlen && IS_INTRESOURCE(optval))
5819 SetLastError(WSAEFAULT);
5820 return SOCKET_ERROR;
5823 switch(level)
5825 case WS_SOL_SOCKET:
5826 switch(optname)
5828 /* Some options need some conversion before they can be sent to
5829 * setsockopt. The conversions are done here, then they will fall through
5830 * to the general case. Special options that are not passed to
5831 * setsockopt follow below that.*/
5833 case WS_SO_DONTLINGER:
5834 if (!optval)
5836 SetLastError(WSAEFAULT);
5837 return SOCKET_ERROR;
5839 linger.l_onoff = *(const int*)optval == 0;
5840 linger.l_linger = 0;
5841 level = SOL_SOCKET;
5842 optname = SO_LINGER;
5843 optval = (char*)&linger;
5844 optlen = sizeof(struct linger);
5845 break;
5847 case WS_SO_LINGER:
5848 if (!optval)
5850 SetLastError(WSAEFAULT);
5851 return SOCKET_ERROR;
5853 linger.l_onoff = ((LINGER*)optval)->l_onoff;
5854 linger.l_linger = ((LINGER*)optval)->l_linger;
5855 level = SOL_SOCKET;
5856 optname = SO_LINGER;
5857 optval = (char*)&linger;
5858 optlen = sizeof(struct linger);
5859 break;
5861 case WS_SO_SNDBUF:
5862 if (!*(const int *)optval)
5864 FIXME("SO_SNDBUF ignoring request to disable send buffering\n");
5865 #ifdef __APPLE__
5866 return 0;
5867 #endif
5869 convert_sockopt(&level, &optname);
5870 break;
5872 case WS_SO_RCVBUF:
5873 if (*(const int*)optval < 2048)
5875 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
5876 return 0;
5878 /* Fall through */
5880 /* The options listed here don't need any special handling. Thanks to
5881 * the conversion happening above, options from there will fall through
5882 * to this, too.*/
5883 case WS_SO_ACCEPTCONN:
5884 case WS_SO_BROADCAST:
5885 case WS_SO_ERROR:
5886 case WS_SO_KEEPALIVE:
5887 case WS_SO_OOBINLINE:
5888 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
5889 * however, using it the BSD way fixes bug 8513 and seems to be what
5890 * most programmers assume, anyway */
5891 case WS_SO_REUSEADDR:
5892 case WS_SO_TYPE:
5893 convert_sockopt(&level, &optname);
5894 break;
5896 /* SO_DEBUG is a privileged operation, ignore it. */
5897 case WS_SO_DEBUG:
5898 TRACE("Ignoring SO_DEBUG\n");
5899 return 0;
5901 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
5902 * socket. According to MSDN, this option is silently ignored.*/
5903 case WS_SO_DONTROUTE:
5904 TRACE("Ignoring SO_DONTROUTE\n");
5905 return 0;
5907 /* Stops two sockets from being bound to the same port. Always happens
5908 * on unix systems, so just drop it. */
5909 case WS_SO_EXCLUSIVEADDRUSE:
5910 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
5911 return 0;
5913 /* After a ConnectEx call succeeds, the socket can't be used with half of the
5914 * normal winsock functions on windows. We don't have that problem. */
5915 case WS_SO_UPDATE_CONNECT_CONTEXT:
5916 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
5917 return 0;
5919 /* After a AcceptEx call succeeds, the socket can't be used with half of the
5920 * normal winsock functions on windows. We don't have that problem. */
5921 case WS_SO_UPDATE_ACCEPT_CONTEXT:
5922 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
5923 return 0;
5925 /* SO_OPENTYPE does not require a valid socket handle. */
5926 case WS_SO_OPENTYPE:
5927 if (!optlen || optlen < sizeof(int) || !optval)
5929 SetLastError(WSAEFAULT);
5930 return SOCKET_ERROR;
5932 get_per_thread_data()->opentype = *(const int *)optval;
5933 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
5934 return 0;
5936 #ifdef SO_RCVTIMEO
5937 case WS_SO_RCVTIMEO:
5938 #endif
5939 #ifdef SO_SNDTIMEO
5940 case WS_SO_SNDTIMEO:
5941 #endif
5942 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
5943 if (optval && optlen == sizeof(UINT32)) {
5944 /* WinSock passes milliseconds instead of struct timeval */
5945 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
5946 tval.tv_sec = *(const UINT32*)optval / 1000;
5947 /* min of 500 milliseconds */
5948 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
5949 tval.tv_usec = 500000;
5950 optlen = sizeof(struct timeval);
5951 optval = (char*)&tval;
5952 } else if (optlen == sizeof(struct timeval)) {
5953 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
5954 } else {
5955 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
5956 return 0;
5958 convert_sockopt(&level, &optname);
5959 break;
5960 #endif
5962 case WS_SO_RANDOMIZE_PORT:
5963 FIXME("Ignoring WS_SO_RANDOMIZE_PORT\n");
5964 return 0;
5966 case WS_SO_PORT_SCALABILITY:
5967 FIXME("Ignoring WS_SO_PORT_SCALABILITY\n");
5968 return 0;
5970 case WS_SO_REUSE_UNICASTPORT:
5971 FIXME("Ignoring WS_SO_REUSE_UNICASTPORT\n");
5972 return 0;
5974 case WS_SO_REUSE_MULTICASTPORT:
5975 FIXME("Ignoring WS_SO_REUSE_MULTICASTPORT\n");
5976 return 0;
5978 default:
5979 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
5980 SetLastError(WSAENOPROTOOPT);
5981 return SOCKET_ERROR;
5983 break; /* case WS_SOL_SOCKET */
5985 #ifdef HAS_IPX
5986 case WS_NSPROTO_IPX:
5987 switch(optname)
5989 case WS_IPX_PTYPE:
5990 return set_ipx_packettype(s, *(int*)optval);
5992 case WS_IPX_FILTERPTYPE:
5993 /* Sets the receive filter packet type, at the moment we don't support it */
5994 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
5995 /* Returning 0 is better for now than returning a SOCKET_ERROR */
5996 return 0;
5998 default:
5999 FIXME("opt_name:%x\n", optname);
6000 return SOCKET_ERROR;
6002 break; /* case WS_NSPROTO_IPX */
6003 #endif
6005 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
6006 case WS_IPPROTO_TCP:
6007 switch(optname)
6009 case WS_TCP_NODELAY:
6010 convert_sockopt(&level, &optname);
6011 break;
6012 default:
6013 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
6014 return SOCKET_ERROR;
6016 break;
6018 case WS_IPPROTO_IP:
6019 switch(optname)
6021 case WS_IP_ADD_SOURCE_MEMBERSHIP:
6022 case WS_IP_DROP_SOURCE_MEMBERSHIP:
6023 case WS_IP_BLOCK_SOURCE:
6024 case WS_IP_UNBLOCK_SOURCE:
6026 WS_IP_MREQ_SOURCE* val = (void*)optval;
6027 mreq_source.imr_interface.s_addr = val->imr_interface.S_un.S_addr;
6028 mreq_source.imr_multiaddr.s_addr = val->imr_multiaddr.S_un.S_addr;
6029 mreq_source.imr_sourceaddr.s_addr = val->imr_sourceaddr.S_un.S_addr;
6031 optval = (char*)&mreq_source;
6032 optlen = sizeof(mreq_source);
6034 convert_sockopt(&level, &optname);
6035 break;
6037 case WS_IP_ADD_MEMBERSHIP:
6038 case WS_IP_DROP_MEMBERSHIP:
6039 #ifdef IP_HDRINCL
6040 case WS_IP_HDRINCL:
6041 #endif
6042 case WS_IP_MULTICAST_IF:
6043 case WS_IP_MULTICAST_LOOP:
6044 case WS_IP_MULTICAST_TTL:
6045 case WS_IP_OPTIONS:
6046 #if defined(IP_PKTINFO) || defined(IP_RECVDSTADDR)
6047 case WS_IP_PKTINFO:
6048 #endif
6049 case WS_IP_TOS:
6050 case WS_IP_TTL:
6051 #ifdef IP_UNICAST_IF
6052 case WS_IP_UNICAST_IF:
6053 #endif
6054 convert_sockopt(&level, &optname);
6055 break;
6056 case WS_IP_DONTFRAGMENT:
6057 return set_dont_fragment(s, IPPROTO_IP, *(BOOL *)optval) ? 0 : SOCKET_ERROR;
6058 default:
6059 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
6060 return SOCKET_ERROR;
6062 break;
6064 case WS_IPPROTO_IPV6:
6065 switch(optname)
6067 #ifdef IPV6_ADD_MEMBERSHIP
6068 case WS_IPV6_ADD_MEMBERSHIP:
6069 #endif
6070 #ifdef IPV6_DROP_MEMBERSHIP
6071 case WS_IPV6_DROP_MEMBERSHIP:
6072 #endif
6073 case WS_IPV6_MULTICAST_IF:
6074 case WS_IPV6_MULTICAST_HOPS:
6075 case WS_IPV6_MULTICAST_LOOP:
6076 case WS_IPV6_UNICAST_HOPS:
6077 #ifdef IPV6_UNICAST_IF
6078 case WS_IPV6_UNICAST_IF:
6079 #endif
6080 convert_sockopt(&level, &optname);
6081 break;
6082 case WS_IPV6_DONTFRAG:
6083 return set_dont_fragment(s, IPPROTO_IPV6, *(BOOL *)optval) ? 0 : SOCKET_ERROR;
6084 case WS_IPV6_PROTECTION_LEVEL:
6085 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
6086 return 0;
6087 case WS_IPV6_V6ONLY:
6089 union generic_unix_sockaddr uaddr;
6090 socklen_t uaddrlen;
6091 int bound;
6093 fd = get_sock_fd( s, 0, NULL );
6094 if (fd == -1) return SOCKET_ERROR;
6096 bound = is_fd_bound(fd, &uaddr, &uaddrlen);
6097 release_sock_fd( s, fd );
6098 if (bound == 0 && uaddr.addr.sa_family == AF_INET)
6100 /* Changing IPV6_V6ONLY succeeds on AF_INET (IPv4) socket
6101 * on Windows (with IPv6 support) if the socket is unbound.
6102 * It is essentially a noop, though Windows does store the value
6104 WARN("Silently ignoring IPPROTO_IPV6+IPV6_V6ONLY on AF_INET socket\n");
6105 return 0;
6107 level = IPPROTO_IPV6;
6108 optname = IPV6_V6ONLY;
6109 break;
6111 default:
6112 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
6113 return SOCKET_ERROR;
6115 break;
6117 default:
6118 WARN("Unknown level: 0x%08x\n", level);
6119 SetLastError(WSAEINVAL);
6120 return SOCKET_ERROR;
6121 } /* end switch(level) */
6123 /* avoid endianness issues if argument is a 16-bit int */
6124 if (optval && optlen < sizeof(int))
6126 woptval= *((const INT16 *) optval);
6127 optval= (char*) &woptval;
6128 woptval&= (1 << optlen * 8) - 1;
6129 optlen=sizeof(int);
6131 fd = get_sock_fd( s, 0, NULL );
6132 if (fd == -1) return SOCKET_ERROR;
6134 if (setsockopt(fd, level, optname, optval, optlen) == 0)
6136 #ifdef __APPLE__
6137 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
6138 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
6140 SetLastError(wsaErrno());
6141 release_sock_fd( s, fd );
6142 return SOCKET_ERROR;
6144 #endif
6145 release_sock_fd( s, fd );
6146 return 0;
6148 TRACE("Setting socket error, %d\n", wsaErrno());
6149 SetLastError(wsaErrno());
6150 release_sock_fd( s, fd );
6152 return SOCKET_ERROR;
6155 /***********************************************************************
6156 * shutdown (WS2_32.22)
6158 int WINAPI WS_shutdown(SOCKET s, int how)
6160 int fd, err = WSAENOTSOCK;
6161 unsigned int options = 0, clear_flags = 0;
6163 fd = get_sock_fd( s, 0, &options );
6164 TRACE("socket %04lx, how 0x%x, options 0x%x\n", s, how, options );
6166 if (fd == -1)
6167 return SOCKET_ERROR;
6169 switch( how )
6171 case SD_RECEIVE: /* drop receives */
6172 clear_flags |= FD_READ;
6173 break;
6174 case SD_SEND: /* drop sends */
6175 clear_flags |= FD_WRITE;
6176 break;
6177 case SD_BOTH: /* drop all */
6178 clear_flags |= FD_READ|FD_WRITE;
6179 /*fall through */
6180 default:
6181 clear_flags |= FD_WINE_LISTENING;
6184 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
6186 switch ( how )
6188 case SD_RECEIVE:
6189 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
6190 break;
6191 case SD_SEND:
6192 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
6193 break;
6194 case SD_BOTH:
6195 default:
6196 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
6197 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
6198 break;
6200 if (err) goto error;
6202 else /* non-overlapped mode */
6204 if ( shutdown( fd, how ) )
6206 err = wsaErrno();
6207 goto error;
6211 release_sock_fd( s, fd );
6212 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
6213 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
6214 return 0;
6216 error:
6217 release_sock_fd( s, fd );
6218 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
6219 SetLastError( err );
6220 return SOCKET_ERROR;
6223 /***********************************************************************
6224 * socket (WS2_32.23)
6226 SOCKET WINAPI WS_socket(int af, int type, int protocol)
6228 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
6230 return WSASocketW( af, type, protocol, NULL, 0,
6231 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
6235 /***********************************************************************
6236 * gethostbyaddr (WS2_32.51)
6238 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
6240 struct WS_hostent *retval = NULL;
6241 struct hostent* host;
6242 int unixtype = convert_af_w2u(type);
6243 const char *paddr = addr;
6244 unsigned long loopback;
6245 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6246 char *extrabuf;
6247 int ebufsize = 1024;
6248 struct hostent hostentry;
6249 int locerr = ENOBUFS;
6250 #endif
6252 /* convert back the magic loopback address if necessary */
6253 if (unixtype == AF_INET && len == 4 && !memcmp(addr, magic_loopback_addr, 4))
6255 loopback = htonl(INADDR_LOOPBACK);
6256 paddr = (char*) &loopback;
6259 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6260 host = NULL;
6261 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
6262 while(extrabuf) {
6263 int res = gethostbyaddr_r(paddr, len, unixtype,
6264 &hostentry, extrabuf, ebufsize, &host, &locerr);
6265 if (res != ERANGE) break;
6266 ebufsize *=2;
6267 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
6269 if (host) retval = WS_dup_he(host);
6270 else SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
6271 HeapFree(GetProcessHeap(),0,extrabuf);
6272 #else
6273 EnterCriticalSection( &csWSgetXXXbyYYY );
6274 host = gethostbyaddr(paddr, len, unixtype);
6275 if (host) retval = WS_dup_he(host);
6276 else SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
6277 LeaveCriticalSection( &csWSgetXXXbyYYY );
6278 #endif
6279 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
6280 return retval;
6283 /***********************************************************************
6284 * WS_compare_routes_by_metric_asc (INTERNAL)
6286 * Comparison function for qsort(), for sorting two routes (struct route)
6287 * by metric in ascending order.
6289 static int WS_compare_routes_by_metric_asc(const void *left, const void *right)
6291 const struct route *a = left, *b = right;
6292 if (a->default_route && b->default_route)
6293 return a->default_route - b->default_route;
6294 if (a->default_route && !b->default_route)
6295 return -1;
6296 if (b->default_route && !a->default_route)
6297 return 1;
6298 return a->metric - b->metric;
6301 /***********************************************************************
6302 * WS_get_local_ips (INTERNAL)
6304 * Returns the list of local IP addresses by going through the network
6305 * adapters and using the local routing table to sort the addresses
6306 * from highest routing priority to lowest routing priority. This
6307 * functionality is inferred from the description for obtaining local
6308 * IP addresses given in the Knowledge Base Article Q160215.
6310 * Please note that the returned hostent is only freed when the thread
6311 * closes and is replaced if another hostent is requested.
6313 static struct WS_hostent* WS_get_local_ips( char *hostname )
6315 int numroutes = 0, i, j, default_routes = 0;
6316 DWORD n;
6317 PIP_ADAPTER_INFO adapters = NULL, k;
6318 struct WS_hostent *hostlist = NULL;
6319 PMIB_IPFORWARDTABLE routes = NULL;
6320 struct route *route_addrs = NULL;
6321 DWORD adap_size, route_size;
6323 /* Obtain the size of the adapter list and routing table, also allocate memory */
6324 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
6325 return NULL;
6326 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
6327 return NULL;
6328 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
6329 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
6330 if (adapters == NULL || routes == NULL)
6331 goto cleanup;
6332 /* Obtain the adapter list and the full routing table */
6333 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
6334 goto cleanup;
6335 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
6336 goto cleanup;
6337 /* Store the interface associated with each route */
6338 for (n = 0; n < routes->dwNumEntries; n++)
6340 IF_INDEX ifindex;
6341 DWORD ifmetric, ifdefault = 0;
6342 BOOL exists = FALSE;
6344 /* Check if this is a default route (there may be more than one) */
6345 if (!routes->table[n].dwForwardDest)
6346 ifdefault = ++default_routes;
6347 else if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
6348 continue;
6349 ifindex = routes->table[n].dwForwardIfIndex;
6350 ifmetric = routes->table[n].dwForwardMetric1;
6351 /* Only store the lowest valued metric for an interface */
6352 for (j = 0; j < numroutes; j++)
6354 if (route_addrs[j].interface == ifindex)
6356 if (route_addrs[j].metric > ifmetric)
6357 route_addrs[j].metric = ifmetric;
6358 exists = TRUE;
6361 if (exists)
6362 continue;
6363 route_addrs = heap_realloc(route_addrs, (numroutes+1)*sizeof(struct route));
6364 if (route_addrs == NULL)
6365 goto cleanup; /* Memory allocation error, fail gracefully */
6366 route_addrs[numroutes].interface = ifindex;
6367 route_addrs[numroutes].metric = ifmetric;
6368 route_addrs[numroutes].default_route = ifdefault;
6369 /* If no IP is found in the next step (for whatever reason)
6370 * then fall back to the magic loopback address.
6372 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
6373 numroutes++;
6375 if (numroutes == 0)
6376 goto cleanup; /* No routes, fall back to the Magic IP */
6377 /* Find the IP address associated with each found interface */
6378 for (i = 0; i < numroutes; i++)
6380 for (k = adapters; k != NULL; k = k->Next)
6382 char *ip = k->IpAddressList.IpAddress.String;
6384 if (route_addrs[i].interface == k->Index)
6385 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
6388 /* Allocate a hostent and enough memory for all the IPs,
6389 * including the NULL at the end of the list.
6391 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
6392 if (hostlist == NULL)
6393 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
6394 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
6395 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
6396 hostlist->h_addrtype = AF_INET;
6397 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
6398 /* Reorder the entries before placing them in the host list. Windows expects
6399 * the IP list in order from highest priority to lowest (the critical thing
6400 * is that most applications expect the first IP to be the default route).
6402 if (numroutes > 1)
6403 qsort(route_addrs, numroutes, sizeof(struct route), WS_compare_routes_by_metric_asc);
6405 for (i = 0; i < numroutes; i++)
6406 (*(struct in_addr *) hostlist->h_addr_list[i]) = route_addrs[i].addr;
6408 /* Cleanup all allocated memory except the address list,
6409 * the address list is used by the calling app.
6411 cleanup:
6412 HeapFree(GetProcessHeap(), 0, route_addrs);
6413 HeapFree(GetProcessHeap(), 0, adapters);
6414 HeapFree(GetProcessHeap(), 0, routes);
6415 return hostlist;
6418 /***********************************************************************
6419 * gethostbyname (WS2_32.52)
6421 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
6423 struct WS_hostent *retval = NULL;
6424 struct hostent* host;
6425 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6426 char *extrabuf;
6427 int ebufsize=1024;
6428 struct hostent hostentry;
6429 int locerr = ENOBUFS;
6430 #endif
6431 char hostname[100];
6432 if(!num_startup) {
6433 SetLastError(WSANOTINITIALISED);
6434 return NULL;
6436 if( gethostname( hostname, 100) == -1) {
6437 SetLastError(WSAENOBUFS); /* appropriate ? */
6438 return retval;
6440 if( !name || !name[0]) {
6441 name = hostname;
6443 /* If the hostname of the local machine is requested then return the
6444 * complete list of local IP addresses */
6445 if(strcmp(name, hostname) == 0)
6446 retval = WS_get_local_ips(hostname);
6447 /* If any other hostname was requested (or the routing table lookup failed)
6448 * then return the IP found by the host OS */
6449 if(retval == NULL)
6451 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6452 host = NULL;
6453 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
6454 while(extrabuf) {
6455 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
6456 if( res != ERANGE) break;
6457 ebufsize *=2;
6458 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
6460 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
6461 #else
6462 EnterCriticalSection( &csWSgetXXXbyYYY );
6463 host = gethostbyname(name);
6464 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
6465 #endif
6466 if (host) retval = WS_dup_he(host);
6467 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6468 HeapFree(GetProcessHeap(),0,extrabuf);
6469 #else
6470 LeaveCriticalSection( &csWSgetXXXbyYYY );
6471 #endif
6473 if (retval && retval->h_addr_list[0][0] == 127 &&
6474 strcmp(name, "localhost") != 0)
6476 /* hostname != "localhost" but has loopback address. replace by our
6477 * special address.*/
6478 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
6480 TRACE( "%s ret %p\n", debugstr_a(name), retval );
6481 return retval;
6485 static const struct { int prot; const char *names[3]; } protocols[] =
6487 { 0, { "ip", "IP" }},
6488 { 1, { "icmp", "ICMP" }},
6489 { 2, { "igmp", "IGMP" }},
6490 { 3, { "ggp", "GGP" }},
6491 { 6, { "tcp", "TCP" }},
6492 { 8, { "egp", "EGP" }},
6493 { 9, { "igp", "IGP" }},
6494 { 12, { "pup", "PUP" }},
6495 { 17, { "udp", "UDP" }},
6496 { 20, { "hmp", "HMP" }},
6497 { 22, { "xns-idp", "XNS-IDP" }},
6498 { 27, { "rdp", "RDP" }},
6499 { 29, { "iso-tp4", "ISO-TP4" }},
6500 { 33, { "dccp", "DCCP" }},
6501 { 36, { "xtp", "XTP" }},
6502 { 37, { "ddp", "DDP" }},
6503 { 38, { "idpr-cmtp", "IDPR-CMTP" }},
6504 { 41, { "ipv6", "IPv6" }},
6505 { 43, { "ipv6-route", "IPv6-Route" }},
6506 { 44, { "ipv6-frag", "IPv6-Frag" }},
6507 { 45, { "idrp", "IDRP" }},
6508 { 46, { "rsvp", "RSVP" }},
6509 { 47, { "gre", "GRE" }},
6510 { 50, { "esp", "ESP" }},
6511 { 51, { "ah", "AH" }},
6512 { 57, { "skip", "SKIP" }},
6513 { 58, { "ipv6-icmp", "IPv6-ICMP" }},
6514 { 59, { "ipv6-nonxt", "IPv6-NoNxt" }},
6515 { 60, { "ipv6-opts", "IPv6-Opts" }},
6516 { 66, { "rvd", "RVD" }},
6517 { 73, { "rspf", "RSPF" }},
6518 { 81, { "vmtp", "VMTP" }},
6519 { 88, { "eigrp", "EIGRP" }},
6520 { 89, { "ospf", "OSPFIGP" }},
6521 { 93, { "ax.25", "AX.25" }},
6522 { 94, { "ipip", "IPIP" }},
6523 { 97, { "etherip", "ETHERIP" }},
6524 { 98, { "encap", "ENCAP" }},
6525 { 103, { "pim", "PIM" }},
6526 { 108, { "ipcomp", "IPCOMP" }},
6527 { 112, { "vrrp", "VRRP" }},
6528 { 115, { "l2tp", "L2TP" }},
6529 { 124, { "isis", "ISIS" }},
6530 { 132, { "sctp", "SCTP" }},
6531 { 133, { "fc", "FC" }},
6532 { 135, { "mobility-header", "Mobility-Header" }},
6533 { 136, { "udplite", "UDPLite" }},
6534 { 137, { "mpls-in-ip", "MPLS-in-IP" }},
6535 { 139, { "hip", "HIP" }},
6536 { 140, { "shim6", "Shim6" }},
6537 { 141, { "wesp", "WESP" }},
6538 { 142, { "rohc", "ROHC" }},
6541 /***********************************************************************
6542 * getprotobyname (WS2_32.53)
6544 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
6546 struct WS_protoent* retval = NULL;
6547 #ifdef HAVE_GETPROTOBYNAME
6548 struct protoent* proto;
6549 EnterCriticalSection( &csWSgetXXXbyYYY );
6550 if( (proto = getprotobyname(name)) != NULL )
6551 retval = WS_create_pe( proto->p_name, proto->p_aliases, proto->p_proto );
6552 LeaveCriticalSection( &csWSgetXXXbyYYY );
6553 #endif
6554 if (!retval)
6556 unsigned int i;
6557 for (i = 0; i < ARRAY_SIZE(protocols); i++)
6559 if (_strnicmp( protocols[i].names[0], name, -1 )) continue;
6560 retval = WS_create_pe( protocols[i].names[0], (char **)protocols[i].names + 1,
6561 protocols[i].prot );
6562 break;
6565 if (!retval)
6567 WARN( "protocol %s not found\n", debugstr_a(name) );
6568 SetLastError(WSANO_DATA);
6570 TRACE( "%s ret %p\n", debugstr_a(name), retval );
6571 return retval;
6575 /***********************************************************************
6576 * getprotobynumber (WS2_32.54)
6578 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
6580 struct WS_protoent* retval = NULL;
6581 #ifdef HAVE_GETPROTOBYNUMBER
6582 struct protoent* proto;
6583 EnterCriticalSection( &csWSgetXXXbyYYY );
6584 if( (proto = getprotobynumber(number)) != NULL )
6585 retval = WS_create_pe( proto->p_name, proto->p_aliases, proto->p_proto );
6586 LeaveCriticalSection( &csWSgetXXXbyYYY );
6587 #endif
6588 if (!retval)
6590 unsigned int i;
6591 for (i = 0; i < ARRAY_SIZE(protocols); i++)
6593 if (protocols[i].prot != number) continue;
6594 retval = WS_create_pe( protocols[i].names[0], (char **)protocols[i].names + 1,
6595 protocols[i].prot );
6596 break;
6599 if (!retval)
6601 WARN( "protocol %d not found\n", number );
6602 SetLastError(WSANO_DATA);
6604 TRACE("%i ret %p\n", number, retval);
6605 return retval;
6609 /***********************************************************************
6610 * getservbyname (WS2_32.55)
6612 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
6614 struct WS_servent* retval = NULL;
6615 struct servent* serv;
6616 char *name_str;
6617 char *proto_str = NULL;
6619 if (!(name_str = strdup_lower(name))) return NULL;
6621 if (proto && *proto)
6623 if (!(proto_str = strdup_lower(proto)))
6625 HeapFree( GetProcessHeap(), 0, name_str );
6626 return NULL;
6630 EnterCriticalSection( &csWSgetXXXbyYYY );
6631 serv = getservbyname(name_str, proto_str);
6632 if( serv != NULL )
6634 retval = WS_dup_se(serv);
6636 else SetLastError(WSANO_DATA);
6637 LeaveCriticalSection( &csWSgetXXXbyYYY );
6638 HeapFree( GetProcessHeap(), 0, proto_str );
6639 HeapFree( GetProcessHeap(), 0, name_str );
6640 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
6641 return retval;
6644 /***********************************************************************
6645 * freeaddrinfo (WS2_32.@)
6647 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
6649 while (res) {
6650 struct WS_addrinfo *next;
6652 HeapFree(GetProcessHeap(),0,res->ai_canonname);
6653 HeapFree(GetProcessHeap(),0,res->ai_addr);
6654 next = res->ai_next;
6655 HeapFree(GetProcessHeap(),0,res);
6656 res = next;
6660 /* helper functions for getaddrinfo()/getnameinfo() */
6661 static int convert_aiflag_w2u(int winflags) {
6662 unsigned int i;
6663 int unixflags = 0;
6665 for (i = 0; i < ARRAY_SIZE(ws_aiflag_map); i++)
6666 if (ws_aiflag_map[i][0] & winflags) {
6667 unixflags |= ws_aiflag_map[i][1];
6668 winflags &= ~ws_aiflag_map[i][0];
6670 if (winflags)
6671 FIXME("Unhandled windows AI_xxx flags 0x%x\n", winflags);
6672 return unixflags;
6675 static int convert_niflag_w2u(int winflags) {
6676 unsigned int i;
6677 int unixflags = 0;
6679 for (i = 0; i < ARRAY_SIZE(ws_niflag_map); i++)
6680 if (ws_niflag_map[i][0] & winflags) {
6681 unixflags |= ws_niflag_map[i][1];
6682 winflags &= ~ws_niflag_map[i][0];
6684 if (winflags)
6685 FIXME("Unhandled windows NI_xxx flags 0x%x\n", winflags);
6686 return unixflags;
6689 static int convert_aiflag_u2w(int unixflags) {
6690 unsigned int i;
6691 int winflags = 0;
6693 for (i = 0; i < ARRAY_SIZE(ws_aiflag_map); i++)
6694 if (ws_aiflag_map[i][1] & unixflags) {
6695 winflags |= ws_aiflag_map[i][0];
6696 unixflags &= ~ws_aiflag_map[i][1];
6698 if (unixflags)
6699 WARN("Unhandled UNIX AI_xxx flags 0x%x\n", unixflags);
6700 return winflags;
6703 static int convert_eai_u2w(int unixret) {
6704 int i;
6706 if (!unixret) return 0;
6708 for (i=0;ws_eai_map[i][0];i++)
6709 if (ws_eai_map[i][1] == unixret)
6710 return ws_eai_map[i][0];
6712 if (unixret == EAI_SYSTEM)
6713 /* There are broken versions of glibc which return EAI_SYSTEM
6714 * and set errno to 0 instead of returning EAI_NONAME.
6716 return errno ? sock_get_error( errno ) : WS_EAI_NONAME;
6718 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret);
6719 return unixret;
6722 static char *get_fqdn(void)
6724 char *ret;
6725 DWORD size = 0;
6727 GetComputerNameExA( ComputerNamePhysicalDnsFullyQualified, NULL, &size );
6728 if (GetLastError() != ERROR_MORE_DATA) return NULL;
6729 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
6730 if (!GetComputerNameExA( ComputerNamePhysicalDnsFullyQualified, ret, &size ))
6732 HeapFree( GetProcessHeap(), 0, ret );
6733 return NULL;
6735 return ret;
6738 /***********************************************************************
6739 * getaddrinfo (WS2_32.@)
6741 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
6743 #ifdef HAVE_GETADDRINFO
6744 struct addrinfo *unixaires = NULL;
6745 int result;
6746 struct addrinfo unixhints, *punixhints = NULL;
6747 char *dot, *nodeV6 = NULL, *fqdn;
6748 const char *node;
6749 size_t hostname_len = 0;
6751 *res = NULL;
6752 if (!nodename && !servname)
6754 SetLastError(WSAHOST_NOT_FOUND);
6755 return WSAHOST_NOT_FOUND;
6758 fqdn = get_fqdn();
6759 if (!fqdn) return WSA_NOT_ENOUGH_MEMORY;
6760 dot = strchr(fqdn, '.');
6761 if (dot)
6762 hostname_len = dot - fqdn;
6764 if (!nodename)
6765 node = NULL;
6766 else if (!nodename[0])
6767 node = fqdn;
6768 else
6770 node = nodename;
6772 /* Check for [ipv6] or [ipv6]:portnumber, which are supported by Windows */
6773 if (!hints || hints->ai_family == WS_AF_UNSPEC || hints->ai_family == WS_AF_INET6)
6775 char *close_bracket;
6777 if (node[0] == '[' && (close_bracket = strchr(node + 1, ']')))
6779 nodeV6 = HeapAlloc(GetProcessHeap(), 0, close_bracket - node);
6780 if (!nodeV6)
6782 HeapFree(GetProcessHeap(), 0, fqdn);
6783 return WSA_NOT_ENOUGH_MEMORY;
6785 lstrcpynA(nodeV6, node + 1, close_bracket - node);
6786 node = nodeV6;
6791 /* servname tweak required by OSX and BSD kernels */
6792 if (servname && !servname[0]) servname = "0";
6794 if (hints) {
6795 punixhints = &unixhints;
6797 memset(&unixhints, 0, sizeof(unixhints));
6798 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
6800 /* zero is a wildcard, no need to convert */
6801 if (hints->ai_family)
6802 punixhints->ai_family = convert_af_w2u(hints->ai_family);
6803 if (hints->ai_socktype)
6804 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
6805 if (hints->ai_protocol)
6806 punixhints->ai_protocol = max(convert_proto_w2u(hints->ai_protocol), 0);
6808 if (punixhints->ai_socktype < 0)
6810 SetLastError(WSAESOCKTNOSUPPORT);
6811 HeapFree(GetProcessHeap(), 0, fqdn);
6812 HeapFree(GetProcessHeap(), 0, nodeV6);
6813 return SOCKET_ERROR;
6816 /* windows allows invalid combinations of socket type and protocol, unix does not.
6817 * fix the parameters here to make getaddrinfo call always work */
6818 if (punixhints->ai_protocol == IPPROTO_TCP &&
6819 punixhints->ai_socktype != SOCK_STREAM && punixhints->ai_socktype != SOCK_SEQPACKET)
6820 punixhints->ai_socktype = 0;
6822 else if (punixhints->ai_protocol == IPPROTO_UDP && punixhints->ai_socktype != SOCK_DGRAM)
6823 punixhints->ai_socktype = 0;
6825 else if (IS_IPX_PROTO(punixhints->ai_protocol) && punixhints->ai_socktype != SOCK_DGRAM)
6826 punixhints->ai_socktype = 0;
6828 else if (punixhints->ai_protocol == IPPROTO_IPV6)
6829 punixhints->ai_protocol = 0;
6832 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
6833 result = getaddrinfo(node, servname, punixhints, &unixaires);
6835 if (result && (!hints || !(hints->ai_flags & WS_AI_NUMERICHOST))
6836 && (!strcmp(fqdn, node) || (!strncmp(fqdn, node, hostname_len) && !node[hostname_len])))
6838 /* If it didn't work it means the host name IP is not in /etc/hosts, try again
6839 * by sending a NULL host and avoid sending a NULL servname too because that
6840 * is invalid */
6841 ERR_(winediag)("Failed to resolve your host name IP\n");
6842 result = getaddrinfo(NULL, servname ? servname : "0", punixhints, &unixaires);
6844 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
6845 HeapFree(GetProcessHeap(), 0, fqdn);
6846 HeapFree(GetProcessHeap(), 0, nodeV6);
6848 if (!result) {
6849 struct addrinfo *xuai = unixaires;
6850 struct WS_addrinfo **xai = res;
6852 *xai = NULL;
6853 while (xuai) {
6854 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
6855 SIZE_T len;
6857 if (!ai)
6858 goto outofmem;
6860 *xai = ai;xai = &ai->ai_next;
6861 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
6862 ai->ai_family = convert_af_u2w(xuai->ai_family);
6863 /* copy whatever was sent in the hints */
6864 if(hints) {
6865 ai->ai_socktype = hints->ai_socktype;
6866 ai->ai_protocol = hints->ai_protocol;
6867 } else {
6868 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
6869 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
6871 if (xuai->ai_canonname) {
6872 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
6873 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
6874 if (!ai->ai_canonname)
6875 goto outofmem;
6876 strcpy(ai->ai_canonname,xuai->ai_canonname);
6878 len = xuai->ai_addrlen;
6879 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
6880 if (!ai->ai_addr)
6881 goto outofmem;
6882 ai->ai_addrlen = len;
6883 do {
6884 int winlen = ai->ai_addrlen;
6886 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
6887 ai->ai_addrlen = winlen;
6888 break;
6890 len = 2*len;
6891 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
6892 if (!ai->ai_addr)
6893 goto outofmem;
6894 ai->ai_addrlen = len;
6895 } while (1);
6896 xuai = xuai->ai_next;
6898 freeaddrinfo(unixaires);
6900 if (TRACE_ON(winsock))
6902 struct WS_addrinfo *ai = *res;
6903 while (ai)
6905 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
6906 ai, ai->ai_flags, ai->ai_family, ai->ai_socktype, ai->ai_protocol, ai->ai_addrlen,
6907 ai->ai_canonname, debugstr_sockaddr(ai->ai_addr));
6908 ai = ai->ai_next;
6911 } else
6912 result = convert_eai_u2w(result);
6914 SetLastError(result);
6915 return result;
6917 outofmem:
6918 if (*res) WS_freeaddrinfo(*res);
6919 if (unixaires) freeaddrinfo(unixaires);
6920 return WSA_NOT_ENOUGH_MEMORY;
6921 #else
6922 FIXME("getaddrinfo() failed, not found during buildtime.\n");
6923 return EAI_FAIL;
6924 #endif
6927 static ADDRINFOEXW *addrinfo_AtoW(const struct WS_addrinfo *ai)
6929 ADDRINFOEXW *ret;
6931 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(ADDRINFOEXW)))) return NULL;
6932 ret->ai_flags = ai->ai_flags;
6933 ret->ai_family = ai->ai_family;
6934 ret->ai_socktype = ai->ai_socktype;
6935 ret->ai_protocol = ai->ai_protocol;
6936 ret->ai_addrlen = ai->ai_addrlen;
6937 ret->ai_canonname = NULL;
6938 ret->ai_addr = NULL;
6939 ret->ai_blob = NULL;
6940 ret->ai_bloblen = 0;
6941 ret->ai_provider = NULL;
6942 ret->ai_next = NULL;
6943 if (ai->ai_canonname)
6945 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
6946 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR))))
6948 HeapFree(GetProcessHeap(), 0, ret);
6949 return NULL;
6951 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
6953 if (ai->ai_addr)
6955 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, ai->ai_addrlen)))
6957 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6958 HeapFree(GetProcessHeap(), 0, ret);
6959 return NULL;
6961 memcpy(ret->ai_addr, ai->ai_addr, ai->ai_addrlen);
6963 return ret;
6966 static ADDRINFOEXW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
6968 ADDRINFOEXW *ret, *infoW;
6970 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
6971 while (info->ai_next)
6973 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
6975 FreeAddrInfoExW(ret);
6976 return NULL;
6978 infoW = infoW->ai_next;
6979 info = info->ai_next;
6981 return ret;
6984 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
6986 struct WS_addrinfo *ret;
6988 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
6989 ret->ai_flags = ai->ai_flags;
6990 ret->ai_family = ai->ai_family;
6991 ret->ai_socktype = ai->ai_socktype;
6992 ret->ai_protocol = ai->ai_protocol;
6993 ret->ai_addrlen = ai->ai_addrlen;
6994 ret->ai_canonname = NULL;
6995 ret->ai_addr = NULL;
6996 ret->ai_next = NULL;
6997 if (ai->ai_canonname)
6999 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
7000 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
7002 HeapFree(GetProcessHeap(), 0, ret);
7003 return NULL;
7005 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
7007 if (ai->ai_addr)
7009 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
7011 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
7012 HeapFree(GetProcessHeap(), 0, ret);
7013 return NULL;
7015 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
7017 return ret;
7020 struct getaddrinfo_args
7022 OVERLAPPED *overlapped;
7023 LPLOOKUPSERVICE_COMPLETION_ROUTINE completion_routine;
7024 ADDRINFOEXW **result;
7025 char *nodename;
7026 char *servname;
7029 static void WINAPI getaddrinfo_callback(TP_CALLBACK_INSTANCE *instance, void *context)
7031 struct getaddrinfo_args *args = context;
7032 OVERLAPPED *overlapped = args->overlapped;
7033 HANDLE event = overlapped->hEvent;
7034 LPLOOKUPSERVICE_COMPLETION_ROUTINE completion_routine = args->completion_routine;
7035 struct WS_addrinfo *res;
7036 int ret;
7038 ret = WS_getaddrinfo(args->nodename, args->servname, NULL, &res);
7039 if (res)
7041 *args->result = addrinfo_list_AtoW(res);
7042 overlapped->u.Pointer = args->result;
7043 WS_freeaddrinfo(res);
7046 HeapFree(GetProcessHeap(), 0, args->nodename);
7047 HeapFree(GetProcessHeap(), 0, args->servname);
7048 HeapFree(GetProcessHeap(), 0, args);
7050 overlapped->Internal = ret;
7051 if (completion_routine) completion_routine(ret, 0, overlapped);
7052 if (event) SetEvent(event);
7055 static int WS_getaddrinfoW(const WCHAR *nodename, const WCHAR *servname, const struct WS_addrinfo *hints, ADDRINFOEXW **res,
7056 OVERLAPPED *overlapped, LPLOOKUPSERVICE_COMPLETION_ROUTINE completion_routine)
7058 int ret = EAI_MEMORY, len, i;
7059 char *nodenameA = NULL, *servnameA = NULL;
7060 struct WS_addrinfo *resA;
7061 WCHAR *local_nodenameW = (WCHAR *)nodename;
7063 *res = NULL;
7064 if (nodename)
7066 /* Is this an IDN? Most likely if any char is above the Ascii table, this
7067 * is the simplest validation possible, further validation will be done by
7068 * the native getaddrinfo() */
7069 for (i = 0; nodename[i]; i++)
7071 if (nodename[i] > 'z')
7072 break;
7074 if (nodename[i])
7076 if (hints && (hints->ai_flags & WS_AI_DISABLE_IDN_ENCODING))
7078 /* Name requires conversion but it was disabled */
7079 ret = WSAHOST_NOT_FOUND;
7080 WSASetLastError(ret);
7081 goto end;
7084 len = IdnToAscii(0, nodename, -1, NULL, 0);
7085 if (!len)
7087 ERR("Failed to convert %s to punycode\n", debugstr_w(nodename));
7088 ret = EAI_FAIL;
7089 goto end;
7091 if (!(local_nodenameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) goto end;
7092 IdnToAscii(0, nodename, -1, local_nodenameW, len);
7095 if (local_nodenameW)
7097 len = WideCharToMultiByte(CP_ACP, 0, local_nodenameW, -1, NULL, 0, NULL, NULL);
7098 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) goto end;
7099 WideCharToMultiByte(CP_ACP, 0, local_nodenameW, -1, nodenameA, len, NULL, NULL);
7101 if (servname)
7103 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
7104 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len))) goto end;
7105 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
7108 if (overlapped)
7110 struct getaddrinfo_args *args;
7112 if (overlapped->hEvent && completion_routine)
7114 ret = WSAEINVAL;
7115 goto end;
7118 if (!(args = HeapAlloc(GetProcessHeap(), 0, sizeof(*args)))) goto end;
7119 args->overlapped = overlapped;
7120 args->completion_routine = completion_routine;
7121 args->result = res;
7122 args->nodename = nodenameA;
7123 args->servname = servnameA;
7125 overlapped->Internal = WSAEINPROGRESS;
7126 if (!TrySubmitThreadpoolCallback(getaddrinfo_callback, args, NULL))
7128 HeapFree(GetProcessHeap(), 0, args);
7129 ret = GetLastError();
7130 goto end;
7133 if (local_nodenameW != nodename)
7134 HeapFree(GetProcessHeap(), 0, local_nodenameW);
7135 WSASetLastError(ERROR_IO_PENDING);
7136 return ERROR_IO_PENDING;
7139 ret = WS_getaddrinfo(nodenameA, servnameA, hints, &resA);
7140 if (!ret)
7142 *res = addrinfo_list_AtoW(resA);
7143 WS_freeaddrinfo(resA);
7146 end:
7147 if (local_nodenameW != nodename)
7148 HeapFree(GetProcessHeap(), 0, local_nodenameW);
7149 HeapFree(GetProcessHeap(), 0, nodenameA);
7150 HeapFree(GetProcessHeap(), 0, servnameA);
7151 return ret;
7154 /***********************************************************************
7155 * GetAddrInfoExW (WS2_32.@)
7157 int WINAPI GetAddrInfoExW(const WCHAR *name, const WCHAR *servname, DWORD namespace, GUID *namespace_id,
7158 const ADDRINFOEXW *hints, ADDRINFOEXW **result, struct WS_timeval *timeout, OVERLAPPED *overlapped,
7159 LPLOOKUPSERVICE_COMPLETION_ROUTINE completion_routine, HANDLE *handle)
7161 int ret;
7163 TRACE("(%s %s %x %s %p %p %p %p %p %p)\n", debugstr_w(name), debugstr_w(servname), namespace,
7164 debugstr_guid(namespace_id), hints, result, timeout, overlapped, completion_routine, handle);
7166 if (namespace != NS_DNS)
7167 FIXME("Unsupported namespace %u\n", namespace);
7168 if (namespace_id)
7169 FIXME("Unsupported naemspace_id %s\n", debugstr_guid(namespace_id));
7170 if (hints)
7171 FIXME("Unsupported hints\n");
7172 if (timeout)
7173 FIXME("Unsupported timeout\n");
7174 if (handle)
7175 FIXME("Unsupported cancel handle\n");
7177 ret = WS_getaddrinfoW(name, servname, NULL, result, overlapped, completion_routine);
7178 if (ret) return ret;
7179 if (handle) *handle = (HANDLE)0xdeadbeef;
7180 return 0;
7183 /***********************************************************************
7184 * GetAddrInfoExOverlappedResult (WS2_32.@)
7186 int WINAPI GetAddrInfoExOverlappedResult(OVERLAPPED *overlapped)
7188 TRACE("(%p)\n", overlapped);
7189 return overlapped->Internal;
7192 /***********************************************************************
7193 * GetAddrInfoExCancel (WS2_32.@)
7195 int WINAPI GetAddrInfoExCancel(HANDLE *handle)
7197 FIXME("(%p)\n", handle);
7198 return WSA_INVALID_HANDLE;
7201 /***********************************************************************
7202 * GetAddrInfoW (WS2_32.@)
7204 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
7206 struct WS_addrinfo *hintsA = NULL;
7207 ADDRINFOEXW *resex;
7208 int ret = EAI_MEMORY;
7210 TRACE("nodename %s, servname %s, hints %p, result %p\n",
7211 debugstr_w(nodename), debugstr_w(servname), hints, res);
7213 *res = NULL;
7214 if (hints) hintsA = addrinfo_WtoA(hints);
7215 ret = WS_getaddrinfoW(nodename, servname, hintsA, &resex, NULL, NULL);
7216 WS_freeaddrinfo(hintsA);
7217 if (ret) return ret;
7219 if (resex)
7221 /* ADDRINFOEXW has layout compatible with ADDRINFOW except for ai_next field,
7222 * so we may convert it in place */
7223 *res = (ADDRINFOW*)resex;
7224 do {
7225 ((ADDRINFOW*)resex)->ai_next = (ADDRINFOW*)resex->ai_next;
7226 resex = resex->ai_next;
7227 } while (resex);
7229 return 0;
7232 /***********************************************************************
7233 * FreeAddrInfoW (WS2_32.@)
7235 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
7237 while (ai)
7239 ADDRINFOW *next;
7240 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
7241 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
7242 next = ai->ai_next;
7243 HeapFree(GetProcessHeap(), 0, ai);
7244 ai = next;
7248 /***********************************************************************
7249 * FreeAddrInfoExW (WS2_32.@)
7251 void WINAPI FreeAddrInfoExW(ADDRINFOEXW *ai)
7253 TRACE("(%p)\n", ai);
7255 while (ai)
7257 ADDRINFOEXW *next;
7258 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
7259 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
7260 next = ai->ai_next;
7261 HeapFree(GetProcessHeap(), 0, ai);
7262 ai = next;
7266 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
7267 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
7269 #ifdef HAVE_GETNAMEINFO
7270 int ret;
7271 union generic_unix_sockaddr sa_u;
7272 unsigned int size;
7274 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
7275 serv, servlen, flags);
7277 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
7278 if (!size)
7280 SetLastError(WSAEFAULT);
7281 return WSA_NOT_ENOUGH_MEMORY;
7283 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
7284 return convert_eai_u2w(ret);
7285 #else
7286 FIXME("getnameinfo() failed, not found during buildtime.\n");
7287 return EAI_FAIL;
7288 #endif
7291 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
7292 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
7294 int ret;
7295 char *hostA = NULL, *servA = NULL;
7297 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
7298 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
7300 HeapFree(GetProcessHeap(), 0, hostA);
7301 return EAI_MEMORY;
7304 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
7305 if (!ret)
7307 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
7308 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
7311 HeapFree(GetProcessHeap(), 0, hostA);
7312 HeapFree(GetProcessHeap(), 0, servA);
7313 return ret;
7316 /***********************************************************************
7317 * getservbyport (WS2_32.56)
7319 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
7321 struct WS_servent* retval = NULL;
7322 #ifdef HAVE_GETSERVBYPORT
7323 struct servent* serv;
7324 char *proto_str = NULL;
7326 if (proto && *proto)
7328 if (!(proto_str = strdup_lower(proto))) return NULL;
7330 EnterCriticalSection( &csWSgetXXXbyYYY );
7331 if( (serv = getservbyport(port, proto_str)) != NULL ) {
7332 retval = WS_dup_se(serv);
7334 else SetLastError(WSANO_DATA);
7335 LeaveCriticalSection( &csWSgetXXXbyYYY );
7336 HeapFree( GetProcessHeap(), 0, proto_str );
7337 #endif
7338 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
7339 return retval;
7343 /***********************************************************************
7344 * gethostname (WS2_32.57)
7346 int WINAPI WS_gethostname(char *name, int namelen)
7348 char buf[256];
7349 int len;
7351 TRACE("name %p, len %d\n", name, namelen);
7353 if (!name)
7355 SetLastError(WSAEFAULT);
7356 return SOCKET_ERROR;
7359 if (gethostname(buf, sizeof(buf)) != 0)
7361 SetLastError(wsaErrno());
7362 return SOCKET_ERROR;
7365 TRACE("<- '%s'\n", buf);
7366 len = strlen(buf);
7367 if (len > 15)
7368 WARN("Windows supports NetBIOS name length up to 15 bytes!\n");
7369 if (namelen <= len)
7371 SetLastError(WSAEFAULT);
7372 WARN("<- not enough space for hostname, required %d, got %d!\n", len + 1, namelen);
7373 return SOCKET_ERROR;
7375 strcpy(name, buf);
7376 return 0;
7380 /* ------------------------------------- Windows sockets extensions -- *
7382 * ------------------------------------------------------------------- */
7384 /***********************************************************************
7385 * WSAEnumNetworkEvents (WS2_32.36)
7387 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
7389 int ret;
7390 int i;
7391 int errors[FD_MAX_EVENTS];
7393 TRACE("%04lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
7395 SERVER_START_REQ( get_socket_event )
7397 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7398 req->service = TRUE;
7399 req->c_event = wine_server_obj_handle( hEvent );
7400 wine_server_set_reply( req, errors, sizeof(errors) );
7401 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
7403 SERVER_END_REQ;
7404 if (!ret)
7406 for (i = 0; i < FD_MAX_EVENTS; i++)
7408 if (lpEvent->lNetworkEvents & (1 << i))
7409 lpEvent->iErrorCode[i] = errors[i];
7411 return 0;
7413 SetLastError(WSAEINVAL);
7414 return SOCKET_ERROR;
7417 /***********************************************************************
7418 * WSAEventSelect (WS2_32.39)
7420 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
7422 int ret;
7424 TRACE("%04lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
7426 SERVER_START_REQ( set_socket_event )
7428 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7429 req->mask = lEvent;
7430 req->event = wine_server_obj_handle( hEvent );
7431 req->window = 0;
7432 req->msg = 0;
7433 ret = wine_server_call( req );
7435 SERVER_END_REQ;
7436 if (!ret) return 0;
7437 SetLastError(WSAEINVAL);
7438 return SOCKET_ERROR;
7441 /**********************************************************************
7442 * WSAGetOverlappedResult (WS2_32.40)
7444 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
7445 LPDWORD lpcbTransfer, BOOL fWait,
7446 LPDWORD lpdwFlags )
7448 NTSTATUS status;
7450 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
7451 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
7453 if ( lpOverlapped == NULL )
7455 ERR( "Invalid pointer\n" );
7456 SetLastError(WSA_INVALID_PARAMETER);
7457 return FALSE;
7460 status = lpOverlapped->Internal;
7461 if (status == STATUS_PENDING)
7463 if (!fWait)
7465 SetLastError( WSA_IO_INCOMPLETE );
7466 return FALSE;
7469 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
7470 INFINITE ) == WAIT_FAILED)
7471 return FALSE;
7472 status = lpOverlapped->Internal;
7475 if ( lpcbTransfer )
7476 *lpcbTransfer = lpOverlapped->InternalHigh;
7478 if ( lpdwFlags )
7479 *lpdwFlags = lpOverlapped->u.s.Offset;
7481 if (status) SetLastError( RtlNtStatusToDosError(status) );
7482 return !status;
7486 /***********************************************************************
7487 * WSAAsyncSelect (WS2_32.101)
7489 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
7491 int ret;
7493 TRACE("%04lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
7495 SERVER_START_REQ( set_socket_event )
7497 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7498 req->mask = lEvent;
7499 req->event = 0;
7500 req->window = wine_server_user_handle( hWnd );
7501 req->msg = uMsg;
7502 ret = wine_server_call( req );
7504 SERVER_END_REQ;
7505 if (!ret) return 0;
7506 SetLastError(WSAEINVAL);
7507 return SOCKET_ERROR;
7510 /***********************************************************************
7511 * WSACreateEvent (WS2_32.31)
7514 WSAEVENT WINAPI WSACreateEvent(void)
7516 /* Create a manual-reset event, with initial state: unsignaled */
7517 TRACE("\n");
7519 return CreateEventW(NULL, TRUE, FALSE, NULL);
7522 /***********************************************************************
7523 * WSACloseEvent (WS2_32.29)
7526 BOOL WINAPI WSACloseEvent(WSAEVENT event)
7528 TRACE ("event=%p\n", event);
7530 return CloseHandle(event);
7533 /***********************************************************************
7534 * WSASocketA (WS2_32.78)
7537 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
7538 LPWSAPROTOCOL_INFOA lpProtocolInfo,
7539 GROUP g, DWORD dwFlags)
7541 INT len;
7542 WSAPROTOCOL_INFOW info;
7544 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
7545 af, type, protocol, lpProtocolInfo, g, dwFlags);
7547 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
7549 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
7550 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
7551 info.szProtocol, WSAPROTOCOL_LEN + 1);
7553 if (!len)
7555 SetLastError(WSAEINVAL);
7556 return SOCKET_ERROR;
7559 return WSASocketW(af, type, protocol, &info, g, dwFlags);
7562 /***********************************************************************
7563 * WSASocketW (WS2_32.79)
7566 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
7567 LPWSAPROTOCOL_INFOW lpProtocolInfo,
7568 GROUP g, DWORD dwFlags)
7570 SOCKET ret;
7571 DWORD err;
7572 int unixaf, unixtype, ipxptype = -1;
7575 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
7576 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
7579 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
7580 af, type, protocol, lpProtocolInfo, g, dwFlags );
7582 if (!num_startup)
7584 err = WSANOTINITIALISED;
7585 goto done;
7588 /* hack for WSADuplicateSocket */
7589 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
7590 ret = lpProtocolInfo->dwServiceFlags3;
7591 TRACE("\tgot duplicate %04lx\n", ret);
7592 return ret;
7595 if (lpProtocolInfo)
7597 if (af == FROM_PROTOCOL_INFO || !af)
7598 af = lpProtocolInfo->iAddressFamily;
7599 if (type == FROM_PROTOCOL_INFO || !type)
7600 type = lpProtocolInfo->iSocketType;
7601 if (protocol == FROM_PROTOCOL_INFO || !protocol)
7602 protocol = lpProtocolInfo->iProtocol;
7605 if (!type && (af || protocol))
7607 int autoproto = protocol;
7608 WSAPROTOCOL_INFOW infow;
7610 /* default to the first valid protocol */
7611 if (!autoproto)
7612 autoproto = valid_protocols[0];
7613 else if(IS_IPX_PROTO(autoproto))
7614 autoproto = WS_NSPROTO_IPX;
7616 if (WS_EnterSingleProtocolW(autoproto, &infow))
7618 type = infow.iSocketType;
7620 /* after win2003 it's no longer possible to pass AF_UNSPEC
7621 using the protocol info struct */
7622 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
7623 af = infow.iAddressFamily;
7628 Windows has an extension to the IPX protocol that allows one to create sockets
7629 and set the IPX packet type at the same time, to do that a caller will use
7630 a protocol like NSPROTO_IPX + <PACKET TYPE>
7632 if (IS_IPX_PROTO(protocol))
7633 ipxptype = protocol - WS_NSPROTO_IPX;
7635 /* convert the socket family, type and protocol */
7636 unixaf = convert_af_w2u(af);
7637 unixtype = convert_socktype_w2u(type);
7638 protocol = convert_proto_w2u(protocol);
7639 if (unixaf == AF_UNSPEC) unixaf = -1;
7641 /* filter invalid parameters */
7642 if (protocol < 0)
7644 /* the type could not be converted */
7645 if (type && unixtype < 0)
7647 err = WSAESOCKTNOSUPPORT;
7648 goto done;
7651 err = WSAEPROTONOSUPPORT;
7652 goto done;
7654 if (unixaf < 0)
7656 /* both family and protocol can't be invalid */
7657 if (protocol <= 0)
7659 err = WSAEINVAL;
7660 goto done;
7663 /* family could not be converted and neither socket type */
7664 if (unixtype < 0 && af >= 0)
7667 err = WSAESOCKTNOSUPPORT;
7668 goto done;
7671 err = WSAEAFNOSUPPORT;
7672 goto done;
7675 SERVER_START_REQ( create_socket )
7677 req->family = unixaf;
7678 req->type = unixtype;
7679 req->protocol = protocol;
7680 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
7681 req->attributes = (dwFlags & WSA_FLAG_NO_HANDLE_INHERIT) ? 0 : OBJ_INHERIT;
7682 req->flags = dwFlags & ~WSA_FLAG_NO_HANDLE_INHERIT;
7683 err = NtStatusToWSAError( wine_server_call( req ) );
7684 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
7686 SERVER_END_REQ;
7687 if (ret)
7689 TRACE("\tcreated %04lx\n", ret );
7690 if (ipxptype > 0)
7691 set_ipx_packettype(ret, ipxptype);
7693 if (unixaf == AF_INET || unixaf == AF_INET6)
7695 /* ensure IP_DONTFRAGMENT is disabled for SOCK_DGRAM and SOCK_RAW, enabled for SOCK_STREAM */
7696 if (unixtype == SOCK_DGRAM || unixtype == SOCK_RAW) /* in Linux the global default can be enabled */
7697 set_dont_fragment(ret, unixaf == AF_INET6 ? IPPROTO_IPV6 : IPPROTO_IP, FALSE);
7698 else if (unixtype == SOCK_STREAM)
7699 set_dont_fragment(ret, unixaf == AF_INET6 ? IPPROTO_IPV6 : IPPROTO_IP, TRUE);
7702 #ifdef IPV6_V6ONLY
7703 if (unixaf == AF_INET6)
7705 int fd = get_sock_fd(ret, 0, NULL);
7706 if (fd != -1)
7708 /* IPV6_V6ONLY is set by default on Windows */
7709 int enable = 1;
7710 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)))
7711 WARN("\tsetting IPV6_V6ONLY failed - errno = %i\n", errno);
7712 release_sock_fd(ret, fd);
7715 #endif
7716 return ret;
7719 if (err == WSAEACCES) /* raw socket denied */
7721 if (type == SOCK_RAW)
7722 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
7723 else
7724 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
7727 done:
7728 WARN("\t\tfailed, error %d!\n", err);
7729 SetLastError(err);
7730 return INVALID_SOCKET;
7733 /***********************************************************************
7734 * WSAJoinLeaf (WS2_32.58)
7737 SOCKET WINAPI WSAJoinLeaf(
7738 SOCKET s,
7739 const struct WS_sockaddr *addr,
7740 int addrlen,
7741 LPWSABUF lpCallerData,
7742 LPWSABUF lpCalleeData,
7743 LPQOS lpSQOS,
7744 LPQOS lpGQOS,
7745 DWORD dwFlags)
7747 FIXME("stub.\n");
7748 return INVALID_SOCKET;
7751 /***********************************************************************
7752 * __WSAFDIsSet (WS2_32.151)
7754 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
7756 int i = set->fd_count, ret = 0;
7758 while (i--)
7759 if (set->fd_array[i] == s)
7761 ret = 1;
7762 break;
7765 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s, set, set->fd_count, ret);
7766 return ret;
7769 /***********************************************************************
7770 * WSAIsBlocking (WS2_32.114)
7772 BOOL WINAPI WSAIsBlocking(void)
7774 /* By default WinSock should set all its sockets to non-blocking mode
7775 * and poll in PeekMessage loop when processing "blocking" ones. This
7776 * function is supposed to tell if the program is in this loop. Our
7777 * blocking calls are truly blocking so we always return FALSE.
7779 * Note: It is allowed to call this function without prior WSAStartup().
7782 TRACE("\n");
7783 return FALSE;
7786 /***********************************************************************
7787 * WSACancelBlockingCall (WS2_32.113)
7789 INT WINAPI WSACancelBlockingCall(void)
7791 TRACE("\n");
7792 return 0;
7795 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
7797 FIXME("How was this called?\n");
7798 return x();
7802 /***********************************************************************
7803 * WSASetBlockingHook (WS2_32.109)
7805 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
7807 FARPROC prev = blocking_hook;
7808 blocking_hook = lpBlockFunc;
7809 TRACE("hook %p\n", lpBlockFunc);
7810 return prev;
7814 /***********************************************************************
7815 * WSAUnhookBlockingHook (WS2_32.110)
7817 INT WINAPI WSAUnhookBlockingHook(void)
7819 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
7820 return 0;
7824 /* ----------------------------------- end of API stuff */
7826 /* ----------------------------------- helper functions -
7828 * TODO: Merge WS_dup_..() stuff into one function that
7829 * would operate with a generic structure containing internal
7830 * pointers (via a template of some kind).
7833 static int list_size(char** l, int item_size)
7835 int i,j = 0;
7836 if(l)
7837 { for(i=0;l[i];i++)
7838 j += (item_size) ? item_size : strlen(l[i]) + 1;
7839 j += (i + 1) * sizeof(char*); }
7840 return j;
7843 static int list_dup(char** l_src, char** l_to, int item_size)
7845 char *p;
7846 int i;
7848 for (i = 0; l_src[i]; i++) ;
7849 p = (char *)(l_to + i + 1);
7850 for (i = 0; l_src[i]; i++)
7852 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
7853 memcpy(p, l_src[i], count);
7854 l_to[i] = p;
7855 p += count;
7857 l_to[i] = NULL;
7858 return p - (char *)l_to;
7861 /* ----- hostent */
7863 /* create a hostent entry
7865 * Creates the entry with enough memory for the name, aliases
7866 * addresses, and the address pointers. Also copies the name
7867 * and sets up all the pointers.
7869 * NOTE: The alias and address lists must be allocated with room
7870 * for the NULL item terminating the list. This is true even if
7871 * the list has no items ("aliases" and "addresses" must be
7872 * at least "1", a truly empty list is invalid).
7874 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
7876 struct WS_hostent *p_to;
7877 char *p;
7878 int size = (sizeof(struct WS_hostent) +
7879 strlen(name) + 1 +
7880 sizeof(char *) * aliases +
7881 aliases_size +
7882 sizeof(char *) * addresses +
7883 address_length * (addresses - 1)), i;
7885 if (!(p_to = check_buffer_he(size))) return NULL;
7886 memset(p_to, 0, size);
7888 /* Use the memory in the same way winsock does.
7889 * First set the pointer for aliases, second set the pointers for addresses.
7890 * Third fill the addresses indexes, fourth jump aliases names size.
7891 * Fifth fill the hostname.
7892 * NOTE: This method is valid for OS version's >= XP.
7894 p = (char *)(p_to + 1);
7895 p_to->h_aliases = (char **)p;
7896 p += sizeof(char *)*aliases;
7898 p_to->h_addr_list = (char **)p;
7899 p += sizeof(char *)*addresses;
7901 for (i = 0, addresses--; i < addresses; i++, p += address_length)
7902 p_to->h_addr_list[i] = p;
7904 /* NOTE: h_aliases must be filled in manually because we don't know each string
7905 * size, leave these pointers NULL (already set to NULL by memset earlier).
7907 p += aliases_size;
7909 p_to->h_name = p;
7910 strcpy(p, name);
7912 return p_to;
7915 /* duplicate hostent entry
7916 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
7917 * Ditto for protoent and servent.
7919 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
7921 int i, addresses = 0, alias_size = 0;
7922 struct WS_hostent *p_to;
7923 char *p;
7925 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
7926 while (p_he->h_addr_list[addresses]) addresses++;
7928 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
7930 if (!p_to) return NULL;
7931 p_to->h_addrtype = convert_af_u2w(p_he->h_addrtype);
7932 p_to->h_length = p_he->h_length;
7934 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
7935 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
7937 /* Fill the aliases after the IP data */
7938 for(i = 0; p_he->h_aliases[i]; i++)
7940 p_to->h_aliases[i] = p;
7941 strcpy(p, p_he->h_aliases[i]);
7942 p += strlen(p) + 1;
7945 return p_to;
7948 /* ----- protoent */
7950 static struct WS_protoent *WS_create_pe( const char *name, char **aliases, int prot )
7952 struct WS_protoent *ret;
7953 unsigned int size = sizeof(*ret) + strlen(name) + sizeof(char *) + list_size(aliases, 0);
7955 if (!(ret = check_buffer_pe( size ))) return NULL;
7956 ret->p_proto = prot;
7957 ret->p_name = (char *)(ret + 1);
7958 strcpy( ret->p_name, name );
7959 ret->p_aliases = (char **)ret->p_name + strlen(name) / sizeof(char *) + 1;
7960 list_dup( aliases, ret->p_aliases, 0 );
7961 return ret;
7964 /* ----- servent */
7966 static struct WS_servent *WS_dup_se(const struct servent* p_se)
7968 char *p;
7969 struct WS_servent *p_to;
7971 int size = (sizeof(*p_se) +
7972 strlen(p_se->s_proto) + 1 +
7973 strlen(p_se->s_name) + 1 +
7974 list_size(p_se->s_aliases, 0));
7976 if (!(p_to = check_buffer_se(size))) return NULL;
7977 p_to->s_port = p_se->s_port;
7979 p = (char *)(p_to + 1);
7980 p_to->s_name = p;
7981 strcpy(p, p_se->s_name);
7982 p += strlen(p) + 1;
7984 p_to->s_proto = p;
7985 strcpy(p, p_se->s_proto);
7986 p += strlen(p) + 1;
7988 p_to->s_aliases = (char **)p;
7989 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
7990 return p_to;
7994 /***********************************************************************
7995 * WSARecv (WS2_32.67)
7997 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7998 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
7999 LPWSAOVERLAPPED lpOverlapped,
8000 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
8002 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
8003 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
8006 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
8007 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
8008 struct WS_sockaddr *lpFrom,
8009 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
8010 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
8011 LPWSABUF lpControlBuffer )
8013 unsigned int i, options;
8014 int n, fd, err, overlapped, flags;
8015 struct ws2_async *wsa = NULL, localwsa;
8016 BOOL is_blocking;
8017 DWORD timeout_start = GetTickCount();
8018 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
8020 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
8021 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
8022 (lpFromlen ? *lpFromlen : -1),
8023 lpOverlapped, lpCompletionRoutine);
8025 fd = get_sock_fd( s, FILE_READ_DATA, &options );
8026 TRACE( "fd=%d, options=%x\n", fd, options );
8028 if (fd == -1) return SOCKET_ERROR;
8030 if (*lpFlags & WS_MSG_OOB)
8032 /* It's invalid to receive OOB data from an OOBINLINED socket
8033 * as OOB data is turned into normal data. */
8034 socklen_t len = sizeof(n);
8035 if (!getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, (char*) &n, &len) && n)
8037 err = WSAEINVAL;
8038 goto error;
8042 overlapped = (lpOverlapped || lpCompletionRoutine) &&
8043 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
8044 if (overlapped || dwBufferCount > 1)
8046 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]),
8047 WS2_async_recv )))
8049 err = WSAEFAULT;
8050 goto error;
8053 else
8054 wsa = &localwsa;
8056 wsa->hSocket = SOCKET2HANDLE(s);
8057 wsa->flags = *lpFlags;
8058 wsa->lpFlags = lpFlags;
8059 wsa->addr = lpFrom;
8060 wsa->addrlen.ptr = lpFromlen;
8061 wsa->control = lpControlBuffer;
8062 wsa->n_iovecs = dwBufferCount;
8063 wsa->first_iovec = 0;
8064 for (i = 0; i < dwBufferCount; i++)
8066 /* check buffer first to trigger write watches */
8067 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
8069 err = WSAEFAULT;
8070 goto error;
8072 wsa->iovec[i].iov_base = lpBuffers[i].buf;
8073 wsa->iovec[i].iov_len = lpBuffers[i].len;
8076 flags = convert_flags(wsa->flags);
8077 for (;;)
8079 n = WS2_recv( fd, wsa, flags );
8080 if (n == -1)
8082 /* Unix-like systems return EINVAL when attempting to read OOB data from
8083 * an empty socket buffer, convert that to a Windows expected return. */
8084 if ((flags & MSG_OOB) && errno == EINVAL)
8085 errno = EWOULDBLOCK;
8087 if (errno != EAGAIN)
8089 err = wsaErrno();
8090 goto error;
8093 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
8095 if (overlapped)
8097 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
8099 wsa->user_overlapped = lpOverlapped;
8100 wsa->completion_func = lpCompletionRoutine;
8101 release_sock_fd( s, fd );
8103 if (n == -1)
8105 iosb->u.Status = STATUS_PENDING;
8106 iosb->Information = 0;
8108 if (wsa->completion_func)
8109 err = register_async( ASYNC_TYPE_READ, wsa->hSocket, &wsa->io, NULL,
8110 ws2_async_apc, wsa, iosb );
8111 else
8112 err = register_async( ASYNC_TYPE_READ, wsa->hSocket, &wsa->io, lpOverlapped->hEvent,
8113 NULL, (void *)cvalue, iosb );
8115 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
8116 SetLastError(NtStatusToWSAError( err ));
8117 return SOCKET_ERROR;
8120 iosb->u.Status = STATUS_SUCCESS;
8121 iosb->Information = n;
8122 if (!wsa->completion_func)
8124 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n, FALSE );
8125 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
8126 HeapFree( GetProcessHeap(), 0, wsa );
8128 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
8129 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
8130 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
8131 return 0;
8134 if (n != -1) break;
8136 if ((err = sock_is_blocking( s, &is_blocking ))) goto error;
8138 if ( is_blocking )
8140 struct pollfd pfd;
8141 int poll_timeout = -1;
8142 INT64 timeout = get_rcvsnd_timeo(fd, TRUE);
8144 if (timeout)
8146 timeout -= GetTickCount() - timeout_start;
8147 if (timeout < 0) poll_timeout = 0;
8148 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
8151 pfd.fd = fd;
8152 pfd.events = POLLIN;
8153 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
8155 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
8157 err = WSAETIMEDOUT;
8158 /* a timeout is not fatal */
8159 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
8160 goto error;
8163 else
8165 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
8166 err = WSAEWOULDBLOCK;
8167 goto error;
8171 TRACE(" -> %i bytes\n", n);
8172 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
8173 release_sock_fd( s, fd );
8174 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
8175 SetLastError(ERROR_SUCCESS);
8177 return 0;
8179 error:
8180 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
8181 release_sock_fd( s, fd );
8182 WARN(" -> ERROR %d\n", err);
8183 SetLastError( err );
8184 return SOCKET_ERROR;
8187 /***********************************************************************
8188 * WSARecvFrom (WS2_32.69)
8190 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
8191 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
8192 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
8193 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
8196 return WS2_recv_base( s, lpBuffers, dwBufferCount,
8197 lpNumberOfBytesRecvd, lpFlags,
8198 lpFrom, lpFromlen,
8199 lpOverlapped, lpCompletionRoutine, NULL );
8202 /***********************************************************************
8203 * WSCInstallProvider (WS2_32.88)
8205 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
8206 LPCWSTR lpszProviderDllPath,
8207 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
8208 DWORD dwNumberOfEntries,
8209 LPINT lpErrno )
8211 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
8212 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
8213 dwNumberOfEntries, lpErrno);
8214 *lpErrno = 0;
8215 return 0;
8219 /***********************************************************************
8220 * WSCDeinstallProvider (WS2_32.83)
8222 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
8224 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
8225 *lpErrno = 0;
8226 return 0;
8230 /***********************************************************************
8231 * WSAAccept (WS2_32.26)
8233 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
8234 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
8237 int ret = 0, size;
8238 WSABUF CallerId, CallerData, CalleeId, CalleeData;
8239 /* QOS SQOS, GQOS; */
8240 GROUP g;
8241 SOCKET cs;
8242 SOCKADDR src_addr, dst_addr;
8244 TRACE("socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
8245 s, addr, addrlen, lpfnCondition, dwCallbackData);
8247 cs = WS_accept(s, addr, addrlen);
8248 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
8249 if (!lpfnCondition) return cs;
8251 if (addr && addrlen)
8253 CallerId.buf = (char *)addr;
8254 CallerId.len = *addrlen;
8256 else
8258 size = sizeof(src_addr);
8259 WS_getpeername(cs, &src_addr, &size);
8260 CallerId.buf = (char *)&src_addr;
8261 CallerId.len = size;
8263 CallerData.buf = NULL;
8264 CallerData.len = 0;
8266 size = sizeof(dst_addr);
8267 WS_getsockname(cs, &dst_addr, &size);
8269 CalleeId.buf = (char *)&dst_addr;
8270 CalleeId.len = sizeof(dst_addr);
8272 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
8273 &CalleeId, &CalleeData, &g, dwCallbackData);
8275 switch (ret)
8277 case CF_ACCEPT:
8278 return cs;
8279 case CF_DEFER:
8280 SERVER_START_REQ( set_socket_deferred )
8282 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
8283 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
8284 if ( !wine_server_call_err ( req ) )
8286 SetLastError( WSATRY_AGAIN );
8287 WS_closesocket( cs );
8290 SERVER_END_REQ;
8291 return SOCKET_ERROR;
8292 case CF_REJECT:
8293 WS_closesocket(cs);
8294 SetLastError(WSAECONNREFUSED);
8295 return SOCKET_ERROR;
8296 default:
8297 FIXME("Unknown return type from Condition function\n");
8298 SetLastError(WSAENOTSOCK);
8299 return SOCKET_ERROR;
8303 /***********************************************************************
8304 * WSADuplicateSocketA (WS2_32.32)
8306 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
8308 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
8311 /***********************************************************************
8312 * WSADuplicateSocketW (WS2_32.33)
8314 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
8316 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
8319 /***********************************************************************
8320 * WSAInstallServiceClassA (WS2_32.48)
8322 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
8324 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
8325 SetLastError(WSAEACCES);
8326 return SOCKET_ERROR;
8329 /***********************************************************************
8330 * WSAInstallServiceClassW (WS2_32.49)
8332 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
8334 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
8335 SetLastError(WSAEACCES);
8336 return SOCKET_ERROR;
8339 /***********************************************************************
8340 * WSARemoveServiceClass (WS2_32.70)
8342 int WINAPI WSARemoveServiceClass(LPGUID info)
8344 FIXME("Request to remove service %s\n", debugstr_guid(info));
8345 SetLastError(WSATYPE_NOT_FOUND);
8346 return SOCKET_ERROR;
8349 /***********************************************************************
8350 * inet_ntop (WS2_32.@)
8352 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
8354 #ifdef HAVE_INET_NTOP
8355 struct WS_in6_addr *in6;
8356 struct WS_in_addr *in;
8357 PCSTR pdst;
8359 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
8360 if (!buffer)
8362 SetLastError( STATUS_INVALID_PARAMETER );
8363 return NULL;
8366 switch (family)
8368 case WS_AF_INET:
8370 in = addr;
8371 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
8372 break;
8374 case WS_AF_INET6:
8376 in6 = addr;
8377 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
8378 break;
8380 default:
8381 SetLastError( WSAEAFNOSUPPORT );
8382 return NULL;
8385 if (!pdst) SetLastError( STATUS_INVALID_PARAMETER );
8386 return pdst;
8387 #else
8388 FIXME( "not supported on this platform\n" );
8389 SetLastError( WSAEAFNOSUPPORT );
8390 return NULL;
8391 #endif
8394 /***********************************************************************
8395 * inet_pton (WS2_32.@)
8397 INT WINAPI WS_inet_pton( INT family, PCSTR addr, PVOID buffer)
8399 #ifdef HAVE_INET_PTON
8400 int unixaf, ret;
8402 TRACE("family %d, addr %s, buffer (%p)\n", family, debugstr_a(addr), buffer);
8404 if (!addr || !buffer)
8406 SetLastError(WSAEFAULT);
8407 return SOCKET_ERROR;
8410 unixaf = convert_af_w2u(family);
8411 if (unixaf != AF_INET && unixaf != AF_INET6)
8413 SetLastError(WSAEAFNOSUPPORT);
8414 return SOCKET_ERROR;
8417 ret = inet_pton(unixaf, addr, buffer);
8418 if (ret == -1) SetLastError(wsaErrno());
8419 return ret;
8420 #else
8421 FIXME( "not supported on this platform\n" );
8422 SetLastError( WSAEAFNOSUPPORT );
8423 return SOCKET_ERROR;
8424 #endif
8427 /***********************************************************************
8428 * InetPtonW (WS2_32.@)
8430 INT WINAPI InetPtonW(INT family, PCWSTR addr, PVOID buffer)
8432 char *addrA;
8433 int len;
8434 INT ret;
8436 TRACE("family %d, addr %s, buffer (%p)\n", family, debugstr_w(addr), buffer);
8438 if (!addr)
8440 SetLastError(WSAEFAULT);
8441 return SOCKET_ERROR;
8444 len = WideCharToMultiByte(CP_ACP, 0, addr, -1, NULL, 0, NULL, NULL);
8445 if (!(addrA = HeapAlloc(GetProcessHeap(), 0, len)))
8447 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8448 return SOCKET_ERROR;
8450 WideCharToMultiByte(CP_ACP, 0, addr, -1, addrA, len, NULL, NULL);
8452 ret = WS_inet_pton(family, addrA, buffer);
8453 if (!ret) SetLastError(WSAEINVAL);
8455 HeapFree(GetProcessHeap(), 0, addrA);
8456 return ret;
8459 /***********************************************************************
8460 * InetNtopW (WS2_32.@)
8462 PCWSTR WINAPI InetNtopW(INT family, PVOID addr, PWSTR buffer, SIZE_T len)
8464 char bufferA[WS_INET6_ADDRSTRLEN];
8465 PWSTR ret = NULL;
8467 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
8469 if (WS_inet_ntop(family, addr, bufferA, sizeof(bufferA)))
8471 if (MultiByteToWideChar(CP_ACP, 0, bufferA, -1, buffer, len))
8472 ret = buffer;
8473 else
8474 SetLastError(ERROR_INVALID_PARAMETER);
8476 return ret;
8479 /***********************************************************************
8480 * WSAStringToAddressA (WS2_32.80)
8482 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
8483 INT AddressFamily,
8484 LPWSAPROTOCOL_INFOA lpProtocolInfo,
8485 LPSOCKADDR lpAddress,
8486 LPINT lpAddressLength)
8488 INT res=0;
8489 NTSTATUS status;
8491 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
8492 lpProtocolInfo, lpAddress, lpAddressLength );
8494 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
8496 if (!AddressString)
8498 SetLastError(WSAEINVAL);
8499 return SOCKET_ERROR;
8502 if (lpProtocolInfo)
8503 FIXME("ProtocolInfo not implemented.\n");
8505 switch(AddressFamily)
8507 case WS_AF_INET:
8509 SOCKADDR_IN *addr4 = (SOCKADDR_IN *)lpAddress;
8511 /* If lpAddressLength is too small, tell caller the size we need */
8512 if (*lpAddressLength < sizeof(SOCKADDR_IN))
8514 *lpAddressLength = sizeof(SOCKADDR_IN);
8515 res = WSAEFAULT;
8516 break;
8518 *lpAddressLength = sizeof(SOCKADDR_IN);
8519 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
8521 status = RtlIpv4StringToAddressExA(AddressString, FALSE, &addr4->sin_addr, &addr4->sin_port);
8522 if (status != STATUS_SUCCESS)
8524 res = WSAEINVAL;
8525 break;
8527 addr4->sin_family = WS_AF_INET;
8528 break;
8530 case WS_AF_INET6:
8532 SOCKADDR_IN6 *addr6 = (SOCKADDR_IN6 *)lpAddress;
8534 /* If lpAddressLength is too small, tell caller the size we need */
8535 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
8537 *lpAddressLength = sizeof(SOCKADDR_IN6);
8538 res = WSAEFAULT;
8539 break;
8541 *lpAddressLength = sizeof(SOCKADDR_IN6);
8542 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
8544 status = RtlIpv6StringToAddressExA(AddressString, &addr6->sin6_addr, &addr6->sin6_scope_id, &addr6->sin6_port);
8545 if (status != STATUS_SUCCESS)
8547 res = WSAEINVAL;
8548 break;
8550 addr6->sin6_family = WS_AF_INET6;
8551 break;
8553 default:
8554 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
8555 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
8556 res = WSAEINVAL;
8559 if (!res) return 0;
8560 SetLastError(res);
8561 return SOCKET_ERROR;
8564 /***********************************************************************
8565 * WSAStringToAddressW (WS2_32.81)
8567 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
8568 * If this should be the case, it would be required to map these digits
8569 * to Unicode digits (0-9) using FoldString first.
8571 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
8572 INT AddressFamily,
8573 LPWSAPROTOCOL_INFOW lpProtocolInfo,
8574 LPSOCKADDR lpAddress,
8575 LPINT lpAddressLength)
8577 INT sBuffer,res=0;
8578 LPSTR workBuffer=NULL;
8579 WSAPROTOCOL_INFOA infoA;
8580 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
8582 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
8583 lpAddress, lpAddressLength );
8585 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
8587 /* if ProtocolInfo is available - convert to ANSI variant */
8588 if (lpProtocolInfo)
8590 lpProtoInfoA = &infoA;
8591 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
8593 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
8594 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
8596 SetLastError(WSAEINVAL);
8597 return SOCKET_ERROR;
8601 if (AddressString)
8603 /* Translate AddressString to ANSI code page - assumes that only
8604 standard digits 0-9 are used with this API call */
8605 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
8606 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
8608 if (workBuffer)
8610 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
8611 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
8612 lpAddress,lpAddressLength);
8613 HeapFree( GetProcessHeap(), 0, workBuffer );
8614 return res;
8616 else
8617 res = WSA_NOT_ENOUGH_MEMORY;
8619 else
8620 res = WSAEINVAL;
8622 SetLastError(res);
8623 return SOCKET_ERROR;
8626 /***********************************************************************
8627 * WSAAddressToStringA (WS2_32.27)
8629 * See WSAAddressToStringW
8631 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
8632 LPWSAPROTOCOL_INFOA info, LPSTR string,
8633 LPDWORD lenstr )
8635 DWORD size;
8636 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8637 CHAR *p;
8639 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
8641 if (!sockaddr) return SOCKET_ERROR;
8642 if (!string || !lenstr) return SOCKET_ERROR;
8644 switch(sockaddr->sa_family)
8646 case WS_AF_INET:
8648 unsigned int long_ip = ntohl(((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr);
8649 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
8650 sprintf( buffer, "%u.%u.%u.%u:%u",
8651 (long_ip >> 24) & 0xff,
8652 (long_ip >> 16) & 0xff,
8653 (long_ip >> 8) & 0xff,
8654 long_ip & 0xff,
8655 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
8657 p = strchr( buffer, ':' );
8658 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
8659 break;
8661 case WS_AF_INET6:
8663 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
8664 size_t slen;
8666 buffer[0] = 0;
8667 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
8668 if ((sockaddr6->sin6_port))
8669 strcpy(buffer, "[");
8670 slen = strlen(buffer);
8671 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, &buffer[slen], sizeof(buffer) - slen))
8673 SetLastError(WSAEINVAL);
8674 return SOCKET_ERROR;
8676 if ((sockaddr6->sin6_scope_id))
8677 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
8678 if ((sockaddr6->sin6_port))
8679 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
8680 break;
8683 default:
8684 SetLastError(WSAEINVAL);
8685 return SOCKET_ERROR;
8688 size = strlen( buffer ) + 1;
8690 if (*lenstr < size)
8692 *lenstr = size;
8693 SetLastError(WSAEFAULT);
8694 return SOCKET_ERROR;
8697 TRACE("=> %s,%u bytes\n", debugstr_a(buffer), size);
8698 *lenstr = size;
8699 strcpy( string, buffer );
8700 return 0;
8703 /***********************************************************************
8704 * WSAAddressToStringW (WS2_32.28)
8706 * Convert a sockaddr address into a readable address string.
8708 * PARAMS
8709 * sockaddr [I] Pointer to a sockaddr structure.
8710 * len [I] Size of the sockaddr structure.
8711 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
8712 * string [I/O] Pointer to a buffer to receive the address string.
8713 * lenstr [I/O] Size of the receive buffer in WCHARs.
8715 * RETURNS
8716 * Success: 0
8717 * Failure: SOCKET_ERROR
8719 * NOTES
8720 * The 'info' parameter is ignored.
8722 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
8723 LPWSAPROTOCOL_INFOW info, LPWSTR string,
8724 LPDWORD lenstr )
8726 INT ret;
8727 DWORD size;
8728 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8729 CHAR bufAddr[54];
8731 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
8733 size = *lenstr;
8734 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
8736 if (ret) return ret;
8738 MultiByteToWideChar(CP_ACP, 0, bufAddr, size, buffer, ARRAY_SIZE(buffer));
8740 if (*lenstr < size)
8742 *lenstr = size;
8743 SetLastError(WSAEFAULT);
8744 return SOCKET_ERROR;
8747 TRACE("=> %s,%u bytes\n", debugstr_w(buffer), size);
8748 *lenstr = size;
8749 lstrcpyW( string, buffer );
8750 return 0;
8753 /***********************************************************************
8754 * WSAEnumNameSpaceProvidersA (WS2_32.34)
8756 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
8758 FIXME( "(%p %p) Stub!\n", len, buffer );
8759 return 0;
8762 /***********************************************************************
8763 * WSAEnumNameSpaceProvidersW (WS2_32.35)
8765 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
8767 FIXME( "(%p %p) Stub!\n", len, buffer );
8768 return 0;
8771 /***********************************************************************
8772 * WSAGetQOSByName (WS2_32.41)
8774 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
8776 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
8777 return FALSE;
8780 /***********************************************************************
8781 * WSAGetServiceClassInfoA (WS2_32.42)
8783 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
8784 LPWSASERVICECLASSINFOA info )
8786 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
8787 len, info );
8788 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8789 return SOCKET_ERROR;
8792 /***********************************************************************
8793 * WSAGetServiceClassInfoW (WS2_32.43)
8795 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
8796 LPWSASERVICECLASSINFOW info )
8798 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
8799 len, info );
8800 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8801 return SOCKET_ERROR;
8804 /***********************************************************************
8805 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
8807 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
8809 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
8810 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8811 return SOCKET_ERROR;
8814 /***********************************************************************
8815 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
8817 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
8819 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
8820 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8821 return SOCKET_ERROR;
8824 /***********************************************************************
8825 * WSALookupServiceBeginA (WS2_32.59)
8827 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
8828 DWORD dwControlFlags,
8829 LPHANDLE lphLookup)
8831 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
8832 lphLookup);
8833 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8834 return SOCKET_ERROR;
8837 /***********************************************************************
8838 * WSALookupServiceBeginW (WS2_32.60)
8840 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
8841 DWORD dwControlFlags,
8842 LPHANDLE lphLookup)
8844 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
8845 lphLookup);
8846 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8847 return SOCKET_ERROR;
8850 /***********************************************************************
8851 * WSALookupServiceEnd (WS2_32.61)
8853 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
8855 FIXME("(%p) Stub!\n", lookup );
8856 return 0;
8859 /***********************************************************************
8860 * WSALookupServiceNextA (WS2_32.62)
8862 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
8864 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
8865 SetLastError(WSA_E_NO_MORE);
8866 return SOCKET_ERROR;
8869 /***********************************************************************
8870 * WSALookupServiceNextW (WS2_32.63)
8872 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
8874 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
8875 SetLastError(WSA_E_NO_MORE);
8876 return SOCKET_ERROR;
8879 /***********************************************************************
8880 * WSANtohl (WS2_32.64)
8882 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
8884 TRACE( "(%04lx 0x%08x %p)\n", s, netlong, lphostlong );
8886 if (!lphostlong) return WSAEFAULT;
8888 *lphostlong = ntohl( netlong );
8889 return 0;
8892 /***********************************************************************
8893 * WSANtohs (WS2_32.65)
8895 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
8897 TRACE( "(%04lx 0x%08x %p)\n", s, netshort, lphostshort );
8899 if (!lphostshort) return WSAEFAULT;
8901 *lphostshort = ntohs( netshort );
8902 return 0;
8905 /***********************************************************************
8906 * WSAProviderConfigChange (WS2_32.66)
8908 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
8909 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
8911 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
8912 return SOCKET_ERROR;
8915 /***********************************************************************
8916 * WSARecvDisconnect (WS2_32.68)
8918 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
8920 TRACE( "(%04lx %p)\n", s, disconnectdata );
8922 return WS_shutdown( s, SD_RECEIVE );
8925 /***********************************************************************
8926 * WSASetServiceA (WS2_32.76)
8928 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
8930 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
8931 return 0;
8934 /***********************************************************************
8935 * WSASetServiceW (WS2_32.77)
8937 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
8939 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
8940 return 0;
8943 /***********************************************************************
8944 * WSCEnableNSProvider (WS2_32.84)
8946 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
8948 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
8949 return 0;
8952 /***********************************************************************
8953 * WSCGetProviderInfo
8955 INT WINAPI WSCGetProviderInfo( LPGUID provider, WSC_PROVIDER_INFO_TYPE info_type,
8956 PBYTE info, size_t* len, DWORD flags, LPINT errcode )
8958 FIXME( "(%s 0x%08x %p %p 0x%08x %p) Stub!\n",
8959 debugstr_guid(provider), info_type, info, len, flags, errcode );
8961 if (!errcode)
8962 return SOCKET_ERROR;
8964 if (!provider) {
8965 *errcode = WSAEFAULT;
8966 return SOCKET_ERROR;
8969 *errcode = WSANO_RECOVERY;
8970 return SOCKET_ERROR;
8973 /***********************************************************************
8974 * WSCGetProviderPath (WS2_32.86)
8976 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
8978 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
8980 if (!errcode || !provider || !len) return WSAEFAULT;
8982 *errcode = WSAEINVAL;
8983 return SOCKET_ERROR;
8986 /***********************************************************************
8987 * WSCInstallNameSpace (WS2_32.87)
8989 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
8990 DWORD version, LPGUID provider )
8992 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
8993 namespace, version, debugstr_guid(provider) );
8994 return 0;
8997 /***********************************************************************
8998 * WSCUnInstallNameSpace (WS2_32.89)
9000 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
9002 FIXME("(%s) Stub!\n", debugstr_guid(lpProviderId));
9003 return NO_ERROR;
9006 /***********************************************************************
9007 * WSCWriteProviderOrder (WS2_32.91)
9009 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
9011 FIXME("(%p 0x%08x) Stub!\n", entry, number);
9012 return 0;
9015 /***********************************************************************
9016 * WSCSetApplicationCategory (WS2_32.@)
9018 INT WINAPI WSCSetApplicationCategory( LPCWSTR path, DWORD len, LPCWSTR extra, DWORD extralen,
9019 DWORD lspcat, DWORD *prev_lspcat, LPINT err )
9021 FIXME("(%s %d %s %d %d %p) Stub!\n", debugstr_w(path), len, debugstr_w(extra),
9022 extralen, lspcat, prev_lspcat);
9023 return 0;
9026 /***********************************************************************
9027 * WSANSPIoctl (WS2_32.91)
9029 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
9030 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
9031 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
9033 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
9034 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
9035 SetLastError(WSA_NOT_ENOUGH_MEMORY);
9036 return SOCKET_ERROR;
9039 /*****************************************************************************
9040 * WSAEnumProtocolsA [WS2_32.@]
9042 * see function WSAEnumProtocolsW
9044 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
9046 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
9049 /*****************************************************************************
9050 * WSAEnumProtocolsW [WS2_32.@]
9052 * Retrieves information about specified set of active network protocols.
9054 * PARAMS
9055 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
9056 * retrieves information on all available protocols.
9057 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
9058 * structures.
9059 * len [I/O] Pointer to a variable specifying buffer size. On output
9060 * the variable holds the number of bytes needed when the
9061 * specified size is too small.
9063 * RETURNS
9064 * Success: number of WSAPROTOCOL_INFO structures in buffer.
9065 * Failure: SOCKET_ERROR
9067 * NOTES
9068 * NT4SP5 does not return SPX if protocols == NULL
9070 * BUGS
9071 * - NT4SP5 returns in addition these list of NETBIOS protocols
9072 * (address family 17), each entry two times one for socket type 2 and 5
9074 * iProtocol szProtocol
9075 * 0x80000000 \Device\NwlnkNb
9076 * 0xfffffffa \Device\NetBT_CBENT7
9077 * 0xfffffffb \Device\Nbf_CBENT7
9078 * 0xfffffffc \Device\NetBT_NdisWan5
9079 * 0xfffffffd \Device\NetBT_El9202
9080 * 0xfffffffe \Device\Nbf_El9202
9081 * 0xffffffff \Device\Nbf_NdisWan4
9083 * - there is no check that the operating system supports the returned
9084 * protocols
9086 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
9088 return WS_EnumProtocols( TRUE, protocols, buffer, len);
9091 /*****************************************************************************
9092 * WSCEnumProtocols [WS2_32.@]
9094 * PARAMS
9095 * protocols [I] Null-terminated array of iProtocol values.
9096 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
9097 * len [I/O] Size of buffer on input/output.
9098 * errno [O] Error code.
9100 * RETURNS
9101 * Success: number of protocols to be reported on.
9102 * Failure: SOCKET_ERROR. error is in errno.
9104 * BUGS
9105 * Doesn't supply info on layered protocols.
9108 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
9110 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
9112 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
9114 return ret;