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>
40 #ifdef HAVE_SYS_IOCTL_H
41 # include <sys/ioctl.h>
43 #ifdef HAVE_SYS_FILIO_H
44 # include <sys/filio.h>
46 #ifdef HAVE_SYS_SOCKIO_H
47 # include <sys/sockio.h>
51 # include <sys/so_ioctl.h>
54 #ifdef HAVE_SYS_PARAM_H
55 # include <sys/param.h>
61 #ifdef HAVE_SYS_WAIT_H
62 # include <sys/wait.h>
67 #ifdef HAVE_SYS_SOCKET_H
68 #include <sys/socket.h>
70 #ifdef HAVE_NETINET_IN_H
71 # include <netinet/in.h>
73 #ifdef HAVE_NETINET_TCP_H
74 # include <netinet/tcp.h>
76 #ifdef HAVE_ARPA_INET_H
77 # include <arpa/inet.h>
89 #ifdef HAVE_ARPA_NAMESER_H
90 # include <arpa/nameser.h>
98 #ifdef HAVE_LINUX_FILTER_H
99 # include <linux/filter.h>
102 #ifdef HAVE_NETIPX_IPX_H
103 # include <netipx/ipx.h>
104 #elif defined(HAVE_LINUX_IPX_H)
105 # ifdef HAVE_ASM_TYPES_H
106 # include <asm/types.h>
108 # ifdef HAVE_LINUX_TYPES_H
109 # include <linux/types.h>
111 # include <linux/ipx.h>
113 #if defined(SOL_IPX) || defined(SO_DEFAULT_HEADERS)
117 #ifdef HAVE_LINUX_IRDA_H
118 # ifdef HAVE_LINUX_TYPES_H
119 # include <linux/types.h>
121 # include <linux/irda.h>
128 #ifdef HAVE_SYS_POLL_H
129 # include <sys/poll.h>
131 #ifdef HAVE_SYS_TIME_H
132 # include <sys/time.h>
135 #define NONAMELESSUNION
136 #define NONAMELESSSTRUCT
137 #include "ntstatus.h"
138 #define WIN32_NO_STATUS
143 #include "winerror.h"
145 #include "winsock2.h"
147 #include "ws2tcpip.h"
150 #include "wsnwlink.h"
151 #include "wshisotp.h"
155 #define USE_WC_PREFIX /* For CMSG_DATA */
156 #include "iphlpapi.h"
157 #include "wine/server.h"
158 #include "wine/debug.h"
159 #include "wine/exception.h"
160 #include "wine/unicode.h"
162 #if defined(linux) && !defined(IP_UNICAST_IF)
163 #define IP_UNICAST_IF 50
166 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
167 # define sipx_network sipx_addr.x_net
168 # define sipx_node sipx_addr.x_host.c_host
169 #endif /* __FreeBSD__ */
172 #define INADDR_NONE ~0UL
175 #if !defined(TCP_KEEPIDLE) && defined(TCP_KEEPALIVE)
176 /* TCP_KEEPALIVE is the Mac OS name for TCP_KEEPIDLE */
177 #define TCP_KEEPIDLE TCP_KEEPALIVE
180 WINE_DEFAULT_DEBUG_CHANNEL(winsock
);
181 WINE_DECLARE_DEBUG_CHANNEL(winediag
);
183 /* names of the protocols */
184 static const WCHAR NameIpxW
[] = {'I', 'P', 'X', '\0'};
185 static const WCHAR NameSpxW
[] = {'S', 'P', 'X', '\0'};
186 static const WCHAR NameSpxIIW
[] = {'S', 'P', 'X', ' ', 'I', 'I', '\0'};
187 static const WCHAR NameTcpW
[] = {'T', 'C', 'P', '/', 'I', 'P', '\0'};
188 static const WCHAR NameUdpW
[] = {'U', 'D', 'P', '/', 'I', 'P', '\0'};
190 /* Taken from Win2k */
191 static const GUID ProviderIdIP
= { 0xe70f1aa0, 0xab8b, 0x11cf,
192 { 0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
193 static const GUID ProviderIdIPX
= { 0x11058240, 0xbe47, 0x11cf,
194 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
195 static const GUID ProviderIdSPX
= { 0x11058241, 0xbe47, 0x11cf,
196 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
198 static const INT valid_protocols
[] =
208 #define IS_IPX_PROTO(X) ((X) >= WS_NSPROTO_IPX && (X) <= WS_NSPROTO_IPX + 255)
210 #if defined(IP_UNICAST_IF) && defined(SO_ATTACH_FILTER)
211 # define LINUX_BOUND_IF
212 struct interface_filter
{
213 struct sock_filter iface_memaddr
;
214 struct sock_filter iface_rule
;
215 struct sock_filter ip_memaddr
;
216 struct sock_filter ip_rule
;
217 struct sock_filter return_keep
;
218 struct sock_filter return_dump
;
220 # define FILTER_JUMP_DUMP(here) (u_char)(offsetof(struct interface_filter, return_dump) \
221 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
222 /sizeof(struct sock_filter)
223 # define FILTER_JUMP_KEEP(here) (u_char)(offsetof(struct interface_filter, return_keep) \
224 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
225 /sizeof(struct sock_filter)
226 # define FILTER_JUMP_NEXT() (u_char)(0)
227 # define SKF_NET_DESTIP 16 /* offset in the network header to the destination IP */
228 static struct interface_filter generic_interface_filter
= {
229 /* This filter rule allows incoming packets on the specified interface, which works for all
230 * remotely generated packets and for locally generated broadcast packets. */
231 BPF_STMT(BPF_LD
+BPF_W
+BPF_ABS
, SKF_AD_OFF
+SKF_AD_IFINDEX
),
232 BPF_JUMP(BPF_JMP
+BPF_JEQ
+BPF_K
, 0xdeadbeef, FILTER_JUMP_KEEP(iface_rule
), FILTER_JUMP_NEXT()),
233 /* This rule allows locally generated packets targeted at the specific IP address of the chosen
234 * adapter (local packets not destined for the broadcast address do not have IFINDEX set) */
235 BPF_STMT(BPF_LD
+BPF_W
+BPF_ABS
, SKF_NET_OFF
+SKF_NET_DESTIP
),
236 BPF_JUMP(BPF_JMP
+BPF_JEQ
+BPF_K
, 0xdeadbeef, FILTER_JUMP_KEEP(ip_rule
), FILTER_JUMP_DUMP(ip_rule
)),
237 BPF_STMT(BPF_RET
+BPF_K
, (u_int
)-1), /* keep packet */
238 BPF_STMT(BPF_RET
+BPF_K
, 0) /* dump packet */
240 #endif /* LINUX_BOUND_IF */
243 * The actual definition of WSASendTo, wrapped in a different function name
244 * so that internal calls from ws2_32 itself will not trigger programs like
245 * Garena, which hooks WSASendTo/WSARecvFrom calls.
247 static int WS2_sendto( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
248 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
249 const struct WS_sockaddr
*to
, int tolen
,
250 LPWSAOVERLAPPED lpOverlapped
,
251 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);
254 * Internal fundamental receive function, essentially WSARecvFrom with an
255 * additional parameter to support message control headers.
257 static int WS2_recv_base( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
258 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
,
259 struct WS_sockaddr
*lpFrom
,
260 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
261 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
,
262 LPWSABUF lpControlBuffer
);
264 /* critical section to protect some non-reentrant net function */
265 static CRITICAL_SECTION csWSgetXXXbyYYY
;
266 static CRITICAL_SECTION_DEBUG critsect_debug
=
268 0, 0, &csWSgetXXXbyYYY
,
269 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
270 0, 0, { (DWORD_PTR
)(__FILE__
": csWSgetXXXbyYYY") }
272 static CRITICAL_SECTION csWSgetXXXbyYYY
= { &critsect_debug
, -1, 0, 0, 0, 0 };
274 union generic_unix_sockaddr
276 struct sockaddr addr
;
277 char data
[128]; /* should be big enough for all families */
280 static inline const char *debugstr_sockaddr( const struct WS_sockaddr
*a
)
282 if (!a
) return "(nil)";
283 switch (a
->sa_family
)
289 struct WS_sockaddr_in
*sin
= (struct WS_sockaddr_in
*)a
;
291 p
= WS_inet_ntop( WS_AF_INET
, &sin
->sin_addr
, buf
, sizeof(buf
) );
293 p
= "(unknown IPv4 address)";
295 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
296 p
, ntohs(sin
->sin_port
));
302 struct WS_sockaddr_in6
*sin
= (struct WS_sockaddr_in6
*)a
;
304 p
= WS_inet_ntop( WS_AF_INET6
, &sin
->sin6_addr
, buf
, sizeof(buf
) );
306 p
= "(unknown IPv6 address)";
307 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
308 p
, ntohs(sin
->sin6_port
));
313 char netnum
[16], nodenum
[16];
314 struct WS_sockaddr_ipx
*sin
= (struct WS_sockaddr_ipx
*)a
;
316 for (i
= 0;i
< 4; i
++) sprintf(netnum
+ i
* 2, "%02X", (unsigned char) sin
->sa_netnum
[i
]);
317 for (i
= 0;i
< 6; i
++) sprintf(nodenum
+ i
* 2, "%02X", (unsigned char) sin
->sa_nodenum
[i
]);
319 return wine_dbg_sprintf("{ family AF_IPX, address %s.%s, ipx socket %d }",
320 netnum
, nodenum
, sin
->sa_socket
);
326 memcpy( &addr
, ((const SOCKADDR_IRDA
*)a
)->irdaDeviceID
, sizeof(addr
) );
327 addr
= ntohl( addr
);
328 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
330 ((const SOCKADDR_IRDA
*)a
)->irdaServiceName
);
333 return wine_dbg_sprintf("{ family %d }", a
->sa_family
);
337 static inline const char *debugstr_sockopt(int level
, int optname
)
339 const char *stropt
= NULL
, *strlevel
= NULL
;
341 #define DEBUG_SOCKLEVEL(x) case (x): strlevel = #x
342 #define DEBUG_SOCKOPT(x) case (x): stropt = #x; break
346 DEBUG_SOCKLEVEL(WS_SOL_SOCKET
);
349 DEBUG_SOCKOPT(WS_SO_ACCEPTCONN
);
350 DEBUG_SOCKOPT(WS_SO_BROADCAST
);
351 DEBUG_SOCKOPT(WS_SO_BSP_STATE
);
352 DEBUG_SOCKOPT(WS_SO_CONDITIONAL_ACCEPT
);
353 DEBUG_SOCKOPT(WS_SO_CONNECT_TIME
);
354 DEBUG_SOCKOPT(WS_SO_DEBUG
);
355 DEBUG_SOCKOPT(WS_SO_DONTLINGER
);
356 DEBUG_SOCKOPT(WS_SO_DONTROUTE
);
357 DEBUG_SOCKOPT(WS_SO_ERROR
);
358 DEBUG_SOCKOPT(WS_SO_EXCLUSIVEADDRUSE
);
359 DEBUG_SOCKOPT(WS_SO_GROUP_ID
);
360 DEBUG_SOCKOPT(WS_SO_GROUP_PRIORITY
);
361 DEBUG_SOCKOPT(WS_SO_KEEPALIVE
);
362 DEBUG_SOCKOPT(WS_SO_LINGER
);
363 DEBUG_SOCKOPT(WS_SO_MAX_MSG_SIZE
);
364 DEBUG_SOCKOPT(WS_SO_OOBINLINE
);
365 DEBUG_SOCKOPT(WS_SO_OPENTYPE
);
366 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOA
);
367 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOW
);
368 DEBUG_SOCKOPT(WS_SO_RCVBUF
);
369 DEBUG_SOCKOPT(WS_SO_RCVTIMEO
);
370 DEBUG_SOCKOPT(WS_SO_REUSEADDR
);
371 DEBUG_SOCKOPT(WS_SO_SNDBUF
);
372 DEBUG_SOCKOPT(WS_SO_SNDTIMEO
);
373 DEBUG_SOCKOPT(WS_SO_TYPE
);
377 DEBUG_SOCKLEVEL(WS_NSPROTO_IPX
);
380 DEBUG_SOCKOPT(WS_IPX_PTYPE
);
381 DEBUG_SOCKOPT(WS_IPX_FILTERPTYPE
);
382 DEBUG_SOCKOPT(WS_IPX_DSTYPE
);
383 DEBUG_SOCKOPT(WS_IPX_RECVHDR
);
384 DEBUG_SOCKOPT(WS_IPX_MAXSIZE
);
385 DEBUG_SOCKOPT(WS_IPX_ADDRESS
);
386 DEBUG_SOCKOPT(WS_IPX_MAX_ADAPTER_NUM
);
390 DEBUG_SOCKLEVEL(WS_SOL_IRLMP
);
393 DEBUG_SOCKOPT(WS_IRLMP_ENUMDEVICES
);
397 DEBUG_SOCKLEVEL(WS_IPPROTO_TCP
);
400 DEBUG_SOCKOPT(WS_TCP_BSDURGENT
);
401 DEBUG_SOCKOPT(WS_TCP_EXPEDITED_1122
);
402 DEBUG_SOCKOPT(WS_TCP_NODELAY
);
406 DEBUG_SOCKLEVEL(WS_IPPROTO_IP
);
409 DEBUG_SOCKOPT(WS_IP_ADD_MEMBERSHIP
);
410 DEBUG_SOCKOPT(WS_IP_DROP_MEMBERSHIP
);
411 DEBUG_SOCKOPT(WS_IP_HDRINCL
);
412 DEBUG_SOCKOPT(WS_IP_MULTICAST_IF
);
413 DEBUG_SOCKOPT(WS_IP_MULTICAST_LOOP
);
414 DEBUG_SOCKOPT(WS_IP_MULTICAST_TTL
);
415 DEBUG_SOCKOPT(WS_IP_OPTIONS
);
416 DEBUG_SOCKOPT(WS_IP_PKTINFO
);
417 DEBUG_SOCKOPT(WS_IP_TOS
);
418 DEBUG_SOCKOPT(WS_IP_TTL
);
419 DEBUG_SOCKOPT(WS_IP_UNICAST_IF
);
420 DEBUG_SOCKOPT(WS_IP_DONTFRAGMENT
);
424 DEBUG_SOCKLEVEL(WS_IPPROTO_IPV6
);
427 DEBUG_SOCKOPT(WS_IPV6_ADD_MEMBERSHIP
);
428 DEBUG_SOCKOPT(WS_IPV6_DROP_MEMBERSHIP
);
429 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_IF
);
430 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_HOPS
);
431 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_LOOP
);
432 DEBUG_SOCKOPT(WS_IPV6_UNICAST_HOPS
);
433 DEBUG_SOCKOPT(WS_IPV6_V6ONLY
);
434 DEBUG_SOCKOPT(WS_IPV6_UNICAST_IF
);
435 DEBUG_SOCKOPT(WS_IPV6_DONTFRAG
);
439 #undef DEBUG_SOCKLEVEL
443 strlevel
= wine_dbg_sprintf("WS_0x%x", level
);
445 stropt
= wine_dbg_sprintf("WS_0x%x", optname
);
447 return wine_dbg_sprintf("level %s, name %s", strlevel
+ 3, stropt
+ 3);
450 static inline const char *debugstr_optval(const char *optval
, int optlenval
)
452 if (optval
&& !IS_INTRESOURCE(optval
) && optlenval
>= 1 && optlenval
<= sizeof(DWORD
))
455 memcpy(&value
, optval
, optlenval
);
456 return wine_dbg_sprintf("%p (%u)", optval
, value
);
458 return wine_dbg_sprintf("%p", optval
);
461 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
462 #define SOCKET2HANDLE(s) ((HANDLE)(s))
463 #define HANDLE2SOCKET(h) ((SOCKET)(h))
465 /****************************************************************
466 * Async IO declarations
467 ****************************************************************/
471 struct ws2_async_io
*next
;
474 struct ws2_async_shutdown
476 struct ws2_async_io io
;
478 IO_STATUS_BLOCK iosb
;
484 struct ws2_async_io io
;
486 LPWSAOVERLAPPED user_overlapped
;
487 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func
;
488 IO_STATUS_BLOCK local_iosb
;
489 struct WS_sockaddr
*addr
;
492 int val
; /* for send operations */
493 int *ptr
; /* for recv operations */
498 unsigned int n_iovecs
;
499 unsigned int first_iovec
;
500 struct iovec iovec
[1];
503 struct ws2_accept_async
505 struct ws2_async_io io
;
506 HANDLE listen_socket
;
507 HANDLE accept_socket
;
508 LPOVERLAPPED user_overlapped
;
510 PVOID buf
; /* buffer to write data to */
514 struct ws2_async
*read
;
517 static struct ws2_async_io
*async_io_freelist
;
519 static void release_async_io( struct ws2_async_io
*io
)
523 struct ws2_async_io
*next
= async_io_freelist
;
525 if (InterlockedCompareExchangePointer( (void **)&async_io_freelist
, io
, next
) == next
) return;
529 static struct ws2_async_io
*alloc_async_io( DWORD size
)
531 /* first free remaining previous fileinfos */
533 struct ws2_async_io
*io
= InterlockedExchangePointer( (void **)&async_io_freelist
, NULL
);
537 struct ws2_async_io
*next
= io
->next
;
538 HeapFree( GetProcessHeap(), 0, io
);
542 return HeapAlloc( GetProcessHeap(), 0, size
);
545 /****************************************************************/
547 /* ----------------------------------- internal data */
549 /* ws_... struct conversion flags */
551 typedef struct /* WSAAsyncSelect() control struct */
553 HANDLE service
, event
, sock
;
559 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
560 #define WS_MAX_UDP_DATAGRAM 1024
561 static INT WINAPI
WSA_DefaultBlockingHook( FARPROC x
);
563 /* hostent's, servent's and protent's are stored in one buffer per thread,
564 * as documented on MSDN for the functions that return any of the buffers */
565 struct per_thread_data
568 struct WS_hostent
*he_buffer
;
569 struct WS_servent
*se_buffer
;
570 struct WS_protoent
*pe_buffer
;
574 char ntoa_buffer
[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
577 /* internal: routing description information */
584 static INT num_startup
; /* reference counter */
585 static FARPROC blocking_hook
= (FARPROC
)WSA_DefaultBlockingHook
;
587 /* function prototypes */
588 static struct WS_hostent
*WS_create_he(char *name
, int aliases
, int aliases_size
, int addresses
, int address_length
);
589 static struct WS_hostent
*WS_dup_he(const struct hostent
* p_he
);
590 static struct WS_protoent
*WS_dup_pe(const struct protoent
* p_pe
);
591 static struct WS_servent
*WS_dup_se(const struct servent
* p_se
);
592 static int ws_protocol_info(SOCKET s
, int unicode
, WSAPROTOCOL_INFOW
*buffer
, int *size
);
594 int WSAIOCTL_GetInterfaceCount(void);
595 int WSAIOCTL_GetInterfaceName(int intNumber
, char *intName
);
597 static void WS_AddCompletion( SOCKET sock
, ULONG_PTR CompletionValue
, NTSTATUS CompletionStatus
, ULONG Information
);
599 #define MAP_OPTION(opt) { WS_##opt, opt }
601 static const int ws_flags_map
[][2] =
603 MAP_OPTION( MSG_OOB
),
604 MAP_OPTION( MSG_PEEK
),
605 MAP_OPTION( MSG_DONTROUTE
),
606 MAP_OPTION( MSG_WAITALL
),
609 static const int ws_sock_map
[][2] =
611 MAP_OPTION( SO_DEBUG
),
612 MAP_OPTION( SO_ACCEPTCONN
),
613 MAP_OPTION( SO_REUSEADDR
),
614 MAP_OPTION( SO_KEEPALIVE
),
615 MAP_OPTION( SO_DONTROUTE
),
616 MAP_OPTION( SO_BROADCAST
),
617 MAP_OPTION( SO_LINGER
),
618 MAP_OPTION( SO_OOBINLINE
),
619 MAP_OPTION( SO_SNDBUF
),
620 MAP_OPTION( SO_RCVBUF
),
621 MAP_OPTION( SO_ERROR
),
622 MAP_OPTION( SO_TYPE
),
624 MAP_OPTION( SO_RCVTIMEO
),
627 MAP_OPTION( SO_SNDTIMEO
),
631 static const int ws_tcp_map
[][2] =
634 MAP_OPTION( TCP_NODELAY
),
638 static const int ws_ip_map
[][2] =
640 MAP_OPTION( IP_MULTICAST_IF
),
641 MAP_OPTION( IP_MULTICAST_TTL
),
642 MAP_OPTION( IP_MULTICAST_LOOP
),
643 MAP_OPTION( IP_ADD_MEMBERSHIP
),
644 MAP_OPTION( IP_DROP_MEMBERSHIP
),
645 MAP_OPTION( IP_OPTIONS
),
647 MAP_OPTION( IP_HDRINCL
),
649 MAP_OPTION( IP_TOS
),
650 MAP_OPTION( IP_TTL
),
652 MAP_OPTION( IP_PKTINFO
),
655 MAP_OPTION( IP_UNICAST_IF
),
659 static const int ws_ipv6_map
[][2] =
661 #ifdef IPV6_ADD_MEMBERSHIP
662 MAP_OPTION( IPV6_ADD_MEMBERSHIP
),
664 #ifdef IPV6_DROP_MEMBERSHIP
665 MAP_OPTION( IPV6_DROP_MEMBERSHIP
),
667 MAP_OPTION( IPV6_MULTICAST_IF
),
668 MAP_OPTION( IPV6_MULTICAST_HOPS
),
669 MAP_OPTION( IPV6_MULTICAST_LOOP
),
670 MAP_OPTION( IPV6_UNICAST_HOPS
),
671 MAP_OPTION( IPV6_V6ONLY
),
672 #ifdef IPV6_UNICAST_IF
673 MAP_OPTION( IPV6_UNICAST_IF
),
677 static const int ws_af_map
[][2] =
679 MAP_OPTION( AF_UNSPEC
),
680 MAP_OPTION( AF_INET
),
681 MAP_OPTION( AF_INET6
),
683 MAP_OPTION( AF_IPX
),
686 MAP_OPTION( AF_IRDA
),
688 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
691 static const int ws_socktype_map
[][2] =
693 MAP_OPTION( SOCK_DGRAM
),
694 MAP_OPTION( SOCK_STREAM
),
695 MAP_OPTION( SOCK_RAW
),
696 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
699 static const int ws_proto_map
[][2] =
701 MAP_OPTION( IPPROTO_IP
),
702 MAP_OPTION( IPPROTO_TCP
),
703 MAP_OPTION( IPPROTO_UDP
),
704 MAP_OPTION( IPPROTO_IPV6
),
705 MAP_OPTION( IPPROTO_ICMP
),
706 MAP_OPTION( IPPROTO_IGMP
),
707 MAP_OPTION( IPPROTO_RAW
),
708 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
711 static const int ws_aiflag_map
[][2] =
713 MAP_OPTION( AI_PASSIVE
),
714 MAP_OPTION( AI_CANONNAME
),
715 MAP_OPTION( AI_NUMERICHOST
),
716 #ifdef AI_NUMERICSERV
717 MAP_OPTION( AI_NUMERICSERV
),
720 MAP_OPTION( AI_V4MAPPED
),
722 MAP_OPTION( AI_ADDRCONFIG
),
725 static const int ws_niflag_map
[][2] =
727 MAP_OPTION( NI_NOFQDN
),
728 MAP_OPTION( NI_NUMERICHOST
),
729 MAP_OPTION( NI_NAMEREQD
),
730 MAP_OPTION( NI_NUMERICSERV
),
731 MAP_OPTION( NI_DGRAM
),
734 static const int ws_eai_map
[][2] =
736 MAP_OPTION( EAI_AGAIN
),
737 MAP_OPTION( EAI_BADFLAGS
),
738 MAP_OPTION( EAI_FAIL
),
739 MAP_OPTION( EAI_FAMILY
),
740 MAP_OPTION( EAI_MEMORY
),
741 /* Note: EAI_NODATA is deprecated, but still
742 * used by Windows and Linux... We map the newer
743 * EAI_NONAME to EAI_NODATA for now until Windows
747 MAP_OPTION( EAI_NODATA
),
750 { WS_EAI_NODATA
, EAI_NONAME
},
753 MAP_OPTION( EAI_SERVICE
),
754 MAP_OPTION( EAI_SOCKTYPE
),
758 static const char magic_loopback_addr
[] = {127, 12, 34, 56};
760 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
762 static inline WSACMSGHDR
*fill_control_message(int level
, int type
, WSACMSGHDR
*current
, ULONG
*maxsize
, void *data
, int len
)
764 ULONG msgsize
= sizeof(WSACMSGHDR
) + WSA_CMSG_ALIGN(len
);
765 char *ptr
= (char *) current
+ sizeof(WSACMSGHDR
);
767 /* Make sure there is at least enough room for this entry */
768 if (msgsize
> *maxsize
)
771 /* Fill in the entry */
772 current
->cmsg_len
= sizeof(WSACMSGHDR
) + len
;
773 current
->cmsg_level
= level
;
774 current
->cmsg_type
= type
;
775 memcpy(ptr
, data
, len
);
776 /* Return the pointer to where next entry should go */
777 return (WSACMSGHDR
*) (ptr
+ WSA_CMSG_ALIGN(len
));
779 #endif /* IP_PKTINFO */
781 static inline int convert_control_headers(struct msghdr
*hdr
, WSABUF
*control
)
784 WSACMSGHDR
*cmsg_win
= (WSACMSGHDR
*) control
->buf
, *ptr
;
785 ULONG ctlsize
= control
->len
;
786 struct cmsghdr
*cmsg_unix
;
789 /* Loop over all the headers, converting as appropriate */
790 for (cmsg_unix
= CMSG_FIRSTHDR(hdr
); cmsg_unix
!= NULL
; cmsg_unix
= CMSG_NXTHDR(hdr
, cmsg_unix
))
792 switch(cmsg_unix
->cmsg_level
)
795 switch(cmsg_unix
->cmsg_type
)
799 /* Convert the Unix IP_PKTINFO structure to the Windows version */
800 struct in_pktinfo
*data_unix
= (struct in_pktinfo
*) CMSG_DATA(cmsg_unix
);
801 struct WS_in_pktinfo data_win
;
803 memcpy(&data_win
.ipi_addr
,&data_unix
->ipi_addr
.s_addr
,4); /* 4 bytes = 32 address bits */
804 data_win
.ipi_ifindex
= data_unix
->ipi_ifindex
;
805 ptr
= fill_control_message(WS_IPPROTO_IP
, WS_IP_PKTINFO
, ptr
, &ctlsize
,
806 (void*)&data_win
, sizeof(data_win
));
807 if (!ptr
) goto error
;
810 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix
->cmsg_type
);
815 FIXME("Unhandled message header level %d\n", cmsg_unix
->cmsg_level
);
821 /* Set the length of the returned control headers */
822 control
->len
= (ptr
== NULL
? 0 : (char*)ptr
- (char*)cmsg_win
);
823 return (ptr
!= NULL
);
824 #else /* IP_PKTINFO */
827 #endif /* IP_PKTINFO */
829 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
831 /* ----------------------------------- error handling */
833 static NTSTATUS
sock_get_ntstatus( int err
)
837 case EBADF
: return STATUS_INVALID_HANDLE
;
838 case EBUSY
: return STATUS_DEVICE_BUSY
;
840 case EACCES
: return STATUS_ACCESS_DENIED
;
841 case EFAULT
: return STATUS_NO_MEMORY
;
842 case EINVAL
: return STATUS_INVALID_PARAMETER
;
844 case EMFILE
: return STATUS_TOO_MANY_OPENED_FILES
;
845 case EWOULDBLOCK
: return STATUS_CANT_WAIT
;
846 case EINPROGRESS
: return STATUS_PENDING
;
847 case EALREADY
: return STATUS_NETWORK_BUSY
;
848 case ENOTSOCK
: return STATUS_OBJECT_TYPE_MISMATCH
;
849 case EDESTADDRREQ
: return STATUS_INVALID_PARAMETER
;
850 case EMSGSIZE
: return STATUS_BUFFER_OVERFLOW
;
851 case EPROTONOSUPPORT
:
852 case ESOCKTNOSUPPORT
:
855 case EPROTOTYPE
: return STATUS_NOT_SUPPORTED
;
856 case ENOPROTOOPT
: return STATUS_INVALID_PARAMETER
;
857 case EOPNOTSUPP
: return STATUS_NOT_SUPPORTED
;
858 case EADDRINUSE
: return STATUS_ADDRESS_ALREADY_ASSOCIATED
;
859 case EADDRNOTAVAIL
: return STATUS_INVALID_PARAMETER
;
860 case ECONNREFUSED
: return STATUS_CONNECTION_REFUSED
;
861 case ESHUTDOWN
: return STATUS_PIPE_DISCONNECTED
;
862 case ENOTCONN
: return STATUS_CONNECTION_DISCONNECTED
;
863 case ETIMEDOUT
: return STATUS_IO_TIMEOUT
;
864 case ENETUNREACH
: return STATUS_NETWORK_UNREACHABLE
;
865 case ENETDOWN
: return STATUS_NETWORK_BUSY
;
867 case ECONNRESET
: return STATUS_CONNECTION_RESET
;
868 case ECONNABORTED
: return STATUS_CONNECTION_ABORTED
;
870 case 0: return STATUS_SUCCESS
;
872 WARN("Unknown errno %d!\n", err
);
873 return STATUS_UNSUCCESSFUL
;
877 static UINT
sock_get_error( int err
)
881 case EINTR
: return WSAEINTR
;
883 case EACCES
: return WSAEACCES
;
884 case EFAULT
: return WSAEFAULT
;
885 case EINVAL
: return WSAEINVAL
;
886 case EMFILE
: return WSAEMFILE
;
887 case EWOULDBLOCK
: return WSAEWOULDBLOCK
;
888 case EINPROGRESS
: return WSAEINPROGRESS
;
889 case EALREADY
: return WSAEALREADY
;
891 case ENOTSOCK
: return WSAENOTSOCK
;
892 case EDESTADDRREQ
: return WSAEDESTADDRREQ
;
893 case EMSGSIZE
: return WSAEMSGSIZE
;
894 case EPROTOTYPE
: return WSAEPROTOTYPE
;
895 case ENOPROTOOPT
: return WSAENOPROTOOPT
;
896 case EPROTONOSUPPORT
: return WSAEPROTONOSUPPORT
;
897 case ESOCKTNOSUPPORT
: return WSAESOCKTNOSUPPORT
;
898 case EOPNOTSUPP
: return WSAEOPNOTSUPP
;
899 case EPFNOSUPPORT
: return WSAEPFNOSUPPORT
;
900 case EAFNOSUPPORT
: return WSAEAFNOSUPPORT
;
901 case EADDRINUSE
: return WSAEADDRINUSE
;
902 case EADDRNOTAVAIL
: return WSAEADDRNOTAVAIL
;
903 case ENETDOWN
: return WSAENETDOWN
;
904 case ENETUNREACH
: return WSAENETUNREACH
;
905 case ENETRESET
: return WSAENETRESET
;
906 case ECONNABORTED
: return WSAECONNABORTED
;
908 case ECONNRESET
: return WSAECONNRESET
;
909 case ENOBUFS
: return WSAENOBUFS
;
910 case EISCONN
: return WSAEISCONN
;
911 case ENOTCONN
: return WSAENOTCONN
;
912 case ESHUTDOWN
: return WSAESHUTDOWN
;
913 case ETOOMANYREFS
: return WSAETOOMANYREFS
;
914 case ETIMEDOUT
: return WSAETIMEDOUT
;
915 case ECONNREFUSED
: return WSAECONNREFUSED
;
916 case ELOOP
: return WSAELOOP
;
917 case ENAMETOOLONG
: return WSAENAMETOOLONG
;
918 case EHOSTDOWN
: return WSAEHOSTDOWN
;
919 case EHOSTUNREACH
: return WSAEHOSTUNREACH
;
920 case ENOTEMPTY
: return WSAENOTEMPTY
;
922 case EPROCLIM
: return WSAEPROCLIM
;
925 case EUSERS
: return WSAEUSERS
;
928 case EDQUOT
: return WSAEDQUOT
;
931 case ESTALE
: return WSAESTALE
;
934 case EREMOTE
: return WSAEREMOTE
;
937 /* just in case we ever get here and there are no problems */
940 WARN("Unknown errno %d!\n", err
);
941 return WSAEOPNOTSUPP
;
945 static UINT
wsaErrno(void)
947 int loc_errno
= errno
;
948 WARN("errno %d, (%s).\n", loc_errno
, strerror(loc_errno
));
950 return sock_get_error( loc_errno
);
953 /* most ws2 overlapped functions return an ntstatus-based error code */
954 static NTSTATUS
wsaErrStatus(void)
956 int loc_errno
= errno
;
957 WARN("errno %d, (%s).\n", loc_errno
, strerror(loc_errno
));
959 return sock_get_ntstatus(loc_errno
);
962 static UINT
wsaHerrno(int loc_errno
)
964 WARN("h_errno %d.\n", loc_errno
);
968 case HOST_NOT_FOUND
: return WSAHOST_NOT_FOUND
;
969 case TRY_AGAIN
: return WSATRY_AGAIN
;
970 case NO_RECOVERY
: return WSANO_RECOVERY
;
971 case NO_DATA
: return WSANO_DATA
;
972 case ENOBUFS
: return WSAENOBUFS
;
976 WARN("Unknown h_errno %d!\n", loc_errno
);
977 return WSAEOPNOTSUPP
;
981 static inline DWORD
NtStatusToWSAError( const DWORD status
)
983 /* We only need to cover the status codes set by server async request handling */
987 case STATUS_SUCCESS
: wserr
= 0; break;
988 case STATUS_PENDING
: wserr
= WSA_IO_PENDING
; break;
989 case STATUS_OBJECT_TYPE_MISMATCH
: wserr
= WSAENOTSOCK
; break;
990 case STATUS_INVALID_HANDLE
: wserr
= WSAEBADF
; break;
991 case STATUS_INVALID_PARAMETER
: wserr
= WSAEINVAL
; break;
992 case STATUS_PIPE_DISCONNECTED
: wserr
= WSAESHUTDOWN
; break;
993 case STATUS_NETWORK_BUSY
: wserr
= WSAEALREADY
; break;
994 case STATUS_NETWORK_UNREACHABLE
: wserr
= WSAENETUNREACH
; break;
995 case STATUS_CONNECTION_REFUSED
: wserr
= WSAECONNREFUSED
; break;
996 case STATUS_CONNECTION_DISCONNECTED
: wserr
= WSAENOTCONN
; break;
997 case STATUS_CONNECTION_RESET
: wserr
= WSAECONNRESET
; break;
998 case STATUS_CONNECTION_ABORTED
: wserr
= WSAECONNABORTED
; break;
999 case STATUS_CANCELLED
: wserr
= WSA_OPERATION_ABORTED
; break;
1000 case STATUS_ADDRESS_ALREADY_ASSOCIATED
: wserr
= WSAEADDRINUSE
; break;
1001 case STATUS_IO_TIMEOUT
:
1002 case STATUS_TIMEOUT
: wserr
= WSAETIMEDOUT
; break;
1003 case STATUS_NO_MEMORY
: wserr
= WSAEFAULT
; break;
1004 case STATUS_ACCESS_DENIED
: wserr
= WSAEACCES
; break;
1005 case STATUS_TOO_MANY_OPENED_FILES
: wserr
= WSAEMFILE
; break;
1006 case STATUS_CANT_WAIT
: wserr
= WSAEWOULDBLOCK
; break;
1007 case STATUS_BUFFER_OVERFLOW
: wserr
= WSAEMSGSIZE
; break;
1008 case STATUS_NOT_SUPPORTED
: wserr
= WSAEOPNOTSUPP
; break;
1009 case STATUS_HOST_UNREACHABLE
: wserr
= WSAEHOSTUNREACH
; break;
1012 wserr
= RtlNtStatusToDosError( status
);
1013 FIXME( "Status code %08x converted to DOS error code %x\n", status
, wserr
);
1018 /* set last error code from NT status without mapping WSA errors */
1019 static inline unsigned int set_error( unsigned int err
)
1023 err
= NtStatusToWSAError( err
);
1024 SetLastError( err
);
1029 static inline int get_sock_fd( SOCKET s
, DWORD access
, unsigned int *options
)
1032 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s
), access
, &fd
, options
) ))
1037 static inline void release_sock_fd( SOCKET s
, int fd
)
1039 wine_server_release_fd( SOCKET2HANDLE(s
), fd
);
1042 static void _enable_event( HANDLE s
, unsigned int event
,
1043 unsigned int sstate
, unsigned int cstate
)
1045 SERVER_START_REQ( enable_socket_event
)
1047 req
->handle
= wine_server_obj_handle( s
);
1049 req
->sstate
= sstate
;
1050 req
->cstate
= cstate
;
1051 wine_server_call( req
);
1056 static NTSTATUS
_is_blocking(SOCKET s
, BOOL
*ret
)
1059 SERVER_START_REQ( get_socket_event
)
1061 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1062 req
->service
= FALSE
;
1064 status
= wine_server_call( req
);
1065 *ret
= (reply
->state
& FD_WINE_NONBLOCKING
) == 0;
1071 static unsigned int _get_sock_mask(SOCKET s
)
1074 SERVER_START_REQ( get_socket_event
)
1076 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1077 req
->service
= FALSE
;
1079 wine_server_call( req
);
1086 static void _sync_sock_state(SOCKET s
)
1089 /* do a dummy wineserver request in order to let
1090 the wineserver run through its select loop once */
1091 (void)_is_blocking(s
, &dummy
);
1094 static void _get_sock_errors(SOCKET s
, int *events
)
1096 SERVER_START_REQ( get_socket_event
)
1098 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1099 req
->service
= FALSE
;
1101 wine_server_set_reply( req
, events
, sizeof(int) * FD_MAX_EVENTS
);
1102 wine_server_call( req
);
1107 static int _get_sock_error(SOCKET s
, unsigned int bit
)
1109 int events
[FD_MAX_EVENTS
];
1110 _get_sock_errors(s
, events
);
1114 static int _get_fd_type(int fd
)
1117 socklen_t optlen
= sizeof(sock_type
);
1118 getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char*) &sock_type
, &optlen
);
1122 static struct per_thread_data
*get_per_thread_data(void)
1124 struct per_thread_data
* ptb
= NtCurrentTeb()->WinSockData
;
1125 /* lazy initialization */
1128 ptb
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(*ptb
) );
1129 NtCurrentTeb()->WinSockData
= ptb
;
1134 static void free_per_thread_data(void)
1136 struct per_thread_data
* ptb
= NtCurrentTeb()->WinSockData
;
1140 /* delete scratch buffers */
1141 HeapFree( GetProcessHeap(), 0, ptb
->he_buffer
);
1142 HeapFree( GetProcessHeap(), 0, ptb
->se_buffer
);
1143 HeapFree( GetProcessHeap(), 0, ptb
->pe_buffer
);
1144 ptb
->he_buffer
= NULL
;
1145 ptb
->se_buffer
= NULL
;
1146 ptb
->pe_buffer
= NULL
;
1148 HeapFree( GetProcessHeap(), 0, ptb
);
1149 NtCurrentTeb()->WinSockData
= NULL
;
1152 /***********************************************************************
1153 * DllMain (WS2_32.init)
1155 BOOL WINAPI
DllMain(HINSTANCE hInstDLL
, DWORD fdwReason
, LPVOID fImpLoad
)
1157 TRACE("%p 0x%x %p\n", hInstDLL
, fdwReason
, fImpLoad
);
1158 switch (fdwReason
) {
1159 case DLL_PROCESS_ATTACH
:
1161 case DLL_PROCESS_DETACH
:
1162 if (fImpLoad
) break;
1163 free_per_thread_data();
1164 DeleteCriticalSection(&csWSgetXXXbyYYY
);
1166 case DLL_THREAD_DETACH
:
1167 free_per_thread_data();
1173 /***********************************************************************
1176 * Converts send/recv flags from Windows format.
1177 * Return the converted flag bits, unsupported flags remain unchanged.
1179 static int convert_flags(int flags
)
1182 if (!flags
) return 0;
1184 for (out
= i
= 0; flags
&& i
< sizeof(ws_flags_map
) / sizeof(ws_flags_map
[0]); i
++)
1186 if (ws_flags_map
[i
][0] & flags
)
1188 out
|= ws_flags_map
[i
][1];
1189 flags
&= ~ws_flags_map
[i
][0];
1194 FIXME("Unknown send/recv flags 0x%x, using anyway...\n", flags
);
1200 /***********************************************************************
1203 * Converts socket flags from Windows format.
1204 * Return 1 if converted, 0 if not (error).
1206 static int convert_sockopt(INT
*level
, INT
*optname
)
1212 *level
= SOL_SOCKET
;
1213 for(i
=0; i
<sizeof(ws_sock_map
)/sizeof(ws_sock_map
[0]); i
++) {
1214 if( ws_sock_map
[i
][0] == *optname
)
1216 *optname
= ws_sock_map
[i
][1];
1220 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname
);
1222 case WS_IPPROTO_TCP
:
1223 *level
= IPPROTO_TCP
;
1224 for(i
=0; i
<sizeof(ws_tcp_map
)/sizeof(ws_tcp_map
[0]); i
++) {
1225 if ( ws_tcp_map
[i
][0] == *optname
)
1227 *optname
= ws_tcp_map
[i
][1];
1231 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname
);
1234 *level
= IPPROTO_IP
;
1235 for(i
=0; i
<sizeof(ws_ip_map
)/sizeof(ws_ip_map
[0]); i
++) {
1236 if (ws_ip_map
[i
][0] == *optname
)
1238 *optname
= ws_ip_map
[i
][1];
1242 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname
);
1244 case WS_IPPROTO_IPV6
:
1245 *level
= IPPROTO_IPV6
;
1246 for(i
=0; i
<sizeof(ws_ipv6_map
)/sizeof(ws_ipv6_map
[0]); i
++) {
1247 if (ws_ipv6_map
[i
][0] == *optname
)
1249 *optname
= ws_ipv6_map
[i
][1];
1253 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname
);
1255 default: FIXME("Unimplemented or unknown socket level\n");
1260 /* ----------------------------------- Per-thread info (or per-process?) */
1262 static char *strdup_lower(const char *str
)
1265 char *ret
= HeapAlloc( GetProcessHeap(), 0, strlen(str
) + 1 );
1269 for (i
= 0; str
[i
]; i
++) ret
[i
] = tolower(str
[i
]);
1272 else SetLastError(WSAENOBUFS
);
1276 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1277 * from an fd and return the value converted to milli seconds
1278 * or 0 if there is an infinite time out */
1279 static inline INT64
get_rcvsnd_timeo( int fd
, BOOL is_recv
)
1282 socklen_t len
= sizeof(tv
);
1287 optname
= SO_RCVTIMEO
;
1293 optname
= SO_SNDTIMEO
;
1298 res
= getsockopt(fd
, SOL_SOCKET
, optname
, &tv
, &len
);
1301 return (UINT64
)tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000;
1304 /* utility: given an fd, will block until one of the events occurs */
1305 static inline int do_block( int fd
, int events
, int timeout
)
1311 pfd
.events
= events
;
1313 while ((ret
= poll(&pfd
, 1, timeout
)) < 0)
1324 convert_af_w2u(int windowsaf
) {
1327 for (i
=0;i
<sizeof(ws_af_map
)/sizeof(ws_af_map
[0]);i
++)
1328 if (ws_af_map
[i
][0] == windowsaf
)
1329 return ws_af_map
[i
][1];
1330 FIXME("unhandled Windows address family %d\n", windowsaf
);
1335 convert_af_u2w(int unixaf
) {
1338 for (i
=0;i
<sizeof(ws_af_map
)/sizeof(ws_af_map
[0]);i
++)
1339 if (ws_af_map
[i
][1] == unixaf
)
1340 return ws_af_map
[i
][0];
1341 FIXME("unhandled UNIX address family %d\n", unixaf
);
1346 convert_proto_w2u(int windowsproto
) {
1349 for (i
=0;i
<sizeof(ws_proto_map
)/sizeof(ws_proto_map
[0]);i
++)
1350 if (ws_proto_map
[i
][0] == windowsproto
)
1351 return ws_proto_map
[i
][1];
1353 /* check for extended IPX */
1354 if (IS_IPX_PROTO(windowsproto
))
1355 return windowsproto
;
1357 FIXME("unhandled Windows socket protocol %d\n", windowsproto
);
1362 convert_proto_u2w(int unixproto
) {
1365 for (i
=0;i
<sizeof(ws_proto_map
)/sizeof(ws_proto_map
[0]);i
++)
1366 if (ws_proto_map
[i
][1] == unixproto
)
1367 return ws_proto_map
[i
][0];
1369 /* if value is inside IPX range just return it - the kernel simply
1370 * echoes the value used in the socket() function */
1371 if (IS_IPX_PROTO(unixproto
))
1374 FIXME("unhandled UNIX socket protocol %d\n", unixproto
);
1379 convert_socktype_w2u(int windowssocktype
) {
1382 for (i
=0;i
<sizeof(ws_socktype_map
)/sizeof(ws_socktype_map
[0]);i
++)
1383 if (ws_socktype_map
[i
][0] == windowssocktype
)
1384 return ws_socktype_map
[i
][1];
1385 FIXME("unhandled Windows socket type %d\n", windowssocktype
);
1390 convert_socktype_u2w(int unixsocktype
) {
1393 for (i
=0;i
<sizeof(ws_socktype_map
)/sizeof(ws_socktype_map
[0]);i
++)
1394 if (ws_socktype_map
[i
][1] == unixsocktype
)
1395 return ws_socktype_map
[i
][0];
1396 FIXME("unhandled UNIX socket type %d\n", unixsocktype
);
1400 static int set_ipx_packettype(int sock
, int ptype
)
1403 int fd
= get_sock_fd( sock
, 0, NULL
), ret
= 0;
1404 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype
, fd
);
1406 if (fd
== -1) return SOCKET_ERROR
;
1408 /* We try to set the ipx type on ipx socket level. */
1410 if(setsockopt(fd
, SOL_IPX
, IPX_TYPE
, &ptype
, sizeof(ptype
)) == -1)
1412 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1418 /* Should we retrieve val using a getsockopt call and then
1419 * set the modified one? */
1421 setsockopt(fd
, 0, SO_DEFAULT_HEADERS
, &val
, sizeof(struct ipx
));
1424 release_sock_fd( sock
, fd
);
1427 WARN("IPX support is not enabled, can't set packet type\n");
1428 return SOCKET_ERROR
;
1432 /* ----------------------------------- API -----
1434 * Init / cleanup / error checking.
1437 /***********************************************************************
1438 * WSAStartup (WS2_32.115)
1440 int WINAPI
WSAStartup(WORD wVersionRequested
, LPWSADATA lpWSAData
)
1442 TRACE("verReq=%x\n", wVersionRequested
);
1444 if (LOBYTE(wVersionRequested
) < 1)
1445 return WSAVERNOTSUPPORTED
;
1447 if (!lpWSAData
) return WSAEINVAL
;
1451 /* that's the whole of the negotiation for now */
1452 lpWSAData
->wVersion
= wVersionRequested
;
1453 /* return winsock information */
1454 lpWSAData
->wHighVersion
= 0x0202;
1455 strcpy(lpWSAData
->szDescription
, "WinSock 2.0" );
1456 strcpy(lpWSAData
->szSystemStatus
, "Running" );
1457 lpWSAData
->iMaxSockets
= WS_MAX_SOCKETS_PER_PROCESS
;
1458 lpWSAData
->iMaxUdpDg
= WS_MAX_UDP_DATAGRAM
;
1459 /* don't do anything with lpWSAData->lpVendorInfo */
1460 /* (some apps don't allocate the space for this field) */
1462 TRACE("succeeded starts: %d\n", num_startup
);
1467 /***********************************************************************
1468 * WSACleanup (WS2_32.116)
1470 INT WINAPI
WSACleanup(void)
1474 TRACE("pending cleanups: %d\n", num_startup
);
1477 SetLastError(WSANOTINITIALISED
);
1478 return SOCKET_ERROR
;
1482 /***********************************************************************
1483 * WSAGetLastError (WS2_32.111)
1485 INT WINAPI
WSAGetLastError(void)
1487 return GetLastError();
1490 /***********************************************************************
1491 * WSASetLastError (WS2_32.112)
1493 void WINAPI
WSASetLastError(INT iError
) {
1494 SetLastError(iError
);
1497 static struct WS_hostent
*check_buffer_he(int size
)
1499 struct per_thread_data
* ptb
= get_per_thread_data();
1502 if (ptb
->he_len
>= size
) return ptb
->he_buffer
;
1503 HeapFree( GetProcessHeap(), 0, ptb
->he_buffer
);
1505 ptb
->he_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->he_len
= size
) );
1506 if (!ptb
->he_buffer
) SetLastError(WSAENOBUFS
);
1507 return ptb
->he_buffer
;
1510 static struct WS_servent
*check_buffer_se(int size
)
1512 struct per_thread_data
* ptb
= get_per_thread_data();
1515 if (ptb
->se_len
>= size
) return ptb
->se_buffer
;
1516 HeapFree( GetProcessHeap(), 0, ptb
->se_buffer
);
1518 ptb
->se_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->se_len
= size
) );
1519 if (!ptb
->se_buffer
) SetLastError(WSAENOBUFS
);
1520 return ptb
->se_buffer
;
1523 static struct WS_protoent
*check_buffer_pe(int size
)
1525 struct per_thread_data
* ptb
= get_per_thread_data();
1528 if (ptb
->pe_len
>= size
) return ptb
->pe_buffer
;
1529 HeapFree( GetProcessHeap(), 0, ptb
->pe_buffer
);
1531 ptb
->pe_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->pe_len
= size
) );
1532 if (!ptb
->pe_buffer
) SetLastError(WSAENOBUFS
);
1533 return ptb
->pe_buffer
;
1536 /* ----------------------------------- i/o APIs */
1538 static inline BOOL
supported_pf(int pf
)
1558 static inline BOOL
supported_protocol(int protocol
)
1561 for (i
= 0; i
< sizeof(valid_protocols
) / sizeof(valid_protocols
[0]); i
++)
1562 if (protocol
== valid_protocols
[i
])
1567 /**********************************************************************/
1569 /* Returns the length of the converted address if successful, 0 if it was too small to
1572 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr
* wsaddr
, int wsaddrlen
,
1573 union generic_unix_sockaddr
*uaddr
)
1575 unsigned int uaddrlen
= 0;
1577 switch (wsaddr
->sa_family
)
1582 const struct WS_sockaddr_ipx
* wsipx
=(const struct WS_sockaddr_ipx
*)wsaddr
;
1583 struct sockaddr_ipx
* uipx
= (struct sockaddr_ipx
*)uaddr
;
1585 if (wsaddrlen
<sizeof(struct WS_sockaddr_ipx
))
1588 uaddrlen
= sizeof(struct sockaddr_ipx
);
1589 memset( uaddr
, 0, uaddrlen
);
1590 uipx
->sipx_family
=AF_IPX
;
1591 uipx
->sipx_port
=wsipx
->sa_socket
;
1592 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1595 memcpy(&uipx
->sipx_network
,wsipx
->sa_netnum
,sizeof(uipx
->sipx_network
)+sizeof(uipx
->sipx_node
));
1596 #ifdef IPX_FRAME_NONE
1597 uipx
->sipx_type
=IPX_FRAME_NONE
;
1603 struct sockaddr_in6
* uin6
= (struct sockaddr_in6
*)uaddr
;
1604 const struct WS_sockaddr_in6
* win6
= (const struct WS_sockaddr_in6
*)wsaddr
;
1606 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1607 * scope_id, one without.
1609 if (wsaddrlen
>= sizeof(struct WS_sockaddr_in6_old
)) {
1610 uaddrlen
= sizeof(struct sockaddr_in6
);
1611 memset( uaddr
, 0, uaddrlen
);
1612 uin6
->sin6_family
= AF_INET6
;
1613 uin6
->sin6_port
= win6
->sin6_port
;
1614 uin6
->sin6_flowinfo
= win6
->sin6_flowinfo
;
1615 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1616 if (wsaddrlen
>= sizeof(struct WS_sockaddr_in6
)) uin6
->sin6_scope_id
= win6
->sin6_scope_id
;
1618 memcpy(&uin6
->sin6_addr
,&win6
->sin6_addr
,16); /* 16 bytes = 128 address bits */
1621 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen
);
1625 struct sockaddr_in
* uin
= (struct sockaddr_in
*)uaddr
;
1626 const struct WS_sockaddr_in
* win
= (const struct WS_sockaddr_in
*)wsaddr
;
1628 if (wsaddrlen
<sizeof(struct WS_sockaddr_in
))
1630 uaddrlen
= sizeof(struct sockaddr_in
);
1631 memset( uaddr
, 0, uaddrlen
);
1632 uin
->sin_family
= AF_INET
;
1633 uin
->sin_port
= win
->sin_port
;
1634 memcpy(&uin
->sin_addr
,&win
->sin_addr
,4); /* 4 bytes = 32 address bits */
1639 struct sockaddr_irda
*uin
= (struct sockaddr_irda
*)uaddr
;
1640 const SOCKADDR_IRDA
*win
= (const SOCKADDR_IRDA
*)wsaddr
;
1642 if (wsaddrlen
< sizeof(SOCKADDR_IRDA
))
1644 uaddrlen
= sizeof(struct sockaddr_irda
);
1645 memset( uaddr
, 0, uaddrlen
);
1646 uin
->sir_family
= AF_IRDA
;
1647 if (!strncmp( win
->irdaServiceName
, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1649 unsigned int lsap_sel
= 0;
1651 sscanf( win
->irdaServiceName
, "LSAP-SEL%u", &lsap_sel
);
1652 uin
->sir_lsap_sel
= lsap_sel
;
1656 uin
->sir_lsap_sel
= LSAP_ANY
;
1657 memcpy( uin
->sir_name
, win
->irdaServiceName
, 25 );
1659 memcpy( &uin
->sir_addr
, win
->irdaDeviceID
, sizeof(uin
->sir_addr
) );
1663 case WS_AF_UNSPEC
: {
1664 /* Try to determine the needed space by the passed windows sockaddr space */
1665 switch (wsaddrlen
) {
1666 default: /* likely an ipv4 address */
1667 case sizeof(struct WS_sockaddr_in
):
1668 uaddrlen
= sizeof(struct sockaddr_in
);
1671 case sizeof(struct WS_sockaddr_ipx
):
1672 uaddrlen
= sizeof(struct sockaddr_ipx
);
1676 case sizeof(SOCKADDR_IRDA
):
1677 uaddrlen
= sizeof(struct sockaddr_irda
);
1680 case sizeof(struct WS_sockaddr_in6
):
1681 case sizeof(struct WS_sockaddr_in6_old
):
1682 uaddrlen
= sizeof(struct sockaddr_in6
);
1685 memset( uaddr
, 0, uaddrlen
);
1689 FIXME("Unknown address family %d, return NULL.\n", wsaddr
->sa_family
);
1695 static BOOL
is_sockaddr_bound(const struct sockaddr
*uaddr
, int uaddrlen
)
1697 switch (uaddr
->sa_family
)
1702 static const struct sockaddr_ipx emptyAddr
;
1703 struct sockaddr_ipx
*ipx
= (struct sockaddr_ipx
*) uaddr
;
1704 return ipx
->sipx_port
1705 || memcmp(&ipx
->sipx_network
, &emptyAddr
.sipx_network
, sizeof(emptyAddr
.sipx_network
))
1706 || memcmp(&ipx
->sipx_node
, &emptyAddr
.sipx_node
, sizeof(emptyAddr
.sipx_node
));
1711 static const struct sockaddr_in6 emptyAddr
;
1712 const struct sockaddr_in6
*in6
= (const struct sockaddr_in6
*) uaddr
;
1713 return in6
->sin6_port
|| memcmp(&in6
->sin6_addr
, &emptyAddr
.sin6_addr
, sizeof(struct in6_addr
));
1717 static const struct sockaddr_in emptyAddr
;
1718 const struct sockaddr_in
*in
= (const struct sockaddr_in
*) uaddr
;
1719 return in
->sin_port
|| memcmp(&in
->sin_addr
, &emptyAddr
.sin_addr
, sizeof(struct in_addr
));
1724 FIXME("unknown address family %d\n", uaddr
->sa_family
);
1729 /* Returns -1 if getsockname fails, 0 if not bound, 1 otherwise */
1730 static int is_fd_bound(int fd
, union generic_unix_sockaddr
*uaddr
, socklen_t
*uaddrlen
)
1732 union generic_unix_sockaddr inaddr
;
1736 if (!uaddr
) uaddr
= &inaddr
;
1737 if (!uaddrlen
) uaddrlen
= &inlen
;
1739 *uaddrlen
= sizeof(inaddr
);
1740 res
= getsockname(fd
, &uaddr
->addr
, uaddrlen
);
1741 if (!res
) res
= is_sockaddr_bound(&uaddr
->addr
, *uaddrlen
);
1745 /* Returns 0 if successful, -1 if the buffer is too small */
1746 static int ws_sockaddr_u2ws(const struct sockaddr
* uaddr
, struct WS_sockaddr
* wsaddr
, int* wsaddrlen
)
1750 switch(uaddr
->sa_family
)
1755 const struct sockaddr_ipx
* uipx
=(const struct sockaddr_ipx
*)uaddr
;
1756 struct WS_sockaddr_ipx
* wsipx
=(struct WS_sockaddr_ipx
*)wsaddr
;
1759 switch (*wsaddrlen
) /* how much can we copy? */
1763 *wsaddrlen
= sizeof(*wsipx
);
1764 wsipx
->sa_socket
=uipx
->sipx_port
;
1768 memcpy(wsipx
->sa_nodenum
,uipx
->sipx_node
,sizeof(wsipx
->sa_nodenum
));
1776 memcpy(wsipx
->sa_netnum
,&uipx
->sipx_network
,sizeof(wsipx
->sa_netnum
));
1782 wsipx
->sa_family
=WS_AF_IPX
;
1794 const struct sockaddr_irda
*uin
= (const struct sockaddr_irda
*)uaddr
;
1795 SOCKADDR_IRDA
*win
= (SOCKADDR_IRDA
*)wsaddr
;
1797 if (*wsaddrlen
< sizeof(SOCKADDR_IRDA
))
1799 win
->irdaAddressFamily
= WS_AF_IRDA
;
1800 memcpy( win
->irdaDeviceID
, &uin
->sir_addr
, sizeof(win
->irdaDeviceID
) );
1801 if (uin
->sir_lsap_sel
!= LSAP_ANY
)
1802 sprintf( win
->irdaServiceName
, "LSAP-SEL%u", uin
->sir_lsap_sel
);
1804 memcpy( win
->irdaServiceName
, uin
->sir_name
,
1805 sizeof(win
->irdaServiceName
) );
1810 const struct sockaddr_in6
* uin6
= (const struct sockaddr_in6
*)uaddr
;
1811 struct WS_sockaddr_in6_old
* win6old
= (struct WS_sockaddr_in6_old
*)wsaddr
;
1813 if (*wsaddrlen
< sizeof(struct WS_sockaddr_in6_old
))
1815 win6old
->sin6_family
= WS_AF_INET6
;
1816 win6old
->sin6_port
= uin6
->sin6_port
;
1817 win6old
->sin6_flowinfo
= uin6
->sin6_flowinfo
;
1818 memcpy(&win6old
->sin6_addr
,&uin6
->sin6_addr
,16); /* 16 bytes = 128 address bits */
1819 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1820 if (*wsaddrlen
>= sizeof(struct WS_sockaddr_in6
)) {
1821 struct WS_sockaddr_in6
* win6
= (struct WS_sockaddr_in6
*)wsaddr
;
1822 win6
->sin6_scope_id
= uin6
->sin6_scope_id
;
1823 *wsaddrlen
= sizeof(struct WS_sockaddr_in6
);
1826 *wsaddrlen
= sizeof(struct WS_sockaddr_in6_old
);
1828 *wsaddrlen
= sizeof(struct WS_sockaddr_in6_old
);
1833 const struct sockaddr_in
* uin
= (const struct sockaddr_in
*)uaddr
;
1834 struct WS_sockaddr_in
* win
= (struct WS_sockaddr_in
*)wsaddr
;
1836 if (*wsaddrlen
< sizeof(struct WS_sockaddr_in
))
1838 win
->sin_family
= WS_AF_INET
;
1839 win
->sin_port
= uin
->sin_port
;
1840 memcpy(&win
->sin_addr
,&uin
->sin_addr
,4); /* 4 bytes = 32 address bits */
1841 memset(win
->sin_zero
, 0, 8); /* Make sure the null padding is null */
1842 *wsaddrlen
= sizeof(struct WS_sockaddr_in
);
1846 memset(wsaddr
,0,*wsaddrlen
);
1850 FIXME("Unknown address family %d\n", uaddr
->sa_family
);
1856 static INT
WS_DuplicateSocket(BOOL unicode
, SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOW lpProtocolInfo
)
1860 WSAPROTOCOL_INFOW infow
;
1862 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
1863 unicode
, s
, dwProcessId
, lpProtocolInfo
);
1865 if (!ws_protocol_info(s
, unicode
, &infow
, &size
))
1866 return SOCKET_ERROR
;
1868 if (!(hProcess
= OpenProcess(PROCESS_DUP_HANDLE
, FALSE
, dwProcessId
)))
1870 SetLastError(WSAEINVAL
);
1871 return SOCKET_ERROR
;
1874 if (!lpProtocolInfo
)
1876 CloseHandle(hProcess
);
1877 SetLastError(WSAEFAULT
);
1878 return SOCKET_ERROR
;
1881 /* I don't know what the real Windoze does next, this is a hack */
1882 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
1883 * the target use the global duplicate, or we could copy a reference to us to the structure
1884 * and let the target duplicate it from us, but let's do it as simple as possible */
1885 memcpy(lpProtocolInfo
, &infow
, size
);
1886 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s
),
1887 hProcess
, (LPHANDLE
)&lpProtocolInfo
->dwServiceFlags3
,
1888 0, FALSE
, DUPLICATE_SAME_ACCESS
);
1889 CloseHandle(hProcess
);
1890 lpProtocolInfo
->dwServiceFlags4
= 0xff00ff00; /* magic */
1894 /*****************************************************************************
1895 * WS_EnterSingleProtocolW [internal]
1897 * enters the protocol information of one given protocol into the given
1901 * TRUE if a protocol was entered into the buffer.
1904 * - only implemented for IPX, SPX, SPXII, TCP, UDP
1905 * - there is no check that the operating system supports the returned
1908 static BOOL
WS_EnterSingleProtocolW( INT protocol
, WSAPROTOCOL_INFOW
* info
)
1910 memset( info
, 0, sizeof(WSAPROTOCOL_INFOW
) );
1911 info
->iProtocol
= protocol
;
1915 case WS_IPPROTO_TCP
:
1916 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_EXPEDITED_DATA
|
1917 XP1_GRACEFUL_CLOSE
| XP1_GUARANTEED_ORDER
|
1918 XP1_GUARANTEED_DELIVERY
;
1919 info
->ProviderId
= ProviderIdIP
;
1920 info
->dwCatalogEntryId
= 0x3e9;
1921 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1922 info
->ProtocolChain
.ChainLen
= 1;
1924 info
->iAddressFamily
= WS_AF_INET
;
1925 info
->iMaxSockAddr
= 0x10;
1926 info
->iMinSockAddr
= 0x10;
1927 info
->iSocketType
= WS_SOCK_STREAM
;
1928 strcpyW( info
->szProtocol
, NameTcpW
);
1931 case WS_IPPROTO_UDP
:
1932 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_SUPPORT_BROADCAST
|
1933 XP1_SUPPORT_MULTIPOINT
| XP1_MESSAGE_ORIENTED
|
1935 info
->ProviderId
= ProviderIdIP
;
1936 info
->dwCatalogEntryId
= 0x3ea;
1937 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1938 info
->ProtocolChain
.ChainLen
= 1;
1940 info
->iAddressFamily
= WS_AF_INET
;
1941 info
->iMaxSockAddr
= 0x10;
1942 info
->iMinSockAddr
= 0x10;
1943 info
->iSocketType
= WS_SOCK_DGRAM
;
1944 info
->dwMessageSize
= 0xffbb;
1945 strcpyW( info
->szProtocol
, NameUdpW
);
1948 case WS_NSPROTO_IPX
:
1949 info
->dwServiceFlags1
= XP1_PARTIAL_MESSAGE
| XP1_SUPPORT_BROADCAST
|
1950 XP1_SUPPORT_MULTIPOINT
| XP1_MESSAGE_ORIENTED
|
1952 info
->ProviderId
= ProviderIdIPX
;
1953 info
->dwCatalogEntryId
= 0x406;
1954 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1955 info
->ProtocolChain
.ChainLen
= 1;
1957 info
->iAddressFamily
= WS_AF_IPX
;
1958 info
->iMaxSockAddr
= 0x10;
1959 info
->iMinSockAddr
= 0x0e;
1960 info
->iSocketType
= WS_SOCK_DGRAM
;
1961 info
->iProtocolMaxOffset
= 0xff;
1962 info
->dwMessageSize
= 0x240;
1963 strcpyW( info
->szProtocol
, NameIpxW
);
1966 case WS_NSPROTO_SPX
:
1967 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_PSEUDO_STREAM
|
1968 XP1_MESSAGE_ORIENTED
| XP1_GUARANTEED_ORDER
|
1969 XP1_GUARANTEED_DELIVERY
;
1970 info
->ProviderId
= ProviderIdSPX
;
1971 info
->dwCatalogEntryId
= 0x407;
1972 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1973 info
->ProtocolChain
.ChainLen
= 1;
1975 info
->iAddressFamily
= WS_AF_IPX
;
1976 info
->iMaxSockAddr
= 0x10;
1977 info
->iMinSockAddr
= 0x0e;
1978 info
->iSocketType
= WS_SOCK_SEQPACKET
;
1979 info
->dwMessageSize
= 0xffffffff;
1980 strcpyW( info
->szProtocol
, NameSpxW
);
1983 case WS_NSPROTO_SPXII
:
1984 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_GRACEFUL_CLOSE
|
1985 XP1_PSEUDO_STREAM
| XP1_MESSAGE_ORIENTED
|
1986 XP1_GUARANTEED_ORDER
| XP1_GUARANTEED_DELIVERY
;
1987 info
->ProviderId
= ProviderIdSPX
;
1988 info
->dwCatalogEntryId
= 0x409;
1989 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1990 info
->ProtocolChain
.ChainLen
= 1;
1992 info
->iAddressFamily
= WS_AF_IPX
;
1993 info
->iMaxSockAddr
= 0x10;
1994 info
->iMinSockAddr
= 0x0e;
1995 info
->iSocketType
= WS_SOCK_SEQPACKET
;
1996 info
->dwMessageSize
= 0xffffffff;
1997 strcpyW( info
->szProtocol
, NameSpxIIW
);
2001 FIXME("unknown Protocol <0x%08x>\n", protocol
);
2007 /*****************************************************************************
2008 * WS_EnterSingleProtocolA [internal]
2010 * see function WS_EnterSingleProtocolW
2013 static BOOL
WS_EnterSingleProtocolA( INT protocol
, WSAPROTOCOL_INFOA
* info
)
2015 WSAPROTOCOL_INFOW infow
;
2017 memset( info
, 0, sizeof(WSAPROTOCOL_INFOA
) );
2019 ret
= WS_EnterSingleProtocolW( protocol
, &infow
);
2022 /* convert the structure from W to A */
2023 memcpy( info
, &infow
, FIELD_OFFSET( WSAPROTOCOL_INFOA
, szProtocol
) );
2024 WideCharToMultiByte( CP_ACP
, 0, infow
.szProtocol
, -1,
2025 info
->szProtocol
, WSAPROTOCOL_LEN
+1, NULL
, NULL
);
2031 static INT
WS_EnumProtocols( BOOL unicode
, const INT
*protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
)
2033 INT i
= 0, items
= 0;
2037 LPWSAPROTOCOL_INFOA a
;
2038 LPWSAPROTOCOL_INFOW w
;
2042 if (!protocols
) protocols
= valid_protocols
;
2044 while (protocols
[i
])
2046 if(supported_protocol(protocols
[i
++]))
2050 size
= items
* (unicode
? sizeof(WSAPROTOCOL_INFOW
) : sizeof(WSAPROTOCOL_INFOA
));
2052 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
2053 unicode
, protocols
, buffer
, len
, len
? *len
: 0, items
, size
);
2055 if (*len
< size
|| !buffer
)
2058 SetLastError(WSAENOBUFS
);
2059 return SOCKET_ERROR
;
2062 for (i
= items
= 0; protocols
[i
]; i
++)
2064 if (!supported_protocol(protocols
[i
])) continue;
2067 if (WS_EnterSingleProtocolW( protocols
[i
], &info
.w
[items
] ))
2072 if (WS_EnterSingleProtocolA( protocols
[i
], &info
.a
[items
] ))
2079 static BOOL
ws_protocol_info(SOCKET s
, int unicode
, WSAPROTOCOL_INFOW
*buffer
, int *size
)
2083 *size
= unicode
? sizeof(WSAPROTOCOL_INFOW
) : sizeof(WSAPROTOCOL_INFOA
);
2084 memset(buffer
, 0, *size
);
2086 SERVER_START_REQ( get_socket_info
)
2088 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
2089 status
= wine_server_call( req
);
2092 buffer
->iAddressFamily
= convert_af_u2w(reply
->family
);
2093 buffer
->iSocketType
= convert_socktype_u2w(reply
->type
);
2094 buffer
->iProtocol
= convert_proto_u2w(reply
->protocol
);
2101 unsigned int err
= NtStatusToWSAError( status
);
2102 SetLastError( err
== WSAEBADF
? WSAENOTSOCK
: err
);
2107 WS_EnterSingleProtocolW( buffer
->iProtocol
, buffer
);
2109 WS_EnterSingleProtocolA( buffer
->iProtocol
, (WSAPROTOCOL_INFOA
*)buffer
);
2114 /**************************************************************************
2115 * Functions for handling overlapped I/O
2116 **************************************************************************/
2118 /* user APC called upon async completion */
2119 static void WINAPI
ws2_async_apc( void *arg
, IO_STATUS_BLOCK
*iosb
, ULONG reserved
)
2121 struct ws2_async
*wsa
= arg
;
2123 if (wsa
->completion_func
) wsa
->completion_func( NtStatusToWSAError(iosb
->u
.Status
),
2124 iosb
->Information
, wsa
->user_overlapped
,
2126 release_async_io( &wsa
->io
);
2129 /***********************************************************************
2130 * WS2_recv (INTERNAL)
2132 * Workhorse for both synchronous and asynchronous recv() operations.
2134 static int WS2_recv( int fd
, struct ws2_async
*wsa
, int flags
)
2136 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2140 union generic_unix_sockaddr unix_sockaddr
;
2143 hdr
.msg_name
= NULL
;
2147 hdr
.msg_namelen
= sizeof(unix_sockaddr
);
2148 hdr
.msg_name
= &unix_sockaddr
;
2151 hdr
.msg_namelen
= 0;
2153 hdr
.msg_iov
= wsa
->iovec
+ wsa
->first_iovec
;
2154 hdr
.msg_iovlen
= wsa
->n_iovecs
- wsa
->first_iovec
;
2155 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2156 hdr
.msg_accrights
= NULL
;
2157 hdr
.msg_accrightslen
= 0;
2159 hdr
.msg_control
= pktbuf
;
2160 hdr
.msg_controllen
= sizeof(pktbuf
);
2164 while ((n
= recvmsg(fd
, &hdr
, flags
)) == -1)
2170 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2173 ERR("Message control headers cannot be properly supported on this system.\n");
2174 wsa
->control
->len
= 0;
2177 if (wsa
->control
&& !convert_control_headers(&hdr
, wsa
->control
))
2179 WARN("Application passed insufficient room for control headers.\n");
2180 *wsa
->lpFlags
|= WS_MSG_CTRUNC
;
2186 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
2187 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
2189 * quoting linux 2.6 net/ipv4/tcp.c:
2190 * "According to UNIX98, msg_name/msg_namelen are ignored
2191 * on connected socket. I was just happy when found this 8) --ANK"
2193 * likewise MSDN says that lpFrom and lpFromlen are ignored for
2194 * connection-oriented sockets, so don't try to update lpFrom.
2196 if (wsa
->addr
&& hdr
.msg_namelen
)
2197 ws_sockaddr_u2ws( &unix_sockaddr
.addr
, wsa
->addr
, wsa
->addrlen
.ptr
);
2202 /***********************************************************************
2203 * WS2_async_recv (INTERNAL)
2205 * Handler for overlapped recv() operations.
2207 static NTSTATUS
WS2_async_recv( void *user
, IO_STATUS_BLOCK
*iosb
,
2208 NTSTATUS status
, void **apc
, void **arg
)
2210 struct ws2_async
*wsa
= user
;
2215 case STATUS_ALERTED
:
2216 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, FILE_READ_DATA
, &fd
, NULL
) ))
2219 result
= WS2_recv( fd
, wsa
, convert_flags(wsa
->flags
) );
2220 wine_server_release_fd( wsa
->hSocket
, fd
);
2223 status
= STATUS_SUCCESS
;
2224 _enable_event( wsa
->hSocket
, FD_READ
, 0, 0 );
2228 if (errno
== EAGAIN
)
2230 status
= STATUS_PENDING
;
2231 _enable_event( wsa
->hSocket
, FD_READ
, 0, 0 );
2236 status
= wsaErrStatus();
2241 if (status
!= STATUS_PENDING
)
2243 iosb
->u
.Status
= status
;
2244 iosb
->Information
= result
;
2245 if (wsa
->completion_func
)
2247 *apc
= ws2_async_apc
;
2251 release_async_io( &wsa
->io
);
2256 /***********************************************************************
2257 * WS2_async_accept_recv (INTERNAL)
2259 * This function is used to finish the read part of an accept request. It is
2260 * needed to place the completion on the correct socket (listener).
2262 static NTSTATUS
WS2_async_accept_recv( void *user
, IO_STATUS_BLOCK
*iosb
,
2263 NTSTATUS status
, void **apc
, void **arg
)
2266 struct ws2_accept_async
*wsa
= user
;
2268 status
= WS2_async_recv( wsa
->read
, iosb
, status
, &junk
, &junk
);
2269 if (status
== STATUS_PENDING
)
2273 WS_AddCompletion( HANDLE2SOCKET(wsa
->listen_socket
), wsa
->cvalue
, iosb
->u
.Status
, iosb
->Information
);
2275 release_async_io( &wsa
->io
);
2279 /***********************************************************************
2280 * WS2_async_accept (INTERNAL)
2282 * This is the function called to satisfy the AcceptEx callback
2284 static NTSTATUS
WS2_async_accept( void *user
, IO_STATUS_BLOCK
*iosb
,
2285 NTSTATUS status
, void **apc
, void **arg
)
2287 struct ws2_accept_async
*wsa
= user
;
2291 TRACE("status: 0x%x listen: %p, accept: %p\n", status
, wsa
->listen_socket
, wsa
->accept_socket
);
2293 if (status
== STATUS_ALERTED
)
2295 SERVER_START_REQ( accept_into_socket
)
2297 req
->lhandle
= wine_server_obj_handle( wsa
->listen_socket
);
2298 req
->ahandle
= wine_server_obj_handle( wsa
->accept_socket
);
2299 status
= wine_server_call( req
);
2303 if (status
== STATUS_CANT_WAIT
)
2304 return STATUS_PENDING
;
2306 if (status
== STATUS_INVALID_HANDLE
)
2308 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2309 status
= STATUS_CANCELLED
;
2312 else if (status
== STATUS_HANDLES_CLOSED
)
2313 status
= STATUS_CANCELLED
; /* strange windows behavior */
2315 if (status
!= STATUS_SUCCESS
)
2318 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2319 addr
= ((char *)wsa
->buf
) + wsa
->data_len
;
2320 len
= wsa
->local_len
- sizeof(int);
2321 WS_getsockname(HANDLE2SOCKET(wsa
->accept_socket
),
2322 (struct WS_sockaddr
*)(addr
+ sizeof(int)), &len
);
2325 addr
+= wsa
->local_len
;
2326 len
= wsa
->remote_len
- sizeof(int);
2327 WS_getpeername(HANDLE2SOCKET(wsa
->accept_socket
),
2328 (struct WS_sockaddr
*)(addr
+ sizeof(int)), &len
);
2334 SERVER_START_REQ( register_async
)
2336 req
->type
= ASYNC_TYPE_READ
;
2337 req
->async
.handle
= wine_server_obj_handle( wsa
->accept_socket
);
2338 req
->async
.event
= wine_server_obj_handle( wsa
->user_overlapped
->hEvent
);
2339 req
->async
.callback
= wine_server_client_ptr( WS2_async_accept_recv
);
2340 req
->async
.iosb
= wine_server_client_ptr( iosb
);
2341 req
->async
.arg
= wine_server_client_ptr( wsa
);
2342 status
= wine_server_call( req
);
2346 if (status
!= STATUS_PENDING
)
2349 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2350 * needs to be performed by WS2_async_accept_recv() first. */
2351 return STATUS_MORE_PROCESSING_REQUIRED
;
2354 iosb
->u
.Status
= status
;
2355 iosb
->Information
= 0;
2357 if (wsa
->read
) release_async_io( &wsa
->read
->io
);
2358 release_async_io( &wsa
->io
);
2362 /***********************************************************************
2363 * WS2_send (INTERNAL)
2365 * Workhorse for both synchronous and asynchronous send() operations.
2367 static int WS2_send( int fd
, struct ws2_async
*wsa
, int flags
)
2370 union generic_unix_sockaddr unix_addr
;
2373 hdr
.msg_name
= NULL
;
2374 hdr
.msg_namelen
= 0;
2378 hdr
.msg_name
= &unix_addr
;
2379 hdr
.msg_namelen
= ws_sockaddr_ws2u( wsa
->addr
, wsa
->addrlen
.val
, &unix_addr
);
2380 if ( !hdr
.msg_namelen
)
2386 #if defined(HAS_IPX) && defined(SOL_IPX)
2387 if(wsa
->addr
->sa_family
== WS_AF_IPX
)
2389 struct sockaddr_ipx
* uipx
= (struct sockaddr_ipx
*)hdr
.msg_name
;
2391 socklen_t len
= sizeof(int);
2393 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2394 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2395 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2396 * ipx type in the sockaddr_opx structure with the stored value.
2398 if(getsockopt(fd
, SOL_IPX
, IPX_TYPE
, &val
, &len
) != -1)
2399 uipx
->sipx_type
= val
;
2404 hdr
.msg_iov
= wsa
->iovec
+ wsa
->first_iovec
;
2405 hdr
.msg_iovlen
= wsa
->n_iovecs
- wsa
->first_iovec
;
2406 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2407 hdr
.msg_accrights
= NULL
;
2408 hdr
.msg_accrightslen
= 0;
2410 hdr
.msg_control
= NULL
;
2411 hdr
.msg_controllen
= 0;
2415 while ((ret
= sendmsg(fd
, &hdr
, flags
)) == -1)
2422 while (wsa
->first_iovec
< wsa
->n_iovecs
&& wsa
->iovec
[wsa
->first_iovec
].iov_len
<= n
)
2423 n
-= wsa
->iovec
[wsa
->first_iovec
++].iov_len
;
2424 if (wsa
->first_iovec
< wsa
->n_iovecs
)
2426 wsa
->iovec
[wsa
->first_iovec
].iov_base
= (char*)wsa
->iovec
[wsa
->first_iovec
].iov_base
+ n
;
2427 wsa
->iovec
[wsa
->first_iovec
].iov_len
-= n
;
2432 /***********************************************************************
2433 * WS2_async_send (INTERNAL)
2435 * Handler for overlapped send() operations.
2437 static NTSTATUS
WS2_async_send( void *user
, IO_STATUS_BLOCK
*iosb
,
2438 NTSTATUS status
, void **apc
, void **arg
)
2440 struct ws2_async
*wsa
= user
;
2445 case STATUS_ALERTED
:
2446 if ( wsa
->n_iovecs
<= wsa
->first_iovec
)
2449 status
= STATUS_SUCCESS
;
2452 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, FILE_WRITE_DATA
, &fd
, NULL
) ))
2455 /* check to see if the data is ready (non-blocking) */
2456 result
= WS2_send( fd
, wsa
, convert_flags(wsa
->flags
) );
2457 wine_server_release_fd( wsa
->hSocket
, fd
);
2461 if (wsa
->first_iovec
< wsa
->n_iovecs
)
2462 status
= STATUS_PENDING
;
2464 status
= STATUS_SUCCESS
;
2466 iosb
->Information
+= result
;
2468 else if (errno
== EAGAIN
)
2470 status
= STATUS_PENDING
;
2474 status
= wsaErrStatus();
2478 if (status
!= STATUS_PENDING
)
2480 iosb
->u
.Status
= status
;
2481 if (wsa
->completion_func
)
2483 *apc
= ws2_async_apc
;
2487 release_async_io( &wsa
->io
);
2492 /***********************************************************************
2493 * WS2_async_shutdown (INTERNAL)
2495 * Handler for shutdown() operations on overlapped sockets.
2497 static NTSTATUS
WS2_async_shutdown( void *user
, IO_STATUS_BLOCK
*iosb
,
2498 NTSTATUS status
, void **apc
, void **arg
)
2500 struct ws2_async_shutdown
*wsa
= user
;
2505 case STATUS_ALERTED
:
2506 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, 0, &fd
, NULL
) ))
2509 switch ( wsa
->type
)
2511 case ASYNC_TYPE_READ
: err
= shutdown( fd
, 0 ); break;
2512 case ASYNC_TYPE_WRITE
: err
= shutdown( fd
, 1 ); break;
2514 status
= err
? wsaErrStatus() : STATUS_SUCCESS
;
2515 wine_server_release_fd( wsa
->hSocket
, fd
);
2518 iosb
->u
.Status
= status
;
2519 iosb
->Information
= 0;
2520 release_async_io( &wsa
->io
);
2524 /***********************************************************************
2525 * WS2_register_async_shutdown (INTERNAL)
2527 * Helper function for WS_shutdown() on overlapped sockets.
2529 static int WS2_register_async_shutdown( SOCKET s
, int type
)
2531 struct ws2_async_shutdown
*wsa
;
2534 TRACE("socket %04lx type %d\n", s
, type
);
2536 wsa
= (struct ws2_async_shutdown
*)alloc_async_io( sizeof(*wsa
) );
2540 wsa
->hSocket
= SOCKET2HANDLE(s
);
2543 SERVER_START_REQ( register_async
)
2546 req
->async
.handle
= wine_server_obj_handle( wsa
->hSocket
);
2547 req
->async
.callback
= wine_server_client_ptr( WS2_async_shutdown
);
2548 req
->async
.iosb
= wine_server_client_ptr( &wsa
->iosb
);
2549 req
->async
.arg
= wine_server_client_ptr( wsa
);
2550 req
->async
.cvalue
= 0;
2551 status
= wine_server_call( req
);
2555 if (status
!= STATUS_PENDING
)
2557 HeapFree( GetProcessHeap(), 0, wsa
);
2558 return NtStatusToWSAError( status
);
2563 /***********************************************************************
2566 SOCKET WINAPI
WS_accept(SOCKET s
, struct WS_sockaddr
*addr
, int *addrlen32
)
2572 TRACE("socket %04lx\n", s
);
2573 status
= _is_blocking(s
, &is_blocking
);
2577 return INVALID_SOCKET
;
2581 /* try accepting first (if there is a deferred connection) */
2582 SERVER_START_REQ( accept_socket
)
2584 req
->lhandle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
2585 req
->access
= GENERIC_READ
|GENERIC_WRITE
|SYNCHRONIZE
;
2586 req
->attributes
= OBJ_INHERIT
;
2587 status
= wine_server_call( req
);
2588 as
= HANDLE2SOCKET( wine_server_ptr_handle( reply
->handle
));
2593 if (addr
&& WS_getpeername(as
, addr
, addrlen32
))
2596 return SOCKET_ERROR
;
2598 TRACE("\taccepted %04lx\n", as
);
2601 if (is_blocking
&& status
== STATUS_CANT_WAIT
)
2603 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
2605 do_block(fd
, POLLIN
, -1);
2606 _sync_sock_state(s
); /* let wineserver notice connection */
2607 release_sock_fd( s
, fd
);
2609 } while (is_blocking
&& status
== STATUS_CANT_WAIT
);
2612 return INVALID_SOCKET
;
2615 /***********************************************************************
2618 static BOOL WINAPI
WS2_AcceptEx(SOCKET listener
, SOCKET acceptor
, PVOID dest
, DWORD dest_len
,
2619 DWORD local_addr_len
, DWORD rem_addr_len
, LPDWORD received
,
2620 LPOVERLAPPED overlapped
)
2623 struct ws2_accept_async
*wsa
;
2626 TRACE("(%04lx, %04lx, %p, %d, %d, %d, %p, %p)\n", listener
, acceptor
, dest
, dest_len
, local_addr_len
,
2627 rem_addr_len
, received
, overlapped
);
2631 SetLastError(WSAEINVAL
);
2637 SetLastError(WSA_INVALID_PARAMETER
);
2643 SetLastError(WSAEFAULT
);
2647 fd
= get_sock_fd( listener
, FILE_READ_DATA
, NULL
);
2650 SetLastError(WSAENOTSOCK
);
2653 release_sock_fd( listener
, fd
);
2655 fd
= get_sock_fd( acceptor
, FILE_READ_DATA
, NULL
);
2658 SetLastError(WSAENOTSOCK
);
2661 release_sock_fd( acceptor
, fd
);
2663 wsa
= (struct ws2_accept_async
*)alloc_async_io( sizeof(*wsa
) );
2666 SetLastError(WSAEFAULT
);
2670 wsa
->listen_socket
= SOCKET2HANDLE(listener
);
2671 wsa
->accept_socket
= SOCKET2HANDLE(acceptor
);
2672 wsa
->user_overlapped
= overlapped
;
2673 wsa
->cvalue
= !((ULONG_PTR
)overlapped
->hEvent
& 1) ? (ULONG_PTR
)overlapped
: 0;
2675 wsa
->data_len
= dest_len
;
2676 wsa
->local_len
= local_addr_len
;
2677 wsa
->remote_len
= rem_addr_len
;
2682 /* set up a read request if we need it */
2683 wsa
->read
= (struct ws2_async
*)alloc_async_io( offsetof(struct ws2_async
, iovec
[1]) );
2686 HeapFree( GetProcessHeap(), 0, wsa
);
2687 SetLastError(WSAEFAULT
);
2691 wsa
->read
->hSocket
= wsa
->accept_socket
;
2692 wsa
->read
->flags
= 0;
2693 wsa
->read
->lpFlags
= &wsa
->read
->flags
;
2694 wsa
->read
->addr
= NULL
;
2695 wsa
->read
->addrlen
.ptr
= NULL
;
2696 wsa
->read
->control
= NULL
;
2697 wsa
->read
->n_iovecs
= 1;
2698 wsa
->read
->first_iovec
= 0;
2699 wsa
->read
->completion_func
= NULL
;
2700 wsa
->read
->iovec
[0].iov_base
= wsa
->buf
;
2701 wsa
->read
->iovec
[0].iov_len
= wsa
->data_len
;
2704 SERVER_START_REQ( register_async
)
2706 req
->type
= ASYNC_TYPE_READ
;
2707 req
->async
.handle
= wine_server_obj_handle( SOCKET2HANDLE(listener
) );
2708 req
->async
.event
= wine_server_obj_handle( overlapped
->hEvent
);
2709 req
->async
.callback
= wine_server_client_ptr( WS2_async_accept
);
2710 req
->async
.iosb
= wine_server_client_ptr( overlapped
);
2711 req
->async
.arg
= wine_server_client_ptr( wsa
);
2712 req
->async
.cvalue
= wsa
->cvalue
;
2713 status
= wine_server_call( req
);
2717 if(status
!= STATUS_PENDING
)
2719 HeapFree( GetProcessHeap(), 0, wsa
->read
);
2720 HeapFree( GetProcessHeap(), 0, wsa
);
2723 SetLastError( NtStatusToWSAError(status
) );
2727 /***********************************************************************
2730 static BOOL WINAPI
WS2_TransmitFile( SOCKET s
, HANDLE h
, DWORD file_bytes
, DWORD bytes_per_send
,
2731 LPOVERLAPPED overlapped
, LPTRANSMIT_FILE_BUFFERS buffers
,
2734 FIXME("(%lx, %p, %d, %d, %p, %p, %d): stub !\n", s
, h
, file_bytes
, bytes_per_send
, overlapped
,
2736 WSASetLastError( WSAEOPNOTSUPP
);
2740 /***********************************************************************
2741 * GetAcceptExSockaddrs
2743 static void WINAPI
WS2_GetAcceptExSockaddrs(PVOID buffer
, DWORD data_size
, DWORD local_size
, DWORD remote_size
,
2744 struct WS_sockaddr
**local_addr
, LPINT local_addr_len
,
2745 struct WS_sockaddr
**remote_addr
, LPINT remote_addr_len
)
2747 char *cbuf
= buffer
;
2748 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer
, data_size
, local_size
, remote_size
, local_addr
,
2749 local_addr_len
, remote_addr
, remote_addr_len
);
2752 *local_addr_len
= *(int *) cbuf
;
2753 *local_addr
= (struct WS_sockaddr
*)(cbuf
+ sizeof(int));
2757 *remote_addr_len
= *(int *) cbuf
;
2758 *remote_addr
= (struct WS_sockaddr
*)(cbuf
+ sizeof(int));
2761 /***********************************************************************
2764 int WINAPI
WSASendMsg( SOCKET s
, LPWSAMSG msg
, DWORD dwFlags
, LPDWORD lpNumberOfBytesSent
,
2765 LPWSAOVERLAPPED lpOverlapped
,
2766 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
2770 SetLastError( WSAEFAULT
);
2771 return SOCKET_ERROR
;
2774 return WS2_sendto( s
, msg
->lpBuffers
, msg
->dwBufferCount
, lpNumberOfBytesSent
,
2775 dwFlags
, msg
->name
, msg
->namelen
,
2776 lpOverlapped
, lpCompletionRoutine
);
2779 /***********************************************************************
2782 * Perform a receive operation that is capable of returning message
2783 * control headers. It is important to note that the WSAMSG parameter
2784 * must remain valid throughout the operation, even when an overlapped
2785 * receive is performed.
2787 static int WINAPI
WS2_WSARecvMsg( SOCKET s
, LPWSAMSG msg
, LPDWORD lpNumberOfBytesRecvd
,
2788 LPWSAOVERLAPPED lpOverlapped
,
2789 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
2793 SetLastError( WSAEFAULT
);
2794 return SOCKET_ERROR
;
2797 return WS2_recv_base( s
, msg
->lpBuffers
, msg
->dwBufferCount
, lpNumberOfBytesRecvd
,
2798 &msg
->dwFlags
, msg
->name
, &msg
->namelen
,
2799 lpOverlapped
, lpCompletionRoutine
, &msg
->Control
);
2802 /***********************************************************************
2803 * interface_bind (INTERNAL)
2805 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
2806 * operating only on the specified interface. This restriction consists of two components:
2807 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
2808 * 2) An incoming packet restriction dropping packets not meant for the interface.
2809 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
2810 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
2811 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
2812 * to receive broadcast packets on a socket that is bound to a specific network interface.
2814 static BOOL
interface_bind( SOCKET s
, int fd
, struct sockaddr
*addr
)
2816 struct sockaddr_in
*in_sock
= (struct sockaddr_in
*) addr
;
2817 in_addr_t bind_addr
= in_sock
->sin_addr
.s_addr
;
2818 PIP_ADAPTER_INFO adapters
= NULL
, adapter
;
2823 if (bind_addr
== htonl(INADDR_ANY
) || bind_addr
== htonl(INADDR_LOOPBACK
))
2824 return FALSE
; /* Not binding to a network adapter, special interface binding unnecessary. */
2825 if (_get_fd_type(fd
) != SOCK_DGRAM
)
2826 return FALSE
; /* Special interface binding is only necessary for UDP datagrams. */
2827 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
2829 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
2830 if (adapters
== NULL
|| GetAdaptersInfo(adapters
, &adap_size
) != NO_ERROR
)
2832 /* Search the IPv4 adapter list for the appropriate binding interface */
2833 for (adapter
= adapters
; adapter
!= NULL
; adapter
= adapter
->Next
)
2835 in_addr_t adapter_addr
= (in_addr_t
) inet_addr(adapter
->IpAddressList
.IpAddress
.String
);
2837 if (bind_addr
== adapter_addr
)
2839 #if defined(IP_BOUND_IF)
2840 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
2841 if (setsockopt(fd
, IPPROTO_IP
, IP_BOUND_IF
, &adapter
->Index
, sizeof(adapter
->Index
)) != 0)
2844 #elif defined(LINUX_BOUND_IF)
2845 in_addr_t ifindex
= (in_addr_t
) htonl(adapter
->Index
);
2846 struct interface_filter specific_interface_filter
;
2847 struct sock_fprog filter_prog
;
2849 if (setsockopt(fd
, IPPROTO_IP
, IP_UNICAST_IF
, &ifindex
, sizeof(ifindex
)) != 0)
2850 goto cleanup
; /* Failed to suggest egress interface */
2851 specific_interface_filter
= generic_interface_filter
;
2852 specific_interface_filter
.iface_rule
.k
= adapter
->Index
;
2853 specific_interface_filter
.ip_rule
.k
= htonl(adapter_addr
);
2854 filter_prog
.len
= sizeof(generic_interface_filter
)/sizeof(struct sock_filter
);
2855 filter_prog
.filter
= (struct sock_filter
*) &specific_interface_filter
;
2856 if (setsockopt(fd
, SOL_SOCKET
, SO_ATTACH_FILTER
, &filter_prog
, sizeof(filter_prog
)) != 0)
2857 goto cleanup
; /* Failed to specify incoming packet filter */
2860 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
2861 "receiving broadcast packets will not work on socket %04lx.\n", s
);
2866 /* Will soon be switching to INADDR_ANY: permit address reuse */
2867 if (ret
&& setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &enable
, sizeof(enable
)) == 0)
2868 TRACE("Socket %04lx bound to interface index %d\n", s
, adapter
->Index
);
2874 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s
);
2875 HeapFree(GetProcessHeap(), 0, adapters
);
2879 /***********************************************************************
2882 int WINAPI
WS_bind(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
)
2884 int fd
= get_sock_fd( s
, 0, NULL
);
2885 int res
= SOCKET_ERROR
;
2887 TRACE("socket %04lx, ptr %p %s, length %d\n", s
, name
, debugstr_sockaddr(name
), namelen
);
2891 if (!name
|| (name
->sa_family
&& !supported_pf(name
->sa_family
)))
2893 SetLastError(WSAEAFNOSUPPORT
);
2897 union generic_unix_sockaddr uaddr
;
2898 unsigned int uaddrlen
= ws_sockaddr_ws2u(name
, namelen
, &uaddr
);
2901 SetLastError(WSAEFAULT
);
2906 const struct sockaddr_in6
*in6
= (const struct sockaddr_in6
*) &uaddr
;
2907 if (name
->sa_family
== WS_AF_INET6
&&
2908 !memcmp(&in6
->sin6_addr
, &in6addr_any
, sizeof(struct in6_addr
)))
2911 if (setsockopt(fd
, IPPROTO_IPV6
, IPV6_V6ONLY
, &enable
, sizeof(enable
)) == -1)
2913 release_sock_fd( s
, fd
);
2914 SetLastError(WSAEAFNOSUPPORT
);
2915 return SOCKET_ERROR
;
2919 if (name
->sa_family
== WS_AF_INET
)
2921 struct sockaddr_in
*in4
= (struct sockaddr_in
*) &uaddr
;
2922 if (memcmp(&in4
->sin_addr
, magic_loopback_addr
, 4) == 0)
2924 /* Trying to bind to the default host interface, using
2925 * INADDR_ANY instead*/
2926 WARN("Trying to bind to magic IP address, using "
2927 "INADDR_ANY instead.\n");
2928 in4
->sin_addr
.s_addr
= htonl(INADDR_ANY
);
2930 else if (interface_bind(s
, fd
, &uaddr
.addr
))
2931 in4
->sin_addr
.s_addr
= htonl(INADDR_ANY
);
2933 if (bind(fd
, &uaddr
.addr
, uaddrlen
) < 0)
2935 int loc_errno
= errno
;
2936 WARN("\tfailure - errno = %i\n", errno
);
2941 SetLastError(WSAEINVAL
);
2946 socklen_t optlen
= sizeof(optval
);
2947 /* Windows >= 2003 will return different results depending on
2948 * SO_REUSEADDR, WSAEACCES may be returned representing that
2949 * the socket hijacking protection prevented the bind */
2950 if (!getsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&optval
, &optlen
) && optval
)
2952 SetLastError(WSAEACCES
);
2958 SetLastError(wsaErrno());
2964 res
=0; /* success */
2968 release_sock_fd( s
, fd
);
2973 /***********************************************************************
2974 * closesocket (WS2_32.3)
2976 int WINAPI
WS_closesocket(SOCKET s
)
2978 int res
= SOCKET_ERROR
, fd
;
2981 fd
= get_sock_fd(s
, FILE_READ_DATA
, NULL
);
2984 release_sock_fd(s
, fd
);
2985 if (CloseHandle(SOCKET2HANDLE(s
)))
2989 SetLastError(WSAENOTSOCK
);
2992 SetLastError(WSANOTINITIALISED
);
2993 TRACE("(socket %04lx) -> %d\n", s
, res
);
2997 static int do_connect(int fd
, const struct WS_sockaddr
* name
, int namelen
)
2999 union generic_unix_sockaddr uaddr
;
3000 unsigned int uaddrlen
= ws_sockaddr_ws2u(name
, namelen
, &uaddr
);
3005 if (name
->sa_family
== WS_AF_INET
)
3007 struct sockaddr_in
*in4
= (struct sockaddr_in
*) &uaddr
;
3008 if (memcmp(&in4
->sin_addr
, magic_loopback_addr
, 4) == 0)
3010 /* Trying to connect to magic replace-loopback address,
3011 * assuming we really want to connect to localhost */
3012 TRACE("Trying to connect to magic IP address, using "
3013 "INADDR_LOOPBACK instead.\n");
3014 in4
->sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
3018 if (connect(fd
, &uaddr
.addr
, uaddrlen
) == 0)
3024 /***********************************************************************
3025 * connect (WS2_32.4)
3027 int WINAPI
WS_connect(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
)
3029 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
3031 TRACE("socket %04lx, ptr %p %s, length %d\n", s
, name
, debugstr_sockaddr(name
), namelen
);
3037 int ret
= do_connect(fd
, name
, namelen
);
3039 goto connect_success
;
3041 if (ret
== WSAEINPROGRESS
)
3043 /* tell wineserver that a connection is in progress */
3044 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3046 FD_WINE_CONNECTED
|FD_WINE_LISTENING
);
3047 status
= _is_blocking( s
, &is_blocking
);
3050 release_sock_fd( s
, fd
);
3051 set_error( status
);
3052 return SOCKET_ERROR
;
3058 do_block(fd
, POLLIN
| POLLOUT
, -1);
3059 _sync_sock_state(s
); /* let wineserver notice connection */
3060 /* retrieve any error codes from it */
3061 result
= _get_sock_error(s
, FD_CONNECT_BIT
);
3063 SetLastError(NtStatusToWSAError(result
));
3066 goto connect_success
;
3071 SetLastError(WSAEWOULDBLOCK
);
3078 release_sock_fd( s
, fd
);
3080 return SOCKET_ERROR
;
3083 release_sock_fd( s
, fd
);
3084 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3085 FD_WINE_CONNECTED
|FD_READ
|FD_WRITE
,
3086 FD_CONNECT
|FD_WINE_LISTENING
);
3087 TRACE("\tconnected %04lx\n", s
);
3091 /***********************************************************************
3092 * WSAConnect (WS2_32.30)
3094 int WINAPI
WSAConnect( SOCKET s
, const struct WS_sockaddr
* name
, int namelen
,
3095 LPWSABUF lpCallerData
, LPWSABUF lpCalleeData
,
3096 LPQOS lpSQOS
, LPQOS lpGQOS
)
3098 if ( lpCallerData
|| lpCalleeData
|| lpSQOS
|| lpGQOS
)
3099 FIXME("unsupported parameters!\n");
3100 return WS_connect( s
, name
, namelen
);
3103 /***********************************************************************
3106 static BOOL WINAPI
WS2_ConnectEx(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
,
3107 PVOID sendBuf
, DWORD sendBufLen
, LPDWORD sent
, LPOVERLAPPED ov
)
3109 int fd
, ret
, status
;
3113 SetLastError( ERROR_INVALID_PARAMETER
);
3117 fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
3120 SetLastError( WSAENOTSOCK
);
3124 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
3125 s
, name
, debugstr_sockaddr(name
), namelen
, sendBuf
, sendBufLen
, ov
);
3127 ret
= is_fd_bound(fd
, NULL
, NULL
);
3130 SetLastError(ret
== -1 ? wsaErrno() : WSAEINVAL
);
3131 release_sock_fd( s
, fd
);
3135 ret
= do_connect(fd
, name
, namelen
);
3140 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3141 FD_WINE_CONNECTED
|FD_READ
|FD_WRITE
,
3142 FD_CONNECT
|FD_WINE_LISTENING
);
3144 wsabuf
.len
= sendBufLen
;
3145 wsabuf
.buf
= (char*) sendBuf
;
3147 /* WSASend takes care of completion if need be */
3148 if (WSASend(s
, &wsabuf
, sendBuf
? 1 : 0, sent
, 0, ov
, NULL
) != SOCKET_ERROR
)
3149 goto connection_success
;
3151 else if (ret
== WSAEINPROGRESS
)
3153 struct ws2_async
*wsa
;
3154 ULONG_PTR cvalue
= (((ULONG_PTR
)ov
->hEvent
& 1) == 0) ? (ULONG_PTR
)ov
: 0;
3156 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3158 FD_WINE_CONNECTED
|FD_WINE_LISTENING
);
3160 /* Indirectly call WSASend */
3161 if (!(wsa
= (struct ws2_async
*)alloc_async_io( offsetof( struct ws2_async
, iovec
[1] ))))
3163 SetLastError(WSAEFAULT
);
3167 IO_STATUS_BLOCK
*iosb
= (IO_STATUS_BLOCK
*)ov
;
3168 iosb
->u
.Status
= STATUS_PENDING
;
3169 iosb
->Information
= 0;
3171 wsa
->hSocket
= SOCKET2HANDLE(s
);
3173 wsa
->addrlen
.val
= 0;
3175 wsa
->lpFlags
= &wsa
->flags
;
3176 wsa
->control
= NULL
;
3177 wsa
->n_iovecs
= sendBuf
? 1 : 0;
3178 wsa
->first_iovec
= 0;
3179 wsa
->completion_func
= NULL
;
3180 wsa
->iovec
[0].iov_base
= sendBuf
;
3181 wsa
->iovec
[0].iov_len
= sendBufLen
;
3183 SERVER_START_REQ( register_async
)
3185 req
->type
= ASYNC_TYPE_WRITE
;
3186 req
->async
.handle
= wine_server_obj_handle( wsa
->hSocket
);
3187 req
->async
.callback
= wine_server_client_ptr( WS2_async_send
);
3188 req
->async
.iosb
= wine_server_client_ptr( iosb
);
3189 req
->async
.arg
= wine_server_client_ptr( wsa
);
3190 req
->async
.event
= wine_server_obj_handle( ov
->hEvent
);
3191 req
->async
.cvalue
= cvalue
;
3192 status
= wine_server_call( req
);
3196 if (status
!= STATUS_PENDING
) HeapFree(GetProcessHeap(), 0, wsa
);
3198 /* If the connect already failed */
3199 if (status
== STATUS_PIPE_DISCONNECTED
)
3200 status
= _get_sock_error(s
, FD_CONNECT_BIT
);
3201 SetLastError( NtStatusToWSAError(status
) );
3209 release_sock_fd( s
, fd
);
3213 release_sock_fd( s
, fd
);
3218 /***********************************************************************
3219 * getpeername (WS2_32.5)
3221 int WINAPI
WS_getpeername(SOCKET s
, struct WS_sockaddr
*name
, int *namelen
)
3226 TRACE("socket %04lx, ptr %p, len %08x\n", s
, name
, namelen
? *namelen
: 0);
3228 fd
= get_sock_fd( s
, 0, NULL
);
3233 union generic_unix_sockaddr uaddr
;
3234 socklen_t uaddrlen
= sizeof(uaddr
);
3236 if (getpeername(fd
, &uaddr
.addr
, &uaddrlen
) == 0)
3238 if (!name
|| !namelen
)
3239 SetLastError(WSAEFAULT
);
3240 else if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
3241 /* The buffer was too small */
3242 SetLastError(WSAEFAULT
);
3246 TRACE("=> %s\n", debugstr_sockaddr(name
));
3250 SetLastError(wsaErrno());
3251 release_sock_fd( s
, fd
);
3256 /* When binding to an UDP address with filter support the getsockname call on the socket
3257 * will always return 0.0.0.0 instead of the filtered interface address. This function
3258 * checks if the socket is interface-bound on UDP and return the correct address.
3259 * This is required because applications often do a bind() with port zero followed by a
3260 * getsockname() to retrieve the port and address acquired.
3262 static void interface_bind_check(int fd
, struct sockaddr_in
*addr
)
3264 #if !defined(IP_BOUND_IF) && !defined(LINUX_BOUND_IF)
3270 /* Check for IPv4, address 0.0.0.0 and UDP socket */
3271 if (addr
->sin_family
!= AF_INET
|| addr
->sin_addr
.s_addr
!= 0)
3273 if (_get_fd_type(fd
) != SOCK_DGRAM
)
3277 len
= sizeof(ifindex
);
3278 #if defined(IP_BOUND_IF)
3279 getsockopt(fd
, IPPROTO_IP
, IP_BOUND_IF
, &ifindex
, &len
);
3280 #elif defined(LINUX_BOUND_IF)
3281 getsockopt(fd
, IPPROTO_IP
, IP_UNICAST_IF
, &ifindex
, &len
);
3282 if (ifindex
> 0) ifindex
= ntohl(ifindex
);
3286 PIP_ADAPTER_INFO adapters
, adapter
;
3289 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
3291 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
3292 if (adapters
&& GetAdaptersInfo(adapters
, &adap_size
) == NO_ERROR
)
3294 /* Search the IPv4 adapter list for the appropriate bound interface */
3295 for (adapter
= adapters
; adapter
!= NULL
; adapter
= adapter
->Next
)
3297 in_addr_t adapter_addr
;
3298 if (adapter
->Index
!= ifindex
) continue;
3300 adapter_addr
= inet_addr(adapter
->IpAddressList
.IpAddress
.String
);
3301 addr
->sin_addr
.s_addr
= adapter_addr
;
3302 TRACE("reporting interface address from adapter %d\n", ifindex
);
3306 HeapFree(GetProcessHeap(), 0, adapters
);
3311 /***********************************************************************
3312 * getsockname (WS2_32.6)
3314 int WINAPI
WS_getsockname(SOCKET s
, struct WS_sockaddr
*name
, int *namelen
)
3319 TRACE("socket %04lx, ptr %p, len %08x\n", s
, name
, namelen
? *namelen
: 0);
3321 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3322 if( (name
== NULL
) || (namelen
== NULL
) )
3324 SetLastError( WSAEFAULT
);
3325 return SOCKET_ERROR
;
3328 fd
= get_sock_fd( s
, 0, NULL
);
3333 union generic_unix_sockaddr uaddr
;
3335 int bound
= is_fd_bound(fd
, &uaddr
, &uaddrlen
);
3339 SetLastError(bound
== -1 ? wsaErrno() : WSAEINVAL
);
3341 else if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
3343 /* The buffer was too small */
3344 SetLastError(WSAEFAULT
);
3348 interface_bind_check(fd
, (struct sockaddr_in
*) &uaddr
);
3349 if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
3351 /* The buffer was too small */
3352 SetLastError(WSAEFAULT
);
3357 TRACE("=> %s\n", debugstr_sockaddr(name
));
3360 release_sock_fd( s
, fd
);
3365 /***********************************************************************
3366 * getsockopt (WS2_32.7)
3368 INT WINAPI
WS_getsockopt(SOCKET s
, INT level
,
3369 INT optname
, char *optval
, INT
*optlen
)
3374 TRACE("(socket %04lx, %s, optval %s, optlen %p (%d))\n", s
,
3375 debugstr_sockopt(level
, optname
), debugstr_optval(optval
, 0),
3376 optlen
, optlen
? *optlen
: 0);
3384 /* Handle common cases. The special cases are below, sorted
3386 case WS_SO_BROADCAST
:
3388 case WS_SO_KEEPALIVE
:
3389 case WS_SO_OOBINLINE
:
3391 case WS_SO_REUSEADDR
:
3393 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3394 return SOCKET_ERROR
;
3395 convert_sockopt(&level
, &optname
);
3396 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3398 SetLastError(wsaErrno());
3401 release_sock_fd( s
, fd
);
3403 case WS_SO_ACCEPTCONN
:
3404 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3405 return SOCKET_ERROR
;
3406 if (getsockopt(fd
, SOL_SOCKET
, SO_ACCEPTCONN
, optval
, (socklen_t
*)optlen
) != 0 )
3408 SetLastError(wsaErrno());
3413 /* BSD returns != 0 while Windows return exact == 1 */
3414 if (*(int *)optval
) *(int *)optval
= 1;
3416 release_sock_fd( s
, fd
);
3418 case WS_SO_BSP_STATE
:
3420 int req_size
, addr_size
;
3421 WSAPROTOCOL_INFOW infow
;
3422 CSADDR_INFO
*csinfo
;
3424 ret
= ws_protocol_info(s
, TRUE
, &infow
, &addr_size
);
3427 if (infow
.iAddressFamily
== WS_AF_INET
)
3428 addr_size
= sizeof(struct sockaddr_in
);
3429 else if (infow
.iAddressFamily
== WS_AF_INET6
)
3430 addr_size
= sizeof(struct sockaddr_in6
);
3433 FIXME("Family %d is unsupported for SO_BSP_STATE\n", infow
.iAddressFamily
);
3434 SetLastError(WSAEAFNOSUPPORT
);
3435 return SOCKET_ERROR
;
3438 req_size
= sizeof(CSADDR_INFO
) + addr_size
* 2;
3439 if (*optlen
< req_size
)
3442 SetLastError(WSAEFAULT
);
3446 union generic_unix_sockaddr uaddr
;
3449 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3450 return SOCKET_ERROR
;
3452 csinfo
= (CSADDR_INFO
*) optval
;
3454 /* Check if the sock is bound */
3455 if (is_fd_bound(fd
, &uaddr
, &uaddrlen
) == 1)
3457 csinfo
->LocalAddr
.lpSockaddr
=
3458 (LPSOCKADDR
) (optval
+ sizeof(CSADDR_INFO
));
3459 ws_sockaddr_u2ws(&uaddr
.addr
, csinfo
->LocalAddr
.lpSockaddr
, &addr_size
);
3460 csinfo
->LocalAddr
.iSockaddrLength
= addr_size
;
3464 csinfo
->LocalAddr
.lpSockaddr
= NULL
;
3465 csinfo
->LocalAddr
.iSockaddrLength
= 0;
3468 /* Check if the sock is connected */
3469 if (!getpeername(fd
, &uaddr
.addr
, &uaddrlen
) &&
3470 is_sockaddr_bound(&uaddr
.addr
, uaddrlen
))
3472 csinfo
->RemoteAddr
.lpSockaddr
=
3473 (LPSOCKADDR
) (optval
+ sizeof(CSADDR_INFO
) + addr_size
);
3474 ws_sockaddr_u2ws(&uaddr
.addr
, csinfo
->RemoteAddr
.lpSockaddr
, &addr_size
);
3475 csinfo
->RemoteAddr
.iSockaddrLength
= addr_size
;
3479 csinfo
->RemoteAddr
.lpSockaddr
= NULL
;
3480 csinfo
->RemoteAddr
.iSockaddrLength
= 0;
3483 csinfo
->iSocketType
= infow
.iSocketType
;
3484 csinfo
->iProtocol
= infow
.iProtocol
;
3485 release_sock_fd( s
, fd
);
3488 return ret
? 0 : SOCKET_ERROR
;
3490 case WS_SO_DONTLINGER
:
3492 struct linger lingval
;
3493 socklen_t len
= sizeof(struct linger
);
3495 if (!optlen
|| *optlen
< sizeof(BOOL
)|| !optval
)
3497 SetLastError(WSAEFAULT
);
3498 return SOCKET_ERROR
;
3500 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3501 return SOCKET_ERROR
;
3503 if (getsockopt(fd
, SOL_SOCKET
, SO_LINGER
, &lingval
, &len
) != 0 )
3505 SetLastError(wsaErrno());
3510 *(BOOL
*)optval
= !lingval
.l_onoff
;
3511 *optlen
= sizeof(BOOL
);
3514 release_sock_fd( s
, fd
);
3518 case WS_SO_CONNECT_TIME
:
3520 static int pretendtime
= 0;
3521 struct WS_sockaddr addr
;
3522 int len
= sizeof(addr
);
3524 if (!optlen
|| *optlen
< sizeof(DWORD
) || !optval
)
3526 SetLastError(WSAEFAULT
);
3527 return SOCKET_ERROR
;
3529 if (WS_getpeername(s
, &addr
, &len
) == SOCKET_ERROR
)
3530 *(DWORD
*)optval
= ~0u;
3533 if (!pretendtime
) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3534 *(DWORD
*)optval
= pretendtime
++;
3536 *optlen
= sizeof(DWORD
);
3539 /* As mentioned in setsockopt, Windows ignores this, so we
3540 * always return true here */
3541 case WS_SO_DONTROUTE
:
3542 if (!optlen
|| *optlen
< sizeof(BOOL
) || !optval
)
3544 SetLastError(WSAEFAULT
);
3545 return SOCKET_ERROR
;
3547 *(BOOL
*)optval
= TRUE
;
3548 *optlen
= sizeof(BOOL
);
3553 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3554 return SOCKET_ERROR
;
3555 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, optval
, (socklen_t
*)optlen
) != 0 )
3557 SetLastError(wsaErrno());
3560 release_sock_fd( s
, fd
);
3562 /* The wineserver may have swallowed the error before us */
3563 if (!ret
&& *(int*) optval
== 0)
3565 int i
, events
[FD_MAX_EVENTS
];
3566 _get_sock_errors(s
, events
);
3567 for (i
= 0; i
< FD_MAX_EVENTS
; i
++)
3571 events
[i
] = NtStatusToWSAError(events
[i
]);
3572 TRACE("returning SO_ERROR %d from wine server\n", events
[i
]);
3573 *(int*) optval
= events
[i
];
3583 struct linger lingval
;
3584 socklen_t len
= sizeof(struct linger
);
3586 /* struct linger and LINGER have different sizes */
3587 if (!optlen
|| *optlen
< sizeof(LINGER
) || !optval
)
3589 SetLastError(WSAEFAULT
);
3590 return SOCKET_ERROR
;
3592 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3593 return SOCKET_ERROR
;
3595 if (_get_fd_type(fd
) == SOCK_DGRAM
)
3597 SetLastError(WSAENOPROTOOPT
);
3600 else if (getsockopt(fd
, SOL_SOCKET
, SO_LINGER
, &lingval
, &len
) != 0)
3602 SetLastError(wsaErrno());
3607 ((LINGER
*)optval
)->l_onoff
= lingval
.l_onoff
;
3608 ((LINGER
*)optval
)->l_linger
= lingval
.l_linger
;
3609 *optlen
= sizeof(struct linger
);
3612 release_sock_fd( s
, fd
);
3616 case WS_SO_MAX_MSG_SIZE
:
3617 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
3619 SetLastError(WSAEFAULT
);
3620 return SOCKET_ERROR
;
3622 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3623 *(int *)optval
= 65507;
3624 *optlen
= sizeof(int);
3627 /* SO_OPENTYPE does not require a valid socket handle. */
3628 case WS_SO_OPENTYPE
:
3629 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
3631 SetLastError(WSAEFAULT
);
3632 return SOCKET_ERROR
;
3634 *(int *)optval
= get_per_thread_data()->opentype
;
3635 *optlen
= sizeof(int);
3636 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval
) );
3638 case WS_SO_PROTOCOL_INFOA
:
3639 case WS_SO_PROTOCOL_INFOW
:
3642 WSAPROTOCOL_INFOW infow
;
3644 ret
= ws_protocol_info(s
, optname
== WS_SO_PROTOCOL_INFOW
, &infow
, &size
);
3647 if (!optlen
|| !optval
|| *optlen
< size
)
3649 if(optlen
) *optlen
= size
;
3651 SetLastError(WSAEFAULT
);
3654 memcpy(optval
, &infow
, size
);
3656 return ret
? 0 : SOCKET_ERROR
;
3658 case WS_SO_RCVTIMEO
:
3659 case WS_SO_SNDTIMEO
:
3663 if (!optlen
|| *optlen
< sizeof(int)|| !optval
)
3665 SetLastError(WSAEFAULT
);
3666 return SOCKET_ERROR
;
3668 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3669 return SOCKET_ERROR
;
3671 timeout
= get_rcvsnd_timeo(fd
, optname
== WS_SO_RCVTIMEO
);
3672 *(int *)optval
= timeout
<= UINT_MAX
? timeout
: UINT_MAX
;
3674 release_sock_fd( s
, fd
);
3680 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
3682 SetLastError(WSAEFAULT
);
3683 return SOCKET_ERROR
;
3685 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3686 return SOCKET_ERROR
;
3688 sock_type
= _get_fd_type(fd
);
3689 if (sock_type
== -1)
3691 SetLastError(wsaErrno());
3695 (*(int *)optval
) = convert_socktype_u2w(sock_type
);
3697 release_sock_fd( s
, fd
);
3701 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname
);
3702 SetLastError(WSAENOPROTOOPT
);
3703 return SOCKET_ERROR
;
3704 } /* end switch(optname) */
3705 }/* end case WS_SOL_SOCKET */
3707 case WS_NSPROTO_IPX
:
3709 struct WS_sockaddr_ipx addr
;
3710 IPX_ADDRESS_DATA
*data
;
3715 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
3717 if(getsockopt(fd
, SOL_IPX
, IPX_TYPE
, optval
, (socklen_t
*)optlen
) == -1)
3724 socklen_t len
=sizeof(struct ipx
);
3725 if(getsockopt(fd
, 0, SO_DEFAULT_HEADERS
, &val
, &len
) == -1 )
3728 *optval
= (int)val
.ipx_pt
;
3731 TRACE("ptype: %d (fd: %d)\n", *(int*)optval
, fd
);
3732 release_sock_fd( s
, fd
);
3735 case WS_IPX_ADDRESS
:
3737 * On a Win2000 system with one network card there are usually
3738 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
3739 * Using this call you can then retrieve info about this all.
3740 * In case of Linux it is a bit different. Usually you have
3741 * only "one" device active and further it is not possible to
3742 * query things like the linkspeed.
3744 FIXME("IPX_ADDRESS\n");
3745 namelen
= sizeof(struct WS_sockaddr_ipx
);
3746 memset(&addr
, 0, sizeof(struct WS_sockaddr_ipx
));
3747 WS_getsockname(s
, (struct WS_sockaddr
*)&addr
, &namelen
);
3749 data
= (IPX_ADDRESS_DATA
*)optval
;
3750 memcpy(data
->nodenum
,addr
.sa_nodenum
,sizeof(data
->nodenum
));
3751 memcpy(data
->netnum
,addr
.sa_netnum
,sizeof(data
->netnum
));
3752 data
->adapternum
= 0;
3753 data
->wan
= FALSE
; /* We are not on a wan for now .. */
3754 data
->status
= FALSE
; /* Since we are not on a wan, the wan link isn't up */
3755 data
->maxpkt
= 1467; /* This value is the default one, at least on Win2k/WinXP */
3756 data
->linkspeed
= 100000; /* Set the line speed in 100bit/s to 10 Mbit;
3757 * note 1MB = 1000kB in this case */
3760 case WS_IPX_MAX_ADAPTER_NUM
:
3761 FIXME("IPX_MAX_ADAPTER_NUM\n");
3762 *(int*)optval
= 1; /* As noted under IPX_ADDRESS we have just one card. */
3766 FIXME("IPX optname:%x\n", optname
);
3767 return SOCKET_ERROR
;
3768 }/* end switch(optname) */
3769 } /* end case WS_NSPROTO_IPX */
3773 #define MAX_IRDA_DEVICES 10
3778 case WS_IRLMP_ENUMDEVICES
:
3780 char buf
[sizeof(struct irda_device_list
) +
3781 (MAX_IRDA_DEVICES
- 1) * sizeof(struct irda_device_info
)];
3783 socklen_t len
= sizeof(buf
);
3785 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3786 return SOCKET_ERROR
;
3787 res
= getsockopt( fd
, SOL_IRLMP
, IRLMP_ENUMDEVICES
, buf
, &len
);
3788 release_sock_fd( s
, fd
);
3791 SetLastError(wsaErrno());
3792 return SOCKET_ERROR
;
3796 struct irda_device_list
*src
= (struct irda_device_list
*)buf
;
3797 DEVICELIST
*dst
= (DEVICELIST
*)optval
;
3798 INT needed
= sizeof(DEVICELIST
);
3802 needed
+= (src
->len
- 1) * sizeof(IRDA_DEVICE_INFO
);
3803 if (*optlen
< needed
)
3805 SetLastError(WSAEFAULT
);
3806 return SOCKET_ERROR
;
3809 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src
->len
);
3810 dst
->numDevice
= src
->len
;
3811 for (i
= 0; i
< src
->len
; i
++)
3813 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
3814 src
->dev
[i
].saddr
, src
->dev
[i
].daddr
,
3815 src
->dev
[i
].info
, src
->dev
[i
].hints
[0],
3816 src
->dev
[i
].hints
[1]);
3817 memcpy( dst
->Device
[i
].irdaDeviceID
,
3819 sizeof(dst
->Device
[i
].irdaDeviceID
) ) ;
3820 memcpy( dst
->Device
[i
].irdaDeviceName
,
3822 sizeof(dst
->Device
[i
].irdaDeviceName
) ) ;
3823 memcpy( &dst
->Device
[i
].irdaDeviceHints1
,
3824 &src
->dev
[i
].hints
[0],
3825 sizeof(dst
->Device
[i
].irdaDeviceHints1
) ) ;
3826 memcpy( &dst
->Device
[i
].irdaDeviceHints2
,
3827 &src
->dev
[i
].hints
[1],
3828 sizeof(dst
->Device
[i
].irdaDeviceHints2
) ) ;
3829 dst
->Device
[i
].irdaCharSet
= src
->dev
[i
].charset
;
3835 FIXME("IrDA optname:0x%x\n", optname
);
3836 return SOCKET_ERROR
;
3838 break; /* case WS_SOL_IRLMP */
3839 #undef MAX_IRDA_DEVICES
3842 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3843 case WS_IPPROTO_TCP
:
3846 case WS_TCP_NODELAY
:
3847 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3848 return SOCKET_ERROR
;
3849 convert_sockopt(&level
, &optname
);
3850 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3852 SetLastError(wsaErrno());
3855 release_sock_fd( s
, fd
);
3858 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname
);
3859 return SOCKET_ERROR
;
3864 case WS_IP_ADD_MEMBERSHIP
:
3865 case WS_IP_DROP_MEMBERSHIP
:
3869 case WS_IP_MULTICAST_IF
:
3870 case WS_IP_MULTICAST_LOOP
:
3871 case WS_IP_MULTICAST_TTL
:
3878 #ifdef IP_UNICAST_IF
3879 case WS_IP_UNICAST_IF
:
3881 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3882 return SOCKET_ERROR
;
3883 convert_sockopt(&level
, &optname
);
3884 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3886 SetLastError(wsaErrno());
3889 release_sock_fd( s
, fd
);
3891 case WS_IP_DONTFRAGMENT
:
3892 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
3893 *(BOOL
*)optval
= FALSE
;
3896 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname
);
3897 return SOCKET_ERROR
;
3899 case WS_IPPROTO_IPV6
:
3902 #ifdef IPV6_ADD_MEMBERSHIP
3903 case WS_IPV6_ADD_MEMBERSHIP
:
3905 #ifdef IPV6_DROP_MEMBERSHIP
3906 case WS_IPV6_DROP_MEMBERSHIP
:
3908 case WS_IPV6_MULTICAST_IF
:
3909 case WS_IPV6_MULTICAST_HOPS
:
3910 case WS_IPV6_MULTICAST_LOOP
:
3911 case WS_IPV6_UNICAST_HOPS
:
3912 case WS_IPV6_V6ONLY
:
3913 #ifdef IPV6_UNICAST_IF
3914 case WS_IPV6_UNICAST_IF
:
3916 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3917 return SOCKET_ERROR
;
3918 convert_sockopt(&level
, &optname
);
3919 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3921 SetLastError(wsaErrno());
3924 release_sock_fd( s
, fd
);
3926 case WS_IPV6_DONTFRAG
:
3927 FIXME("WS_IPV6_DONTFRAG is always false!\n");
3928 *(BOOL
*)optval
= FALSE
;
3931 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname
);
3932 return SOCKET_ERROR
;
3935 WARN("Unknown level: 0x%08x\n", level
);
3936 SetLastError(WSAEINVAL
);
3937 return SOCKET_ERROR
;
3938 } /* end switch(level) */
3941 /***********************************************************************
3944 WS_u_long WINAPI
WS_htonl(WS_u_long hostlong
)
3946 return htonl(hostlong
);
3950 /***********************************************************************
3953 WS_u_short WINAPI
WS_htons(WS_u_short hostshort
)
3955 return htons(hostshort
);
3958 /***********************************************************************
3959 * WSAHtonl (WS2_32.46)
3960 * From MSDN description of error codes, this function should also
3961 * check if WinSock has been initialized and the socket is a valid
3962 * socket. But why? This function only translates a host byte order
3963 * u_long into a network byte order u_long...
3965 int WINAPI
WSAHtonl(SOCKET s
, WS_u_long hostlong
, WS_u_long
*lpnetlong
)
3969 *lpnetlong
= htonl(hostlong
);
3972 SetLastError(WSAEFAULT
);
3973 return SOCKET_ERROR
;
3976 /***********************************************************************
3977 * WSAHtons (WS2_32.47)
3978 * From MSDN description of error codes, this function should also
3979 * check if WinSock has been initialized and the socket is a valid
3980 * socket. But why? This function only translates a host byte order
3981 * u_short into a network byte order u_short...
3983 int WINAPI
WSAHtons(SOCKET s
, WS_u_short hostshort
, WS_u_short
*lpnetshort
)
3988 *lpnetshort
= htons(hostshort
);
3991 SetLastError(WSAEFAULT
);
3992 return SOCKET_ERROR
;
3996 /***********************************************************************
3997 * inet_addr (WS2_32.11)
3999 WS_u_long WINAPI
WS_inet_addr(const char *cp
)
4001 if (!cp
) return INADDR_NONE
;
4002 return inet_addr(cp
);
4006 /***********************************************************************
4009 WS_u_long WINAPI
WS_ntohl(WS_u_long netlong
)
4011 return ntohl(netlong
);
4015 /***********************************************************************
4018 WS_u_short WINAPI
WS_ntohs(WS_u_short netshort
)
4020 return ntohs(netshort
);
4024 /***********************************************************************
4025 * inet_ntoa (WS2_32.12)
4027 char* WINAPI
WS_inet_ntoa(struct WS_in_addr in
)
4029 struct per_thread_data
*data
= get_per_thread_data();
4031 sprintf( data
->ntoa_buffer
, "%u.%u.%u.%u",
4032 (unsigned int)(ntohl( in
.WS_s_addr
) >> 24 & 0xff),
4033 (unsigned int)(ntohl( in
.WS_s_addr
) >> 16 & 0xff),
4034 (unsigned int)(ntohl( in
.WS_s_addr
) >> 8 & 0xff),
4035 (unsigned int)(ntohl( in
.WS_s_addr
) & 0xff) );
4037 return data
->ntoa_buffer
;
4040 static const char *debugstr_wsaioctl(DWORD ioctl
)
4042 const char *buf_type
, *family
;
4044 switch(ioctl
& 0x18000000)
4049 case WS_IOC_PROTOCOL
:
4050 family
= "IOC_PROTOCOL";
4053 family
= "IOC_VENDOR";
4055 default: /* WS_IOC_UNIX */
4057 BYTE size
= (ioctl
>> 16) & WS_IOCPARM_MASK
;
4058 char x
= (ioctl
& 0xff00) >> 8;
4059 BYTE y
= ioctl
& 0xff;
4062 switch (ioctl
& (WS_IOC_VOID
|WS_IOC_INOUT
))
4066 sprintf(args
, "%d, %d", x
, y
);
4070 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
4074 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
4078 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
4081 return wine_dbg_sprintf("%s(%s)", buf_type
, args
);
4085 /* We are different from WS_IOC_UNIX. */
4086 switch (ioctl
& (WS_IOC_VOID
|WS_IOC_INOUT
))
4089 buf_type
= "_WSAIO";
4092 buf_type
= "_WSAIORW";
4095 buf_type
= "_WSAIOW";
4098 buf_type
= "_WSAIOR";
4105 return wine_dbg_sprintf("%s(%s, %d)", buf_type
, family
,
4106 (USHORT
)(ioctl
& 0xffff));
4109 /* do an ioctl call through the server */
4110 static DWORD
server_ioctl_sock( SOCKET s
, DWORD code
, LPVOID in_buff
, DWORD in_size
,
4111 LPVOID out_buff
, DWORD out_size
, LPDWORD ret_size
,
4112 LPWSAOVERLAPPED overlapped
,
4113 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
4115 HANDLE event
= overlapped
? overlapped
->hEvent
: 0;
4116 HANDLE handle
= SOCKET2HANDLE( s
);
4117 struct ws2_async
*wsa
;
4119 PIO_STATUS_BLOCK io
;
4121 if (!(wsa
= (struct ws2_async
*)alloc_async_io( sizeof(*wsa
) )))
4122 return WSA_NOT_ENOUGH_MEMORY
;
4123 wsa
->hSocket
= handle
;
4124 wsa
->user_overlapped
= overlapped
;
4125 wsa
->completion_func
= completion
;
4126 io
= (overlapped
? (PIO_STATUS_BLOCK
)overlapped
: &wsa
->local_iosb
);
4128 status
= NtDeviceIoControlFile( handle
, event
, ws2_async_apc
, wsa
, io
, code
,
4129 in_buff
, in_size
, out_buff
, out_size
);
4130 if (status
== STATUS_NOT_SUPPORTED
)
4132 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
4133 code
, code
>> 16, (code
>> 14) & 3, (code
>> 2) & 0xfff, code
& 3);
4135 else if (status
== STATUS_SUCCESS
)
4136 *ret_size
= io
->Information
; /* "Information" is the size written to the output buffer */
4138 if (status
!= STATUS_PENDING
) RtlFreeHeap( GetProcessHeap(), 0, wsa
);
4140 return NtStatusToWSAError( status
);
4143 /**********************************************************************
4144 * WSAIoctl (WS2_32.50)
4147 INT WINAPI
WSAIoctl(SOCKET s
, DWORD code
, LPVOID in_buff
, DWORD in_size
, LPVOID out_buff
,
4148 DWORD out_size
, LPDWORD ret_size
, LPWSAOVERLAPPED overlapped
,
4149 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
4152 DWORD status
= 0, total
= 0;
4154 TRACE("%04lx, %s, %p, %d, %p, %d, %p, %p, %p\n",
4155 s
, debugstr_wsaioctl(code
), in_buff
, in_size
, out_buff
, out_size
, ret_size
, overlapped
, completion
);
4160 if (in_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(in_buff
))
4162 SetLastError(WSAEFAULT
);
4163 return SOCKET_ERROR
;
4165 TRACE("-> FIONBIO (%x)\n", *(WS_u_long
*)in_buff
);
4166 if (_get_sock_mask(s
))
4168 /* AsyncSelect()'ed sockets are always nonblocking */
4169 if (!*(WS_u_long
*)in_buff
) status
= WSAEINVAL
;
4172 if (*(WS_u_long
*)in_buff
)
4173 _enable_event(SOCKET2HANDLE(s
), 0, FD_WINE_NONBLOCKING
, 0);
4175 _enable_event(SOCKET2HANDLE(s
), 0, 0, FD_WINE_NONBLOCKING
);
4180 if (out_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(out_buff
))
4182 SetLastError(WSAEFAULT
);
4183 return SOCKET_ERROR
;
4185 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
4186 if (ioctl(fd
, FIONREAD
, out_buff
) == -1)
4187 status
= wsaErrno();
4188 release_sock_fd( s
, fd
);
4194 unsigned int oob
= 0, atmark
= 0;
4195 socklen_t oobsize
= sizeof(int);
4196 if (out_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(out_buff
))
4198 SetLastError(WSAEFAULT
);
4199 return SOCKET_ERROR
;
4201 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
4202 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
4203 if ((getsockopt(fd
, SOL_SOCKET
, SO_OOBINLINE
, &oob
, &oobsize
) == -1)
4204 || (!oob
&& ioctl(fd
, SIOCATMARK
, &atmark
) == -1))
4205 status
= wsaErrno();
4208 /* The SIOCATMARK value read from ioctl() is reversed
4209 * because BSD returns TRUE if it's in the OOB mark
4210 * while Windows returns TRUE if there are NO OOB bytes.
4212 (*(WS_u_long
*) out_buff
) = oob
|| !atmark
;
4215 release_sock_fd( s
, fd
);
4220 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
4221 SetLastError(WSAEINVAL
);
4222 return SOCKET_ERROR
;
4224 case WS_SIO_GET_INTERFACE_LIST
:
4226 INTERFACE_INFO
* intArray
= out_buff
;
4227 DWORD size
, numInt
= 0, apiReturn
;
4229 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
4231 if (!out_buff
|| !ret_size
)
4233 SetLastError(WSAEFAULT
);
4234 return SOCKET_ERROR
;
4237 fd
= get_sock_fd( s
, 0, NULL
);
4238 if (fd
== -1) return SOCKET_ERROR
;
4240 apiReturn
= GetAdaptersInfo(NULL
, &size
);
4241 if (apiReturn
== ERROR_BUFFER_OVERFLOW
)
4243 PIP_ADAPTER_INFO table
= HeapAlloc(GetProcessHeap(),0,size
);
4247 if (GetAdaptersInfo(table
, &size
) == NO_ERROR
)
4249 PIP_ADAPTER_INFO ptr
;
4251 for (ptr
= table
, numInt
= 0; ptr
; ptr
= ptr
->Next
)
4253 unsigned int addr
, mask
, bcast
;
4254 struct ifreq ifInfo
;
4256 /* Skip interfaces without an IPv4 address. */
4257 if (ptr
->IpAddressList
.IpAddress
.String
[0] == '\0')
4260 if ((numInt
+ 1)*sizeof(INTERFACE_INFO
)/sizeof(IP_ADAPTER_INFO
) > out_size
)
4262 WARN("Buffer too small = %u, out_size = %u\n", numInt
+ 1, out_size
);
4267 /* Socket Status Flags */
4268 lstrcpynA(ifInfo
.ifr_name
, ptr
->AdapterName
, IFNAMSIZ
);
4269 if (ioctl(fd
, SIOCGIFFLAGS
, &ifInfo
) < 0)
4271 ERR("Error obtaining status flags for socket!\n");
4277 /* set flags; the values of IFF_* are not the same
4278 under Linux and Windows, therefore must generate
4280 intArray
->iiFlags
= 0;
4281 if (ifInfo
.ifr_flags
& IFF_BROADCAST
)
4282 intArray
->iiFlags
|= WS_IFF_BROADCAST
;
4283 #ifdef IFF_POINTOPOINT
4284 if (ifInfo
.ifr_flags
& IFF_POINTOPOINT
)
4285 intArray
->iiFlags
|= WS_IFF_POINTTOPOINT
;
4287 if (ifInfo
.ifr_flags
& IFF_LOOPBACK
)
4288 intArray
->iiFlags
|= WS_IFF_LOOPBACK
;
4289 if (ifInfo
.ifr_flags
& IFF_UP
)
4290 intArray
->iiFlags
|= WS_IFF_UP
;
4291 if (ifInfo
.ifr_flags
& IFF_MULTICAST
)
4292 intArray
->iiFlags
|= WS_IFF_MULTICAST
;
4295 addr
= inet_addr(ptr
->IpAddressList
.IpAddress
.String
);
4296 mask
= inet_addr(ptr
->IpAddressList
.IpMask
.String
);
4297 bcast
= addr
| ~mask
;
4298 intArray
->iiAddress
.AddressIn
.sin_family
= AF_INET
;
4299 intArray
->iiAddress
.AddressIn
.sin_port
= 0;
4300 intArray
->iiAddress
.AddressIn
.sin_addr
.WS_s_addr
=
4302 intArray
->iiNetmask
.AddressIn
.sin_family
= AF_INET
;
4303 intArray
->iiNetmask
.AddressIn
.sin_port
= 0;
4304 intArray
->iiNetmask
.AddressIn
.sin_addr
.WS_s_addr
=
4306 intArray
->iiBroadcastAddress
.AddressIn
.sin_family
=
4308 intArray
->iiBroadcastAddress
.AddressIn
.sin_port
= 0;
4309 intArray
->iiBroadcastAddress
.AddressIn
.sin_addr
.
4317 ERR("Unable to get interface table!\n");
4320 HeapFree(GetProcessHeap(),0,table
);
4322 else status
= WSAEINVAL
;
4324 else if (apiReturn
!= ERROR_NO_DATA
)
4326 ERR("Unable to get interface table!\n");
4329 /* Calculate the size of the array being returned */
4330 total
= sizeof(INTERFACE_INFO
) * numInt
;
4331 release_sock_fd( s
, fd
);
4335 case WS_SIO_ADDRESS_LIST_QUERY
:
4339 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
4343 SetLastError(WSAEFAULT
);
4344 return SOCKET_ERROR
;
4347 if (out_size
&& out_size
< FIELD_OFFSET(SOCKET_ADDRESS_LIST
, Address
[0]))
4350 SetLastError(WSAEINVAL
);
4351 return SOCKET_ERROR
;
4354 if (GetAdaptersInfo(NULL
, &size
) == ERROR_BUFFER_OVERFLOW
)
4356 IP_ADAPTER_INFO
*p
, *table
= HeapAlloc(GetProcessHeap(), 0, size
);
4357 SOCKET_ADDRESS_LIST
*sa_list
;
4358 SOCKADDR_IN
*sockaddr
;
4363 if (!table
|| GetAdaptersInfo(table
, &size
))
4365 HeapFree(GetProcessHeap(), 0, table
);
4370 for (p
= table
, num
= 0; p
; p
= p
->Next
)
4371 if (p
->IpAddressList
.IpAddress
.String
[0]) num
++;
4373 total
= FIELD_OFFSET(SOCKET_ADDRESS_LIST
, Address
[num
]) + num
* sizeof(*sockaddr
);
4374 if (total
> out_size
|| !out_buff
)
4377 HeapFree(GetProcessHeap(), 0, table
);
4383 sa
= sa_list
->Address
;
4384 sockaddr
= (SOCKADDR_IN
*)&sa
[num
];
4385 sa_list
->iAddressCount
= num
;
4387 for (p
= table
, i
= 0; p
; p
= p
->Next
)
4389 if (!p
->IpAddressList
.IpAddress
.String
[0]) continue;
4391 sa
[i
].lpSockaddr
= (SOCKADDR
*)&sockaddr
[i
];
4392 sa
[i
].iSockaddrLength
= sizeof(SOCKADDR
);
4394 sockaddr
[i
].sin_family
= AF_INET
;
4395 sockaddr
[i
].sin_port
= 0;
4396 sockaddr
[i
].sin_addr
.WS_s_addr
= inet_addr(p
->IpAddressList
.IpAddress
.String
);
4400 HeapFree(GetProcessHeap(), 0, table
);
4404 WARN("unable to get IP address list\n");
4411 FIXME("SIO_FLUSH: stub.\n");
4414 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER
:
4416 static const GUID connectex_guid
= WSAID_CONNECTEX
;
4417 static const GUID disconnectex_guid
= WSAID_DISCONNECTEX
;
4418 static const GUID acceptex_guid
= WSAID_ACCEPTEX
;
4419 static const GUID getaccepexsockaddrs_guid
= WSAID_GETACCEPTEXSOCKADDRS
;
4420 static const GUID transmitfile_guid
= WSAID_TRANSMITFILE
;
4421 static const GUID transmitpackets_guid
= WSAID_TRANSMITPACKETS
;
4422 static const GUID wsarecvmsg_guid
= WSAID_WSARECVMSG
;
4423 static const GUID wsasendmsg_guid
= WSAID_WSASENDMSG
;
4425 if ( IsEqualGUID(&connectex_guid
, in_buff
) )
4427 *(LPFN_CONNECTEX
*)out_buff
= WS2_ConnectEx
;
4430 else if ( IsEqualGUID(&disconnectex_guid
, in_buff
) )
4432 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
4434 else if ( IsEqualGUID(&acceptex_guid
, in_buff
) )
4436 *(LPFN_ACCEPTEX
*)out_buff
= WS2_AcceptEx
;
4439 else if ( IsEqualGUID(&getaccepexsockaddrs_guid
, in_buff
) )
4441 *(LPFN_GETACCEPTEXSOCKADDRS
*)out_buff
= WS2_GetAcceptExSockaddrs
;
4444 else if ( IsEqualGUID(&transmitfile_guid
, in_buff
) )
4446 *(LPFN_TRANSMITFILE
*)out_buff
= WS2_TransmitFile
;
4449 else if ( IsEqualGUID(&transmitpackets_guid
, in_buff
) )
4451 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
4453 else if ( IsEqualGUID(&wsarecvmsg_guid
, in_buff
) )
4455 *(LPFN_WSARECVMSG
*)out_buff
= WS2_WSARecvMsg
;
4458 else if ( IsEqualGUID(&wsasendmsg_guid
, in_buff
) )
4460 *(LPFN_WSASENDMSG
*)out_buff
= WSASendMsg
;
4464 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff
));
4466 status
= WSAEOPNOTSUPP
;
4469 case WS_SIO_KEEPALIVE_VALS
:
4471 struct tcp_keepalive
*k
;
4472 int keepalive
, keepidle
, keepintvl
;
4474 if (!in_buff
|| in_size
< sizeof(struct tcp_keepalive
))
4476 SetLastError(WSAEFAULT
);
4477 return SOCKET_ERROR
;
4481 keepalive
= k
->onoff
? 1 : 0;
4482 keepidle
= max( 1, (k
->keepalivetime
+ 500) / 1000 );
4483 keepintvl
= max( 1, (k
->keepaliveinterval
+ 500) / 1000 );
4485 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive
, keepidle
, keepintvl
);
4487 fd
= get_sock_fd(s
, 0, NULL
);
4488 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&keepalive
, sizeof(int)) == -1)
4490 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPINTVL)
4491 /* these values need to be set only if SO_KEEPALIVE is enabled */
4494 #ifndef TCP_KEEPIDLE
4495 FIXME("ignoring keepalive timeout\n");
4497 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPIDLE
, (void *)&keepidle
, sizeof(int)) == -1)
4501 #ifdef TCP_KEEPINTVL
4502 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPINTVL
, (void *)&keepintvl
, sizeof(int)) == -1)
4505 FIXME("ignoring keepalive interval\n");
4510 FIXME("ignoring keepalive interval and timeout\n");
4512 release_sock_fd(s
, fd
);
4515 case WS_SIO_ROUTING_INTERFACE_QUERY
:
4517 struct WS_sockaddr
*daddr
= (struct WS_sockaddr
*)in_buff
;
4518 struct WS_sockaddr_in
*daddr_in
= (struct WS_sockaddr_in
*)daddr
;
4519 struct WS_sockaddr_in
*saddr_in
= out_buff
;
4520 MIB_IPFORWARDROW row
;
4521 PMIB_IPADDRTABLE ipAddrTable
= NULL
;
4522 DWORD size
, i
, found_index
;
4524 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4526 if (!in_buff
|| in_size
< sizeof(struct WS_sockaddr
) ||
4527 !out_buff
|| out_size
< sizeof(struct WS_sockaddr_in
) || !ret_size
)
4529 SetLastError(WSAEFAULT
);
4530 return SOCKET_ERROR
;
4532 if (daddr
->sa_family
!= AF_INET
)
4534 FIXME("unsupported address family %d\n", daddr
->sa_family
);
4535 status
= WSAEAFNOSUPPORT
;
4538 if (GetBestRoute(daddr_in
->sin_addr
.S_un
.S_addr
, 0, &row
) != NOERROR
||
4539 GetIpAddrTable(NULL
, &size
, FALSE
) != ERROR_INSUFFICIENT_BUFFER
)
4544 ipAddrTable
= HeapAlloc(GetProcessHeap(), 0, size
);
4545 if (GetIpAddrTable(ipAddrTable
, &size
, FALSE
))
4547 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
4551 for (i
= 0, found_index
= ipAddrTable
->dwNumEntries
;
4552 i
< ipAddrTable
->dwNumEntries
; i
++)
4554 if (ipAddrTable
->table
[i
].dwIndex
== row
.dwForwardIfIndex
)
4557 if (found_index
== ipAddrTable
->dwNumEntries
)
4559 ERR("no matching IP address for interface %d\n",
4560 row
.dwForwardIfIndex
);
4561 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
4565 saddr_in
->sin_family
= AF_INET
;
4566 saddr_in
->sin_addr
.S_un
.S_addr
= ipAddrTable
->table
[found_index
].dwAddr
;
4567 saddr_in
->sin_port
= 0;
4568 total
= sizeof(struct WS_sockaddr_in
);
4569 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
4572 case WS_SIO_SET_COMPATIBILITY_MODE
:
4573 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4574 status
= WSAEOPNOTSUPP
;
4576 case WS_SIO_UDP_CONNRESET
:
4577 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4579 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4580 SetLastError(WSAEOPNOTSUPP
);
4581 return SOCKET_ERROR
;
4583 status
= WSAEOPNOTSUPP
;
4587 if (status
== WSAEOPNOTSUPP
)
4589 status
= server_ioctl_sock(s
, code
, in_buff
, in_size
, out_buff
, out_size
, &total
,
4590 overlapped
, completion
);
4591 if (status
!= WSAEOPNOTSUPP
)
4593 if (status
== 0 || status
== WSA_IO_PENDING
)
4594 TRACE("-> %s request\n", debugstr_wsaioctl(code
));
4596 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code
), status
);
4598 /* overlapped and completion operations will be handled by the server */
4603 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code
));
4608 FIXME( "completion routine %p not supported\n", completion
);
4610 else if (overlapped
)
4612 ULONG_PTR cvalue
= (overlapped
&& ((ULONG_PTR
)overlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)overlapped
: 0;
4613 overlapped
->Internal
= status
;
4614 overlapped
->InternalHigh
= total
;
4615 if (overlapped
->hEvent
) NtSetEvent( overlapped
->hEvent
, NULL
);
4616 if (cvalue
) WS_AddCompletion( HANDLE2SOCKET(s
), cvalue
, status
, total
);
4621 if (ret_size
) *ret_size
= total
;
4624 SetLastError( status
);
4625 return SOCKET_ERROR
;
4629 /***********************************************************************
4630 * ioctlsocket (WS2_32.10)
4632 int WINAPI
WS_ioctlsocket(SOCKET s
, LONG cmd
, WS_u_long
*argp
)
4635 return WSAIoctl( s
, cmd
, argp
, sizeof(WS_u_long
), argp
, sizeof(WS_u_long
), &ret_size
, NULL
, NULL
);
4638 /***********************************************************************
4639 * listen (WS2_32.13)
4641 int WINAPI
WS_listen(SOCKET s
, int backlog
)
4643 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
), ret
= SOCKET_ERROR
;
4645 TRACE("socket %04lx, backlog %d\n", s
, backlog
);
4648 int bound
= is_fd_bound(fd
, NULL
, NULL
);
4652 SetLastError(bound
== -1 ? wsaErrno() : WSAEINVAL
);
4654 else if (listen(fd
, backlog
) == 0)
4656 _enable_event(SOCKET2HANDLE(s
), FD_ACCEPT
,
4658 FD_CONNECT
|FD_WINE_CONNECTED
);
4662 SetLastError(wsaErrno());
4663 release_sock_fd( s
, fd
);
4666 SetLastError(WSAENOTSOCK
);
4670 /***********************************************************************
4673 int WINAPI
WS_recv(SOCKET s
, char *buf
, int len
, int flags
)
4675 DWORD n
, dwFlags
= flags
;
4681 if ( WS2_recv_base(s
, &wsabuf
, 1, &n
, &dwFlags
, NULL
, NULL
, NULL
, NULL
, NULL
) == SOCKET_ERROR
)
4682 return SOCKET_ERROR
;
4687 /***********************************************************************
4688 * recvfrom (WS2_32.17)
4690 int WINAPI
WS_recvfrom(SOCKET s
, char *buf
, INT len
, int flags
,
4691 struct WS_sockaddr
*from
, int *fromlen
)
4693 DWORD n
, dwFlags
= flags
;
4699 if ( WS2_recv_base(s
, &wsabuf
, 1, &n
, &dwFlags
, from
, fromlen
, NULL
, NULL
, NULL
) == SOCKET_ERROR
)
4700 return SOCKET_ERROR
;
4705 /* allocate a poll array for the corresponding fd sets */
4706 static struct pollfd
*fd_sets_to_poll( const WS_fd_set
*readfds
, const WS_fd_set
*writefds
,
4707 const WS_fd_set
*exceptfds
, int *count_ptr
)
4709 unsigned int i
, j
= 0, count
= 0;
4712 if (readfds
) count
+= readfds
->fd_count
;
4713 if (writefds
) count
+= writefds
->fd_count
;
4714 if (exceptfds
) count
+= exceptfds
->fd_count
;
4718 SetLastError(WSAEINVAL
);
4721 if (!(fds
= HeapAlloc( GetProcessHeap(), 0, count
* sizeof(fds
[0]))))
4723 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
4727 for (i
= 0; i
< readfds
->fd_count
; i
++, j
++)
4729 fds
[j
].fd
= get_sock_fd( readfds
->fd_array
[i
], FILE_READ_DATA
, NULL
);
4730 if (fds
[j
].fd
== -1) goto failed
;
4732 if (is_fd_bound(fds
[j
].fd
, NULL
, NULL
) == 1)
4734 fds
[j
].events
= POLLIN
;
4738 release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
4744 for (i
= 0; i
< writefds
->fd_count
; i
++, j
++)
4746 fds
[j
].fd
= get_sock_fd( writefds
->fd_array
[i
], FILE_WRITE_DATA
, NULL
);
4747 if (fds
[j
].fd
== -1) goto failed
;
4749 if (is_fd_bound(fds
[j
].fd
, NULL
, NULL
) == 1 ||
4750 _get_fd_type(fds
[j
].fd
) == SOCK_DGRAM
)
4752 fds
[j
].events
= POLLOUT
;
4756 release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
4762 for (i
= 0; i
< exceptfds
->fd_count
; i
++, j
++)
4764 fds
[j
].fd
= get_sock_fd( exceptfds
->fd_array
[i
], 0, NULL
);
4765 if (fds
[j
].fd
== -1) goto failed
;
4767 if (is_fd_bound(fds
[j
].fd
, NULL
, NULL
) == 1)
4769 int oob_inlined
= 0;
4770 socklen_t olen
= sizeof(oob_inlined
);
4772 fds
[j
].events
= POLLHUP
;
4774 /* Check if we need to test for urgent data or not */
4775 getsockopt(fds
[j
].fd
, SOL_SOCKET
, SO_OOBINLINE
, (char*) &oob_inlined
, &olen
);
4777 fds
[j
].events
|= POLLPRI
;
4781 release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
4792 for (i
= 0; i
< readfds
->fd_count
&& j
< count
; i
++, j
++)
4793 if (fds
[j
].fd
!= -1) release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
4795 for (i
= 0; i
< writefds
->fd_count
&& j
< count
; i
++, j
++)
4796 if (fds
[j
].fd
!= -1) release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
4798 for (i
= 0; i
< exceptfds
->fd_count
&& j
< count
; i
++, j
++)
4799 if (fds
[j
].fd
!= -1) release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
4800 HeapFree( GetProcessHeap(), 0, fds
);
4804 /* release the file descriptor obtained in fd_sets_to_poll */
4805 /* must be called with the original fd_set arrays, before calling get_poll_results */
4806 static void release_poll_fds( const WS_fd_set
*readfds
, const WS_fd_set
*writefds
,
4807 const WS_fd_set
*exceptfds
, struct pollfd
*fds
)
4809 unsigned int i
, j
= 0;
4813 for (i
= 0; i
< readfds
->fd_count
; i
++, j
++)
4814 if (fds
[j
].fd
!= -1) release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
4818 for (i
= 0; i
< writefds
->fd_count
; i
++, j
++)
4819 if (fds
[j
].fd
!= -1) release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
4823 for (i
= 0; i
< exceptfds
->fd_count
; i
++, j
++)
4825 if (fds
[j
].fd
== -1) continue;
4826 release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
4827 if (fds
[j
].revents
& POLLHUP
)
4829 int fd
= get_sock_fd( exceptfds
->fd_array
[i
], 0, NULL
);
4831 release_sock_fd( exceptfds
->fd_array
[i
], fd
);
4839 static int do_poll(struct pollfd
*pollfds
, int count
, int timeout
)
4841 struct timeval tv1
, tv2
;
4842 int ret
, torig
= timeout
;
4844 if (timeout
> 0) gettimeofday( &tv1
, 0 );
4846 while ((ret
= poll( pollfds
, count
, timeout
)) < 0)
4848 if (errno
!= EINTR
) break;
4849 if (timeout
< 0) continue;
4850 if (timeout
== 0) return 0;
4852 gettimeofday( &tv2
, 0 );
4854 tv2
.tv_sec
-= tv1
.tv_sec
;
4855 tv2
.tv_usec
-= tv1
.tv_usec
;
4856 if (tv2
.tv_usec
< 0)
4858 tv2
.tv_usec
+= 1000000;
4862 timeout
= torig
- (tv2
.tv_sec
* 1000) - (tv2
.tv_usec
+ 999) / 1000;
4863 if (timeout
<= 0) return 0;
4868 /* map the poll results back into the Windows fd sets */
4869 static int get_poll_results( WS_fd_set
*readfds
, WS_fd_set
*writefds
, WS_fd_set
*exceptfds
,
4870 const struct pollfd
*fds
)
4872 const struct pollfd
*poll_writefds
= fds
+ (readfds
? readfds
->fd_count
: 0);
4873 const struct pollfd
*poll_exceptfds
= poll_writefds
+ (writefds
? writefds
->fd_count
: 0);
4874 unsigned int i
, k
, total
= 0;
4878 for (i
= k
= 0; i
< readfds
->fd_count
; i
++)
4880 if (fds
[i
].revents
||
4881 (readfds
== writefds
&& (poll_writefds
[i
].revents
& POLLOUT
) && !(poll_writefds
[i
].revents
& POLLHUP
)) ||
4882 (readfds
== exceptfds
&& poll_exceptfds
[i
].revents
))
4883 readfds
->fd_array
[k
++] = readfds
->fd_array
[i
];
4885 readfds
->fd_count
= k
;
4888 if (writefds
&& writefds
!= readfds
)
4890 for (i
= k
= 0; i
< writefds
->fd_count
; i
++)
4892 if (((poll_writefds
[i
].revents
& POLLOUT
) && !(poll_writefds
[i
].revents
& POLLHUP
)) ||
4893 (writefds
== exceptfds
&& poll_exceptfds
[i
].revents
))
4894 writefds
->fd_array
[k
++] = writefds
->fd_array
[i
];
4896 writefds
->fd_count
= k
;
4899 if (exceptfds
&& exceptfds
!= readfds
&& exceptfds
!= writefds
)
4901 for (i
= k
= 0; i
< exceptfds
->fd_count
; i
++)
4902 if (poll_exceptfds
[i
].revents
) exceptfds
->fd_array
[k
++] = exceptfds
->fd_array
[i
];
4903 exceptfds
->fd_count
= k
;
4909 /***********************************************************************
4910 * select (WS2_32.18)
4912 int WINAPI
WS_select(int nfds
, WS_fd_set
*ws_readfds
,
4913 WS_fd_set
*ws_writefds
, WS_fd_set
*ws_exceptfds
,
4914 const struct WS_timeval
* ws_timeout
)
4916 struct pollfd
*pollfds
;
4917 int count
, ret
, timeout
= -1;
4919 TRACE("read %p, write %p, excp %p timeout %p\n",
4920 ws_readfds
, ws_writefds
, ws_exceptfds
, ws_timeout
);
4922 if (!(pollfds
= fd_sets_to_poll( ws_readfds
, ws_writefds
, ws_exceptfds
, &count
)))
4923 return SOCKET_ERROR
;
4926 timeout
= (ws_timeout
->tv_sec
* 1000) + (ws_timeout
->tv_usec
+ 999) / 1000;
4928 ret
= do_poll(pollfds
, count
, timeout
);
4929 release_poll_fds( ws_readfds
, ws_writefds
, ws_exceptfds
, pollfds
);
4931 if (ret
== -1) SetLastError(wsaErrno());
4932 else ret
= get_poll_results( ws_readfds
, ws_writefds
, ws_exceptfds
, pollfds
);
4933 HeapFree( GetProcessHeap(), 0, pollfds
);
4937 /* helper to send completion messages for client-only i/o operation case */
4938 static void WS_AddCompletion( SOCKET sock
, ULONG_PTR CompletionValue
, NTSTATUS CompletionStatus
,
4941 SERVER_START_REQ( add_fd_completion
)
4943 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(sock
) );
4944 req
->cvalue
= CompletionValue
;
4945 req
->status
= CompletionStatus
;
4946 req
->information
= Information
;
4947 wine_server_call( req
);
4953 /***********************************************************************
4956 int WINAPI
WS_send(SOCKET s
, const char *buf
, int len
, int flags
)
4962 wsabuf
.buf
= (char*) buf
;
4964 if ( WS2_sendto( s
, &wsabuf
, 1, &n
, flags
, NULL
, 0, NULL
, NULL
) == SOCKET_ERROR
)
4965 return SOCKET_ERROR
;
4970 /***********************************************************************
4971 * WSASend (WS2_32.72)
4973 INT WINAPI
WSASend( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
4974 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
4975 LPWSAOVERLAPPED lpOverlapped
,
4976 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
4978 return WS2_sendto( s
, lpBuffers
, dwBufferCount
, lpNumberOfBytesSent
, dwFlags
,
4979 NULL
, 0, lpOverlapped
, lpCompletionRoutine
);
4982 /***********************************************************************
4983 * WSASendDisconnect (WS2_32.73)
4985 INT WINAPI
WSASendDisconnect( SOCKET s
, LPWSABUF lpBuffers
)
4987 return WS_shutdown( s
, SD_SEND
);
4991 static int WS2_sendto( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
4992 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
4993 const struct WS_sockaddr
*to
, int tolen
,
4994 LPWSAOVERLAPPED lpOverlapped
,
4995 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
4997 unsigned int i
, options
;
4998 int n
, fd
, err
, overlapped
, flags
;
4999 struct ws2_async
*wsa
= NULL
, localwsa
;
5000 int totalLength
= 0;
5004 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
5005 s
, lpBuffers
, dwBufferCount
, dwFlags
,
5006 to
, tolen
, lpOverlapped
, lpCompletionRoutine
);
5008 fd
= get_sock_fd( s
, FILE_WRITE_DATA
, &options
);
5009 TRACE( "fd=%d, options=%x\n", fd
, options
);
5011 if ( fd
== -1 ) return SOCKET_ERROR
;
5013 if (!lpOverlapped
&& !lpNumberOfBytesSent
)
5019 overlapped
= (lpOverlapped
|| lpCompletionRoutine
) &&
5020 !(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
));
5021 if (overlapped
|| dwBufferCount
> 1)
5023 if (!(wsa
= (struct ws2_async
*)alloc_async_io( offsetof(struct ws2_async
, iovec
[dwBufferCount
]))))
5032 wsa
->hSocket
= SOCKET2HANDLE(s
);
5033 wsa
->addr
= (struct WS_sockaddr
*)to
;
5034 wsa
->addrlen
.val
= tolen
;
5035 wsa
->flags
= dwFlags
;
5036 wsa
->lpFlags
= &wsa
->flags
;
5037 wsa
->control
= NULL
;
5038 wsa
->n_iovecs
= dwBufferCount
;
5039 wsa
->first_iovec
= 0;
5040 for ( i
= 0; i
< dwBufferCount
; i
++ )
5042 wsa
->iovec
[i
].iov_base
= lpBuffers
[i
].buf
;
5043 wsa
->iovec
[i
].iov_len
= lpBuffers
[i
].len
;
5044 totalLength
+= lpBuffers
[i
].len
;
5047 flags
= convert_flags(dwFlags
);
5048 n
= WS2_send( fd
, wsa
, flags
);
5049 if (n
== -1 && errno
!= EAGAIN
)
5057 IO_STATUS_BLOCK
*iosb
= lpOverlapped
? (IO_STATUS_BLOCK
*)lpOverlapped
: &wsa
->local_iosb
;
5058 ULONG_PTR cvalue
= (lpOverlapped
&& ((ULONG_PTR
)lpOverlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)lpOverlapped
: 0;
5060 wsa
->user_overlapped
= lpOverlapped
;
5061 wsa
->completion_func
= lpCompletionRoutine
;
5062 release_sock_fd( s
, fd
);
5064 if (n
== -1 || n
< totalLength
)
5066 iosb
->u
.Status
= STATUS_PENDING
;
5067 iosb
->Information
= n
== -1 ? 0 : n
;
5069 SERVER_START_REQ( register_async
)
5071 req
->type
= ASYNC_TYPE_WRITE
;
5072 req
->async
.handle
= wine_server_obj_handle( wsa
->hSocket
);
5073 req
->async
.callback
= wine_server_client_ptr( WS2_async_send
);
5074 req
->async
.iosb
= wine_server_client_ptr( iosb
);
5075 req
->async
.arg
= wine_server_client_ptr( wsa
);
5076 req
->async
.event
= wine_server_obj_handle( lpCompletionRoutine
? 0 : lpOverlapped
->hEvent
);
5077 req
->async
.cvalue
= cvalue
;
5078 err
= wine_server_call( req
);
5082 /* Enable the event only after starting the async. The server will deliver it as soon as
5083 the async is done. */
5084 _enable_event(SOCKET2HANDLE(s
), FD_WRITE
, 0, 0);
5086 if (err
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
5087 SetLastError(NtStatusToWSAError( err
));
5088 return SOCKET_ERROR
;
5091 iosb
->u
.Status
= STATUS_SUCCESS
;
5092 iosb
->Information
= n
;
5093 if (lpNumberOfBytesSent
) *lpNumberOfBytesSent
= n
;
5094 if (!wsa
->completion_func
)
5096 if (cvalue
) WS_AddCompletion( s
, cvalue
, STATUS_SUCCESS
, n
);
5097 if (lpOverlapped
->hEvent
) SetEvent( lpOverlapped
->hEvent
);
5098 HeapFree( GetProcessHeap(), 0, wsa
);
5100 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC
)ws2_async_apc
,
5101 (ULONG_PTR
)wsa
, (ULONG_PTR
)iosb
, 0 );
5102 SetLastError(ERROR_SUCCESS
);
5106 if ((err
= _is_blocking( s
, &is_blocking
)))
5108 err
= NtStatusToWSAError( err
);
5114 /* On a blocking non-overlapped stream socket,
5115 * sending blocks until the entire buffer is sent. */
5116 DWORD timeout_start
= GetTickCount();
5118 bytes_sent
= n
== -1 ? 0 : n
;
5120 while (wsa
->first_iovec
< wsa
->n_iovecs
)
5123 int poll_timeout
= -1;
5124 INT64 timeout
= get_rcvsnd_timeo(fd
, FALSE
);
5128 timeout
-= GetTickCount() - timeout_start
;
5129 if (timeout
< 0) poll_timeout
= 0;
5130 else poll_timeout
= timeout
<= INT_MAX
? timeout
: INT_MAX
;
5134 pfd
.events
= POLLOUT
;
5136 if (!poll_timeout
|| !poll( &pfd
, 1, poll_timeout
))
5139 goto error
; /* msdn says a timeout in send is fatal */
5142 n
= WS2_send( fd
, wsa
, flags
);
5143 if (n
== -1 && errno
!= EAGAIN
)
5153 else /* non-blocking */
5155 if (n
< totalLength
)
5156 _enable_event(SOCKET2HANDLE(s
), FD_WRITE
, 0, 0);
5159 err
= WSAEWOULDBLOCK
;
5165 TRACE(" -> %i bytes\n", bytes_sent
);
5167 if (lpNumberOfBytesSent
) *lpNumberOfBytesSent
= bytes_sent
;
5168 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
5169 release_sock_fd( s
, fd
);
5170 SetLastError(ERROR_SUCCESS
);
5174 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
5175 release_sock_fd( s
, fd
);
5176 WARN(" -> ERROR %d\n", err
);
5178 return SOCKET_ERROR
;
5181 /***********************************************************************
5182 * WSASendTo (WS2_32.74)
5184 INT WINAPI
WSASendTo( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
5185 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
5186 const struct WS_sockaddr
*to
, int tolen
,
5187 LPWSAOVERLAPPED lpOverlapped
,
5188 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
5190 return WS2_sendto( s
, lpBuffers
, dwBufferCount
,
5191 lpNumberOfBytesSent
, dwFlags
,
5193 lpOverlapped
, lpCompletionRoutine
);
5196 /***********************************************************************
5197 * sendto (WS2_32.20)
5199 int WINAPI
WS_sendto(SOCKET s
, const char *buf
, int len
, int flags
,
5200 const struct WS_sockaddr
*to
, int tolen
)
5206 wsabuf
.buf
= (char*) buf
;
5208 if ( WS2_sendto(s
, &wsabuf
, 1, &n
, flags
, to
, tolen
, NULL
, NULL
) == SOCKET_ERROR
)
5209 return SOCKET_ERROR
;
5214 /***********************************************************************
5215 * setsockopt (WS2_32.21)
5217 int WINAPI
WS_setsockopt(SOCKET s
, int level
, int optname
,
5218 const char *optval
, int optlen
)
5222 struct linger linger
;
5223 struct timeval tval
;
5225 TRACE("(socket %04lx, %s, optval %s, optlen %d)\n", s
,
5226 debugstr_sockopt(level
, optname
), debugstr_optval(optval
, optlen
),
5229 /* some broken apps pass the value directly instead of a pointer to it */
5230 if(optlen
&& IS_INTRESOURCE(optval
))
5232 SetLastError(WSAEFAULT
);
5233 return SOCKET_ERROR
;
5241 /* Some options need some conversion before they can be sent to
5242 * setsockopt. The conversions are done here, then they will fall through
5243 * to the general case. Special options that are not passed to
5244 * setsockopt follow below that.*/
5246 case WS_SO_DONTLINGER
:
5249 SetLastError(WSAEFAULT
);
5250 return SOCKET_ERROR
;
5252 linger
.l_onoff
= *(const int*)optval
== 0;
5253 linger
.l_linger
= 0;
5255 optname
= SO_LINGER
;
5256 optval
= (char*)&linger
;
5257 optlen
= sizeof(struct linger
);
5263 SetLastError(WSAEFAULT
);
5264 return SOCKET_ERROR
;
5266 linger
.l_onoff
= ((LINGER
*)optval
)->l_onoff
;
5267 linger
.l_linger
= ((LINGER
*)optval
)->l_linger
;
5269 optname
= SO_LINGER
;
5270 optval
= (char*)&linger
;
5271 optlen
= sizeof(struct linger
);
5275 if (*(const int*)optval
< 2048)
5277 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval
);
5282 /* The options listed here don't need any special handling. Thanks to
5283 * the conversion happening above, options from there will fall through
5285 case WS_SO_ACCEPTCONN
:
5286 case WS_SO_BROADCAST
:
5288 case WS_SO_KEEPALIVE
:
5289 case WS_SO_OOBINLINE
:
5290 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
5291 * however, using it the BSD way fixes bug 8513 and seems to be what
5292 * most programmers assume, anyway */
5293 case WS_SO_REUSEADDR
:
5296 convert_sockopt(&level
, &optname
);
5299 /* SO_DEBUG is a privileged operation, ignore it. */
5301 TRACE("Ignoring SO_DEBUG\n");
5304 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
5305 * socket. According to MSDN, this option is silently ignored.*/
5306 case WS_SO_DONTROUTE
:
5307 TRACE("Ignoring SO_DONTROUTE\n");
5310 /* Stops two sockets from being bound to the same port. Always happens
5311 * on unix systems, so just drop it. */
5312 case WS_SO_EXCLUSIVEADDRUSE
:
5313 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
5316 /* After a ConnectEx call succeeds, the socket can't be used with half of the
5317 * normal winsock functions on windows. We don't have that problem. */
5318 case WS_SO_UPDATE_CONNECT_CONTEXT
:
5319 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
5322 /* After a AcceptEx call succeeds, the socket can't be used with half of the
5323 * normal winsock functions on windows. We don't have that problem. */
5324 case WS_SO_UPDATE_ACCEPT_CONTEXT
:
5325 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
5328 /* SO_OPENTYPE does not require a valid socket handle. */
5329 case WS_SO_OPENTYPE
:
5330 if (!optlen
|| optlen
< sizeof(int) || !optval
)
5332 SetLastError(WSAEFAULT
);
5333 return SOCKET_ERROR
;
5335 get_per_thread_data()->opentype
= *(const int *)optval
;
5336 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval
) );
5340 case WS_SO_RCVTIMEO
:
5343 case WS_SO_SNDTIMEO
:
5345 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
5346 if (optval
&& optlen
== sizeof(UINT32
)) {
5347 /* WinSock passes milliseconds instead of struct timeval */
5348 tval
.tv_usec
= (*(const UINT32
*)optval
% 1000) * 1000;
5349 tval
.tv_sec
= *(const UINT32
*)optval
/ 1000;
5350 /* min of 500 milliseconds */
5351 if (tval
.tv_sec
== 0 && tval
.tv_usec
&& tval
.tv_usec
< 500000)
5352 tval
.tv_usec
= 500000;
5353 optlen
= sizeof(struct timeval
);
5354 optval
= (char*)&tval
;
5355 } else if (optlen
== sizeof(struct timeval
)) {
5356 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen
);
5358 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen
);
5361 convert_sockopt(&level
, &optname
);
5366 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname
);
5367 SetLastError(WSAENOPROTOOPT
);
5368 return SOCKET_ERROR
;
5370 break; /* case WS_SOL_SOCKET */
5373 case WS_NSPROTO_IPX
:
5377 return set_ipx_packettype(s
, *(int*)optval
);
5379 case WS_IPX_FILTERPTYPE
:
5380 /* Sets the receive filter packet type, at the moment we don't support it */
5381 FIXME("IPX_FILTERPTYPE: %x\n", *optval
);
5382 /* Returning 0 is better for now than returning a SOCKET_ERROR */
5386 FIXME("opt_name:%x\n", optname
);
5387 return SOCKET_ERROR
;
5389 break; /* case WS_NSPROTO_IPX */
5392 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
5393 case WS_IPPROTO_TCP
:
5396 case WS_TCP_NODELAY
:
5397 convert_sockopt(&level
, &optname
);
5400 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname
);
5401 return SOCKET_ERROR
;
5408 case WS_IP_ADD_MEMBERSHIP
:
5409 case WS_IP_DROP_MEMBERSHIP
:
5413 case WS_IP_MULTICAST_IF
:
5414 case WS_IP_MULTICAST_LOOP
:
5415 case WS_IP_MULTICAST_TTL
:
5422 #ifdef IP_UNICAST_IF
5423 case WS_IP_UNICAST_IF
:
5425 convert_sockopt(&level
, &optname
);
5427 case WS_IP_DONTFRAGMENT
:
5428 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
5431 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname
);
5432 return SOCKET_ERROR
;
5436 case WS_IPPROTO_IPV6
:
5439 #ifdef IPV6_ADD_MEMBERSHIP
5440 case WS_IPV6_ADD_MEMBERSHIP
:
5442 #ifdef IPV6_DROP_MEMBERSHIP
5443 case WS_IPV6_DROP_MEMBERSHIP
:
5445 case WS_IPV6_MULTICAST_IF
:
5446 case WS_IPV6_MULTICAST_HOPS
:
5447 case WS_IPV6_MULTICAST_LOOP
:
5448 case WS_IPV6_UNICAST_HOPS
:
5449 case WS_IPV6_V6ONLY
:
5450 #ifdef IPV6_UNICAST_IF
5451 case WS_IPV6_UNICAST_IF
:
5453 convert_sockopt(&level
, &optname
);
5455 case WS_IPV6_DONTFRAG
:
5456 FIXME("IPV6_DONTFRAG is silently ignored!\n");
5458 case WS_IPV6_PROTECTION_LEVEL
:
5459 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
5462 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname
);
5463 return SOCKET_ERROR
;
5468 WARN("Unknown level: 0x%08x\n", level
);
5469 SetLastError(WSAEINVAL
);
5470 return SOCKET_ERROR
;
5471 } /* end switch(level) */
5473 /* avoid endianness issues if argument is a 16-bit int */
5474 if (optval
&& optlen
< sizeof(int))
5476 woptval
= *((const INT16
*) optval
);
5477 optval
= (char*) &woptval
;
5478 woptval
&= (1 << optlen
* 8) - 1;
5481 fd
= get_sock_fd( s
, 0, NULL
);
5482 if (fd
== -1) return SOCKET_ERROR
;
5484 if (setsockopt(fd
, level
, optname
, optval
, optlen
) == 0)
5487 if (level
== SOL_SOCKET
&& optname
== SO_REUSEADDR
&&
5488 setsockopt(fd
, level
, SO_REUSEPORT
, optval
, optlen
) != 0)
5490 SetLastError(wsaErrno());
5491 release_sock_fd( s
, fd
);
5492 return SOCKET_ERROR
;
5495 release_sock_fd( s
, fd
);
5498 TRACE("Setting socket error, %d\n", wsaErrno());
5499 SetLastError(wsaErrno());
5500 release_sock_fd( s
, fd
);
5502 return SOCKET_ERROR
;
5505 /***********************************************************************
5506 * shutdown (WS2_32.22)
5508 int WINAPI
WS_shutdown(SOCKET s
, int how
)
5510 int fd
, err
= WSAENOTSOCK
;
5511 unsigned int options
= 0, clear_flags
= 0;
5513 fd
= get_sock_fd( s
, 0, &options
);
5514 TRACE("socket %04lx, how 0x%x, options 0x%x\n", s
, how
, options
);
5517 return SOCKET_ERROR
;
5521 case SD_RECEIVE
: /* drop receives */
5522 clear_flags
|= FD_READ
;
5524 case SD_SEND
: /* drop sends */
5525 clear_flags
|= FD_WRITE
;
5527 case SD_BOTH
: /* drop all */
5528 clear_flags
|= FD_READ
|FD_WRITE
;
5531 clear_flags
|= FD_WINE_LISTENING
;
5534 if (!(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
)))
5539 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_READ
);
5542 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_WRITE
);
5546 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_READ
);
5547 if (!err
) err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_WRITE
);
5550 if (err
) goto error
;
5552 else /* non-overlapped mode */
5554 if ( shutdown( fd
, how
) )
5561 release_sock_fd( s
, fd
);
5562 _enable_event( SOCKET2HANDLE(s
), 0, 0, clear_flags
);
5563 if ( how
> 1) WSAAsyncSelect( s
, 0, 0, 0 );
5567 release_sock_fd( s
, fd
);
5568 _enable_event( SOCKET2HANDLE(s
), 0, 0, clear_flags
);
5569 SetLastError( err
);
5570 return SOCKET_ERROR
;
5573 /***********************************************************************
5574 * socket (WS2_32.23)
5576 SOCKET WINAPI
WS_socket(int af
, int type
, int protocol
)
5578 TRACE("af=%d type=%d protocol=%d\n", af
, type
, protocol
);
5580 return WSASocketW( af
, type
, protocol
, NULL
, 0,
5581 get_per_thread_data()->opentype
? 0 : WSA_FLAG_OVERLAPPED
);
5585 /***********************************************************************
5586 * gethostbyaddr (WS2_32.51)
5588 struct WS_hostent
* WINAPI
WS_gethostbyaddr(const char *addr
, int len
, int type
)
5590 struct WS_hostent
*retval
= NULL
;
5591 struct hostent
* host
;
5592 int unixtype
= convert_af_w2u(type
);
5593 const char *paddr
= addr
;
5594 unsigned long loopback
;
5595 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5597 int ebufsize
= 1024;
5598 struct hostent hostentry
;
5599 int locerr
= ENOBUFS
;
5602 /* convert back the magic loopback address if necessary */
5603 if (unixtype
== AF_INET
&& len
== 4 && !memcmp(addr
, magic_loopback_addr
, 4))
5605 loopback
= htonl(INADDR_LOOPBACK
);
5606 paddr
= (char*) &loopback
;
5609 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5611 extrabuf
=HeapAlloc(GetProcessHeap(),0,ebufsize
) ;
5613 int res
= gethostbyaddr_r(paddr
, len
, unixtype
,
5614 &hostentry
, extrabuf
, ebufsize
, &host
, &locerr
);
5615 if (res
!= ERANGE
) break;
5617 extrabuf
=HeapReAlloc(GetProcessHeap(),0,extrabuf
,ebufsize
) ;
5619 if (host
) retval
= WS_dup_he(host
);
5620 else SetLastError((locerr
< 0) ? wsaErrno() : wsaHerrno(locerr
));
5621 HeapFree(GetProcessHeap(),0,extrabuf
);
5623 EnterCriticalSection( &csWSgetXXXbyYYY
);
5624 host
= gethostbyaddr(paddr
, len
, unixtype
);
5625 if (host
) retval
= WS_dup_he(host
);
5626 else SetLastError((h_errno
< 0) ? wsaErrno() : wsaHerrno(h_errno
));
5627 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5629 TRACE("ptr %p, len %d, type %d ret %p\n", addr
, len
, type
, retval
);
5633 /***********************************************************************
5634 * WS_compare_routes_by_metric_asc (INTERNAL)
5636 * Comparison function for qsort(), for sorting two routes (struct route)
5637 * by metric in ascending order.
5639 static int WS_compare_routes_by_metric_asc(const void *left
, const void *right
)
5641 return ((const struct route
*)left
)->metric
- ((const struct route
*)right
)->metric
;
5644 /***********************************************************************
5645 * WS_get_local_ips (INTERNAL)
5647 * Returns the list of local IP addresses by going through the network
5648 * adapters and using the local routing table to sort the addresses
5649 * from highest routing priority to lowest routing priority. This
5650 * functionality is inferred from the description for obtaining local
5651 * IP addresses given in the Knowledge Base Article Q160215.
5653 * Please note that the returned hostent is only freed when the thread
5654 * closes and is replaced if another hostent is requested.
5656 static struct WS_hostent
* WS_get_local_ips( char *hostname
)
5658 int numroutes
= 0, i
, j
;
5660 PIP_ADAPTER_INFO adapters
= NULL
, k
;
5661 struct WS_hostent
*hostlist
= NULL
;
5662 PMIB_IPFORWARDTABLE routes
= NULL
;
5663 struct route
*route_addrs
= NULL
;
5664 DWORD adap_size
, route_size
;
5666 /* Obtain the size of the adapter list and routing table, also allocate memory */
5667 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
5669 if (GetIpForwardTable(NULL
, &route_size
, FALSE
) != ERROR_INSUFFICIENT_BUFFER
)
5671 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
5672 routes
= HeapAlloc(GetProcessHeap(), 0, route_size
);
5673 route_addrs
= HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
5674 if (adapters
== NULL
|| routes
== NULL
|| route_addrs
== NULL
)
5676 /* Obtain the adapter list and the full routing table */
5677 if (GetAdaptersInfo(adapters
, &adap_size
) != NO_ERROR
)
5679 if (GetIpForwardTable(routes
, &route_size
, FALSE
) != NO_ERROR
)
5681 /* Store the interface associated with each route */
5682 for (n
= 0; n
< routes
->dwNumEntries
; n
++)
5686 BOOL exists
= FALSE
;
5688 if (routes
->table
[n
].u1
.ForwardType
!= MIB_IPROUTE_TYPE_DIRECT
)
5690 ifindex
= routes
->table
[n
].dwForwardIfIndex
;
5691 ifmetric
= routes
->table
[n
].dwForwardMetric1
;
5692 /* Only store the lowest valued metric for an interface */
5693 for (j
= 0; j
< numroutes
; j
++)
5695 if (route_addrs
[j
].interface
== ifindex
)
5697 if (route_addrs
[j
].metric
> ifmetric
)
5698 route_addrs
[j
].metric
= ifmetric
;
5704 route_addrs
= HeapReAlloc(GetProcessHeap(), 0, route_addrs
, (numroutes
+1)*sizeof(struct route
));
5705 if (route_addrs
== NULL
)
5706 goto cleanup
; /* Memory allocation error, fail gracefully */
5707 route_addrs
[numroutes
].interface
= ifindex
;
5708 route_addrs
[numroutes
].metric
= ifmetric
;
5709 /* If no IP is found in the next step (for whatever reason)
5710 * then fall back to the magic loopback address.
5712 memcpy(&(route_addrs
[numroutes
].addr
.s_addr
), magic_loopback_addr
, 4);
5716 goto cleanup
; /* No routes, fall back to the Magic IP */
5717 /* Find the IP address associated with each found interface */
5718 for (i
= 0; i
< numroutes
; i
++)
5720 for (k
= adapters
; k
!= NULL
; k
= k
->Next
)
5722 char *ip
= k
->IpAddressList
.IpAddress
.String
;
5724 if (route_addrs
[i
].interface
== k
->Index
)
5725 route_addrs
[i
].addr
.s_addr
= (in_addr_t
) inet_addr(ip
);
5728 /* Allocate a hostent and enough memory for all the IPs,
5729 * including the NULL at the end of the list.
5731 hostlist
= WS_create_he(hostname
, 1, 0, numroutes
+1, sizeof(struct in_addr
));
5732 if (hostlist
== NULL
)
5733 goto cleanup
; /* Failed to allocate a hostent for the list of IPs */
5734 hostlist
->h_addr_list
[numroutes
] = NULL
; /* NULL-terminate the address list */
5735 hostlist
->h_aliases
[0] = NULL
; /* NULL-terminate the alias list */
5736 hostlist
->h_addrtype
= AF_INET
;
5737 hostlist
->h_length
= sizeof(struct in_addr
); /* = 4 */
5738 /* Reorder the entries before placing them in the host list. Windows expects
5739 * the IP list in order from highest priority to lowest (the critical thing
5740 * is that most applications expect the first IP to be the default route).
5743 qsort(route_addrs
, numroutes
, sizeof(struct route
), WS_compare_routes_by_metric_asc
);
5745 for (i
= 0; i
< numroutes
; i
++)
5746 (*(struct in_addr
*) hostlist
->h_addr_list
[i
]) = route_addrs
[i
].addr
;
5748 /* Cleanup all allocated memory except the address list,
5749 * the address list is used by the calling app.
5752 HeapFree(GetProcessHeap(), 0, route_addrs
);
5753 HeapFree(GetProcessHeap(), 0, adapters
);
5754 HeapFree(GetProcessHeap(), 0, routes
);
5758 /***********************************************************************
5759 * gethostbyname (WS2_32.52)
5761 struct WS_hostent
* WINAPI
WS_gethostbyname(const char* name
)
5763 struct WS_hostent
*retval
= NULL
;
5764 struct hostent
* host
;
5765 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5768 struct hostent hostentry
;
5769 int locerr
= ENOBUFS
;
5773 SetLastError(WSANOTINITIALISED
);
5776 if( gethostname( hostname
, 100) == -1) {
5777 SetLastError(WSAENOBUFS
); /* appropriate ? */
5780 if( !name
|| !name
[0]) {
5783 /* If the hostname of the local machine is requested then return the
5784 * complete list of local IP addresses */
5785 if(strcmp(name
, hostname
) == 0)
5786 retval
= WS_get_local_ips(hostname
);
5787 /* If any other hostname was requested (or the routing table lookup failed)
5788 * then return the IP found by the host OS */
5791 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5793 extrabuf
=HeapAlloc(GetProcessHeap(),0,ebufsize
) ;
5795 int res
= gethostbyname_r(name
, &hostentry
, extrabuf
, ebufsize
, &host
, &locerr
);
5796 if( res
!= ERANGE
) break;
5798 extrabuf
=HeapReAlloc(GetProcessHeap(),0,extrabuf
,ebufsize
) ;
5800 if (!host
) SetLastError((locerr
< 0) ? wsaErrno() : wsaHerrno(locerr
));
5802 EnterCriticalSection( &csWSgetXXXbyYYY
);
5803 host
= gethostbyname(name
);
5804 if (!host
) SetLastError((h_errno
< 0) ? wsaErrno() : wsaHerrno(h_errno
));
5806 if (host
) retval
= WS_dup_he(host
);
5807 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5808 HeapFree(GetProcessHeap(),0,extrabuf
);
5810 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5813 if (retval
&& retval
->h_addr_list
[0][0] == 127 &&
5814 strcmp(name
, "localhost") != 0)
5816 /* hostname != "localhost" but has loopback address. replace by our
5817 * special address.*/
5818 memcpy(retval
->h_addr_list
[0], magic_loopback_addr
, 4);
5820 TRACE( "%s ret %p\n", debugstr_a(name
), retval
);
5825 /***********************************************************************
5826 * getprotobyname (WS2_32.53)
5828 struct WS_protoent
* WINAPI
WS_getprotobyname(const char* name
)
5830 struct WS_protoent
* retval
= NULL
;
5831 #ifdef HAVE_GETPROTOBYNAME
5832 struct protoent
* proto
;
5833 EnterCriticalSection( &csWSgetXXXbyYYY
);
5834 if( (proto
= getprotobyname(name
)) != NULL
)
5836 retval
= WS_dup_pe(proto
);
5839 MESSAGE("protocol %s not found; You might want to add "
5840 "this to /etc/protocols\n", debugstr_a(name
) );
5841 SetLastError(WSANO_DATA
);
5843 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5845 TRACE( "%s ret %p\n", debugstr_a(name
), retval
);
5850 /***********************************************************************
5851 * getprotobynumber (WS2_32.54)
5853 struct WS_protoent
* WINAPI
WS_getprotobynumber(int number
)
5855 struct WS_protoent
* retval
= NULL
;
5856 #ifdef HAVE_GETPROTOBYNUMBER
5857 struct protoent
* proto
;
5858 EnterCriticalSection( &csWSgetXXXbyYYY
);
5859 if( (proto
= getprotobynumber(number
)) != NULL
)
5861 retval
= WS_dup_pe(proto
);
5864 MESSAGE("protocol number %d not found; You might want to add "
5865 "this to /etc/protocols\n", number
);
5866 SetLastError(WSANO_DATA
);
5868 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5870 TRACE("%i ret %p\n", number
, retval
);
5875 /***********************************************************************
5876 * getservbyname (WS2_32.55)
5878 struct WS_servent
* WINAPI
WS_getservbyname(const char *name
, const char *proto
)
5880 struct WS_servent
* retval
= NULL
;
5881 struct servent
* serv
;
5883 char *proto_str
= NULL
;
5885 if (!(name_str
= strdup_lower(name
))) return NULL
;
5887 if (proto
&& *proto
)
5889 if (!(proto_str
= strdup_lower(proto
)))
5891 HeapFree( GetProcessHeap(), 0, name_str
);
5896 EnterCriticalSection( &csWSgetXXXbyYYY
);
5897 serv
= getservbyname(name_str
, proto_str
);
5900 retval
= WS_dup_se(serv
);
5902 else SetLastError(WSANO_DATA
);
5903 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5904 HeapFree( GetProcessHeap(), 0, proto_str
);
5905 HeapFree( GetProcessHeap(), 0, name_str
);
5906 TRACE( "%s, %s ret %p\n", debugstr_a(name
), debugstr_a(proto
), retval
);
5910 /***********************************************************************
5911 * freeaddrinfo (WS2_32.@)
5913 void WINAPI
WS_freeaddrinfo(struct WS_addrinfo
*res
)
5916 struct WS_addrinfo
*next
;
5918 HeapFree(GetProcessHeap(),0,res
->ai_canonname
);
5919 HeapFree(GetProcessHeap(),0,res
->ai_addr
);
5920 next
= res
->ai_next
;
5921 HeapFree(GetProcessHeap(),0,res
);
5926 /* helper functions for getaddrinfo()/getnameinfo() */
5927 static int convert_aiflag_w2u(int winflags
) {
5931 for (i
=0;i
<sizeof(ws_aiflag_map
)/sizeof(ws_aiflag_map
[0]);i
++)
5932 if (ws_aiflag_map
[i
][0] & winflags
) {
5933 unixflags
|= ws_aiflag_map
[i
][1];
5934 winflags
&= ~ws_aiflag_map
[i
][0];
5937 FIXME("Unhandled windows AI_xxx flags %x\n", winflags
);
5941 static int convert_niflag_w2u(int winflags
) {
5945 for (i
=0;i
<sizeof(ws_niflag_map
)/sizeof(ws_niflag_map
[0]);i
++)
5946 if (ws_niflag_map
[i
][0] & winflags
) {
5947 unixflags
|= ws_niflag_map
[i
][1];
5948 winflags
&= ~ws_niflag_map
[i
][0];
5951 FIXME("Unhandled windows NI_xxx flags %x\n", winflags
);
5955 static int convert_aiflag_u2w(int unixflags
) {
5959 for (i
=0;i
<sizeof(ws_aiflag_map
)/sizeof(ws_aiflag_map
[0]);i
++)
5960 if (ws_aiflag_map
[i
][1] & unixflags
) {
5961 winflags
|= ws_aiflag_map
[i
][0];
5962 unixflags
&= ~ws_aiflag_map
[i
][1];
5964 if (unixflags
) /* will warn usually */
5965 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags
);
5969 static int convert_eai_u2w(int unixret
) {
5972 if (!unixret
) return 0;
5974 for (i
=0;ws_eai_map
[i
][0];i
++)
5975 if (ws_eai_map
[i
][1] == unixret
)
5976 return ws_eai_map
[i
][0];
5978 if (unixret
== EAI_SYSTEM
)
5979 /* There are broken versions of glibc which return EAI_SYSTEM
5980 * and set errno to 0 instead of returning EAI_NONAME.
5982 return errno
? sock_get_error( errno
) : WS_EAI_NONAME
;
5984 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret
);
5988 static char *get_hostname(void)
5993 GetComputerNameExA( ComputerNamePhysicalDnsHostname
, NULL
, &size
);
5994 if (GetLastError() != ERROR_MORE_DATA
) return NULL
;
5995 if (!(ret
= HeapAlloc( GetProcessHeap(), 0, size
))) return NULL
;
5996 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname
, ret
, &size
))
5998 HeapFree( GetProcessHeap(), 0, ret
);
6004 /***********************************************************************
6005 * getaddrinfo (WS2_32.@)
6007 int WINAPI
WS_getaddrinfo(LPCSTR nodename
, LPCSTR servname
, const struct WS_addrinfo
*hints
, struct WS_addrinfo
**res
)
6009 #ifdef HAVE_GETADDRINFO
6010 struct addrinfo
*unixaires
= NULL
;
6012 struct addrinfo unixhints
, *punixhints
= NULL
;
6017 if (!nodename
&& !servname
)
6019 SetLastError(WSAHOST_NOT_FOUND
);
6020 return WSAHOST_NOT_FOUND
;
6023 hostname
= get_hostname();
6024 if (!hostname
) return WSA_NOT_ENOUGH_MEMORY
;
6028 else if (!nodename
[0])
6033 /* servname tweak required by OSX and BSD kernels */
6034 if (servname
&& !servname
[0]) servname
= "0";
6037 punixhints
= &unixhints
;
6039 memset(&unixhints
, 0, sizeof(unixhints
));
6040 punixhints
->ai_flags
= convert_aiflag_w2u(hints
->ai_flags
);
6042 /* zero is a wildcard, no need to convert */
6043 if (hints
->ai_family
)
6044 punixhints
->ai_family
= convert_af_w2u(hints
->ai_family
);
6045 if (hints
->ai_socktype
)
6046 punixhints
->ai_socktype
= convert_socktype_w2u(hints
->ai_socktype
);
6047 if (hints
->ai_protocol
)
6048 punixhints
->ai_protocol
= max(convert_proto_w2u(hints
->ai_protocol
), 0);
6050 if (punixhints
->ai_socktype
< 0)
6052 SetLastError(WSAESOCKTNOSUPPORT
);
6053 HeapFree(GetProcessHeap(), 0, hostname
);
6054 return SOCKET_ERROR
;
6057 /* windows allows invalid combinations of socket type and protocol, unix does not.
6058 * fix the parameters here to make getaddrinfo call always work */
6059 if (punixhints
->ai_protocol
== IPPROTO_TCP
&&
6060 punixhints
->ai_socktype
!= SOCK_STREAM
&& punixhints
->ai_socktype
!= SOCK_SEQPACKET
)
6061 punixhints
->ai_socktype
= 0;
6063 else if (punixhints
->ai_protocol
== IPPROTO_UDP
&& punixhints
->ai_socktype
!= SOCK_DGRAM
)
6064 punixhints
->ai_socktype
= 0;
6066 else if (IS_IPX_PROTO(punixhints
->ai_protocol
) && punixhints
->ai_socktype
!= SOCK_DGRAM
)
6067 punixhints
->ai_socktype
= 0;
6070 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
6071 result
= getaddrinfo(node
, servname
, punixhints
, &unixaires
);
6073 if (result
&& !strcmp(hostname
, node
))
6075 /* If it didn't work it means the host name IP is not in /etc/hosts, try again
6076 * by sending a NULL host and avoid sending a NULL servname too because that
6078 ERR_(winediag
)("Failed to resolve your host name IP\n");
6079 result
= getaddrinfo(NULL
, servname
? servname
: "0", punixhints
, &unixaires
);
6081 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename
), debugstr_a(servname
), hints
, res
, result
);
6082 HeapFree(GetProcessHeap(), 0, hostname
);
6085 struct addrinfo
*xuai
= unixaires
;
6086 struct WS_addrinfo
**xai
= res
;
6090 struct WS_addrinfo
*ai
= HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY
, sizeof(struct WS_addrinfo
));
6096 *xai
= ai
;xai
= &ai
->ai_next
;
6097 ai
->ai_flags
= convert_aiflag_u2w(xuai
->ai_flags
);
6098 ai
->ai_family
= convert_af_u2w(xuai
->ai_family
);
6099 /* copy whatever was sent in the hints */
6101 ai
->ai_socktype
= hints
->ai_socktype
;
6102 ai
->ai_protocol
= hints
->ai_protocol
;
6104 ai
->ai_socktype
= convert_socktype_u2w(xuai
->ai_socktype
);
6105 ai
->ai_protocol
= convert_proto_u2w(xuai
->ai_protocol
);
6107 if (xuai
->ai_canonname
) {
6108 TRACE("canon name - %s\n",debugstr_a(xuai
->ai_canonname
));
6109 ai
->ai_canonname
= HeapAlloc(GetProcessHeap(),0,strlen(xuai
->ai_canonname
)+1);
6110 if (!ai
->ai_canonname
)
6112 strcpy(ai
->ai_canonname
,xuai
->ai_canonname
);
6114 len
= xuai
->ai_addrlen
;
6115 ai
->ai_addr
= HeapAlloc(GetProcessHeap(),0,len
);
6118 ai
->ai_addrlen
= len
;
6120 int winlen
= ai
->ai_addrlen
;
6122 if (!ws_sockaddr_u2ws(xuai
->ai_addr
, ai
->ai_addr
, &winlen
)) {
6123 ai
->ai_addrlen
= winlen
;
6127 ai
->ai_addr
= HeapReAlloc(GetProcessHeap(),0,ai
->ai_addr
,len
);
6130 ai
->ai_addrlen
= len
;
6132 xuai
= xuai
->ai_next
;
6134 freeaddrinfo(unixaires
);
6136 if (TRACE_ON(winsock
))
6138 struct WS_addrinfo
*ai
= *res
;
6141 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
6142 ai
, ai
->ai_flags
, ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
, ai
->ai_addrlen
,
6143 ai
->ai_canonname
, debugstr_sockaddr(ai
->ai_addr
));
6148 result
= convert_eai_u2w(result
);
6150 SetLastError(result
);
6154 if (*res
) WS_freeaddrinfo(*res
);
6155 if (unixaires
) freeaddrinfo(unixaires
);
6156 return WSA_NOT_ENOUGH_MEMORY
;
6158 FIXME("getaddrinfo() failed, not found during buildtime.\n");
6163 static struct WS_addrinfoW
*addrinfo_AtoW(const struct WS_addrinfo
*ai
)
6165 struct WS_addrinfoW
*ret
;
6167 if (!(ret
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW
)))) return NULL
;
6168 ret
->ai_flags
= ai
->ai_flags
;
6169 ret
->ai_family
= ai
->ai_family
;
6170 ret
->ai_socktype
= ai
->ai_socktype
;
6171 ret
->ai_protocol
= ai
->ai_protocol
;
6172 ret
->ai_addrlen
= ai
->ai_addrlen
;
6173 ret
->ai_canonname
= NULL
;
6174 ret
->ai_addr
= NULL
;
6175 ret
->ai_next
= NULL
;
6176 if (ai
->ai_canonname
)
6178 int len
= MultiByteToWideChar(CP_ACP
, 0, ai
->ai_canonname
, -1, NULL
, 0);
6179 if (!(ret
->ai_canonname
= HeapAlloc(GetProcessHeap(), 0, len
*sizeof(WCHAR
))))
6181 HeapFree(GetProcessHeap(), 0, ret
);
6184 MultiByteToWideChar(CP_ACP
, 0, ai
->ai_canonname
, -1, ret
->ai_canonname
, len
);
6188 if (!(ret
->ai_addr
= HeapAlloc(GetProcessHeap(), 0, ai
->ai_addrlen
)))
6190 HeapFree(GetProcessHeap(), 0, ret
->ai_canonname
);
6191 HeapFree(GetProcessHeap(), 0, ret
);
6194 memcpy(ret
->ai_addr
, ai
->ai_addr
, ai
->ai_addrlen
);
6199 static struct WS_addrinfoW
*addrinfo_list_AtoW(const struct WS_addrinfo
*info
)
6201 struct WS_addrinfoW
*ret
, *infoW
;
6203 if (!(ret
= infoW
= addrinfo_AtoW(info
))) return NULL
;
6204 while (info
->ai_next
)
6206 if (!(infoW
->ai_next
= addrinfo_AtoW(info
->ai_next
)))
6211 infoW
= infoW
->ai_next
;
6212 info
= info
->ai_next
;
6217 static struct WS_addrinfo
*addrinfo_WtoA(const struct WS_addrinfoW
*ai
)
6219 struct WS_addrinfo
*ret
;
6221 if (!(ret
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo
)))) return NULL
;
6222 ret
->ai_flags
= ai
->ai_flags
;
6223 ret
->ai_family
= ai
->ai_family
;
6224 ret
->ai_socktype
= ai
->ai_socktype
;
6225 ret
->ai_protocol
= ai
->ai_protocol
;
6226 ret
->ai_addrlen
= ai
->ai_addrlen
;
6227 ret
->ai_canonname
= NULL
;
6228 ret
->ai_addr
= NULL
;
6229 ret
->ai_next
= NULL
;
6230 if (ai
->ai_canonname
)
6232 int len
= WideCharToMultiByte(CP_ACP
, 0, ai
->ai_canonname
, -1, NULL
, 0, NULL
, NULL
);
6233 if (!(ret
->ai_canonname
= HeapAlloc(GetProcessHeap(), 0, len
)))
6235 HeapFree(GetProcessHeap(), 0, ret
);
6238 WideCharToMultiByte(CP_ACP
, 0, ai
->ai_canonname
, -1, ret
->ai_canonname
, len
, NULL
, NULL
);
6242 if (!(ret
->ai_addr
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr
))))
6244 HeapFree(GetProcessHeap(), 0, ret
->ai_canonname
);
6245 HeapFree(GetProcessHeap(), 0, ret
);
6248 memcpy(ret
->ai_addr
, ai
->ai_addr
, sizeof(struct WS_sockaddr
));
6253 /***********************************************************************
6254 * GetAddrInfoW (WS2_32.@)
6256 int WINAPI
GetAddrInfoW(LPCWSTR nodename
, LPCWSTR servname
, const ADDRINFOW
*hints
, PADDRINFOW
*res
)
6259 char *nodenameA
= NULL
, *servnameA
= NULL
;
6260 struct WS_addrinfo
*resA
, *hintsA
= NULL
;
6265 len
= WideCharToMultiByte(CP_ACP
, 0, nodename
, -1, NULL
, 0, NULL
, NULL
);
6266 if (!(nodenameA
= HeapAlloc(GetProcessHeap(), 0, len
))) return EAI_MEMORY
;
6267 WideCharToMultiByte(CP_ACP
, 0, nodename
, -1, nodenameA
, len
, NULL
, NULL
);
6271 len
= WideCharToMultiByte(CP_ACP
, 0, servname
, -1, NULL
, 0, NULL
, NULL
);
6272 if (!(servnameA
= HeapAlloc(GetProcessHeap(), 0, len
)))
6274 HeapFree(GetProcessHeap(), 0, nodenameA
);
6277 WideCharToMultiByte(CP_ACP
, 0, servname
, -1, servnameA
, len
, NULL
, NULL
);
6280 if (hints
) hintsA
= addrinfo_WtoA(hints
);
6281 ret
= WS_getaddrinfo(nodenameA
, servnameA
, hintsA
, &resA
);
6282 WS_freeaddrinfo(hintsA
);
6286 *res
= addrinfo_list_AtoW(resA
);
6287 WS_freeaddrinfo(resA
);
6290 HeapFree(GetProcessHeap(), 0, nodenameA
);
6291 HeapFree(GetProcessHeap(), 0, servnameA
);
6295 /***********************************************************************
6296 * FreeAddrInfoW (WS2_32.@)
6298 void WINAPI
FreeAddrInfoW(PADDRINFOW ai
)
6303 HeapFree(GetProcessHeap(), 0, ai
->ai_canonname
);
6304 HeapFree(GetProcessHeap(), 0, ai
->ai_addr
);
6306 HeapFree(GetProcessHeap(), 0, ai
);
6311 int WINAPI
WS_getnameinfo(const SOCKADDR
*sa
, WS_socklen_t salen
, PCHAR host
,
6312 DWORD hostlen
, PCHAR serv
, DWORD servlen
, INT flags
)
6314 #ifdef HAVE_GETNAMEINFO
6316 union generic_unix_sockaddr sa_u
;
6319 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa
), salen
, host
, hostlen
,
6320 serv
, servlen
, flags
);
6322 size
= ws_sockaddr_ws2u(sa
, salen
, &sa_u
);
6325 SetLastError(WSAEFAULT
);
6326 return WSA_NOT_ENOUGH_MEMORY
;
6328 ret
= getnameinfo(&sa_u
.addr
, size
, host
, hostlen
, serv
, servlen
, convert_niflag_w2u(flags
));
6329 return convert_eai_u2w(ret
);
6331 FIXME("getnameinfo() failed, not found during buildtime.\n");
6336 int WINAPI
GetNameInfoW(const SOCKADDR
*sa
, WS_socklen_t salen
, PWCHAR host
,
6337 DWORD hostlen
, PWCHAR serv
, DWORD servlen
, INT flags
)
6340 char *hostA
= NULL
, *servA
= NULL
;
6342 if (host
&& (!(hostA
= HeapAlloc(GetProcessHeap(), 0, hostlen
)))) return EAI_MEMORY
;
6343 if (serv
&& (!(servA
= HeapAlloc(GetProcessHeap(), 0, servlen
))))
6345 HeapFree(GetProcessHeap(), 0, hostA
);
6349 ret
= WS_getnameinfo(sa
, salen
, hostA
, hostlen
, servA
, servlen
, flags
);
6352 if (host
) MultiByteToWideChar(CP_ACP
, 0, hostA
, -1, host
, hostlen
);
6353 if (serv
) MultiByteToWideChar(CP_ACP
, 0, servA
, -1, serv
, servlen
);
6356 HeapFree(GetProcessHeap(), 0, hostA
);
6357 HeapFree(GetProcessHeap(), 0, servA
);
6361 /***********************************************************************
6362 * getservbyport (WS2_32.56)
6364 struct WS_servent
* WINAPI
WS_getservbyport(int port
, const char *proto
)
6366 struct WS_servent
* retval
= NULL
;
6367 #ifdef HAVE_GETSERVBYPORT
6368 struct servent
* serv
;
6369 char *proto_str
= NULL
;
6371 if (proto
&& *proto
)
6373 if (!(proto_str
= strdup_lower(proto
))) return NULL
;
6375 EnterCriticalSection( &csWSgetXXXbyYYY
);
6376 if( (serv
= getservbyport(port
, proto_str
)) != NULL
) {
6377 retval
= WS_dup_se(serv
);
6379 else SetLastError(WSANO_DATA
);
6380 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6381 HeapFree( GetProcessHeap(), 0, proto_str
);
6383 TRACE("%d (i.e. port %d), %s ret %p\n", port
, (int)ntohl(port
), debugstr_a(proto
), retval
);
6388 /***********************************************************************
6389 * gethostname (WS2_32.57)
6391 int WINAPI
WS_gethostname(char *name
, int namelen
)
6396 TRACE("name %p, len %d\n", name
, namelen
);
6400 SetLastError(WSAEFAULT
);
6401 return SOCKET_ERROR
;
6404 if (gethostname(buf
, sizeof(buf
)) != 0)
6406 SetLastError(wsaErrno());
6407 return SOCKET_ERROR
;
6410 TRACE("<- '%s'\n", buf
);
6413 WARN("Windows supports NetBIOS name length up to 15 bytes!\n");
6416 SetLastError(WSAEFAULT
);
6417 WARN("<- not enough space for hostname, required %d, got %d!\n", len
+ 1, namelen
);
6418 return SOCKET_ERROR
;
6425 /* ------------------------------------- Windows sockets extensions -- *
6427 * ------------------------------------------------------------------- */
6429 /***********************************************************************
6430 * WSAEnumNetworkEvents (WS2_32.36)
6432 int WINAPI
WSAEnumNetworkEvents(SOCKET s
, WSAEVENT hEvent
, LPWSANETWORKEVENTS lpEvent
)
6436 int errors
[FD_MAX_EVENTS
];
6438 TRACE("%04lx, hEvent %p, lpEvent %p\n", s
, hEvent
, lpEvent
);
6440 SERVER_START_REQ( get_socket_event
)
6442 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
6443 req
->service
= TRUE
;
6444 req
->c_event
= wine_server_obj_handle( hEvent
);
6445 wine_server_set_reply( req
, errors
, sizeof(errors
) );
6446 if (!(ret
= wine_server_call(req
))) lpEvent
->lNetworkEvents
= reply
->pmask
& reply
->mask
;
6451 for (i
= 0; i
< FD_MAX_EVENTS
; i
++)
6452 lpEvent
->iErrorCode
[i
] = NtStatusToWSAError(errors
[i
]);
6455 SetLastError(WSAEINVAL
);
6456 return SOCKET_ERROR
;
6459 /***********************************************************************
6460 * WSAEventSelect (WS2_32.39)
6462 int WINAPI
WSAEventSelect(SOCKET s
, WSAEVENT hEvent
, LONG lEvent
)
6466 TRACE("%04lx, hEvent %p, event %08x\n", s
, hEvent
, lEvent
);
6468 SERVER_START_REQ( set_socket_event
)
6470 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
6472 req
->event
= wine_server_obj_handle( hEvent
);
6475 ret
= wine_server_call( req
);
6479 SetLastError(WSAEINVAL
);
6480 return SOCKET_ERROR
;
6483 /**********************************************************************
6484 * WSAGetOverlappedResult (WS2_32.40)
6486 BOOL WINAPI
WSAGetOverlappedResult( SOCKET s
, LPWSAOVERLAPPED lpOverlapped
,
6487 LPDWORD lpcbTransfer
, BOOL fWait
,
6492 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
6493 s
, lpOverlapped
, lpcbTransfer
, fWait
, lpdwFlags
);
6495 if ( lpOverlapped
== NULL
)
6497 ERR( "Invalid pointer\n" );
6498 SetLastError(WSA_INVALID_PARAMETER
);
6502 status
= lpOverlapped
->Internal
;
6503 if (status
== STATUS_PENDING
)
6507 SetLastError( WSA_IO_INCOMPLETE
);
6511 if (WaitForSingleObject( lpOverlapped
->hEvent
? lpOverlapped
->hEvent
: SOCKET2HANDLE(s
),
6512 INFINITE
) == WAIT_FAILED
)
6514 status
= lpOverlapped
->Internal
;
6518 *lpcbTransfer
= lpOverlapped
->InternalHigh
;
6521 *lpdwFlags
= lpOverlapped
->u
.s
.Offset
;
6523 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
6528 /***********************************************************************
6529 * WSAAsyncSelect (WS2_32.101)
6531 INT WINAPI
WSAAsyncSelect(SOCKET s
, HWND hWnd
, UINT uMsg
, LONG lEvent
)
6535 TRACE("%04lx, hWnd %p, uMsg %08x, event %08x\n", s
, hWnd
, uMsg
, lEvent
);
6537 SERVER_START_REQ( set_socket_event
)
6539 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
6542 req
->window
= wine_server_user_handle( hWnd
);
6544 ret
= wine_server_call( req
);
6548 SetLastError(WSAEINVAL
);
6549 return SOCKET_ERROR
;
6552 /***********************************************************************
6553 * WSACreateEvent (WS2_32.31)
6556 WSAEVENT WINAPI
WSACreateEvent(void)
6558 /* Create a manual-reset event, with initial state: unsignaled */
6561 return CreateEventW(NULL
, TRUE
, FALSE
, NULL
);
6564 /***********************************************************************
6565 * WSACloseEvent (WS2_32.29)
6568 BOOL WINAPI
WSACloseEvent(WSAEVENT event
)
6570 TRACE ("event=%p\n", event
);
6572 return CloseHandle(event
);
6575 /***********************************************************************
6576 * WSASocketA (WS2_32.78)
6579 SOCKET WINAPI
WSASocketA(int af
, int type
, int protocol
,
6580 LPWSAPROTOCOL_INFOA lpProtocolInfo
,
6581 GROUP g
, DWORD dwFlags
)
6584 WSAPROTOCOL_INFOW info
;
6586 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6587 af
, type
, protocol
, lpProtocolInfo
, g
, dwFlags
);
6589 if (!lpProtocolInfo
) return WSASocketW(af
, type
, protocol
, NULL
, g
, dwFlags
);
6591 memcpy(&info
, lpProtocolInfo
, FIELD_OFFSET(WSAPROTOCOL_INFOW
, szProtocol
));
6592 len
= MultiByteToWideChar(CP_ACP
, 0, lpProtocolInfo
->szProtocol
, -1,
6593 info
.szProtocol
, WSAPROTOCOL_LEN
+ 1);
6597 SetLastError(WSAEINVAL
);
6598 return SOCKET_ERROR
;
6601 return WSASocketW(af
, type
, protocol
, &info
, g
, dwFlags
);
6604 /***********************************************************************
6605 * WSASocketW (WS2_32.79)
6608 SOCKET WINAPI
WSASocketW(int af
, int type
, int protocol
,
6609 LPWSAPROTOCOL_INFOW lpProtocolInfo
,
6610 GROUP g
, DWORD dwFlags
)
6614 int unixaf
, unixtype
, ipxptype
= -1;
6617 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
6618 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
6621 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6622 af
, type
, protocol
, lpProtocolInfo
, g
, dwFlags
);
6626 err
= WSANOTINITIALISED
;
6630 /* hack for WSADuplicateSocket */
6631 if (lpProtocolInfo
&& lpProtocolInfo
->dwServiceFlags4
== 0xff00ff00) {
6632 ret
= lpProtocolInfo
->dwServiceFlags3
;
6633 TRACE("\tgot duplicate %04lx\n", ret
);
6639 if (af
== FROM_PROTOCOL_INFO
|| !af
)
6640 af
= lpProtocolInfo
->iAddressFamily
;
6641 if (type
== FROM_PROTOCOL_INFO
|| !type
)
6642 type
= lpProtocolInfo
->iSocketType
;
6643 if (protocol
== FROM_PROTOCOL_INFO
|| !protocol
)
6644 protocol
= lpProtocolInfo
->iProtocol
;
6647 if (!type
&& (af
|| protocol
))
6649 int autoproto
= protocol
;
6650 WSAPROTOCOL_INFOW infow
;
6652 /* default to the first valid protocol */
6654 autoproto
= valid_protocols
[0];
6655 else if(IS_IPX_PROTO(autoproto
))
6656 autoproto
= WS_NSPROTO_IPX
;
6658 if (WS_EnterSingleProtocolW(autoproto
, &infow
))
6660 type
= infow
.iSocketType
;
6662 /* after win2003 it's no longer possible to pass AF_UNSPEC
6663 using the protocol info struct */
6664 if (!lpProtocolInfo
&& af
== WS_AF_UNSPEC
)
6665 af
= infow
.iAddressFamily
;
6670 Windows has an extension to the IPX protocol that allows one to create sockets
6671 and set the IPX packet type at the same time, to do that a caller will use
6672 a protocol like NSPROTO_IPX + <PACKET TYPE>
6674 if (IS_IPX_PROTO(protocol
))
6675 ipxptype
= protocol
- WS_NSPROTO_IPX
;
6677 /* convert the socket family, type and protocol */
6678 unixaf
= convert_af_w2u(af
);
6679 unixtype
= convert_socktype_w2u(type
);
6680 protocol
= convert_proto_w2u(protocol
);
6681 if (unixaf
== AF_UNSPEC
) unixaf
= -1;
6683 /* filter invalid parameters */
6686 /* the type could not be converted */
6687 if (type
&& unixtype
< 0)
6689 err
= WSAESOCKTNOSUPPORT
;
6693 err
= WSAEPROTONOSUPPORT
;
6698 /* both family and protocol can't be invalid */
6705 /* family could not be converted and neither socket type */
6706 if (unixtype
< 0 && af
>= 0)
6709 err
= WSAESOCKTNOSUPPORT
;
6713 err
= WSAEAFNOSUPPORT
;
6717 SERVER_START_REQ( create_socket
)
6719 req
->family
= unixaf
;
6720 req
->type
= unixtype
;
6721 req
->protocol
= protocol
;
6722 req
->access
= GENERIC_READ
|GENERIC_WRITE
|SYNCHRONIZE
;
6723 req
->attributes
= (dwFlags
& WSA_FLAG_NO_HANDLE_INHERIT
) ? 0 : OBJ_INHERIT
;
6724 req
->flags
= dwFlags
& ~WSA_FLAG_NO_HANDLE_INHERIT
;
6725 set_error( wine_server_call( req
) );
6726 ret
= HANDLE2SOCKET( wine_server_ptr_handle( reply
->handle
));
6731 TRACE("\tcreated %04lx\n", ret
);
6733 set_ipx_packettype(ret
, ipxptype
);
6737 err
= GetLastError();
6738 if (err
== WSAEACCES
) /* raw socket denied */
6740 if (type
== SOCK_RAW
)
6741 ERR_(winediag
)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
6743 ERR_(winediag
)("Failed to create socket, this requires special permissions.\n");
6747 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
6748 if (err
== WSAEINVAL
)
6749 err
= WSAESOCKTNOSUPPORT
;
6750 else if (err
== WSAEOPNOTSUPP
)
6751 err
= WSAEPROTONOSUPPORT
;
6755 WARN("\t\tfailed, error %d!\n", err
);
6757 return INVALID_SOCKET
;
6760 /***********************************************************************
6761 * WSAJoinLeaf (WS2_32.58)
6764 SOCKET WINAPI
WSAJoinLeaf(
6766 const struct WS_sockaddr
*addr
,
6768 LPWSABUF lpCallerData
,
6769 LPWSABUF lpCalleeData
,
6775 return INVALID_SOCKET
;
6778 /***********************************************************************
6779 * __WSAFDIsSet (WS2_32.151)
6781 int WINAPI
__WSAFDIsSet(SOCKET s
, WS_fd_set
*set
)
6783 int i
= set
->fd_count
, ret
= 0;
6786 if (set
->fd_array
[i
] == s
)
6792 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s
, set
, set
->fd_count
, ret
);
6796 /***********************************************************************
6797 * WSAIsBlocking (WS2_32.114)
6799 BOOL WINAPI
WSAIsBlocking(void)
6801 /* By default WinSock should set all its sockets to non-blocking mode
6802 * and poll in PeekMessage loop when processing "blocking" ones. This
6803 * function is supposed to tell if the program is in this loop. Our
6804 * blocking calls are truly blocking so we always return FALSE.
6806 * Note: It is allowed to call this function without prior WSAStartup().
6813 /***********************************************************************
6814 * WSACancelBlockingCall (WS2_32.113)
6816 INT WINAPI
WSACancelBlockingCall(void)
6822 static INT WINAPI
WSA_DefaultBlockingHook( FARPROC x
)
6824 FIXME("How was this called?\n");
6829 /***********************************************************************
6830 * WSASetBlockingHook (WS2_32.109)
6832 FARPROC WINAPI
WSASetBlockingHook(FARPROC lpBlockFunc
)
6834 FARPROC prev
= blocking_hook
;
6835 blocking_hook
= lpBlockFunc
;
6836 TRACE("hook %p\n", lpBlockFunc
);
6841 /***********************************************************************
6842 * WSAUnhookBlockingHook (WS2_32.110)
6844 INT WINAPI
WSAUnhookBlockingHook(void)
6846 blocking_hook
= (FARPROC
)WSA_DefaultBlockingHook
;
6851 /* ----------------------------------- end of API stuff */
6853 /* ----------------------------------- helper functions -
6855 * TODO: Merge WS_dup_..() stuff into one function that
6856 * would operate with a generic structure containing internal
6857 * pointers (via a template of some kind).
6860 static int list_size(char** l
, int item_size
)
6865 j
+= (item_size
) ? item_size
: strlen(l
[i
]) + 1;
6866 j
+= (i
+ 1) * sizeof(char*); }
6870 static int list_dup(char** l_src
, char** l_to
, int item_size
)
6875 for (i
= 0; l_src
[i
]; i
++) ;
6876 p
= (char *)(l_to
+ i
+ 1);
6877 for (i
= 0; l_src
[i
]; i
++)
6879 int count
= ( item_size
) ? item_size
: strlen(l_src
[i
]) + 1;
6880 memcpy(p
, l_src
[i
], count
);
6885 return p
- (char *)l_to
;
6890 /* create a hostent entry
6892 * Creates the entry with enough memory for the name, aliases
6893 * addresses, and the address pointers. Also copies the name
6894 * and sets up all the pointers.
6896 * NOTE: The alias and address lists must be allocated with room
6897 * for the NULL item terminating the list. This is true even if
6898 * the list has no items ("aliases" and "addresses" must be
6899 * at least "1", a truly empty list is invalid).
6901 static struct WS_hostent
*WS_create_he(char *name
, int aliases
, int aliases_size
, int addresses
, int address_length
)
6903 struct WS_hostent
*p_to
;
6905 int size
= (sizeof(struct WS_hostent
) +
6907 sizeof(char *) * aliases
+
6909 sizeof(char *) * addresses
+
6910 address_length
* (addresses
- 1)), i
;
6912 if (!(p_to
= check_buffer_he(size
))) return NULL
;
6913 memset(p_to
, 0, size
);
6915 /* Use the memory in the same way winsock does.
6916 * First set the pointer for aliases, second set the pointers for addresses.
6917 * Third fill the addresses indexes, fourth jump aliases names size.
6918 * Fifth fill the hostname.
6919 * NOTE: This method is valid for OS version's >= XP.
6921 p
= (char *)(p_to
+ 1);
6922 p_to
->h_aliases
= (char **)p
;
6923 p
+= sizeof(char *)*aliases
;
6925 p_to
->h_addr_list
= (char **)p
;
6926 p
+= sizeof(char *)*addresses
;
6928 for (i
= 0, addresses
--; i
< addresses
; i
++, p
+= address_length
)
6929 p_to
->h_addr_list
[i
] = p
;
6931 /* NOTE: h_aliases must be filled in manually because we don't know each string
6932 * size, leave these pointers NULL (already set to NULL by memset earlier).
6942 /* duplicate hostent entry
6943 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
6944 * Ditto for protoent and servent.
6946 static struct WS_hostent
*WS_dup_he(const struct hostent
* p_he
)
6948 int i
, addresses
= 0, alias_size
= 0;
6949 struct WS_hostent
*p_to
;
6952 for( i
= 0; p_he
->h_aliases
[i
]; i
++) alias_size
+= strlen(p_he
->h_aliases
[i
]) + 1;
6953 while (p_he
->h_addr_list
[addresses
]) addresses
++;
6955 p_to
= WS_create_he(p_he
->h_name
, i
+ 1, alias_size
, addresses
+ 1, p_he
->h_length
);
6957 if (!p_to
) return NULL
;
6958 p_to
->h_addrtype
= convert_af_u2w(p_he
->h_addrtype
);
6959 p_to
->h_length
= p_he
->h_length
;
6961 for(i
= 0, p
= p_to
->h_addr_list
[0]; p_he
->h_addr_list
[i
]; i
++, p
+= p_to
->h_length
)
6962 memcpy(p
, p_he
->h_addr_list
[i
], p_to
->h_length
);
6964 /* Fill the aliases after the IP data */
6965 for(i
= 0; p_he
->h_aliases
[i
]; i
++)
6967 p_to
->h_aliases
[i
] = p
;
6968 strcpy(p
, p_he
->h_aliases
[i
]);
6975 /* ----- protoent */
6977 static struct WS_protoent
*WS_dup_pe(const struct protoent
* p_pe
)
6980 struct WS_protoent
*p_to
;
6982 int size
= (sizeof(*p_pe
) +
6983 strlen(p_pe
->p_name
) + 1 +
6984 list_size(p_pe
->p_aliases
, 0));
6986 if (!(p_to
= check_buffer_pe(size
))) return NULL
;
6987 p_to
->p_proto
= p_pe
->p_proto
;
6989 p
= (char *)(p_to
+ 1);
6991 strcpy(p
, p_pe
->p_name
);
6994 p_to
->p_aliases
= (char **)p
;
6995 list_dup(p_pe
->p_aliases
, p_to
->p_aliases
, 0);
7001 static struct WS_servent
*WS_dup_se(const struct servent
* p_se
)
7004 struct WS_servent
*p_to
;
7006 int size
= (sizeof(*p_se
) +
7007 strlen(p_se
->s_proto
) + 1 +
7008 strlen(p_se
->s_name
) + 1 +
7009 list_size(p_se
->s_aliases
, 0));
7011 if (!(p_to
= check_buffer_se(size
))) return NULL
;
7012 p_to
->s_port
= p_se
->s_port
;
7014 p
= (char *)(p_to
+ 1);
7016 strcpy(p
, p_se
->s_name
);
7020 strcpy(p
, p_se
->s_proto
);
7023 p_to
->s_aliases
= (char **)p
;
7024 list_dup(p_se
->s_aliases
, p_to
->s_aliases
, 0);
7029 /***********************************************************************
7030 * WSARecv (WS2_32.67)
7032 int WINAPI
WSARecv(SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
7033 LPDWORD NumberOfBytesReceived
, LPDWORD lpFlags
,
7034 LPWSAOVERLAPPED lpOverlapped
,
7035 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
7037 return WS2_recv_base(s
, lpBuffers
, dwBufferCount
, NumberOfBytesReceived
, lpFlags
,
7038 NULL
, NULL
, lpOverlapped
, lpCompletionRoutine
, NULL
);
7041 static int WS2_recv_base( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
7042 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
,
7043 struct WS_sockaddr
*lpFrom
,
7044 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
7045 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
,
7046 LPWSABUF lpControlBuffer
)
7048 unsigned int i
, options
;
7049 int n
, fd
, err
, overlapped
, flags
;
7050 struct ws2_async
*wsa
= NULL
, localwsa
;
7052 DWORD timeout_start
= GetTickCount();
7053 ULONG_PTR cvalue
= (lpOverlapped
&& ((ULONG_PTR
)lpOverlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)lpOverlapped
: 0;
7055 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
7056 s
, lpBuffers
, dwBufferCount
, *lpFlags
, lpFrom
,
7057 (lpFromlen
? *lpFromlen
: -1),
7058 lpOverlapped
, lpCompletionRoutine
);
7060 fd
= get_sock_fd( s
, FILE_READ_DATA
, &options
);
7061 TRACE( "fd=%d, options=%x\n", fd
, options
);
7063 if (fd
== -1) return SOCKET_ERROR
;
7065 if (*lpFlags
& WS_MSG_OOB
)
7067 /* It's invalid to receive OOB data from an OOBINLINED socket
7068 * as OOB data is turned into normal data. */
7070 if (!getsockopt(fd
, SOL_SOCKET
, SO_OOBINLINE
, (char*) &n
, &i
) && n
)
7077 overlapped
= (lpOverlapped
|| lpCompletionRoutine
) &&
7078 !(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
));
7079 if (overlapped
|| dwBufferCount
> 1)
7081 if (!(wsa
= (struct ws2_async
*)alloc_async_io( offsetof(struct ws2_async
, iovec
[dwBufferCount
]))))
7090 wsa
->hSocket
= SOCKET2HANDLE(s
);
7091 wsa
->flags
= *lpFlags
;
7092 wsa
->lpFlags
= lpFlags
;
7094 wsa
->addrlen
.ptr
= lpFromlen
;
7095 wsa
->control
= lpControlBuffer
;
7096 wsa
->n_iovecs
= dwBufferCount
;
7097 wsa
->first_iovec
= 0;
7098 for (i
= 0; i
< dwBufferCount
; i
++)
7100 /* check buffer first to trigger write watches */
7101 if (IsBadWritePtr( lpBuffers
[i
].buf
, lpBuffers
[i
].len
))
7106 wsa
->iovec
[i
].iov_base
= lpBuffers
[i
].buf
;
7107 wsa
->iovec
[i
].iov_len
= lpBuffers
[i
].len
;
7110 flags
= convert_flags(wsa
->flags
);
7113 n
= WS2_recv( fd
, wsa
, flags
);
7116 /* Unix-like systems return EINVAL when attempting to read OOB data from
7117 * an empty socket buffer, convert that to a Windows expected return. */
7118 if ((flags
& MSG_OOB
) && errno
== EINVAL
)
7119 errno
= EWOULDBLOCK
;
7121 if (errno
!= EAGAIN
)
7123 int loc_errno
= errno
;
7125 if (cvalue
) WS_AddCompletion( s
, cvalue
, sock_get_ntstatus(loc_errno
), 0 );
7129 else if (lpNumberOfBytesRecvd
) *lpNumberOfBytesRecvd
= n
;
7133 IO_STATUS_BLOCK
*iosb
= lpOverlapped
? (IO_STATUS_BLOCK
*)lpOverlapped
: &wsa
->local_iosb
;
7135 wsa
->user_overlapped
= lpOverlapped
;
7136 wsa
->completion_func
= lpCompletionRoutine
;
7137 release_sock_fd( s
, fd
);
7141 iosb
->u
.Status
= STATUS_PENDING
;
7142 iosb
->Information
= 0;
7144 SERVER_START_REQ( register_async
)
7146 req
->type
= ASYNC_TYPE_READ
;
7147 req
->async
.handle
= wine_server_obj_handle( wsa
->hSocket
);
7148 req
->async
.callback
= wine_server_client_ptr( WS2_async_recv
);
7149 req
->async
.iosb
= wine_server_client_ptr( iosb
);
7150 req
->async
.arg
= wine_server_client_ptr( wsa
);
7151 req
->async
.event
= wine_server_obj_handle( lpCompletionRoutine
? 0 : lpOverlapped
->hEvent
);
7152 req
->async
.cvalue
= cvalue
;
7153 err
= wine_server_call( req
);
7157 if (err
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
7158 SetLastError(NtStatusToWSAError( err
));
7159 return SOCKET_ERROR
;
7162 iosb
->u
.Status
= STATUS_SUCCESS
;
7163 iosb
->Information
= n
;
7164 if (!wsa
->completion_func
)
7166 if (cvalue
) WS_AddCompletion( s
, cvalue
, STATUS_SUCCESS
, n
);
7167 if (lpOverlapped
->hEvent
) SetEvent( lpOverlapped
->hEvent
);
7168 HeapFree( GetProcessHeap(), 0, wsa
);
7170 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC
)ws2_async_apc
,
7171 (ULONG_PTR
)wsa
, (ULONG_PTR
)iosb
, 0 );
7172 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7178 if ((err
= _is_blocking( s
, &is_blocking
)))
7180 err
= NtStatusToWSAError( err
);
7187 int poll_timeout
= -1;
7188 INT64 timeout
= get_rcvsnd_timeo(fd
, TRUE
);
7192 timeout
-= GetTickCount() - timeout_start
;
7193 if (timeout
< 0) poll_timeout
= 0;
7194 else poll_timeout
= timeout
<= INT_MAX
? timeout
: INT_MAX
;
7198 pfd
.events
= POLLIN
;
7199 if (*lpFlags
& WS_MSG_OOB
) pfd
.events
|= POLLPRI
;
7201 if (!poll_timeout
|| !poll( &pfd
, 1, poll_timeout
))
7204 /* a timeout is not fatal */
7205 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7211 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7212 err
= WSAEWOULDBLOCK
;
7217 TRACE(" -> %i bytes\n", n
);
7218 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
7219 release_sock_fd( s
, fd
);
7220 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7221 SetLastError(ERROR_SUCCESS
);
7226 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
7227 release_sock_fd( s
, fd
);
7228 WARN(" -> ERROR %d\n", err
);
7229 SetLastError( err
);
7230 return SOCKET_ERROR
;
7233 /***********************************************************************
7234 * WSARecvFrom (WS2_32.69)
7236 INT WINAPI
WSARecvFrom( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
7237 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
, struct WS_sockaddr
*lpFrom
,
7238 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
7239 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
7242 return WS2_recv_base( s
, lpBuffers
, dwBufferCount
,
7243 lpNumberOfBytesRecvd
, lpFlags
,
7245 lpOverlapped
, lpCompletionRoutine
, NULL
);
7248 /***********************************************************************
7249 * WSCInstallProvider (WS2_32.88)
7251 INT WINAPI
WSCInstallProvider( const LPGUID lpProviderId
,
7252 LPCWSTR lpszProviderDllPath
,
7253 const LPWSAPROTOCOL_INFOW lpProtocolInfoList
,
7254 DWORD dwNumberOfEntries
,
7257 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId
),
7258 debugstr_w(lpszProviderDllPath
), lpProtocolInfoList
,
7259 dwNumberOfEntries
, lpErrno
);
7265 /***********************************************************************
7266 * WSCDeinstallProvider (WS2_32.83)
7268 INT WINAPI
WSCDeinstallProvider(LPGUID lpProviderId
, LPINT lpErrno
)
7270 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId
), lpErrno
);
7276 /***********************************************************************
7277 * WSAAccept (WS2_32.26)
7279 SOCKET WINAPI
WSAAccept( SOCKET s
, struct WS_sockaddr
*addr
, LPINT addrlen
,
7280 LPCONDITIONPROC lpfnCondition
, DWORD_PTR dwCallbackData
)
7284 WSABUF CallerId
, CallerData
, CalleeId
, CalleeData
;
7285 /* QOS SQOS, GQOS; */
7288 SOCKADDR src_addr
, dst_addr
;
7290 TRACE("socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
7291 s
, addr
, addrlen
, lpfnCondition
, dwCallbackData
);
7293 cs
= WS_accept(s
, addr
, addrlen
);
7294 if (cs
== SOCKET_ERROR
) return SOCKET_ERROR
;
7295 if (!lpfnCondition
) return cs
;
7297 if (addr
&& addrlen
)
7299 CallerId
.buf
= (char *)addr
;
7300 CallerId
.len
= *addrlen
;
7304 size
= sizeof(src_addr
);
7305 WS_getpeername(cs
, &src_addr
, &size
);
7306 CallerId
.buf
= (char *)&src_addr
;
7307 CallerId
.len
= size
;
7309 CallerData
.buf
= NULL
;
7312 size
= sizeof(dst_addr
);
7313 WS_getsockname(cs
, &dst_addr
, &size
);
7315 CalleeId
.buf
= (char *)&dst_addr
;
7316 CalleeId
.len
= sizeof(dst_addr
);
7318 ret
= (*lpfnCondition
)(&CallerId
, &CallerData
, NULL
, NULL
,
7319 &CalleeId
, &CalleeData
, &g
, dwCallbackData
);
7326 SERVER_START_REQ( set_socket_deferred
)
7328 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
7329 req
->deferred
= wine_server_obj_handle( SOCKET2HANDLE(cs
) );
7330 if ( !wine_server_call_err ( req
) )
7332 SetLastError( WSATRY_AGAIN
);
7333 WS_closesocket( cs
);
7337 return SOCKET_ERROR
;
7340 SetLastError(WSAECONNREFUSED
);
7341 return SOCKET_ERROR
;
7343 FIXME("Unknown return type from Condition function\n");
7344 SetLastError(WSAENOTSOCK
);
7345 return SOCKET_ERROR
;
7349 /***********************************************************************
7350 * WSADuplicateSocketA (WS2_32.32)
7352 int WINAPI
WSADuplicateSocketA( SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOA lpProtocolInfo
)
7354 return WS_DuplicateSocket(FALSE
, s
, dwProcessId
, (LPWSAPROTOCOL_INFOW
) lpProtocolInfo
);
7357 /***********************************************************************
7358 * WSADuplicateSocketW (WS2_32.33)
7360 int WINAPI
WSADuplicateSocketW( SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOW lpProtocolInfo
)
7362 return WS_DuplicateSocket(TRUE
, s
, dwProcessId
, lpProtocolInfo
);
7365 /***********************************************************************
7366 * WSAInstallServiceClassA (WS2_32.48)
7368 int WINAPI
WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info
)
7370 FIXME("Request to install service %s\n",debugstr_a(info
->lpszServiceClassName
));
7371 SetLastError(WSAEACCES
);
7372 return SOCKET_ERROR
;
7375 /***********************************************************************
7376 * WSAInstallServiceClassW (WS2_32.49)
7378 int WINAPI
WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info
)
7380 FIXME("Request to install service %s\n",debugstr_w(info
->lpszServiceClassName
));
7381 SetLastError(WSAEACCES
);
7382 return SOCKET_ERROR
;
7385 /***********************************************************************
7386 * WSARemoveServiceClass (WS2_32.70)
7388 int WINAPI
WSARemoveServiceClass(LPGUID info
)
7390 FIXME("Request to remove service %p\n",info
);
7391 SetLastError(WSATYPE_NOT_FOUND
);
7392 return SOCKET_ERROR
;
7395 /***********************************************************************
7396 * inet_ntop (WS2_32.@)
7398 PCSTR WINAPI
WS_inet_ntop( INT family
, PVOID addr
, PSTR buffer
, SIZE_T len
)
7400 #ifdef HAVE_INET_NTOP
7401 struct WS_in6_addr
*in6
;
7402 struct WS_in_addr
*in
;
7405 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family
, addr
, buffer
, len
);
7408 SetLastError( STATUS_INVALID_PARAMETER
);
7417 pdst
= inet_ntop( AF_INET
, &in
->WS_s_addr
, buffer
, len
);
7423 pdst
= inet_ntop( AF_INET6
, in6
->WS_s6_addr
, buffer
, len
);
7427 SetLastError( WSAEAFNOSUPPORT
);
7431 if (!pdst
) SetLastError( STATUS_INVALID_PARAMETER
);
7434 FIXME( "not supported on this platform\n" );
7435 SetLastError( WSAEAFNOSUPPORT
);
7440 /***********************************************************************
7441 * inet_pton (WS2_32.@)
7443 INT WINAPI
WS_inet_pton( INT family
, PCSTR addr
, PVOID buffer
)
7445 #ifdef HAVE_INET_PTON
7448 TRACE("family %d, addr %s, buffer (%p)\n", family
, debugstr_a(addr
), buffer
);
7450 if (!addr
|| !buffer
)
7452 SetLastError(WSAEFAULT
);
7453 return SOCKET_ERROR
;
7456 unixaf
= convert_af_w2u(family
);
7457 if (unixaf
!= AF_INET
&& unixaf
!= AF_INET6
)
7459 SetLastError(WSAEAFNOSUPPORT
);
7460 return SOCKET_ERROR
;
7463 ret
= inet_pton(unixaf
, addr
, buffer
);
7464 if (ret
== -1) SetLastError(wsaErrno());
7467 FIXME( "not supported on this platform\n" );
7468 SetLastError( WSAEAFNOSUPPORT
);
7469 return SOCKET_ERROR
;
7473 /***********************************************************************
7474 * InetPtonW (WS2_32.@)
7476 INT WINAPI
InetPtonW(INT family
, PCWSTR addr
, PVOID buffer
)
7482 TRACE("family %d, addr %s, buffer (%p)\n", family
, debugstr_w(addr
), buffer
);
7486 SetLastError(WSAEFAULT
);
7487 return SOCKET_ERROR
;
7490 len
= WideCharToMultiByte(CP_ACP
, 0, addr
, -1, NULL
, 0, NULL
, NULL
);
7491 if (!(addrA
= HeapAlloc(GetProcessHeap(), 0, len
)))
7493 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
7494 return SOCKET_ERROR
;
7496 WideCharToMultiByte(CP_ACP
, 0, addr
, -1, addrA
, len
, NULL
, NULL
);
7498 ret
= WS_inet_pton(family
, addrA
, buffer
);
7500 HeapFree(GetProcessHeap(), 0, addrA
);
7504 /***********************************************************************
7505 * WSAStringToAddressA (WS2_32.80)
7507 INT WINAPI
WSAStringToAddressA(LPSTR AddressString
,
7509 LPWSAPROTOCOL_INFOA lpProtocolInfo
,
7510 LPSOCKADDR lpAddress
,
7511 LPINT lpAddressLength
)
7514 LPSTR workBuffer
=NULL
,ptrPort
;
7516 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString
), AddressFamily
,
7517 lpProtocolInfo
, lpAddress
, lpAddressLength
);
7519 if (!lpAddressLength
|| !lpAddress
) return SOCKET_ERROR
;
7523 SetLastError(WSAEINVAL
);
7524 return SOCKET_ERROR
;
7528 FIXME("ProtocolInfo not implemented.\n");
7530 workBuffer
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
,
7531 strlen(AddressString
) + 1);
7534 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
7535 return SOCKET_ERROR
;
7538 strcpy(workBuffer
, AddressString
);
7540 switch(AddressFamily
)
7544 struct in_addr inetaddr
;
7546 /* If lpAddressLength is too small, tell caller the size we need */
7547 if (*lpAddressLength
< sizeof(SOCKADDR_IN
))
7549 *lpAddressLength
= sizeof(SOCKADDR_IN
);
7553 *lpAddressLength
= sizeof(SOCKADDR_IN
);
7554 memset(lpAddress
, 0, sizeof(SOCKADDR_IN
));
7556 ((LPSOCKADDR_IN
)lpAddress
)->sin_family
= WS_AF_INET
;
7558 ptrPort
= strchr(workBuffer
, ':');
7561 /* User may have entered an IPv6 and asked to parse as IPv4 */
7562 if(strchr(ptrPort
+ 1, ':'))
7567 ((LPSOCKADDR_IN
)lpAddress
)->sin_port
= htons(atoi(ptrPort
+1));
7572 ((LPSOCKADDR_IN
)lpAddress
)->sin_port
= 0;
7575 if(inet_aton(workBuffer
, &inetaddr
) > 0)
7577 ((LPSOCKADDR_IN
)lpAddress
)->sin_addr
.WS_s_addr
= inetaddr
.s_addr
;
7588 struct in6_addr inetaddr
;
7589 /* If lpAddressLength is too small, tell caller the size we need */
7590 if (*lpAddressLength
< sizeof(SOCKADDR_IN6
))
7592 *lpAddressLength
= sizeof(SOCKADDR_IN6
);
7596 #ifdef HAVE_INET_PTON
7597 *lpAddressLength
= sizeof(SOCKADDR_IN6
);
7598 memset(lpAddress
, 0, sizeof(SOCKADDR_IN6
));
7600 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_family
= WS_AF_INET6
;
7602 /* This one is a bit tricky. An IPv6 address contains colons, so the
7603 * check from IPv4 doesn't work like that. However, IPv6 addresses that
7604 * contain a port are written with braces like [fd12:3456:7890::1]:12345
7605 * so what we will do is to look for ']', check if the next char is a
7606 * colon, and if it is, parse the port as in IPv4. */
7608 ptrPort
= strchr(workBuffer
, ']');
7609 if(ptrPort
&& *(++ptrPort
) == ':')
7611 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_port
= htons(atoi(ptrPort
+1));
7616 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_port
= 0;
7619 if(inet_pton(AF_INET6
, workBuffer
, &inetaddr
) > 0)
7621 memcpy(&((LPSOCKADDR_IN6
)lpAddress
)->sin6_addr
, &inetaddr
,
7622 sizeof(struct in6_addr
));
7626 #endif /* HAVE_INET_PTON */
7632 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
7633 TRACE("Unsupported address family specified: %d.\n", AddressFamily
);
7637 HeapFree(GetProcessHeap(), 0, workBuffer
);
7641 return SOCKET_ERROR
;
7644 /***********************************************************************
7645 * WSAStringToAddressW (WS2_32.81)
7647 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
7648 * If this should be the case, it would be required to map these digits
7649 * to Unicode digits (0-9) using FoldString first.
7651 INT WINAPI
WSAStringToAddressW(LPWSTR AddressString
,
7653 LPWSAPROTOCOL_INFOW lpProtocolInfo
,
7654 LPSOCKADDR lpAddress
,
7655 LPINT lpAddressLength
)
7658 LPSTR workBuffer
=NULL
;
7659 WSAPROTOCOL_INFOA infoA
;
7660 LPWSAPROTOCOL_INFOA lpProtoInfoA
= NULL
;
7662 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString
), AddressFamily
, lpProtocolInfo
,
7663 lpAddress
, lpAddressLength
);
7665 if (!lpAddressLength
|| !lpAddress
) return SOCKET_ERROR
;
7667 /* if ProtocolInfo is available - convert to ANSI variant */
7670 lpProtoInfoA
= &infoA
;
7671 memcpy( lpProtoInfoA
, lpProtocolInfo
, FIELD_OFFSET( WSAPROTOCOL_INFOA
, szProtocol
) );
7673 if (!WideCharToMultiByte( CP_ACP
, 0, lpProtocolInfo
->szProtocol
, -1,
7674 lpProtoInfoA
->szProtocol
, WSAPROTOCOL_LEN
+1, NULL
, NULL
))
7676 SetLastError(WSAEINVAL
);
7677 return SOCKET_ERROR
;
7683 /* Translate AddressString to ANSI code page - assumes that only
7684 standard digits 0-9 are used with this API call */
7685 sBuffer
= WideCharToMultiByte( CP_ACP
, 0, AddressString
, -1, NULL
, 0, NULL
, NULL
);
7686 workBuffer
= HeapAlloc( GetProcessHeap(), 0, sBuffer
);
7690 WideCharToMultiByte( CP_ACP
, 0, AddressString
, -1, workBuffer
, sBuffer
, NULL
, NULL
);
7691 res
= WSAStringToAddressA(workBuffer
,AddressFamily
,lpProtoInfoA
,
7692 lpAddress
,lpAddressLength
);
7693 HeapFree( GetProcessHeap(), 0, workBuffer
);
7697 res
= WSA_NOT_ENOUGH_MEMORY
;
7703 return SOCKET_ERROR
;
7706 /***********************************************************************
7707 * WSAAddressToStringA (WS2_32.27)
7709 * See WSAAddressToStringW
7711 INT WINAPI
WSAAddressToStringA( LPSOCKADDR sockaddr
, DWORD len
,
7712 LPWSAPROTOCOL_INFOA info
, LPSTR string
,
7716 CHAR buffer
[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7719 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr
, len
, info
, string
, lenstr
);
7721 if (!sockaddr
) return SOCKET_ERROR
;
7722 if (!string
|| !lenstr
) return SOCKET_ERROR
;
7724 switch(sockaddr
->sa_family
)
7727 if (len
< sizeof(SOCKADDR_IN
)) return SOCKET_ERROR
;
7728 sprintf( buffer
, "%u.%u.%u.%u:%u",
7729 (unsigned int)(ntohl( ((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
) >> 24 & 0xff),
7730 (unsigned int)(ntohl( ((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
) >> 16 & 0xff),
7731 (unsigned int)(ntohl( ((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
) >> 8 & 0xff),
7732 (unsigned int)(ntohl( ((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
) & 0xff),
7733 ntohs( ((SOCKADDR_IN
*)sockaddr
)->sin_port
) );
7735 p
= strchr( buffer
, ':' );
7736 if (!((SOCKADDR_IN
*)sockaddr
)->sin_port
) *p
= 0;
7741 struct WS_sockaddr_in6
*sockaddr6
= (LPSOCKADDR_IN6
) sockaddr
;
7745 if (len
< sizeof(SOCKADDR_IN6
)) return SOCKET_ERROR
;
7746 if ((sockaddr6
->sin6_port
))
7747 strcpy(buffer
, "[");
7748 slen
= strlen(buffer
);
7749 if (!WS_inet_ntop(WS_AF_INET6
, &sockaddr6
->sin6_addr
, &buffer
[slen
], sizeof(buffer
) - slen
))
7751 SetLastError(WSAEINVAL
);
7752 return SOCKET_ERROR
;
7754 if ((sockaddr6
->sin6_scope_id
))
7755 sprintf(buffer
+strlen(buffer
), "%%%u", sockaddr6
->sin6_scope_id
);
7756 if ((sockaddr6
->sin6_port
))
7757 sprintf(buffer
+strlen(buffer
), "]:%u", ntohs(sockaddr6
->sin6_port
));
7762 SetLastError(WSAEINVAL
);
7763 return SOCKET_ERROR
;
7766 size
= strlen( buffer
) + 1;
7771 SetLastError(WSAEFAULT
);
7772 return SOCKET_ERROR
;
7775 TRACE("=> %s,%u bytes\n", debugstr_a(buffer
), size
);
7777 strcpy( string
, buffer
);
7781 /***********************************************************************
7782 * WSAAddressToStringW (WS2_32.28)
7784 * Convert a sockaddr address into a readable address string.
7787 * sockaddr [I] Pointer to a sockaddr structure.
7788 * len [I] Size of the sockaddr structure.
7789 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
7790 * string [I/O] Pointer to a buffer to receive the address string.
7791 * lenstr [I/O] Size of the receive buffer in WCHARs.
7795 * Failure: SOCKET_ERROR
7798 * The 'info' parameter is ignored.
7800 INT WINAPI
WSAAddressToStringW( LPSOCKADDR sockaddr
, DWORD len
,
7801 LPWSAPROTOCOL_INFOW info
, LPWSTR string
,
7806 WCHAR buffer
[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7809 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr
, len
, info
, string
, lenstr
);
7812 ret
= WSAAddressToStringA(sockaddr
, len
, NULL
, bufAddr
, &size
);
7814 if (ret
) return ret
;
7816 MultiByteToWideChar( CP_ACP
, 0, bufAddr
, size
, buffer
, sizeof( buffer
)/sizeof(WCHAR
));
7821 SetLastError(WSAEFAULT
);
7822 return SOCKET_ERROR
;
7825 TRACE("=> %s,%u bytes\n", debugstr_w(buffer
), size
);
7827 lstrcpyW( string
, buffer
);
7831 /***********************************************************************
7832 * WSAEnumNameSpaceProvidersA (WS2_32.34)
7834 INT WINAPI
WSAEnumNameSpaceProvidersA( LPDWORD len
, LPWSANAMESPACE_INFOA buffer
)
7836 FIXME( "(%p %p) Stub!\n", len
, buffer
);
7840 /***********************************************************************
7841 * WSAEnumNameSpaceProvidersW (WS2_32.35)
7843 INT WINAPI
WSAEnumNameSpaceProvidersW( LPDWORD len
, LPWSANAMESPACE_INFOW buffer
)
7845 FIXME( "(%p %p) Stub!\n", len
, buffer
);
7849 /***********************************************************************
7850 * WSAGetQOSByName (WS2_32.41)
7852 BOOL WINAPI
WSAGetQOSByName( SOCKET s
, LPWSABUF lpQOSName
, LPQOS lpQOS
)
7854 FIXME( "(0x%04lx %p %p) Stub!\n", s
, lpQOSName
, lpQOS
);
7858 /***********************************************************************
7859 * WSAGetServiceClassInfoA (WS2_32.42)
7861 INT WINAPI
WSAGetServiceClassInfoA( LPGUID provider
, LPGUID service
, LPDWORD len
,
7862 LPWSASERVICECLASSINFOA info
)
7864 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider
), debugstr_guid(service
),
7866 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
7867 return SOCKET_ERROR
;
7870 /***********************************************************************
7871 * WSAGetServiceClassInfoW (WS2_32.43)
7873 INT WINAPI
WSAGetServiceClassInfoW( LPGUID provider
, LPGUID service
, LPDWORD len
,
7874 LPWSASERVICECLASSINFOW info
)
7876 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider
), debugstr_guid(service
),
7878 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
7879 return SOCKET_ERROR
;
7882 /***********************************************************************
7883 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
7885 INT WINAPI
WSAGetServiceClassNameByClassIdA( LPGUID
class, LPSTR service
, LPDWORD len
)
7887 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service
, len
);
7888 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
7889 return SOCKET_ERROR
;
7892 /***********************************************************************
7893 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
7895 INT WINAPI
WSAGetServiceClassNameByClassIdW( LPGUID
class, LPWSTR service
, LPDWORD len
)
7897 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service
, len
);
7898 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
7899 return SOCKET_ERROR
;
7902 /***********************************************************************
7903 * WSALookupServiceBeginA (WS2_32.59)
7905 INT WINAPI
WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions
,
7906 DWORD dwControlFlags
,
7909 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions
, dwControlFlags
,
7911 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
7912 return SOCKET_ERROR
;
7915 /***********************************************************************
7916 * WSALookupServiceBeginW (WS2_32.60)
7918 INT WINAPI
WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions
,
7919 DWORD dwControlFlags
,
7922 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions
, dwControlFlags
,
7924 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
7925 return SOCKET_ERROR
;
7928 /***********************************************************************
7929 * WSALookupServiceEnd (WS2_32.61)
7931 INT WINAPI
WSALookupServiceEnd( HANDLE lookup
)
7933 FIXME("(%p) Stub!\n", lookup
);
7937 /***********************************************************************
7938 * WSALookupServiceNextA (WS2_32.62)
7940 INT WINAPI
WSALookupServiceNextA( HANDLE lookup
, DWORD flags
, LPDWORD len
, LPWSAQUERYSETA results
)
7942 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup
, flags
, len
, results
);
7943 SetLastError(WSA_E_NO_MORE
);
7944 return SOCKET_ERROR
;
7947 /***********************************************************************
7948 * WSALookupServiceNextW (WS2_32.63)
7950 INT WINAPI
WSALookupServiceNextW( HANDLE lookup
, DWORD flags
, LPDWORD len
, LPWSAQUERYSETW results
)
7952 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup
, flags
, len
, results
);
7953 SetLastError(WSA_E_NO_MORE
);
7954 return SOCKET_ERROR
;
7957 /***********************************************************************
7958 * WSANtohl (WS2_32.64)
7960 INT WINAPI
WSANtohl( SOCKET s
, WS_u_long netlong
, WS_u_long
* lphostlong
)
7962 TRACE( "(%04lx 0x%08x %p)\n", s
, netlong
, lphostlong
);
7964 if (!lphostlong
) return WSAEFAULT
;
7966 *lphostlong
= ntohl( netlong
);
7970 /***********************************************************************
7971 * WSANtohs (WS2_32.65)
7973 INT WINAPI
WSANtohs( SOCKET s
, WS_u_short netshort
, WS_u_short
* lphostshort
)
7975 TRACE( "(%04lx 0x%08x %p)\n", s
, netshort
, lphostshort
);
7977 if (!lphostshort
) return WSAEFAULT
;
7979 *lphostshort
= ntohs( netshort
);
7983 /***********************************************************************
7984 * WSAProviderConfigChange (WS2_32.66)
7986 INT WINAPI
WSAProviderConfigChange( LPHANDLE handle
, LPWSAOVERLAPPED overlapped
,
7987 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
7989 FIXME( "(%p %p %p) Stub!\n", handle
, overlapped
, completion
);
7990 return SOCKET_ERROR
;
7993 /***********************************************************************
7994 * WSARecvDisconnect (WS2_32.68)
7996 INT WINAPI
WSARecvDisconnect( SOCKET s
, LPWSABUF disconnectdata
)
7998 TRACE( "(%04lx %p)\n", s
, disconnectdata
);
8000 return WS_shutdown( s
, SD_RECEIVE
);
8003 /***********************************************************************
8004 * WSASetServiceA (WS2_32.76)
8006 INT WINAPI
WSASetServiceA( LPWSAQUERYSETA query
, WSAESETSERVICEOP operation
, DWORD flags
)
8008 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query
, operation
, flags
);
8012 /***********************************************************************
8013 * WSASetServiceW (WS2_32.77)
8015 INT WINAPI
WSASetServiceW( LPWSAQUERYSETW query
, WSAESETSERVICEOP operation
, DWORD flags
)
8017 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query
, operation
, flags
);
8021 /***********************************************************************
8022 * WSCEnableNSProvider (WS2_32.84)
8024 INT WINAPI
WSCEnableNSProvider( LPGUID provider
, BOOL enable
)
8026 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider
), enable
);
8030 /***********************************************************************
8031 * WSCGetProviderPath (WS2_32.86)
8033 INT WINAPI
WSCGetProviderPath( LPGUID provider
, LPWSTR path
, LPINT len
, LPINT errcode
)
8035 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider
), path
, len
, errcode
);
8037 if (!errcode
|| !provider
|| !len
) return WSAEFAULT
;
8039 *errcode
= WSAEINVAL
;
8040 return SOCKET_ERROR
;
8043 /***********************************************************************
8044 * WSCInstallNameSpace (WS2_32.87)
8046 INT WINAPI
WSCInstallNameSpace( LPWSTR identifier
, LPWSTR path
, DWORD
namespace,
8047 DWORD version
, LPGUID provider
)
8049 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier
), debugstr_w(path
),
8050 namespace, version
, debugstr_guid(provider
) );
8054 /***********************************************************************
8055 * WSCUnInstallNameSpace (WS2_32.89)
8057 INT WINAPI
WSCUnInstallNameSpace( LPGUID lpProviderId
)
8059 FIXME("(%p) Stub!\n", lpProviderId
);
8063 /***********************************************************************
8064 * WSCWriteProviderOrder (WS2_32.91)
8066 INT WINAPI
WSCWriteProviderOrder( LPDWORD entry
, DWORD number
)
8068 FIXME("(%p 0x%08x) Stub!\n", entry
, number
);
8072 /***********************************************************************
8073 * WSANSPIoctl (WS2_32.91)
8075 INT WINAPI
WSANSPIoctl( HANDLE hLookup
, DWORD dwControlCode
, LPVOID lpvInBuffer
,
8076 DWORD cbInBuffer
, LPVOID lpvOutBuffer
, DWORD cbOutBuffer
,
8077 LPDWORD lpcbBytesReturned
, LPWSACOMPLETION lpCompletion
)
8079 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup
, dwControlCode
,
8080 lpvInBuffer
, cbInBuffer
, lpvOutBuffer
, cbOutBuffer
, lpcbBytesReturned
, lpCompletion
);
8081 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8082 return SOCKET_ERROR
;
8085 /*****************************************************************************
8086 * WSAEnumProtocolsA [WS2_32.@]
8088 * see function WSAEnumProtocolsW
8090 INT WINAPI
WSAEnumProtocolsA( LPINT protocols
, LPWSAPROTOCOL_INFOA buffer
, LPDWORD len
)
8092 return WS_EnumProtocols( FALSE
, protocols
, (LPWSAPROTOCOL_INFOW
) buffer
, len
);
8095 /*****************************************************************************
8096 * WSAEnumProtocolsW [WS2_32.@]
8098 * Retrieves information about specified set of active network protocols.
8101 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
8102 * retrieves information on all available protocols.
8103 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
8105 * len [I/O] Pointer to a variable specifying buffer size. On output
8106 * the variable holds the number of bytes needed when the
8107 * specified size is too small.
8110 * Success: number of WSAPROTOCOL_INFO structures in buffer.
8111 * Failure: SOCKET_ERROR
8114 * NT4SP5 does not return SPX if protocols == NULL
8117 * - NT4SP5 returns in addition these list of NETBIOS protocols
8118 * (address family 17), each entry two times one for socket type 2 and 5
8120 * iProtocol szProtocol
8121 * 0x80000000 \Device\NwlnkNb
8122 * 0xfffffffa \Device\NetBT_CBENT7
8123 * 0xfffffffb \Device\Nbf_CBENT7
8124 * 0xfffffffc \Device\NetBT_NdisWan5
8125 * 0xfffffffd \Device\NetBT_El9202
8126 * 0xfffffffe \Device\Nbf_El9202
8127 * 0xffffffff \Device\Nbf_NdisWan4
8129 * - there is no check that the operating system supports the returned
8132 INT WINAPI
WSAEnumProtocolsW( LPINT protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
)
8134 return WS_EnumProtocols( TRUE
, protocols
, buffer
, len
);
8137 /*****************************************************************************
8138 * WSCEnumProtocols [WS2_32.@]
8141 * protocols [I] Null-terminated array of iProtocol values.
8142 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
8143 * len [I/O] Size of buffer on input/output.
8144 * errno [O] Error code.
8147 * Success: number of protocols to be reported on.
8148 * Failure: SOCKET_ERROR. error is in errno.
8151 * Doesn't supply info on layered protocols.
8154 INT WINAPI
WSCEnumProtocols( LPINT protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
, LPINT err
)
8156 INT ret
= WSAEnumProtocolsW( protocols
, buffer
, len
);
8158 if (ret
== SOCKET_ERROR
) *err
= WSAENOBUFS
;