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).
30 #include "wine/port.h"
35 #include <sys/types.h>
39 #ifdef HAVE_SYS_IOCTL_H
40 # include <sys/ioctl.h>
42 #ifdef HAVE_SYS_FILIO_H
43 # include <sys/filio.h>
45 #ifdef HAVE_SYS_SOCKIO_H
46 # include <sys/sockio.h>
50 # include <sys/so_ioctl.h>
53 #ifdef HAVE_SYS_PARAM_H
54 # include <sys/param.h>
60 #ifdef HAVE_SYS_WAIT_H
61 # include <sys/wait.h>
66 #ifdef HAVE_SYS_SOCKET_H
67 #include <sys/socket.h>
69 #ifdef HAVE_NETINET_IN_H
70 # include <netinet/in.h>
72 #ifdef HAVE_NETINET_TCP_H
73 # include <netinet/tcp.h>
75 #ifdef HAVE_ARPA_INET_H
76 # include <arpa/inet.h>
88 #ifdef HAVE_ARPA_NAMESER_H
89 # include <arpa/nameser.h>
97 #ifdef HAVE_LINUX_FILTER_H
98 # include <linux/filter.h>
101 #ifdef HAVE_NETIPX_IPX_H
102 # include <netipx/ipx.h>
103 #elif defined(HAVE_LINUX_IPX_H)
104 # ifdef HAVE_ASM_TYPES_H
105 # include <asm/types.h>
107 # ifdef HAVE_LINUX_TYPES_H
108 # include <linux/types.h>
110 # include <linux/ipx.h>
112 #if defined(SOL_IPX) || defined(SO_DEFAULT_HEADERS)
116 #ifdef HAVE_LINUX_IRDA_H
117 # ifdef HAVE_LINUX_TYPES_H
118 # include <linux/types.h>
120 # include <linux/irda.h>
127 #ifdef HAVE_SYS_POLL_H
128 # include <sys/poll.h>
130 #ifdef HAVE_SYS_TIME_H
131 # include <sys/time.h>
134 #define NONAMELESSUNION
135 #define NONAMELESSSTRUCT
136 #include "ntstatus.h"
137 #define WIN32_NO_STATUS
142 #include "winerror.h"
144 #include "winsock2.h"
146 #include "ws2tcpip.h"
149 #include "wsnwlink.h"
150 #include "wshisotp.h"
154 #define USE_WC_PREFIX /* For CMSG_DATA */
155 #include "iphlpapi.h"
156 #include "wine/server.h"
157 #include "wine/debug.h"
158 #include "wine/exception.h"
159 #include "wine/unicode.h"
161 #if defined(linux) && !defined(IP_UNICAST_IF)
162 #define IP_UNICAST_IF 50
165 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
166 # define sipx_network sipx_addr.x_net
167 # define sipx_node sipx_addr.x_host.c_host
168 #endif /* __FreeBSD__ */
171 #define INADDR_NONE ~0UL
174 WINE_DEFAULT_DEBUG_CHANNEL(winsock
);
175 WINE_DECLARE_DEBUG_CHANNEL(winediag
);
177 /* names of the protocols */
178 static const WCHAR NameIpxW
[] = {'I', 'P', 'X', '\0'};
179 static const WCHAR NameSpxW
[] = {'S', 'P', 'X', '\0'};
180 static const WCHAR NameSpxIIW
[] = {'S', 'P', 'X', ' ', 'I', 'I', '\0'};
181 static const WCHAR NameTcpW
[] = {'T', 'C', 'P', '/', 'I', 'P', '\0'};
182 static const WCHAR NameUdpW
[] = {'U', 'D', 'P', '/', 'I', 'P', '\0'};
184 /* Taken from Win2k */
185 static const GUID ProviderIdIP
= { 0xe70f1aa0, 0xab8b, 0x11cf,
186 { 0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
187 static const GUID ProviderIdIPX
= { 0x11058240, 0xbe47, 0x11cf,
188 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
189 static const GUID ProviderIdSPX
= { 0x11058241, 0xbe47, 0x11cf,
190 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
192 static const INT valid_protocols
[] =
202 #define IS_IPX_PROTO(X) ((X) >= WS_NSPROTO_IPX && (X) <= WS_NSPROTO_IPX + 255)
204 #if defined(IP_UNICAST_IF) && defined(SO_ATTACH_FILTER)
205 # define LINUX_BOUND_IF
206 struct interface_filter
{
207 struct sock_filter iface_memaddr
;
208 struct sock_filter iface_rule
;
209 struct sock_filter ip_memaddr
;
210 struct sock_filter ip_rule
;
211 struct sock_filter return_keep
;
212 struct sock_filter return_dump
;
214 # define FILTER_JUMP_DUMP(here) (u_char)(offsetof(struct interface_filter, return_dump) \
215 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
216 /sizeof(struct sock_filter)
217 # define FILTER_JUMP_KEEP(here) (u_char)(offsetof(struct interface_filter, return_keep) \
218 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
219 /sizeof(struct sock_filter)
220 # define FILTER_JUMP_NEXT() (u_char)(0)
221 # define SKF_NET_DESTIP 16 /* offset in the network header to the destination IP */
222 static struct interface_filter generic_interface_filter
= {
223 /* This filter rule allows incoming packets on the specified interface, which works for all
224 * remotely generated packets and for locally generated broadcast packets. */
225 BPF_STMT(BPF_LD
+BPF_W
+BPF_ABS
, SKF_AD_OFF
+SKF_AD_IFINDEX
),
226 BPF_JUMP(BPF_JMP
+BPF_JEQ
+BPF_K
, 0xdeadbeef, FILTER_JUMP_KEEP(iface_rule
), FILTER_JUMP_NEXT()),
227 /* This rule allows locally generated packets targeted at the specific IP address of the chosen
228 * adapter (local packets not destined for the broadcast address do not have IFINDEX set) */
229 BPF_STMT(BPF_LD
+BPF_W
+BPF_ABS
, SKF_NET_OFF
+SKF_NET_DESTIP
),
230 BPF_JUMP(BPF_JMP
+BPF_JEQ
+BPF_K
, 0xdeadbeef, FILTER_JUMP_KEEP(ip_rule
), FILTER_JUMP_DUMP(ip_rule
)),
231 BPF_STMT(BPF_RET
+BPF_K
, (u_int
)-1), /* keep packet */
232 BPF_STMT(BPF_RET
+BPF_K
, 0) /* dump packet */
234 #endif /* LINUX_BOUND_IF */
237 * The actual definition of WSASendTo, wrapped in a different function name
238 * so that internal calls from ws2_32 itself will not trigger programs like
239 * Garena, which hooks WSASendTo/WSARecvFrom calls.
241 static int WS2_sendto( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
242 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
243 const struct WS_sockaddr
*to
, int tolen
,
244 LPWSAOVERLAPPED lpOverlapped
,
245 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);
248 * Internal fundamental receive function, essentially WSARecvFrom with an
249 * additional parameter to support message control headers.
251 static int WS2_recv_base( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
252 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
,
253 struct WS_sockaddr
*lpFrom
,
254 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
255 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
,
256 LPWSABUF lpControlBuffer
);
258 /* critical section to protect some non-reentrant net function */
259 static CRITICAL_SECTION csWSgetXXXbyYYY
;
260 static CRITICAL_SECTION_DEBUG critsect_debug
=
262 0, 0, &csWSgetXXXbyYYY
,
263 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
264 0, 0, { (DWORD_PTR
)(__FILE__
": csWSgetXXXbyYYY") }
266 static CRITICAL_SECTION csWSgetXXXbyYYY
= { &critsect_debug
, -1, 0, 0, 0, 0 };
268 union generic_unix_sockaddr
270 struct sockaddr addr
;
271 char data
[128]; /* should be big enough for all families */
274 static inline const char *debugstr_sockaddr( const struct WS_sockaddr
*a
)
276 if (!a
) return "(nil)";
277 switch (a
->sa_family
)
280 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
281 inet_ntoa(((const struct sockaddr_in
*)a
)->sin_addr
),
282 ntohs(((const struct sockaddr_in
*)a
)->sin_port
));
287 struct WS_sockaddr_in6
*sin
= (struct WS_sockaddr_in6
*)a
;
289 p
= WS_inet_ntop( WS_AF_INET6
, &sin
->sin6_addr
, buf
, sizeof(buf
) );
291 p
= "(unknown IPv6 address)";
292 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
293 p
, ntohs(sin
->sin6_port
));
298 char netnum
[16], nodenum
[16];
299 struct WS_sockaddr_ipx
*sin
= (struct WS_sockaddr_ipx
*)a
;
301 for (i
= 0;i
< 4; i
++) sprintf(netnum
+ i
* 2, "%02X", (unsigned char) sin
->sa_netnum
[i
]);
302 for (i
= 0;i
< 6; i
++) sprintf(nodenum
+ i
* 2, "%02X", (unsigned char) sin
->sa_nodenum
[i
]);
304 return wine_dbg_sprintf("{ family AF_IPX, address %s.%s, ipx socket %d }",
305 netnum
, nodenum
, sin
->sa_socket
);
311 memcpy( &addr
, ((const SOCKADDR_IRDA
*)a
)->irdaDeviceID
, sizeof(addr
) );
312 addr
= ntohl( addr
);
313 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
315 ((const SOCKADDR_IRDA
*)a
)->irdaServiceName
);
318 return wine_dbg_sprintf("{ family %d }", a
->sa_family
);
322 static inline const char *debugstr_sockopt(int level
, int optname
)
324 const char *stropt
= NULL
, *strlevel
= NULL
;
326 #define DEBUG_SOCKLEVEL(x) case (x): strlevel = #x
327 #define DEBUG_SOCKOPT(x) case (x): stropt = #x; break
331 DEBUG_SOCKLEVEL(WS_SOL_SOCKET
);
334 DEBUG_SOCKOPT(WS_SO_ACCEPTCONN
);
335 DEBUG_SOCKOPT(WS_SO_BROADCAST
);
336 DEBUG_SOCKOPT(WS_SO_BSP_STATE
);
337 DEBUG_SOCKOPT(WS_SO_CONDITIONAL_ACCEPT
);
338 DEBUG_SOCKOPT(WS_SO_CONNECT_TIME
);
339 DEBUG_SOCKOPT(WS_SO_DEBUG
);
340 DEBUG_SOCKOPT(WS_SO_DONTLINGER
);
341 DEBUG_SOCKOPT(WS_SO_DONTROUTE
);
342 DEBUG_SOCKOPT(WS_SO_ERROR
);
343 DEBUG_SOCKOPT(WS_SO_EXCLUSIVEADDRUSE
);
344 DEBUG_SOCKOPT(WS_SO_GROUP_ID
);
345 DEBUG_SOCKOPT(WS_SO_GROUP_PRIORITY
);
346 DEBUG_SOCKOPT(WS_SO_KEEPALIVE
);
347 DEBUG_SOCKOPT(WS_SO_LINGER
);
348 DEBUG_SOCKOPT(WS_SO_MAX_MSG_SIZE
);
349 DEBUG_SOCKOPT(WS_SO_OOBINLINE
);
350 DEBUG_SOCKOPT(WS_SO_OPENTYPE
);
351 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOA
);
352 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOW
);
353 DEBUG_SOCKOPT(WS_SO_RCVBUF
);
354 DEBUG_SOCKOPT(WS_SO_RCVTIMEO
);
355 DEBUG_SOCKOPT(WS_SO_REUSEADDR
);
356 DEBUG_SOCKOPT(WS_SO_SNDBUF
);
357 DEBUG_SOCKOPT(WS_SO_SNDTIMEO
);
358 DEBUG_SOCKOPT(WS_SO_TYPE
);
362 DEBUG_SOCKLEVEL(WS_NSPROTO_IPX
);
365 DEBUG_SOCKOPT(WS_IPX_PTYPE
);
366 DEBUG_SOCKOPT(WS_IPX_FILTERPTYPE
);
367 DEBUG_SOCKOPT(WS_IPX_DSTYPE
);
368 DEBUG_SOCKOPT(WS_IPX_RECVHDR
);
369 DEBUG_SOCKOPT(WS_IPX_MAXSIZE
);
370 DEBUG_SOCKOPT(WS_IPX_ADDRESS
);
371 DEBUG_SOCKOPT(WS_IPX_MAX_ADAPTER_NUM
);
375 DEBUG_SOCKLEVEL(WS_SOL_IRLMP
);
378 DEBUG_SOCKOPT(WS_IRLMP_ENUMDEVICES
);
382 DEBUG_SOCKLEVEL(WS_IPPROTO_TCP
);
385 DEBUG_SOCKOPT(WS_TCP_BSDURGENT
);
386 DEBUG_SOCKOPT(WS_TCP_EXPEDITED_1122
);
387 DEBUG_SOCKOPT(WS_TCP_NODELAY
);
391 DEBUG_SOCKLEVEL(WS_IPPROTO_IP
);
394 DEBUG_SOCKOPT(WS_IP_ADD_MEMBERSHIP
);
395 DEBUG_SOCKOPT(WS_IP_DROP_MEMBERSHIP
);
396 DEBUG_SOCKOPT(WS_IP_HDRINCL
);
397 DEBUG_SOCKOPT(WS_IP_MULTICAST_IF
);
398 DEBUG_SOCKOPT(WS_IP_MULTICAST_LOOP
);
399 DEBUG_SOCKOPT(WS_IP_MULTICAST_TTL
);
400 DEBUG_SOCKOPT(WS_IP_OPTIONS
);
401 DEBUG_SOCKOPT(WS_IP_PKTINFO
);
402 DEBUG_SOCKOPT(WS_IP_TOS
);
403 DEBUG_SOCKOPT(WS_IP_TTL
);
404 DEBUG_SOCKOPT(WS_IP_UNICAST_IF
);
405 DEBUG_SOCKOPT(WS_IP_DONTFRAGMENT
);
409 DEBUG_SOCKLEVEL(WS_IPPROTO_IPV6
);
412 DEBUG_SOCKOPT(WS_IPV6_ADD_MEMBERSHIP
);
413 DEBUG_SOCKOPT(WS_IPV6_DROP_MEMBERSHIP
);
414 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_IF
);
415 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_HOPS
);
416 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_LOOP
);
417 DEBUG_SOCKOPT(WS_IPV6_UNICAST_HOPS
);
418 DEBUG_SOCKOPT(WS_IPV6_V6ONLY
);
419 DEBUG_SOCKOPT(WS_IPV6_UNICAST_IF
);
420 DEBUG_SOCKOPT(WS_IPV6_DONTFRAG
);
424 #undef DEBUG_SOCKLEVEL
428 strlevel
= wine_dbg_sprintf("WS_0x%x", level
);
430 stropt
= wine_dbg_sprintf("WS_0x%x", optname
);
432 return wine_dbg_sprintf("level %s, name %s", strlevel
+ 3, stropt
+ 3);
435 static inline const char *debugstr_optval(const char *optval
, int optlenval
)
437 if (optval
&& !IS_INTRESOURCE(optval
) && optlenval
>= 1 && optlenval
<= sizeof(DWORD
))
440 memcpy(&value
, optval
, optlenval
);
441 return wine_dbg_sprintf("%p (%u)", optval
, value
);
443 return wine_dbg_sprintf("%p", optval
);
446 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
447 #define SOCKET2HANDLE(s) ((HANDLE)(s))
448 #define HANDLE2SOCKET(h) ((SOCKET)(h))
450 /****************************************************************
451 * Async IO declarations
452 ****************************************************************/
456 struct ws2_async_io
*next
;
459 struct ws2_async_shutdown
461 struct ws2_async_io io
;
463 IO_STATUS_BLOCK iosb
;
469 struct ws2_async_io io
;
471 LPWSAOVERLAPPED user_overlapped
;
472 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func
;
473 IO_STATUS_BLOCK local_iosb
;
474 struct WS_sockaddr
*addr
;
477 int val
; /* for send operations */
478 int *ptr
; /* for recv operations */
483 unsigned int n_iovecs
;
484 unsigned int first_iovec
;
485 struct iovec iovec
[1];
488 struct ws2_accept_async
490 struct ws2_async_io io
;
491 HANDLE listen_socket
;
492 HANDLE accept_socket
;
493 LPOVERLAPPED user_overlapped
;
495 PVOID buf
; /* buffer to write data to */
499 struct ws2_async
*read
;
502 static struct ws2_async_io
*async_io_freelist
;
504 static void release_async_io( struct ws2_async_io
*io
)
508 struct ws2_async_io
*next
= async_io_freelist
;
510 if (InterlockedCompareExchangePointer( (void **)&async_io_freelist
, io
, next
) == next
) return;
514 static struct ws2_async_io
*alloc_async_io( DWORD size
)
516 /* first free remaining previous fileinfos */
518 struct ws2_async_io
*io
= InterlockedExchangePointer( (void **)&async_io_freelist
, NULL
);
522 struct ws2_async_io
*next
= io
->next
;
523 HeapFree( GetProcessHeap(), 0, io
);
527 return HeapAlloc( GetProcessHeap(), 0, size
);
530 /****************************************************************/
532 /* ----------------------------------- internal data */
534 /* ws_... struct conversion flags */
536 typedef struct /* WSAAsyncSelect() control struct */
538 HANDLE service
, event
, sock
;
544 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
545 #define WS_MAX_UDP_DATAGRAM 1024
546 static INT WINAPI
WSA_DefaultBlockingHook( FARPROC x
);
548 /* hostent's, servent's and protent's are stored in one buffer per thread,
549 * as documented on MSDN for the functions that return any of the buffers */
550 struct per_thread_data
553 struct WS_hostent
*he_buffer
;
554 struct WS_servent
*se_buffer
;
555 struct WS_protoent
*pe_buffer
;
559 char ntoa_buffer
[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
562 /* internal: routing description information */
569 static INT num_startup
; /* reference counter */
570 static FARPROC blocking_hook
= (FARPROC
)WSA_DefaultBlockingHook
;
572 /* function prototypes */
573 static struct WS_hostent
*WS_create_he(char *name
, int aliases
, int aliases_size
, int addresses
, int address_length
);
574 static struct WS_hostent
*WS_dup_he(const struct hostent
* p_he
);
575 static struct WS_protoent
*WS_dup_pe(const struct protoent
* p_pe
);
576 static struct WS_servent
*WS_dup_se(const struct servent
* p_se
);
577 static int ws_protocol_info(SOCKET s
, int unicode
, WSAPROTOCOL_INFOW
*buffer
, int *size
);
579 int WSAIOCTL_GetInterfaceCount(void);
580 int WSAIOCTL_GetInterfaceName(int intNumber
, char *intName
);
582 static void WS_AddCompletion( SOCKET sock
, ULONG_PTR CompletionValue
, NTSTATUS CompletionStatus
, ULONG Information
);
584 #define MAP_OPTION(opt) { WS_##opt, opt }
586 static const int ws_flags_map
[][2] =
588 MAP_OPTION( MSG_OOB
),
589 MAP_OPTION( MSG_PEEK
),
590 MAP_OPTION( MSG_DONTROUTE
),
591 MAP_OPTION( MSG_WAITALL
),
594 static const int ws_sock_map
[][2] =
596 MAP_OPTION( SO_DEBUG
),
597 MAP_OPTION( SO_ACCEPTCONN
),
598 MAP_OPTION( SO_REUSEADDR
),
599 MAP_OPTION( SO_KEEPALIVE
),
600 MAP_OPTION( SO_DONTROUTE
),
601 MAP_OPTION( SO_BROADCAST
),
602 MAP_OPTION( SO_LINGER
),
603 MAP_OPTION( SO_OOBINLINE
),
604 MAP_OPTION( SO_SNDBUF
),
605 MAP_OPTION( SO_RCVBUF
),
606 MAP_OPTION( SO_ERROR
),
607 MAP_OPTION( SO_TYPE
),
609 MAP_OPTION( SO_RCVTIMEO
),
612 MAP_OPTION( SO_SNDTIMEO
),
616 static const int ws_tcp_map
[][2] =
619 MAP_OPTION( TCP_NODELAY
),
623 static const int ws_ip_map
[][2] =
625 MAP_OPTION( IP_MULTICAST_IF
),
626 MAP_OPTION( IP_MULTICAST_TTL
),
627 MAP_OPTION( IP_MULTICAST_LOOP
),
628 MAP_OPTION( IP_ADD_MEMBERSHIP
),
629 MAP_OPTION( IP_DROP_MEMBERSHIP
),
630 MAP_OPTION( IP_OPTIONS
),
632 MAP_OPTION( IP_HDRINCL
),
634 MAP_OPTION( IP_TOS
),
635 MAP_OPTION( IP_TTL
),
637 MAP_OPTION( IP_PKTINFO
),
640 MAP_OPTION( IP_UNICAST_IF
),
644 static const int ws_ipv6_map
[][2] =
646 #ifdef IPV6_ADD_MEMBERSHIP
647 MAP_OPTION( IPV6_ADD_MEMBERSHIP
),
649 #ifdef IPV6_DROP_MEMBERSHIP
650 MAP_OPTION( IPV6_DROP_MEMBERSHIP
),
652 MAP_OPTION( IPV6_MULTICAST_IF
),
653 MAP_OPTION( IPV6_MULTICAST_HOPS
),
654 MAP_OPTION( IPV6_MULTICAST_LOOP
),
655 MAP_OPTION( IPV6_UNICAST_HOPS
),
656 MAP_OPTION( IPV6_V6ONLY
),
657 #ifdef IPV6_UNICAST_IF
658 MAP_OPTION( IPV6_UNICAST_IF
),
662 static const int ws_af_map
[][2] =
664 MAP_OPTION( AF_UNSPEC
),
665 MAP_OPTION( AF_INET
),
666 MAP_OPTION( AF_INET6
),
668 MAP_OPTION( AF_IPX
),
671 MAP_OPTION( AF_IRDA
),
673 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
676 static const int ws_socktype_map
[][2] =
678 MAP_OPTION( SOCK_DGRAM
),
679 MAP_OPTION( SOCK_STREAM
),
680 MAP_OPTION( SOCK_RAW
),
681 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
684 static const int ws_proto_map
[][2] =
686 MAP_OPTION( IPPROTO_IP
),
687 MAP_OPTION( IPPROTO_TCP
),
688 MAP_OPTION( IPPROTO_UDP
),
689 MAP_OPTION( IPPROTO_ICMP
),
690 MAP_OPTION( IPPROTO_IGMP
),
691 MAP_OPTION( IPPROTO_RAW
),
692 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
695 static const int ws_aiflag_map
[][2] =
697 MAP_OPTION( AI_PASSIVE
),
698 MAP_OPTION( AI_CANONNAME
),
699 MAP_OPTION( AI_NUMERICHOST
),
700 #ifdef AI_NUMERICSERV
701 MAP_OPTION( AI_NUMERICSERV
),
704 MAP_OPTION( AI_V4MAPPED
),
706 MAP_OPTION( AI_ADDRCONFIG
),
709 static const int ws_niflag_map
[][2] =
711 MAP_OPTION( NI_NOFQDN
),
712 MAP_OPTION( NI_NUMERICHOST
),
713 MAP_OPTION( NI_NAMEREQD
),
714 MAP_OPTION( NI_NUMERICSERV
),
715 MAP_OPTION( NI_DGRAM
),
718 static const int ws_eai_map
[][2] =
720 MAP_OPTION( EAI_AGAIN
),
721 MAP_OPTION( EAI_BADFLAGS
),
722 MAP_OPTION( EAI_FAIL
),
723 MAP_OPTION( EAI_FAMILY
),
724 MAP_OPTION( EAI_MEMORY
),
725 /* Note: EAI_NODATA is deprecated, but still
726 * used by Windows and Linux... We map the newer
727 * EAI_NONAME to EAI_NODATA for now until Windows
731 MAP_OPTION( EAI_NODATA
),
734 { WS_EAI_NODATA
, EAI_NONAME
},
737 MAP_OPTION( EAI_SERVICE
),
738 MAP_OPTION( EAI_SOCKTYPE
),
742 static const char magic_loopback_addr
[] = {127, 12, 34, 56};
744 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
746 static inline WSACMSGHDR
*fill_control_message(int level
, int type
, WSACMSGHDR
*current
, ULONG
*maxsize
, void *data
, int len
)
748 ULONG msgsize
= sizeof(WSACMSGHDR
) + WSA_CMSG_ALIGN(len
);
749 char *ptr
= (char *) current
+ sizeof(WSACMSGHDR
);
751 /* Make sure there is at least enough room for this entry */
752 if (msgsize
> *maxsize
)
755 /* Fill in the entry */
756 current
->cmsg_len
= sizeof(WSACMSGHDR
) + len
;
757 current
->cmsg_level
= level
;
758 current
->cmsg_type
= type
;
759 memcpy(ptr
, data
, len
);
760 /* Return the pointer to where next entry should go */
761 return (WSACMSGHDR
*) (ptr
+ WSA_CMSG_ALIGN(len
));
763 #endif /* IP_PKTINFO */
765 static inline int convert_control_headers(struct msghdr
*hdr
, WSABUF
*control
)
768 WSACMSGHDR
*cmsg_win
= (WSACMSGHDR
*) control
->buf
, *ptr
;
769 ULONG ctlsize
= control
->len
;
770 struct cmsghdr
*cmsg_unix
;
773 /* Loop over all the headers, converting as appropriate */
774 for (cmsg_unix
= CMSG_FIRSTHDR(hdr
); cmsg_unix
!= NULL
; cmsg_unix
= CMSG_NXTHDR(hdr
, cmsg_unix
))
776 switch(cmsg_unix
->cmsg_level
)
779 switch(cmsg_unix
->cmsg_type
)
783 /* Convert the Unix IP_PKTINFO structure to the Windows version */
784 struct in_pktinfo
*data_unix
= (struct in_pktinfo
*) CMSG_DATA(cmsg_unix
);
785 struct WS_in_pktinfo data_win
;
787 memcpy(&data_win
.ipi_addr
,&data_unix
->ipi_addr
.s_addr
,4); /* 4 bytes = 32 address bits */
788 data_win
.ipi_ifindex
= data_unix
->ipi_ifindex
;
789 ptr
= fill_control_message(WS_IPPROTO_IP
, WS_IP_PKTINFO
, ptr
, &ctlsize
,
790 (void*)&data_win
, sizeof(data_win
));
791 if (!ptr
) goto error
;
794 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix
->cmsg_type
);
799 FIXME("Unhandled message header level %d\n", cmsg_unix
->cmsg_level
);
805 /* Set the length of the returned control headers */
806 control
->len
= (ptr
== NULL
? 0 : (char*)ptr
- (char*)cmsg_win
);
807 return (ptr
!= NULL
);
808 #else /* IP_PKTINFO */
811 #endif /* IP_PKTINFO */
813 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
815 /* ----------------------------------- error handling */
817 static NTSTATUS
sock_get_ntstatus( int err
)
821 case EBADF
: return STATUS_INVALID_HANDLE
;
822 case EBUSY
: return STATUS_DEVICE_BUSY
;
824 case EACCES
: return STATUS_ACCESS_DENIED
;
825 case EFAULT
: return STATUS_NO_MEMORY
;
826 case EINVAL
: return STATUS_INVALID_PARAMETER
;
828 case EMFILE
: return STATUS_TOO_MANY_OPENED_FILES
;
829 case EWOULDBLOCK
: return STATUS_CANT_WAIT
;
830 case EINPROGRESS
: return STATUS_PENDING
;
831 case EALREADY
: return STATUS_NETWORK_BUSY
;
832 case ENOTSOCK
: return STATUS_OBJECT_TYPE_MISMATCH
;
833 case EDESTADDRREQ
: return STATUS_INVALID_PARAMETER
;
834 case EMSGSIZE
: return STATUS_BUFFER_OVERFLOW
;
835 case EPROTONOSUPPORT
:
836 case ESOCKTNOSUPPORT
:
839 case EPROTOTYPE
: return STATUS_NOT_SUPPORTED
;
840 case ENOPROTOOPT
: return STATUS_INVALID_PARAMETER
;
841 case EOPNOTSUPP
: return STATUS_NOT_SUPPORTED
;
842 case EADDRINUSE
: return STATUS_ADDRESS_ALREADY_ASSOCIATED
;
843 case EADDRNOTAVAIL
: return STATUS_INVALID_PARAMETER
;
844 case ECONNREFUSED
: return STATUS_CONNECTION_REFUSED
;
845 case ESHUTDOWN
: return STATUS_PIPE_DISCONNECTED
;
846 case ENOTCONN
: return STATUS_CONNECTION_DISCONNECTED
;
847 case ETIMEDOUT
: return STATUS_IO_TIMEOUT
;
848 case ENETUNREACH
: return STATUS_NETWORK_UNREACHABLE
;
849 case ENETDOWN
: return STATUS_NETWORK_BUSY
;
851 case ECONNRESET
: return STATUS_CONNECTION_RESET
;
852 case ECONNABORTED
: return STATUS_CONNECTION_ABORTED
;
854 case 0: return STATUS_SUCCESS
;
856 WARN("Unknown errno %d!\n", err
);
857 return STATUS_UNSUCCESSFUL
;
861 static UINT
sock_get_error( int err
)
865 case EINTR
: return WSAEINTR
;
867 case EACCES
: return WSAEACCES
;
868 case EFAULT
: return WSAEFAULT
;
869 case EINVAL
: return WSAEINVAL
;
870 case EMFILE
: return WSAEMFILE
;
871 case EWOULDBLOCK
: return WSAEWOULDBLOCK
;
872 case EINPROGRESS
: return WSAEINPROGRESS
;
873 case EALREADY
: return WSAEALREADY
;
875 case ENOTSOCK
: return WSAENOTSOCK
;
876 case EDESTADDRREQ
: return WSAEDESTADDRREQ
;
877 case EMSGSIZE
: return WSAEMSGSIZE
;
878 case EPROTOTYPE
: return WSAEPROTOTYPE
;
879 case ENOPROTOOPT
: return WSAENOPROTOOPT
;
880 case EPROTONOSUPPORT
: return WSAEPROTONOSUPPORT
;
881 case ESOCKTNOSUPPORT
: return WSAESOCKTNOSUPPORT
;
882 case EOPNOTSUPP
: return WSAEOPNOTSUPP
;
883 case EPFNOSUPPORT
: return WSAEPFNOSUPPORT
;
884 case EAFNOSUPPORT
: return WSAEAFNOSUPPORT
;
885 case EADDRINUSE
: return WSAEADDRINUSE
;
886 case EADDRNOTAVAIL
: return WSAEADDRNOTAVAIL
;
887 case ENETDOWN
: return WSAENETDOWN
;
888 case ENETUNREACH
: return WSAENETUNREACH
;
889 case ENETRESET
: return WSAENETRESET
;
890 case ECONNABORTED
: return WSAECONNABORTED
;
892 case ECONNRESET
: return WSAECONNRESET
;
893 case ENOBUFS
: return WSAENOBUFS
;
894 case EISCONN
: return WSAEISCONN
;
895 case ENOTCONN
: return WSAENOTCONN
;
896 case ESHUTDOWN
: return WSAESHUTDOWN
;
897 case ETOOMANYREFS
: return WSAETOOMANYREFS
;
898 case ETIMEDOUT
: return WSAETIMEDOUT
;
899 case ECONNREFUSED
: return WSAECONNREFUSED
;
900 case ELOOP
: return WSAELOOP
;
901 case ENAMETOOLONG
: return WSAENAMETOOLONG
;
902 case EHOSTDOWN
: return WSAEHOSTDOWN
;
903 case EHOSTUNREACH
: return WSAEHOSTUNREACH
;
904 case ENOTEMPTY
: return WSAENOTEMPTY
;
906 case EPROCLIM
: return WSAEPROCLIM
;
909 case EUSERS
: return WSAEUSERS
;
912 case EDQUOT
: return WSAEDQUOT
;
915 case ESTALE
: return WSAESTALE
;
918 case EREMOTE
: return WSAEREMOTE
;
921 /* just in case we ever get here and there are no problems */
924 WARN("Unknown errno %d!\n", err
);
925 return WSAEOPNOTSUPP
;
929 static UINT
wsaErrno(void)
931 int loc_errno
= errno
;
932 WARN("errno %d, (%s).\n", loc_errno
, strerror(loc_errno
));
934 return sock_get_error( loc_errno
);
937 /* most ws2 overlapped functions return an ntstatus-based error code */
938 static NTSTATUS
wsaErrStatus(void)
940 int loc_errno
= errno
;
941 WARN("errno %d, (%s).\n", loc_errno
, strerror(loc_errno
));
943 return sock_get_ntstatus(loc_errno
);
946 static UINT
wsaHerrno(int loc_errno
)
948 WARN("h_errno %d.\n", loc_errno
);
952 case HOST_NOT_FOUND
: return WSAHOST_NOT_FOUND
;
953 case TRY_AGAIN
: return WSATRY_AGAIN
;
954 case NO_RECOVERY
: return WSANO_RECOVERY
;
955 case NO_DATA
: return WSANO_DATA
;
956 case ENOBUFS
: return WSAENOBUFS
;
960 WARN("Unknown h_errno %d!\n", loc_errno
);
961 return WSAEOPNOTSUPP
;
965 static inline DWORD
NtStatusToWSAError( const DWORD status
)
967 /* We only need to cover the status codes set by server async request handling */
971 case STATUS_SUCCESS
: wserr
= 0; break;
972 case STATUS_PENDING
: wserr
= WSA_IO_PENDING
; break;
973 case STATUS_OBJECT_TYPE_MISMATCH
: wserr
= WSAENOTSOCK
; break;
974 case STATUS_INVALID_HANDLE
: wserr
= WSAEBADF
; break;
975 case STATUS_INVALID_PARAMETER
: wserr
= WSAEINVAL
; break;
976 case STATUS_PIPE_DISCONNECTED
: wserr
= WSAESHUTDOWN
; break;
977 case STATUS_NETWORK_BUSY
: wserr
= WSAEALREADY
; break;
978 case STATUS_NETWORK_UNREACHABLE
: wserr
= WSAENETUNREACH
; break;
979 case STATUS_CONNECTION_REFUSED
: wserr
= WSAECONNREFUSED
; break;
980 case STATUS_CONNECTION_DISCONNECTED
: wserr
= WSAENOTCONN
; break;
981 case STATUS_CONNECTION_RESET
: wserr
= WSAECONNRESET
; break;
982 case STATUS_CONNECTION_ABORTED
: wserr
= WSAECONNABORTED
; break;
983 case STATUS_CANCELLED
: wserr
= WSA_OPERATION_ABORTED
; break;
984 case STATUS_ADDRESS_ALREADY_ASSOCIATED
: wserr
= WSAEADDRINUSE
; break;
985 case STATUS_IO_TIMEOUT
:
986 case STATUS_TIMEOUT
: wserr
= WSAETIMEDOUT
; break;
987 case STATUS_NO_MEMORY
: wserr
= WSAEFAULT
; break;
988 case STATUS_ACCESS_DENIED
: wserr
= WSAEACCES
; break;
989 case STATUS_TOO_MANY_OPENED_FILES
: wserr
= WSAEMFILE
; break;
990 case STATUS_CANT_WAIT
: wserr
= WSAEWOULDBLOCK
; break;
991 case STATUS_BUFFER_OVERFLOW
: wserr
= WSAEMSGSIZE
; break;
992 case STATUS_NOT_SUPPORTED
: wserr
= WSAEOPNOTSUPP
; break;
993 case STATUS_HOST_UNREACHABLE
: wserr
= WSAEHOSTUNREACH
; break;
996 wserr
= RtlNtStatusToDosError( status
);
997 FIXME( "Status code %08x converted to DOS error code %x\n", status
, wserr
);
1002 /* set last error code from NT status without mapping WSA errors */
1003 static inline unsigned int set_error( unsigned int err
)
1007 err
= NtStatusToWSAError( err
);
1008 SetLastError( err
);
1013 static inline int get_sock_fd( SOCKET s
, DWORD access
, unsigned int *options
)
1016 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s
), access
, &fd
, options
) ))
1021 static inline void release_sock_fd( SOCKET s
, int fd
)
1023 wine_server_release_fd( SOCKET2HANDLE(s
), fd
);
1026 static void _enable_event( HANDLE s
, unsigned int event
,
1027 unsigned int sstate
, unsigned int cstate
)
1029 SERVER_START_REQ( enable_socket_event
)
1031 req
->handle
= wine_server_obj_handle( s
);
1033 req
->sstate
= sstate
;
1034 req
->cstate
= cstate
;
1035 wine_server_call( req
);
1040 static NTSTATUS
_is_blocking(SOCKET s
, BOOL
*ret
)
1043 SERVER_START_REQ( get_socket_event
)
1045 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1046 req
->service
= FALSE
;
1048 status
= wine_server_call( req
);
1049 *ret
= (reply
->state
& FD_WINE_NONBLOCKING
) == 0;
1055 static unsigned int _get_sock_mask(SOCKET s
)
1058 SERVER_START_REQ( get_socket_event
)
1060 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1061 req
->service
= FALSE
;
1063 wine_server_call( req
);
1070 static void _sync_sock_state(SOCKET s
)
1073 /* do a dummy wineserver request in order to let
1074 the wineserver run through its select loop once */
1075 (void)_is_blocking(s
, &dummy
);
1078 static void _get_sock_errors(SOCKET s
, int *events
)
1080 SERVER_START_REQ( get_socket_event
)
1082 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1083 req
->service
= FALSE
;
1085 wine_server_set_reply( req
, events
, sizeof(int) * FD_MAX_EVENTS
);
1086 wine_server_call( req
);
1091 static int _get_sock_error(SOCKET s
, unsigned int bit
)
1093 int events
[FD_MAX_EVENTS
];
1094 _get_sock_errors(s
, events
);
1098 static struct per_thread_data
*get_per_thread_data(void)
1100 struct per_thread_data
* ptb
= NtCurrentTeb()->WinSockData
;
1101 /* lazy initialization */
1104 ptb
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(*ptb
) );
1105 NtCurrentTeb()->WinSockData
= ptb
;
1110 static void free_per_thread_data(void)
1112 struct per_thread_data
* ptb
= NtCurrentTeb()->WinSockData
;
1116 /* delete scratch buffers */
1117 HeapFree( GetProcessHeap(), 0, ptb
->he_buffer
);
1118 HeapFree( GetProcessHeap(), 0, ptb
->se_buffer
);
1119 HeapFree( GetProcessHeap(), 0, ptb
->pe_buffer
);
1120 ptb
->he_buffer
= NULL
;
1121 ptb
->se_buffer
= NULL
;
1122 ptb
->pe_buffer
= NULL
;
1124 HeapFree( GetProcessHeap(), 0, ptb
);
1125 NtCurrentTeb()->WinSockData
= NULL
;
1128 /***********************************************************************
1129 * DllMain (WS2_32.init)
1131 BOOL WINAPI
DllMain(HINSTANCE hInstDLL
, DWORD fdwReason
, LPVOID fImpLoad
)
1133 TRACE("%p 0x%x %p\n", hInstDLL
, fdwReason
, fImpLoad
);
1134 switch (fdwReason
) {
1135 case DLL_PROCESS_ATTACH
:
1137 case DLL_PROCESS_DETACH
:
1138 if (fImpLoad
) break;
1139 free_per_thread_data();
1140 DeleteCriticalSection(&csWSgetXXXbyYYY
);
1142 case DLL_THREAD_DETACH
:
1143 free_per_thread_data();
1149 /***********************************************************************
1152 * Converts send/recv flags from Windows format.
1153 * Return the converted flag bits, unsupported flags remain unchanged.
1155 static int convert_flags(int flags
)
1158 if (!flags
) return 0;
1160 for (out
= i
= 0; flags
&& i
< sizeof(ws_flags_map
) / sizeof(ws_flags_map
[0]); i
++)
1162 if (ws_flags_map
[i
][0] & flags
)
1164 out
|= ws_flags_map
[i
][1];
1165 flags
&= ~ws_flags_map
[i
][0];
1170 FIXME("Unknown send/recv flags 0x%x, using anyway...\n", flags
);
1176 /***********************************************************************
1179 * Converts socket flags from Windows format.
1180 * Return 1 if converted, 0 if not (error).
1182 static int convert_sockopt(INT
*level
, INT
*optname
)
1188 *level
= SOL_SOCKET
;
1189 for(i
=0; i
<sizeof(ws_sock_map
)/sizeof(ws_sock_map
[0]); i
++) {
1190 if( ws_sock_map
[i
][0] == *optname
)
1192 *optname
= ws_sock_map
[i
][1];
1196 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname
);
1198 case WS_IPPROTO_TCP
:
1199 *level
= IPPROTO_TCP
;
1200 for(i
=0; i
<sizeof(ws_tcp_map
)/sizeof(ws_tcp_map
[0]); i
++) {
1201 if ( ws_tcp_map
[i
][0] == *optname
)
1203 *optname
= ws_tcp_map
[i
][1];
1207 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname
);
1210 *level
= IPPROTO_IP
;
1211 for(i
=0; i
<sizeof(ws_ip_map
)/sizeof(ws_ip_map
[0]); i
++) {
1212 if (ws_ip_map
[i
][0] == *optname
)
1214 *optname
= ws_ip_map
[i
][1];
1218 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname
);
1220 case WS_IPPROTO_IPV6
:
1221 *level
= IPPROTO_IPV6
;
1222 for(i
=0; i
<sizeof(ws_ipv6_map
)/sizeof(ws_ipv6_map
[0]); i
++) {
1223 if (ws_ipv6_map
[i
][0] == *optname
)
1225 *optname
= ws_ipv6_map
[i
][1];
1229 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname
);
1231 default: FIXME("Unimplemented or unknown socket level\n");
1236 /* ----------------------------------- Per-thread info (or per-process?) */
1238 static char *strdup_lower(const char *str
)
1241 char *ret
= HeapAlloc( GetProcessHeap(), 0, strlen(str
) + 1 );
1245 for (i
= 0; str
[i
]; i
++) ret
[i
] = tolower(str
[i
]);
1248 else SetLastError(WSAENOBUFS
);
1252 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1253 * from an fd and return the value converted to milli seconds
1254 * or -1 if there is an infinite time out */
1255 static inline int get_rcvsnd_timeo( int fd
, int optname
)
1258 socklen_t len
= sizeof(tv
);
1259 int ret
= getsockopt(fd
, SOL_SOCKET
, optname
, &tv
, &len
);
1261 ret
= tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000;
1262 if( ret
<= 0 ) /* tv == {0,0} means infinite time out */
1267 /* macro wrappers for portability */
1269 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
1271 #define GET_RCVTIMEO(fd) (-1)
1275 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
1277 #define GET_SNDTIMEO(fd) (-1)
1280 /* utility: given an fd, will block until one of the events occurs */
1281 static inline int do_block( int fd
, int events
, int timeout
)
1287 pfd
.events
= events
;
1289 while ((ret
= poll(&pfd
, 1, timeout
)) < 0)
1300 convert_af_w2u(int windowsaf
) {
1303 for (i
=0;i
<sizeof(ws_af_map
)/sizeof(ws_af_map
[0]);i
++)
1304 if (ws_af_map
[i
][0] == windowsaf
)
1305 return ws_af_map
[i
][1];
1306 FIXME("unhandled Windows address family %d\n", windowsaf
);
1311 convert_af_u2w(int unixaf
) {
1314 for (i
=0;i
<sizeof(ws_af_map
)/sizeof(ws_af_map
[0]);i
++)
1315 if (ws_af_map
[i
][1] == unixaf
)
1316 return ws_af_map
[i
][0];
1317 FIXME("unhandled UNIX address family %d\n", unixaf
);
1322 convert_proto_w2u(int windowsproto
) {
1325 for (i
=0;i
<sizeof(ws_proto_map
)/sizeof(ws_proto_map
[0]);i
++)
1326 if (ws_proto_map
[i
][0] == windowsproto
)
1327 return ws_proto_map
[i
][1];
1329 /* check for extended IPX */
1330 if (IS_IPX_PROTO(windowsproto
))
1331 return windowsproto
;
1333 FIXME("unhandled Windows socket protocol %d\n", windowsproto
);
1338 convert_proto_u2w(int unixproto
) {
1341 for (i
=0;i
<sizeof(ws_proto_map
)/sizeof(ws_proto_map
[0]);i
++)
1342 if (ws_proto_map
[i
][1] == unixproto
)
1343 return ws_proto_map
[i
][0];
1345 /* if value is inside IPX range just return it - the kernel simply
1346 * echoes the value used in the socket() function */
1347 if (IS_IPX_PROTO(unixproto
))
1350 FIXME("unhandled UNIX socket protocol %d\n", unixproto
);
1355 convert_socktype_w2u(int windowssocktype
) {
1358 for (i
=0;i
<sizeof(ws_socktype_map
)/sizeof(ws_socktype_map
[0]);i
++)
1359 if (ws_socktype_map
[i
][0] == windowssocktype
)
1360 return ws_socktype_map
[i
][1];
1361 FIXME("unhandled Windows socket type %d\n", windowssocktype
);
1366 convert_socktype_u2w(int unixsocktype
) {
1369 for (i
=0;i
<sizeof(ws_socktype_map
)/sizeof(ws_socktype_map
[0]);i
++)
1370 if (ws_socktype_map
[i
][1] == unixsocktype
)
1371 return ws_socktype_map
[i
][0];
1372 FIXME("unhandled UNIX socket type %d\n", unixsocktype
);
1376 static int set_ipx_packettype(int sock
, int ptype
)
1379 int fd
= get_sock_fd( sock
, 0, NULL
), ret
= 0;
1380 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype
, fd
);
1382 if (fd
== -1) return SOCKET_ERROR
;
1384 /* We try to set the ipx type on ipx socket level. */
1386 if(setsockopt(fd
, SOL_IPX
, IPX_TYPE
, &ptype
, sizeof(ptype
)) == -1)
1388 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1394 /* Should we retrieve val using a getsockopt call and then
1395 * set the modified one? */
1397 setsockopt(fd
, 0, SO_DEFAULT_HEADERS
, &val
, sizeof(struct ipx
));
1400 release_sock_fd( sock
, fd
);
1403 WARN("IPX support is not enabled, can't set packet type\n");
1404 return SOCKET_ERROR
;
1408 /* ----------------------------------- API -----
1410 * Init / cleanup / error checking.
1413 /***********************************************************************
1414 * WSAStartup (WS2_32.115)
1416 int WINAPI
WSAStartup(WORD wVersionRequested
, LPWSADATA lpWSAData
)
1418 TRACE("verReq=%x\n", wVersionRequested
);
1420 if (LOBYTE(wVersionRequested
) < 1)
1421 return WSAVERNOTSUPPORTED
;
1423 if (!lpWSAData
) return WSAEINVAL
;
1427 /* that's the whole of the negotiation for now */
1428 lpWSAData
->wVersion
= wVersionRequested
;
1429 /* return winsock information */
1430 lpWSAData
->wHighVersion
= 0x0202;
1431 strcpy(lpWSAData
->szDescription
, "WinSock 2.0" );
1432 strcpy(lpWSAData
->szSystemStatus
, "Running" );
1433 lpWSAData
->iMaxSockets
= WS_MAX_SOCKETS_PER_PROCESS
;
1434 lpWSAData
->iMaxUdpDg
= WS_MAX_UDP_DATAGRAM
;
1435 /* don't do anything with lpWSAData->lpVendorInfo */
1436 /* (some apps don't allocate the space for this field) */
1438 TRACE("succeeded starts: %d\n", num_startup
);
1443 /***********************************************************************
1444 * WSACleanup (WS2_32.116)
1446 INT WINAPI
WSACleanup(void)
1450 TRACE("pending cleanups: %d\n", num_startup
);
1453 SetLastError(WSANOTINITIALISED
);
1454 return SOCKET_ERROR
;
1458 /***********************************************************************
1459 * WSAGetLastError (WS2_32.111)
1461 INT WINAPI
WSAGetLastError(void)
1463 return GetLastError();
1466 /***********************************************************************
1467 * WSASetLastError (WS2_32.112)
1469 void WINAPI
WSASetLastError(INT iError
) {
1470 SetLastError(iError
);
1473 static struct WS_hostent
*check_buffer_he(int size
)
1475 struct per_thread_data
* ptb
= get_per_thread_data();
1478 if (ptb
->he_len
>= size
) return ptb
->he_buffer
;
1479 HeapFree( GetProcessHeap(), 0, ptb
->he_buffer
);
1481 ptb
->he_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->he_len
= size
) );
1482 if (!ptb
->he_buffer
) SetLastError(WSAENOBUFS
);
1483 return ptb
->he_buffer
;
1486 static struct WS_servent
*check_buffer_se(int size
)
1488 struct per_thread_data
* ptb
= get_per_thread_data();
1491 if (ptb
->se_len
>= size
) return ptb
->se_buffer
;
1492 HeapFree( GetProcessHeap(), 0, ptb
->se_buffer
);
1494 ptb
->se_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->se_len
= size
) );
1495 if (!ptb
->se_buffer
) SetLastError(WSAENOBUFS
);
1496 return ptb
->se_buffer
;
1499 static struct WS_protoent
*check_buffer_pe(int size
)
1501 struct per_thread_data
* ptb
= get_per_thread_data();
1504 if (ptb
->pe_len
>= size
) return ptb
->pe_buffer
;
1505 HeapFree( GetProcessHeap(), 0, ptb
->pe_buffer
);
1507 ptb
->pe_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->pe_len
= size
) );
1508 if (!ptb
->pe_buffer
) SetLastError(WSAENOBUFS
);
1509 return ptb
->pe_buffer
;
1512 /* ----------------------------------- i/o APIs */
1514 static inline BOOL
supported_pf(int pf
)
1534 static inline BOOL
supported_protocol(int protocol
)
1537 for (i
= 0; i
< sizeof(valid_protocols
) / sizeof(valid_protocols
[0]); i
++)
1538 if (protocol
== valid_protocols
[i
])
1543 /**********************************************************************/
1545 /* Returns the length of the converted address if successful, 0 if it was too small to
1548 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr
* wsaddr
, int wsaddrlen
,
1549 union generic_unix_sockaddr
*uaddr
)
1551 unsigned int uaddrlen
= 0;
1553 switch (wsaddr
->sa_family
)
1558 const struct WS_sockaddr_ipx
* wsipx
=(const struct WS_sockaddr_ipx
*)wsaddr
;
1559 struct sockaddr_ipx
* uipx
= (struct sockaddr_ipx
*)uaddr
;
1561 if (wsaddrlen
<sizeof(struct WS_sockaddr_ipx
))
1564 uaddrlen
= sizeof(struct sockaddr_ipx
);
1565 memset( uaddr
, 0, uaddrlen
);
1566 uipx
->sipx_family
=AF_IPX
;
1567 uipx
->sipx_port
=wsipx
->sa_socket
;
1568 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1571 memcpy(&uipx
->sipx_network
,wsipx
->sa_netnum
,sizeof(uipx
->sipx_network
)+sizeof(uipx
->sipx_node
));
1572 #ifdef IPX_FRAME_NONE
1573 uipx
->sipx_type
=IPX_FRAME_NONE
;
1579 struct sockaddr_in6
* uin6
= (struct sockaddr_in6
*)uaddr
;
1580 const struct WS_sockaddr_in6
* win6
= (const struct WS_sockaddr_in6
*)wsaddr
;
1582 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1583 * scope_id, one without.
1585 if (wsaddrlen
>= sizeof(struct WS_sockaddr_in6_old
)) {
1586 uaddrlen
= sizeof(struct sockaddr_in6
);
1587 memset( uaddr
, 0, uaddrlen
);
1588 uin6
->sin6_family
= AF_INET6
;
1589 uin6
->sin6_port
= win6
->sin6_port
;
1590 uin6
->sin6_flowinfo
= win6
->sin6_flowinfo
;
1591 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1592 if (wsaddrlen
>= sizeof(struct WS_sockaddr_in6
)) uin6
->sin6_scope_id
= win6
->sin6_scope_id
;
1594 memcpy(&uin6
->sin6_addr
,&win6
->sin6_addr
,16); /* 16 bytes = 128 address bits */
1597 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen
);
1601 struct sockaddr_in
* uin
= (struct sockaddr_in
*)uaddr
;
1602 const struct WS_sockaddr_in
* win
= (const struct WS_sockaddr_in
*)wsaddr
;
1604 if (wsaddrlen
<sizeof(struct WS_sockaddr_in
))
1606 uaddrlen
= sizeof(struct sockaddr_in
);
1607 memset( uaddr
, 0, uaddrlen
);
1608 uin
->sin_family
= AF_INET
;
1609 uin
->sin_port
= win
->sin_port
;
1610 memcpy(&uin
->sin_addr
,&win
->sin_addr
,4); /* 4 bytes = 32 address bits */
1615 struct sockaddr_irda
*uin
= (struct sockaddr_irda
*)uaddr
;
1616 const SOCKADDR_IRDA
*win
= (const SOCKADDR_IRDA
*)wsaddr
;
1618 if (wsaddrlen
< sizeof(SOCKADDR_IRDA
))
1620 uaddrlen
= sizeof(struct sockaddr_irda
);
1621 memset( uaddr
, 0, uaddrlen
);
1622 uin
->sir_family
= AF_IRDA
;
1623 if (!strncmp( win
->irdaServiceName
, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1625 unsigned int lsap_sel
= 0;
1627 sscanf( win
->irdaServiceName
, "LSAP-SEL%u", &lsap_sel
);
1628 uin
->sir_lsap_sel
= lsap_sel
;
1632 uin
->sir_lsap_sel
= LSAP_ANY
;
1633 memcpy( uin
->sir_name
, win
->irdaServiceName
, 25 );
1635 memcpy( &uin
->sir_addr
, win
->irdaDeviceID
, sizeof(uin
->sir_addr
) );
1639 case WS_AF_UNSPEC
: {
1640 /* Try to determine the needed space by the passed windows sockaddr space */
1641 switch (wsaddrlen
) {
1642 default: /* likely an ipv4 address */
1643 case sizeof(struct WS_sockaddr_in
):
1644 uaddrlen
= sizeof(struct sockaddr_in
);
1647 case sizeof(struct WS_sockaddr_ipx
):
1648 uaddrlen
= sizeof(struct sockaddr_ipx
);
1652 case sizeof(SOCKADDR_IRDA
):
1653 uaddrlen
= sizeof(struct sockaddr_irda
);
1656 case sizeof(struct WS_sockaddr_in6
):
1657 case sizeof(struct WS_sockaddr_in6_old
):
1658 uaddrlen
= sizeof(struct sockaddr_in6
);
1661 memset( uaddr
, 0, uaddrlen
);
1665 FIXME("Unknown address family %d, return NULL.\n", wsaddr
->sa_family
);
1671 static BOOL
is_sockaddr_bound(const struct sockaddr
*uaddr
, int uaddrlen
)
1673 switch (uaddr
->sa_family
)
1678 static const struct sockaddr_ipx emptyAddr
;
1679 struct sockaddr_ipx
*ipx
= (struct sockaddr_ipx
*) uaddr
;
1680 return ipx
->sipx_port
1681 || memcmp(&ipx
->sipx_network
, &emptyAddr
.sipx_network
, sizeof(emptyAddr
.sipx_network
))
1682 || memcmp(&ipx
->sipx_node
, &emptyAddr
.sipx_node
, sizeof(emptyAddr
.sipx_node
));
1687 static const struct sockaddr_in6 emptyAddr
;
1688 const struct sockaddr_in6
*in6
= (const struct sockaddr_in6
*) uaddr
;
1689 return in6
->sin6_port
|| memcmp(&in6
->sin6_addr
, &emptyAddr
.sin6_addr
, sizeof(struct in6_addr
));
1693 static const struct sockaddr_in emptyAddr
;
1694 const struct sockaddr_in
*in
= (const struct sockaddr_in
*) uaddr
;
1695 return in
->sin_port
|| memcmp(&in
->sin_addr
, &emptyAddr
.sin_addr
, sizeof(struct in_addr
));
1700 FIXME("unknown address family %d\n", uaddr
->sa_family
);
1705 /* Returns -1 if getsockname fails, 0 if not bound, 1 otherwise */
1706 static int is_fd_bound(int fd
, union generic_unix_sockaddr
*uaddr
, socklen_t
*uaddrlen
)
1708 union generic_unix_sockaddr inaddr
;
1712 if (!uaddr
) uaddr
= &inaddr
;
1713 if (!uaddrlen
) uaddrlen
= &inlen
;
1715 *uaddrlen
= sizeof(inaddr
);
1716 res
= getsockname(fd
, &uaddr
->addr
, uaddrlen
);
1717 if (!res
) res
= is_sockaddr_bound(&uaddr
->addr
, *uaddrlen
);
1721 /* Returns 0 if successful, -1 if the buffer is too small */
1722 static int ws_sockaddr_u2ws(const struct sockaddr
* uaddr
, struct WS_sockaddr
* wsaddr
, int* wsaddrlen
)
1726 switch(uaddr
->sa_family
)
1731 const struct sockaddr_ipx
* uipx
=(const struct sockaddr_ipx
*)uaddr
;
1732 struct WS_sockaddr_ipx
* wsipx
=(struct WS_sockaddr_ipx
*)wsaddr
;
1735 switch (*wsaddrlen
) /* how much can we copy? */
1739 *wsaddrlen
= sizeof(*wsipx
);
1740 wsipx
->sa_socket
=uipx
->sipx_port
;
1744 memcpy(wsipx
->sa_nodenum
,uipx
->sipx_node
,sizeof(wsipx
->sa_nodenum
));
1752 memcpy(wsipx
->sa_netnum
,&uipx
->sipx_network
,sizeof(wsipx
->sa_netnum
));
1758 wsipx
->sa_family
=WS_AF_IPX
;
1770 const struct sockaddr_irda
*uin
= (const struct sockaddr_irda
*)uaddr
;
1771 SOCKADDR_IRDA
*win
= (SOCKADDR_IRDA
*)wsaddr
;
1773 if (*wsaddrlen
< sizeof(SOCKADDR_IRDA
))
1775 win
->irdaAddressFamily
= WS_AF_IRDA
;
1776 memcpy( win
->irdaDeviceID
, &uin
->sir_addr
, sizeof(win
->irdaDeviceID
) );
1777 if (uin
->sir_lsap_sel
!= LSAP_ANY
)
1778 sprintf( win
->irdaServiceName
, "LSAP-SEL%u", uin
->sir_lsap_sel
);
1780 memcpy( win
->irdaServiceName
, uin
->sir_name
,
1781 sizeof(win
->irdaServiceName
) );
1786 const struct sockaddr_in6
* uin6
= (const struct sockaddr_in6
*)uaddr
;
1787 struct WS_sockaddr_in6_old
* win6old
= (struct WS_sockaddr_in6_old
*)wsaddr
;
1789 if (*wsaddrlen
< sizeof(struct WS_sockaddr_in6_old
))
1791 win6old
->sin6_family
= WS_AF_INET6
;
1792 win6old
->sin6_port
= uin6
->sin6_port
;
1793 win6old
->sin6_flowinfo
= uin6
->sin6_flowinfo
;
1794 memcpy(&win6old
->sin6_addr
,&uin6
->sin6_addr
,16); /* 16 bytes = 128 address bits */
1795 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1796 if (*wsaddrlen
>= sizeof(struct WS_sockaddr_in6
)) {
1797 struct WS_sockaddr_in6
* win6
= (struct WS_sockaddr_in6
*)wsaddr
;
1798 win6
->sin6_scope_id
= uin6
->sin6_scope_id
;
1799 *wsaddrlen
= sizeof(struct WS_sockaddr_in6
);
1802 *wsaddrlen
= sizeof(struct WS_sockaddr_in6_old
);
1804 *wsaddrlen
= sizeof(struct WS_sockaddr_in6_old
);
1809 const struct sockaddr_in
* uin
= (const struct sockaddr_in
*)uaddr
;
1810 struct WS_sockaddr_in
* win
= (struct WS_sockaddr_in
*)wsaddr
;
1812 if (*wsaddrlen
< sizeof(struct WS_sockaddr_in
))
1814 win
->sin_family
= WS_AF_INET
;
1815 win
->sin_port
= uin
->sin_port
;
1816 memcpy(&win
->sin_addr
,&uin
->sin_addr
,4); /* 4 bytes = 32 address bits */
1817 memset(win
->sin_zero
, 0, 8); /* Make sure the null padding is null */
1818 *wsaddrlen
= sizeof(struct WS_sockaddr_in
);
1822 memset(wsaddr
,0,*wsaddrlen
);
1826 FIXME("Unknown address family %d\n", uaddr
->sa_family
);
1832 static INT
WS_DuplicateSocket(BOOL unicode
, SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOW lpProtocolInfo
)
1836 WSAPROTOCOL_INFOW infow
;
1838 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
1839 unicode
, s
, dwProcessId
, lpProtocolInfo
);
1841 if (!ws_protocol_info(s
, unicode
, &infow
, &size
))
1842 return SOCKET_ERROR
;
1844 if (!(hProcess
= OpenProcess(PROCESS_DUP_HANDLE
, FALSE
, dwProcessId
)))
1846 SetLastError(WSAEINVAL
);
1847 return SOCKET_ERROR
;
1850 if (!lpProtocolInfo
)
1852 CloseHandle(hProcess
);
1853 SetLastError(WSAEFAULT
);
1854 return SOCKET_ERROR
;
1857 /* I don't know what the real Windoze does next, this is a hack */
1858 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
1859 * the target use the global duplicate, or we could copy a reference to us to the structure
1860 * and let the target duplicate it from us, but let's do it as simple as possible */
1861 memcpy(lpProtocolInfo
, &infow
, size
);
1862 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s
),
1863 hProcess
, (LPHANDLE
)&lpProtocolInfo
->dwServiceFlags3
,
1864 0, FALSE
, DUPLICATE_SAME_ACCESS
);
1865 CloseHandle(hProcess
);
1866 lpProtocolInfo
->dwServiceFlags4
= 0xff00ff00; /* magic */
1870 /*****************************************************************************
1871 * WS_EnterSingleProtocolW [internal]
1873 * enters the protocol information of one given protocol into the given
1877 * TRUE if a protocol was entered into the buffer.
1880 * - only implemented for IPX, SPX, SPXII, TCP, UDP
1881 * - there is no check that the operating system supports the returned
1884 static BOOL
WS_EnterSingleProtocolW( INT protocol
, WSAPROTOCOL_INFOW
* info
)
1886 memset( info
, 0, sizeof(WSAPROTOCOL_INFOW
) );
1887 info
->iProtocol
= protocol
;
1891 case WS_IPPROTO_TCP
:
1892 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_EXPEDITED_DATA
|
1893 XP1_GRACEFUL_CLOSE
| XP1_GUARANTEED_ORDER
|
1894 XP1_GUARANTEED_DELIVERY
;
1895 info
->ProviderId
= ProviderIdIP
;
1896 info
->dwCatalogEntryId
= 0x3e9;
1897 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1898 info
->ProtocolChain
.ChainLen
= 1;
1900 info
->iAddressFamily
= WS_AF_INET
;
1901 info
->iMaxSockAddr
= 0x10;
1902 info
->iMinSockAddr
= 0x10;
1903 info
->iSocketType
= WS_SOCK_STREAM
;
1904 strcpyW( info
->szProtocol
, NameTcpW
);
1907 case WS_IPPROTO_UDP
:
1908 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_SUPPORT_BROADCAST
|
1909 XP1_SUPPORT_MULTIPOINT
| XP1_MESSAGE_ORIENTED
|
1911 info
->ProviderId
= ProviderIdIP
;
1912 info
->dwCatalogEntryId
= 0x3ea;
1913 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1914 info
->ProtocolChain
.ChainLen
= 1;
1916 info
->iAddressFamily
= WS_AF_INET
;
1917 info
->iMaxSockAddr
= 0x10;
1918 info
->iMinSockAddr
= 0x10;
1919 info
->iSocketType
= WS_SOCK_DGRAM
;
1920 info
->dwMessageSize
= 0xffbb;
1921 strcpyW( info
->szProtocol
, NameUdpW
);
1924 case WS_NSPROTO_IPX
:
1925 info
->dwServiceFlags1
= XP1_PARTIAL_MESSAGE
| XP1_SUPPORT_BROADCAST
|
1926 XP1_SUPPORT_MULTIPOINT
| XP1_MESSAGE_ORIENTED
|
1928 info
->ProviderId
= ProviderIdIPX
;
1929 info
->dwCatalogEntryId
= 0x406;
1930 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1931 info
->ProtocolChain
.ChainLen
= 1;
1933 info
->iAddressFamily
= WS_AF_IPX
;
1934 info
->iMaxSockAddr
= 0x10;
1935 info
->iMinSockAddr
= 0x0e;
1936 info
->iSocketType
= WS_SOCK_DGRAM
;
1937 info
->iProtocolMaxOffset
= 0xff;
1938 info
->dwMessageSize
= 0x240;
1939 strcpyW( info
->szProtocol
, NameIpxW
);
1942 case WS_NSPROTO_SPX
:
1943 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_PSEUDO_STREAM
|
1944 XP1_MESSAGE_ORIENTED
| XP1_GUARANTEED_ORDER
|
1945 XP1_GUARANTEED_DELIVERY
;
1946 info
->ProviderId
= ProviderIdSPX
;
1947 info
->dwCatalogEntryId
= 0x407;
1948 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1949 info
->ProtocolChain
.ChainLen
= 1;
1951 info
->iAddressFamily
= WS_AF_IPX
;
1952 info
->iMaxSockAddr
= 0x10;
1953 info
->iMinSockAddr
= 0x0e;
1954 info
->iSocketType
= WS_SOCK_SEQPACKET
;
1955 info
->dwMessageSize
= 0xffffffff;
1956 strcpyW( info
->szProtocol
, NameSpxW
);
1959 case WS_NSPROTO_SPXII
:
1960 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_GRACEFUL_CLOSE
|
1961 XP1_PSEUDO_STREAM
| XP1_MESSAGE_ORIENTED
|
1962 XP1_GUARANTEED_ORDER
| XP1_GUARANTEED_DELIVERY
;
1963 info
->ProviderId
= ProviderIdSPX
;
1964 info
->dwCatalogEntryId
= 0x409;
1965 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1966 info
->ProtocolChain
.ChainLen
= 1;
1968 info
->iAddressFamily
= WS_AF_IPX
;
1969 info
->iMaxSockAddr
= 0x10;
1970 info
->iMinSockAddr
= 0x0e;
1971 info
->iSocketType
= WS_SOCK_SEQPACKET
;
1972 info
->dwMessageSize
= 0xffffffff;
1973 strcpyW( info
->szProtocol
, NameSpxIIW
);
1977 FIXME("unknown Protocol <0x%08x>\n", protocol
);
1983 /*****************************************************************************
1984 * WS_EnterSingleProtocolA [internal]
1986 * see function WS_EnterSingleProtocolW
1989 static BOOL
WS_EnterSingleProtocolA( INT protocol
, WSAPROTOCOL_INFOA
* info
)
1991 WSAPROTOCOL_INFOW infow
;
1993 memset( info
, 0, sizeof(WSAPROTOCOL_INFOA
) );
1995 ret
= WS_EnterSingleProtocolW( protocol
, &infow
);
1998 /* convert the structure from W to A */
1999 memcpy( info
, &infow
, FIELD_OFFSET( WSAPROTOCOL_INFOA
, szProtocol
) );
2000 WideCharToMultiByte( CP_ACP
, 0, infow
.szProtocol
, -1,
2001 info
->szProtocol
, WSAPROTOCOL_LEN
+1, NULL
, NULL
);
2007 static INT
WS_EnumProtocols( BOOL unicode
, const INT
*protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
)
2009 INT i
= 0, items
= 0;
2013 LPWSAPROTOCOL_INFOA a
;
2014 LPWSAPROTOCOL_INFOW w
;
2018 if (!protocols
) protocols
= valid_protocols
;
2020 while (protocols
[i
])
2022 if(supported_protocol(protocols
[i
++]))
2026 size
= items
* (unicode
? sizeof(WSAPROTOCOL_INFOW
) : sizeof(WSAPROTOCOL_INFOA
));
2028 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
2029 unicode
, protocols
, buffer
, len
, len
? *len
: 0, items
, size
);
2031 if (*len
< size
|| !buffer
)
2034 SetLastError(WSAENOBUFS
);
2035 return SOCKET_ERROR
;
2038 for (i
= items
= 0; protocols
[i
]; i
++)
2040 if (!supported_protocol(protocols
[i
])) continue;
2043 if (WS_EnterSingleProtocolW( protocols
[i
], &info
.w
[items
] ))
2048 if (WS_EnterSingleProtocolA( protocols
[i
], &info
.a
[items
] ))
2055 static BOOL
ws_protocol_info(SOCKET s
, int unicode
, WSAPROTOCOL_INFOW
*buffer
, int *size
)
2059 *size
= unicode
? sizeof(WSAPROTOCOL_INFOW
) : sizeof(WSAPROTOCOL_INFOA
);
2060 memset(buffer
, 0, *size
);
2062 SERVER_START_REQ( get_socket_info
)
2064 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
2065 status
= wine_server_call( req
);
2068 buffer
->iAddressFamily
= convert_af_u2w(reply
->family
);
2069 buffer
->iSocketType
= convert_socktype_u2w(reply
->type
);
2070 buffer
->iProtocol
= convert_proto_u2w(reply
->protocol
);
2077 unsigned int err
= NtStatusToWSAError( status
);
2078 SetLastError( err
== WSAEBADF
? WSAENOTSOCK
: err
);
2083 WS_EnterSingleProtocolW( buffer
->iProtocol
, buffer
);
2085 WS_EnterSingleProtocolA( buffer
->iProtocol
, (WSAPROTOCOL_INFOA
*)buffer
);
2090 /**************************************************************************
2091 * Functions for handling overlapped I/O
2092 **************************************************************************/
2094 /* user APC called upon async completion */
2095 static void WINAPI
ws2_async_apc( void *arg
, IO_STATUS_BLOCK
*iosb
, ULONG reserved
)
2097 struct ws2_async
*wsa
= arg
;
2099 if (wsa
->completion_func
) wsa
->completion_func( NtStatusToWSAError(iosb
->u
.Status
),
2100 iosb
->Information
, wsa
->user_overlapped
,
2102 release_async_io( &wsa
->io
);
2105 /***********************************************************************
2106 * WS2_recv (INTERNAL)
2108 * Workhorse for both synchronous and asynchronous recv() operations.
2110 static int WS2_recv( int fd
, struct ws2_async
*wsa
, int flags
)
2112 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2116 union generic_unix_sockaddr unix_sockaddr
;
2119 hdr
.msg_name
= NULL
;
2123 hdr
.msg_namelen
= sizeof(unix_sockaddr
);
2124 hdr
.msg_name
= &unix_sockaddr
;
2127 hdr
.msg_namelen
= 0;
2129 hdr
.msg_iov
= wsa
->iovec
+ wsa
->first_iovec
;
2130 hdr
.msg_iovlen
= wsa
->n_iovecs
- wsa
->first_iovec
;
2131 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2132 hdr
.msg_accrights
= NULL
;
2133 hdr
.msg_accrightslen
= 0;
2135 hdr
.msg_control
= pktbuf
;
2136 hdr
.msg_controllen
= sizeof(pktbuf
);
2140 while ((n
= recvmsg(fd
, &hdr
, flags
)) == -1)
2146 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2149 ERR("Message control headers cannot be properly supported on this system.\n");
2150 wsa
->control
->len
= 0;
2153 if (wsa
->control
&& !convert_control_headers(&hdr
, wsa
->control
))
2155 WARN("Application passed insufficient room for control headers.\n");
2156 *wsa
->lpFlags
|= WS_MSG_CTRUNC
;
2162 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
2163 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
2165 * quoting linux 2.6 net/ipv4/tcp.c:
2166 * "According to UNIX98, msg_name/msg_namelen are ignored
2167 * on connected socket. I was just happy when found this 8) --ANK"
2169 * likewise MSDN says that lpFrom and lpFromlen are ignored for
2170 * connection-oriented sockets, so don't try to update lpFrom.
2172 if (wsa
->addr
&& hdr
.msg_namelen
)
2173 ws_sockaddr_u2ws( &unix_sockaddr
.addr
, wsa
->addr
, wsa
->addrlen
.ptr
);
2178 /***********************************************************************
2179 * WS2_async_recv (INTERNAL)
2181 * Handler for overlapped recv() operations.
2183 static NTSTATUS
WS2_async_recv( void *user
, IO_STATUS_BLOCK
*iosb
,
2184 NTSTATUS status
, void **apc
, void **arg
)
2186 struct ws2_async
*wsa
= user
;
2191 case STATUS_ALERTED
:
2192 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, FILE_READ_DATA
, &fd
, NULL
) ))
2195 result
= WS2_recv( fd
, wsa
, convert_flags(wsa
->flags
) );
2196 wine_server_release_fd( wsa
->hSocket
, fd
);
2199 status
= STATUS_SUCCESS
;
2200 _enable_event( wsa
->hSocket
, FD_READ
, 0, 0 );
2204 if (errno
== EAGAIN
)
2206 status
= STATUS_PENDING
;
2207 _enable_event( wsa
->hSocket
, FD_READ
, 0, 0 );
2212 status
= wsaErrStatus();
2217 if (status
!= STATUS_PENDING
)
2219 iosb
->u
.Status
= status
;
2220 iosb
->Information
= result
;
2221 if (wsa
->completion_func
)
2223 *apc
= ws2_async_apc
;
2227 release_async_io( &wsa
->io
);
2232 /***********************************************************************
2233 * WS2_async_accept_recv (INTERNAL)
2235 * This function is used to finish the read part of an accept request. It is
2236 * needed to place the completion on the correct socket (listener).
2238 static NTSTATUS
WS2_async_accept_recv( void *user
, IO_STATUS_BLOCK
*iosb
,
2239 NTSTATUS status
, void **apc
, void **arg
)
2242 struct ws2_accept_async
*wsa
= user
;
2244 status
= WS2_async_recv( wsa
->read
, iosb
, status
, &junk
, &junk
);
2245 if (status
== STATUS_PENDING
)
2249 WS_AddCompletion( HANDLE2SOCKET(wsa
->listen_socket
), wsa
->cvalue
, iosb
->u
.Status
, iosb
->Information
);
2251 release_async_io( &wsa
->io
);
2255 /***********************************************************************
2256 * WS2_async_accept (INTERNAL)
2258 * This is the function called to satisfy the AcceptEx callback
2260 static NTSTATUS
WS2_async_accept( void *user
, IO_STATUS_BLOCK
*iosb
,
2261 NTSTATUS status
, void **apc
, void **arg
)
2263 struct ws2_accept_async
*wsa
= user
;
2267 TRACE("status: 0x%x listen: %p, accept: %p\n", status
, wsa
->listen_socket
, wsa
->accept_socket
);
2269 if (status
== STATUS_ALERTED
)
2271 SERVER_START_REQ( accept_into_socket
)
2273 req
->lhandle
= wine_server_obj_handle( wsa
->listen_socket
);
2274 req
->ahandle
= wine_server_obj_handle( wsa
->accept_socket
);
2275 status
= wine_server_call( req
);
2279 if (status
== STATUS_CANT_WAIT
)
2280 return STATUS_PENDING
;
2282 if (status
== STATUS_INVALID_HANDLE
)
2284 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2285 status
= STATUS_CANCELLED
;
2288 else if (status
== STATUS_HANDLES_CLOSED
)
2289 status
= STATUS_CANCELLED
; /* strange windows behavior */
2291 if (status
!= STATUS_SUCCESS
)
2294 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2295 addr
= ((char *)wsa
->buf
) + wsa
->data_len
;
2296 len
= wsa
->local_len
- sizeof(int);
2297 WS_getsockname(HANDLE2SOCKET(wsa
->accept_socket
),
2298 (struct WS_sockaddr
*)(addr
+ sizeof(int)), &len
);
2301 addr
+= wsa
->local_len
;
2302 len
= wsa
->remote_len
- sizeof(int);
2303 WS_getpeername(HANDLE2SOCKET(wsa
->accept_socket
),
2304 (struct WS_sockaddr
*)(addr
+ sizeof(int)), &len
);
2310 SERVER_START_REQ( register_async
)
2312 req
->type
= ASYNC_TYPE_READ
;
2313 req
->async
.handle
= wine_server_obj_handle( wsa
->accept_socket
);
2314 req
->async
.event
= wine_server_obj_handle( wsa
->user_overlapped
->hEvent
);
2315 req
->async
.callback
= wine_server_client_ptr( WS2_async_accept_recv
);
2316 req
->async
.iosb
= wine_server_client_ptr( iosb
);
2317 req
->async
.arg
= wine_server_client_ptr( wsa
);
2318 status
= wine_server_call( req
);
2322 if (status
!= STATUS_PENDING
)
2325 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2326 * needs to be performed by WS2_async_accept_recv() first. */
2327 return STATUS_MORE_PROCESSING_REQUIRED
;
2330 iosb
->u
.Status
= status
;
2331 iosb
->Information
= 0;
2333 if (wsa
->read
) release_async_io( &wsa
->read
->io
);
2334 release_async_io( &wsa
->io
);
2338 /***********************************************************************
2339 * WS2_send (INTERNAL)
2341 * Workhorse for both synchronous and asynchronous send() operations.
2343 static int WS2_send( int fd
, struct ws2_async
*wsa
, int flags
)
2346 union generic_unix_sockaddr unix_addr
;
2349 hdr
.msg_name
= NULL
;
2350 hdr
.msg_namelen
= 0;
2354 hdr
.msg_name
= &unix_addr
;
2355 hdr
.msg_namelen
= ws_sockaddr_ws2u( wsa
->addr
, wsa
->addrlen
.val
, &unix_addr
);
2356 if ( !hdr
.msg_namelen
)
2362 #if defined(HAS_IPX) && defined(SOL_IPX)
2363 if(wsa
->addr
->sa_family
== WS_AF_IPX
)
2365 struct sockaddr_ipx
* uipx
= (struct sockaddr_ipx
*)hdr
.msg_name
;
2367 socklen_t len
= sizeof(int);
2369 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2370 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2371 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2372 * ipx type in the sockaddr_opx structure with the stored value.
2374 if(getsockopt(fd
, SOL_IPX
, IPX_TYPE
, &val
, &len
) != -1)
2375 uipx
->sipx_type
= val
;
2380 hdr
.msg_iov
= wsa
->iovec
+ wsa
->first_iovec
;
2381 hdr
.msg_iovlen
= wsa
->n_iovecs
- wsa
->first_iovec
;
2382 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2383 hdr
.msg_accrights
= NULL
;
2384 hdr
.msg_accrightslen
= 0;
2386 hdr
.msg_control
= NULL
;
2387 hdr
.msg_controllen
= 0;
2391 while ((ret
= sendmsg(fd
, &hdr
, flags
)) == -1)
2398 while (wsa
->first_iovec
< wsa
->n_iovecs
&& wsa
->iovec
[wsa
->first_iovec
].iov_len
<= n
)
2399 n
-= wsa
->iovec
[wsa
->first_iovec
++].iov_len
;
2400 if (wsa
->first_iovec
< wsa
->n_iovecs
)
2402 wsa
->iovec
[wsa
->first_iovec
].iov_base
= (char*)wsa
->iovec
[wsa
->first_iovec
].iov_base
+ n
;
2403 wsa
->iovec
[wsa
->first_iovec
].iov_len
-= n
;
2408 /***********************************************************************
2409 * WS2_async_send (INTERNAL)
2411 * Handler for overlapped send() operations.
2413 static NTSTATUS
WS2_async_send( void *user
, IO_STATUS_BLOCK
*iosb
,
2414 NTSTATUS status
, void **apc
, void **arg
)
2416 struct ws2_async
*wsa
= user
;
2421 case STATUS_ALERTED
:
2422 if ( wsa
->n_iovecs
<= wsa
->first_iovec
)
2425 status
= STATUS_SUCCESS
;
2428 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, FILE_WRITE_DATA
, &fd
, NULL
) ))
2431 /* check to see if the data is ready (non-blocking) */
2432 result
= WS2_send( fd
, wsa
, convert_flags(wsa
->flags
) );
2433 wine_server_release_fd( wsa
->hSocket
, fd
);
2437 if (wsa
->first_iovec
< wsa
->n_iovecs
)
2438 status
= STATUS_PENDING
;
2440 status
= STATUS_SUCCESS
;
2442 iosb
->Information
+= result
;
2444 else if (errno
== EAGAIN
)
2446 status
= STATUS_PENDING
;
2450 status
= wsaErrStatus();
2454 if (status
!= STATUS_PENDING
)
2456 iosb
->u
.Status
= status
;
2457 if (wsa
->completion_func
)
2459 *apc
= ws2_async_apc
;
2463 release_async_io( &wsa
->io
);
2468 /***********************************************************************
2469 * WS2_async_shutdown (INTERNAL)
2471 * Handler for shutdown() operations on overlapped sockets.
2473 static NTSTATUS
WS2_async_shutdown( void *user
, IO_STATUS_BLOCK
*iosb
,
2474 NTSTATUS status
, void **apc
, void **arg
)
2476 struct ws2_async_shutdown
*wsa
= user
;
2481 case STATUS_ALERTED
:
2482 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, 0, &fd
, NULL
) ))
2485 switch ( wsa
->type
)
2487 case ASYNC_TYPE_READ
: err
= shutdown( fd
, 0 ); break;
2488 case ASYNC_TYPE_WRITE
: err
= shutdown( fd
, 1 ); break;
2490 status
= err
? wsaErrStatus() : STATUS_SUCCESS
;
2491 wine_server_release_fd( wsa
->hSocket
, fd
);
2494 iosb
->u
.Status
= status
;
2495 iosb
->Information
= 0;
2496 release_async_io( &wsa
->io
);
2500 /***********************************************************************
2501 * WS2_register_async_shutdown (INTERNAL)
2503 * Helper function for WS_shutdown() on overlapped sockets.
2505 static int WS2_register_async_shutdown( SOCKET s
, int type
)
2507 struct ws2_async_shutdown
*wsa
;
2510 TRACE("socket %04lx type %d\n", s
, type
);
2512 wsa
= (struct ws2_async_shutdown
*)alloc_async_io( sizeof(*wsa
) );
2516 wsa
->hSocket
= SOCKET2HANDLE(s
);
2519 SERVER_START_REQ( register_async
)
2522 req
->async
.handle
= wine_server_obj_handle( wsa
->hSocket
);
2523 req
->async
.callback
= wine_server_client_ptr( WS2_async_shutdown
);
2524 req
->async
.iosb
= wine_server_client_ptr( &wsa
->iosb
);
2525 req
->async
.arg
= wine_server_client_ptr( wsa
);
2526 req
->async
.cvalue
= 0;
2527 status
= wine_server_call( req
);
2531 if (status
!= STATUS_PENDING
)
2533 HeapFree( GetProcessHeap(), 0, wsa
);
2534 return NtStatusToWSAError( status
);
2539 /***********************************************************************
2542 SOCKET WINAPI
WS_accept(SOCKET s
, struct WS_sockaddr
*addr
, int *addrlen32
)
2548 TRACE("socket %04lx\n", s
);
2549 status
= _is_blocking(s
, &is_blocking
);
2553 return INVALID_SOCKET
;
2557 /* try accepting first (if there is a deferred connection) */
2558 SERVER_START_REQ( accept_socket
)
2560 req
->lhandle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
2561 req
->access
= GENERIC_READ
|GENERIC_WRITE
|SYNCHRONIZE
;
2562 req
->attributes
= OBJ_INHERIT
;
2563 status
= wine_server_call( req
);
2564 as
= HANDLE2SOCKET( wine_server_ptr_handle( reply
->handle
));
2569 if (addr
&& WS_getpeername(as
, addr
, addrlen32
))
2572 return SOCKET_ERROR
;
2576 if (is_blocking
&& status
== STATUS_CANT_WAIT
)
2578 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
2580 do_block(fd
, POLLIN
, -1);
2581 _sync_sock_state(s
); /* let wineserver notice connection */
2582 release_sock_fd( s
, fd
);
2584 } while (is_blocking
&& status
== STATUS_CANT_WAIT
);
2587 return INVALID_SOCKET
;
2590 /***********************************************************************
2593 static BOOL WINAPI
WS2_AcceptEx(SOCKET listener
, SOCKET acceptor
, PVOID dest
, DWORD dest_len
,
2594 DWORD local_addr_len
, DWORD rem_addr_len
, LPDWORD received
,
2595 LPOVERLAPPED overlapped
)
2598 struct ws2_accept_async
*wsa
;
2601 TRACE("(%04lx, %04lx, %p, %d, %d, %d, %p, %p)\n", listener
, acceptor
, dest
, dest_len
, local_addr_len
,
2602 rem_addr_len
, received
, overlapped
);
2606 SetLastError(WSAEINVAL
);
2612 SetLastError(WSA_INVALID_PARAMETER
);
2618 SetLastError(WSAEFAULT
);
2622 fd
= get_sock_fd( listener
, FILE_READ_DATA
, NULL
);
2625 SetLastError(WSAENOTSOCK
);
2628 release_sock_fd( listener
, fd
);
2630 fd
= get_sock_fd( acceptor
, FILE_READ_DATA
, NULL
);
2633 SetLastError(WSAENOTSOCK
);
2636 release_sock_fd( acceptor
, fd
);
2638 wsa
= (struct ws2_accept_async
*)alloc_async_io( sizeof(*wsa
) );
2641 SetLastError(WSAEFAULT
);
2645 wsa
->listen_socket
= SOCKET2HANDLE(listener
);
2646 wsa
->accept_socket
= SOCKET2HANDLE(acceptor
);
2647 wsa
->user_overlapped
= overlapped
;
2648 wsa
->cvalue
= !((ULONG_PTR
)overlapped
->hEvent
& 1) ? (ULONG_PTR
)overlapped
: 0;
2650 wsa
->data_len
= dest_len
;
2651 wsa
->local_len
= local_addr_len
;
2652 wsa
->remote_len
= rem_addr_len
;
2657 /* set up a read request if we need it */
2658 wsa
->read
= (struct ws2_async
*)alloc_async_io( offsetof(struct ws2_async
, iovec
[1]) );
2661 HeapFree( GetProcessHeap(), 0, wsa
);
2662 SetLastError(WSAEFAULT
);
2666 wsa
->read
->hSocket
= wsa
->accept_socket
;
2667 wsa
->read
->flags
= 0;
2668 wsa
->read
->lpFlags
= &wsa
->read
->flags
;
2669 wsa
->read
->addr
= NULL
;
2670 wsa
->read
->addrlen
.ptr
= NULL
;
2671 wsa
->read
->control
= NULL
;
2672 wsa
->read
->n_iovecs
= 1;
2673 wsa
->read
->first_iovec
= 0;
2674 wsa
->read
->completion_func
= NULL
;
2675 wsa
->read
->iovec
[0].iov_base
= wsa
->buf
;
2676 wsa
->read
->iovec
[0].iov_len
= wsa
->data_len
;
2679 SERVER_START_REQ( register_async
)
2681 req
->type
= ASYNC_TYPE_READ
;
2682 req
->async
.handle
= wine_server_obj_handle( SOCKET2HANDLE(listener
) );
2683 req
->async
.event
= wine_server_obj_handle( overlapped
->hEvent
);
2684 req
->async
.callback
= wine_server_client_ptr( WS2_async_accept
);
2685 req
->async
.iosb
= wine_server_client_ptr( overlapped
);
2686 req
->async
.arg
= wine_server_client_ptr( wsa
);
2687 req
->async
.cvalue
= wsa
->cvalue
;
2688 status
= wine_server_call( req
);
2692 if(status
!= STATUS_PENDING
)
2694 HeapFree( GetProcessHeap(), 0, wsa
->read
);
2695 HeapFree( GetProcessHeap(), 0, wsa
);
2698 SetLastError( NtStatusToWSAError(status
) );
2702 /***********************************************************************
2703 * GetAcceptExSockaddrs
2705 static void WINAPI
WS2_GetAcceptExSockaddrs(PVOID buffer
, DWORD data_size
, DWORD local_size
, DWORD remote_size
,
2706 struct WS_sockaddr
**local_addr
, LPINT local_addr_len
,
2707 struct WS_sockaddr
**remote_addr
, LPINT remote_addr_len
)
2709 char *cbuf
= buffer
;
2710 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer
, data_size
, local_size
, remote_size
, local_addr
,
2711 local_addr_len
, remote_addr
, remote_addr_len
);
2714 *local_addr_len
= *(int *) cbuf
;
2715 *local_addr
= (struct WS_sockaddr
*)(cbuf
+ sizeof(int));
2719 *remote_addr_len
= *(int *) cbuf
;
2720 *remote_addr
= (struct WS_sockaddr
*)(cbuf
+ sizeof(int));
2723 /***********************************************************************
2726 int WINAPI
WSASendMsg( SOCKET s
, LPWSAMSG msg
, DWORD dwFlags
, LPDWORD lpNumberOfBytesSent
,
2727 LPWSAOVERLAPPED lpOverlapped
,
2728 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
2732 SetLastError( WSAEFAULT
);
2733 return SOCKET_ERROR
;
2736 return WS2_sendto( s
, msg
->lpBuffers
, msg
->dwBufferCount
, lpNumberOfBytesSent
,
2737 dwFlags
, msg
->name
, msg
->namelen
,
2738 lpOverlapped
, lpCompletionRoutine
);
2741 /***********************************************************************
2744 * Perform a receive operation that is capable of returning message
2745 * control headers. It is important to note that the WSAMSG parameter
2746 * must remain valid throughout the operation, even when an overlapped
2747 * receive is performed.
2749 static int WINAPI
WS2_WSARecvMsg( SOCKET s
, LPWSAMSG msg
, LPDWORD lpNumberOfBytesRecvd
,
2750 LPWSAOVERLAPPED lpOverlapped
,
2751 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
2755 SetLastError( WSAEFAULT
);
2756 return SOCKET_ERROR
;
2759 return WS2_recv_base( s
, msg
->lpBuffers
, msg
->dwBufferCount
, lpNumberOfBytesRecvd
,
2760 &msg
->dwFlags
, msg
->name
, &msg
->namelen
,
2761 lpOverlapped
, lpCompletionRoutine
, &msg
->Control
);
2764 /***********************************************************************
2765 * interface_bind (INTERNAL)
2767 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
2768 * operating only on the specified interface. This restriction consists of two components:
2769 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
2770 * 2) An incoming packet restriction dropping packets not meant for the interface.
2771 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
2772 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
2773 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
2774 * to receive broadcast packets on a socket that is bound to a specific network interface.
2776 static BOOL
interface_bind( SOCKET s
, int fd
, struct sockaddr
*addr
)
2778 struct sockaddr_in
*in_sock
= (struct sockaddr_in
*) addr
;
2779 unsigned int sock_type
= 0;
2780 socklen_t optlen
= sizeof(sock_type
);
2781 in_addr_t bind_addr
= in_sock
->sin_addr
.s_addr
;
2782 PIP_ADAPTER_INFO adapters
= NULL
, adapter
;
2787 if (bind_addr
== htonl(INADDR_ANY
) || bind_addr
== htonl(INADDR_LOOPBACK
))
2788 return FALSE
; /* Not binding to a network adapter, special interface binding unnecessary. */
2789 if (getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, &sock_type
, &optlen
) == -1 || sock_type
!= SOCK_DGRAM
)
2790 return FALSE
; /* Special interface binding is only necessary for UDP datagrams. */
2791 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
2793 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
2794 if (adapters
== NULL
|| GetAdaptersInfo(adapters
, &adap_size
) != NO_ERROR
)
2796 /* Search the IPv4 adapter list for the appropriate binding interface */
2797 for (adapter
= adapters
; adapter
!= NULL
; adapter
= adapter
->Next
)
2799 in_addr_t adapter_addr
= (in_addr_t
) inet_addr(adapter
->IpAddressList
.IpAddress
.String
);
2801 if (bind_addr
== adapter_addr
)
2803 #if defined(IP_BOUND_IF)
2804 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
2805 if (setsockopt(fd
, IPPROTO_IP
, IP_BOUND_IF
, &adapter
->Index
, sizeof(adapter
->Index
)) != 0)
2808 #elif defined(LINUX_BOUND_IF)
2809 in_addr_t ifindex
= (in_addr_t
) htonl(adapter
->Index
);
2810 struct interface_filter specific_interface_filter
;
2811 struct sock_fprog filter_prog
;
2813 if (setsockopt(fd
, IPPROTO_IP
, IP_UNICAST_IF
, &ifindex
, sizeof(ifindex
)) != 0)
2814 goto cleanup
; /* Failed to suggest egress interface */
2815 specific_interface_filter
= generic_interface_filter
;
2816 specific_interface_filter
.iface_rule
.k
= adapter
->Index
;
2817 specific_interface_filter
.ip_rule
.k
= htonl(adapter_addr
);
2818 filter_prog
.len
= sizeof(generic_interface_filter
)/sizeof(struct sock_filter
);
2819 filter_prog
.filter
= (struct sock_filter
*) &specific_interface_filter
;
2820 if (setsockopt(fd
, SOL_SOCKET
, SO_ATTACH_FILTER
, &filter_prog
, sizeof(filter_prog
)) != 0)
2821 goto cleanup
; /* Failed to specify incoming packet filter */
2824 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
2825 "receiving broadcast packets will not work on socket %04lx.\n", s
);
2830 /* Will soon be switching to INADDR_ANY: permit address reuse */
2831 if (ret
&& setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &enable
, sizeof(enable
)) == 0)
2832 TRACE("Socket %04lx bound to interface index %d\n", s
, adapter
->Index
);
2838 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s
);
2839 HeapFree(GetProcessHeap(), 0, adapters
);
2843 /***********************************************************************
2846 int WINAPI
WS_bind(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
)
2848 int fd
= get_sock_fd( s
, 0, NULL
);
2849 int res
= SOCKET_ERROR
;
2851 TRACE("socket %04lx, ptr %p %s, length %d\n", s
, name
, debugstr_sockaddr(name
), namelen
);
2855 if (!name
|| (name
->sa_family
&& !supported_pf(name
->sa_family
)))
2857 SetLastError(WSAEAFNOSUPPORT
);
2861 union generic_unix_sockaddr uaddr
;
2862 unsigned int uaddrlen
= ws_sockaddr_ws2u(name
, namelen
, &uaddr
);
2865 SetLastError(WSAEFAULT
);
2870 const struct sockaddr_in6
*in6
= (const struct sockaddr_in6
*) &uaddr
;
2871 if (name
->sa_family
== WS_AF_INET6
&&
2872 !memcmp(&in6
->sin6_addr
, &in6addr_any
, sizeof(struct in6_addr
)))
2875 if (setsockopt(fd
, IPPROTO_IPV6
, IPV6_V6ONLY
, &enable
, sizeof(enable
)) == -1)
2877 release_sock_fd( s
, fd
);
2878 SetLastError(WSAEAFNOSUPPORT
);
2879 return SOCKET_ERROR
;
2883 if (name
->sa_family
== WS_AF_INET
)
2885 struct sockaddr_in
*in4
= (struct sockaddr_in
*) &uaddr
;
2886 if (memcmp(&in4
->sin_addr
, magic_loopback_addr
, 4) == 0)
2888 /* Trying to bind to the default host interface, using
2889 * INADDR_ANY instead*/
2890 WARN("Trying to bind to magic IP address, using "
2891 "INADDR_ANY instead.\n");
2892 in4
->sin_addr
.s_addr
= htonl(INADDR_ANY
);
2894 else if (interface_bind(s
, fd
, &uaddr
.addr
))
2895 in4
->sin_addr
.s_addr
= htonl(INADDR_ANY
);
2897 if (bind(fd
, &uaddr
.addr
, uaddrlen
) < 0)
2899 int loc_errno
= errno
;
2900 WARN("\tfailure - errno = %i\n", errno
);
2905 SetLastError(WSAEINVAL
);
2910 socklen_t optlen
= sizeof(optval
);
2911 /* Windows >= 2003 will return different results depending on
2912 * SO_REUSEADDR, WSAEACCES may be returned representing that
2913 * the socket hijacking protection prevented the bind */
2914 if (!getsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&optval
, &optlen
) && optval
)
2916 SetLastError(WSAEACCES
);
2922 SetLastError(wsaErrno());
2928 res
=0; /* success */
2932 release_sock_fd( s
, fd
);
2937 /***********************************************************************
2938 * closesocket (WS2_32.3)
2940 int WINAPI
WS_closesocket(SOCKET s
)
2942 int res
= SOCKET_ERROR
, fd
;
2945 fd
= get_sock_fd(s
, FILE_READ_DATA
, NULL
);
2948 release_sock_fd(s
, fd
);
2949 if (CloseHandle(SOCKET2HANDLE(s
)))
2953 SetLastError(WSAENOTSOCK
);
2956 SetLastError(WSANOTINITIALISED
);
2957 TRACE("(socket %04lx) -> %d\n", s
, res
);
2961 static int do_connect(int fd
, const struct WS_sockaddr
* name
, int namelen
)
2963 union generic_unix_sockaddr uaddr
;
2964 unsigned int uaddrlen
= ws_sockaddr_ws2u(name
, namelen
, &uaddr
);
2969 if (name
->sa_family
== WS_AF_INET
)
2971 struct sockaddr_in
*in4
= (struct sockaddr_in
*) &uaddr
;
2972 if (memcmp(&in4
->sin_addr
, magic_loopback_addr
, 4) == 0)
2974 /* Trying to connect to magic replace-loopback address,
2975 * assuming we really want to connect to localhost */
2976 TRACE("Trying to connect to magic IP address, using "
2977 "INADDR_LOOPBACK instead.\n");
2978 in4
->sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
2982 if (connect(fd
, &uaddr
.addr
, uaddrlen
) == 0)
2988 /***********************************************************************
2989 * connect (WS2_32.4)
2991 int WINAPI
WS_connect(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
)
2993 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
2995 TRACE("socket %04lx, ptr %p %s, length %d\n", s
, name
, debugstr_sockaddr(name
), namelen
);
3001 int ret
= do_connect(fd
, name
, namelen
);
3003 goto connect_success
;
3005 if (ret
== WSAEINPROGRESS
)
3007 /* tell wineserver that a connection is in progress */
3008 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3010 FD_WINE_CONNECTED
|FD_WINE_LISTENING
);
3011 status
= _is_blocking( s
, &is_blocking
);
3014 release_sock_fd( s
, fd
);
3015 set_error( status
);
3016 return SOCKET_ERROR
;
3022 do_block(fd
, POLLIN
| POLLOUT
, -1);
3023 _sync_sock_state(s
); /* let wineserver notice connection */
3024 /* retrieve any error codes from it */
3025 result
= _get_sock_error(s
, FD_CONNECT_BIT
);
3027 SetLastError(NtStatusToWSAError(result
));
3030 goto connect_success
;
3035 SetLastError(WSAEWOULDBLOCK
);
3042 release_sock_fd( s
, fd
);
3044 return SOCKET_ERROR
;
3047 release_sock_fd( s
, fd
);
3048 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3049 FD_WINE_CONNECTED
|FD_READ
|FD_WRITE
,
3050 FD_CONNECT
|FD_WINE_LISTENING
);
3054 /***********************************************************************
3055 * WSAConnect (WS2_32.30)
3057 int WINAPI
WSAConnect( SOCKET s
, const struct WS_sockaddr
* name
, int namelen
,
3058 LPWSABUF lpCallerData
, LPWSABUF lpCalleeData
,
3059 LPQOS lpSQOS
, LPQOS lpGQOS
)
3061 if ( lpCallerData
|| lpCalleeData
|| lpSQOS
|| lpGQOS
)
3062 FIXME("unsupported parameters!\n");
3063 return WS_connect( s
, name
, namelen
);
3066 /***********************************************************************
3069 static BOOL WINAPI
WS2_ConnectEx(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
,
3070 PVOID sendBuf
, DWORD sendBufLen
, LPDWORD sent
, LPOVERLAPPED ov
)
3072 int fd
, ret
, status
;
3076 SetLastError( ERROR_INVALID_PARAMETER
);
3080 fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
3083 SetLastError( WSAENOTSOCK
);
3087 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
3088 s
, name
, debugstr_sockaddr(name
), namelen
, sendBuf
, sendBufLen
, ov
);
3090 ret
= is_fd_bound(fd
, NULL
, NULL
);
3093 SetLastError(ret
== -1 ? wsaErrno() : WSAEINVAL
);
3097 ret
= do_connect(fd
, name
, namelen
);
3102 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3103 FD_WINE_CONNECTED
|FD_READ
|FD_WRITE
,
3104 FD_CONNECT
|FD_WINE_LISTENING
);
3106 wsabuf
.len
= sendBufLen
;
3107 wsabuf
.buf
= (char*) sendBuf
;
3109 /* WSASend takes care of completion if need be */
3110 if (WSASend(s
, &wsabuf
, sendBuf
? 1 : 0, sent
, 0, ov
, NULL
) != SOCKET_ERROR
)
3111 goto connection_success
;
3113 else if (ret
== WSAEINPROGRESS
)
3115 struct ws2_async
*wsa
;
3116 ULONG_PTR cvalue
= (((ULONG_PTR
)ov
->hEvent
& 1) == 0) ? (ULONG_PTR
)ov
: 0;
3118 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3120 FD_WINE_CONNECTED
|FD_WINE_LISTENING
);
3122 /* Indirectly call WSASend */
3123 if (!(wsa
= (struct ws2_async
*)alloc_async_io( offsetof( struct ws2_async
, iovec
[1] ))))
3125 SetLastError(WSAEFAULT
);
3129 IO_STATUS_BLOCK
*iosb
= (IO_STATUS_BLOCK
*)ov
;
3130 iosb
->u
.Status
= STATUS_PENDING
;
3131 iosb
->Information
= 0;
3133 wsa
->hSocket
= SOCKET2HANDLE(s
);
3135 wsa
->addrlen
.val
= 0;
3137 wsa
->lpFlags
= &wsa
->flags
;
3138 wsa
->control
= NULL
;
3139 wsa
->n_iovecs
= sendBuf
? 1 : 0;
3140 wsa
->first_iovec
= 0;
3141 wsa
->completion_func
= NULL
;
3142 wsa
->iovec
[0].iov_base
= sendBuf
;
3143 wsa
->iovec
[0].iov_len
= sendBufLen
;
3145 SERVER_START_REQ( register_async
)
3147 req
->type
= ASYNC_TYPE_WRITE
;
3148 req
->async
.handle
= wine_server_obj_handle( wsa
->hSocket
);
3149 req
->async
.callback
= wine_server_client_ptr( WS2_async_send
);
3150 req
->async
.iosb
= wine_server_client_ptr( iosb
);
3151 req
->async
.arg
= wine_server_client_ptr( wsa
);
3152 req
->async
.event
= wine_server_obj_handle( ov
->hEvent
);
3153 req
->async
.cvalue
= cvalue
;
3154 status
= wine_server_call( req
);
3158 if (status
!= STATUS_PENDING
) HeapFree(GetProcessHeap(), 0, wsa
);
3160 /* If the connect already failed */
3161 if (status
== STATUS_PIPE_DISCONNECTED
)
3162 status
= _get_sock_error(s
, FD_CONNECT_BIT
);
3163 SetLastError( NtStatusToWSAError(status
) );
3171 release_sock_fd( s
, fd
);
3175 release_sock_fd( s
, fd
);
3180 /***********************************************************************
3181 * getpeername (WS2_32.5)
3183 int WINAPI
WS_getpeername(SOCKET s
, struct WS_sockaddr
*name
, int *namelen
)
3188 TRACE("socket %04lx, ptr %p, len %08x\n", s
, name
, namelen
? *namelen
: 0);
3190 fd
= get_sock_fd( s
, 0, NULL
);
3195 union generic_unix_sockaddr uaddr
;
3196 socklen_t uaddrlen
= sizeof(uaddr
);
3198 if (getpeername(fd
, &uaddr
.addr
, &uaddrlen
) == 0)
3200 if (!name
|| !namelen
)
3201 SetLastError(WSAEFAULT
);
3202 else if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
3203 /* The buffer was too small */
3204 SetLastError(WSAEFAULT
);
3208 TRACE("=> %s\n", debugstr_sockaddr(name
));
3212 SetLastError(wsaErrno());
3213 release_sock_fd( s
, fd
);
3218 /* When binding to an UDP address with filter support the getsockname call on the socket
3219 * will always return 0.0.0.0 instead of the filtered interface address. This function
3220 * checks if the socket is interface-bound on UDP and return the correct address.
3221 * This is required because applications often do a bind() with port zero followed by a
3222 * getsockname() to retrieve the port and address acquired.
3224 static void interface_bind_check(int fd
, struct sockaddr_in
*addr
)
3226 #if !defined(IP_BOUND_IF) && !defined(LINUX_BOUND_IF)
3230 socklen_t len
= sizeof(ifindex
);
3232 /* Check for IPv4, address 0.0.0.0 and UDP socket */
3233 if (addr
->sin_family
!= AF_INET
|| addr
->sin_addr
.s_addr
!= 0)
3235 if (getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, &ifindex
, &len
) || ifindex
!= SOCK_DGRAM
)
3239 len
= sizeof(ifindex
);
3240 #if defined(IP_BOUND_IF)
3241 getsockopt(fd
, IPPROTO_IP
, IP_BOUND_IF
, &ifindex
, &len
);
3242 #elif defined(LINUX_BOUND_IF)
3243 getsockopt(fd
, IPPROTO_IP
, IP_UNICAST_IF
, &ifindex
, &len
);
3244 if (ifindex
> 0) ifindex
= ntohl(ifindex
);
3248 PIP_ADAPTER_INFO adapters
, adapter
;
3251 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
3253 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
3254 if (adapters
&& GetAdaptersInfo(adapters
, &adap_size
) == NO_ERROR
)
3256 /* Search the IPv4 adapter list for the appropriate bound interface */
3257 for (adapter
= adapters
; adapter
!= NULL
; adapter
= adapter
->Next
)
3259 in_addr_t adapter_addr
;
3260 if (adapter
->Index
!= ifindex
) continue;
3262 adapter_addr
= inet_addr(adapter
->IpAddressList
.IpAddress
.String
);
3263 addr
->sin_addr
.s_addr
= adapter_addr
;
3264 TRACE("reporting interface address from adapter %d\n", ifindex
);
3268 HeapFree(GetProcessHeap(), 0, adapters
);
3273 /***********************************************************************
3274 * getsockname (WS2_32.6)
3276 int WINAPI
WS_getsockname(SOCKET s
, struct WS_sockaddr
*name
, int *namelen
)
3281 TRACE("socket %04lx, ptr %p, len %08x\n", s
, name
, namelen
? *namelen
: 0);
3283 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3284 if( (name
== NULL
) || (namelen
== NULL
) )
3286 SetLastError( WSAEFAULT
);
3287 return SOCKET_ERROR
;
3290 fd
= get_sock_fd( s
, 0, NULL
);
3295 union generic_unix_sockaddr uaddr
;
3297 int bound
= is_fd_bound(fd
, &uaddr
, &uaddrlen
);
3301 SetLastError(bound
== -1 ? wsaErrno() : WSAEINVAL
);
3303 else if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
3305 /* The buffer was too small */
3306 SetLastError(WSAEFAULT
);
3310 interface_bind_check(fd
, (struct sockaddr_in
*) &uaddr
);
3311 if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
3313 /* The buffer was too small */
3314 SetLastError(WSAEFAULT
);
3319 TRACE("=> %s\n", debugstr_sockaddr(name
));
3322 release_sock_fd( s
, fd
);
3327 /***********************************************************************
3328 * getsockopt (WS2_32.7)
3330 INT WINAPI
WS_getsockopt(SOCKET s
, INT level
,
3331 INT optname
, char *optval
, INT
*optlen
)
3336 TRACE("(socket %04lx, %s, optval %s, optlen %p (%d))\n", s
,
3337 debugstr_sockopt(level
, optname
), debugstr_optval(optval
, 0),
3338 optlen
, optlen
? *optlen
: 0);
3346 /* Handle common cases. The special cases are below, sorted
3348 case WS_SO_BROADCAST
:
3350 case WS_SO_KEEPALIVE
:
3351 case WS_SO_OOBINLINE
:
3353 case WS_SO_REUSEADDR
:
3355 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3356 return SOCKET_ERROR
;
3357 convert_sockopt(&level
, &optname
);
3358 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3360 SetLastError(wsaErrno());
3363 release_sock_fd( s
, fd
);
3365 case WS_SO_ACCEPTCONN
:
3366 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3367 return SOCKET_ERROR
;
3368 if (getsockopt(fd
, SOL_SOCKET
, SO_ACCEPTCONN
, optval
, (socklen_t
*)optlen
) != 0 )
3370 SetLastError(wsaErrno());
3375 /* BSD returns != 0 while Windows return exact == 1 */
3376 if (*(int *)optval
) *(int *)optval
= 1;
3378 release_sock_fd( s
, fd
);
3380 case WS_SO_BSP_STATE
:
3382 int req_size
, addr_size
;
3383 WSAPROTOCOL_INFOW infow
;
3384 CSADDR_INFO
*csinfo
;
3386 ret
= ws_protocol_info(s
, TRUE
, &infow
, &addr_size
);
3389 if (infow
.iAddressFamily
== WS_AF_INET
)
3390 addr_size
= sizeof(struct sockaddr_in
);
3391 else if (infow
.iAddressFamily
== WS_AF_INET6
)
3392 addr_size
= sizeof(struct sockaddr_in6
);
3395 FIXME("Family %d is unsupported for SO_BSP_STATE\n", infow
.iAddressFamily
);
3396 SetLastError(WSAEAFNOSUPPORT
);
3397 return SOCKET_ERROR
;
3400 req_size
= sizeof(CSADDR_INFO
) + addr_size
* 2;
3401 if (*optlen
< req_size
)
3404 SetLastError(WSAEFAULT
);
3408 union generic_unix_sockaddr uaddr
;
3411 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3412 return SOCKET_ERROR
;
3414 csinfo
= (CSADDR_INFO
*) optval
;
3416 /* Check if the sock is bound */
3417 if (is_fd_bound(fd
, &uaddr
, &uaddrlen
) == 1)
3419 csinfo
->LocalAddr
.lpSockaddr
=
3420 (LPSOCKADDR
) (optval
+ sizeof(CSADDR_INFO
));
3421 ws_sockaddr_u2ws(&uaddr
.addr
, csinfo
->LocalAddr
.lpSockaddr
, &addr_size
);
3422 csinfo
->LocalAddr
.iSockaddrLength
= addr_size
;
3426 csinfo
->LocalAddr
.lpSockaddr
= NULL
;
3427 csinfo
->LocalAddr
.iSockaddrLength
= 0;
3430 /* Check if the sock is connected */
3431 if (!getpeername(fd
, &uaddr
.addr
, &uaddrlen
) &&
3432 is_sockaddr_bound(&uaddr
.addr
, uaddrlen
))
3434 csinfo
->RemoteAddr
.lpSockaddr
=
3435 (LPSOCKADDR
) (optval
+ sizeof(CSADDR_INFO
) + addr_size
);
3436 ws_sockaddr_u2ws(&uaddr
.addr
, csinfo
->RemoteAddr
.lpSockaddr
, &addr_size
);
3437 csinfo
->RemoteAddr
.iSockaddrLength
= addr_size
;
3441 csinfo
->RemoteAddr
.lpSockaddr
= NULL
;
3442 csinfo
->RemoteAddr
.iSockaddrLength
= 0;
3445 csinfo
->iSocketType
= infow
.iSocketType
;
3446 csinfo
->iProtocol
= infow
.iProtocol
;
3447 release_sock_fd( s
, fd
);
3450 return ret
? 0 : SOCKET_ERROR
;
3452 case WS_SO_DONTLINGER
:
3454 struct linger lingval
;
3455 socklen_t len
= sizeof(struct linger
);
3457 if (!optlen
|| *optlen
< sizeof(BOOL
)|| !optval
)
3459 SetLastError(WSAEFAULT
);
3460 return SOCKET_ERROR
;
3462 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3463 return SOCKET_ERROR
;
3465 if (getsockopt(fd
, SOL_SOCKET
, SO_LINGER
, &lingval
, &len
) != 0 )
3467 SetLastError(wsaErrno());
3472 *(BOOL
*)optval
= !lingval
.l_onoff
;
3473 *optlen
= sizeof(BOOL
);
3476 release_sock_fd( s
, fd
);
3480 case WS_SO_CONNECT_TIME
:
3482 static int pretendtime
= 0;
3483 struct WS_sockaddr addr
;
3484 int len
= sizeof(addr
);
3486 if (!optlen
|| *optlen
< sizeof(DWORD
) || !optval
)
3488 SetLastError(WSAEFAULT
);
3489 return SOCKET_ERROR
;
3491 if (WS_getpeername(s
, &addr
, &len
) == SOCKET_ERROR
)
3492 *(DWORD
*)optval
= ~0u;
3495 if (!pretendtime
) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3496 *(DWORD
*)optval
= pretendtime
++;
3498 *optlen
= sizeof(DWORD
);
3501 /* As mentioned in setsockopt, Windows ignores this, so we
3502 * always return true here */
3503 case WS_SO_DONTROUTE
:
3504 if (!optlen
|| *optlen
< sizeof(BOOL
) || !optval
)
3506 SetLastError(WSAEFAULT
);
3507 return SOCKET_ERROR
;
3509 *(BOOL
*)optval
= TRUE
;
3510 *optlen
= sizeof(BOOL
);
3515 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3516 return SOCKET_ERROR
;
3517 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, optval
, (socklen_t
*)optlen
) != 0 )
3519 SetLastError(wsaErrno());
3522 release_sock_fd( s
, fd
);
3524 /* The wineserver may have swallowed the error before us */
3525 if (!ret
&& *(int*) optval
== 0)
3527 int i
, events
[FD_MAX_EVENTS
];
3528 _get_sock_errors(s
, events
);
3529 for (i
= 0; i
< FD_MAX_EVENTS
; i
++)
3533 events
[i
] = NtStatusToWSAError(events
[i
]);
3534 TRACE("returning SO_ERROR %d from wine server\n", events
[i
]);
3535 *(int*) optval
= events
[i
];
3545 struct linger lingval
;
3547 socklen_t len
= sizeof(struct linger
), slen
= sizeof(int);
3549 /* struct linger and LINGER have different sizes */
3550 if (!optlen
|| *optlen
< sizeof(LINGER
) || !optval
)
3552 SetLastError(WSAEFAULT
);
3553 return SOCKET_ERROR
;
3555 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3556 return SOCKET_ERROR
;
3558 if ((getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, &so_type
, &slen
) == 0 && so_type
== SOCK_DGRAM
))
3560 SetLastError(WSAENOPROTOOPT
);
3563 else if (getsockopt(fd
, SOL_SOCKET
, SO_LINGER
, &lingval
, &len
) != 0)
3565 SetLastError(wsaErrno());
3570 ((LINGER
*)optval
)->l_onoff
= lingval
.l_onoff
;
3571 ((LINGER
*)optval
)->l_linger
= lingval
.l_linger
;
3572 *optlen
= sizeof(struct linger
);
3575 release_sock_fd( s
, fd
);
3579 case WS_SO_MAX_MSG_SIZE
:
3580 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
3582 SetLastError(WSAEFAULT
);
3583 return SOCKET_ERROR
;
3585 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3586 *(int *)optval
= 65507;
3587 *optlen
= sizeof(int);
3590 /* SO_OPENTYPE does not require a valid socket handle. */
3591 case WS_SO_OPENTYPE
:
3592 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
3594 SetLastError(WSAEFAULT
);
3595 return SOCKET_ERROR
;
3597 *(int *)optval
= get_per_thread_data()->opentype
;
3598 *optlen
= sizeof(int);
3599 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval
) );
3601 case WS_SO_PROTOCOL_INFOA
:
3602 case WS_SO_PROTOCOL_INFOW
:
3605 WSAPROTOCOL_INFOW infow
;
3607 ret
= ws_protocol_info(s
, optname
== WS_SO_PROTOCOL_INFOW
, &infow
, &size
);
3610 if (!optlen
|| !optval
|| *optlen
< size
)
3612 if(optlen
) *optlen
= size
;
3614 SetLastError(WSAEFAULT
);
3617 memcpy(optval
, &infow
, size
);
3619 return ret
? 0 : SOCKET_ERROR
;
3622 case WS_SO_RCVTIMEO
:
3625 case WS_SO_SNDTIMEO
:
3627 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3630 socklen_t len
= sizeof(struct timeval
);
3632 if (!optlen
|| *optlen
< sizeof(int)|| !optval
)
3634 SetLastError(WSAEFAULT
);
3635 return SOCKET_ERROR
;
3637 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3638 return SOCKET_ERROR
;
3640 convert_sockopt(&level
, &optname
);
3641 if (getsockopt(fd
, level
, optname
, &tv
, &len
) != 0 )
3643 SetLastError(wsaErrno());
3648 *(int *)optval
= tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000;
3649 *optlen
= sizeof(int);
3652 release_sock_fd( s
, fd
);
3658 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
3660 SetLastError(WSAEFAULT
);
3661 return SOCKET_ERROR
;
3663 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3664 return SOCKET_ERROR
;
3666 if (getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, optval
, (socklen_t
*)optlen
) != 0 )
3668 SetLastError(wsaErrno());
3672 (*(int *)optval
) = convert_socktype_u2w(*(int *)optval
);
3674 release_sock_fd( s
, fd
);
3678 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname
);
3679 SetLastError(WSAENOPROTOOPT
);
3680 return SOCKET_ERROR
;
3681 } /* end switch(optname) */
3682 }/* end case WS_SOL_SOCKET */
3684 case WS_NSPROTO_IPX
:
3686 struct WS_sockaddr_ipx addr
;
3687 IPX_ADDRESS_DATA
*data
;
3692 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
3694 if(getsockopt(fd
, SOL_IPX
, IPX_TYPE
, optval
, (socklen_t
*)optlen
) == -1)
3701 socklen_t len
=sizeof(struct ipx
);
3702 if(getsockopt(fd
, 0, SO_DEFAULT_HEADERS
, &val
, &len
) == -1 )
3705 *optval
= (int)val
.ipx_pt
;
3708 TRACE("ptype: %d (fd: %d)\n", *(int*)optval
, fd
);
3709 release_sock_fd( s
, fd
);
3712 case WS_IPX_ADDRESS
:
3714 * On a Win2000 system with one network card there are usually
3715 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
3716 * Using this call you can then retrieve info about this all.
3717 * In case of Linux it is a bit different. Usually you have
3718 * only "one" device active and further it is not possible to
3719 * query things like the linkspeed.
3721 FIXME("IPX_ADDRESS\n");
3722 namelen
= sizeof(struct WS_sockaddr_ipx
);
3723 memset(&addr
, 0, sizeof(struct WS_sockaddr_ipx
));
3724 WS_getsockname(s
, (struct WS_sockaddr
*)&addr
, &namelen
);
3726 data
= (IPX_ADDRESS_DATA
*)optval
;
3727 memcpy(data
->nodenum
,addr
.sa_nodenum
,sizeof(data
->nodenum
));
3728 memcpy(data
->netnum
,addr
.sa_netnum
,sizeof(data
->netnum
));
3729 data
->adapternum
= 0;
3730 data
->wan
= FALSE
; /* We are not on a wan for now .. */
3731 data
->status
= FALSE
; /* Since we are not on a wan, the wan link isn't up */
3732 data
->maxpkt
= 1467; /* This value is the default one, at least on Win2k/WinXP */
3733 data
->linkspeed
= 100000; /* Set the line speed in 100bit/s to 10 Mbit;
3734 * note 1MB = 1000kB in this case */
3737 case WS_IPX_MAX_ADAPTER_NUM
:
3738 FIXME("IPX_MAX_ADAPTER_NUM\n");
3739 *(int*)optval
= 1; /* As noted under IPX_ADDRESS we have just one card. */
3743 FIXME("IPX optname:%x\n", optname
);
3744 return SOCKET_ERROR
;
3745 }/* end switch(optname) */
3746 } /* end case WS_NSPROTO_IPX */
3750 #define MAX_IRDA_DEVICES 10
3755 case WS_IRLMP_ENUMDEVICES
:
3757 char buf
[sizeof(struct irda_device_list
) +
3758 (MAX_IRDA_DEVICES
- 1) * sizeof(struct irda_device_info
)];
3760 socklen_t len
= sizeof(buf
);
3762 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3763 return SOCKET_ERROR
;
3764 res
= getsockopt( fd
, SOL_IRLMP
, IRLMP_ENUMDEVICES
, buf
, &len
);
3765 release_sock_fd( s
, fd
);
3768 SetLastError(wsaErrno());
3769 return SOCKET_ERROR
;
3773 struct irda_device_list
*src
= (struct irda_device_list
*)buf
;
3774 DEVICELIST
*dst
= (DEVICELIST
*)optval
;
3775 INT needed
= sizeof(DEVICELIST
);
3779 needed
+= (src
->len
- 1) * sizeof(IRDA_DEVICE_INFO
);
3780 if (*optlen
< needed
)
3782 SetLastError(WSAEFAULT
);
3783 return SOCKET_ERROR
;
3786 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src
->len
);
3787 dst
->numDevice
= src
->len
;
3788 for (i
= 0; i
< src
->len
; i
++)
3790 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
3791 src
->dev
[i
].saddr
, src
->dev
[i
].daddr
,
3792 src
->dev
[i
].info
, src
->dev
[i
].hints
[0],
3793 src
->dev
[i
].hints
[1]);
3794 memcpy( dst
->Device
[i
].irdaDeviceID
,
3796 sizeof(dst
->Device
[i
].irdaDeviceID
) ) ;
3797 memcpy( dst
->Device
[i
].irdaDeviceName
,
3799 sizeof(dst
->Device
[i
].irdaDeviceName
) ) ;
3800 memcpy( &dst
->Device
[i
].irdaDeviceHints1
,
3801 &src
->dev
[i
].hints
[0],
3802 sizeof(dst
->Device
[i
].irdaDeviceHints1
) ) ;
3803 memcpy( &dst
->Device
[i
].irdaDeviceHints2
,
3804 &src
->dev
[i
].hints
[1],
3805 sizeof(dst
->Device
[i
].irdaDeviceHints2
) ) ;
3806 dst
->Device
[i
].irdaCharSet
= src
->dev
[i
].charset
;
3812 FIXME("IrDA optname:0x%x\n", optname
);
3813 return SOCKET_ERROR
;
3815 break; /* case WS_SOL_IRLMP */
3816 #undef MAX_IRDA_DEVICES
3819 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3820 case WS_IPPROTO_TCP
:
3823 case WS_TCP_NODELAY
:
3824 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3825 return SOCKET_ERROR
;
3826 convert_sockopt(&level
, &optname
);
3827 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3829 SetLastError(wsaErrno());
3832 release_sock_fd( s
, fd
);
3835 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname
);
3836 return SOCKET_ERROR
;
3841 case WS_IP_ADD_MEMBERSHIP
:
3842 case WS_IP_DROP_MEMBERSHIP
:
3846 case WS_IP_MULTICAST_IF
:
3847 case WS_IP_MULTICAST_LOOP
:
3848 case WS_IP_MULTICAST_TTL
:
3855 #ifdef IP_UNICAST_IF
3856 case WS_IP_UNICAST_IF
:
3858 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3859 return SOCKET_ERROR
;
3860 convert_sockopt(&level
, &optname
);
3861 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3863 SetLastError(wsaErrno());
3866 release_sock_fd( s
, fd
);
3868 case WS_IP_DONTFRAGMENT
:
3869 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
3870 *(BOOL
*)optval
= FALSE
;
3873 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname
);
3874 return SOCKET_ERROR
;
3876 case WS_IPPROTO_IPV6
:
3879 #ifdef IPV6_ADD_MEMBERSHIP
3880 case WS_IPV6_ADD_MEMBERSHIP
:
3882 #ifdef IPV6_DROP_MEMBERSHIP
3883 case WS_IPV6_DROP_MEMBERSHIP
:
3885 case WS_IPV6_MULTICAST_IF
:
3886 case WS_IPV6_MULTICAST_HOPS
:
3887 case WS_IPV6_MULTICAST_LOOP
:
3888 case WS_IPV6_UNICAST_HOPS
:
3889 case WS_IPV6_V6ONLY
:
3890 #ifdef IPV6_UNICAST_IF
3891 case WS_IPV6_UNICAST_IF
:
3893 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3894 return SOCKET_ERROR
;
3895 convert_sockopt(&level
, &optname
);
3896 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3898 SetLastError(wsaErrno());
3901 release_sock_fd( s
, fd
);
3903 case WS_IPV6_DONTFRAG
:
3904 FIXME("WS_IPV6_DONTFRAG is always false!\n");
3905 *(BOOL
*)optval
= FALSE
;
3908 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname
);
3909 return SOCKET_ERROR
;
3912 WARN("Unknown level: 0x%08x\n", level
);
3913 SetLastError(WSAEINVAL
);
3914 return SOCKET_ERROR
;
3915 } /* end switch(level) */
3918 /***********************************************************************
3921 WS_u_long WINAPI
WS_htonl(WS_u_long hostlong
)
3923 return htonl(hostlong
);
3927 /***********************************************************************
3930 WS_u_short WINAPI
WS_htons(WS_u_short hostshort
)
3932 return htons(hostshort
);
3935 /***********************************************************************
3936 * WSAHtonl (WS2_32.46)
3937 * From MSDN description of error codes, this function should also
3938 * check if WinSock has been initialized and the socket is a valid
3939 * socket. But why? This function only translates a host byte order
3940 * u_long into a network byte order u_long...
3942 int WINAPI
WSAHtonl(SOCKET s
, WS_u_long hostlong
, WS_u_long
*lpnetlong
)
3946 *lpnetlong
= htonl(hostlong
);
3949 SetLastError(WSAEFAULT
);
3950 return SOCKET_ERROR
;
3953 /***********************************************************************
3954 * WSAHtons (WS2_32.47)
3955 * From MSDN description of error codes, this function should also
3956 * check if WinSock has been initialized and the socket is a valid
3957 * socket. But why? This function only translates a host byte order
3958 * u_short into a network byte order u_short...
3960 int WINAPI
WSAHtons(SOCKET s
, WS_u_short hostshort
, WS_u_short
*lpnetshort
)
3965 *lpnetshort
= htons(hostshort
);
3968 SetLastError(WSAEFAULT
);
3969 return SOCKET_ERROR
;
3973 /***********************************************************************
3974 * inet_addr (WS2_32.11)
3976 WS_u_long WINAPI
WS_inet_addr(const char *cp
)
3978 if (!cp
) return INADDR_NONE
;
3979 return inet_addr(cp
);
3983 /***********************************************************************
3986 WS_u_long WINAPI
WS_ntohl(WS_u_long netlong
)
3988 return ntohl(netlong
);
3992 /***********************************************************************
3995 WS_u_short WINAPI
WS_ntohs(WS_u_short netshort
)
3997 return ntohs(netshort
);
4001 /***********************************************************************
4002 * inet_ntoa (WS2_32.12)
4004 char* WINAPI
WS_inet_ntoa(struct WS_in_addr in
)
4006 char* s
= inet_ntoa(*((struct in_addr
*)&in
));
4009 struct per_thread_data
*data
= get_per_thread_data();
4010 strcpy(data
->ntoa_buffer
, s
);
4011 return data
->ntoa_buffer
;
4013 SetLastError(wsaErrno());
4017 static const char *debugstr_wsaioctl(DWORD ioctl
)
4019 const char *buf_type
, *family
;
4021 switch(ioctl
& 0x18000000)
4026 case WS_IOC_PROTOCOL
:
4027 family
= "IOC_PROTOCOL";
4030 family
= "IOC_VENDOR";
4032 default: /* WS_IOC_UNIX */
4034 BYTE size
= (ioctl
>> 16) & WS_IOCPARM_MASK
;
4035 char x
= (ioctl
& 0xff00) >> 8;
4036 BYTE y
= ioctl
& 0xff;
4039 switch (ioctl
& (WS_IOC_VOID
|WS_IOC_INOUT
))
4043 sprintf(args
, "%d, %d", x
, y
);
4047 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
4051 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
4055 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
4058 return wine_dbg_sprintf("%s(%s)", buf_type
, args
);
4062 /* We are different from WS_IOC_UNIX. */
4063 switch (ioctl
& (WS_IOC_VOID
|WS_IOC_INOUT
))
4066 buf_type
= "_WSAIO";
4069 buf_type
= "_WSAIORW";
4072 buf_type
= "_WSAIOW";
4075 buf_type
= "_WSAIOR";
4082 return wine_dbg_sprintf("%s(%s, %d)", buf_type
, family
,
4083 (USHORT
)(ioctl
& 0xffff));
4086 /* do an ioctl call through the server */
4087 static DWORD
server_ioctl_sock( SOCKET s
, DWORD code
, LPVOID in_buff
, DWORD in_size
,
4088 LPVOID out_buff
, DWORD out_size
, LPDWORD ret_size
,
4089 LPWSAOVERLAPPED overlapped
,
4090 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
4092 HANDLE event
= overlapped
? overlapped
->hEvent
: 0;
4093 HANDLE handle
= SOCKET2HANDLE( s
);
4094 struct ws2_async
*wsa
;
4096 PIO_STATUS_BLOCK io
;
4098 if (!(wsa
= (struct ws2_async
*)alloc_async_io( sizeof(*wsa
) )))
4099 return WSA_NOT_ENOUGH_MEMORY
;
4100 wsa
->hSocket
= handle
;
4101 wsa
->user_overlapped
= overlapped
;
4102 wsa
->completion_func
= completion
;
4103 io
= (overlapped
? (PIO_STATUS_BLOCK
)overlapped
: &wsa
->local_iosb
);
4105 status
= NtDeviceIoControlFile( handle
, event
, ws2_async_apc
, wsa
, io
, code
,
4106 in_buff
, in_size
, out_buff
, out_size
);
4107 if (status
== STATUS_NOT_SUPPORTED
)
4109 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
4110 code
, code
>> 16, (code
>> 14) & 3, (code
>> 2) & 0xfff, code
& 3);
4112 else if (status
== STATUS_SUCCESS
)
4113 *ret_size
= io
->Information
; /* "Information" is the size written to the output buffer */
4115 if (status
!= STATUS_PENDING
) RtlFreeHeap( GetProcessHeap(), 0, wsa
);
4117 return NtStatusToWSAError( status
);
4120 /**********************************************************************
4121 * WSAIoctl (WS2_32.50)
4124 INT WINAPI
WSAIoctl(SOCKET s
, DWORD code
, LPVOID in_buff
, DWORD in_size
, LPVOID out_buff
,
4125 DWORD out_size
, LPDWORD ret_size
, LPWSAOVERLAPPED overlapped
,
4126 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
4129 DWORD status
= 0, total
= 0;
4131 TRACE("%04lx, %s, %p, %d, %p, %d, %p, %p, %p\n",
4132 s
, debugstr_wsaioctl(code
), in_buff
, in_size
, out_buff
, out_size
, ret_size
, overlapped
, completion
);
4137 if (in_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(in_buff
))
4139 SetLastError(WSAEFAULT
);
4140 return SOCKET_ERROR
;
4142 TRACE("-> FIONBIO (%x)\n", *(WS_u_long
*)in_buff
);
4143 if (_get_sock_mask(s
))
4145 /* AsyncSelect()'ed sockets are always nonblocking */
4146 if (!*(WS_u_long
*)in_buff
) status
= WSAEINVAL
;
4149 if (*(WS_u_long
*)in_buff
)
4150 _enable_event(SOCKET2HANDLE(s
), 0, FD_WINE_NONBLOCKING
, 0);
4152 _enable_event(SOCKET2HANDLE(s
), 0, 0, FD_WINE_NONBLOCKING
);
4157 if (out_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(out_buff
))
4159 SetLastError(WSAEFAULT
);
4160 return SOCKET_ERROR
;
4162 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
4163 if (ioctl(fd
, FIONREAD
, out_buff
) == -1)
4164 status
= wsaErrno();
4165 release_sock_fd( s
, fd
);
4171 unsigned int oob
= 0, atmark
= 0;
4172 socklen_t oobsize
= sizeof(int);
4173 if (out_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(out_buff
))
4175 SetLastError(WSAEFAULT
);
4176 return SOCKET_ERROR
;
4178 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
4179 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
4180 if ((getsockopt(fd
, SOL_SOCKET
, SO_OOBINLINE
, &oob
, &oobsize
) == -1)
4181 || (!oob
&& ioctl(fd
, SIOCATMARK
, &atmark
) == -1))
4182 status
= wsaErrno();
4185 /* The SIOCATMARK value read from ioctl() is reversed
4186 * because BSD returns TRUE if it's in the OOB mark
4187 * while Windows returns TRUE if there are NO OOB bytes.
4189 (*(WS_u_long
*) out_buff
) = oob
|| !atmark
;
4192 release_sock_fd( s
, fd
);
4197 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
4198 SetLastError(WSAEINVAL
);
4199 return SOCKET_ERROR
;
4201 case WS_SIO_GET_INTERFACE_LIST
:
4203 INTERFACE_INFO
* intArray
= out_buff
;
4204 DWORD size
, numInt
= 0, apiReturn
;
4206 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
4208 if (!out_buff
|| !ret_size
)
4210 SetLastError(WSAEFAULT
);
4211 return SOCKET_ERROR
;
4214 fd
= get_sock_fd( s
, 0, NULL
);
4215 if (fd
== -1) return SOCKET_ERROR
;
4217 apiReturn
= GetAdaptersInfo(NULL
, &size
);
4218 if (apiReturn
== ERROR_BUFFER_OVERFLOW
)
4220 PIP_ADAPTER_INFO table
= HeapAlloc(GetProcessHeap(),0,size
);
4224 if (GetAdaptersInfo(table
, &size
) == NO_ERROR
)
4226 PIP_ADAPTER_INFO ptr
;
4228 for (ptr
= table
, numInt
= 0; ptr
; ptr
= ptr
->Next
)
4230 unsigned int addr
, mask
, bcast
;
4231 struct ifreq ifInfo
;
4233 /* Skip interfaces without an IPv4 address. */
4234 if (ptr
->IpAddressList
.IpAddress
.String
[0] == '\0')
4237 if ((numInt
+ 1)*sizeof(INTERFACE_INFO
)/sizeof(IP_ADAPTER_INFO
) > out_size
)
4239 WARN("Buffer too small = %u, out_size = %u\n", numInt
+ 1, out_size
);
4244 /* Socket Status Flags */
4245 lstrcpynA(ifInfo
.ifr_name
, ptr
->AdapterName
, IFNAMSIZ
);
4246 if (ioctl(fd
, SIOCGIFFLAGS
, &ifInfo
) < 0)
4248 ERR("Error obtaining status flags for socket!\n");
4254 /* set flags; the values of IFF_* are not the same
4255 under Linux and Windows, therefore must generate
4257 intArray
->iiFlags
= 0;
4258 if (ifInfo
.ifr_flags
& IFF_BROADCAST
)
4259 intArray
->iiFlags
|= WS_IFF_BROADCAST
;
4260 #ifdef IFF_POINTOPOINT
4261 if (ifInfo
.ifr_flags
& IFF_POINTOPOINT
)
4262 intArray
->iiFlags
|= WS_IFF_POINTTOPOINT
;
4264 if (ifInfo
.ifr_flags
& IFF_LOOPBACK
)
4265 intArray
->iiFlags
|= WS_IFF_LOOPBACK
;
4266 if (ifInfo
.ifr_flags
& IFF_UP
)
4267 intArray
->iiFlags
|= WS_IFF_UP
;
4268 if (ifInfo
.ifr_flags
& IFF_MULTICAST
)
4269 intArray
->iiFlags
|= WS_IFF_MULTICAST
;
4272 addr
= inet_addr(ptr
->IpAddressList
.IpAddress
.String
);
4273 mask
= inet_addr(ptr
->IpAddressList
.IpMask
.String
);
4274 bcast
= addr
| ~mask
;
4275 intArray
->iiAddress
.AddressIn
.sin_family
= AF_INET
;
4276 intArray
->iiAddress
.AddressIn
.sin_port
= 0;
4277 intArray
->iiAddress
.AddressIn
.sin_addr
.WS_s_addr
=
4279 intArray
->iiNetmask
.AddressIn
.sin_family
= AF_INET
;
4280 intArray
->iiNetmask
.AddressIn
.sin_port
= 0;
4281 intArray
->iiNetmask
.AddressIn
.sin_addr
.WS_s_addr
=
4283 intArray
->iiBroadcastAddress
.AddressIn
.sin_family
=
4285 intArray
->iiBroadcastAddress
.AddressIn
.sin_port
= 0;
4286 intArray
->iiBroadcastAddress
.AddressIn
.sin_addr
.
4294 ERR("Unable to get interface table!\n");
4297 HeapFree(GetProcessHeap(),0,table
);
4299 else status
= WSAEINVAL
;
4301 else if (apiReturn
!= ERROR_NO_DATA
)
4303 ERR("Unable to get interface table!\n");
4306 /* Calculate the size of the array being returned */
4307 total
= sizeof(INTERFACE_INFO
) * numInt
;
4308 release_sock_fd( s
, fd
);
4312 case WS_SIO_ADDRESS_LIST_QUERY
:
4316 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
4320 SetLastError(WSAEFAULT
);
4321 return SOCKET_ERROR
;
4324 if (out_size
&& out_size
< FIELD_OFFSET(SOCKET_ADDRESS_LIST
, Address
[0]))
4327 SetLastError(WSAEINVAL
);
4328 return SOCKET_ERROR
;
4331 if (GetAdaptersInfo(NULL
, &size
) == ERROR_BUFFER_OVERFLOW
)
4333 IP_ADAPTER_INFO
*p
, *table
= HeapAlloc(GetProcessHeap(), 0, size
);
4334 SOCKET_ADDRESS_LIST
*sa_list
;
4335 SOCKADDR_IN
*sockaddr
;
4340 if (!table
|| GetAdaptersInfo(table
, &size
))
4342 HeapFree(GetProcessHeap(), 0, table
);
4347 for (p
= table
, num
= 0; p
; p
= p
->Next
)
4348 if (p
->IpAddressList
.IpAddress
.String
[0]) num
++;
4350 total
= FIELD_OFFSET(SOCKET_ADDRESS_LIST
, Address
[num
]) + num
* sizeof(*sockaddr
);
4351 if (total
> out_size
|| !out_buff
)
4354 HeapFree(GetProcessHeap(), 0, table
);
4360 sa
= sa_list
->Address
;
4361 sockaddr
= (SOCKADDR_IN
*)&sa
[num
];
4362 sa_list
->iAddressCount
= num
;
4364 for (p
= table
, i
= 0; p
; p
= p
->Next
)
4366 if (!p
->IpAddressList
.IpAddress
.String
[0]) continue;
4368 sa
[i
].lpSockaddr
= (SOCKADDR
*)&sockaddr
[i
];
4369 sa
[i
].iSockaddrLength
= sizeof(SOCKADDR
);
4371 sockaddr
[i
].sin_family
= AF_INET
;
4372 sockaddr
[i
].sin_port
= 0;
4373 sockaddr
[i
].sin_addr
.WS_s_addr
= inet_addr(p
->IpAddressList
.IpAddress
.String
);
4377 HeapFree(GetProcessHeap(), 0, table
);
4381 WARN("unable to get IP address list\n");
4388 FIXME("SIO_FLUSH: stub.\n");
4391 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER
:
4393 static const GUID connectex_guid
= WSAID_CONNECTEX
;
4394 static const GUID disconnectex_guid
= WSAID_DISCONNECTEX
;
4395 static const GUID acceptex_guid
= WSAID_ACCEPTEX
;
4396 static const GUID getaccepexsockaddrs_guid
= WSAID_GETACCEPTEXSOCKADDRS
;
4397 static const GUID transmitfile_guid
= WSAID_TRANSMITFILE
;
4398 static const GUID transmitpackets_guid
= WSAID_TRANSMITPACKETS
;
4399 static const GUID wsarecvmsg_guid
= WSAID_WSARECVMSG
;
4400 static const GUID wsasendmsg_guid
= WSAID_WSASENDMSG
;
4402 if ( IsEqualGUID(&connectex_guid
, in_buff
) )
4404 *(LPFN_CONNECTEX
*)out_buff
= WS2_ConnectEx
;
4407 else if ( IsEqualGUID(&disconnectex_guid
, in_buff
) )
4409 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
4411 else if ( IsEqualGUID(&acceptex_guid
, in_buff
) )
4413 *(LPFN_ACCEPTEX
*)out_buff
= WS2_AcceptEx
;
4416 else if ( IsEqualGUID(&getaccepexsockaddrs_guid
, in_buff
) )
4418 *(LPFN_GETACCEPTEXSOCKADDRS
*)out_buff
= WS2_GetAcceptExSockaddrs
;
4421 else if ( IsEqualGUID(&transmitfile_guid
, in_buff
) )
4423 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
4425 else if ( IsEqualGUID(&transmitpackets_guid
, in_buff
) )
4427 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
4429 else if ( IsEqualGUID(&wsarecvmsg_guid
, in_buff
) )
4431 *(LPFN_WSARECVMSG
*)out_buff
= WS2_WSARecvMsg
;
4434 else if ( IsEqualGUID(&wsasendmsg_guid
, in_buff
) )
4436 *(LPFN_WSASENDMSG
*)out_buff
= WSASendMsg
;
4440 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff
));
4442 status
= WSAEOPNOTSUPP
;
4445 case WS_SIO_KEEPALIVE_VALS
:
4447 struct tcp_keepalive
*k
;
4448 int keepalive
, keepidle
, keepintvl
;
4450 if (!in_buff
|| in_size
< sizeof(struct tcp_keepalive
))
4452 SetLastError(WSAEFAULT
);
4453 return SOCKET_ERROR
;
4457 keepalive
= k
->onoff
? 1 : 0;
4458 keepidle
= max( 1, (k
->keepalivetime
+ 500) / 1000 );
4459 keepintvl
= max( 1, (k
->keepaliveinterval
+ 500) / 1000 );
4461 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive
, keepidle
, keepintvl
);
4463 fd
= get_sock_fd(s
, 0, NULL
);
4464 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&keepalive
, sizeof(int)) == -1)
4466 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
4467 /* these values need to be set only if SO_KEEPALIVE is enabled */
4470 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPIDLE
, (void *)&keepidle
, sizeof(int)) == -1)
4472 else if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPINTVL
, (void *)&keepintvl
, sizeof(int)) == -1)
4477 FIXME("ignoring keepalive interval and timeout\n");
4479 release_sock_fd(s
, fd
);
4482 case WS_SIO_ROUTING_INTERFACE_QUERY
:
4484 struct WS_sockaddr
*daddr
= (struct WS_sockaddr
*)in_buff
;
4485 struct WS_sockaddr_in
*daddr_in
= (struct WS_sockaddr_in
*)daddr
;
4486 struct WS_sockaddr_in
*saddr_in
= out_buff
;
4487 MIB_IPFORWARDROW row
;
4488 PMIB_IPADDRTABLE ipAddrTable
= NULL
;
4489 DWORD size
, i
, found_index
;
4491 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4493 if (!in_buff
|| in_size
< sizeof(struct WS_sockaddr
) ||
4494 !out_buff
|| out_size
< sizeof(struct WS_sockaddr_in
) || !ret_size
)
4496 SetLastError(WSAEFAULT
);
4497 return SOCKET_ERROR
;
4499 if (daddr
->sa_family
!= AF_INET
)
4501 FIXME("unsupported address family %d\n", daddr
->sa_family
);
4502 status
= WSAEAFNOSUPPORT
;
4505 if (GetBestRoute(daddr_in
->sin_addr
.S_un
.S_addr
, 0, &row
) != NOERROR
||
4506 GetIpAddrTable(NULL
, &size
, FALSE
) != ERROR_INSUFFICIENT_BUFFER
)
4511 ipAddrTable
= HeapAlloc(GetProcessHeap(), 0, size
);
4512 if (GetIpAddrTable(ipAddrTable
, &size
, FALSE
))
4514 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
4518 for (i
= 0, found_index
= ipAddrTable
->dwNumEntries
;
4519 i
< ipAddrTable
->dwNumEntries
; i
++)
4521 if (ipAddrTable
->table
[i
].dwIndex
== row
.dwForwardIfIndex
)
4524 if (found_index
== ipAddrTable
->dwNumEntries
)
4526 ERR("no matching IP address for interface %d\n",
4527 row
.dwForwardIfIndex
);
4528 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
4532 saddr_in
->sin_family
= AF_INET
;
4533 saddr_in
->sin_addr
.S_un
.S_addr
= ipAddrTable
->table
[found_index
].dwAddr
;
4534 saddr_in
->sin_port
= 0;
4535 total
= sizeof(struct WS_sockaddr_in
);
4536 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
4539 case WS_SIO_SET_COMPATIBILITY_MODE
:
4540 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4541 status
= WSAEOPNOTSUPP
;
4543 case WS_SIO_UDP_CONNRESET
:
4544 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4546 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4547 SetLastError(WSAEOPNOTSUPP
);
4548 return SOCKET_ERROR
;
4550 status
= WSAEOPNOTSUPP
;
4554 if (status
== WSAEOPNOTSUPP
)
4556 status
= server_ioctl_sock(s
, code
, in_buff
, in_size
, out_buff
, out_size
, &total
,
4557 overlapped
, completion
);
4558 if (status
!= WSAEOPNOTSUPP
)
4560 if (status
== 0 || status
== WSA_IO_PENDING
)
4561 TRACE("-> %s request\n", debugstr_wsaioctl(code
));
4563 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code
), status
);
4565 /* overlapped and completion operations will be handled by the server */
4570 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code
));
4575 FIXME( "completion routine %p not supported\n", completion
);
4577 else if (overlapped
)
4579 ULONG_PTR cvalue
= (overlapped
&& ((ULONG_PTR
)overlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)overlapped
: 0;
4580 overlapped
->Internal
= status
;
4581 overlapped
->InternalHigh
= total
;
4582 if (overlapped
->hEvent
) NtSetEvent( overlapped
->hEvent
, NULL
);
4583 if (cvalue
) WS_AddCompletion( HANDLE2SOCKET(s
), cvalue
, status
, total
);
4588 if (ret_size
) *ret_size
= total
;
4591 SetLastError( status
);
4592 return SOCKET_ERROR
;
4596 /***********************************************************************
4597 * ioctlsocket (WS2_32.10)
4599 int WINAPI
WS_ioctlsocket(SOCKET s
, LONG cmd
, WS_u_long
*argp
)
4602 return WSAIoctl( s
, cmd
, argp
, sizeof(WS_u_long
), argp
, sizeof(WS_u_long
), &ret_size
, NULL
, NULL
);
4605 /***********************************************************************
4606 * listen (WS2_32.13)
4608 int WINAPI
WS_listen(SOCKET s
, int backlog
)
4610 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
), ret
= SOCKET_ERROR
;
4612 TRACE("socket %04lx, backlog %d\n", s
, backlog
);
4615 int bound
= is_fd_bound(fd
, NULL
, NULL
);
4619 SetLastError(bound
== -1 ? wsaErrno() : WSAEINVAL
);
4621 else if (listen(fd
, backlog
) == 0)
4623 _enable_event(SOCKET2HANDLE(s
), FD_ACCEPT
,
4625 FD_CONNECT
|FD_WINE_CONNECTED
);
4629 SetLastError(wsaErrno());
4630 release_sock_fd( s
, fd
);
4633 SetLastError(WSAENOTSOCK
);
4637 /***********************************************************************
4640 int WINAPI
WS_recv(SOCKET s
, char *buf
, int len
, int flags
)
4642 DWORD n
, dwFlags
= flags
;
4648 if ( WS2_recv_base(s
, &wsabuf
, 1, &n
, &dwFlags
, NULL
, NULL
, NULL
, NULL
, NULL
) == SOCKET_ERROR
)
4649 return SOCKET_ERROR
;
4654 /***********************************************************************
4655 * recvfrom (WS2_32.17)
4657 int WINAPI
WS_recvfrom(SOCKET s
, char *buf
, INT len
, int flags
,
4658 struct WS_sockaddr
*from
, int *fromlen
)
4660 DWORD n
, dwFlags
= flags
;
4666 if ( WS2_recv_base(s
, &wsabuf
, 1, &n
, &dwFlags
, from
, fromlen
, NULL
, NULL
, NULL
) == SOCKET_ERROR
)
4667 return SOCKET_ERROR
;
4672 /* allocate a poll array for the corresponding fd sets */
4673 static struct pollfd
*fd_sets_to_poll( const WS_fd_set
*readfds
, const WS_fd_set
*writefds
,
4674 const WS_fd_set
*exceptfds
, int *count_ptr
)
4676 unsigned int i
, j
= 0, count
= 0;
4679 if (readfds
) count
+= readfds
->fd_count
;
4680 if (writefds
) count
+= writefds
->fd_count
;
4681 if (exceptfds
) count
+= exceptfds
->fd_count
;
4685 SetLastError(WSAEINVAL
);
4688 if (!(fds
= HeapAlloc( GetProcessHeap(), 0, count
* sizeof(fds
[0]))))
4690 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
4694 for (i
= 0; i
< readfds
->fd_count
; i
++, j
++)
4696 fds
[j
].fd
= get_sock_fd( readfds
->fd_array
[i
], FILE_READ_DATA
, NULL
);
4697 if (fds
[j
].fd
== -1) goto failed
;
4699 if (is_fd_bound(fds
[j
].fd
, NULL
, NULL
) == 1)
4701 fds
[j
].events
= POLLIN
;
4705 release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
4711 for (i
= 0; i
< writefds
->fd_count
; i
++, j
++)
4713 fds
[j
].fd
= get_sock_fd( writefds
->fd_array
[i
], FILE_WRITE_DATA
, NULL
);
4714 if (fds
[j
].fd
== -1) goto failed
;
4716 if (is_fd_bound(fds
[j
].fd
, NULL
, NULL
) == 1)
4718 fds
[j
].events
= POLLOUT
;
4722 release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
4728 for (i
= 0; i
< exceptfds
->fd_count
; i
++, j
++)
4730 fds
[j
].fd
= get_sock_fd( exceptfds
->fd_array
[i
], 0, NULL
);
4731 if (fds
[j
].fd
== -1) goto failed
;
4733 if (is_fd_bound(fds
[j
].fd
, NULL
, NULL
) == 1)
4735 int oob_inlined
= 0;
4736 socklen_t olen
= sizeof(oob_inlined
);
4738 fds
[j
].events
= POLLHUP
;
4740 /* Check if we need to test for urgent data or not */
4741 getsockopt(fds
[j
].fd
, SOL_SOCKET
, SO_OOBINLINE
, (char*) &oob_inlined
, &olen
);
4743 fds
[j
].events
|= POLLPRI
;
4747 release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
4758 for (i
= 0; i
< readfds
->fd_count
&& j
< count
; i
++, j
++)
4759 if (fds
[j
].fd
!= -1) release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
4761 for (i
= 0; i
< writefds
->fd_count
&& j
< count
; i
++, j
++)
4762 if (fds
[j
].fd
!= -1) release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
4764 for (i
= 0; i
< exceptfds
->fd_count
&& j
< count
; i
++, j
++)
4765 if (fds
[j
].fd
!= -1) release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
4766 HeapFree( GetProcessHeap(), 0, fds
);
4770 /* release the file descriptor obtained in fd_sets_to_poll */
4771 /* must be called with the original fd_set arrays, before calling get_poll_results */
4772 static void release_poll_fds( const WS_fd_set
*readfds
, const WS_fd_set
*writefds
,
4773 const WS_fd_set
*exceptfds
, struct pollfd
*fds
)
4775 unsigned int i
, j
= 0;
4779 for (i
= 0; i
< readfds
->fd_count
; i
++, j
++)
4780 if (fds
[j
].fd
!= -1) release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
4784 for (i
= 0; i
< writefds
->fd_count
; i
++, j
++)
4785 if (fds
[j
].fd
!= -1) release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
4789 for (i
= 0; i
< exceptfds
->fd_count
; i
++, j
++)
4790 if (fds
[j
].fd
!= -1) release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
4794 /* map the poll results back into the Windows fd sets */
4795 static int get_poll_results( WS_fd_set
*readfds
, WS_fd_set
*writefds
, WS_fd_set
*exceptfds
,
4796 const struct pollfd
*fds
)
4798 const struct pollfd
*poll_writefds
= fds
+ (readfds
? readfds
->fd_count
: 0);
4799 const struct pollfd
*poll_exceptfds
= poll_writefds
+ (writefds
? writefds
->fd_count
: 0);
4800 unsigned int i
, k
, total
= 0;
4804 for (i
= k
= 0; i
< readfds
->fd_count
; i
++)
4806 if (fds
[i
].revents
||
4807 (readfds
== writefds
&& (poll_writefds
[i
].revents
& POLLOUT
) && !(poll_writefds
[i
].revents
& POLLHUP
)) ||
4808 (readfds
== exceptfds
&& poll_exceptfds
[i
].revents
))
4809 readfds
->fd_array
[k
++] = readfds
->fd_array
[i
];
4811 readfds
->fd_count
= k
;
4814 if (writefds
&& writefds
!= readfds
)
4816 for (i
= k
= 0; i
< writefds
->fd_count
; i
++)
4818 if (((poll_writefds
[i
].revents
& POLLOUT
) && !(poll_writefds
[i
].revents
& POLLHUP
)) ||
4819 (writefds
== exceptfds
&& poll_exceptfds
[i
].revents
))
4820 writefds
->fd_array
[k
++] = writefds
->fd_array
[i
];
4822 writefds
->fd_count
= k
;
4825 if (exceptfds
&& exceptfds
!= readfds
&& exceptfds
!= writefds
)
4827 for (i
= k
= 0; i
< exceptfds
->fd_count
; i
++)
4828 if (poll_exceptfds
[i
].revents
) exceptfds
->fd_array
[k
++] = exceptfds
->fd_array
[i
];
4829 exceptfds
->fd_count
= k
;
4836 /***********************************************************************
4837 * select (WS2_32.18)
4839 int WINAPI
WS_select(int nfds
, WS_fd_set
*ws_readfds
,
4840 WS_fd_set
*ws_writefds
, WS_fd_set
*ws_exceptfds
,
4841 const struct WS_timeval
* ws_timeout
)
4843 struct pollfd
*pollfds
;
4844 struct timeval tv1
, tv2
;
4846 int count
, ret
, timeout
= -1;
4848 TRACE("read %p, write %p, excp %p timeout %p\n",
4849 ws_readfds
, ws_writefds
, ws_exceptfds
, ws_timeout
);
4851 if (!(pollfds
= fd_sets_to_poll( ws_readfds
, ws_writefds
, ws_exceptfds
, &count
)))
4852 return SOCKET_ERROR
;
4856 torig
= (ws_timeout
->tv_sec
* 1000) + (ws_timeout
->tv_usec
+ 999) / 1000;
4858 gettimeofday( &tv1
, 0 );
4861 while ((ret
= poll( pollfds
, count
, timeout
)) < 0)
4865 if (!ws_timeout
) continue;
4866 gettimeofday( &tv2
, 0 );
4868 tv2
.tv_sec
-= tv1
.tv_sec
;
4869 tv2
.tv_usec
-= tv1
.tv_usec
;
4870 if (tv2
.tv_usec
< 0)
4872 tv2
.tv_usec
+= 1000000;
4876 timeout
= torig
- (tv2
.tv_sec
* 1000) - (tv2
.tv_usec
+ 999) / 1000;
4884 release_poll_fds( ws_readfds
, ws_writefds
, ws_exceptfds
, pollfds
);
4886 if (ret
== -1) SetLastError(wsaErrno());
4887 else ret
= get_poll_results( ws_readfds
, ws_writefds
, ws_exceptfds
, pollfds
);
4888 HeapFree( GetProcessHeap(), 0, pollfds
);
4892 /* helper to send completion messages for client-only i/o operation case */
4893 static void WS_AddCompletion( SOCKET sock
, ULONG_PTR CompletionValue
, NTSTATUS CompletionStatus
,
4896 SERVER_START_REQ( add_fd_completion
)
4898 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(sock
) );
4899 req
->cvalue
= CompletionValue
;
4900 req
->status
= CompletionStatus
;
4901 req
->information
= Information
;
4902 wine_server_call( req
);
4908 /***********************************************************************
4911 int WINAPI
WS_send(SOCKET s
, const char *buf
, int len
, int flags
)
4917 wsabuf
.buf
= (char*) buf
;
4919 if ( WS2_sendto( s
, &wsabuf
, 1, &n
, flags
, NULL
, 0, NULL
, NULL
) == SOCKET_ERROR
)
4920 return SOCKET_ERROR
;
4925 /***********************************************************************
4926 * WSASend (WS2_32.72)
4928 INT WINAPI
WSASend( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
4929 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
4930 LPWSAOVERLAPPED lpOverlapped
,
4931 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
4933 return WS2_sendto( s
, lpBuffers
, dwBufferCount
, lpNumberOfBytesSent
, dwFlags
,
4934 NULL
, 0, lpOverlapped
, lpCompletionRoutine
);
4937 /***********************************************************************
4938 * WSASendDisconnect (WS2_32.73)
4940 INT WINAPI
WSASendDisconnect( SOCKET s
, LPWSABUF lpBuffers
)
4942 return WS_shutdown( s
, SD_SEND
);
4946 static int WS2_sendto( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
4947 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
4948 const struct WS_sockaddr
*to
, int tolen
,
4949 LPWSAOVERLAPPED lpOverlapped
,
4950 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
4952 unsigned int i
, options
;
4953 int n
, fd
, err
, overlapped
, flags
;
4954 struct ws2_async
*wsa
= NULL
, localwsa
;
4955 int totalLength
= 0;
4959 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
4960 s
, lpBuffers
, dwBufferCount
, dwFlags
,
4961 to
, tolen
, lpOverlapped
, lpCompletionRoutine
);
4963 fd
= get_sock_fd( s
, FILE_WRITE_DATA
, &options
);
4964 TRACE( "fd=%d, options=%x\n", fd
, options
);
4966 if ( fd
== -1 ) return SOCKET_ERROR
;
4968 if (!lpOverlapped
&& !lpNumberOfBytesSent
)
4974 overlapped
= (lpOverlapped
|| lpCompletionRoutine
) &&
4975 !(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
));
4976 if (overlapped
|| dwBufferCount
> 1)
4978 if (!(wsa
= (struct ws2_async
*)alloc_async_io( offsetof(struct ws2_async
, iovec
[dwBufferCount
]))))
4987 wsa
->hSocket
= SOCKET2HANDLE(s
);
4988 wsa
->addr
= (struct WS_sockaddr
*)to
;
4989 wsa
->addrlen
.val
= tolen
;
4990 wsa
->flags
= dwFlags
;
4991 wsa
->lpFlags
= &wsa
->flags
;
4992 wsa
->control
= NULL
;
4993 wsa
->n_iovecs
= dwBufferCount
;
4994 wsa
->first_iovec
= 0;
4995 for ( i
= 0; i
< dwBufferCount
; i
++ )
4997 wsa
->iovec
[i
].iov_base
= lpBuffers
[i
].buf
;
4998 wsa
->iovec
[i
].iov_len
= lpBuffers
[i
].len
;
4999 totalLength
+= lpBuffers
[i
].len
;
5002 flags
= convert_flags(dwFlags
);
5003 n
= WS2_send( fd
, wsa
, flags
);
5004 if (n
== -1 && errno
!= EAGAIN
)
5012 IO_STATUS_BLOCK
*iosb
= lpOverlapped
? (IO_STATUS_BLOCK
*)lpOverlapped
: &wsa
->local_iosb
;
5013 ULONG_PTR cvalue
= (lpOverlapped
&& ((ULONG_PTR
)lpOverlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)lpOverlapped
: 0;
5015 wsa
->user_overlapped
= lpOverlapped
;
5016 wsa
->completion_func
= lpCompletionRoutine
;
5017 release_sock_fd( s
, fd
);
5019 if (n
== -1 || n
< totalLength
)
5021 iosb
->u
.Status
= STATUS_PENDING
;
5022 iosb
->Information
= n
== -1 ? 0 : n
;
5024 SERVER_START_REQ( register_async
)
5026 req
->type
= ASYNC_TYPE_WRITE
;
5027 req
->async
.handle
= wine_server_obj_handle( wsa
->hSocket
);
5028 req
->async
.callback
= wine_server_client_ptr( WS2_async_send
);
5029 req
->async
.iosb
= wine_server_client_ptr( iosb
);
5030 req
->async
.arg
= wine_server_client_ptr( wsa
);
5031 req
->async
.event
= wine_server_obj_handle( lpCompletionRoutine
? 0 : lpOverlapped
->hEvent
);
5032 req
->async
.cvalue
= cvalue
;
5033 err
= wine_server_call( req
);
5037 /* Enable the event only after starting the async. The server will deliver it as soon as
5038 the async is done. */
5039 _enable_event(SOCKET2HANDLE(s
), FD_WRITE
, 0, 0);
5041 if (err
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
5042 SetLastError(NtStatusToWSAError( err
));
5043 return SOCKET_ERROR
;
5046 iosb
->u
.Status
= STATUS_SUCCESS
;
5047 iosb
->Information
= n
;
5048 if (lpNumberOfBytesSent
) *lpNumberOfBytesSent
= n
;
5049 if (!wsa
->completion_func
)
5051 if (cvalue
) WS_AddCompletion( s
, cvalue
, STATUS_SUCCESS
, n
);
5052 if (lpOverlapped
->hEvent
) SetEvent( lpOverlapped
->hEvent
);
5053 HeapFree( GetProcessHeap(), 0, wsa
);
5055 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC
)ws2_async_apc
,
5056 (ULONG_PTR
)wsa
, (ULONG_PTR
)iosb
, 0 );
5057 SetLastError(ERROR_SUCCESS
);
5061 if ((err
= _is_blocking( s
, &is_blocking
)))
5063 err
= NtStatusToWSAError( err
);
5069 /* On a blocking non-overlapped stream socket,
5070 * sending blocks until the entire buffer is sent. */
5071 DWORD timeout_start
= GetTickCount();
5073 bytes_sent
= n
== -1 ? 0 : n
;
5075 while (wsa
->first_iovec
< wsa
->n_iovecs
)
5078 int timeout
= GET_SNDTIMEO(fd
);
5082 timeout
-= GetTickCount() - timeout_start
;
5083 if (timeout
< 0) timeout
= 0;
5087 pfd
.events
= POLLOUT
;
5089 if (!timeout
|| !poll( &pfd
, 1, timeout
))
5092 goto error
; /* msdn says a timeout in send is fatal */
5095 n
= WS2_send( fd
, wsa
, flags
);
5096 if (n
== -1 && errno
!= EAGAIN
)
5106 else /* non-blocking */
5108 if (n
< totalLength
)
5109 _enable_event(SOCKET2HANDLE(s
), FD_WRITE
, 0, 0);
5112 err
= WSAEWOULDBLOCK
;
5118 TRACE(" -> %i bytes\n", bytes_sent
);
5120 if (lpNumberOfBytesSent
) *lpNumberOfBytesSent
= bytes_sent
;
5121 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
5122 release_sock_fd( s
, fd
);
5123 SetLastError(ERROR_SUCCESS
);
5127 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
5128 release_sock_fd( s
, fd
);
5129 WARN(" -> ERROR %d\n", err
);
5131 return SOCKET_ERROR
;
5134 /***********************************************************************
5135 * WSASendTo (WS2_32.74)
5137 INT WINAPI
WSASendTo( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
5138 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
5139 const struct WS_sockaddr
*to
, int tolen
,
5140 LPWSAOVERLAPPED lpOverlapped
,
5141 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
5143 return WS2_sendto( s
, lpBuffers
, dwBufferCount
,
5144 lpNumberOfBytesSent
, dwFlags
,
5146 lpOverlapped
, lpCompletionRoutine
);
5149 /***********************************************************************
5150 * sendto (WS2_32.20)
5152 int WINAPI
WS_sendto(SOCKET s
, const char *buf
, int len
, int flags
,
5153 const struct WS_sockaddr
*to
, int tolen
)
5159 wsabuf
.buf
= (char*) buf
;
5161 if ( WS2_sendto(s
, &wsabuf
, 1, &n
, flags
, to
, tolen
, NULL
, NULL
) == SOCKET_ERROR
)
5162 return SOCKET_ERROR
;
5167 /***********************************************************************
5168 * setsockopt (WS2_32.21)
5170 int WINAPI
WS_setsockopt(SOCKET s
, int level
, int optname
,
5171 const char *optval
, int optlen
)
5175 struct linger linger
;
5176 struct timeval tval
;
5178 TRACE("(socket %04lx, %s, optval %s, optlen %d)\n", s
,
5179 debugstr_sockopt(level
, optname
), debugstr_optval(optval
, optlen
),
5182 /* some broken apps pass the value directly instead of a pointer to it */
5183 if(optlen
&& IS_INTRESOURCE(optval
))
5185 SetLastError(WSAEFAULT
);
5186 return SOCKET_ERROR
;
5194 /* Some options need some conversion before they can be sent to
5195 * setsockopt. The conversions are done here, then they will fall through
5196 * to the general case. Special options that are not passed to
5197 * setsockopt follow below that.*/
5199 case WS_SO_DONTLINGER
:
5202 SetLastError(WSAEFAULT
);
5203 return SOCKET_ERROR
;
5205 linger
.l_onoff
= *(const int*)optval
== 0;
5206 linger
.l_linger
= 0;
5208 optname
= SO_LINGER
;
5209 optval
= (char*)&linger
;
5210 optlen
= sizeof(struct linger
);
5216 SetLastError(WSAEFAULT
);
5217 return SOCKET_ERROR
;
5219 linger
.l_onoff
= ((LINGER
*)optval
)->l_onoff
;
5220 linger
.l_linger
= ((LINGER
*)optval
)->l_linger
;
5222 optname
= SO_LINGER
;
5223 optval
= (char*)&linger
;
5224 optlen
= sizeof(struct linger
);
5228 if (*(const int*)optval
< 2048)
5230 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval
);
5235 /* The options listed here don't need any special handling. Thanks to
5236 * the conversion happening above, options from there will fall through
5238 case WS_SO_ACCEPTCONN
:
5239 case WS_SO_BROADCAST
:
5241 case WS_SO_KEEPALIVE
:
5242 case WS_SO_OOBINLINE
:
5243 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
5244 * however, using it the BSD way fixes bug 8513 and seems to be what
5245 * most programmers assume, anyway */
5246 case WS_SO_REUSEADDR
:
5249 convert_sockopt(&level
, &optname
);
5252 /* SO_DEBUG is a privileged operation, ignore it. */
5254 TRACE("Ignoring SO_DEBUG\n");
5257 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
5258 * socket. According to MSDN, this option is silently ignored.*/
5259 case WS_SO_DONTROUTE
:
5260 TRACE("Ignoring SO_DONTROUTE\n");
5263 /* Stops two sockets from being bound to the same port. Always happens
5264 * on unix systems, so just drop it. */
5265 case WS_SO_EXCLUSIVEADDRUSE
:
5266 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
5269 /* After a ConnectEx call succeeds, the socket can't be used with half of the
5270 * normal winsock functions on windows. We don't have that problem. */
5271 case WS_SO_UPDATE_CONNECT_CONTEXT
:
5272 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
5275 /* After a AcceptEx call succeeds, the socket can't be used with half of the
5276 * normal winsock functions on windows. We don't have that problem. */
5277 case WS_SO_UPDATE_ACCEPT_CONTEXT
:
5278 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
5281 /* SO_OPENTYPE does not require a valid socket handle. */
5282 case WS_SO_OPENTYPE
:
5283 if (!optlen
|| optlen
< sizeof(int) || !optval
)
5285 SetLastError(WSAEFAULT
);
5286 return SOCKET_ERROR
;
5288 get_per_thread_data()->opentype
= *(const int *)optval
;
5289 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval
) );
5293 case WS_SO_RCVTIMEO
:
5296 case WS_SO_SNDTIMEO
:
5298 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
5299 if (optval
&& optlen
== sizeof(UINT32
)) {
5300 /* WinSock passes milliseconds instead of struct timeval */
5301 tval
.tv_usec
= (*(const UINT32
*)optval
% 1000) * 1000;
5302 tval
.tv_sec
= *(const UINT32
*)optval
/ 1000;
5303 /* min of 500 milliseconds */
5304 if (tval
.tv_sec
== 0 && tval
.tv_usec
&& tval
.tv_usec
< 500000)
5305 tval
.tv_usec
= 500000;
5306 optlen
= sizeof(struct timeval
);
5307 optval
= (char*)&tval
;
5308 } else if (optlen
== sizeof(struct timeval
)) {
5309 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen
);
5311 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen
);
5314 convert_sockopt(&level
, &optname
);
5319 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname
);
5320 SetLastError(WSAENOPROTOOPT
);
5321 return SOCKET_ERROR
;
5323 break; /* case WS_SOL_SOCKET */
5326 case WS_NSPROTO_IPX
:
5330 return set_ipx_packettype(s
, *(int*)optval
);
5332 case WS_IPX_FILTERPTYPE
:
5333 /* Sets the receive filter packet type, at the moment we don't support it */
5334 FIXME("IPX_FILTERPTYPE: %x\n", *optval
);
5335 /* Returning 0 is better for now than returning a SOCKET_ERROR */
5339 FIXME("opt_name:%x\n", optname
);
5340 return SOCKET_ERROR
;
5342 break; /* case WS_NSPROTO_IPX */
5345 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
5346 case WS_IPPROTO_TCP
:
5349 case WS_TCP_NODELAY
:
5350 convert_sockopt(&level
, &optname
);
5353 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname
);
5354 return SOCKET_ERROR
;
5361 case WS_IP_ADD_MEMBERSHIP
:
5362 case WS_IP_DROP_MEMBERSHIP
:
5366 case WS_IP_MULTICAST_IF
:
5367 case WS_IP_MULTICAST_LOOP
:
5368 case WS_IP_MULTICAST_TTL
:
5375 #ifdef IP_UNICAST_IF
5376 case WS_IP_UNICAST_IF
:
5378 convert_sockopt(&level
, &optname
);
5380 case WS_IP_DONTFRAGMENT
:
5381 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
5384 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname
);
5385 return SOCKET_ERROR
;
5389 case WS_IPPROTO_IPV6
:
5392 #ifdef IPV6_ADD_MEMBERSHIP
5393 case WS_IPV6_ADD_MEMBERSHIP
:
5395 #ifdef IPV6_DROP_MEMBERSHIP
5396 case WS_IPV6_DROP_MEMBERSHIP
:
5398 case WS_IPV6_MULTICAST_IF
:
5399 case WS_IPV6_MULTICAST_HOPS
:
5400 case WS_IPV6_MULTICAST_LOOP
:
5401 case WS_IPV6_UNICAST_HOPS
:
5402 case WS_IPV6_V6ONLY
:
5403 #ifdef IPV6_UNICAST_IF
5404 case WS_IPV6_UNICAST_IF
:
5406 convert_sockopt(&level
, &optname
);
5408 case WS_IPV6_DONTFRAG
:
5409 FIXME("IPV6_DONTFRAG is silently ignored!\n");
5411 case WS_IPV6_PROTECTION_LEVEL
:
5412 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
5415 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname
);
5416 return SOCKET_ERROR
;
5421 WARN("Unknown level: 0x%08x\n", level
);
5422 SetLastError(WSAEINVAL
);
5423 return SOCKET_ERROR
;
5424 } /* end switch(level) */
5426 /* avoid endianness issues if argument is a 16-bit int */
5427 if (optval
&& optlen
< sizeof(int))
5429 woptval
= *((const INT16
*) optval
);
5430 optval
= (char*) &woptval
;
5431 woptval
&= (1 << optlen
* 8) - 1;
5434 fd
= get_sock_fd( s
, 0, NULL
);
5435 if (fd
== -1) return SOCKET_ERROR
;
5437 if (setsockopt(fd
, level
, optname
, optval
, optlen
) == 0)
5440 if (level
== SOL_SOCKET
&& optname
== SO_REUSEADDR
&&
5441 setsockopt(fd
, level
, SO_REUSEPORT
, optval
, optlen
) != 0)
5443 SetLastError(wsaErrno());
5444 release_sock_fd( s
, fd
);
5445 return SOCKET_ERROR
;
5448 release_sock_fd( s
, fd
);
5451 TRACE("Setting socket error, %d\n", wsaErrno());
5452 SetLastError(wsaErrno());
5453 release_sock_fd( s
, fd
);
5455 return SOCKET_ERROR
;
5458 /***********************************************************************
5459 * shutdown (WS2_32.22)
5461 int WINAPI
WS_shutdown(SOCKET s
, int how
)
5463 int fd
, err
= WSAENOTSOCK
;
5464 unsigned int options
= 0, clear_flags
= 0;
5466 fd
= get_sock_fd( s
, 0, &options
);
5467 TRACE("socket %04lx, how 0x%x, options 0x%x\n", s
, how
, options
);
5470 return SOCKET_ERROR
;
5474 case SD_RECEIVE
: /* drop receives */
5475 clear_flags
|= FD_READ
;
5477 case SD_SEND
: /* drop sends */
5478 clear_flags
|= FD_WRITE
;
5480 case SD_BOTH
: /* drop all */
5481 clear_flags
|= FD_READ
|FD_WRITE
;
5484 clear_flags
|= FD_WINE_LISTENING
;
5487 if (!(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
)))
5492 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_READ
);
5495 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_WRITE
);
5499 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_READ
);
5500 if (!err
) err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_WRITE
);
5503 if (err
) goto error
;
5505 else /* non-overlapped mode */
5507 if ( shutdown( fd
, how
) )
5514 release_sock_fd( s
, fd
);
5515 _enable_event( SOCKET2HANDLE(s
), 0, 0, clear_flags
);
5516 if ( how
> 1) WSAAsyncSelect( s
, 0, 0, 0 );
5520 release_sock_fd( s
, fd
);
5521 _enable_event( SOCKET2HANDLE(s
), 0, 0, clear_flags
);
5522 SetLastError( err
);
5523 return SOCKET_ERROR
;
5526 /***********************************************************************
5527 * socket (WS2_32.23)
5529 SOCKET WINAPI
WS_socket(int af
, int type
, int protocol
)
5531 TRACE("af=%d type=%d protocol=%d\n", af
, type
, protocol
);
5533 return WSASocketW( af
, type
, protocol
, NULL
, 0,
5534 get_per_thread_data()->opentype
? 0 : WSA_FLAG_OVERLAPPED
);
5538 /***********************************************************************
5539 * gethostbyaddr (WS2_32.51)
5541 struct WS_hostent
* WINAPI
WS_gethostbyaddr(const char *addr
, int len
, int type
)
5543 struct WS_hostent
*retval
= NULL
;
5544 struct hostent
* host
;
5545 int unixtype
= convert_af_w2u(type
);
5546 const char *paddr
= addr
;
5547 unsigned long loopback
;
5548 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5550 int ebufsize
= 1024;
5551 struct hostent hostentry
;
5552 int locerr
= ENOBUFS
;
5555 /* convert back the magic loopback address if necessary */
5556 if (unixtype
== AF_INET
&& len
== 4 && !memcmp(addr
, magic_loopback_addr
, 4))
5558 loopback
= htonl(INADDR_LOOPBACK
);
5559 paddr
= (char*) &loopback
;
5562 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5564 extrabuf
=HeapAlloc(GetProcessHeap(),0,ebufsize
) ;
5566 int res
= gethostbyaddr_r(paddr
, len
, unixtype
,
5567 &hostentry
, extrabuf
, ebufsize
, &host
, &locerr
);
5568 if (res
!= ERANGE
) break;
5570 extrabuf
=HeapReAlloc(GetProcessHeap(),0,extrabuf
,ebufsize
) ;
5572 if (host
) retval
= WS_dup_he(host
);
5573 else SetLastError((locerr
< 0) ? wsaErrno() : wsaHerrno(locerr
));
5574 HeapFree(GetProcessHeap(),0,extrabuf
);
5576 EnterCriticalSection( &csWSgetXXXbyYYY
);
5577 host
= gethostbyaddr(paddr
, len
, unixtype
);
5578 if (host
) retval
= WS_dup_he(host
);
5579 else SetLastError((h_errno
< 0) ? wsaErrno() : wsaHerrno(h_errno
));
5580 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5582 TRACE("ptr %p, len %d, type %d ret %p\n", addr
, len
, type
, retval
);
5586 /***********************************************************************
5587 * WS_compare_routes_by_metric_asc (INTERNAL)
5589 * Comparison function for qsort(), for sorting two routes (struct route)
5590 * by metric in ascending order.
5592 static int WS_compare_routes_by_metric_asc(const void *left
, const void *right
)
5594 return ((const struct route
*)left
)->metric
- ((const struct route
*)right
)->metric
;
5597 /***********************************************************************
5598 * WS_get_local_ips (INTERNAL)
5600 * Returns the list of local IP addresses by going through the network
5601 * adapters and using the local routing table to sort the addresses
5602 * from highest routing priority to lowest routing priority. This
5603 * functionality is inferred from the description for obtaining local
5604 * IP addresses given in the Knowledge Base Article Q160215.
5606 * Please note that the returned hostent is only freed when the thread
5607 * closes and is replaced if another hostent is requested.
5609 static struct WS_hostent
* WS_get_local_ips( char *hostname
)
5611 int numroutes
= 0, i
, j
;
5613 PIP_ADAPTER_INFO adapters
= NULL
, k
;
5614 struct WS_hostent
*hostlist
= NULL
;
5615 PMIB_IPFORWARDTABLE routes
= NULL
;
5616 struct route
*route_addrs
= NULL
;
5617 DWORD adap_size
, route_size
;
5619 /* Obtain the size of the adapter list and routing table, also allocate memory */
5620 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
5622 if (GetIpForwardTable(NULL
, &route_size
, FALSE
) != ERROR_INSUFFICIENT_BUFFER
)
5624 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
5625 routes
= HeapAlloc(GetProcessHeap(), 0, route_size
);
5626 route_addrs
= HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
5627 if (adapters
== NULL
|| routes
== NULL
|| route_addrs
== NULL
)
5629 /* Obtain the adapter list and the full routing table */
5630 if (GetAdaptersInfo(adapters
, &adap_size
) != NO_ERROR
)
5632 if (GetIpForwardTable(routes
, &route_size
, FALSE
) != NO_ERROR
)
5634 /* Store the interface associated with each route */
5635 for (n
= 0; n
< routes
->dwNumEntries
; n
++)
5639 BOOL exists
= FALSE
;
5641 if (routes
->table
[n
].u1
.ForwardType
!= MIB_IPROUTE_TYPE_DIRECT
)
5643 ifindex
= routes
->table
[n
].dwForwardIfIndex
;
5644 ifmetric
= routes
->table
[n
].dwForwardMetric1
;
5645 /* Only store the lowest valued metric for an interface */
5646 for (j
= 0; j
< numroutes
; j
++)
5648 if (route_addrs
[j
].interface
== ifindex
)
5650 if (route_addrs
[j
].metric
> ifmetric
)
5651 route_addrs
[j
].metric
= ifmetric
;
5657 route_addrs
= HeapReAlloc(GetProcessHeap(), 0, route_addrs
, (numroutes
+1)*sizeof(struct route
));
5658 if (route_addrs
== NULL
)
5659 goto cleanup
; /* Memory allocation error, fail gracefully */
5660 route_addrs
[numroutes
].interface
= ifindex
;
5661 route_addrs
[numroutes
].metric
= ifmetric
;
5662 /* If no IP is found in the next step (for whatever reason)
5663 * then fall back to the magic loopback address.
5665 memcpy(&(route_addrs
[numroutes
].addr
.s_addr
), magic_loopback_addr
, 4);
5669 goto cleanup
; /* No routes, fall back to the Magic IP */
5670 /* Find the IP address associated with each found interface */
5671 for (i
= 0; i
< numroutes
; i
++)
5673 for (k
= adapters
; k
!= NULL
; k
= k
->Next
)
5675 char *ip
= k
->IpAddressList
.IpAddress
.String
;
5677 if (route_addrs
[i
].interface
== k
->Index
)
5678 route_addrs
[i
].addr
.s_addr
= (in_addr_t
) inet_addr(ip
);
5681 /* Allocate a hostent and enough memory for all the IPs,
5682 * including the NULL at the end of the list.
5684 hostlist
= WS_create_he(hostname
, 1, 0, numroutes
+1, sizeof(struct in_addr
));
5685 if (hostlist
== NULL
)
5686 goto cleanup
; /* Failed to allocate a hostent for the list of IPs */
5687 hostlist
->h_addr_list
[numroutes
] = NULL
; /* NULL-terminate the address list */
5688 hostlist
->h_aliases
[0] = NULL
; /* NULL-terminate the alias list */
5689 hostlist
->h_addrtype
= AF_INET
;
5690 hostlist
->h_length
= sizeof(struct in_addr
); /* = 4 */
5691 /* Reorder the entries before placing them in the host list. Windows expects
5692 * the IP list in order from highest priority to lowest (the critical thing
5693 * is that most applications expect the first IP to be the default route).
5696 qsort(route_addrs
, numroutes
, sizeof(struct route
), WS_compare_routes_by_metric_asc
);
5698 for (i
= 0; i
< numroutes
; i
++)
5699 (*(struct in_addr
*) hostlist
->h_addr_list
[i
]) = route_addrs
[i
].addr
;
5701 /* Cleanup all allocated memory except the address list,
5702 * the address list is used by the calling app.
5705 HeapFree(GetProcessHeap(), 0, route_addrs
);
5706 HeapFree(GetProcessHeap(), 0, adapters
);
5707 HeapFree(GetProcessHeap(), 0, routes
);
5711 /***********************************************************************
5712 * gethostbyname (WS2_32.52)
5714 struct WS_hostent
* WINAPI
WS_gethostbyname(const char* name
)
5716 struct WS_hostent
*retval
= NULL
;
5717 struct hostent
* host
;
5718 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5721 struct hostent hostentry
;
5722 int locerr
= ENOBUFS
;
5726 SetLastError(WSANOTINITIALISED
);
5729 if( gethostname( hostname
, 100) == -1) {
5730 SetLastError(WSAENOBUFS
); /* appropriate ? */
5733 if( !name
|| !name
[0]) {
5736 /* If the hostname of the local machine is requested then return the
5737 * complete list of local IP addresses */
5738 if(strcmp(name
, hostname
) == 0)
5739 retval
= WS_get_local_ips(hostname
);
5740 /* If any other hostname was requested (or the routing table lookup failed)
5741 * then return the IP found by the host OS */
5744 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5746 extrabuf
=HeapAlloc(GetProcessHeap(),0,ebufsize
) ;
5748 int res
= gethostbyname_r(name
, &hostentry
, extrabuf
, ebufsize
, &host
, &locerr
);
5749 if( res
!= ERANGE
) break;
5751 extrabuf
=HeapReAlloc(GetProcessHeap(),0,extrabuf
,ebufsize
) ;
5753 if (!host
) SetLastError((locerr
< 0) ? wsaErrno() : wsaHerrno(locerr
));
5755 EnterCriticalSection( &csWSgetXXXbyYYY
);
5756 host
= gethostbyname(name
);
5757 if (!host
) SetLastError((h_errno
< 0) ? wsaErrno() : wsaHerrno(h_errno
));
5759 if (host
) retval
= WS_dup_he(host
);
5760 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5761 HeapFree(GetProcessHeap(),0,extrabuf
);
5763 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5766 if (retval
&& retval
->h_addr_list
[0][0] == 127 &&
5767 strcmp(name
, "localhost") != 0)
5769 /* hostname != "localhost" but has loopback address. replace by our
5770 * special address.*/
5771 memcpy(retval
->h_addr_list
[0], magic_loopback_addr
, 4);
5773 TRACE( "%s ret %p\n", debugstr_a(name
), retval
);
5778 /***********************************************************************
5779 * getprotobyname (WS2_32.53)
5781 struct WS_protoent
* WINAPI
WS_getprotobyname(const char* name
)
5783 struct WS_protoent
* retval
= NULL
;
5784 #ifdef HAVE_GETPROTOBYNAME
5785 struct protoent
* proto
;
5786 EnterCriticalSection( &csWSgetXXXbyYYY
);
5787 if( (proto
= getprotobyname(name
)) != NULL
)
5789 retval
= WS_dup_pe(proto
);
5792 MESSAGE("protocol %s not found; You might want to add "
5793 "this to /etc/protocols\n", debugstr_a(name
) );
5794 SetLastError(WSANO_DATA
);
5796 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5798 TRACE( "%s ret %p\n", debugstr_a(name
), retval
);
5803 /***********************************************************************
5804 * getprotobynumber (WS2_32.54)
5806 struct WS_protoent
* WINAPI
WS_getprotobynumber(int number
)
5808 struct WS_protoent
* retval
= NULL
;
5809 #ifdef HAVE_GETPROTOBYNUMBER
5810 struct protoent
* proto
;
5811 EnterCriticalSection( &csWSgetXXXbyYYY
);
5812 if( (proto
= getprotobynumber(number
)) != NULL
)
5814 retval
= WS_dup_pe(proto
);
5817 MESSAGE("protocol number %d not found; You might want to add "
5818 "this to /etc/protocols\n", number
);
5819 SetLastError(WSANO_DATA
);
5821 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5823 TRACE("%i ret %p\n", number
, retval
);
5828 /***********************************************************************
5829 * getservbyname (WS2_32.55)
5831 struct WS_servent
* WINAPI
WS_getservbyname(const char *name
, const char *proto
)
5833 struct WS_servent
* retval
= NULL
;
5834 struct servent
* serv
;
5836 char *proto_str
= NULL
;
5838 if (!(name_str
= strdup_lower(name
))) return NULL
;
5840 if (proto
&& *proto
)
5842 if (!(proto_str
= strdup_lower(proto
)))
5844 HeapFree( GetProcessHeap(), 0, name_str
);
5849 EnterCriticalSection( &csWSgetXXXbyYYY
);
5850 serv
= getservbyname(name_str
, proto_str
);
5853 retval
= WS_dup_se(serv
);
5855 else SetLastError(WSANO_DATA
);
5856 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5857 HeapFree( GetProcessHeap(), 0, proto_str
);
5858 HeapFree( GetProcessHeap(), 0, name_str
);
5859 TRACE( "%s, %s ret %p\n", debugstr_a(name
), debugstr_a(proto
), retval
);
5863 /***********************************************************************
5864 * freeaddrinfo (WS2_32.@)
5866 void WINAPI
WS_freeaddrinfo(struct WS_addrinfo
*res
)
5869 struct WS_addrinfo
*next
;
5871 HeapFree(GetProcessHeap(),0,res
->ai_canonname
);
5872 HeapFree(GetProcessHeap(),0,res
->ai_addr
);
5873 next
= res
->ai_next
;
5874 HeapFree(GetProcessHeap(),0,res
);
5879 /* helper functions for getaddrinfo()/getnameinfo() */
5880 static int convert_aiflag_w2u(int winflags
) {
5884 for (i
=0;i
<sizeof(ws_aiflag_map
)/sizeof(ws_aiflag_map
[0]);i
++)
5885 if (ws_aiflag_map
[i
][0] & winflags
) {
5886 unixflags
|= ws_aiflag_map
[i
][1];
5887 winflags
&= ~ws_aiflag_map
[i
][0];
5890 FIXME("Unhandled windows AI_xxx flags %x\n", winflags
);
5894 static int convert_niflag_w2u(int winflags
) {
5898 for (i
=0;i
<sizeof(ws_niflag_map
)/sizeof(ws_niflag_map
[0]);i
++)
5899 if (ws_niflag_map
[i
][0] & winflags
) {
5900 unixflags
|= ws_niflag_map
[i
][1];
5901 winflags
&= ~ws_niflag_map
[i
][0];
5904 FIXME("Unhandled windows NI_xxx flags %x\n", winflags
);
5908 static int convert_aiflag_u2w(int unixflags
) {
5912 for (i
=0;i
<sizeof(ws_aiflag_map
)/sizeof(ws_aiflag_map
[0]);i
++)
5913 if (ws_aiflag_map
[i
][1] & unixflags
) {
5914 winflags
|= ws_aiflag_map
[i
][0];
5915 unixflags
&= ~ws_aiflag_map
[i
][1];
5917 if (unixflags
) /* will warn usually */
5918 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags
);
5922 static int convert_eai_u2w(int unixret
) {
5925 if (!unixret
) return 0;
5927 for (i
=0;ws_eai_map
[i
][0];i
++)
5928 if (ws_eai_map
[i
][1] == unixret
)
5929 return ws_eai_map
[i
][0];
5931 if (unixret
== EAI_SYSTEM
)
5932 /* There are broken versions of glibc which return EAI_SYSTEM
5933 * and set errno to 0 instead of returning EAI_NONAME.
5935 return errno
? sock_get_error( errno
) : WS_EAI_NONAME
;
5937 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret
);
5941 static char *get_hostname(void)
5946 GetComputerNameExA( ComputerNamePhysicalDnsHostname
, NULL
, &size
);
5947 if (GetLastError() != ERROR_MORE_DATA
) return NULL
;
5948 if (!(ret
= HeapAlloc( GetProcessHeap(), 0, size
))) return NULL
;
5949 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname
, ret
, &size
))
5951 HeapFree( GetProcessHeap(), 0, ret
);
5957 /***********************************************************************
5958 * getaddrinfo (WS2_32.@)
5960 int WINAPI
WS_getaddrinfo(LPCSTR nodename
, LPCSTR servname
, const struct WS_addrinfo
*hints
, struct WS_addrinfo
**res
)
5962 #ifdef HAVE_GETADDRINFO
5963 struct addrinfo
*unixaires
= NULL
;
5965 struct addrinfo unixhints
, *punixhints
= NULL
;
5966 char *hostname
= NULL
;
5970 if (!nodename
&& !servname
)
5972 SetLastError(WSAHOST_NOT_FOUND
);
5973 return WSAHOST_NOT_FOUND
;
5978 else if (!nodename
[0])
5980 node
= hostname
= get_hostname();
5981 if (!node
) return WSA_NOT_ENOUGH_MEMORY
;
5986 /* servname tweak required by OSX and BSD kernels */
5987 if (servname
&& !servname
[0]) servname
= "0";
5990 punixhints
= &unixhints
;
5992 memset(&unixhints
, 0, sizeof(unixhints
));
5993 punixhints
->ai_flags
= convert_aiflag_w2u(hints
->ai_flags
);
5995 /* zero is a wildcard, no need to convert */
5996 if (hints
->ai_family
)
5997 punixhints
->ai_family
= convert_af_w2u(hints
->ai_family
);
5998 if (hints
->ai_socktype
)
5999 punixhints
->ai_socktype
= convert_socktype_w2u(hints
->ai_socktype
);
6000 if (hints
->ai_protocol
)
6001 punixhints
->ai_protocol
= max(convert_proto_w2u(hints
->ai_protocol
), 0);
6003 if (punixhints
->ai_socktype
< 0)
6005 SetLastError(WSAESOCKTNOSUPPORT
);
6006 HeapFree(GetProcessHeap(), 0, hostname
);
6007 return SOCKET_ERROR
;
6010 /* windows allows invalid combinations of socket type and protocol, unix does not.
6011 * fix the parameters here to make getaddrinfo call always work */
6012 if (punixhints
->ai_protocol
== IPPROTO_TCP
&&
6013 punixhints
->ai_socktype
!= SOCK_STREAM
&& punixhints
->ai_socktype
!= SOCK_SEQPACKET
)
6014 punixhints
->ai_socktype
= 0;
6016 else if (punixhints
->ai_protocol
== IPPROTO_UDP
&& punixhints
->ai_socktype
!= SOCK_DGRAM
)
6017 punixhints
->ai_socktype
= 0;
6019 else if (IS_IPX_PROTO(punixhints
->ai_protocol
) && punixhints
->ai_socktype
!= SOCK_DGRAM
)
6020 punixhints
->ai_socktype
= 0;
6023 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
6024 result
= getaddrinfo(node
, servname
, punixhints
, &unixaires
);
6026 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename
), debugstr_a(servname
), hints
, res
, result
);
6027 HeapFree(GetProcessHeap(), 0, hostname
);
6030 struct addrinfo
*xuai
= unixaires
;
6031 struct WS_addrinfo
**xai
= res
;
6035 struct WS_addrinfo
*ai
= HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY
, sizeof(struct WS_addrinfo
));
6041 *xai
= ai
;xai
= &ai
->ai_next
;
6042 ai
->ai_flags
= convert_aiflag_u2w(xuai
->ai_flags
);
6043 ai
->ai_family
= convert_af_u2w(xuai
->ai_family
);
6044 /* copy whatever was sent in the hints */
6046 ai
->ai_socktype
= hints
->ai_socktype
;
6047 ai
->ai_protocol
= hints
->ai_protocol
;
6049 ai
->ai_socktype
= convert_socktype_u2w(xuai
->ai_socktype
);
6050 ai
->ai_protocol
= convert_proto_u2w(xuai
->ai_protocol
);
6052 if (xuai
->ai_canonname
) {
6053 TRACE("canon name - %s\n",debugstr_a(xuai
->ai_canonname
));
6054 ai
->ai_canonname
= HeapAlloc(GetProcessHeap(),0,strlen(xuai
->ai_canonname
)+1);
6055 if (!ai
->ai_canonname
)
6057 strcpy(ai
->ai_canonname
,xuai
->ai_canonname
);
6059 len
= xuai
->ai_addrlen
;
6060 ai
->ai_addr
= HeapAlloc(GetProcessHeap(),0,len
);
6063 ai
->ai_addrlen
= len
;
6065 int winlen
= ai
->ai_addrlen
;
6067 if (!ws_sockaddr_u2ws(xuai
->ai_addr
, ai
->ai_addr
, &winlen
)) {
6068 ai
->ai_addrlen
= winlen
;
6072 ai
->ai_addr
= HeapReAlloc(GetProcessHeap(),0,ai
->ai_addr
,len
);
6075 ai
->ai_addrlen
= len
;
6077 xuai
= xuai
->ai_next
;
6079 freeaddrinfo(unixaires
);
6081 if (TRACE_ON(winsock
))
6083 struct WS_addrinfo
*ai
= *res
;
6086 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
6087 ai
, ai
->ai_flags
, ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
, ai
->ai_addrlen
,
6088 ai
->ai_canonname
, debugstr_sockaddr(ai
->ai_addr
));
6093 result
= convert_eai_u2w(result
);
6095 SetLastError(result
);
6099 if (*res
) WS_freeaddrinfo(*res
);
6100 if (unixaires
) freeaddrinfo(unixaires
);
6101 return WSA_NOT_ENOUGH_MEMORY
;
6103 FIXME("getaddrinfo() failed, not found during buildtime.\n");
6108 static struct WS_addrinfoW
*addrinfo_AtoW(const struct WS_addrinfo
*ai
)
6110 struct WS_addrinfoW
*ret
;
6112 if (!(ret
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW
)))) return NULL
;
6113 ret
->ai_flags
= ai
->ai_flags
;
6114 ret
->ai_family
= ai
->ai_family
;
6115 ret
->ai_socktype
= ai
->ai_socktype
;
6116 ret
->ai_protocol
= ai
->ai_protocol
;
6117 ret
->ai_addrlen
= ai
->ai_addrlen
;
6118 ret
->ai_canonname
= NULL
;
6119 ret
->ai_addr
= NULL
;
6120 ret
->ai_next
= NULL
;
6121 if (ai
->ai_canonname
)
6123 int len
= MultiByteToWideChar(CP_ACP
, 0, ai
->ai_canonname
, -1, NULL
, 0);
6124 if (!(ret
->ai_canonname
= HeapAlloc(GetProcessHeap(), 0, len
)))
6126 HeapFree(GetProcessHeap(), 0, ret
);
6129 MultiByteToWideChar(CP_ACP
, 0, ai
->ai_canonname
, -1, ret
->ai_canonname
, len
);
6133 if (!(ret
->ai_addr
= HeapAlloc(GetProcessHeap(), 0, ai
->ai_addrlen
)))
6135 HeapFree(GetProcessHeap(), 0, ret
->ai_canonname
);
6136 HeapFree(GetProcessHeap(), 0, ret
);
6139 memcpy(ret
->ai_addr
, ai
->ai_addr
, ai
->ai_addrlen
);
6144 static struct WS_addrinfoW
*addrinfo_list_AtoW(const struct WS_addrinfo
*info
)
6146 struct WS_addrinfoW
*ret
, *infoW
;
6148 if (!(ret
= infoW
= addrinfo_AtoW(info
))) return NULL
;
6149 while (info
->ai_next
)
6151 if (!(infoW
->ai_next
= addrinfo_AtoW(info
->ai_next
)))
6156 infoW
= infoW
->ai_next
;
6157 info
= info
->ai_next
;
6162 static struct WS_addrinfo
*addrinfo_WtoA(const struct WS_addrinfoW
*ai
)
6164 struct WS_addrinfo
*ret
;
6166 if (!(ret
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo
)))) return NULL
;
6167 ret
->ai_flags
= ai
->ai_flags
;
6168 ret
->ai_family
= ai
->ai_family
;
6169 ret
->ai_socktype
= ai
->ai_socktype
;
6170 ret
->ai_protocol
= ai
->ai_protocol
;
6171 ret
->ai_addrlen
= ai
->ai_addrlen
;
6172 ret
->ai_canonname
= NULL
;
6173 ret
->ai_addr
= NULL
;
6174 ret
->ai_next
= NULL
;
6175 if (ai
->ai_canonname
)
6177 int len
= WideCharToMultiByte(CP_ACP
, 0, ai
->ai_canonname
, -1, NULL
, 0, NULL
, NULL
);
6178 if (!(ret
->ai_canonname
= HeapAlloc(GetProcessHeap(), 0, len
)))
6180 HeapFree(GetProcessHeap(), 0, ret
);
6183 WideCharToMultiByte(CP_ACP
, 0, ai
->ai_canonname
, -1, ret
->ai_canonname
, len
, NULL
, NULL
);
6187 if (!(ret
->ai_addr
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr
))))
6189 HeapFree(GetProcessHeap(), 0, ret
->ai_canonname
);
6190 HeapFree(GetProcessHeap(), 0, ret
);
6193 memcpy(ret
->ai_addr
, ai
->ai_addr
, sizeof(struct WS_sockaddr
));
6198 /***********************************************************************
6199 * GetAddrInfoW (WS2_32.@)
6201 int WINAPI
GetAddrInfoW(LPCWSTR nodename
, LPCWSTR servname
, const ADDRINFOW
*hints
, PADDRINFOW
*res
)
6204 char *nodenameA
= NULL
, *servnameA
= NULL
;
6205 struct WS_addrinfo
*resA
, *hintsA
= NULL
;
6210 len
= WideCharToMultiByte(CP_ACP
, 0, nodename
, -1, NULL
, 0, NULL
, NULL
);
6211 if (!(nodenameA
= HeapAlloc(GetProcessHeap(), 0, len
))) return EAI_MEMORY
;
6212 WideCharToMultiByte(CP_ACP
, 0, nodename
, -1, nodenameA
, len
, NULL
, NULL
);
6216 len
= WideCharToMultiByte(CP_ACP
, 0, servname
, -1, NULL
, 0, NULL
, NULL
);
6217 if (!(servnameA
= HeapAlloc(GetProcessHeap(), 0, len
)))
6219 HeapFree(GetProcessHeap(), 0, nodenameA
);
6222 WideCharToMultiByte(CP_ACP
, 0, servname
, -1, servnameA
, len
, NULL
, NULL
);
6225 if (hints
) hintsA
= addrinfo_WtoA(hints
);
6226 ret
= WS_getaddrinfo(nodenameA
, servnameA
, hintsA
, &resA
);
6227 WS_freeaddrinfo(hintsA
);
6231 *res
= addrinfo_list_AtoW(resA
);
6232 WS_freeaddrinfo(resA
);
6235 HeapFree(GetProcessHeap(), 0, nodenameA
);
6236 HeapFree(GetProcessHeap(), 0, servnameA
);
6240 /***********************************************************************
6241 * FreeAddrInfoW (WS2_32.@)
6243 void WINAPI
FreeAddrInfoW(PADDRINFOW ai
)
6248 HeapFree(GetProcessHeap(), 0, ai
->ai_canonname
);
6249 HeapFree(GetProcessHeap(), 0, ai
->ai_addr
);
6251 HeapFree(GetProcessHeap(), 0, ai
);
6256 int WINAPI
WS_getnameinfo(const SOCKADDR
*sa
, WS_socklen_t salen
, PCHAR host
,
6257 DWORD hostlen
, PCHAR serv
, DWORD servlen
, INT flags
)
6259 #ifdef HAVE_GETNAMEINFO
6261 union generic_unix_sockaddr sa_u
;
6264 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa
), salen
, host
, hostlen
,
6265 serv
, servlen
, flags
);
6267 size
= ws_sockaddr_ws2u(sa
, salen
, &sa_u
);
6270 SetLastError(WSAEFAULT
);
6271 return WSA_NOT_ENOUGH_MEMORY
;
6273 ret
= getnameinfo(&sa_u
.addr
, size
, host
, hostlen
, serv
, servlen
, convert_niflag_w2u(flags
));
6274 return convert_eai_u2w(ret
);
6276 FIXME("getnameinfo() failed, not found during buildtime.\n");
6281 int WINAPI
GetNameInfoW(const SOCKADDR
*sa
, WS_socklen_t salen
, PWCHAR host
,
6282 DWORD hostlen
, PWCHAR serv
, DWORD servlen
, INT flags
)
6285 char *hostA
= NULL
, *servA
= NULL
;
6287 if (host
&& (!(hostA
= HeapAlloc(GetProcessHeap(), 0, hostlen
)))) return EAI_MEMORY
;
6288 if (serv
&& (!(servA
= HeapAlloc(GetProcessHeap(), 0, servlen
))))
6290 HeapFree(GetProcessHeap(), 0, hostA
);
6294 ret
= WS_getnameinfo(sa
, salen
, hostA
, hostlen
, servA
, servlen
, flags
);
6297 if (host
) MultiByteToWideChar(CP_ACP
, 0, hostA
, -1, host
, hostlen
);
6298 if (serv
) MultiByteToWideChar(CP_ACP
, 0, servA
, -1, serv
, servlen
);
6301 HeapFree(GetProcessHeap(), 0, hostA
);
6302 HeapFree(GetProcessHeap(), 0, servA
);
6306 /***********************************************************************
6307 * getservbyport (WS2_32.56)
6309 struct WS_servent
* WINAPI
WS_getservbyport(int port
, const char *proto
)
6311 struct WS_servent
* retval
= NULL
;
6312 #ifdef HAVE_GETSERVBYPORT
6313 struct servent
* serv
;
6314 char *proto_str
= NULL
;
6316 if (proto
&& *proto
)
6318 if (!(proto_str
= strdup_lower(proto
))) return NULL
;
6320 EnterCriticalSection( &csWSgetXXXbyYYY
);
6321 if( (serv
= getservbyport(port
, proto_str
)) != NULL
) {
6322 retval
= WS_dup_se(serv
);
6324 else SetLastError(WSANO_DATA
);
6325 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6326 HeapFree( GetProcessHeap(), 0, proto_str
);
6328 TRACE("%d (i.e. port %d), %s ret %p\n", port
, (int)ntohl(port
), debugstr_a(proto
), retval
);
6333 /***********************************************************************
6334 * gethostname (WS2_32.57)
6336 int WINAPI
WS_gethostname(char *name
, int namelen
)
6341 TRACE("name %p, len %d\n", name
, namelen
);
6345 SetLastError(WSAEFAULT
);
6346 return SOCKET_ERROR
;
6349 if (gethostname(buf
, sizeof(buf
)) != 0)
6351 SetLastError(wsaErrno());
6352 return SOCKET_ERROR
;
6355 TRACE("<- '%s'\n", buf
);
6358 WARN("Windows supports NetBIOS name length up to 15 bytes!\n");
6361 SetLastError(WSAEFAULT
);
6362 WARN("<- not enough space for hostname, required %d, got %d!\n", len
+ 1, namelen
);
6363 return SOCKET_ERROR
;
6370 /* ------------------------------------- Windows sockets extensions -- *
6372 * ------------------------------------------------------------------- */
6374 /***********************************************************************
6375 * WSAEnumNetworkEvents (WS2_32.36)
6377 int WINAPI
WSAEnumNetworkEvents(SOCKET s
, WSAEVENT hEvent
, LPWSANETWORKEVENTS lpEvent
)
6381 int errors
[FD_MAX_EVENTS
];
6383 TRACE("%04lx, hEvent %p, lpEvent %p\n", s
, hEvent
, lpEvent
);
6385 SERVER_START_REQ( get_socket_event
)
6387 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
6388 req
->service
= TRUE
;
6389 req
->c_event
= wine_server_obj_handle( hEvent
);
6390 wine_server_set_reply( req
, errors
, sizeof(errors
) );
6391 if (!(ret
= wine_server_call(req
))) lpEvent
->lNetworkEvents
= reply
->pmask
& reply
->mask
;
6396 for (i
= 0; i
< FD_MAX_EVENTS
; i
++)
6397 lpEvent
->iErrorCode
[i
] = NtStatusToWSAError(errors
[i
]);
6400 SetLastError(WSAEINVAL
);
6401 return SOCKET_ERROR
;
6404 /***********************************************************************
6405 * WSAEventSelect (WS2_32.39)
6407 int WINAPI
WSAEventSelect(SOCKET s
, WSAEVENT hEvent
, LONG lEvent
)
6411 TRACE("%04lx, hEvent %p, event %08x\n", s
, hEvent
, lEvent
);
6413 SERVER_START_REQ( set_socket_event
)
6415 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
6417 req
->event
= wine_server_obj_handle( hEvent
);
6420 ret
= wine_server_call( req
);
6424 SetLastError(WSAEINVAL
);
6425 return SOCKET_ERROR
;
6428 /**********************************************************************
6429 * WSAGetOverlappedResult (WS2_32.40)
6431 BOOL WINAPI
WSAGetOverlappedResult( SOCKET s
, LPWSAOVERLAPPED lpOverlapped
,
6432 LPDWORD lpcbTransfer
, BOOL fWait
,
6437 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
6438 s
, lpOverlapped
, lpcbTransfer
, fWait
, lpdwFlags
);
6440 if ( lpOverlapped
== NULL
)
6442 ERR( "Invalid pointer\n" );
6443 SetLastError(WSA_INVALID_PARAMETER
);
6447 status
= lpOverlapped
->Internal
;
6448 if (status
== STATUS_PENDING
)
6452 SetLastError( WSA_IO_INCOMPLETE
);
6456 if (WaitForSingleObject( lpOverlapped
->hEvent
? lpOverlapped
->hEvent
: SOCKET2HANDLE(s
),
6457 INFINITE
) == WAIT_FAILED
)
6459 status
= lpOverlapped
->Internal
;
6463 *lpcbTransfer
= lpOverlapped
->InternalHigh
;
6466 *lpdwFlags
= lpOverlapped
->u
.s
.Offset
;
6468 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
6473 /***********************************************************************
6474 * WSAAsyncSelect (WS2_32.101)
6476 INT WINAPI
WSAAsyncSelect(SOCKET s
, HWND hWnd
, UINT uMsg
, LONG lEvent
)
6480 TRACE("%04lx, hWnd %p, uMsg %08x, event %08x\n", s
, hWnd
, uMsg
, lEvent
);
6482 SERVER_START_REQ( set_socket_event
)
6484 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
6487 req
->window
= wine_server_user_handle( hWnd
);
6489 ret
= wine_server_call( req
);
6493 SetLastError(WSAEINVAL
);
6494 return SOCKET_ERROR
;
6497 /***********************************************************************
6498 * WSACreateEvent (WS2_32.31)
6501 WSAEVENT WINAPI
WSACreateEvent(void)
6503 /* Create a manual-reset event, with initial state: unsignaled */
6506 return CreateEventW(NULL
, TRUE
, FALSE
, NULL
);
6509 /***********************************************************************
6510 * WSACloseEvent (WS2_32.29)
6513 BOOL WINAPI
WSACloseEvent(WSAEVENT event
)
6515 TRACE ("event=%p\n", event
);
6517 return CloseHandle(event
);
6520 /***********************************************************************
6521 * WSASocketA (WS2_32.78)
6524 SOCKET WINAPI
WSASocketA(int af
, int type
, int protocol
,
6525 LPWSAPROTOCOL_INFOA lpProtocolInfo
,
6526 GROUP g
, DWORD dwFlags
)
6529 WSAPROTOCOL_INFOW info
;
6531 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6532 af
, type
, protocol
, lpProtocolInfo
, g
, dwFlags
);
6534 if (!lpProtocolInfo
) return WSASocketW(af
, type
, protocol
, NULL
, g
, dwFlags
);
6536 memcpy(&info
, lpProtocolInfo
, FIELD_OFFSET(WSAPROTOCOL_INFOW
, szProtocol
));
6537 len
= MultiByteToWideChar(CP_ACP
, 0, lpProtocolInfo
->szProtocol
, -1,
6538 info
.szProtocol
, WSAPROTOCOL_LEN
+ 1);
6542 SetLastError(WSAEINVAL
);
6543 return SOCKET_ERROR
;
6546 return WSASocketW(af
, type
, protocol
, &info
, g
, dwFlags
);
6549 /***********************************************************************
6550 * WSASocketW (WS2_32.79)
6553 SOCKET WINAPI
WSASocketW(int af
, int type
, int protocol
,
6554 LPWSAPROTOCOL_INFOW lpProtocolInfo
,
6555 GROUP g
, DWORD dwFlags
)
6559 int unixaf
, unixtype
, ipxptype
= -1;
6562 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
6563 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
6566 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6567 af
, type
, protocol
, lpProtocolInfo
, g
, dwFlags
);
6571 err
= WSANOTINITIALISED
;
6575 /* hack for WSADuplicateSocket */
6576 if (lpProtocolInfo
&& lpProtocolInfo
->dwServiceFlags4
== 0xff00ff00) {
6577 ret
= lpProtocolInfo
->dwServiceFlags3
;
6578 TRACE("\tgot duplicate %04lx\n", ret
);
6584 if (af
== FROM_PROTOCOL_INFO
|| !af
)
6585 af
= lpProtocolInfo
->iAddressFamily
;
6586 if (type
== FROM_PROTOCOL_INFO
|| !type
)
6587 type
= lpProtocolInfo
->iSocketType
;
6588 if (protocol
== FROM_PROTOCOL_INFO
|| !protocol
)
6589 protocol
= lpProtocolInfo
->iProtocol
;
6592 if (!type
&& (af
|| protocol
))
6594 int autoproto
= protocol
;
6595 WSAPROTOCOL_INFOW infow
;
6597 /* default to the first valid protocol */
6599 autoproto
= valid_protocols
[0];
6600 else if(IS_IPX_PROTO(autoproto
))
6601 autoproto
= WS_NSPROTO_IPX
;
6603 if (WS_EnterSingleProtocolW(autoproto
, &infow
))
6605 type
= infow
.iSocketType
;
6607 /* after win2003 it's no longer possible to pass AF_UNSPEC
6608 using the protocol info struct */
6609 if (!lpProtocolInfo
&& af
== WS_AF_UNSPEC
)
6610 af
= infow
.iAddressFamily
;
6615 Windows has an extension to the IPX protocol that allows one to create sockets
6616 and set the IPX packet type at the same time, to do that a caller will use
6617 a protocol like NSPROTO_IPX + <PACKET TYPE>
6619 if (IS_IPX_PROTO(protocol
))
6620 ipxptype
= protocol
- WS_NSPROTO_IPX
;
6622 /* convert the socket family, type and protocol */
6623 unixaf
= convert_af_w2u(af
);
6624 unixtype
= convert_socktype_w2u(type
);
6625 protocol
= convert_proto_w2u(protocol
);
6626 if (unixaf
== AF_UNSPEC
) unixaf
= -1;
6628 /* filter invalid parameters */
6631 /* the type could not be converted */
6632 if (type
&& unixtype
< 0)
6634 err
= WSAESOCKTNOSUPPORT
;
6638 err
= WSAEPROTONOSUPPORT
;
6643 /* both family and protocol can't be invalid */
6650 /* family could not be converted and neither socket type */
6651 if (unixtype
< 0 && af
>= 0)
6654 err
= WSAESOCKTNOSUPPORT
;
6658 err
= WSAEAFNOSUPPORT
;
6662 SERVER_START_REQ( create_socket
)
6664 req
->family
= unixaf
;
6665 req
->type
= unixtype
;
6666 req
->protocol
= protocol
;
6667 req
->access
= GENERIC_READ
|GENERIC_WRITE
|SYNCHRONIZE
;
6668 req
->attributes
= (dwFlags
& WSA_FLAG_NO_HANDLE_INHERIT
) ? 0 : OBJ_INHERIT
;
6669 req
->flags
= dwFlags
& ~WSA_FLAG_NO_HANDLE_INHERIT
;
6670 set_error( wine_server_call( req
) );
6671 ret
= HANDLE2SOCKET( wine_server_ptr_handle( reply
->handle
));
6676 TRACE("\tcreated %04lx\n", ret
);
6678 set_ipx_packettype(ret
, ipxptype
);
6682 err
= GetLastError();
6683 if (err
== WSAEACCES
) /* raw socket denied */
6685 if (type
== SOCK_RAW
)
6686 ERR_(winediag
)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
6688 ERR_(winediag
)("Failed to create socket, this requires special permissions.\n");
6692 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
6693 if (err
== WSAEINVAL
)
6694 err
= WSAESOCKTNOSUPPORT
;
6695 else if (err
== WSAEOPNOTSUPP
)
6696 err
= WSAEPROTONOSUPPORT
;
6700 WARN("\t\tfailed, error %d!\n", err
);
6702 return INVALID_SOCKET
;
6705 /***********************************************************************
6706 * WSAJoinLeaf (WS2_32.58)
6709 SOCKET WINAPI
WSAJoinLeaf(
6711 const struct WS_sockaddr
*addr
,
6713 LPWSABUF lpCallerData
,
6714 LPWSABUF lpCalleeData
,
6720 return INVALID_SOCKET
;
6723 /***********************************************************************
6724 * __WSAFDIsSet (WS2_32.151)
6726 int WINAPI
__WSAFDIsSet(SOCKET s
, WS_fd_set
*set
)
6728 int i
= set
->fd_count
, ret
= 0;
6731 if (set
->fd_array
[i
] == s
)
6737 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s
, set
, set
->fd_count
, ret
);
6741 /***********************************************************************
6742 * WSAIsBlocking (WS2_32.114)
6744 BOOL WINAPI
WSAIsBlocking(void)
6746 /* By default WinSock should set all its sockets to non-blocking mode
6747 * and poll in PeekMessage loop when processing "blocking" ones. This
6748 * function is supposed to tell if the program is in this loop. Our
6749 * blocking calls are truly blocking so we always return FALSE.
6751 * Note: It is allowed to call this function without prior WSAStartup().
6758 /***********************************************************************
6759 * WSACancelBlockingCall (WS2_32.113)
6761 INT WINAPI
WSACancelBlockingCall(void)
6767 static INT WINAPI
WSA_DefaultBlockingHook( FARPROC x
)
6769 FIXME("How was this called?\n");
6774 /***********************************************************************
6775 * WSASetBlockingHook (WS2_32.109)
6777 FARPROC WINAPI
WSASetBlockingHook(FARPROC lpBlockFunc
)
6779 FARPROC prev
= blocking_hook
;
6780 blocking_hook
= lpBlockFunc
;
6781 TRACE("hook %p\n", lpBlockFunc
);
6786 /***********************************************************************
6787 * WSAUnhookBlockingHook (WS2_32.110)
6789 INT WINAPI
WSAUnhookBlockingHook(void)
6791 blocking_hook
= (FARPROC
)WSA_DefaultBlockingHook
;
6796 /* ----------------------------------- end of API stuff */
6798 /* ----------------------------------- helper functions -
6800 * TODO: Merge WS_dup_..() stuff into one function that
6801 * would operate with a generic structure containing internal
6802 * pointers (via a template of some kind).
6805 static int list_size(char** l
, int item_size
)
6810 j
+= (item_size
) ? item_size
: strlen(l
[i
]) + 1;
6811 j
+= (i
+ 1) * sizeof(char*); }
6815 static int list_dup(char** l_src
, char** l_to
, int item_size
)
6820 for (i
= 0; l_src
[i
]; i
++) ;
6821 p
= (char *)(l_to
+ i
+ 1);
6822 for (i
= 0; l_src
[i
]; i
++)
6824 int count
= ( item_size
) ? item_size
: strlen(l_src
[i
]) + 1;
6825 memcpy(p
, l_src
[i
], count
);
6830 return p
- (char *)l_to
;
6835 /* create a hostent entry
6837 * Creates the entry with enough memory for the name, aliases
6838 * addresses, and the address pointers. Also copies the name
6839 * and sets up all the pointers.
6841 * NOTE: The alias and address lists must be allocated with room
6842 * for the NULL item terminating the list. This is true even if
6843 * the list has no items ("aliases" and "addresses" must be
6844 * at least "1", a truly empty list is invalid).
6846 static struct WS_hostent
*WS_create_he(char *name
, int aliases
, int aliases_size
, int addresses
, int address_length
)
6848 struct WS_hostent
*p_to
;
6850 int size
= (sizeof(struct WS_hostent
) +
6852 sizeof(char *) * aliases
+
6854 sizeof(char *) * addresses
+
6855 address_length
* (addresses
- 1)), i
;
6857 if (!(p_to
= check_buffer_he(size
))) return NULL
;
6858 memset(p_to
, 0, size
);
6860 /* Use the memory in the same way winsock does.
6861 * First set the pointer for aliases, second set the pointers for addresses.
6862 * Third fill the addresses indexes, fourth jump aliases names size.
6863 * Fifth fill the hostname.
6864 * NOTE: This method is valid for OS version's >= XP.
6866 p
= (char *)(p_to
+ 1);
6867 p_to
->h_aliases
= (char **)p
;
6868 p
+= sizeof(char *)*aliases
;
6870 p_to
->h_addr_list
= (char **)p
;
6871 p
+= sizeof(char *)*addresses
;
6873 for (i
= 0, addresses
--; i
< addresses
; i
++, p
+= address_length
)
6874 p_to
->h_addr_list
[i
] = p
;
6876 /* NOTE: h_aliases must be filled in manually because we don't know each string
6877 * size, leave these pointers NULL (already set to NULL by memset earlier).
6887 /* duplicate hostent entry
6888 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
6889 * Ditto for protoent and servent.
6891 static struct WS_hostent
*WS_dup_he(const struct hostent
* p_he
)
6893 int i
, addresses
= 0, alias_size
= 0;
6894 struct WS_hostent
*p_to
;
6897 for( i
= 0; p_he
->h_aliases
[i
]; i
++) alias_size
+= strlen(p_he
->h_aliases
[i
]) + 1;
6898 while (p_he
->h_addr_list
[addresses
]) addresses
++;
6900 p_to
= WS_create_he(p_he
->h_name
, i
+ 1, alias_size
, addresses
+ 1, p_he
->h_length
);
6902 if (!p_to
) return NULL
;
6903 p_to
->h_addrtype
= convert_af_u2w(p_he
->h_addrtype
);
6904 p_to
->h_length
= p_he
->h_length
;
6906 for(i
= 0, p
= p_to
->h_addr_list
[0]; p_he
->h_addr_list
[i
]; i
++, p
+= p_to
->h_length
)
6907 memcpy(p
, p_he
->h_addr_list
[i
], p_to
->h_length
);
6909 /* Fill the aliases after the IP data */
6910 for(i
= 0; p_he
->h_aliases
[i
]; i
++)
6912 p_to
->h_aliases
[i
] = p
;
6913 strcpy(p
, p_he
->h_aliases
[i
]);
6920 /* ----- protoent */
6922 static struct WS_protoent
*WS_dup_pe(const struct protoent
* p_pe
)
6925 struct WS_protoent
*p_to
;
6927 int size
= (sizeof(*p_pe
) +
6928 strlen(p_pe
->p_name
) + 1 +
6929 list_size(p_pe
->p_aliases
, 0));
6931 if (!(p_to
= check_buffer_pe(size
))) return NULL
;
6932 p_to
->p_proto
= p_pe
->p_proto
;
6934 p
= (char *)(p_to
+ 1);
6936 strcpy(p
, p_pe
->p_name
);
6939 p_to
->p_aliases
= (char **)p
;
6940 list_dup(p_pe
->p_aliases
, p_to
->p_aliases
, 0);
6946 static struct WS_servent
*WS_dup_se(const struct servent
* p_se
)
6949 struct WS_servent
*p_to
;
6951 int size
= (sizeof(*p_se
) +
6952 strlen(p_se
->s_proto
) + 1 +
6953 strlen(p_se
->s_name
) + 1 +
6954 list_size(p_se
->s_aliases
, 0));
6956 if (!(p_to
= check_buffer_se(size
))) return NULL
;
6957 p_to
->s_port
= p_se
->s_port
;
6959 p
= (char *)(p_to
+ 1);
6961 strcpy(p
, p_se
->s_name
);
6965 strcpy(p
, p_se
->s_proto
);
6968 p_to
->s_aliases
= (char **)p
;
6969 list_dup(p_se
->s_aliases
, p_to
->s_aliases
, 0);
6974 /***********************************************************************
6975 * WSARecv (WS2_32.67)
6977 int WINAPI
WSARecv(SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
6978 LPDWORD NumberOfBytesReceived
, LPDWORD lpFlags
,
6979 LPWSAOVERLAPPED lpOverlapped
,
6980 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
6982 return WS2_recv_base(s
, lpBuffers
, dwBufferCount
, NumberOfBytesReceived
, lpFlags
,
6983 NULL
, NULL
, lpOverlapped
, lpCompletionRoutine
, NULL
);
6986 static int WS2_recv_base( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
6987 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
,
6988 struct WS_sockaddr
*lpFrom
,
6989 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
6990 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
,
6991 LPWSABUF lpControlBuffer
)
6993 unsigned int i
, options
;
6994 int n
, fd
, err
, overlapped
, flags
;
6995 struct ws2_async
*wsa
= NULL
, localwsa
;
6997 DWORD timeout_start
= GetTickCount();
6998 ULONG_PTR cvalue
= (lpOverlapped
&& ((ULONG_PTR
)lpOverlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)lpOverlapped
: 0;
7000 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
7001 s
, lpBuffers
, dwBufferCount
, *lpFlags
, lpFrom
,
7002 (lpFromlen
? *lpFromlen
: -1),
7003 lpOverlapped
, lpCompletionRoutine
);
7005 fd
= get_sock_fd( s
, FILE_READ_DATA
, &options
);
7006 TRACE( "fd=%d, options=%x\n", fd
, options
);
7008 if (fd
== -1) return SOCKET_ERROR
;
7010 if (*lpFlags
& WS_MSG_OOB
)
7012 /* It's invalid to receive OOB data from an OOBINLINED socket
7013 * as OOB data is turned into normal data. */
7015 if (!getsockopt(fd
, SOL_SOCKET
, SO_OOBINLINE
, (char*) &n
, &i
) && n
)
7022 overlapped
= (lpOverlapped
|| lpCompletionRoutine
) &&
7023 !(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
));
7024 if (overlapped
|| dwBufferCount
> 1)
7026 if (!(wsa
= (struct ws2_async
*)alloc_async_io( offsetof(struct ws2_async
, iovec
[dwBufferCount
]))))
7035 wsa
->hSocket
= SOCKET2HANDLE(s
);
7036 wsa
->flags
= *lpFlags
;
7037 wsa
->lpFlags
= lpFlags
;
7039 wsa
->addrlen
.ptr
= lpFromlen
;
7040 wsa
->control
= lpControlBuffer
;
7041 wsa
->n_iovecs
= dwBufferCount
;
7042 wsa
->first_iovec
= 0;
7043 for (i
= 0; i
< dwBufferCount
; i
++)
7045 /* check buffer first to trigger write watches */
7046 if (IsBadWritePtr( lpBuffers
[i
].buf
, lpBuffers
[i
].len
))
7051 wsa
->iovec
[i
].iov_base
= lpBuffers
[i
].buf
;
7052 wsa
->iovec
[i
].iov_len
= lpBuffers
[i
].len
;
7055 flags
= convert_flags(wsa
->flags
);
7058 n
= WS2_recv( fd
, wsa
, flags
);
7061 /* Unix-like systems return EINVAL when attempting to read OOB data from
7062 * an empty socket buffer, convert that to a Windows expected return. */
7063 if ((flags
& MSG_OOB
) && errno
== EINVAL
)
7064 errno
= EWOULDBLOCK
;
7066 if (errno
!= EAGAIN
)
7068 int loc_errno
= errno
;
7070 if (cvalue
) WS_AddCompletion( s
, cvalue
, sock_get_ntstatus(loc_errno
), 0 );
7074 else if (lpNumberOfBytesRecvd
) *lpNumberOfBytesRecvd
= n
;
7078 IO_STATUS_BLOCK
*iosb
= lpOverlapped
? (IO_STATUS_BLOCK
*)lpOverlapped
: &wsa
->local_iosb
;
7080 wsa
->user_overlapped
= lpOverlapped
;
7081 wsa
->completion_func
= lpCompletionRoutine
;
7082 release_sock_fd( s
, fd
);
7086 iosb
->u
.Status
= STATUS_PENDING
;
7087 iosb
->Information
= 0;
7089 SERVER_START_REQ( register_async
)
7091 req
->type
= ASYNC_TYPE_READ
;
7092 req
->async
.handle
= wine_server_obj_handle( wsa
->hSocket
);
7093 req
->async
.callback
= wine_server_client_ptr( WS2_async_recv
);
7094 req
->async
.iosb
= wine_server_client_ptr( iosb
);
7095 req
->async
.arg
= wine_server_client_ptr( wsa
);
7096 req
->async
.event
= wine_server_obj_handle( lpCompletionRoutine
? 0 : lpOverlapped
->hEvent
);
7097 req
->async
.cvalue
= cvalue
;
7098 err
= wine_server_call( req
);
7102 if (err
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
7103 SetLastError(NtStatusToWSAError( err
));
7104 return SOCKET_ERROR
;
7107 iosb
->u
.Status
= STATUS_SUCCESS
;
7108 iosb
->Information
= n
;
7109 if (!wsa
->completion_func
)
7111 if (cvalue
) WS_AddCompletion( s
, cvalue
, STATUS_SUCCESS
, n
);
7112 if (lpOverlapped
->hEvent
) SetEvent( lpOverlapped
->hEvent
);
7113 HeapFree( GetProcessHeap(), 0, wsa
);
7115 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC
)ws2_async_apc
,
7116 (ULONG_PTR
)wsa
, (ULONG_PTR
)iosb
, 0 );
7117 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7123 if ((err
= _is_blocking( s
, &is_blocking
)))
7125 err
= NtStatusToWSAError( err
);
7132 int timeout
= GET_RCVTIMEO(fd
);
7135 timeout
-= GetTickCount() - timeout_start
;
7136 if (timeout
< 0) timeout
= 0;
7140 pfd
.events
= POLLIN
;
7141 if (*lpFlags
& WS_MSG_OOB
) pfd
.events
|= POLLPRI
;
7143 if (!timeout
|| !poll( &pfd
, 1, timeout
))
7146 /* a timeout is not fatal */
7147 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7153 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7154 err
= WSAEWOULDBLOCK
;
7159 TRACE(" -> %i bytes\n", n
);
7160 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
7161 release_sock_fd( s
, fd
);
7162 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7163 SetLastError(ERROR_SUCCESS
);
7168 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
7169 release_sock_fd( s
, fd
);
7170 WARN(" -> ERROR %d\n", err
);
7171 SetLastError( err
);
7172 return SOCKET_ERROR
;
7175 /***********************************************************************
7176 * WSARecvFrom (WS2_32.69)
7178 INT WINAPI
WSARecvFrom( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
7179 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
, struct WS_sockaddr
*lpFrom
,
7180 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
7181 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
7184 return WS2_recv_base( s
, lpBuffers
, dwBufferCount
,
7185 lpNumberOfBytesRecvd
, lpFlags
,
7187 lpOverlapped
, lpCompletionRoutine
, NULL
);
7190 /***********************************************************************
7191 * WSCInstallProvider (WS2_32.88)
7193 INT WINAPI
WSCInstallProvider( const LPGUID lpProviderId
,
7194 LPCWSTR lpszProviderDllPath
,
7195 const LPWSAPROTOCOL_INFOW lpProtocolInfoList
,
7196 DWORD dwNumberOfEntries
,
7199 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId
),
7200 debugstr_w(lpszProviderDllPath
), lpProtocolInfoList
,
7201 dwNumberOfEntries
, lpErrno
);
7207 /***********************************************************************
7208 * WSCDeinstallProvider (WS2_32.83)
7210 INT WINAPI
WSCDeinstallProvider(LPGUID lpProviderId
, LPINT lpErrno
)
7212 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId
), lpErrno
);
7218 /***********************************************************************
7219 * WSAAccept (WS2_32.26)
7221 SOCKET WINAPI
WSAAccept( SOCKET s
, struct WS_sockaddr
*addr
, LPINT addrlen
,
7222 LPCONDITIONPROC lpfnCondition
, DWORD_PTR dwCallbackData
)
7226 WSABUF CallerId
, CallerData
, CalleeId
, CalleeData
;
7227 /* QOS SQOS, GQOS; */
7230 SOCKADDR src_addr
, dst_addr
;
7232 TRACE("socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
7233 s
, addr
, addrlen
, lpfnCondition
, dwCallbackData
);
7235 cs
= WS_accept(s
, addr
, addrlen
);
7236 if (cs
== SOCKET_ERROR
) return SOCKET_ERROR
;
7237 if (!lpfnCondition
) return cs
;
7239 if (addr
&& addrlen
)
7241 CallerId
.buf
= (char *)addr
;
7242 CallerId
.len
= *addrlen
;
7246 size
= sizeof(src_addr
);
7247 WS_getpeername(cs
, &src_addr
, &size
);
7248 CallerId
.buf
= (char *)&src_addr
;
7249 CallerId
.len
= size
;
7251 CallerData
.buf
= NULL
;
7254 size
= sizeof(dst_addr
);
7255 WS_getsockname(cs
, &dst_addr
, &size
);
7257 CalleeId
.buf
= (char *)&dst_addr
;
7258 CalleeId
.len
= sizeof(dst_addr
);
7260 ret
= (*lpfnCondition
)(&CallerId
, &CallerData
, NULL
, NULL
,
7261 &CalleeId
, &CalleeData
, &g
, dwCallbackData
);
7268 SERVER_START_REQ( set_socket_deferred
)
7270 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
7271 req
->deferred
= wine_server_obj_handle( SOCKET2HANDLE(cs
) );
7272 if ( !wine_server_call_err ( req
) )
7274 SetLastError( WSATRY_AGAIN
);
7275 WS_closesocket( cs
);
7279 return SOCKET_ERROR
;
7282 SetLastError(WSAECONNREFUSED
);
7283 return SOCKET_ERROR
;
7285 FIXME("Unknown return type from Condition function\n");
7286 SetLastError(WSAENOTSOCK
);
7287 return SOCKET_ERROR
;
7291 /***********************************************************************
7292 * WSADuplicateSocketA (WS2_32.32)
7294 int WINAPI
WSADuplicateSocketA( SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOA lpProtocolInfo
)
7296 return WS_DuplicateSocket(FALSE
, s
, dwProcessId
, (LPWSAPROTOCOL_INFOW
) lpProtocolInfo
);
7299 /***********************************************************************
7300 * WSADuplicateSocketW (WS2_32.33)
7302 int WINAPI
WSADuplicateSocketW( SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOW lpProtocolInfo
)
7304 return WS_DuplicateSocket(TRUE
, s
, dwProcessId
, lpProtocolInfo
);
7307 /***********************************************************************
7308 * WSAInstallServiceClassA (WS2_32.48)
7310 int WINAPI
WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info
)
7312 FIXME("Request to install service %s\n",debugstr_a(info
->lpszServiceClassName
));
7313 SetLastError(WSAEACCES
);
7314 return SOCKET_ERROR
;
7317 /***********************************************************************
7318 * WSAInstallServiceClassW (WS2_32.49)
7320 int WINAPI
WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info
)
7322 FIXME("Request to install service %s\n",debugstr_w(info
->lpszServiceClassName
));
7323 SetLastError(WSAEACCES
);
7324 return SOCKET_ERROR
;
7327 /***********************************************************************
7328 * WSARemoveServiceClass (WS2_32.70)
7330 int WINAPI
WSARemoveServiceClass(LPGUID info
)
7332 FIXME("Request to remove service %p\n",info
);
7333 SetLastError(WSATYPE_NOT_FOUND
);
7334 return SOCKET_ERROR
;
7337 /***********************************************************************
7338 * inet_ntop (WS2_32.@)
7340 PCSTR WINAPI
WS_inet_ntop( INT family
, PVOID addr
, PSTR buffer
, SIZE_T len
)
7342 #ifdef HAVE_INET_NTOP
7343 struct WS_in6_addr
*in6
;
7344 struct WS_in_addr
*in
;
7347 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family
, addr
, buffer
, len
);
7350 SetLastError( STATUS_INVALID_PARAMETER
);
7359 pdst
= inet_ntop( AF_INET
, &in
->WS_s_addr
, buffer
, len
);
7365 pdst
= inet_ntop( AF_INET6
, in6
->WS_s6_addr
, buffer
, len
);
7369 SetLastError( WSAEAFNOSUPPORT
);
7373 if (!pdst
) SetLastError( STATUS_INVALID_PARAMETER
);
7376 FIXME( "not supported on this platform\n" );
7377 SetLastError( WSAEAFNOSUPPORT
);
7382 /***********************************************************************
7383 * inet_pton (WS2_32.@)
7385 INT WINAPI
WS_inet_pton( INT family
, PCSTR addr
, PVOID buffer
)
7387 #ifdef HAVE_INET_PTON
7390 TRACE("family %d, addr '%s', buffer (%p)\n", family
, addr
? addr
: "(null)", buffer
);
7392 if (!addr
|| !buffer
)
7394 SetLastError(WSAEFAULT
);
7395 return SOCKET_ERROR
;
7398 unixaf
= convert_af_w2u(family
);
7399 if (unixaf
!= AF_INET
&& unixaf
!= AF_INET6
)
7401 SetLastError(WSAEAFNOSUPPORT
);
7402 return SOCKET_ERROR
;
7405 ret
= inet_pton(unixaf
, addr
, buffer
);
7406 if (ret
== -1) SetLastError(wsaErrno());
7409 FIXME( "not supported on this platform\n" );
7410 SetLastError( WSAEAFNOSUPPORT
);
7411 return SOCKET_ERROR
;
7416 /***********************************************************************
7417 * WSAStringToAddressA (WS2_32.80)
7419 INT WINAPI
WSAStringToAddressA(LPSTR AddressString
,
7421 LPWSAPROTOCOL_INFOA lpProtocolInfo
,
7422 LPSOCKADDR lpAddress
,
7423 LPINT lpAddressLength
)
7426 LPSTR workBuffer
=NULL
,ptrPort
;
7428 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString
), AddressFamily
,
7429 lpProtocolInfo
, lpAddress
, lpAddressLength
);
7431 if (!lpAddressLength
|| !lpAddress
) return SOCKET_ERROR
;
7435 SetLastError(WSAEINVAL
);
7436 return SOCKET_ERROR
;
7440 FIXME("ProtocolInfo not implemented.\n");
7442 workBuffer
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
,
7443 strlen(AddressString
) + 1);
7446 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
7447 return SOCKET_ERROR
;
7450 strcpy(workBuffer
, AddressString
);
7452 switch(AddressFamily
)
7456 struct in_addr inetaddr
;
7458 /* If lpAddressLength is too small, tell caller the size we need */
7459 if (*lpAddressLength
< sizeof(SOCKADDR_IN
))
7461 *lpAddressLength
= sizeof(SOCKADDR_IN
);
7465 *lpAddressLength
= sizeof(SOCKADDR_IN
);
7466 memset(lpAddress
, 0, sizeof(SOCKADDR_IN
));
7468 ((LPSOCKADDR_IN
)lpAddress
)->sin_family
= WS_AF_INET
;
7470 ptrPort
= strchr(workBuffer
, ':');
7473 /* User may have entered an IPv6 and asked to parse as IPv4 */
7474 if(strchr(ptrPort
+ 1, ':'))
7479 ((LPSOCKADDR_IN
)lpAddress
)->sin_port
= htons(atoi(ptrPort
+1));
7484 ((LPSOCKADDR_IN
)lpAddress
)->sin_port
= 0;
7487 if(inet_aton(workBuffer
, &inetaddr
) > 0)
7489 ((LPSOCKADDR_IN
)lpAddress
)->sin_addr
.WS_s_addr
= inetaddr
.s_addr
;
7500 struct in6_addr inetaddr
;
7501 /* If lpAddressLength is too small, tell caller the size we need */
7502 if (*lpAddressLength
< sizeof(SOCKADDR_IN6
))
7504 *lpAddressLength
= sizeof(SOCKADDR_IN6
);
7508 #ifdef HAVE_INET_PTON
7509 *lpAddressLength
= sizeof(SOCKADDR_IN6
);
7510 memset(lpAddress
, 0, sizeof(SOCKADDR_IN6
));
7512 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_family
= WS_AF_INET6
;
7514 /* This one is a bit tricky. An IPv6 address contains colons, so the
7515 * check from IPv4 doesn't work like that. However, IPv6 addresses that
7516 * contain a port are written with braces like [fd12:3456:7890::1]:12345
7517 * so what we will do is to look for ']', check if the next char is a
7518 * colon, and if it is, parse the port as in IPv4. */
7520 ptrPort
= strchr(workBuffer
, ']');
7521 if(ptrPort
&& *(++ptrPort
) == ':')
7523 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_port
= htons(atoi(ptrPort
+1));
7528 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_port
= 0;
7531 if(inet_pton(AF_INET6
, workBuffer
, &inetaddr
) > 0)
7533 memcpy(&((LPSOCKADDR_IN6
)lpAddress
)->sin6_addr
, &inetaddr
,
7534 sizeof(struct in6_addr
));
7538 #endif /* HAVE_INET_PTON */
7544 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
7545 TRACE("Unsupported address family specified: %d.\n", AddressFamily
);
7549 HeapFree(GetProcessHeap(), 0, workBuffer
);
7553 return SOCKET_ERROR
;
7556 /***********************************************************************
7557 * WSAStringToAddressW (WS2_32.81)
7559 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
7560 * If this should be the case, it would be required to map these digits
7561 * to Unicode digits (0-9) using FoldString first.
7563 INT WINAPI
WSAStringToAddressW(LPWSTR AddressString
,
7565 LPWSAPROTOCOL_INFOW lpProtocolInfo
,
7566 LPSOCKADDR lpAddress
,
7567 LPINT lpAddressLength
)
7570 LPSTR workBuffer
=NULL
;
7571 WSAPROTOCOL_INFOA infoA
;
7572 LPWSAPROTOCOL_INFOA lpProtoInfoA
= NULL
;
7574 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString
), AddressFamily
, lpProtocolInfo
,
7575 lpAddress
, lpAddressLength
);
7577 if (!lpAddressLength
|| !lpAddress
) return SOCKET_ERROR
;
7579 /* if ProtocolInfo is available - convert to ANSI variant */
7582 lpProtoInfoA
= &infoA
;
7583 memcpy( lpProtoInfoA
, lpProtocolInfo
, FIELD_OFFSET( WSAPROTOCOL_INFOA
, szProtocol
) );
7585 if (!WideCharToMultiByte( CP_ACP
, 0, lpProtocolInfo
->szProtocol
, -1,
7586 lpProtoInfoA
->szProtocol
, WSAPROTOCOL_LEN
+1, NULL
, NULL
))
7588 SetLastError(WSAEINVAL
);
7589 return SOCKET_ERROR
;
7595 /* Translate AddressString to ANSI code page - assumes that only
7596 standard digits 0-9 are used with this API call */
7597 sBuffer
= WideCharToMultiByte( CP_ACP
, 0, AddressString
, -1, NULL
, 0, NULL
, NULL
);
7598 workBuffer
= HeapAlloc( GetProcessHeap(), 0, sBuffer
);
7602 WideCharToMultiByte( CP_ACP
, 0, AddressString
, -1, workBuffer
, sBuffer
, NULL
, NULL
);
7603 res
= WSAStringToAddressA(workBuffer
,AddressFamily
,lpProtoInfoA
,
7604 lpAddress
,lpAddressLength
);
7605 HeapFree( GetProcessHeap(), 0, workBuffer
);
7609 res
= WSA_NOT_ENOUGH_MEMORY
;
7615 return SOCKET_ERROR
;
7618 /***********************************************************************
7619 * WSAAddressToStringA (WS2_32.27)
7621 * See WSAAddressToStringW
7623 INT WINAPI
WSAAddressToStringA( LPSOCKADDR sockaddr
, DWORD len
,
7624 LPWSAPROTOCOL_INFOA info
, LPSTR string
,
7628 CHAR buffer
[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7631 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr
, len
, info
, string
, lenstr
);
7633 if (!sockaddr
) return SOCKET_ERROR
;
7634 if (!string
|| !lenstr
) return SOCKET_ERROR
;
7636 switch(sockaddr
->sa_family
)
7639 if (len
< sizeof(SOCKADDR_IN
)) return SOCKET_ERROR
;
7640 sprintf( buffer
, "%u.%u.%u.%u:%u",
7641 (unsigned int)(ntohl( ((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
) >> 24 & 0xff),
7642 (unsigned int)(ntohl( ((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
) >> 16 & 0xff),
7643 (unsigned int)(ntohl( ((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
) >> 8 & 0xff),
7644 (unsigned int)(ntohl( ((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
) & 0xff),
7645 ntohs( ((SOCKADDR_IN
*)sockaddr
)->sin_port
) );
7647 p
= strchr( buffer
, ':' );
7648 if (!((SOCKADDR_IN
*)sockaddr
)->sin_port
) *p
= 0;
7653 struct WS_sockaddr_in6
*sockaddr6
= (LPSOCKADDR_IN6
) sockaddr
;
7656 if (len
< sizeof(SOCKADDR_IN6
)) return SOCKET_ERROR
;
7657 if ((sockaddr6
->sin6_port
))
7658 strcpy(buffer
, "[");
7659 if (!WS_inet_ntop(WS_AF_INET6
, &sockaddr6
->sin6_addr
, buffer
+strlen(buffer
), sizeof(buffer
)))
7661 SetLastError(WSAEINVAL
);
7662 return SOCKET_ERROR
;
7664 if ((sockaddr6
->sin6_scope_id
))
7665 sprintf(buffer
+strlen(buffer
), "%%%u", sockaddr6
->sin6_scope_id
);
7666 if ((sockaddr6
->sin6_port
))
7667 sprintf(buffer
+strlen(buffer
), "]:%u", ntohs(sockaddr6
->sin6_port
));
7672 SetLastError(WSAEINVAL
);
7673 return SOCKET_ERROR
;
7676 size
= strlen( buffer
) + 1;
7681 SetLastError(WSAEFAULT
);
7682 return SOCKET_ERROR
;
7685 TRACE("=> %s,%u bytes\n", debugstr_a(buffer
), size
);
7687 strcpy( string
, buffer
);
7691 /***********************************************************************
7692 * WSAAddressToStringW (WS2_32.28)
7694 * Convert a sockaddr address into a readable address string.
7697 * sockaddr [I] Pointer to a sockaddr structure.
7698 * len [I] Size of the sockaddr structure.
7699 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
7700 * string [I/O] Pointer to a buffer to receive the address string.
7701 * lenstr [I/O] Size of the receive buffer in WCHARs.
7705 * Failure: SOCKET_ERROR
7708 * The 'info' parameter is ignored.
7710 INT WINAPI
WSAAddressToStringW( LPSOCKADDR sockaddr
, DWORD len
,
7711 LPWSAPROTOCOL_INFOW info
, LPWSTR string
,
7716 WCHAR buffer
[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7719 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr
, len
, info
, string
, lenstr
);
7722 ret
= WSAAddressToStringA(sockaddr
, len
, NULL
, bufAddr
, &size
);
7724 if (ret
) return ret
;
7726 MultiByteToWideChar( CP_ACP
, 0, bufAddr
, size
, buffer
, sizeof( buffer
)/sizeof(WCHAR
));
7731 SetLastError(WSAEFAULT
);
7732 return SOCKET_ERROR
;
7735 TRACE("=> %s,%u bytes\n", debugstr_w(buffer
), size
);
7737 lstrcpyW( string
, buffer
);
7741 /***********************************************************************
7742 * WSAEnumNameSpaceProvidersA (WS2_32.34)
7744 INT WINAPI
WSAEnumNameSpaceProvidersA( LPDWORD len
, LPWSANAMESPACE_INFOA buffer
)
7746 FIXME( "(%p %p) Stub!\n", len
, buffer
);
7750 /***********************************************************************
7751 * WSAEnumNameSpaceProvidersW (WS2_32.35)
7753 INT WINAPI
WSAEnumNameSpaceProvidersW( LPDWORD len
, LPWSANAMESPACE_INFOW buffer
)
7755 FIXME( "(%p %p) Stub!\n", len
, buffer
);
7759 /***********************************************************************
7760 * WSAGetQOSByName (WS2_32.41)
7762 BOOL WINAPI
WSAGetQOSByName( SOCKET s
, LPWSABUF lpQOSName
, LPQOS lpQOS
)
7764 FIXME( "(0x%04lx %p %p) Stub!\n", s
, lpQOSName
, lpQOS
);
7768 /***********************************************************************
7769 * WSAGetServiceClassInfoA (WS2_32.42)
7771 INT WINAPI
WSAGetServiceClassInfoA( LPGUID provider
, LPGUID service
, LPDWORD len
,
7772 LPWSASERVICECLASSINFOA info
)
7774 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider
), debugstr_guid(service
),
7776 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
7777 return SOCKET_ERROR
;
7780 /***********************************************************************
7781 * WSAGetServiceClassInfoW (WS2_32.43)
7783 INT WINAPI
WSAGetServiceClassInfoW( LPGUID provider
, LPGUID service
, LPDWORD len
,
7784 LPWSASERVICECLASSINFOW info
)
7786 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider
), debugstr_guid(service
),
7788 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
7789 return SOCKET_ERROR
;
7792 /***********************************************************************
7793 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
7795 INT WINAPI
WSAGetServiceClassNameByClassIdA( LPGUID
class, LPSTR service
, LPDWORD len
)
7797 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service
, len
);
7798 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
7799 return SOCKET_ERROR
;
7802 /***********************************************************************
7803 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
7805 INT WINAPI
WSAGetServiceClassNameByClassIdW( LPGUID
class, LPWSTR service
, LPDWORD len
)
7807 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service
, len
);
7808 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
7809 return SOCKET_ERROR
;
7812 /***********************************************************************
7813 * WSALookupServiceBeginA (WS2_32.59)
7815 INT WINAPI
WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions
,
7816 DWORD dwControlFlags
,
7819 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions
, dwControlFlags
,
7821 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
7822 return SOCKET_ERROR
;
7825 /***********************************************************************
7826 * WSALookupServiceBeginW (WS2_32.60)
7828 INT WINAPI
WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions
,
7829 DWORD dwControlFlags
,
7832 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions
, dwControlFlags
,
7834 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
7835 return SOCKET_ERROR
;
7838 /***********************************************************************
7839 * WSALookupServiceEnd (WS2_32.61)
7841 INT WINAPI
WSALookupServiceEnd( HANDLE lookup
)
7843 FIXME("(%p) Stub!\n", lookup
);
7847 /***********************************************************************
7848 * WSALookupServiceNextA (WS2_32.62)
7850 INT WINAPI
WSALookupServiceNextA( HANDLE lookup
, DWORD flags
, LPDWORD len
, LPWSAQUERYSETA results
)
7852 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup
, flags
, len
, results
);
7853 SetLastError(WSA_E_NO_MORE
);
7854 return SOCKET_ERROR
;
7857 /***********************************************************************
7858 * WSALookupServiceNextW (WS2_32.63)
7860 INT WINAPI
WSALookupServiceNextW( HANDLE lookup
, DWORD flags
, LPDWORD len
, LPWSAQUERYSETW results
)
7862 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup
, flags
, len
, results
);
7863 SetLastError(WSA_E_NO_MORE
);
7864 return SOCKET_ERROR
;
7867 /***********************************************************************
7868 * WSANtohl (WS2_32.64)
7870 INT WINAPI
WSANtohl( SOCKET s
, WS_u_long netlong
, WS_u_long
* lphostlong
)
7872 TRACE( "(%04lx 0x%08x %p)\n", s
, netlong
, lphostlong
);
7874 if (!lphostlong
) return WSAEFAULT
;
7876 *lphostlong
= ntohl( netlong
);
7880 /***********************************************************************
7881 * WSANtohs (WS2_32.65)
7883 INT WINAPI
WSANtohs( SOCKET s
, WS_u_short netshort
, WS_u_short
* lphostshort
)
7885 TRACE( "(%04lx 0x%08x %p)\n", s
, netshort
, lphostshort
);
7887 if (!lphostshort
) return WSAEFAULT
;
7889 *lphostshort
= ntohs( netshort
);
7893 /***********************************************************************
7894 * WSAProviderConfigChange (WS2_32.66)
7896 INT WINAPI
WSAProviderConfigChange( LPHANDLE handle
, LPWSAOVERLAPPED overlapped
,
7897 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
7899 FIXME( "(%p %p %p) Stub!\n", handle
, overlapped
, completion
);
7900 return SOCKET_ERROR
;
7903 /***********************************************************************
7904 * WSARecvDisconnect (WS2_32.68)
7906 INT WINAPI
WSARecvDisconnect( SOCKET s
, LPWSABUF disconnectdata
)
7908 TRACE( "(%04lx %p)\n", s
, disconnectdata
);
7910 return WS_shutdown( s
, SD_RECEIVE
);
7913 /***********************************************************************
7914 * WSASetServiceA (WS2_32.76)
7916 INT WINAPI
WSASetServiceA( LPWSAQUERYSETA query
, WSAESETSERVICEOP operation
, DWORD flags
)
7918 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query
, operation
, flags
);
7922 /***********************************************************************
7923 * WSASetServiceW (WS2_32.77)
7925 INT WINAPI
WSASetServiceW( LPWSAQUERYSETW query
, WSAESETSERVICEOP operation
, DWORD flags
)
7927 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query
, operation
, flags
);
7931 /***********************************************************************
7932 * WSCEnableNSProvider (WS2_32.84)
7934 INT WINAPI
WSCEnableNSProvider( LPGUID provider
, BOOL enable
)
7936 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider
), enable
);
7940 /***********************************************************************
7941 * WSCGetProviderPath (WS2_32.86)
7943 INT WINAPI
WSCGetProviderPath( LPGUID provider
, LPWSTR path
, LPINT len
, LPINT errcode
)
7945 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider
), path
, len
, errcode
);
7947 if (!errcode
|| !provider
|| !len
) return WSAEFAULT
;
7949 *errcode
= WSAEINVAL
;
7950 return SOCKET_ERROR
;
7953 /***********************************************************************
7954 * WSCInstallNameSpace (WS2_32.87)
7956 INT WINAPI
WSCInstallNameSpace( LPWSTR identifier
, LPWSTR path
, DWORD
namespace,
7957 DWORD version
, LPGUID provider
)
7959 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier
), debugstr_w(path
),
7960 namespace, version
, debugstr_guid(provider
) );
7964 /***********************************************************************
7965 * WSCUnInstallNameSpace (WS2_32.89)
7967 INT WINAPI
WSCUnInstallNameSpace( LPGUID lpProviderId
)
7969 FIXME("(%p) Stub!\n", lpProviderId
);
7973 /***********************************************************************
7974 * WSCWriteProviderOrder (WS2_32.91)
7976 INT WINAPI
WSCWriteProviderOrder( LPDWORD entry
, DWORD number
)
7978 FIXME("(%p 0x%08x) Stub!\n", entry
, number
);
7982 /***********************************************************************
7983 * WSANSPIoctl (WS2_32.91)
7985 INT WINAPI
WSANSPIoctl( HANDLE hLookup
, DWORD dwControlCode
, LPVOID lpvInBuffer
,
7986 DWORD cbInBuffer
, LPVOID lpvOutBuffer
, DWORD cbOutBuffer
,
7987 LPDWORD lpcbBytesReturned
, LPWSACOMPLETION lpCompletion
)
7989 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup
, dwControlCode
,
7990 lpvInBuffer
, cbInBuffer
, lpvOutBuffer
, cbOutBuffer
, lpcbBytesReturned
, lpCompletion
);
7991 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
7992 return SOCKET_ERROR
;
7995 /*****************************************************************************
7996 * WSAEnumProtocolsA [WS2_32.@]
7998 * see function WSAEnumProtocolsW
8000 INT WINAPI
WSAEnumProtocolsA( LPINT protocols
, LPWSAPROTOCOL_INFOA buffer
, LPDWORD len
)
8002 return WS_EnumProtocols( FALSE
, protocols
, (LPWSAPROTOCOL_INFOW
) buffer
, len
);
8005 /*****************************************************************************
8006 * WSAEnumProtocolsW [WS2_32.@]
8008 * Retrieves information about specified set of active network protocols.
8011 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
8012 * retrieves information on all available protocols.
8013 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
8015 * len [I/O] Pointer to a variable specifying buffer size. On output
8016 * the variable holds the number of bytes needed when the
8017 * specified size is too small.
8020 * Success: number of WSAPROTOCOL_INFO structures in buffer.
8021 * Failure: SOCKET_ERROR
8024 * NT4SP5 does not return SPX if protocols == NULL
8027 * - NT4SP5 returns in addition these list of NETBIOS protocols
8028 * (address family 17), each entry two times one for socket type 2 and 5
8030 * iProtocol szProtocol
8031 * 0x80000000 \Device\NwlnkNb
8032 * 0xfffffffa \Device\NetBT_CBENT7
8033 * 0xfffffffb \Device\Nbf_CBENT7
8034 * 0xfffffffc \Device\NetBT_NdisWan5
8035 * 0xfffffffd \Device\NetBT_El9202
8036 * 0xfffffffe \Device\Nbf_El9202
8037 * 0xffffffff \Device\Nbf_NdisWan4
8039 * - there is no check that the operating system supports the returned
8042 INT WINAPI
WSAEnumProtocolsW( LPINT protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
)
8044 return WS_EnumProtocols( TRUE
, protocols
, buffer
, len
);
8047 /*****************************************************************************
8048 * WSCEnumProtocols [WS2_32.@]
8051 * protocols [I] Null-terminated array of iProtocol values.
8052 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
8053 * len [I/O] Size of buffer on input/output.
8054 * errno [O] Error code.
8057 * Success: number of protocols to be reported on.
8058 * Failure: SOCKET_ERROR. error is in errno.
8061 * Doesn't supply info on layered protocols.
8064 INT WINAPI
WSCEnumProtocols( LPINT protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
, LPINT err
)
8066 INT ret
= WSAEnumProtocolsW( protocols
, buffer
, len
);
8068 if (ret
== SOCKET_ERROR
) *err
= WSAENOBUFS
;