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 #define FILE_USE_FILE_POINTER_POSITION ((LONGLONG)-2)
182 WINE_DEFAULT_DEBUG_CHANNEL(winsock
);
183 WINE_DECLARE_DEBUG_CHANNEL(winediag
);
185 /* names of the protocols */
186 static const WCHAR NameIpxW
[] = {'I', 'P', 'X', '\0'};
187 static const WCHAR NameSpxW
[] = {'S', 'P', 'X', '\0'};
188 static const WCHAR NameSpxIIW
[] = {'S', 'P', 'X', ' ', 'I', 'I', '\0'};
189 static const WCHAR NameTcpW
[] = {'T', 'C', 'P', '/', 'I', 'P', '\0'};
190 static const WCHAR NameUdpW
[] = {'U', 'D', 'P', '/', 'I', 'P', '\0'};
192 /* Taken from Win2k */
193 static const GUID ProviderIdIP
= { 0xe70f1aa0, 0xab8b, 0x11cf,
194 { 0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
195 static const GUID ProviderIdIPX
= { 0x11058240, 0xbe47, 0x11cf,
196 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
197 static const GUID ProviderIdSPX
= { 0x11058241, 0xbe47, 0x11cf,
198 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
200 static const INT valid_protocols
[] =
210 #define IS_IPX_PROTO(X) ((X) >= WS_NSPROTO_IPX && (X) <= WS_NSPROTO_IPX + 255)
212 #if defined(IP_UNICAST_IF) && defined(SO_ATTACH_FILTER)
213 # define LINUX_BOUND_IF
214 struct interface_filter
{
215 struct sock_filter iface_memaddr
;
216 struct sock_filter iface_rule
;
217 struct sock_filter ip_memaddr
;
218 struct sock_filter ip_rule
;
219 struct sock_filter return_keep
;
220 struct sock_filter return_dump
;
222 # define FILTER_JUMP_DUMP(here) (u_char)(offsetof(struct interface_filter, return_dump) \
223 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
224 /sizeof(struct sock_filter)
225 # define FILTER_JUMP_KEEP(here) (u_char)(offsetof(struct interface_filter, return_keep) \
226 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
227 /sizeof(struct sock_filter)
228 # define FILTER_JUMP_NEXT() (u_char)(0)
229 # define SKF_NET_DESTIP 16 /* offset in the network header to the destination IP */
230 static struct interface_filter generic_interface_filter
= {
231 /* This filter rule allows incoming packets on the specified interface, which works for all
232 * remotely generated packets and for locally generated broadcast packets. */
233 BPF_STMT(BPF_LD
+BPF_W
+BPF_ABS
, SKF_AD_OFF
+SKF_AD_IFINDEX
),
234 BPF_JUMP(BPF_JMP
+BPF_JEQ
+BPF_K
, 0xdeadbeef, FILTER_JUMP_KEEP(iface_rule
), FILTER_JUMP_NEXT()),
235 /* This rule allows locally generated packets targeted at the specific IP address of the chosen
236 * adapter (local packets not destined for the broadcast address do not have IFINDEX set) */
237 BPF_STMT(BPF_LD
+BPF_W
+BPF_ABS
, SKF_NET_OFF
+SKF_NET_DESTIP
),
238 BPF_JUMP(BPF_JMP
+BPF_JEQ
+BPF_K
, 0xdeadbeef, FILTER_JUMP_KEEP(ip_rule
), FILTER_JUMP_DUMP(ip_rule
)),
239 BPF_STMT(BPF_RET
+BPF_K
, (u_int
)-1), /* keep packet */
240 BPF_STMT(BPF_RET
+BPF_K
, 0) /* dump packet */
242 #endif /* LINUX_BOUND_IF */
245 * The actual definition of WSASendTo, wrapped in a different function name
246 * so that internal calls from ws2_32 itself will not trigger programs like
247 * Garena, which hooks WSASendTo/WSARecvFrom calls.
249 static int WS2_sendto( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
250 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
251 const struct WS_sockaddr
*to
, int tolen
,
252 LPWSAOVERLAPPED lpOverlapped
,
253 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);
256 * Internal fundamental receive function, essentially WSARecvFrom with an
257 * additional parameter to support message control headers.
259 static int WS2_recv_base( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
260 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
,
261 struct WS_sockaddr
*lpFrom
,
262 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
263 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
,
264 LPWSABUF lpControlBuffer
);
266 /* critical section to protect some non-reentrant net function */
267 static CRITICAL_SECTION csWSgetXXXbyYYY
;
268 static CRITICAL_SECTION_DEBUG critsect_debug
=
270 0, 0, &csWSgetXXXbyYYY
,
271 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
272 0, 0, { (DWORD_PTR
)(__FILE__
": csWSgetXXXbyYYY") }
274 static CRITICAL_SECTION csWSgetXXXbyYYY
= { &critsect_debug
, -1, 0, 0, 0, 0 };
276 union generic_unix_sockaddr
278 struct sockaddr addr
;
279 char data
[128]; /* should be big enough for all families */
282 static inline const char *debugstr_sockaddr( const struct WS_sockaddr
*a
)
284 if (!a
) return "(nil)";
285 switch (a
->sa_family
)
291 struct WS_sockaddr_in
*sin
= (struct WS_sockaddr_in
*)a
;
293 p
= WS_inet_ntop( WS_AF_INET
, &sin
->sin_addr
, buf
, sizeof(buf
) );
295 p
= "(unknown IPv4 address)";
297 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
298 p
, ntohs(sin
->sin_port
));
304 struct WS_sockaddr_in6
*sin
= (struct WS_sockaddr_in6
*)a
;
306 p
= WS_inet_ntop( WS_AF_INET6
, &sin
->sin6_addr
, buf
, sizeof(buf
) );
308 p
= "(unknown IPv6 address)";
309 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
310 p
, ntohs(sin
->sin6_port
));
315 char netnum
[16], nodenum
[16];
316 struct WS_sockaddr_ipx
*sin
= (struct WS_sockaddr_ipx
*)a
;
318 for (i
= 0;i
< 4; i
++) sprintf(netnum
+ i
* 2, "%02X", (unsigned char) sin
->sa_netnum
[i
]);
319 for (i
= 0;i
< 6; i
++) sprintf(nodenum
+ i
* 2, "%02X", (unsigned char) sin
->sa_nodenum
[i
]);
321 return wine_dbg_sprintf("{ family AF_IPX, address %s.%s, ipx socket %d }",
322 netnum
, nodenum
, sin
->sa_socket
);
328 memcpy( &addr
, ((const SOCKADDR_IRDA
*)a
)->irdaDeviceID
, sizeof(addr
) );
329 addr
= ntohl( addr
);
330 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
332 ((const SOCKADDR_IRDA
*)a
)->irdaServiceName
);
335 return wine_dbg_sprintf("{ family %d }", a
->sa_family
);
339 static inline const char *debugstr_sockopt(int level
, int optname
)
341 const char *stropt
= NULL
, *strlevel
= NULL
;
343 #define DEBUG_SOCKLEVEL(x) case (x): strlevel = #x
344 #define DEBUG_SOCKOPT(x) case (x): stropt = #x; break
348 DEBUG_SOCKLEVEL(WS_SOL_SOCKET
);
351 DEBUG_SOCKOPT(WS_SO_ACCEPTCONN
);
352 DEBUG_SOCKOPT(WS_SO_BROADCAST
);
353 DEBUG_SOCKOPT(WS_SO_BSP_STATE
);
354 DEBUG_SOCKOPT(WS_SO_CONDITIONAL_ACCEPT
);
355 DEBUG_SOCKOPT(WS_SO_CONNECT_TIME
);
356 DEBUG_SOCKOPT(WS_SO_DEBUG
);
357 DEBUG_SOCKOPT(WS_SO_DONTLINGER
);
358 DEBUG_SOCKOPT(WS_SO_DONTROUTE
);
359 DEBUG_SOCKOPT(WS_SO_ERROR
);
360 DEBUG_SOCKOPT(WS_SO_EXCLUSIVEADDRUSE
);
361 DEBUG_SOCKOPT(WS_SO_GROUP_ID
);
362 DEBUG_SOCKOPT(WS_SO_GROUP_PRIORITY
);
363 DEBUG_SOCKOPT(WS_SO_KEEPALIVE
);
364 DEBUG_SOCKOPT(WS_SO_LINGER
);
365 DEBUG_SOCKOPT(WS_SO_MAX_MSG_SIZE
);
366 DEBUG_SOCKOPT(WS_SO_OOBINLINE
);
367 DEBUG_SOCKOPT(WS_SO_OPENTYPE
);
368 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOA
);
369 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOW
);
370 DEBUG_SOCKOPT(WS_SO_RCVBUF
);
371 DEBUG_SOCKOPT(WS_SO_RCVTIMEO
);
372 DEBUG_SOCKOPT(WS_SO_REUSEADDR
);
373 DEBUG_SOCKOPT(WS_SO_SNDBUF
);
374 DEBUG_SOCKOPT(WS_SO_SNDTIMEO
);
375 DEBUG_SOCKOPT(WS_SO_TYPE
);
376 DEBUG_SOCKOPT(WS_SO_UPDATE_CONNECT_CONTEXT
);
380 DEBUG_SOCKLEVEL(WS_NSPROTO_IPX
);
383 DEBUG_SOCKOPT(WS_IPX_PTYPE
);
384 DEBUG_SOCKOPT(WS_IPX_FILTERPTYPE
);
385 DEBUG_SOCKOPT(WS_IPX_DSTYPE
);
386 DEBUG_SOCKOPT(WS_IPX_RECVHDR
);
387 DEBUG_SOCKOPT(WS_IPX_MAXSIZE
);
388 DEBUG_SOCKOPT(WS_IPX_ADDRESS
);
389 DEBUG_SOCKOPT(WS_IPX_MAX_ADAPTER_NUM
);
393 DEBUG_SOCKLEVEL(WS_SOL_IRLMP
);
396 DEBUG_SOCKOPT(WS_IRLMP_ENUMDEVICES
);
400 DEBUG_SOCKLEVEL(WS_IPPROTO_TCP
);
403 DEBUG_SOCKOPT(WS_TCP_BSDURGENT
);
404 DEBUG_SOCKOPT(WS_TCP_EXPEDITED_1122
);
405 DEBUG_SOCKOPT(WS_TCP_NODELAY
);
409 DEBUG_SOCKLEVEL(WS_IPPROTO_IP
);
412 DEBUG_SOCKOPT(WS_IP_ADD_MEMBERSHIP
);
413 DEBUG_SOCKOPT(WS_IP_DONTFRAGMENT
);
414 DEBUG_SOCKOPT(WS_IP_DROP_MEMBERSHIP
);
415 DEBUG_SOCKOPT(WS_IP_HDRINCL
);
416 DEBUG_SOCKOPT(WS_IP_MULTICAST_IF
);
417 DEBUG_SOCKOPT(WS_IP_MULTICAST_LOOP
);
418 DEBUG_SOCKOPT(WS_IP_MULTICAST_TTL
);
419 DEBUG_SOCKOPT(WS_IP_OPTIONS
);
420 DEBUG_SOCKOPT(WS_IP_PKTINFO
);
421 DEBUG_SOCKOPT(WS_IP_RECEIVE_BROADCAST
);
422 DEBUG_SOCKOPT(WS_IP_TOS
);
423 DEBUG_SOCKOPT(WS_IP_TTL
);
424 DEBUG_SOCKOPT(WS_IP_UNICAST_IF
);
428 DEBUG_SOCKLEVEL(WS_IPPROTO_IPV6
);
431 DEBUG_SOCKOPT(WS_IPV6_ADD_MEMBERSHIP
);
432 DEBUG_SOCKOPT(WS_IPV6_DROP_MEMBERSHIP
);
433 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_IF
);
434 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_HOPS
);
435 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_LOOP
);
436 DEBUG_SOCKOPT(WS_IPV6_UNICAST_HOPS
);
437 DEBUG_SOCKOPT(WS_IPV6_V6ONLY
);
438 DEBUG_SOCKOPT(WS_IPV6_UNICAST_IF
);
439 DEBUG_SOCKOPT(WS_IPV6_DONTFRAG
);
443 #undef DEBUG_SOCKLEVEL
447 strlevel
= wine_dbg_sprintf("WS_0x%x", level
);
449 stropt
= wine_dbg_sprintf("WS_0x%x", optname
);
451 return wine_dbg_sprintf("level %s, name %s", strlevel
+ 3, stropt
+ 3);
454 static inline const char *debugstr_optval(const char *optval
, int optlenval
)
456 if (optval
&& !IS_INTRESOURCE(optval
) && optlenval
>= 1 && optlenval
<= sizeof(DWORD
))
459 memcpy(&value
, optval
, optlenval
);
460 return wine_dbg_sprintf("%p (%u)", optval
, value
);
462 return wine_dbg_sprintf("%p", optval
);
465 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
466 #define SOCKET2HANDLE(s) ((HANDLE)(s))
467 #define HANDLE2SOCKET(h) ((SOCKET)(h))
469 /****************************************************************
470 * Async IO declarations
471 ****************************************************************/
475 struct ws2_async_io
*next
;
478 struct ws2_async_shutdown
480 struct ws2_async_io io
;
482 IO_STATUS_BLOCK iosb
;
488 struct ws2_async_io io
;
490 LPWSAOVERLAPPED user_overlapped
;
491 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func
;
492 IO_STATUS_BLOCK local_iosb
;
493 struct WS_sockaddr
*addr
;
496 int val
; /* for send operations */
497 int *ptr
; /* for recv operations */
502 unsigned int n_iovecs
;
503 unsigned int first_iovec
;
504 struct iovec iovec
[1];
507 struct ws2_accept_async
509 struct ws2_async_io io
;
510 HANDLE listen_socket
;
511 HANDLE accept_socket
;
512 LPOVERLAPPED user_overlapped
;
514 PVOID buf
; /* buffer to write data to */
518 struct ws2_async
*read
;
521 struct ws2_transmitfile_async
523 struct ws2_async_io io
;
528 DWORD bytes_per_send
;
529 TRANSMIT_FILE_BUFFERS buffers
;
531 LARGE_INTEGER offset
;
532 struct ws2_async write
;
535 static struct ws2_async_io
*async_io_freelist
;
537 static void release_async_io( struct ws2_async_io
*io
)
541 struct ws2_async_io
*next
= async_io_freelist
;
543 if (InterlockedCompareExchangePointer( (void **)&async_io_freelist
, io
, next
) == next
) return;
547 static struct ws2_async_io
*alloc_async_io( DWORD size
)
549 /* first free remaining previous fileinfos */
551 struct ws2_async_io
*io
= InterlockedExchangePointer( (void **)&async_io_freelist
, NULL
);
555 struct ws2_async_io
*next
= io
->next
;
556 HeapFree( GetProcessHeap(), 0, io
);
560 return HeapAlloc( GetProcessHeap(), 0, size
);
563 typedef NTSTATUS
async_callback_t( void *user
, IO_STATUS_BLOCK
*io
, NTSTATUS status
, void **apc
, void **arg
);
565 static NTSTATUS
register_async( int type
, HANDLE handle
, async_callback_t callback
, void *arg
, HANDLE event
,
566 PIO_APC_ROUTINE apc
, void *apc_context
, IO_STATUS_BLOCK
*io
)
570 SERVER_START_REQ( register_async
)
573 req
->async
.handle
= wine_server_obj_handle( handle
);
574 req
->async
.callback
= wine_server_client_ptr( callback
);
575 req
->async
.iosb
= wine_server_client_ptr( io
);
576 req
->async
.arg
= wine_server_client_ptr( arg
);
577 req
->async
.event
= wine_server_obj_handle( event
);
578 req
->async
.cvalue
= wine_server_client_ptr( apc
? 0 : apc_context
);
579 status
= wine_server_call( req
);
586 /****************************************************************/
588 /* ----------------------------------- internal data */
590 /* ws_... struct conversion flags */
592 typedef struct /* WSAAsyncSelect() control struct */
594 HANDLE service
, event
, sock
;
600 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
601 #define WS_MAX_UDP_DATAGRAM 1024
602 static INT WINAPI
WSA_DefaultBlockingHook( FARPROC x
);
604 /* hostent's, servent's and protent's are stored in one buffer per thread,
605 * as documented on MSDN for the functions that return any of the buffers */
606 struct per_thread_data
609 struct WS_hostent
*he_buffer
;
610 struct WS_servent
*se_buffer
;
611 struct WS_protoent
*pe_buffer
;
612 struct pollfd
*fd_cache
;
613 unsigned int fd_count
;
617 char ntoa_buffer
[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
620 /* internal: routing description information */
624 DWORD metric
, default_route
;
627 static INT num_startup
; /* reference counter */
628 static FARPROC blocking_hook
= (FARPROC
)WSA_DefaultBlockingHook
;
630 /* function prototypes */
631 static struct WS_hostent
*WS_create_he(char *name
, int aliases
, int aliases_size
, int addresses
, int address_length
);
632 static struct WS_hostent
*WS_dup_he(const struct hostent
* p_he
);
633 static struct WS_protoent
*WS_dup_pe(const struct protoent
* p_pe
);
634 static struct WS_servent
*WS_dup_se(const struct servent
* p_se
);
635 static int ws_protocol_info(SOCKET s
, int unicode
, WSAPROTOCOL_INFOW
*buffer
, int *size
);
637 int WSAIOCTL_GetInterfaceCount(void);
638 int WSAIOCTL_GetInterfaceName(int intNumber
, char *intName
);
640 static void WS_AddCompletion( SOCKET sock
, ULONG_PTR CompletionValue
, NTSTATUS CompletionStatus
, ULONG Information
);
642 #define MAP_OPTION(opt) { WS_##opt, opt }
644 static const int ws_flags_map
[][2] =
646 MAP_OPTION( MSG_OOB
),
647 MAP_OPTION( MSG_PEEK
),
648 MAP_OPTION( MSG_DONTROUTE
),
649 MAP_OPTION( MSG_WAITALL
),
650 { WS_MSG_PARTIAL
, 0 },
653 static const int ws_sock_map
[][2] =
655 MAP_OPTION( SO_DEBUG
),
656 MAP_OPTION( SO_ACCEPTCONN
),
657 MAP_OPTION( SO_REUSEADDR
),
658 MAP_OPTION( SO_KEEPALIVE
),
659 MAP_OPTION( SO_DONTROUTE
),
660 MAP_OPTION( SO_BROADCAST
),
661 MAP_OPTION( SO_LINGER
),
662 MAP_OPTION( SO_OOBINLINE
),
663 MAP_OPTION( SO_SNDBUF
),
664 MAP_OPTION( SO_RCVBUF
),
665 MAP_OPTION( SO_ERROR
),
666 MAP_OPTION( SO_TYPE
),
668 MAP_OPTION( SO_RCVTIMEO
),
671 MAP_OPTION( SO_SNDTIMEO
),
675 static const int ws_tcp_map
[][2] =
678 MAP_OPTION( TCP_NODELAY
),
682 static const int ws_ip_map
[][2] =
684 MAP_OPTION( IP_MULTICAST_IF
),
685 MAP_OPTION( IP_MULTICAST_TTL
),
686 MAP_OPTION( IP_MULTICAST_LOOP
),
687 MAP_OPTION( IP_ADD_MEMBERSHIP
),
688 MAP_OPTION( IP_DROP_MEMBERSHIP
),
689 MAP_OPTION( IP_OPTIONS
),
691 MAP_OPTION( IP_HDRINCL
),
693 MAP_OPTION( IP_TOS
),
694 MAP_OPTION( IP_TTL
),
696 MAP_OPTION( IP_PKTINFO
),
699 MAP_OPTION( IP_UNICAST_IF
),
703 static const int ws_ipv6_map
[][2] =
705 #ifdef IPV6_ADD_MEMBERSHIP
706 MAP_OPTION( IPV6_ADD_MEMBERSHIP
),
708 #ifdef IPV6_DROP_MEMBERSHIP
709 MAP_OPTION( IPV6_DROP_MEMBERSHIP
),
711 MAP_OPTION( IPV6_MULTICAST_IF
),
712 MAP_OPTION( IPV6_MULTICAST_HOPS
),
713 MAP_OPTION( IPV6_MULTICAST_LOOP
),
714 MAP_OPTION( IPV6_UNICAST_HOPS
),
715 MAP_OPTION( IPV6_V6ONLY
),
716 #ifdef IPV6_UNICAST_IF
717 MAP_OPTION( IPV6_UNICAST_IF
),
721 static const int ws_af_map
[][2] =
723 MAP_OPTION( AF_UNSPEC
),
724 MAP_OPTION( AF_INET
),
725 MAP_OPTION( AF_INET6
),
727 MAP_OPTION( AF_IPX
),
730 MAP_OPTION( AF_IRDA
),
732 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
735 static const int ws_socktype_map
[][2] =
737 MAP_OPTION( SOCK_DGRAM
),
738 MAP_OPTION( SOCK_STREAM
),
739 MAP_OPTION( SOCK_RAW
),
740 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
743 static const int ws_proto_map
[][2] =
745 MAP_OPTION( IPPROTO_IP
),
746 MAP_OPTION( IPPROTO_TCP
),
747 MAP_OPTION( IPPROTO_UDP
),
748 MAP_OPTION( IPPROTO_IPV6
),
749 MAP_OPTION( IPPROTO_ICMP
),
750 MAP_OPTION( IPPROTO_IGMP
),
751 MAP_OPTION( IPPROTO_RAW
),
752 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
755 static const int ws_aiflag_map
[][2] =
757 MAP_OPTION( AI_PASSIVE
),
758 MAP_OPTION( AI_CANONNAME
),
759 MAP_OPTION( AI_NUMERICHOST
),
760 #ifdef AI_NUMERICSERV
761 MAP_OPTION( AI_NUMERICSERV
),
764 MAP_OPTION( AI_V4MAPPED
),
766 MAP_OPTION( AI_ADDRCONFIG
),
769 static const int ws_niflag_map
[][2] =
771 MAP_OPTION( NI_NOFQDN
),
772 MAP_OPTION( NI_NUMERICHOST
),
773 MAP_OPTION( NI_NAMEREQD
),
774 MAP_OPTION( NI_NUMERICSERV
),
775 MAP_OPTION( NI_DGRAM
),
778 static const int ws_eai_map
[][2] =
780 MAP_OPTION( EAI_AGAIN
),
781 MAP_OPTION( EAI_BADFLAGS
),
782 MAP_OPTION( EAI_FAIL
),
783 MAP_OPTION( EAI_FAMILY
),
784 MAP_OPTION( EAI_MEMORY
),
785 /* Note: EAI_NODATA is deprecated, but still
786 * used by Windows and Linux... We map the newer
787 * EAI_NONAME to EAI_NODATA for now until Windows
791 MAP_OPTION( EAI_NODATA
),
794 { WS_EAI_NODATA
, EAI_NONAME
},
797 MAP_OPTION( EAI_SERVICE
),
798 MAP_OPTION( EAI_SOCKTYPE
),
802 static const int ws_poll_map
[][2] =
804 MAP_OPTION( POLLERR
),
805 MAP_OPTION( POLLHUP
),
806 MAP_OPTION( POLLNVAL
),
807 MAP_OPTION( POLLWRNORM
),
808 MAP_OPTION( POLLWRBAND
),
809 MAP_OPTION( POLLRDNORM
),
810 { WS_POLLRDBAND
, POLLPRI
}
813 static const char magic_loopback_addr
[] = {127, 12, 34, 56};
815 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
817 static inline WSACMSGHDR
*fill_control_message(int level
, int type
, WSACMSGHDR
*current
, ULONG
*maxsize
, void *data
, int len
)
819 ULONG msgsize
= sizeof(WSACMSGHDR
) + WSA_CMSG_ALIGN(len
);
820 char *ptr
= (char *) current
+ sizeof(WSACMSGHDR
);
822 /* Make sure there is at least enough room for this entry */
823 if (msgsize
> *maxsize
)
826 /* Fill in the entry */
827 current
->cmsg_len
= sizeof(WSACMSGHDR
) + len
;
828 current
->cmsg_level
= level
;
829 current
->cmsg_type
= type
;
830 memcpy(ptr
, data
, len
);
831 /* Return the pointer to where next entry should go */
832 return (WSACMSGHDR
*) (ptr
+ WSA_CMSG_ALIGN(len
));
834 #endif /* IP_PKTINFO */
836 static inline int convert_control_headers(struct msghdr
*hdr
, WSABUF
*control
)
839 WSACMSGHDR
*cmsg_win
= (WSACMSGHDR
*) control
->buf
, *ptr
;
840 ULONG ctlsize
= control
->len
;
841 struct cmsghdr
*cmsg_unix
;
844 /* Loop over all the headers, converting as appropriate */
845 for (cmsg_unix
= CMSG_FIRSTHDR(hdr
); cmsg_unix
!= NULL
; cmsg_unix
= CMSG_NXTHDR(hdr
, cmsg_unix
))
847 switch(cmsg_unix
->cmsg_level
)
850 switch(cmsg_unix
->cmsg_type
)
854 /* Convert the Unix IP_PKTINFO structure to the Windows version */
855 struct in_pktinfo
*data_unix
= (struct in_pktinfo
*) CMSG_DATA(cmsg_unix
);
856 struct WS_in_pktinfo data_win
;
858 memcpy(&data_win
.ipi_addr
,&data_unix
->ipi_addr
.s_addr
,4); /* 4 bytes = 32 address bits */
859 data_win
.ipi_ifindex
= data_unix
->ipi_ifindex
;
860 ptr
= fill_control_message(WS_IPPROTO_IP
, WS_IP_PKTINFO
, ptr
, &ctlsize
,
861 (void*)&data_win
, sizeof(data_win
));
862 if (!ptr
) goto error
;
865 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix
->cmsg_type
);
870 FIXME("Unhandled message header level %d\n", cmsg_unix
->cmsg_level
);
876 /* Set the length of the returned control headers */
877 control
->len
= (ptr
== NULL
? 0 : (char*)ptr
- (char*)cmsg_win
);
878 return (ptr
!= NULL
);
879 #else /* IP_PKTINFO */
882 #endif /* IP_PKTINFO */
884 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
886 /* ----------------------------------- error handling */
888 static NTSTATUS
sock_get_ntstatus( int err
)
892 case EBADF
: return STATUS_INVALID_HANDLE
;
893 case EBUSY
: return STATUS_DEVICE_BUSY
;
895 case EACCES
: return STATUS_ACCESS_DENIED
;
896 case EFAULT
: return STATUS_NO_MEMORY
;
897 case EINVAL
: return STATUS_INVALID_PARAMETER
;
899 case EMFILE
: return STATUS_TOO_MANY_OPENED_FILES
;
900 case EWOULDBLOCK
: return STATUS_CANT_WAIT
;
901 case EINPROGRESS
: return STATUS_PENDING
;
902 case EALREADY
: return STATUS_NETWORK_BUSY
;
903 case ENOTSOCK
: return STATUS_OBJECT_TYPE_MISMATCH
;
904 case EDESTADDRREQ
: return STATUS_INVALID_PARAMETER
;
905 case EMSGSIZE
: return STATUS_BUFFER_OVERFLOW
;
906 case EPROTONOSUPPORT
:
907 case ESOCKTNOSUPPORT
:
910 case EPROTOTYPE
: return STATUS_NOT_SUPPORTED
;
911 case ENOPROTOOPT
: return STATUS_INVALID_PARAMETER
;
912 case EOPNOTSUPP
: return STATUS_NOT_SUPPORTED
;
913 case EADDRINUSE
: return STATUS_ADDRESS_ALREADY_ASSOCIATED
;
914 case EADDRNOTAVAIL
: return STATUS_INVALID_PARAMETER
;
915 case ECONNREFUSED
: return STATUS_CONNECTION_REFUSED
;
916 case ESHUTDOWN
: return STATUS_PIPE_DISCONNECTED
;
917 case ENOTCONN
: return STATUS_CONNECTION_DISCONNECTED
;
918 case ETIMEDOUT
: return STATUS_IO_TIMEOUT
;
919 case ENETUNREACH
: return STATUS_NETWORK_UNREACHABLE
;
920 case ENETDOWN
: return STATUS_NETWORK_BUSY
;
922 case ECONNRESET
: return STATUS_CONNECTION_RESET
;
923 case ECONNABORTED
: return STATUS_CONNECTION_ABORTED
;
925 case 0: return STATUS_SUCCESS
;
927 WARN("Unknown errno %d!\n", err
);
928 return STATUS_UNSUCCESSFUL
;
932 static UINT
sock_get_error( int err
)
936 case EINTR
: return WSAEINTR
;
938 case EACCES
: return WSAEACCES
;
939 case EFAULT
: return WSAEFAULT
;
940 case EINVAL
: return WSAEINVAL
;
941 case EMFILE
: return WSAEMFILE
;
942 case EWOULDBLOCK
: return WSAEWOULDBLOCK
;
943 case EINPROGRESS
: return WSAEINPROGRESS
;
944 case EALREADY
: return WSAEALREADY
;
946 case ENOTSOCK
: return WSAENOTSOCK
;
947 case EDESTADDRREQ
: return WSAEDESTADDRREQ
;
948 case EMSGSIZE
: return WSAEMSGSIZE
;
949 case EPROTOTYPE
: return WSAEPROTOTYPE
;
950 case ENOPROTOOPT
: return WSAENOPROTOOPT
;
951 case EPROTONOSUPPORT
: return WSAEPROTONOSUPPORT
;
952 case ESOCKTNOSUPPORT
: return WSAESOCKTNOSUPPORT
;
953 case EOPNOTSUPP
: return WSAEOPNOTSUPP
;
954 case EPFNOSUPPORT
: return WSAEPFNOSUPPORT
;
955 case EAFNOSUPPORT
: return WSAEAFNOSUPPORT
;
956 case EADDRINUSE
: return WSAEADDRINUSE
;
957 case EADDRNOTAVAIL
: return WSAEADDRNOTAVAIL
;
958 case ENETDOWN
: return WSAENETDOWN
;
959 case ENETUNREACH
: return WSAENETUNREACH
;
960 case ENETRESET
: return WSAENETRESET
;
961 case ECONNABORTED
: return WSAECONNABORTED
;
963 case ECONNRESET
: return WSAECONNRESET
;
964 case ENOBUFS
: return WSAENOBUFS
;
965 case EISCONN
: return WSAEISCONN
;
966 case ENOTCONN
: return WSAENOTCONN
;
967 case ESHUTDOWN
: return WSAESHUTDOWN
;
968 case ETOOMANYREFS
: return WSAETOOMANYREFS
;
969 case ETIMEDOUT
: return WSAETIMEDOUT
;
970 case ECONNREFUSED
: return WSAECONNREFUSED
;
971 case ELOOP
: return WSAELOOP
;
972 case ENAMETOOLONG
: return WSAENAMETOOLONG
;
973 case EHOSTDOWN
: return WSAEHOSTDOWN
;
974 case EHOSTUNREACH
: return WSAEHOSTUNREACH
;
975 case ENOTEMPTY
: return WSAENOTEMPTY
;
977 case EPROCLIM
: return WSAEPROCLIM
;
980 case EUSERS
: return WSAEUSERS
;
983 case EDQUOT
: return WSAEDQUOT
;
986 case ESTALE
: return WSAESTALE
;
989 case EREMOTE
: return WSAEREMOTE
;
992 /* just in case we ever get here and there are no problems */
995 WARN("Unknown errno %d!\n", err
);
996 return WSAEOPNOTSUPP
;
1000 static UINT
wsaErrno(void)
1002 int loc_errno
= errno
;
1003 WARN("errno %d, (%s).\n", loc_errno
, strerror(loc_errno
));
1005 return sock_get_error( loc_errno
);
1008 /* most ws2 overlapped functions return an ntstatus-based error code */
1009 static NTSTATUS
wsaErrStatus(void)
1011 int loc_errno
= errno
;
1012 WARN("errno %d, (%s).\n", loc_errno
, strerror(loc_errno
));
1014 return sock_get_ntstatus(loc_errno
);
1017 static UINT
wsaHerrno(int loc_errno
)
1019 WARN("h_errno %d.\n", loc_errno
);
1023 case HOST_NOT_FOUND
: return WSAHOST_NOT_FOUND
;
1024 case TRY_AGAIN
: return WSATRY_AGAIN
;
1025 case NO_RECOVERY
: return WSANO_RECOVERY
;
1026 case NO_DATA
: return WSANO_DATA
;
1027 case ENOBUFS
: return WSAENOBUFS
;
1031 WARN("Unknown h_errno %d!\n", loc_errno
);
1032 return WSAEOPNOTSUPP
;
1036 static inline DWORD
NtStatusToWSAError( const DWORD status
)
1038 /* We only need to cover the status codes set by server async request handling */
1042 case STATUS_SUCCESS
: wserr
= 0; break;
1043 case STATUS_PENDING
: wserr
= WSA_IO_PENDING
; break;
1044 case STATUS_OBJECT_TYPE_MISMATCH
: wserr
= WSAENOTSOCK
; break;
1045 case STATUS_INVALID_HANDLE
: wserr
= WSAEBADF
; break;
1046 case STATUS_INVALID_PARAMETER
: wserr
= WSAEINVAL
; break;
1047 case STATUS_PIPE_DISCONNECTED
: wserr
= WSAESHUTDOWN
; break;
1048 case STATUS_NETWORK_BUSY
: wserr
= WSAEALREADY
; break;
1049 case STATUS_NETWORK_UNREACHABLE
: wserr
= WSAENETUNREACH
; break;
1050 case STATUS_CONNECTION_REFUSED
: wserr
= WSAECONNREFUSED
; break;
1051 case STATUS_CONNECTION_DISCONNECTED
: wserr
= WSAENOTCONN
; break;
1052 case STATUS_CONNECTION_RESET
: wserr
= WSAECONNRESET
; break;
1053 case STATUS_CONNECTION_ABORTED
: wserr
= WSAECONNABORTED
; break;
1054 case STATUS_CANCELLED
: wserr
= WSA_OPERATION_ABORTED
; break;
1055 case STATUS_ADDRESS_ALREADY_ASSOCIATED
: wserr
= WSAEADDRINUSE
; break;
1056 case STATUS_IO_TIMEOUT
:
1057 case STATUS_TIMEOUT
: wserr
= WSAETIMEDOUT
; break;
1058 case STATUS_NO_MEMORY
: wserr
= WSAEFAULT
; break;
1059 case STATUS_ACCESS_DENIED
: wserr
= WSAEACCES
; break;
1060 case STATUS_TOO_MANY_OPENED_FILES
: wserr
= WSAEMFILE
; break;
1061 case STATUS_CANT_WAIT
: wserr
= WSAEWOULDBLOCK
; break;
1062 case STATUS_BUFFER_OVERFLOW
: wserr
= WSAEMSGSIZE
; break;
1063 case STATUS_NOT_SUPPORTED
: wserr
= WSAEOPNOTSUPP
; break;
1064 case STATUS_HOST_UNREACHABLE
: wserr
= WSAEHOSTUNREACH
; break;
1067 wserr
= RtlNtStatusToDosError( status
);
1068 FIXME( "Status code %08x converted to DOS error code %x\n", status
, wserr
);
1073 /* set last error code from NT status without mapping WSA errors */
1074 static inline unsigned int set_error( unsigned int err
)
1078 err
= NtStatusToWSAError( err
);
1079 SetLastError( err
);
1084 static inline int get_sock_fd( SOCKET s
, DWORD access
, unsigned int *options
)
1087 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s
), access
, &fd
, options
) ))
1092 static inline void release_sock_fd( SOCKET s
, int fd
)
1094 wine_server_release_fd( SOCKET2HANDLE(s
), fd
);
1097 static void _enable_event( HANDLE s
, unsigned int event
,
1098 unsigned int sstate
, unsigned int cstate
)
1100 SERVER_START_REQ( enable_socket_event
)
1102 req
->handle
= wine_server_obj_handle( s
);
1104 req
->sstate
= sstate
;
1105 req
->cstate
= cstate
;
1106 wine_server_call( req
);
1111 static NTSTATUS
_is_blocking(SOCKET s
, BOOL
*ret
)
1114 SERVER_START_REQ( get_socket_event
)
1116 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1117 req
->service
= FALSE
;
1119 status
= wine_server_call( req
);
1120 *ret
= (reply
->state
& FD_WINE_NONBLOCKING
) == 0;
1126 static unsigned int _get_sock_mask(SOCKET s
)
1129 SERVER_START_REQ( get_socket_event
)
1131 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1132 req
->service
= FALSE
;
1134 wine_server_call( req
);
1141 static void _sync_sock_state(SOCKET s
)
1144 /* do a dummy wineserver request in order to let
1145 the wineserver run through its select loop once */
1146 (void)_is_blocking(s
, &dummy
);
1149 static void _get_sock_errors(SOCKET s
, int *events
)
1151 SERVER_START_REQ( get_socket_event
)
1153 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1154 req
->service
= FALSE
;
1156 wine_server_set_reply( req
, events
, sizeof(int) * FD_MAX_EVENTS
);
1157 wine_server_call( req
);
1162 static int _get_sock_error(SOCKET s
, unsigned int bit
)
1164 int events
[FD_MAX_EVENTS
];
1165 _get_sock_errors(s
, events
);
1169 static int _get_fd_type(int fd
)
1172 socklen_t optlen
= sizeof(sock_type
);
1173 getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char*) &sock_type
, &optlen
);
1177 static BOOL
set_dont_fragment(SOCKET s
, int level
, BOOL value
)
1181 if (level
== IPPROTO_IP
)
1184 optname
= IP_DONTFRAG
;
1185 #elif defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO) && defined(IP_PMTUDISC_DONT)
1186 optname
= IP_MTU_DISCOVER
;
1187 value
= value
? IP_PMTUDISC_DO
: IP_PMTUDISC_DONT
;
1191 FIXME("IP_DONTFRAGMENT for IPv4 not supported in this platform\n");
1192 return TRUE
; /* fake success */
1197 #ifdef IPV6_DONTFRAG
1198 optname
= IPV6_DONTFRAG
;
1199 #elif defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO) && defined(IPV6_PMTUDISC_DONT)
1200 optname
= IPV6_MTU_DISCOVER
;
1201 value
= value
? IPV6_PMTUDISC_DO
: IPV6_PMTUDISC_DONT
;
1205 FIXME("IP_DONTFRAGMENT for IPv6 not supported in this platform\n");
1206 return TRUE
; /* fake success */
1210 fd
= get_sock_fd(s
, 0, NULL
);
1211 if (fd
== -1) return FALSE
;
1213 if (!setsockopt(fd
, level
, optname
, &value
, sizeof(value
)))
1217 WSASetLastError(wsaErrno());
1221 release_sock_fd(s
, fd
);
1225 static BOOL
get_dont_fragment(SOCKET s
, int level
, BOOL
*out
)
1227 int fd
, optname
, value
, not_expected
;
1228 socklen_t optlen
= sizeof(value
);
1230 if (level
== IPPROTO_IP
)
1233 optname
= IP_DONTFRAG
;
1235 #elif defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
1236 optname
= IP_MTU_DISCOVER
;
1237 not_expected
= IP_PMTUDISC_DONT
;
1241 FIXME("IP_DONTFRAGMENT for IPv4 not supported in this platform\n");
1242 return TRUE
; /* fake success */
1247 #ifdef IPV6_DONTFRAG
1248 optname
= IPV6_DONTFRAG
;
1250 #elif defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DONT)
1251 optname
= IPV6_MTU_DISCOVER
;
1252 not_expected
= IPV6_PMTUDISC_DONT
;
1256 FIXME("IP_DONTFRAGMENT for IPv6 not supported in this platform\n");
1257 return TRUE
; /* fake success */
1261 fd
= get_sock_fd(s
, 0, NULL
);
1262 if (fd
== -1) return FALSE
;
1264 if (!getsockopt(fd
, level
, optname
, &value
, &optlen
))
1266 *out
= value
!= not_expected
;
1271 WSASetLastError(wsaErrno());
1275 release_sock_fd(s
, fd
);
1279 static struct per_thread_data
*get_per_thread_data(void)
1281 struct per_thread_data
* ptb
= NtCurrentTeb()->WinSockData
;
1282 /* lazy initialization */
1285 ptb
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(*ptb
) );
1286 NtCurrentTeb()->WinSockData
= ptb
;
1291 static void free_per_thread_data(void)
1293 struct per_thread_data
* ptb
= NtCurrentTeb()->WinSockData
;
1297 /* delete scratch buffers */
1298 HeapFree( GetProcessHeap(), 0, ptb
->he_buffer
);
1299 HeapFree( GetProcessHeap(), 0, ptb
->se_buffer
);
1300 HeapFree( GetProcessHeap(), 0, ptb
->pe_buffer
);
1301 HeapFree( GetProcessHeap(), 0, ptb
->fd_cache
);
1303 HeapFree( GetProcessHeap(), 0, ptb
);
1304 NtCurrentTeb()->WinSockData
= NULL
;
1307 /***********************************************************************
1308 * DllMain (WS2_32.init)
1310 BOOL WINAPI
DllMain(HINSTANCE hInstDLL
, DWORD fdwReason
, LPVOID fImpLoad
)
1312 TRACE("%p 0x%x %p\n", hInstDLL
, fdwReason
, fImpLoad
);
1313 switch (fdwReason
) {
1314 case DLL_PROCESS_ATTACH
:
1316 case DLL_PROCESS_DETACH
:
1317 if (fImpLoad
) break;
1318 free_per_thread_data();
1319 DeleteCriticalSection(&csWSgetXXXbyYYY
);
1321 case DLL_THREAD_DETACH
:
1322 free_per_thread_data();
1328 /***********************************************************************
1331 * Converts send/recv flags from Windows format.
1332 * Return the converted flag bits, unsupported flags remain unchanged.
1334 static int convert_flags(int flags
)
1337 if (!flags
) return 0;
1339 for (out
= i
= 0; flags
&& i
< sizeof(ws_flags_map
) / sizeof(ws_flags_map
[0]); i
++)
1341 if (ws_flags_map
[i
][0] & flags
)
1343 out
|= ws_flags_map
[i
][1];
1344 flags
&= ~ws_flags_map
[i
][0];
1349 FIXME("Unknown send/recv flags 0x%x, using anyway...\n", flags
);
1355 /***********************************************************************
1358 * Converts socket flags from Windows format.
1359 * Return 1 if converted, 0 if not (error).
1361 static int convert_sockopt(INT
*level
, INT
*optname
)
1367 *level
= SOL_SOCKET
;
1368 for(i
=0; i
<sizeof(ws_sock_map
)/sizeof(ws_sock_map
[0]); i
++) {
1369 if( ws_sock_map
[i
][0] == *optname
)
1371 *optname
= ws_sock_map
[i
][1];
1375 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname
);
1377 case WS_IPPROTO_TCP
:
1378 *level
= IPPROTO_TCP
;
1379 for(i
=0; i
<sizeof(ws_tcp_map
)/sizeof(ws_tcp_map
[0]); i
++) {
1380 if ( ws_tcp_map
[i
][0] == *optname
)
1382 *optname
= ws_tcp_map
[i
][1];
1386 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname
);
1389 *level
= IPPROTO_IP
;
1390 for(i
=0; i
<sizeof(ws_ip_map
)/sizeof(ws_ip_map
[0]); i
++) {
1391 if (ws_ip_map
[i
][0] == *optname
)
1393 *optname
= ws_ip_map
[i
][1];
1397 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname
);
1399 case WS_IPPROTO_IPV6
:
1400 *level
= IPPROTO_IPV6
;
1401 for(i
=0; i
<sizeof(ws_ipv6_map
)/sizeof(ws_ipv6_map
[0]); i
++) {
1402 if (ws_ipv6_map
[i
][0] == *optname
)
1404 *optname
= ws_ipv6_map
[i
][1];
1408 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname
);
1410 default: FIXME("Unimplemented or unknown socket level\n");
1415 /* ----------------------------------- Per-thread info (or per-process?) */
1417 static char *strdup_lower(const char *str
)
1420 char *ret
= HeapAlloc( GetProcessHeap(), 0, strlen(str
) + 1 );
1424 for (i
= 0; str
[i
]; i
++) ret
[i
] = tolower(str
[i
]);
1427 else SetLastError(WSAENOBUFS
);
1431 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1432 * from an fd and return the value converted to milli seconds
1433 * or 0 if there is an infinite time out */
1434 static inline INT64
get_rcvsnd_timeo( int fd
, BOOL is_recv
)
1437 socklen_t len
= sizeof(tv
);
1442 optname
= SO_RCVTIMEO
;
1448 optname
= SO_SNDTIMEO
;
1453 res
= getsockopt(fd
, SOL_SOCKET
, optname
, &tv
, &len
);
1456 return (UINT64
)tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000;
1459 /* utility: given an fd, will block until one of the events occurs */
1460 static inline int do_block( int fd
, int events
, int timeout
)
1466 pfd
.events
= events
;
1468 while ((ret
= poll(&pfd
, 1, timeout
)) < 0)
1479 convert_af_w2u(int windowsaf
) {
1482 for (i
=0;i
<sizeof(ws_af_map
)/sizeof(ws_af_map
[0]);i
++)
1483 if (ws_af_map
[i
][0] == windowsaf
)
1484 return ws_af_map
[i
][1];
1485 FIXME("unhandled Windows address family %d\n", windowsaf
);
1490 convert_af_u2w(int unixaf
) {
1493 for (i
=0;i
<sizeof(ws_af_map
)/sizeof(ws_af_map
[0]);i
++)
1494 if (ws_af_map
[i
][1] == unixaf
)
1495 return ws_af_map
[i
][0];
1496 FIXME("unhandled UNIX address family %d\n", unixaf
);
1501 convert_proto_w2u(int windowsproto
) {
1504 for (i
=0;i
<sizeof(ws_proto_map
)/sizeof(ws_proto_map
[0]);i
++)
1505 if (ws_proto_map
[i
][0] == windowsproto
)
1506 return ws_proto_map
[i
][1];
1508 /* check for extended IPX */
1509 if (IS_IPX_PROTO(windowsproto
))
1510 return windowsproto
;
1512 FIXME("unhandled Windows socket protocol %d\n", windowsproto
);
1517 convert_proto_u2w(int unixproto
) {
1520 for (i
=0;i
<sizeof(ws_proto_map
)/sizeof(ws_proto_map
[0]);i
++)
1521 if (ws_proto_map
[i
][1] == unixproto
)
1522 return ws_proto_map
[i
][0];
1524 /* if value is inside IPX range just return it - the kernel simply
1525 * echoes the value used in the socket() function */
1526 if (IS_IPX_PROTO(unixproto
))
1529 FIXME("unhandled UNIX socket protocol %d\n", unixproto
);
1534 convert_socktype_w2u(int windowssocktype
) {
1537 for (i
=0;i
<sizeof(ws_socktype_map
)/sizeof(ws_socktype_map
[0]);i
++)
1538 if (ws_socktype_map
[i
][0] == windowssocktype
)
1539 return ws_socktype_map
[i
][1];
1540 FIXME("unhandled Windows socket type %d\n", windowssocktype
);
1545 convert_socktype_u2w(int unixsocktype
) {
1548 for (i
=0;i
<sizeof(ws_socktype_map
)/sizeof(ws_socktype_map
[0]);i
++)
1549 if (ws_socktype_map
[i
][1] == unixsocktype
)
1550 return ws_socktype_map
[i
][0];
1551 FIXME("unhandled UNIX socket type %d\n", unixsocktype
);
1555 static int convert_poll_w2u(int events
)
1558 for (i
= ret
= 0; events
&& i
< sizeof(ws_poll_map
) / sizeof(ws_poll_map
[0]); i
++)
1560 if (ws_poll_map
[i
][0] & events
)
1562 ret
|= ws_poll_map
[i
][1];
1563 events
&= ~ws_poll_map
[i
][0];
1568 FIXME("Unsupported WSAPoll() flags 0x%x\n", events
);
1572 static int convert_poll_u2w(int events
)
1575 for (i
= ret
= 0; events
&& i
< sizeof(ws_poll_map
) / sizeof(ws_poll_map
[0]); i
++)
1577 if (ws_poll_map
[i
][1] & events
)
1579 ret
|= ws_poll_map
[i
][0];
1580 events
&= ~ws_poll_map
[i
][1];
1585 FIXME("Unsupported poll() flags 0x%x\n", events
);
1589 static int set_ipx_packettype(int sock
, int ptype
)
1592 int fd
= get_sock_fd( sock
, 0, NULL
), ret
= 0;
1593 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype
, fd
);
1595 if (fd
== -1) return SOCKET_ERROR
;
1597 /* We try to set the ipx type on ipx socket level. */
1599 if(setsockopt(fd
, SOL_IPX
, IPX_TYPE
, &ptype
, sizeof(ptype
)) == -1)
1601 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1607 /* Should we retrieve val using a getsockopt call and then
1608 * set the modified one? */
1610 setsockopt(fd
, 0, SO_DEFAULT_HEADERS
, &val
, sizeof(struct ipx
));
1613 release_sock_fd( sock
, fd
);
1616 WARN("IPX support is not enabled, can't set packet type\n");
1617 return SOCKET_ERROR
;
1621 /* ----------------------------------- API -----
1623 * Init / cleanup / error checking.
1626 /***********************************************************************
1627 * WSAStartup (WS2_32.115)
1629 int WINAPI
WSAStartup(WORD wVersionRequested
, LPWSADATA lpWSAData
)
1631 TRACE("verReq=%x\n", wVersionRequested
);
1633 if (LOBYTE(wVersionRequested
) < 1)
1634 return WSAVERNOTSUPPORTED
;
1636 if (!lpWSAData
) return WSAEINVAL
;
1640 /* that's the whole of the negotiation for now */
1641 lpWSAData
->wVersion
= wVersionRequested
;
1642 /* return winsock information */
1643 lpWSAData
->wHighVersion
= 0x0202;
1644 strcpy(lpWSAData
->szDescription
, "WinSock 2.0" );
1645 strcpy(lpWSAData
->szSystemStatus
, "Running" );
1646 lpWSAData
->iMaxSockets
= WS_MAX_SOCKETS_PER_PROCESS
;
1647 lpWSAData
->iMaxUdpDg
= WS_MAX_UDP_DATAGRAM
;
1648 /* don't do anything with lpWSAData->lpVendorInfo */
1649 /* (some apps don't allocate the space for this field) */
1651 TRACE("succeeded starts: %d\n", num_startup
);
1656 /***********************************************************************
1657 * WSACleanup (WS2_32.116)
1659 INT WINAPI
WSACleanup(void)
1663 TRACE("pending cleanups: %d\n", num_startup
);
1666 SetLastError(WSANOTINITIALISED
);
1667 return SOCKET_ERROR
;
1671 /***********************************************************************
1672 * WSAGetLastError (WS2_32.111)
1674 INT WINAPI
WSAGetLastError(void)
1676 return GetLastError();
1679 /***********************************************************************
1680 * WSASetLastError (WS2_32.112)
1682 void WINAPI
WSASetLastError(INT iError
) {
1683 SetLastError(iError
);
1686 static struct WS_hostent
*check_buffer_he(int size
)
1688 struct per_thread_data
* ptb
= get_per_thread_data();
1691 if (ptb
->he_len
>= size
) return ptb
->he_buffer
;
1692 HeapFree( GetProcessHeap(), 0, ptb
->he_buffer
);
1694 ptb
->he_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->he_len
= size
) );
1695 if (!ptb
->he_buffer
) SetLastError(WSAENOBUFS
);
1696 return ptb
->he_buffer
;
1699 static struct WS_servent
*check_buffer_se(int size
)
1701 struct per_thread_data
* ptb
= get_per_thread_data();
1704 if (ptb
->se_len
>= size
) return ptb
->se_buffer
;
1705 HeapFree( GetProcessHeap(), 0, ptb
->se_buffer
);
1707 ptb
->se_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->se_len
= size
) );
1708 if (!ptb
->se_buffer
) SetLastError(WSAENOBUFS
);
1709 return ptb
->se_buffer
;
1712 static struct WS_protoent
*check_buffer_pe(int size
)
1714 struct per_thread_data
* ptb
= get_per_thread_data();
1717 if (ptb
->pe_len
>= size
) return ptb
->pe_buffer
;
1718 HeapFree( GetProcessHeap(), 0, ptb
->pe_buffer
);
1720 ptb
->pe_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->pe_len
= size
) );
1721 if (!ptb
->pe_buffer
) SetLastError(WSAENOBUFS
);
1722 return ptb
->pe_buffer
;
1725 /* ----------------------------------- i/o APIs */
1727 static inline BOOL
supported_pf(int pf
)
1747 static inline BOOL
supported_protocol(int protocol
)
1750 for (i
= 0; i
< sizeof(valid_protocols
) / sizeof(valid_protocols
[0]); i
++)
1751 if (protocol
== valid_protocols
[i
])
1756 /**********************************************************************/
1758 /* Returns the length of the converted address if successful, 0 if it was too
1759 * small to start with or unknown family or invalid address buffer.
1761 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr
* wsaddr
, int wsaddrlen
,
1762 union generic_unix_sockaddr
*uaddr
)
1764 unsigned int uaddrlen
= 0;
1769 switch (wsaddr
->sa_family
)
1774 const struct WS_sockaddr_ipx
* wsipx
=(const struct WS_sockaddr_ipx
*)wsaddr
;
1775 struct sockaddr_ipx
* uipx
= (struct sockaddr_ipx
*)uaddr
;
1777 if (wsaddrlen
<sizeof(struct WS_sockaddr_ipx
))
1780 uaddrlen
= sizeof(struct sockaddr_ipx
);
1781 memset( uaddr
, 0, uaddrlen
);
1782 uipx
->sipx_family
=AF_IPX
;
1783 uipx
->sipx_port
=wsipx
->sa_socket
;
1784 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1787 memcpy(&uipx
->sipx_network
,wsipx
->sa_netnum
,sizeof(uipx
->sipx_network
)+sizeof(uipx
->sipx_node
));
1788 #ifdef IPX_FRAME_NONE
1789 uipx
->sipx_type
=IPX_FRAME_NONE
;
1795 struct sockaddr_in6
* uin6
= (struct sockaddr_in6
*)uaddr
;
1796 const struct WS_sockaddr_in6
* win6
= (const struct WS_sockaddr_in6
*)wsaddr
;
1798 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1799 * scope_id, one without.
1801 if (wsaddrlen
>= sizeof(struct WS_sockaddr_in6_old
)) {
1802 uaddrlen
= sizeof(struct sockaddr_in6
);
1803 memset( uaddr
, 0, uaddrlen
);
1804 uin6
->sin6_family
= AF_INET6
;
1805 uin6
->sin6_port
= win6
->sin6_port
;
1806 uin6
->sin6_flowinfo
= win6
->sin6_flowinfo
;
1807 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1808 if (wsaddrlen
>= sizeof(struct WS_sockaddr_in6
)) uin6
->sin6_scope_id
= win6
->sin6_scope_id
;
1810 memcpy(&uin6
->sin6_addr
,&win6
->sin6_addr
,16); /* 16 bytes = 128 address bits */
1813 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen
);
1817 struct sockaddr_in
* uin
= (struct sockaddr_in
*)uaddr
;
1818 const struct WS_sockaddr_in
* win
= (const struct WS_sockaddr_in
*)wsaddr
;
1820 if (wsaddrlen
<sizeof(struct WS_sockaddr_in
))
1822 uaddrlen
= sizeof(struct sockaddr_in
);
1823 memset( uaddr
, 0, uaddrlen
);
1824 uin
->sin_family
= AF_INET
;
1825 uin
->sin_port
= win
->sin_port
;
1826 memcpy(&uin
->sin_addr
,&win
->sin_addr
,4); /* 4 bytes = 32 address bits */
1831 struct sockaddr_irda
*uin
= (struct sockaddr_irda
*)uaddr
;
1832 const SOCKADDR_IRDA
*win
= (const SOCKADDR_IRDA
*)wsaddr
;
1834 if (wsaddrlen
< sizeof(SOCKADDR_IRDA
))
1836 uaddrlen
= sizeof(struct sockaddr_irda
);
1837 memset( uaddr
, 0, uaddrlen
);
1838 uin
->sir_family
= AF_IRDA
;
1839 if (!strncmp( win
->irdaServiceName
, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1841 unsigned int lsap_sel
= 0;
1843 sscanf( win
->irdaServiceName
, "LSAP-SEL%u", &lsap_sel
);
1844 uin
->sir_lsap_sel
= lsap_sel
;
1848 uin
->sir_lsap_sel
= LSAP_ANY
;
1849 memcpy( uin
->sir_name
, win
->irdaServiceName
, 25 );
1851 memcpy( &uin
->sir_addr
, win
->irdaDeviceID
, sizeof(uin
->sir_addr
) );
1855 case WS_AF_UNSPEC
: {
1856 /* Try to determine the needed space by the passed windows sockaddr space */
1857 switch (wsaddrlen
) {
1858 default: /* likely an ipv4 address */
1859 case sizeof(struct WS_sockaddr_in
):
1860 uaddrlen
= sizeof(struct sockaddr_in
);
1863 case sizeof(struct WS_sockaddr_ipx
):
1864 uaddrlen
= sizeof(struct sockaddr_ipx
);
1868 case sizeof(SOCKADDR_IRDA
):
1869 uaddrlen
= sizeof(struct sockaddr_irda
);
1872 case sizeof(struct WS_sockaddr_in6
):
1873 case sizeof(struct WS_sockaddr_in6_old
):
1874 uaddrlen
= sizeof(struct sockaddr_in6
);
1877 memset( uaddr
, 0, uaddrlen
);
1881 FIXME("Unknown address family %d, return NULL.\n", wsaddr
->sa_family
);
1887 static BOOL
is_sockaddr_bound(const struct sockaddr
*uaddr
, int uaddrlen
)
1889 switch (uaddr
->sa_family
)
1894 static const struct sockaddr_ipx emptyAddr
;
1895 struct sockaddr_ipx
*ipx
= (struct sockaddr_ipx
*) uaddr
;
1896 return ipx
->sipx_port
1897 || memcmp(&ipx
->sipx_network
, &emptyAddr
.sipx_network
, sizeof(emptyAddr
.sipx_network
))
1898 || memcmp(&ipx
->sipx_node
, &emptyAddr
.sipx_node
, sizeof(emptyAddr
.sipx_node
));
1903 static const struct sockaddr_in6 emptyAddr
;
1904 const struct sockaddr_in6
*in6
= (const struct sockaddr_in6
*) uaddr
;
1905 return in6
->sin6_port
|| memcmp(&in6
->sin6_addr
, &emptyAddr
.sin6_addr
, sizeof(struct in6_addr
));
1909 static const struct sockaddr_in emptyAddr
;
1910 const struct sockaddr_in
*in
= (const struct sockaddr_in
*) uaddr
;
1911 return in
->sin_port
|| memcmp(&in
->sin_addr
, &emptyAddr
.sin_addr
, sizeof(struct in_addr
));
1916 FIXME("unknown address family %d\n", uaddr
->sa_family
);
1921 /* Returns -1 if getsockname fails, 0 if not bound, 1 otherwise */
1922 static int is_fd_bound(int fd
, union generic_unix_sockaddr
*uaddr
, socklen_t
*uaddrlen
)
1924 union generic_unix_sockaddr inaddr
;
1928 if (!uaddr
) uaddr
= &inaddr
;
1929 if (!uaddrlen
) uaddrlen
= &inlen
;
1931 *uaddrlen
= sizeof(inaddr
);
1932 res
= getsockname(fd
, &uaddr
->addr
, uaddrlen
);
1933 if (!res
) res
= is_sockaddr_bound(&uaddr
->addr
, *uaddrlen
);
1937 /* Returns 0 if successful, -1 if the buffer is too small */
1938 static int ws_sockaddr_u2ws(const struct sockaddr
* uaddr
, struct WS_sockaddr
* wsaddr
, int* wsaddrlen
)
1942 switch(uaddr
->sa_family
)
1947 const struct sockaddr_ipx
* uipx
=(const struct sockaddr_ipx
*)uaddr
;
1948 struct WS_sockaddr_ipx
* wsipx
=(struct WS_sockaddr_ipx
*)wsaddr
;
1951 switch (*wsaddrlen
) /* how much can we copy? */
1955 *wsaddrlen
= sizeof(*wsipx
);
1956 wsipx
->sa_socket
=uipx
->sipx_port
;
1960 memcpy(wsipx
->sa_nodenum
,uipx
->sipx_node
,sizeof(wsipx
->sa_nodenum
));
1968 memcpy(wsipx
->sa_netnum
,&uipx
->sipx_network
,sizeof(wsipx
->sa_netnum
));
1974 wsipx
->sa_family
=WS_AF_IPX
;
1986 const struct sockaddr_irda
*uin
= (const struct sockaddr_irda
*)uaddr
;
1987 SOCKADDR_IRDA
*win
= (SOCKADDR_IRDA
*)wsaddr
;
1989 if (*wsaddrlen
< sizeof(SOCKADDR_IRDA
))
1991 win
->irdaAddressFamily
= WS_AF_IRDA
;
1992 memcpy( win
->irdaDeviceID
, &uin
->sir_addr
, sizeof(win
->irdaDeviceID
) );
1993 if (uin
->sir_lsap_sel
!= LSAP_ANY
)
1994 sprintf( win
->irdaServiceName
, "LSAP-SEL%u", uin
->sir_lsap_sel
);
1996 memcpy( win
->irdaServiceName
, uin
->sir_name
,
1997 sizeof(win
->irdaServiceName
) );
2002 const struct sockaddr_in6
* uin6
= (const struct sockaddr_in6
*)uaddr
;
2003 struct WS_sockaddr_in6_old
* win6old
= (struct WS_sockaddr_in6_old
*)wsaddr
;
2005 if (*wsaddrlen
< sizeof(struct WS_sockaddr_in6_old
))
2007 win6old
->sin6_family
= WS_AF_INET6
;
2008 win6old
->sin6_port
= uin6
->sin6_port
;
2009 win6old
->sin6_flowinfo
= uin6
->sin6_flowinfo
;
2010 memcpy(&win6old
->sin6_addr
,&uin6
->sin6_addr
,16); /* 16 bytes = 128 address bits */
2011 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
2012 if (*wsaddrlen
>= sizeof(struct WS_sockaddr_in6
)) {
2013 struct WS_sockaddr_in6
* win6
= (struct WS_sockaddr_in6
*)wsaddr
;
2014 win6
->sin6_scope_id
= uin6
->sin6_scope_id
;
2015 *wsaddrlen
= sizeof(struct WS_sockaddr_in6
);
2018 *wsaddrlen
= sizeof(struct WS_sockaddr_in6_old
);
2020 *wsaddrlen
= sizeof(struct WS_sockaddr_in6_old
);
2025 const struct sockaddr_in
* uin
= (const struct sockaddr_in
*)uaddr
;
2026 struct WS_sockaddr_in
* win
= (struct WS_sockaddr_in
*)wsaddr
;
2028 if (*wsaddrlen
< sizeof(struct WS_sockaddr_in
))
2030 win
->sin_family
= WS_AF_INET
;
2031 win
->sin_port
= uin
->sin_port
;
2032 memcpy(&win
->sin_addr
,&uin
->sin_addr
,4); /* 4 bytes = 32 address bits */
2033 memset(win
->sin_zero
, 0, 8); /* Make sure the null padding is null */
2034 *wsaddrlen
= sizeof(struct WS_sockaddr_in
);
2038 memset(wsaddr
,0,*wsaddrlen
);
2042 FIXME("Unknown address family %d\n", uaddr
->sa_family
);
2048 static INT
WS_DuplicateSocket(BOOL unicode
, SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOW lpProtocolInfo
)
2052 WSAPROTOCOL_INFOW infow
;
2054 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
2055 unicode
, s
, dwProcessId
, lpProtocolInfo
);
2057 if (!ws_protocol_info(s
, unicode
, &infow
, &size
))
2058 return SOCKET_ERROR
;
2060 if (!(hProcess
= OpenProcess(PROCESS_DUP_HANDLE
, FALSE
, dwProcessId
)))
2062 SetLastError(WSAEINVAL
);
2063 return SOCKET_ERROR
;
2066 if (!lpProtocolInfo
)
2068 CloseHandle(hProcess
);
2069 SetLastError(WSAEFAULT
);
2070 return SOCKET_ERROR
;
2073 /* I don't know what the real Windoze does next, this is a hack */
2074 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
2075 * the target use the global duplicate, or we could copy a reference to us to the structure
2076 * and let the target duplicate it from us, but let's do it as simple as possible */
2077 memcpy(lpProtocolInfo
, &infow
, size
);
2078 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s
),
2079 hProcess
, (LPHANDLE
)&lpProtocolInfo
->dwServiceFlags3
,
2080 0, FALSE
, DUPLICATE_SAME_ACCESS
);
2081 CloseHandle(hProcess
);
2082 lpProtocolInfo
->dwServiceFlags4
= 0xff00ff00; /* magic */
2086 /*****************************************************************************
2087 * WS_EnterSingleProtocolW [internal]
2089 * enters the protocol information of one given protocol into the given
2093 * TRUE if a protocol was entered into the buffer.
2096 * - only implemented for IPX, SPX, SPXII, TCP, UDP
2097 * - there is no check that the operating system supports the returned
2100 static BOOL
WS_EnterSingleProtocolW( INT protocol
, WSAPROTOCOL_INFOW
* info
)
2102 memset( info
, 0, sizeof(WSAPROTOCOL_INFOW
) );
2103 info
->iProtocol
= protocol
;
2107 case WS_IPPROTO_TCP
:
2108 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_EXPEDITED_DATA
|
2109 XP1_GRACEFUL_CLOSE
| XP1_GUARANTEED_ORDER
|
2110 XP1_GUARANTEED_DELIVERY
;
2111 info
->ProviderId
= ProviderIdIP
;
2112 info
->dwCatalogEntryId
= 0x3e9;
2113 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2114 info
->ProtocolChain
.ChainLen
= 1;
2116 info
->iAddressFamily
= WS_AF_INET
;
2117 info
->iMaxSockAddr
= 0x10;
2118 info
->iMinSockAddr
= 0x10;
2119 info
->iSocketType
= WS_SOCK_STREAM
;
2120 strcpyW( info
->szProtocol
, NameTcpW
);
2123 case WS_IPPROTO_UDP
:
2124 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_SUPPORT_BROADCAST
|
2125 XP1_SUPPORT_MULTIPOINT
| XP1_MESSAGE_ORIENTED
|
2127 info
->ProviderId
= ProviderIdIP
;
2128 info
->dwCatalogEntryId
= 0x3ea;
2129 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2130 info
->ProtocolChain
.ChainLen
= 1;
2132 info
->iAddressFamily
= WS_AF_INET
;
2133 info
->iMaxSockAddr
= 0x10;
2134 info
->iMinSockAddr
= 0x10;
2135 info
->iSocketType
= WS_SOCK_DGRAM
;
2136 info
->dwMessageSize
= 0xffbb;
2137 strcpyW( info
->szProtocol
, NameUdpW
);
2140 case WS_NSPROTO_IPX
:
2141 info
->dwServiceFlags1
= XP1_PARTIAL_MESSAGE
| XP1_SUPPORT_BROADCAST
|
2142 XP1_SUPPORT_MULTIPOINT
| XP1_MESSAGE_ORIENTED
|
2144 info
->ProviderId
= ProviderIdIPX
;
2145 info
->dwCatalogEntryId
= 0x406;
2146 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2147 info
->ProtocolChain
.ChainLen
= 1;
2149 info
->iAddressFamily
= WS_AF_IPX
;
2150 info
->iMaxSockAddr
= 0x10;
2151 info
->iMinSockAddr
= 0x0e;
2152 info
->iSocketType
= WS_SOCK_DGRAM
;
2153 info
->iProtocolMaxOffset
= 0xff;
2154 info
->dwMessageSize
= 0x240;
2155 strcpyW( info
->szProtocol
, NameIpxW
);
2158 case WS_NSPROTO_SPX
:
2159 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_PSEUDO_STREAM
|
2160 XP1_MESSAGE_ORIENTED
| XP1_GUARANTEED_ORDER
|
2161 XP1_GUARANTEED_DELIVERY
;
2162 info
->ProviderId
= ProviderIdSPX
;
2163 info
->dwCatalogEntryId
= 0x407;
2164 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2165 info
->ProtocolChain
.ChainLen
= 1;
2167 info
->iAddressFamily
= WS_AF_IPX
;
2168 info
->iMaxSockAddr
= 0x10;
2169 info
->iMinSockAddr
= 0x0e;
2170 info
->iSocketType
= WS_SOCK_SEQPACKET
;
2171 info
->dwMessageSize
= 0xffffffff;
2172 strcpyW( info
->szProtocol
, NameSpxW
);
2175 case WS_NSPROTO_SPXII
:
2176 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_GRACEFUL_CLOSE
|
2177 XP1_PSEUDO_STREAM
| XP1_MESSAGE_ORIENTED
|
2178 XP1_GUARANTEED_ORDER
| XP1_GUARANTEED_DELIVERY
;
2179 info
->ProviderId
= ProviderIdSPX
;
2180 info
->dwCatalogEntryId
= 0x409;
2181 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2182 info
->ProtocolChain
.ChainLen
= 1;
2184 info
->iAddressFamily
= WS_AF_IPX
;
2185 info
->iMaxSockAddr
= 0x10;
2186 info
->iMinSockAddr
= 0x0e;
2187 info
->iSocketType
= WS_SOCK_SEQPACKET
;
2188 info
->dwMessageSize
= 0xffffffff;
2189 strcpyW( info
->szProtocol
, NameSpxIIW
);
2193 FIXME("unknown Protocol <0x%08x>\n", protocol
);
2199 /*****************************************************************************
2200 * WS_EnterSingleProtocolA [internal]
2202 * see function WS_EnterSingleProtocolW
2205 static BOOL
WS_EnterSingleProtocolA( INT protocol
, WSAPROTOCOL_INFOA
* info
)
2207 WSAPROTOCOL_INFOW infow
;
2209 memset( info
, 0, sizeof(WSAPROTOCOL_INFOA
) );
2211 ret
= WS_EnterSingleProtocolW( protocol
, &infow
);
2214 /* convert the structure from W to A */
2215 memcpy( info
, &infow
, FIELD_OFFSET( WSAPROTOCOL_INFOA
, szProtocol
) );
2216 WideCharToMultiByte( CP_ACP
, 0, infow
.szProtocol
, -1,
2217 info
->szProtocol
, WSAPROTOCOL_LEN
+1, NULL
, NULL
);
2223 static INT
WS_EnumProtocols( BOOL unicode
, const INT
*protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
)
2225 INT i
= 0, items
= 0;
2229 LPWSAPROTOCOL_INFOA a
;
2230 LPWSAPROTOCOL_INFOW w
;
2234 if (!protocols
) protocols
= valid_protocols
;
2236 while (protocols
[i
])
2238 if(supported_protocol(protocols
[i
++]))
2242 size
= items
* (unicode
? sizeof(WSAPROTOCOL_INFOW
) : sizeof(WSAPROTOCOL_INFOA
));
2244 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
2245 unicode
, protocols
, buffer
, len
, len
? *len
: 0, items
, size
);
2247 if (*len
< size
|| !buffer
)
2250 SetLastError(WSAENOBUFS
);
2251 return SOCKET_ERROR
;
2254 for (i
= items
= 0; protocols
[i
]; i
++)
2256 if (!supported_protocol(protocols
[i
])) continue;
2259 if (WS_EnterSingleProtocolW( protocols
[i
], &info
.w
[items
] ))
2264 if (WS_EnterSingleProtocolA( protocols
[i
], &info
.a
[items
] ))
2271 static BOOL
ws_protocol_info(SOCKET s
, int unicode
, WSAPROTOCOL_INFOW
*buffer
, int *size
)
2275 *size
= unicode
? sizeof(WSAPROTOCOL_INFOW
) : sizeof(WSAPROTOCOL_INFOA
);
2276 memset(buffer
, 0, *size
);
2278 SERVER_START_REQ( get_socket_info
)
2280 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
2281 status
= wine_server_call( req
);
2284 buffer
->iAddressFamily
= convert_af_u2w(reply
->family
);
2285 buffer
->iSocketType
= convert_socktype_u2w(reply
->type
);
2286 buffer
->iProtocol
= convert_proto_u2w(reply
->protocol
);
2293 unsigned int err
= NtStatusToWSAError( status
);
2294 SetLastError( err
== WSAEBADF
? WSAENOTSOCK
: err
);
2299 WS_EnterSingleProtocolW( buffer
->iProtocol
, buffer
);
2301 WS_EnterSingleProtocolA( buffer
->iProtocol
, (WSAPROTOCOL_INFOA
*)buffer
);
2306 /**************************************************************************
2307 * Functions for handling overlapped I/O
2308 **************************************************************************/
2310 /* user APC called upon async completion */
2311 static void WINAPI
ws2_async_apc( void *arg
, IO_STATUS_BLOCK
*iosb
, ULONG reserved
)
2313 struct ws2_async
*wsa
= arg
;
2315 if (wsa
->completion_func
) wsa
->completion_func( NtStatusToWSAError(iosb
->u
.Status
),
2316 iosb
->Information
, wsa
->user_overlapped
,
2318 release_async_io( &wsa
->io
);
2321 /***********************************************************************
2322 * WS2_recv (INTERNAL)
2324 * Workhorse for both synchronous and asynchronous recv() operations.
2326 static int WS2_recv( int fd
, struct ws2_async
*wsa
, int flags
)
2328 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2332 union generic_unix_sockaddr unix_sockaddr
;
2335 hdr
.msg_name
= NULL
;
2339 hdr
.msg_namelen
= sizeof(unix_sockaddr
);
2340 hdr
.msg_name
= &unix_sockaddr
;
2343 hdr
.msg_namelen
= 0;
2345 hdr
.msg_iov
= wsa
->iovec
+ wsa
->first_iovec
;
2346 hdr
.msg_iovlen
= wsa
->n_iovecs
- wsa
->first_iovec
;
2347 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2348 hdr
.msg_accrights
= NULL
;
2349 hdr
.msg_accrightslen
= 0;
2351 hdr
.msg_control
= pktbuf
;
2352 hdr
.msg_controllen
= sizeof(pktbuf
);
2356 while ((n
= recvmsg(fd
, &hdr
, flags
)) == -1)
2362 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2365 ERR("Message control headers cannot be properly supported on this system.\n");
2366 wsa
->control
->len
= 0;
2369 if (wsa
->control
&& !convert_control_headers(&hdr
, wsa
->control
))
2371 WARN("Application passed insufficient room for control headers.\n");
2372 *wsa
->lpFlags
|= WS_MSG_CTRUNC
;
2378 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
2379 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
2381 * quoting linux 2.6 net/ipv4/tcp.c:
2382 * "According to UNIX98, msg_name/msg_namelen are ignored
2383 * on connected socket. I was just happy when found this 8) --ANK"
2385 * likewise MSDN says that lpFrom and lpFromlen are ignored for
2386 * connection-oriented sockets, so don't try to update lpFrom.
2388 if (wsa
->addr
&& hdr
.msg_namelen
)
2389 ws_sockaddr_u2ws( &unix_sockaddr
.addr
, wsa
->addr
, wsa
->addrlen
.ptr
);
2394 /***********************************************************************
2395 * WS2_async_recv (INTERNAL)
2397 * Handler for overlapped recv() operations.
2399 static NTSTATUS
WS2_async_recv( void *user
, IO_STATUS_BLOCK
*iosb
,
2400 NTSTATUS status
, void **apc
, void **arg
)
2402 struct ws2_async
*wsa
= user
;
2407 case STATUS_ALERTED
:
2408 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, FILE_READ_DATA
, &fd
, NULL
) ))
2411 result
= WS2_recv( fd
, wsa
, convert_flags(wsa
->flags
) );
2412 wine_server_release_fd( wsa
->hSocket
, fd
);
2415 status
= STATUS_SUCCESS
;
2416 _enable_event( wsa
->hSocket
, FD_READ
, 0, 0 );
2420 if (errno
== EAGAIN
)
2422 status
= STATUS_PENDING
;
2423 _enable_event( wsa
->hSocket
, FD_READ
, 0, 0 );
2428 status
= wsaErrStatus();
2433 if (status
!= STATUS_PENDING
)
2435 iosb
->u
.Status
= status
;
2436 iosb
->Information
= result
;
2437 if (wsa
->completion_func
)
2439 *apc
= ws2_async_apc
;
2443 release_async_io( &wsa
->io
);
2448 /***********************************************************************
2449 * WS2_async_accept_recv (INTERNAL)
2451 * This function is used to finish the read part of an accept request. It is
2452 * needed to place the completion on the correct socket (listener).
2454 static NTSTATUS
WS2_async_accept_recv( void *user
, IO_STATUS_BLOCK
*iosb
,
2455 NTSTATUS status
, void **apc
, void **arg
)
2458 struct ws2_accept_async
*wsa
= user
;
2460 status
= WS2_async_recv( wsa
->read
, iosb
, status
, &junk
, &junk
);
2461 if (status
== STATUS_PENDING
)
2465 WS_AddCompletion( HANDLE2SOCKET(wsa
->listen_socket
), wsa
->cvalue
, iosb
->u
.Status
, iosb
->Information
);
2467 release_async_io( &wsa
->io
);
2471 /***********************************************************************
2472 * WS2_async_accept (INTERNAL)
2474 * This is the function called to satisfy the AcceptEx callback
2476 static NTSTATUS
WS2_async_accept( void *user
, IO_STATUS_BLOCK
*iosb
,
2477 NTSTATUS status
, void **apc
, void **arg
)
2479 struct ws2_accept_async
*wsa
= user
;
2483 TRACE("status: 0x%x listen: %p, accept: %p\n", status
, wsa
->listen_socket
, wsa
->accept_socket
);
2485 if (status
== STATUS_ALERTED
)
2487 SERVER_START_REQ( accept_into_socket
)
2489 req
->lhandle
= wine_server_obj_handle( wsa
->listen_socket
);
2490 req
->ahandle
= wine_server_obj_handle( wsa
->accept_socket
);
2491 status
= wine_server_call( req
);
2495 if (status
== STATUS_CANT_WAIT
)
2496 return STATUS_PENDING
;
2498 if (status
== STATUS_INVALID_HANDLE
)
2500 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2501 status
= STATUS_CANCELLED
;
2504 else if (status
== STATUS_HANDLES_CLOSED
)
2505 status
= STATUS_CANCELLED
; /* strange windows behavior */
2507 if (status
!= STATUS_SUCCESS
)
2510 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2511 addr
= ((char *)wsa
->buf
) + wsa
->data_len
;
2512 len
= wsa
->local_len
- sizeof(int);
2513 WS_getsockname(HANDLE2SOCKET(wsa
->accept_socket
),
2514 (struct WS_sockaddr
*)(addr
+ sizeof(int)), &len
);
2517 addr
+= wsa
->local_len
;
2518 len
= wsa
->remote_len
- sizeof(int);
2519 WS_getpeername(HANDLE2SOCKET(wsa
->accept_socket
),
2520 (struct WS_sockaddr
*)(addr
+ sizeof(int)), &len
);
2526 status
= register_async( ASYNC_TYPE_READ
, wsa
->accept_socket
, WS2_async_accept_recv
, wsa
,
2527 wsa
->user_overlapped
->hEvent
, NULL
, NULL
, iosb
);
2529 if (status
!= STATUS_PENDING
)
2532 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2533 * needs to be performed by WS2_async_accept_recv() first. */
2534 return STATUS_MORE_PROCESSING_REQUIRED
;
2537 iosb
->u
.Status
= status
;
2538 iosb
->Information
= 0;
2540 if (wsa
->read
) release_async_io( &wsa
->read
->io
);
2541 release_async_io( &wsa
->io
);
2545 /***********************************************************************
2546 * WS2_send (INTERNAL)
2548 * Workhorse for both synchronous and asynchronous send() operations.
2550 static int WS2_send( int fd
, struct ws2_async
*wsa
, int flags
)
2553 union generic_unix_sockaddr unix_addr
;
2556 hdr
.msg_name
= NULL
;
2557 hdr
.msg_namelen
= 0;
2561 hdr
.msg_name
= &unix_addr
;
2562 hdr
.msg_namelen
= ws_sockaddr_ws2u( wsa
->addr
, wsa
->addrlen
.val
, &unix_addr
);
2563 if ( !hdr
.msg_namelen
)
2569 #if defined(HAS_IPX) && defined(SOL_IPX)
2570 if(wsa
->addr
->sa_family
== WS_AF_IPX
)
2572 struct sockaddr_ipx
* uipx
= (struct sockaddr_ipx
*)hdr
.msg_name
;
2574 socklen_t len
= sizeof(int);
2576 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2577 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2578 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2579 * ipx type in the sockaddr_opx structure with the stored value.
2581 if(getsockopt(fd
, SOL_IPX
, IPX_TYPE
, &val
, &len
) != -1)
2582 uipx
->sipx_type
= val
;
2587 hdr
.msg_iov
= wsa
->iovec
+ wsa
->first_iovec
;
2588 hdr
.msg_iovlen
= wsa
->n_iovecs
- wsa
->first_iovec
;
2589 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2590 hdr
.msg_accrights
= NULL
;
2591 hdr
.msg_accrightslen
= 0;
2593 hdr
.msg_control
= NULL
;
2594 hdr
.msg_controllen
= 0;
2598 while ((ret
= sendmsg(fd
, &hdr
, flags
)) == -1)
2605 while (wsa
->first_iovec
< wsa
->n_iovecs
&& wsa
->iovec
[wsa
->first_iovec
].iov_len
<= n
)
2606 n
-= wsa
->iovec
[wsa
->first_iovec
++].iov_len
;
2607 if (wsa
->first_iovec
< wsa
->n_iovecs
)
2609 wsa
->iovec
[wsa
->first_iovec
].iov_base
= (char*)wsa
->iovec
[wsa
->first_iovec
].iov_base
+ n
;
2610 wsa
->iovec
[wsa
->first_iovec
].iov_len
-= n
;
2615 /***********************************************************************
2616 * WS2_async_send (INTERNAL)
2618 * Handler for overlapped send() operations.
2620 static NTSTATUS
WS2_async_send( void *user
, IO_STATUS_BLOCK
*iosb
,
2621 NTSTATUS status
, void **apc
, void **arg
)
2623 struct ws2_async
*wsa
= user
;
2628 case STATUS_ALERTED
:
2629 if ( wsa
->n_iovecs
<= wsa
->first_iovec
)
2632 status
= STATUS_SUCCESS
;
2635 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, FILE_WRITE_DATA
, &fd
, NULL
) ))
2638 /* check to see if the data is ready (non-blocking) */
2639 result
= WS2_send( fd
, wsa
, convert_flags(wsa
->flags
) );
2640 wine_server_release_fd( wsa
->hSocket
, fd
);
2644 if (wsa
->first_iovec
< wsa
->n_iovecs
)
2645 status
= STATUS_PENDING
;
2647 status
= STATUS_SUCCESS
;
2649 iosb
->Information
+= result
;
2651 else if (errno
== EAGAIN
)
2653 status
= STATUS_PENDING
;
2657 status
= wsaErrStatus();
2661 if (status
!= STATUS_PENDING
)
2663 iosb
->u
.Status
= status
;
2664 if (wsa
->completion_func
)
2666 *apc
= ws2_async_apc
;
2670 release_async_io( &wsa
->io
);
2675 /***********************************************************************
2676 * WS2_async_shutdown (INTERNAL)
2678 * Handler for shutdown() operations on overlapped sockets.
2680 static NTSTATUS
WS2_async_shutdown( void *user
, IO_STATUS_BLOCK
*iosb
,
2681 NTSTATUS status
, void **apc
, void **arg
)
2683 struct ws2_async_shutdown
*wsa
= user
;
2688 case STATUS_ALERTED
:
2689 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, 0, &fd
, NULL
) ))
2692 switch ( wsa
->type
)
2694 case ASYNC_TYPE_READ
: err
= shutdown( fd
, 0 ); break;
2695 case ASYNC_TYPE_WRITE
: err
= shutdown( fd
, 1 ); break;
2697 status
= err
? wsaErrStatus() : STATUS_SUCCESS
;
2698 wine_server_release_fd( wsa
->hSocket
, fd
);
2701 iosb
->u
.Status
= status
;
2702 iosb
->Information
= 0;
2703 release_async_io( &wsa
->io
);
2707 /***********************************************************************
2708 * WS2_register_async_shutdown (INTERNAL)
2710 * Helper function for WS_shutdown() on overlapped sockets.
2712 static int WS2_register_async_shutdown( SOCKET s
, int type
)
2714 struct ws2_async_shutdown
*wsa
;
2717 TRACE("socket %04lx type %d\n", s
, type
);
2719 wsa
= (struct ws2_async_shutdown
*)alloc_async_io( sizeof(*wsa
) );
2723 wsa
->hSocket
= SOCKET2HANDLE(s
);
2726 status
= register_async( type
, wsa
->hSocket
, WS2_async_shutdown
, wsa
, 0, NULL
, NULL
, &wsa
->iosb
);
2727 if (status
!= STATUS_PENDING
)
2729 HeapFree( GetProcessHeap(), 0, wsa
);
2730 return NtStatusToWSAError( status
);
2735 /***********************************************************************
2738 SOCKET WINAPI
WS_accept(SOCKET s
, struct WS_sockaddr
*addr
, int *addrlen32
)
2744 TRACE("socket %04lx\n", s
);
2745 status
= _is_blocking(s
, &is_blocking
);
2750 /* try accepting first (if there is a deferred connection) */
2751 SERVER_START_REQ( accept_socket
)
2753 req
->lhandle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
2754 req
->access
= GENERIC_READ
|GENERIC_WRITE
|SYNCHRONIZE
;
2755 req
->attributes
= OBJ_INHERIT
;
2756 status
= wine_server_call( req
);
2757 as
= HANDLE2SOCKET( wine_server_ptr_handle( reply
->handle
));
2762 if (addr
&& addrlen32
&& WS_getpeername(as
, addr
, addrlen32
))
2765 return SOCKET_ERROR
;
2767 TRACE("\taccepted %04lx\n", as
);
2770 if (is_blocking
&& status
== STATUS_CANT_WAIT
)
2772 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
2774 do_block(fd
, POLLIN
, -1);
2775 _sync_sock_state(s
); /* let wineserver notice connection */
2776 release_sock_fd( s
, fd
);
2778 } while (is_blocking
&& status
== STATUS_CANT_WAIT
);
2782 WARN(" -> ERROR %d\n", GetLastError());
2783 return INVALID_SOCKET
;
2786 /***********************************************************************
2789 static BOOL WINAPI
WS2_AcceptEx(SOCKET listener
, SOCKET acceptor
, PVOID dest
, DWORD dest_len
,
2790 DWORD local_addr_len
, DWORD rem_addr_len
, LPDWORD received
,
2791 LPOVERLAPPED overlapped
)
2794 struct ws2_accept_async
*wsa
;
2797 TRACE("(%04lx, %04lx, %p, %d, %d, %d, %p, %p)\n", listener
, acceptor
, dest
, dest_len
, local_addr_len
,
2798 rem_addr_len
, received
, overlapped
);
2802 SetLastError(WSAEINVAL
);
2808 SetLastError(WSA_INVALID_PARAMETER
);
2814 SetLastError(WSAEFAULT
);
2818 fd
= get_sock_fd( listener
, FILE_READ_DATA
, NULL
);
2821 SetLastError(WSAENOTSOCK
);
2824 release_sock_fd( listener
, fd
);
2826 fd
= get_sock_fd( acceptor
, FILE_READ_DATA
, NULL
);
2829 SetLastError(WSAENOTSOCK
);
2832 release_sock_fd( acceptor
, fd
);
2834 wsa
= (struct ws2_accept_async
*)alloc_async_io( sizeof(*wsa
) );
2837 SetLastError(WSAEFAULT
);
2841 wsa
->listen_socket
= SOCKET2HANDLE(listener
);
2842 wsa
->accept_socket
= SOCKET2HANDLE(acceptor
);
2843 wsa
->user_overlapped
= overlapped
;
2844 wsa
->cvalue
= !((ULONG_PTR
)overlapped
->hEvent
& 1) ? (ULONG_PTR
)overlapped
: 0;
2846 wsa
->data_len
= dest_len
;
2847 wsa
->local_len
= local_addr_len
;
2848 wsa
->remote_len
= rem_addr_len
;
2853 /* set up a read request if we need it */
2854 wsa
->read
= (struct ws2_async
*)alloc_async_io( offsetof(struct ws2_async
, iovec
[1]) );
2857 HeapFree( GetProcessHeap(), 0, wsa
);
2858 SetLastError(WSAEFAULT
);
2862 wsa
->read
->hSocket
= wsa
->accept_socket
;
2863 wsa
->read
->flags
= 0;
2864 wsa
->read
->lpFlags
= &wsa
->read
->flags
;
2865 wsa
->read
->addr
= NULL
;
2866 wsa
->read
->addrlen
.ptr
= NULL
;
2867 wsa
->read
->control
= NULL
;
2868 wsa
->read
->n_iovecs
= 1;
2869 wsa
->read
->first_iovec
= 0;
2870 wsa
->read
->completion_func
= NULL
;
2871 wsa
->read
->iovec
[0].iov_base
= wsa
->buf
;
2872 wsa
->read
->iovec
[0].iov_len
= wsa
->data_len
;
2875 status
= register_async( ASYNC_TYPE_READ
, SOCKET2HANDLE(listener
), WS2_async_accept
, wsa
,
2876 overlapped
->hEvent
, NULL
, (void *)wsa
->cvalue
, (IO_STATUS_BLOCK
*)overlapped
);
2878 if(status
!= STATUS_PENDING
)
2880 HeapFree( GetProcessHeap(), 0, wsa
->read
);
2881 HeapFree( GetProcessHeap(), 0, wsa
);
2884 SetLastError( NtStatusToWSAError(status
) );
2888 /***********************************************************************
2889 * WS2_ReadFile (INTERNAL)
2891 * Perform an APC-safe ReadFile operation
2893 static NTSTATUS
WS2_ReadFile(HANDLE hFile
, PIO_STATUS_BLOCK io_status
, char* buffer
, ULONG length
,
2894 PLARGE_INTEGER offset
)
2896 int result
= -1, unix_handle
;
2897 unsigned int options
;
2900 TRACE( "(%p,%p,0x%08x)\n", hFile
, buffer
,length
);
2902 status
= wine_server_handle_to_fd( hFile
, FILE_READ_DATA
, &unix_handle
, &options
);
2903 if (status
) return status
;
2905 while (result
== -1)
2907 if (offset
->QuadPart
!= FILE_USE_FILE_POINTER_POSITION
)
2908 result
= pread( unix_handle
, buffer
, length
, offset
->QuadPart
);
2910 result
= read( unix_handle
, buffer
, length
);
2916 status
= (length
? STATUS_END_OF_FILE
: STATUS_SUCCESS
);
2917 else if (result
!= -1)
2918 status
= STATUS_SUCCESS
;
2919 else if (errno
!= EAGAIN
)
2920 status
= wsaErrStatus();
2922 status
= STATUS_PENDING
;
2924 wine_server_release_fd( hFile
, unix_handle
);
2925 TRACE("= 0x%08x (%d)\n", status
, result
);
2926 if (status
== STATUS_SUCCESS
|| status
== STATUS_END_OF_FILE
)
2928 io_status
->u
.Status
= status
;
2929 io_status
->Information
= result
;
2935 /***********************************************************************
2936 * WS2_transmitfile_getbuffer (INTERNAL)
2938 * Pick the appropriate buffer for a TransmitFile send operation.
2940 static NTSTATUS
WS2_transmitfile_getbuffer( int fd
, struct ws2_transmitfile_async
*wsa
)
2942 /* send any incomplete writes from a previous iteration */
2943 if (wsa
->write
.first_iovec
< wsa
->write
.n_iovecs
)
2944 return STATUS_PENDING
;
2946 /* process the header (if applicable) */
2947 if (wsa
->buffers
.Head
)
2949 wsa
->write
.first_iovec
= 0;
2950 wsa
->write
.n_iovecs
= 1;
2951 wsa
->write
.iovec
[0].iov_base
= wsa
->buffers
.Head
;
2952 wsa
->write
.iovec
[0].iov_len
= wsa
->buffers
.HeadLength
;
2953 wsa
->buffers
.Head
= NULL
;
2954 return STATUS_PENDING
;
2957 /* process the main file */
2960 DWORD bytes_per_send
= wsa
->bytes_per_send
;
2961 IO_STATUS_BLOCK iosb
;
2964 iosb
.Information
= 0;
2965 /* when the size of the transfer is limited ensure that we don't go past that limit */
2966 if (wsa
->file_bytes
!= 0)
2967 bytes_per_send
= min(bytes_per_send
, wsa
->file_bytes
- wsa
->file_read
);
2968 status
= WS2_ReadFile( wsa
->file
, &iosb
, wsa
->buffer
, bytes_per_send
, &wsa
->offset
);
2969 if (wsa
->offset
.QuadPart
!= FILE_USE_FILE_POINTER_POSITION
)
2970 wsa
->offset
.QuadPart
+= iosb
.Information
;
2971 if (status
== STATUS_END_OF_FILE
)
2972 wsa
->file
= NULL
; /* continue on to the footer */
2973 else if (status
!= STATUS_SUCCESS
)
2977 if (iosb
.Information
)
2979 wsa
->write
.first_iovec
= 0;
2980 wsa
->write
.n_iovecs
= 1;
2981 wsa
->write
.iovec
[0].iov_base
= wsa
->buffer
;
2982 wsa
->write
.iovec
[0].iov_len
= iosb
.Information
;
2983 wsa
->file_read
+= iosb
.Information
;
2986 if (wsa
->file_bytes
!= 0 && wsa
->file_read
>= wsa
->file_bytes
)
2989 return STATUS_PENDING
;
2993 /* send the footer (if applicable) */
2994 if (wsa
->buffers
.Tail
)
2996 wsa
->write
.first_iovec
= 0;
2997 wsa
->write
.n_iovecs
= 1;
2998 wsa
->write
.iovec
[0].iov_base
= wsa
->buffers
.Tail
;
2999 wsa
->write
.iovec
[0].iov_len
= wsa
->buffers
.TailLength
;
3000 wsa
->buffers
.Tail
= NULL
;
3001 return STATUS_PENDING
;
3004 return STATUS_SUCCESS
;
3007 /***********************************************************************
3008 * WS2_transmitfile_base (INTERNAL)
3010 * Shared implementation for both synchronous and asynchronous TransmitFile.
3012 static NTSTATUS
WS2_transmitfile_base( int fd
, struct ws2_transmitfile_async
*wsa
)
3016 status
= WS2_transmitfile_getbuffer( fd
, wsa
);
3017 if (status
== STATUS_PENDING
)
3019 IO_STATUS_BLOCK
*iosb
= (IO_STATUS_BLOCK
*)wsa
->write
.user_overlapped
;
3022 n
= WS2_send( fd
, &wsa
->write
, convert_flags(wsa
->write
.flags
) );
3025 if (iosb
) iosb
->Information
+= n
;
3027 else if (errno
!= EAGAIN
)
3028 return wsaErrStatus();
3034 /***********************************************************************
3035 * WS2_async_transmitfile (INTERNAL)
3037 * Asynchronous callback for overlapped TransmitFile operations.
3039 static NTSTATUS
WS2_async_transmitfile( void *user
, IO_STATUS_BLOCK
*iosb
,
3040 NTSTATUS status
, void **apc
, void **arg
)
3042 struct ws2_transmitfile_async
*wsa
= user
;
3045 if (status
== STATUS_ALERTED
)
3047 if (!(status
= wine_server_handle_to_fd( wsa
->write
.hSocket
, FILE_WRITE_DATA
, &fd
, NULL
)))
3049 status
= WS2_transmitfile_base( fd
, wsa
);
3050 wine_server_release_fd( wsa
->write
.hSocket
, fd
);
3052 if (status
== STATUS_PENDING
)
3056 iosb
->u
.Status
= status
;
3057 release_async_io( &wsa
->io
);
3061 /***********************************************************************
3064 static BOOL WINAPI
WS2_TransmitFile( SOCKET s
, HANDLE h
, DWORD file_bytes
, DWORD bytes_per_send
,
3065 LPOVERLAPPED overlapped
, LPTRANSMIT_FILE_BUFFERS buffers
,
3068 union generic_unix_sockaddr uaddr
;
3069 unsigned int uaddrlen
= sizeof(uaddr
);
3070 struct ws2_transmitfile_async
*wsa
;
3074 TRACE("(%lx, %p, %d, %d, %p, %p, %d)\n", s
, h
, file_bytes
, bytes_per_send
, overlapped
,
3077 fd
= get_sock_fd( s
, FILE_WRITE_DATA
, NULL
);
3080 WSASetLastError( WSAENOTSOCK
);
3083 if (getpeername( fd
, &uaddr
.addr
, &uaddrlen
) != 0)
3085 release_sock_fd( s
, fd
);
3086 WSASetLastError( WSAENOTCONN
);
3090 FIXME("Flags are not currently supported (0x%x).\n", flags
);
3092 if (h
&& GetFileType( h
) != FILE_TYPE_DISK
)
3094 FIXME("Non-disk file handles are not currently supported.\n");
3095 release_sock_fd( s
, fd
);
3096 WSASetLastError( WSAEOPNOTSUPP
);
3100 /* set reasonable defaults when requested */
3101 if (!bytes_per_send
)
3102 bytes_per_send
= (1 << 16); /* Depends on OS version: PAGE_SIZE, 2*PAGE_SIZE, or 2^16 */
3104 if (!(wsa
= (struct ws2_transmitfile_async
*)alloc_async_io( sizeof(*wsa
) + bytes_per_send
)))
3106 release_sock_fd( s
, fd
);
3107 WSASetLastError( WSAEFAULT
);
3111 wsa
->buffers
= *buffers
;
3113 memset(&wsa
->buffers
, 0x0, sizeof(wsa
->buffers
));
3114 wsa
->buffer
= (char *)(wsa
+ 1);
3117 wsa
->file_bytes
= file_bytes
;
3118 wsa
->bytes_per_send
= bytes_per_send
;
3120 wsa
->offset
.QuadPart
= FILE_USE_FILE_POINTER_POSITION
;
3121 wsa
->write
.hSocket
= SOCKET2HANDLE(s
);
3122 wsa
->write
.addr
= NULL
;
3123 wsa
->write
.addrlen
.val
= 0;
3124 wsa
->write
.flags
= 0;
3125 wsa
->write
.lpFlags
= &wsa
->flags
;
3126 wsa
->write
.control
= NULL
;
3127 wsa
->write
.n_iovecs
= 0;
3128 wsa
->write
.first_iovec
= 0;
3129 wsa
->write
.user_overlapped
= overlapped
;
3132 IO_STATUS_BLOCK
*iosb
= (IO_STATUS_BLOCK
*)overlapped
;
3135 wsa
->offset
.u
.LowPart
= overlapped
->u
.s
.Offset
;
3136 wsa
->offset
.u
.HighPart
= overlapped
->u
.s
.OffsetHigh
;
3137 iosb
->u
.Status
= STATUS_PENDING
;
3138 iosb
->Information
= 0;
3139 status
= register_async( ASYNC_TYPE_WRITE
, SOCKET2HANDLE(s
), WS2_async_transmitfile
, wsa
,
3140 overlapped
->hEvent
, NULL
, NULL
, iosb
);
3141 if(status
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
3142 release_sock_fd( s
, fd
);
3143 WSASetLastError( NtStatusToWSAError(status
) );
3149 status
= WS2_transmitfile_base( fd
, wsa
);
3150 if (status
== STATUS_PENDING
)
3153 do_block(fd
, POLLOUT
, -1);
3154 _sync_sock_state(s
); /* let wineserver notice connection */
3157 while (status
== STATUS_PENDING
);
3158 release_sock_fd( s
, fd
);
3160 if (status
!= STATUS_SUCCESS
)
3161 WSASetLastError( NtStatusToWSAError(status
) );
3162 HeapFree( GetProcessHeap(), 0, wsa
);
3163 return (status
== STATUS_SUCCESS
);
3166 /***********************************************************************
3167 * GetAcceptExSockaddrs
3169 static void WINAPI
WS2_GetAcceptExSockaddrs(PVOID buffer
, DWORD data_size
, DWORD local_size
, DWORD remote_size
,
3170 struct WS_sockaddr
**local_addr
, LPINT local_addr_len
,
3171 struct WS_sockaddr
**remote_addr
, LPINT remote_addr_len
)
3173 char *cbuf
= buffer
;
3174 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer
, data_size
, local_size
, remote_size
, local_addr
,
3175 local_addr_len
, remote_addr
, remote_addr_len
);
3178 *local_addr_len
= *(int *) cbuf
;
3179 *local_addr
= (struct WS_sockaddr
*)(cbuf
+ sizeof(int));
3183 *remote_addr_len
= *(int *) cbuf
;
3184 *remote_addr
= (struct WS_sockaddr
*)(cbuf
+ sizeof(int));
3187 /***********************************************************************
3190 int WINAPI
WSASendMsg( SOCKET s
, LPWSAMSG msg
, DWORD dwFlags
, LPDWORD lpNumberOfBytesSent
,
3191 LPWSAOVERLAPPED lpOverlapped
,
3192 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
3196 SetLastError( WSAEFAULT
);
3197 return SOCKET_ERROR
;
3200 return WS2_sendto( s
, msg
->lpBuffers
, msg
->dwBufferCount
, lpNumberOfBytesSent
,
3201 dwFlags
, msg
->name
, msg
->namelen
,
3202 lpOverlapped
, lpCompletionRoutine
);
3205 /***********************************************************************
3208 * Perform a receive operation that is capable of returning message
3209 * control headers. It is important to note that the WSAMSG parameter
3210 * must remain valid throughout the operation, even when an overlapped
3211 * receive is performed.
3213 static int WINAPI
WS2_WSARecvMsg( SOCKET s
, LPWSAMSG msg
, LPDWORD lpNumberOfBytesRecvd
,
3214 LPWSAOVERLAPPED lpOverlapped
,
3215 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
3219 SetLastError( WSAEFAULT
);
3220 return SOCKET_ERROR
;
3223 return WS2_recv_base( s
, msg
->lpBuffers
, msg
->dwBufferCount
, lpNumberOfBytesRecvd
,
3224 &msg
->dwFlags
, msg
->name
, &msg
->namelen
,
3225 lpOverlapped
, lpCompletionRoutine
, &msg
->Control
);
3228 /***********************************************************************
3229 * interface_bind (INTERNAL)
3231 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
3232 * operating only on the specified interface. This restriction consists of two components:
3233 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
3234 * 2) An incoming packet restriction dropping packets not meant for the interface.
3235 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
3236 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
3237 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
3238 * to receive broadcast packets on a socket that is bound to a specific network interface.
3240 static BOOL
interface_bind( SOCKET s
, int fd
, struct sockaddr
*addr
)
3242 struct sockaddr_in
*in_sock
= (struct sockaddr_in
*) addr
;
3243 in_addr_t bind_addr
= in_sock
->sin_addr
.s_addr
;
3244 PIP_ADAPTER_INFO adapters
= NULL
, adapter
;
3249 if (bind_addr
== htonl(INADDR_ANY
) || bind_addr
== htonl(INADDR_LOOPBACK
))
3250 return FALSE
; /* Not binding to a network adapter, special interface binding unnecessary. */
3251 if (_get_fd_type(fd
) != SOCK_DGRAM
)
3252 return FALSE
; /* Special interface binding is only necessary for UDP datagrams. */
3253 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
3255 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
3256 if (adapters
== NULL
|| GetAdaptersInfo(adapters
, &adap_size
) != NO_ERROR
)
3258 /* Search the IPv4 adapter list for the appropriate binding interface */
3259 for (adapter
= adapters
; adapter
!= NULL
; adapter
= adapter
->Next
)
3261 in_addr_t adapter_addr
= (in_addr_t
) inet_addr(adapter
->IpAddressList
.IpAddress
.String
);
3263 if (bind_addr
== adapter_addr
)
3265 #if defined(IP_BOUND_IF)
3266 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
3267 if (setsockopt(fd
, IPPROTO_IP
, IP_BOUND_IF
, &adapter
->Index
, sizeof(adapter
->Index
)) != 0)
3270 #elif defined(LINUX_BOUND_IF)
3271 in_addr_t ifindex
= (in_addr_t
) htonl(adapter
->Index
);
3272 struct interface_filter specific_interface_filter
;
3273 struct sock_fprog filter_prog
;
3275 if (setsockopt(fd
, IPPROTO_IP
, IP_UNICAST_IF
, &ifindex
, sizeof(ifindex
)) != 0)
3276 goto cleanup
; /* Failed to suggest egress interface */
3277 specific_interface_filter
= generic_interface_filter
;
3278 specific_interface_filter
.iface_rule
.k
= adapter
->Index
;
3279 specific_interface_filter
.ip_rule
.k
= htonl(adapter_addr
);
3280 filter_prog
.len
= sizeof(generic_interface_filter
)/sizeof(struct sock_filter
);
3281 filter_prog
.filter
= (struct sock_filter
*) &specific_interface_filter
;
3282 if (setsockopt(fd
, SOL_SOCKET
, SO_ATTACH_FILTER
, &filter_prog
, sizeof(filter_prog
)) != 0)
3283 goto cleanup
; /* Failed to specify incoming packet filter */
3286 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
3287 "receiving broadcast packets will not work on socket %04lx.\n", s
);
3292 /* Will soon be switching to INADDR_ANY: permit address reuse */
3293 if (ret
&& setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &enable
, sizeof(enable
)) == 0)
3294 TRACE("Socket %04lx bound to interface index %d\n", s
, adapter
->Index
);
3300 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s
);
3301 HeapFree(GetProcessHeap(), 0, adapters
);
3305 /***********************************************************************
3308 int WINAPI
WS_bind(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
)
3310 int fd
= get_sock_fd( s
, 0, NULL
);
3311 int res
= SOCKET_ERROR
;
3313 TRACE("socket %04lx, ptr %p %s, length %d\n", s
, name
, debugstr_sockaddr(name
), namelen
);
3317 if (!name
|| (name
->sa_family
&& !supported_pf(name
->sa_family
)))
3319 SetLastError(WSAEAFNOSUPPORT
);
3323 union generic_unix_sockaddr uaddr
;
3324 unsigned int uaddrlen
= ws_sockaddr_ws2u(name
, namelen
, &uaddr
);
3327 SetLastError(WSAEFAULT
);
3331 if (name
->sa_family
== WS_AF_INET
)
3333 struct sockaddr_in
*in4
= (struct sockaddr_in
*) &uaddr
;
3334 if (memcmp(&in4
->sin_addr
, magic_loopback_addr
, 4) == 0)
3336 /* Trying to bind to the default host interface, using
3337 * INADDR_ANY instead*/
3338 WARN("Trying to bind to magic IP address, using "
3339 "INADDR_ANY instead.\n");
3340 in4
->sin_addr
.s_addr
= htonl(INADDR_ANY
);
3342 else if (interface_bind(s
, fd
, &uaddr
.addr
))
3343 in4
->sin_addr
.s_addr
= htonl(INADDR_ANY
);
3345 if (bind(fd
, &uaddr
.addr
, uaddrlen
) < 0)
3347 int loc_errno
= errno
;
3348 WARN("\tfailure - errno = %i\n", errno
);
3353 SetLastError(WSAEINVAL
);
3358 socklen_t optlen
= sizeof(optval
);
3359 /* Windows >= 2003 will return different results depending on
3360 * SO_REUSEADDR, WSAEACCES may be returned representing that
3361 * the socket hijacking protection prevented the bind */
3362 if (!getsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&optval
, &optlen
) && optval
)
3364 SetLastError(WSAEACCES
);
3370 SetLastError(wsaErrno());
3376 res
=0; /* success */
3380 release_sock_fd( s
, fd
);
3385 /***********************************************************************
3386 * closesocket (WS2_32.3)
3388 int WINAPI
WS_closesocket(SOCKET s
)
3390 int res
= SOCKET_ERROR
, fd
;
3393 fd
= get_sock_fd(s
, FILE_READ_DATA
, NULL
);
3396 release_sock_fd(s
, fd
);
3397 if (CloseHandle(SOCKET2HANDLE(s
)))
3401 SetLastError(WSAENOTSOCK
);
3404 SetLastError(WSANOTINITIALISED
);
3405 TRACE("(socket %04lx) -> %d\n", s
, res
);
3409 static int do_connect(int fd
, const struct WS_sockaddr
* name
, int namelen
)
3411 union generic_unix_sockaddr uaddr
;
3412 unsigned int uaddrlen
= ws_sockaddr_ws2u(name
, namelen
, &uaddr
);
3417 if (name
->sa_family
== WS_AF_INET
)
3419 struct sockaddr_in
*in4
= (struct sockaddr_in
*) &uaddr
;
3420 if (memcmp(&in4
->sin_addr
, magic_loopback_addr
, 4) == 0)
3422 /* Trying to connect to magic replace-loopback address,
3423 * assuming we really want to connect to localhost */
3424 TRACE("Trying to connect to magic IP address, using "
3425 "INADDR_LOOPBACK instead.\n");
3426 in4
->sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
3430 if (connect(fd
, &uaddr
.addr
, uaddrlen
) == 0)
3436 /***********************************************************************
3437 * connect (WS2_32.4)
3439 int WINAPI
WS_connect(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
)
3441 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
3443 TRACE("socket %04lx, ptr %p %s, length %d\n", s
, name
, debugstr_sockaddr(name
), namelen
);
3449 int ret
= do_connect(fd
, name
, namelen
);
3451 goto connect_success
;
3453 if (ret
== WSAEINPROGRESS
)
3455 /* tell wineserver that a connection is in progress */
3456 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3458 FD_WINE_CONNECTED
|FD_WINE_LISTENING
);
3459 status
= _is_blocking( s
, &is_blocking
);
3462 release_sock_fd( s
, fd
);
3463 set_error( status
);
3464 return SOCKET_ERROR
;
3470 do_block(fd
, POLLIN
| POLLOUT
, -1);
3471 _sync_sock_state(s
); /* let wineserver notice connection */
3472 /* retrieve any error codes from it */
3473 result
= _get_sock_error(s
, FD_CONNECT_BIT
);
3475 SetLastError(NtStatusToWSAError(result
));
3478 goto connect_success
;
3483 SetLastError(WSAEWOULDBLOCK
);
3490 release_sock_fd( s
, fd
);
3492 return SOCKET_ERROR
;
3495 release_sock_fd( s
, fd
);
3496 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3497 FD_WINE_CONNECTED
|FD_READ
|FD_WRITE
,
3498 FD_CONNECT
|FD_WINE_LISTENING
);
3499 TRACE("\tconnected %04lx\n", s
);
3503 /***********************************************************************
3504 * WSAConnect (WS2_32.30)
3506 int WINAPI
WSAConnect( SOCKET s
, const struct WS_sockaddr
* name
, int namelen
,
3507 LPWSABUF lpCallerData
, LPWSABUF lpCalleeData
,
3508 LPQOS lpSQOS
, LPQOS lpGQOS
)
3510 if ( lpCallerData
|| lpCalleeData
|| lpSQOS
|| lpGQOS
)
3511 FIXME("unsupported parameters!\n");
3512 return WS_connect( s
, name
, namelen
);
3515 /***********************************************************************
3518 static BOOL WINAPI
WS2_ConnectEx(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
,
3519 PVOID sendBuf
, DWORD sendBufLen
, LPDWORD sent
, LPOVERLAPPED ov
)
3521 int fd
, ret
, status
;
3525 SetLastError( ERROR_INVALID_PARAMETER
);
3529 fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
3532 SetLastError( WSAENOTSOCK
);
3536 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
3537 s
, name
, debugstr_sockaddr(name
), namelen
, sendBuf
, sendBufLen
, ov
);
3539 ret
= is_fd_bound(fd
, NULL
, NULL
);
3542 SetLastError(ret
== -1 ? wsaErrno() : WSAEINVAL
);
3543 release_sock_fd( s
, fd
);
3547 ret
= do_connect(fd
, name
, namelen
);
3552 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3553 FD_WINE_CONNECTED
|FD_READ
|FD_WRITE
,
3554 FD_CONNECT
|FD_WINE_LISTENING
);
3556 wsabuf
.len
= sendBufLen
;
3557 wsabuf
.buf
= (char*) sendBuf
;
3559 /* WSASend takes care of completion if need be */
3560 if (WSASend(s
, &wsabuf
, sendBuf
? 1 : 0, sent
, 0, ov
, NULL
) != SOCKET_ERROR
)
3561 goto connection_success
;
3563 else if (ret
== WSAEINPROGRESS
)
3565 struct ws2_async
*wsa
;
3566 ULONG_PTR cvalue
= (((ULONG_PTR
)ov
->hEvent
& 1) == 0) ? (ULONG_PTR
)ov
: 0;
3568 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3570 FD_WINE_CONNECTED
|FD_WINE_LISTENING
);
3572 /* Indirectly call WSASend */
3573 if (!(wsa
= (struct ws2_async
*)alloc_async_io( offsetof( struct ws2_async
, iovec
[1] ))))
3575 SetLastError(WSAEFAULT
);
3579 IO_STATUS_BLOCK
*iosb
= (IO_STATUS_BLOCK
*)ov
;
3580 iosb
->u
.Status
= STATUS_PENDING
;
3581 iosb
->Information
= 0;
3583 wsa
->hSocket
= SOCKET2HANDLE(s
);
3585 wsa
->addrlen
.val
= 0;
3587 wsa
->lpFlags
= &wsa
->flags
;
3588 wsa
->control
= NULL
;
3589 wsa
->n_iovecs
= sendBuf
? 1 : 0;
3590 wsa
->first_iovec
= 0;
3591 wsa
->completion_func
= NULL
;
3592 wsa
->iovec
[0].iov_base
= sendBuf
;
3593 wsa
->iovec
[0].iov_len
= sendBufLen
;
3595 status
= register_async( ASYNC_TYPE_WRITE
, wsa
->hSocket
, WS2_async_send
, wsa
, ov
->hEvent
,
3596 NULL
, (void *)cvalue
, iosb
);
3597 if (status
!= STATUS_PENDING
) HeapFree(GetProcessHeap(), 0, wsa
);
3599 /* If the connect already failed */
3600 if (status
== STATUS_PIPE_DISCONNECTED
)
3601 status
= _get_sock_error(s
, FD_CONNECT_BIT
);
3602 SetLastError( NtStatusToWSAError(status
) );
3610 release_sock_fd( s
, fd
);
3614 release_sock_fd( s
, fd
);
3618 /***********************************************************************
3621 static BOOL WINAPI
WS2_DisconnectEx( SOCKET s
, LPOVERLAPPED ov
, DWORD flags
, DWORD reserved
)
3623 TRACE( "socket %04lx, ov %p, flags 0x%x, reserved 0x%x\n", s
, ov
, flags
, reserved
);
3625 if (flags
& TF_REUSE_SOCKET
)
3626 FIXME( "Reusing socket not supported yet\n" );
3630 ov
->Internal
= STATUS_PENDING
;
3631 ov
->InternalHigh
= 0;
3634 return !WS_shutdown( s
, SD_BOTH
);
3637 /***********************************************************************
3638 * getpeername (WS2_32.5)
3640 int WINAPI
WS_getpeername(SOCKET s
, struct WS_sockaddr
*name
, int *namelen
)
3645 TRACE("socket %04lx, ptr %p, len %08x\n", s
, name
, namelen
? *namelen
: 0);
3647 fd
= get_sock_fd( s
, 0, NULL
);
3652 union generic_unix_sockaddr uaddr
;
3653 socklen_t uaddrlen
= sizeof(uaddr
);
3655 if (getpeername(fd
, &uaddr
.addr
, &uaddrlen
) == 0)
3657 if (!name
|| !namelen
)
3658 SetLastError(WSAEFAULT
);
3659 else if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
3660 /* The buffer was too small */
3661 SetLastError(WSAEFAULT
);
3665 TRACE("=> %s\n", debugstr_sockaddr(name
));
3669 SetLastError(wsaErrno());
3670 release_sock_fd( s
, fd
);
3675 /* When binding to an UDP address with filter support the getsockname call on the socket
3676 * will always return 0.0.0.0 instead of the filtered interface address. This function
3677 * checks if the socket is interface-bound on UDP and return the correct address.
3678 * This is required because applications often do a bind() with port zero followed by a
3679 * getsockname() to retrieve the port and address acquired.
3681 static void interface_bind_check(int fd
, struct sockaddr_in
*addr
)
3683 #if !defined(IP_BOUND_IF) && !defined(LINUX_BOUND_IF)
3689 /* Check for IPv4, address 0.0.0.0 and UDP socket */
3690 if (addr
->sin_family
!= AF_INET
|| addr
->sin_addr
.s_addr
!= 0)
3692 if (_get_fd_type(fd
) != SOCK_DGRAM
)
3696 len
= sizeof(ifindex
);
3697 #if defined(IP_BOUND_IF)
3698 getsockopt(fd
, IPPROTO_IP
, IP_BOUND_IF
, &ifindex
, &len
);
3699 #elif defined(LINUX_BOUND_IF)
3700 getsockopt(fd
, IPPROTO_IP
, IP_UNICAST_IF
, &ifindex
, &len
);
3701 if (ifindex
> 0) ifindex
= ntohl(ifindex
);
3705 PIP_ADAPTER_INFO adapters
, adapter
;
3708 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
3710 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
3711 if (adapters
&& GetAdaptersInfo(adapters
, &adap_size
) == NO_ERROR
)
3713 /* Search the IPv4 adapter list for the appropriate bound interface */
3714 for (adapter
= adapters
; adapter
!= NULL
; adapter
= adapter
->Next
)
3716 in_addr_t adapter_addr
;
3717 if (adapter
->Index
!= ifindex
) continue;
3719 adapter_addr
= inet_addr(adapter
->IpAddressList
.IpAddress
.String
);
3720 addr
->sin_addr
.s_addr
= adapter_addr
;
3721 TRACE("reporting interface address from adapter %d\n", ifindex
);
3725 HeapFree(GetProcessHeap(), 0, adapters
);
3730 /***********************************************************************
3731 * getsockname (WS2_32.6)
3733 int WINAPI
WS_getsockname(SOCKET s
, struct WS_sockaddr
*name
, int *namelen
)
3738 TRACE("socket %04lx, ptr %p, len %08x\n", s
, name
, namelen
? *namelen
: 0);
3740 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3741 if( (name
== NULL
) || (namelen
== NULL
) )
3743 SetLastError( WSAEFAULT
);
3744 return SOCKET_ERROR
;
3747 fd
= get_sock_fd( s
, 0, NULL
);
3752 union generic_unix_sockaddr uaddr
;
3754 int bound
= is_fd_bound(fd
, &uaddr
, &uaddrlen
);
3758 SetLastError(bound
== -1 ? wsaErrno() : WSAEINVAL
);
3760 else if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
3762 /* The buffer was too small */
3763 SetLastError(WSAEFAULT
);
3767 interface_bind_check(fd
, (struct sockaddr_in
*) &uaddr
);
3768 if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
3770 /* The buffer was too small */
3771 SetLastError(WSAEFAULT
);
3776 TRACE("=> %s\n", debugstr_sockaddr(name
));
3779 release_sock_fd( s
, fd
);
3784 /***********************************************************************
3785 * getsockopt (WS2_32.7)
3787 INT WINAPI
WS_getsockopt(SOCKET s
, INT level
,
3788 INT optname
, char *optval
, INT
*optlen
)
3793 TRACE("(socket %04lx, %s, optval %s, optlen %p (%d))\n", s
,
3794 debugstr_sockopt(level
, optname
), debugstr_optval(optval
, 0),
3795 optlen
, optlen
? *optlen
: 0);
3803 /* Handle common cases. The special cases are below, sorted
3805 case WS_SO_BROADCAST
:
3807 case WS_SO_KEEPALIVE
:
3808 case WS_SO_OOBINLINE
:
3810 case WS_SO_REUSEADDR
:
3812 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3813 return SOCKET_ERROR
;
3814 convert_sockopt(&level
, &optname
);
3815 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3817 SetLastError(wsaErrno());
3820 release_sock_fd( s
, fd
);
3822 case WS_SO_ACCEPTCONN
:
3823 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3824 return SOCKET_ERROR
;
3825 if (getsockopt(fd
, SOL_SOCKET
, SO_ACCEPTCONN
, optval
, (socklen_t
*)optlen
) != 0 )
3827 SetLastError(wsaErrno());
3832 /* BSD returns != 0 while Windows return exact == 1 */
3833 if (*(int *)optval
) *(int *)optval
= 1;
3835 release_sock_fd( s
, fd
);
3837 case WS_SO_BSP_STATE
:
3839 int req_size
, addr_size
;
3840 WSAPROTOCOL_INFOW infow
;
3841 CSADDR_INFO
*csinfo
;
3843 ret
= ws_protocol_info(s
, TRUE
, &infow
, &addr_size
);
3846 if (infow
.iAddressFamily
== WS_AF_INET
)
3847 addr_size
= sizeof(struct sockaddr_in
);
3848 else if (infow
.iAddressFamily
== WS_AF_INET6
)
3849 addr_size
= sizeof(struct sockaddr_in6
);
3852 FIXME("Family %d is unsupported for SO_BSP_STATE\n", infow
.iAddressFamily
);
3853 SetLastError(WSAEAFNOSUPPORT
);
3854 return SOCKET_ERROR
;
3857 req_size
= sizeof(CSADDR_INFO
) + addr_size
* 2;
3858 if (*optlen
< req_size
)
3861 SetLastError(WSAEFAULT
);
3865 union generic_unix_sockaddr uaddr
;
3868 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3869 return SOCKET_ERROR
;
3871 csinfo
= (CSADDR_INFO
*) optval
;
3873 /* Check if the sock is bound */
3874 if (is_fd_bound(fd
, &uaddr
, &uaddrlen
) == 1)
3876 csinfo
->LocalAddr
.lpSockaddr
=
3877 (LPSOCKADDR
) (optval
+ sizeof(CSADDR_INFO
));
3878 ws_sockaddr_u2ws(&uaddr
.addr
, csinfo
->LocalAddr
.lpSockaddr
, &addr_size
);
3879 csinfo
->LocalAddr
.iSockaddrLength
= addr_size
;
3883 csinfo
->LocalAddr
.lpSockaddr
= NULL
;
3884 csinfo
->LocalAddr
.iSockaddrLength
= 0;
3887 /* Check if the sock is connected */
3888 if (!getpeername(fd
, &uaddr
.addr
, &uaddrlen
) &&
3889 is_sockaddr_bound(&uaddr
.addr
, uaddrlen
))
3891 csinfo
->RemoteAddr
.lpSockaddr
=
3892 (LPSOCKADDR
) (optval
+ sizeof(CSADDR_INFO
) + addr_size
);
3893 ws_sockaddr_u2ws(&uaddr
.addr
, csinfo
->RemoteAddr
.lpSockaddr
, &addr_size
);
3894 csinfo
->RemoteAddr
.iSockaddrLength
= addr_size
;
3898 csinfo
->RemoteAddr
.lpSockaddr
= NULL
;
3899 csinfo
->RemoteAddr
.iSockaddrLength
= 0;
3902 csinfo
->iSocketType
= infow
.iSocketType
;
3903 csinfo
->iProtocol
= infow
.iProtocol
;
3904 release_sock_fd( s
, fd
);
3907 return ret
? 0 : SOCKET_ERROR
;
3909 case WS_SO_DONTLINGER
:
3911 struct linger lingval
;
3912 socklen_t len
= sizeof(struct linger
);
3914 if (!optlen
|| *optlen
< sizeof(BOOL
)|| !optval
)
3916 SetLastError(WSAEFAULT
);
3917 return SOCKET_ERROR
;
3919 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3920 return SOCKET_ERROR
;
3922 if (getsockopt(fd
, SOL_SOCKET
, SO_LINGER
, &lingval
, &len
) != 0 )
3924 SetLastError(wsaErrno());
3929 *(BOOL
*)optval
= !lingval
.l_onoff
;
3930 *optlen
= sizeof(BOOL
);
3933 release_sock_fd( s
, fd
);
3937 case WS_SO_CONNECT_TIME
:
3939 static int pretendtime
= 0;
3940 struct WS_sockaddr addr
;
3941 int len
= sizeof(addr
);
3943 if (!optlen
|| *optlen
< sizeof(DWORD
) || !optval
)
3945 SetLastError(WSAEFAULT
);
3946 return SOCKET_ERROR
;
3948 if (WS_getpeername(s
, &addr
, &len
) == SOCKET_ERROR
)
3949 *(DWORD
*)optval
= ~0u;
3952 if (!pretendtime
) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3953 *(DWORD
*)optval
= pretendtime
++;
3955 *optlen
= sizeof(DWORD
);
3958 /* As mentioned in setsockopt, Windows ignores this, so we
3959 * always return true here */
3960 case WS_SO_DONTROUTE
:
3961 if (!optlen
|| *optlen
< sizeof(BOOL
) || !optval
)
3963 SetLastError(WSAEFAULT
);
3964 return SOCKET_ERROR
;
3966 *(BOOL
*)optval
= TRUE
;
3967 *optlen
= sizeof(BOOL
);
3972 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3973 return SOCKET_ERROR
;
3974 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, optval
, (socklen_t
*)optlen
) != 0 )
3976 SetLastError(wsaErrno());
3979 release_sock_fd( s
, fd
);
3981 /* The wineserver may have swallowed the error before us */
3982 if (!ret
&& *(int*) optval
== 0)
3984 int i
, events
[FD_MAX_EVENTS
];
3985 _get_sock_errors(s
, events
);
3986 for (i
= 0; i
< FD_MAX_EVENTS
; i
++)
3990 events
[i
] = NtStatusToWSAError(events
[i
]);
3991 TRACE("returning SO_ERROR %d from wine server\n", events
[i
]);
3992 *(int*) optval
= events
[i
];
4002 struct linger lingval
;
4003 socklen_t len
= sizeof(struct linger
);
4005 /* struct linger and LINGER have different sizes */
4006 if (!optlen
|| *optlen
< sizeof(LINGER
) || !optval
)
4008 SetLastError(WSAEFAULT
);
4009 return SOCKET_ERROR
;
4011 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4012 return SOCKET_ERROR
;
4014 if (_get_fd_type(fd
) == SOCK_DGRAM
)
4016 SetLastError(WSAENOPROTOOPT
);
4019 else if (getsockopt(fd
, SOL_SOCKET
, SO_LINGER
, &lingval
, &len
) != 0)
4021 SetLastError(wsaErrno());
4026 ((LINGER
*)optval
)->l_onoff
= lingval
.l_onoff
;
4027 ((LINGER
*)optval
)->l_linger
= lingval
.l_linger
;
4028 *optlen
= sizeof(struct linger
);
4031 release_sock_fd( s
, fd
);
4035 case WS_SO_MAX_MSG_SIZE
:
4036 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
4038 SetLastError(WSAEFAULT
);
4039 return SOCKET_ERROR
;
4041 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
4042 *(int *)optval
= 65507;
4043 *optlen
= sizeof(int);
4046 /* SO_OPENTYPE does not require a valid socket handle. */
4047 case WS_SO_OPENTYPE
:
4048 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
4050 SetLastError(WSAEFAULT
);
4051 return SOCKET_ERROR
;
4053 *(int *)optval
= get_per_thread_data()->opentype
;
4054 *optlen
= sizeof(int);
4055 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval
) );
4057 case WS_SO_PROTOCOL_INFOA
:
4058 case WS_SO_PROTOCOL_INFOW
:
4061 WSAPROTOCOL_INFOW infow
;
4063 ret
= ws_protocol_info(s
, optname
== WS_SO_PROTOCOL_INFOW
, &infow
, &size
);
4066 if (!optlen
|| !optval
|| *optlen
< size
)
4068 if(optlen
) *optlen
= size
;
4070 SetLastError(WSAEFAULT
);
4073 memcpy(optval
, &infow
, size
);
4075 return ret
? 0 : SOCKET_ERROR
;
4077 case WS_SO_RCVTIMEO
:
4078 case WS_SO_SNDTIMEO
:
4082 if (!optlen
|| *optlen
< sizeof(int)|| !optval
)
4084 SetLastError(WSAEFAULT
);
4085 return SOCKET_ERROR
;
4087 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4088 return SOCKET_ERROR
;
4090 timeout
= get_rcvsnd_timeo(fd
, optname
== WS_SO_RCVTIMEO
);
4091 *(int *)optval
= timeout
<= UINT_MAX
? timeout
: UINT_MAX
;
4093 release_sock_fd( s
, fd
);
4099 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
4101 SetLastError(WSAEFAULT
);
4102 return SOCKET_ERROR
;
4104 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4105 return SOCKET_ERROR
;
4107 sock_type
= _get_fd_type(fd
);
4108 if (sock_type
== -1)
4110 SetLastError(wsaErrno());
4114 (*(int *)optval
) = convert_socktype_u2w(sock_type
);
4116 release_sock_fd( s
, fd
);
4120 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname
);
4121 SetLastError(WSAENOPROTOOPT
);
4122 return SOCKET_ERROR
;
4123 } /* end switch(optname) */
4124 }/* end case WS_SOL_SOCKET */
4126 case WS_NSPROTO_IPX
:
4128 struct WS_sockaddr_ipx addr
;
4129 IPX_ADDRESS_DATA
*data
;
4134 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
4136 if(getsockopt(fd
, SOL_IPX
, IPX_TYPE
, optval
, (socklen_t
*)optlen
) == -1)
4143 socklen_t len
=sizeof(struct ipx
);
4144 if(getsockopt(fd
, 0, SO_DEFAULT_HEADERS
, &val
, &len
) == -1 )
4147 *optval
= (int)val
.ipx_pt
;
4150 TRACE("ptype: %d (fd: %d)\n", *(int*)optval
, fd
);
4151 release_sock_fd( s
, fd
);
4154 case WS_IPX_ADDRESS
:
4156 * On a Win2000 system with one network card there are usually
4157 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
4158 * Using this call you can then retrieve info about this all.
4159 * In case of Linux it is a bit different. Usually you have
4160 * only "one" device active and further it is not possible to
4161 * query things like the linkspeed.
4163 FIXME("IPX_ADDRESS\n");
4164 namelen
= sizeof(struct WS_sockaddr_ipx
);
4165 memset(&addr
, 0, sizeof(struct WS_sockaddr_ipx
));
4166 WS_getsockname(s
, (struct WS_sockaddr
*)&addr
, &namelen
);
4168 data
= (IPX_ADDRESS_DATA
*)optval
;
4169 memcpy(data
->nodenum
,addr
.sa_nodenum
,sizeof(data
->nodenum
));
4170 memcpy(data
->netnum
,addr
.sa_netnum
,sizeof(data
->netnum
));
4171 data
->adapternum
= 0;
4172 data
->wan
= FALSE
; /* We are not on a wan for now .. */
4173 data
->status
= FALSE
; /* Since we are not on a wan, the wan link isn't up */
4174 data
->maxpkt
= 1467; /* This value is the default one, at least on Win2k/WinXP */
4175 data
->linkspeed
= 100000; /* Set the line speed in 100bit/s to 10 Mbit;
4176 * note 1MB = 1000kB in this case */
4179 case WS_IPX_MAX_ADAPTER_NUM
:
4180 FIXME("IPX_MAX_ADAPTER_NUM\n");
4181 *(int*)optval
= 1; /* As noted under IPX_ADDRESS we have just one card. */
4185 FIXME("IPX optname:%x\n", optname
);
4186 return SOCKET_ERROR
;
4187 }/* end switch(optname) */
4188 } /* end case WS_NSPROTO_IPX */
4192 #define MAX_IRDA_DEVICES 10
4197 case WS_IRLMP_ENUMDEVICES
:
4199 char buf
[sizeof(struct irda_device_list
) +
4200 (MAX_IRDA_DEVICES
- 1) * sizeof(struct irda_device_info
)];
4202 socklen_t len
= sizeof(buf
);
4204 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4205 return SOCKET_ERROR
;
4206 res
= getsockopt( fd
, SOL_IRLMP
, IRLMP_ENUMDEVICES
, buf
, &len
);
4207 release_sock_fd( s
, fd
);
4210 SetLastError(wsaErrno());
4211 return SOCKET_ERROR
;
4215 struct irda_device_list
*src
= (struct irda_device_list
*)buf
;
4216 DEVICELIST
*dst
= (DEVICELIST
*)optval
;
4217 INT needed
= sizeof(DEVICELIST
);
4221 needed
+= (src
->len
- 1) * sizeof(IRDA_DEVICE_INFO
);
4222 if (*optlen
< needed
)
4224 SetLastError(WSAEFAULT
);
4225 return SOCKET_ERROR
;
4228 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src
->len
);
4229 dst
->numDevice
= src
->len
;
4230 for (i
= 0; i
< src
->len
; i
++)
4232 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
4233 src
->dev
[i
].saddr
, src
->dev
[i
].daddr
,
4234 src
->dev
[i
].info
, src
->dev
[i
].hints
[0],
4235 src
->dev
[i
].hints
[1]);
4236 memcpy( dst
->Device
[i
].irdaDeviceID
,
4238 sizeof(dst
->Device
[i
].irdaDeviceID
) ) ;
4239 memcpy( dst
->Device
[i
].irdaDeviceName
,
4241 sizeof(dst
->Device
[i
].irdaDeviceName
) ) ;
4242 memcpy( &dst
->Device
[i
].irdaDeviceHints1
,
4243 &src
->dev
[i
].hints
[0],
4244 sizeof(dst
->Device
[i
].irdaDeviceHints1
) ) ;
4245 memcpy( &dst
->Device
[i
].irdaDeviceHints2
,
4246 &src
->dev
[i
].hints
[1],
4247 sizeof(dst
->Device
[i
].irdaDeviceHints2
) ) ;
4248 dst
->Device
[i
].irdaCharSet
= src
->dev
[i
].charset
;
4254 FIXME("IrDA optname:0x%x\n", optname
);
4255 return SOCKET_ERROR
;
4257 break; /* case WS_SOL_IRLMP */
4258 #undef MAX_IRDA_DEVICES
4261 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4262 case WS_IPPROTO_TCP
:
4265 case WS_TCP_NODELAY
:
4266 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4267 return SOCKET_ERROR
;
4268 convert_sockopt(&level
, &optname
);
4269 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
4271 SetLastError(wsaErrno());
4274 release_sock_fd( s
, fd
);
4277 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname
);
4278 return SOCKET_ERROR
;
4283 case WS_IP_ADD_MEMBERSHIP
:
4284 case WS_IP_DROP_MEMBERSHIP
:
4288 case WS_IP_MULTICAST_IF
:
4289 case WS_IP_MULTICAST_LOOP
:
4290 case WS_IP_MULTICAST_TTL
:
4297 #ifdef IP_UNICAST_IF
4298 case WS_IP_UNICAST_IF
:
4300 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4301 return SOCKET_ERROR
;
4302 convert_sockopt(&level
, &optname
);
4303 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
4305 SetLastError(wsaErrno());
4308 release_sock_fd( s
, fd
);
4310 case WS_IP_DONTFRAGMENT
:
4311 return get_dont_fragment(s
, IPPROTO_IP
, (BOOL
*)optval
) ? 0 : SOCKET_ERROR
;
4313 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname
);
4314 return SOCKET_ERROR
;
4316 case WS_IPPROTO_IPV6
:
4319 #ifdef IPV6_ADD_MEMBERSHIP
4320 case WS_IPV6_ADD_MEMBERSHIP
:
4322 #ifdef IPV6_DROP_MEMBERSHIP
4323 case WS_IPV6_DROP_MEMBERSHIP
:
4325 case WS_IPV6_MULTICAST_IF
:
4326 case WS_IPV6_MULTICAST_HOPS
:
4327 case WS_IPV6_MULTICAST_LOOP
:
4328 case WS_IPV6_UNICAST_HOPS
:
4329 case WS_IPV6_V6ONLY
:
4330 #ifdef IPV6_UNICAST_IF
4331 case WS_IPV6_UNICAST_IF
:
4333 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4334 return SOCKET_ERROR
;
4335 convert_sockopt(&level
, &optname
);
4336 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
4338 SetLastError(wsaErrno());
4341 release_sock_fd( s
, fd
);
4343 case WS_IPV6_DONTFRAG
:
4344 return get_dont_fragment(s
, IPPROTO_IPV6
, (BOOL
*)optval
) ? 0 : SOCKET_ERROR
;
4346 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname
);
4347 return SOCKET_ERROR
;
4350 WARN("Unknown level: 0x%08x\n", level
);
4351 SetLastError(WSAEINVAL
);
4352 return SOCKET_ERROR
;
4353 } /* end switch(level) */
4356 /***********************************************************************
4359 WS_u_long WINAPI
WS_htonl(WS_u_long hostlong
)
4361 return htonl(hostlong
);
4365 /***********************************************************************
4368 WS_u_short WINAPI
WS_htons(WS_u_short hostshort
)
4370 return htons(hostshort
);
4373 /***********************************************************************
4374 * WSAHtonl (WS2_32.46)
4375 * From MSDN description of error codes, this function should also
4376 * check if WinSock has been initialized and the socket is a valid
4377 * socket. But why? This function only translates a host byte order
4378 * u_long into a network byte order u_long...
4380 int WINAPI
WSAHtonl(SOCKET s
, WS_u_long hostlong
, WS_u_long
*lpnetlong
)
4384 *lpnetlong
= htonl(hostlong
);
4387 SetLastError(WSAEFAULT
);
4388 return SOCKET_ERROR
;
4391 /***********************************************************************
4392 * WSAHtons (WS2_32.47)
4393 * From MSDN description of error codes, this function should also
4394 * check if WinSock has been initialized and the socket is a valid
4395 * socket. But why? This function only translates a host byte order
4396 * u_short into a network byte order u_short...
4398 int WINAPI
WSAHtons(SOCKET s
, WS_u_short hostshort
, WS_u_short
*lpnetshort
)
4403 *lpnetshort
= htons(hostshort
);
4406 SetLastError(WSAEFAULT
);
4407 return SOCKET_ERROR
;
4411 /***********************************************************************
4412 * inet_addr (WS2_32.11)
4414 WS_u_long WINAPI
WS_inet_addr(const char *cp
)
4416 if (!cp
) return INADDR_NONE
;
4417 return inet_addr(cp
);
4421 /***********************************************************************
4424 WS_u_long WINAPI
WS_ntohl(WS_u_long netlong
)
4426 return ntohl(netlong
);
4430 /***********************************************************************
4433 WS_u_short WINAPI
WS_ntohs(WS_u_short netshort
)
4435 return ntohs(netshort
);
4439 /***********************************************************************
4440 * inet_ntoa (WS2_32.12)
4442 char* WINAPI
WS_inet_ntoa(struct WS_in_addr in
)
4444 unsigned int long_ip
= ntohl(in
.WS_s_addr
);
4445 struct per_thread_data
*data
= get_per_thread_data();
4447 sprintf( data
->ntoa_buffer
, "%u.%u.%u.%u",
4448 (long_ip
>> 24) & 0xff,
4449 (long_ip
>> 16) & 0xff,
4450 (long_ip
>> 8) & 0xff,
4453 return data
->ntoa_buffer
;
4456 static const char *debugstr_wsaioctl(DWORD code
)
4458 const char *name
= NULL
, *buf_type
, *family
;
4460 #define IOCTL_NAME(x) case x: name = #x; break
4463 IOCTL_NAME(WS_FIONBIO
);
4464 IOCTL_NAME(WS_FIONREAD
);
4465 IOCTL_NAME(WS_SIOCATMARK
);
4466 /* IOCTL_NAME(WS_SIO_ACQUIRE_PORT_RESERVATION); */
4467 IOCTL_NAME(WS_SIO_ADDRESS_LIST_CHANGE
);
4468 IOCTL_NAME(WS_SIO_ADDRESS_LIST_QUERY
);
4469 IOCTL_NAME(WS_SIO_ASSOCIATE_HANDLE
);
4470 /* IOCTL_NAME(WS_SIO_ASSOCIATE_PORT_RESERVATION);
4471 IOCTL_NAME(WS_SIO_BASE_HANDLE);
4472 IOCTL_NAME(WS_SIO_BSP_HANDLE);
4473 IOCTL_NAME(WS_SIO_BSP_HANDLE_SELECT);
4474 IOCTL_NAME(WS_SIO_BSP_HANDLE_POLL);
4475 IOCTL_NAME(WS_SIO_CHK_QOS); */
4476 IOCTL_NAME(WS_SIO_ENABLE_CIRCULAR_QUEUEING
);
4477 IOCTL_NAME(WS_SIO_FIND_ROUTE
);
4478 IOCTL_NAME(WS_SIO_FLUSH
);
4479 IOCTL_NAME(WS_SIO_GET_BROADCAST_ADDRESS
);
4480 IOCTL_NAME(WS_SIO_GET_EXTENSION_FUNCTION_POINTER
);
4481 IOCTL_NAME(WS_SIO_GET_GROUP_QOS
);
4482 IOCTL_NAME(WS_SIO_GET_INTERFACE_LIST
);
4483 /* IOCTL_NAME(WS_SIO_GET_INTERFACE_LIST_EX); */
4484 IOCTL_NAME(WS_SIO_GET_QOS
);
4485 /* IOCTL_NAME(WS_SIO_IDEAL_SEND_BACKLOG_CHANGE);
4486 IOCTL_NAME(WS_SIO_IDEAL_SEND_BACKLOG_QUERY); */
4487 IOCTL_NAME(WS_SIO_KEEPALIVE_VALS
);
4488 IOCTL_NAME(WS_SIO_MULTIPOINT_LOOPBACK
);
4489 IOCTL_NAME(WS_SIO_MULTICAST_SCOPE
);
4490 /* IOCTL_NAME(WS_SIO_QUERY_RSS_SCALABILITY_INFO);
4491 IOCTL_NAME(WS_SIO_QUERY_WFP_ALE_ENDPOINT_HANDLE); */
4492 IOCTL_NAME(WS_SIO_RCVALL
);
4493 IOCTL_NAME(WS_SIO_RCVALL_IGMPMCAST
);
4494 IOCTL_NAME(WS_SIO_RCVALL_MCAST
);
4495 /* IOCTL_NAME(WS_SIO_RELEASE_PORT_RESERVATION); */
4496 IOCTL_NAME(WS_SIO_ROUTING_INTERFACE_CHANGE
);
4497 IOCTL_NAME(WS_SIO_ROUTING_INTERFACE_QUERY
);
4498 IOCTL_NAME(WS_SIO_SET_COMPATIBILITY_MODE
);
4499 IOCTL_NAME(WS_SIO_SET_GROUP_QOS
);
4500 IOCTL_NAME(WS_SIO_SET_QOS
);
4501 IOCTL_NAME(WS_SIO_TRANSLATE_HANDLE
);
4502 IOCTL_NAME(WS_SIO_UDP_CONNRESET
);
4509 /* If this is not a known code split its bits */
4510 switch(code
& 0x18000000)
4515 case WS_IOC_PROTOCOL
:
4516 family
= "IOC_PROTOCOL";
4519 family
= "IOC_VENDOR";
4521 default: /* WS_IOC_UNIX */
4523 BYTE size
= (code
>> 16) & WS_IOCPARM_MASK
;
4524 char x
= (code
& 0xff00) >> 8;
4525 BYTE y
= code
& 0xff;
4528 switch (code
& (WS_IOC_VOID
|WS_IOC_INOUT
))
4532 sprintf(args
, "%d, %d", x
, y
);
4536 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
4540 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
4544 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
4547 return wine_dbg_sprintf("%s(%s)", buf_type
, args
);
4551 /* We are different from WS_IOC_UNIX. */
4552 switch (code
& (WS_IOC_VOID
|WS_IOC_INOUT
))
4555 buf_type
= "_WSAIO";
4558 buf_type
= "_WSAIORW";
4561 buf_type
= "_WSAIOW";
4564 buf_type
= "_WSAIOR";
4571 return wine_dbg_sprintf("%s(%s, %d)", buf_type
, family
,
4572 (USHORT
)(code
& 0xffff));
4575 /* do an ioctl call through the server */
4576 static DWORD
server_ioctl_sock( SOCKET s
, DWORD code
, LPVOID in_buff
, DWORD in_size
,
4577 LPVOID out_buff
, DWORD out_size
, LPDWORD ret_size
,
4578 LPWSAOVERLAPPED overlapped
,
4579 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
4581 HANDLE event
= overlapped
? overlapped
->hEvent
: 0;
4582 HANDLE handle
= SOCKET2HANDLE( s
);
4583 struct ws2_async
*wsa
= NULL
;
4584 IO_STATUS_BLOCK
*io
= (PIO_STATUS_BLOCK
)overlapped
, iosb
;
4585 void *cvalue
= NULL
;
4590 if (!(wsa
= (struct ws2_async
*)alloc_async_io( sizeof(*wsa
) )))
4591 return WSA_NOT_ENOUGH_MEMORY
;
4592 wsa
->hSocket
= handle
;
4593 wsa
->user_overlapped
= overlapped
;
4594 wsa
->completion_func
= completion
;
4595 if (!io
) io
= &wsa
->local_iosb
;
4600 else if (!((ULONG_PTR
)overlapped
->hEvent
& 1))
4601 cvalue
= overlapped
;
4603 status
= NtDeviceIoControlFile( handle
, event
, wsa
? ws2_async_apc
: NULL
, cvalue
, io
, code
,
4604 in_buff
, in_size
, out_buff
, out_size
);
4605 if (status
== STATUS_NOT_SUPPORTED
)
4607 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
4608 code
, code
>> 16, (code
>> 14) & 3, (code
>> 2) & 0xfff, code
& 3);
4610 else if (status
== STATUS_SUCCESS
)
4611 *ret_size
= io
->Information
; /* "Information" is the size written to the output buffer */
4613 if (status
!= STATUS_PENDING
) RtlFreeHeap( GetProcessHeap(), 0, wsa
);
4615 return NtStatusToWSAError( status
);
4618 /**********************************************************************
4619 * WSAIoctl (WS2_32.50)
4622 INT WINAPI
WSAIoctl(SOCKET s
, DWORD code
, LPVOID in_buff
, DWORD in_size
, LPVOID out_buff
,
4623 DWORD out_size
, LPDWORD ret_size
, LPWSAOVERLAPPED overlapped
,
4624 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
4627 DWORD status
= 0, total
= 0;
4629 TRACE("%04lx, %s, %p, %d, %p, %d, %p, %p, %p\n",
4630 s
, debugstr_wsaioctl(code
), in_buff
, in_size
, out_buff
, out_size
, ret_size
, overlapped
, completion
);
4635 if (in_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(in_buff
))
4637 SetLastError(WSAEFAULT
);
4638 return SOCKET_ERROR
;
4640 TRACE("-> FIONBIO (%x)\n", *(WS_u_long
*)in_buff
);
4641 if (_get_sock_mask(s
))
4643 /* AsyncSelect()'ed sockets are always nonblocking */
4644 if (!*(WS_u_long
*)in_buff
) status
= WSAEINVAL
;
4647 if (*(WS_u_long
*)in_buff
)
4648 _enable_event(SOCKET2HANDLE(s
), 0, FD_WINE_NONBLOCKING
, 0);
4650 _enable_event(SOCKET2HANDLE(s
), 0, 0, FD_WINE_NONBLOCKING
);
4655 if (out_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(out_buff
))
4657 SetLastError(WSAEFAULT
);
4658 return SOCKET_ERROR
;
4660 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
4661 if (ioctl(fd
, FIONREAD
, out_buff
) == -1)
4662 status
= wsaErrno();
4663 release_sock_fd( s
, fd
);
4669 unsigned int oob
= 0, atmark
= 0;
4670 socklen_t oobsize
= sizeof(int);
4671 if (out_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(out_buff
))
4673 SetLastError(WSAEFAULT
);
4674 return SOCKET_ERROR
;
4676 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
4677 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
4678 if ((getsockopt(fd
, SOL_SOCKET
, SO_OOBINLINE
, &oob
, &oobsize
) == -1)
4679 || (!oob
&& ioctl(fd
, SIOCATMARK
, &atmark
) == -1))
4680 status
= wsaErrno();
4683 /* The SIOCATMARK value read from ioctl() is reversed
4684 * because BSD returns TRUE if it's in the OOB mark
4685 * while Windows returns TRUE if there are NO OOB bytes.
4687 (*(WS_u_long
*) out_buff
) = oob
|| !atmark
;
4690 release_sock_fd( s
, fd
);
4695 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
4696 SetLastError(WSAEINVAL
);
4697 return SOCKET_ERROR
;
4699 case WS_SIO_GET_INTERFACE_LIST
:
4701 INTERFACE_INFO
* intArray
= out_buff
;
4702 DWORD size
, numInt
= 0, apiReturn
;
4704 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
4706 if (!out_buff
|| !ret_size
)
4708 SetLastError(WSAEFAULT
);
4709 return SOCKET_ERROR
;
4712 fd
= get_sock_fd( s
, 0, NULL
);
4713 if (fd
== -1) return SOCKET_ERROR
;
4715 apiReturn
= GetAdaptersInfo(NULL
, &size
);
4716 if (apiReturn
== ERROR_BUFFER_OVERFLOW
)
4718 PIP_ADAPTER_INFO table
= HeapAlloc(GetProcessHeap(),0,size
);
4722 if (GetAdaptersInfo(table
, &size
) == NO_ERROR
)
4724 PIP_ADAPTER_INFO ptr
;
4726 for (ptr
= table
, numInt
= 0; ptr
; ptr
= ptr
->Next
)
4728 unsigned int addr
, mask
, bcast
;
4729 struct ifreq ifInfo
;
4731 /* Skip interfaces without an IPv4 address. */
4732 if (ptr
->IpAddressList
.IpAddress
.String
[0] == '\0')
4735 if ((numInt
+ 1)*sizeof(INTERFACE_INFO
)/sizeof(IP_ADAPTER_INFO
) > out_size
)
4737 WARN("Buffer too small = %u, out_size = %u\n", numInt
+ 1, out_size
);
4742 /* Socket Status Flags */
4743 lstrcpynA(ifInfo
.ifr_name
, ptr
->AdapterName
, IFNAMSIZ
);
4744 if (ioctl(fd
, SIOCGIFFLAGS
, &ifInfo
) < 0)
4746 ERR("Error obtaining status flags for socket!\n");
4752 /* set flags; the values of IFF_* are not the same
4753 under Linux and Windows, therefore must generate
4755 intArray
->iiFlags
= 0;
4756 if (ifInfo
.ifr_flags
& IFF_BROADCAST
)
4757 intArray
->iiFlags
|= WS_IFF_BROADCAST
;
4758 #ifdef IFF_POINTOPOINT
4759 if (ifInfo
.ifr_flags
& IFF_POINTOPOINT
)
4760 intArray
->iiFlags
|= WS_IFF_POINTTOPOINT
;
4762 if (ifInfo
.ifr_flags
& IFF_LOOPBACK
)
4763 intArray
->iiFlags
|= WS_IFF_LOOPBACK
;
4764 if (ifInfo
.ifr_flags
& IFF_UP
)
4765 intArray
->iiFlags
|= WS_IFF_UP
;
4766 if (ifInfo
.ifr_flags
& IFF_MULTICAST
)
4767 intArray
->iiFlags
|= WS_IFF_MULTICAST
;
4770 addr
= inet_addr(ptr
->IpAddressList
.IpAddress
.String
);
4771 mask
= inet_addr(ptr
->IpAddressList
.IpMask
.String
);
4772 bcast
= addr
| ~mask
;
4773 intArray
->iiAddress
.AddressIn
.sin_family
= WS_AF_INET
;
4774 intArray
->iiAddress
.AddressIn
.sin_port
= 0;
4775 intArray
->iiAddress
.AddressIn
.sin_addr
.WS_s_addr
= addr
;
4777 intArray
->iiNetmask
.AddressIn
.sin_family
= WS_AF_INET
;
4778 intArray
->iiNetmask
.AddressIn
.sin_port
= 0;
4779 intArray
->iiNetmask
.AddressIn
.sin_addr
.WS_s_addr
= mask
;
4781 intArray
->iiBroadcastAddress
.AddressIn
.sin_family
= WS_AF_INET
;
4782 intArray
->iiBroadcastAddress
.AddressIn
.sin_port
= 0;
4783 intArray
->iiBroadcastAddress
.AddressIn
.sin_addr
.WS_s_addr
= bcast
;
4790 ERR("Unable to get interface table!\n");
4793 HeapFree(GetProcessHeap(),0,table
);
4795 else status
= WSAEINVAL
;
4797 else if (apiReturn
!= ERROR_NO_DATA
)
4799 ERR("Unable to get interface table!\n");
4802 /* Calculate the size of the array being returned */
4803 total
= sizeof(INTERFACE_INFO
) * numInt
;
4804 release_sock_fd( s
, fd
);
4808 case WS_SIO_ADDRESS_LIST_QUERY
:
4812 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
4816 SetLastError(WSAEFAULT
);
4817 return SOCKET_ERROR
;
4820 if (out_size
&& out_size
< FIELD_OFFSET(SOCKET_ADDRESS_LIST
, Address
[0]))
4823 SetLastError(WSAEINVAL
);
4824 return SOCKET_ERROR
;
4827 if (GetAdaptersInfo(NULL
, &size
) == ERROR_BUFFER_OVERFLOW
)
4829 IP_ADAPTER_INFO
*p
, *table
= HeapAlloc(GetProcessHeap(), 0, size
);
4830 SOCKET_ADDRESS_LIST
*sa_list
;
4831 SOCKADDR_IN
*sockaddr
;
4836 if (!table
|| GetAdaptersInfo(table
, &size
))
4838 HeapFree(GetProcessHeap(), 0, table
);
4843 for (p
= table
, num
= 0; p
; p
= p
->Next
)
4844 if (p
->IpAddressList
.IpAddress
.String
[0]) num
++;
4846 total
= FIELD_OFFSET(SOCKET_ADDRESS_LIST
, Address
[num
]) + num
* sizeof(*sockaddr
);
4847 if (total
> out_size
|| !out_buff
)
4850 HeapFree(GetProcessHeap(), 0, table
);
4856 sa
= sa_list
->Address
;
4857 sockaddr
= (SOCKADDR_IN
*)&sa
[num
];
4858 sa_list
->iAddressCount
= num
;
4860 for (p
= table
, i
= 0; p
; p
= p
->Next
)
4862 if (!p
->IpAddressList
.IpAddress
.String
[0]) continue;
4864 sa
[i
].lpSockaddr
= (SOCKADDR
*)&sockaddr
[i
];
4865 sa
[i
].iSockaddrLength
= sizeof(SOCKADDR
);
4867 sockaddr
[i
].sin_family
= WS_AF_INET
;
4868 sockaddr
[i
].sin_port
= 0;
4869 sockaddr
[i
].sin_addr
.WS_s_addr
= inet_addr(p
->IpAddressList
.IpAddress
.String
);
4873 HeapFree(GetProcessHeap(), 0, table
);
4877 WARN("unable to get IP address list\n");
4884 FIXME("SIO_FLUSH: stub.\n");
4887 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER
:
4889 #define EXTENSION_FUNCTION(x, y) { x, y, #y },
4896 EXTENSION_FUNCTION(WSAID_CONNECTEX
, WS2_ConnectEx
)
4897 EXTENSION_FUNCTION(WSAID_DISCONNECTEX
, WS2_DisconnectEx
)
4898 EXTENSION_FUNCTION(WSAID_ACCEPTEX
, WS2_AcceptEx
)
4899 EXTENSION_FUNCTION(WSAID_GETACCEPTEXSOCKADDRS
, WS2_GetAcceptExSockaddrs
)
4900 EXTENSION_FUNCTION(WSAID_TRANSMITFILE
, WS2_TransmitFile
)
4901 /* EXTENSION_FUNCTION(WSAID_TRANSMITPACKETS, WS2_TransmitPackets) */
4902 EXTENSION_FUNCTION(WSAID_WSARECVMSG
, WS2_WSARecvMsg
)
4903 EXTENSION_FUNCTION(WSAID_WSASENDMSG
, WSASendMsg
)
4905 #undef EXTENSION_FUNCTION
4909 for (i
= 0; i
< sizeof(guid_funcs
) / sizeof(guid_funcs
[0]); i
++)
4911 if (IsEqualGUID(&guid_funcs
[i
].guid
, in_buff
))
4920 TRACE("-> got %s\n", guid_funcs
[i
].name
);
4921 *(void **)out_buff
= guid_funcs
[i
].func_ptr
;
4925 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff
));
4926 status
= WSAEOPNOTSUPP
;
4929 case WS_SIO_KEEPALIVE_VALS
:
4931 struct tcp_keepalive
*k
;
4932 int keepalive
, keepidle
, keepintvl
;
4934 if (!in_buff
|| in_size
< sizeof(struct tcp_keepalive
))
4936 SetLastError(WSAEFAULT
);
4937 return SOCKET_ERROR
;
4941 keepalive
= k
->onoff
? 1 : 0;
4942 keepidle
= max( 1, (k
->keepalivetime
+ 500) / 1000 );
4943 keepintvl
= max( 1, (k
->keepaliveinterval
+ 500) / 1000 );
4945 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive
, keepidle
, keepintvl
);
4947 fd
= get_sock_fd(s
, 0, NULL
);
4948 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&keepalive
, sizeof(int)) == -1)
4950 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPINTVL)
4951 /* these values need to be set only if SO_KEEPALIVE is enabled */
4954 #ifndef TCP_KEEPIDLE
4955 FIXME("ignoring keepalive timeout\n");
4957 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPIDLE
, (void *)&keepidle
, sizeof(int)) == -1)
4961 #ifdef TCP_KEEPINTVL
4962 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPINTVL
, (void *)&keepintvl
, sizeof(int)) == -1)
4965 FIXME("ignoring keepalive interval\n");
4970 FIXME("ignoring keepalive interval and timeout\n");
4972 release_sock_fd(s
, fd
);
4975 case WS_SIO_ROUTING_INTERFACE_QUERY
:
4977 struct WS_sockaddr
*daddr
= (struct WS_sockaddr
*)in_buff
;
4978 struct WS_sockaddr_in
*daddr_in
= (struct WS_sockaddr_in
*)daddr
;
4979 struct WS_sockaddr_in
*saddr_in
= out_buff
;
4980 MIB_IPFORWARDROW row
;
4981 PMIB_IPADDRTABLE ipAddrTable
= NULL
;
4982 DWORD size
, i
, found_index
;
4984 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4986 if (!in_buff
|| in_size
< sizeof(struct WS_sockaddr
) ||
4987 !out_buff
|| out_size
< sizeof(struct WS_sockaddr_in
) || !ret_size
)
4989 SetLastError(WSAEFAULT
);
4990 return SOCKET_ERROR
;
4992 if (daddr
->sa_family
!= WS_AF_INET
)
4994 FIXME("unsupported address family %d\n", daddr
->sa_family
);
4995 status
= WSAEAFNOSUPPORT
;
4998 if (GetBestRoute(daddr_in
->sin_addr
.S_un
.S_addr
, 0, &row
) != NOERROR
||
4999 GetIpAddrTable(NULL
, &size
, FALSE
) != ERROR_INSUFFICIENT_BUFFER
)
5004 ipAddrTable
= HeapAlloc(GetProcessHeap(), 0, size
);
5005 if (GetIpAddrTable(ipAddrTable
, &size
, FALSE
))
5007 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
5011 for (i
= 0, found_index
= ipAddrTable
->dwNumEntries
;
5012 i
< ipAddrTable
->dwNumEntries
; i
++)
5014 if (ipAddrTable
->table
[i
].dwIndex
== row
.dwForwardIfIndex
)
5017 if (found_index
== ipAddrTable
->dwNumEntries
)
5019 ERR("no matching IP address for interface %d\n",
5020 row
.dwForwardIfIndex
);
5021 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
5025 saddr_in
->sin_family
= WS_AF_INET
;
5026 saddr_in
->sin_addr
.S_un
.S_addr
= ipAddrTable
->table
[found_index
].dwAddr
;
5027 saddr_in
->sin_port
= 0;
5028 total
= sizeof(struct WS_sockaddr_in
);
5029 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
5032 case WS_SIO_SET_COMPATIBILITY_MODE
:
5033 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
5034 status
= WSAEOPNOTSUPP
;
5036 case WS_SIO_UDP_CONNRESET
:
5037 FIXME("WS_SIO_UDP_CONNRESET stub\n");
5039 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
5040 SetLastError(WSAEOPNOTSUPP
);
5041 return SOCKET_ERROR
;
5043 status
= WSAEOPNOTSUPP
;
5047 if (status
== WSAEOPNOTSUPP
)
5049 status
= server_ioctl_sock(s
, code
, in_buff
, in_size
, out_buff
, out_size
, &total
,
5050 overlapped
, completion
);
5051 if (status
!= WSAEOPNOTSUPP
)
5053 if (status
== 0 || status
== WSA_IO_PENDING
)
5054 TRACE("-> %s request\n", debugstr_wsaioctl(code
));
5056 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code
), status
);
5058 /* overlapped and completion operations will be handled by the server */
5063 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code
));
5068 FIXME( "completion routine %p not supported\n", completion
);
5070 else if (overlapped
)
5072 ULONG_PTR cvalue
= (overlapped
&& ((ULONG_PTR
)overlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)overlapped
: 0;
5073 overlapped
->Internal
= status
;
5074 overlapped
->InternalHigh
= total
;
5075 if (overlapped
->hEvent
) NtSetEvent( overlapped
->hEvent
, NULL
);
5076 if (cvalue
) WS_AddCompletion( HANDLE2SOCKET(s
), cvalue
, status
, total
);
5081 if (ret_size
) *ret_size
= total
;
5084 SetLastError( status
);
5085 return SOCKET_ERROR
;
5089 /***********************************************************************
5090 * ioctlsocket (WS2_32.10)
5092 int WINAPI
WS_ioctlsocket(SOCKET s
, LONG cmd
, WS_u_long
*argp
)
5095 return WSAIoctl( s
, cmd
, argp
, sizeof(WS_u_long
), argp
, sizeof(WS_u_long
), &ret_size
, NULL
, NULL
);
5098 /***********************************************************************
5099 * listen (WS2_32.13)
5101 int WINAPI
WS_listen(SOCKET s
, int backlog
)
5103 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
), ret
= SOCKET_ERROR
;
5105 TRACE("socket %04lx, backlog %d\n", s
, backlog
);
5108 int bound
= is_fd_bound(fd
, NULL
, NULL
);
5112 SetLastError(bound
== -1 ? wsaErrno() : WSAEINVAL
);
5114 else if (listen(fd
, backlog
) == 0)
5116 _enable_event(SOCKET2HANDLE(s
), FD_ACCEPT
,
5118 FD_CONNECT
|FD_WINE_CONNECTED
);
5122 SetLastError(wsaErrno());
5123 release_sock_fd( s
, fd
);
5126 SetLastError(WSAENOTSOCK
);
5130 /***********************************************************************
5133 int WINAPI
WS_recv(SOCKET s
, char *buf
, int len
, int flags
)
5135 DWORD n
, dwFlags
= flags
;
5141 if ( WS2_recv_base(s
, &wsabuf
, 1, &n
, &dwFlags
, NULL
, NULL
, NULL
, NULL
, NULL
) == SOCKET_ERROR
)
5142 return SOCKET_ERROR
;
5147 /***********************************************************************
5148 * recvfrom (WS2_32.17)
5150 int WINAPI
WS_recvfrom(SOCKET s
, char *buf
, INT len
, int flags
,
5151 struct WS_sockaddr
*from
, int *fromlen
)
5153 DWORD n
, dwFlags
= flags
;
5159 if ( WS2_recv_base(s
, &wsabuf
, 1, &n
, &dwFlags
, from
, fromlen
, NULL
, NULL
, NULL
) == SOCKET_ERROR
)
5160 return SOCKET_ERROR
;
5165 /* allocate a poll array for the corresponding fd sets */
5166 static struct pollfd
*fd_sets_to_poll( const WS_fd_set
*readfds
, const WS_fd_set
*writefds
,
5167 const WS_fd_set
*exceptfds
, int *count_ptr
)
5169 unsigned int i
, j
= 0, count
= 0;
5171 struct per_thread_data
*ptb
= get_per_thread_data();
5173 if (readfds
) count
+= readfds
->fd_count
;
5174 if (writefds
) count
+= writefds
->fd_count
;
5175 if (exceptfds
) count
+= exceptfds
->fd_count
;
5179 SetLastError(WSAEINVAL
);
5183 /* check if the cache can hold all descriptors, if not do the resizing */
5184 if (ptb
->fd_count
< count
)
5186 if (!(fds
= HeapAlloc(GetProcessHeap(), 0, count
* sizeof(fds
[0]))))
5188 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
5191 HeapFree(GetProcessHeap(), 0, ptb
->fd_cache
);
5192 ptb
->fd_cache
= fds
;
5193 ptb
->fd_count
= count
;
5196 fds
= ptb
->fd_cache
;
5199 for (i
= 0; i
< readfds
->fd_count
; i
++, j
++)
5201 fds
[j
].fd
= get_sock_fd( readfds
->fd_array
[i
], FILE_READ_DATA
, NULL
);
5202 if (fds
[j
].fd
== -1) goto failed
;
5204 if (is_fd_bound(fds
[j
].fd
, NULL
, NULL
) == 1)
5206 fds
[j
].events
= POLLIN
;
5210 release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
5216 for (i
= 0; i
< writefds
->fd_count
; i
++, j
++)
5218 fds
[j
].fd
= get_sock_fd( writefds
->fd_array
[i
], FILE_WRITE_DATA
, NULL
);
5219 if (fds
[j
].fd
== -1) goto failed
;
5221 if (is_fd_bound(fds
[j
].fd
, NULL
, NULL
) == 1 ||
5222 _get_fd_type(fds
[j
].fd
) == SOCK_DGRAM
)
5224 fds
[j
].events
= POLLOUT
;
5228 release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
5234 for (i
= 0; i
< exceptfds
->fd_count
; i
++, j
++)
5236 fds
[j
].fd
= get_sock_fd( exceptfds
->fd_array
[i
], 0, NULL
);
5237 if (fds
[j
].fd
== -1) goto failed
;
5239 if (is_fd_bound(fds
[j
].fd
, NULL
, NULL
) == 1)
5241 int oob_inlined
= 0;
5242 socklen_t olen
= sizeof(oob_inlined
);
5244 fds
[j
].events
= POLLHUP
;
5246 /* Check if we need to test for urgent data or not */
5247 getsockopt(fds
[j
].fd
, SOL_SOCKET
, SO_OOBINLINE
, (char*) &oob_inlined
, &olen
);
5249 fds
[j
].events
|= POLLPRI
;
5253 release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
5264 for (i
= 0; i
< readfds
->fd_count
&& j
< count
; i
++, j
++)
5265 if (fds
[j
].fd
!= -1) release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
5267 for (i
= 0; i
< writefds
->fd_count
&& j
< count
; i
++, j
++)
5268 if (fds
[j
].fd
!= -1) release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
5270 for (i
= 0; i
< exceptfds
->fd_count
&& j
< count
; i
++, j
++)
5271 if (fds
[j
].fd
!= -1) release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
5275 /* release the file descriptor obtained in fd_sets_to_poll */
5276 /* must be called with the original fd_set arrays, before calling get_poll_results */
5277 static void release_poll_fds( const WS_fd_set
*readfds
, const WS_fd_set
*writefds
,
5278 const WS_fd_set
*exceptfds
, struct pollfd
*fds
)
5280 unsigned int i
, j
= 0;
5284 for (i
= 0; i
< readfds
->fd_count
; i
++, j
++)
5285 if (fds
[j
].fd
!= -1) release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
5289 for (i
= 0; i
< writefds
->fd_count
; i
++, j
++)
5290 if (fds
[j
].fd
!= -1) release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
5294 for (i
= 0; i
< exceptfds
->fd_count
; i
++, j
++)
5296 if (fds
[j
].fd
== -1) continue;
5297 release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
5298 if (fds
[j
].revents
& POLLHUP
)
5300 int fd
= get_sock_fd( exceptfds
->fd_array
[i
], 0, NULL
);
5302 release_sock_fd( exceptfds
->fd_array
[i
], fd
);
5310 static int do_poll(struct pollfd
*pollfds
, int count
, int timeout
)
5312 struct timeval tv1
, tv2
;
5313 int ret
, torig
= timeout
;
5315 if (timeout
> 0) gettimeofday( &tv1
, 0 );
5317 while ((ret
= poll( pollfds
, count
, timeout
)) < 0)
5319 if (errno
!= EINTR
) break;
5320 if (timeout
< 0) continue;
5321 if (timeout
== 0) return 0;
5323 gettimeofday( &tv2
, 0 );
5325 tv2
.tv_sec
-= tv1
.tv_sec
;
5326 tv2
.tv_usec
-= tv1
.tv_usec
;
5327 if (tv2
.tv_usec
< 0)
5329 tv2
.tv_usec
+= 1000000;
5333 timeout
= torig
- (tv2
.tv_sec
* 1000) - (tv2
.tv_usec
+ 999) / 1000;
5334 if (timeout
<= 0) return 0;
5339 /* map the poll results back into the Windows fd sets */
5340 static int get_poll_results( WS_fd_set
*readfds
, WS_fd_set
*writefds
, WS_fd_set
*exceptfds
,
5341 const struct pollfd
*fds
)
5343 const struct pollfd
*poll_writefds
= fds
+ (readfds
? readfds
->fd_count
: 0);
5344 const struct pollfd
*poll_exceptfds
= poll_writefds
+ (writefds
? writefds
->fd_count
: 0);
5345 unsigned int i
, k
, total
= 0;
5349 for (i
= k
= 0; i
< readfds
->fd_count
; i
++)
5351 if (fds
[i
].revents
||
5352 (readfds
== writefds
&& (poll_writefds
[i
].revents
& POLLOUT
) && !(poll_writefds
[i
].revents
& POLLHUP
)) ||
5353 (readfds
== exceptfds
&& poll_exceptfds
[i
].revents
))
5354 readfds
->fd_array
[k
++] = readfds
->fd_array
[i
];
5356 readfds
->fd_count
= k
;
5359 if (writefds
&& writefds
!= readfds
)
5361 for (i
= k
= 0; i
< writefds
->fd_count
; i
++)
5363 if (((poll_writefds
[i
].revents
& POLLOUT
) && !(poll_writefds
[i
].revents
& POLLHUP
)) ||
5364 (writefds
== exceptfds
&& poll_exceptfds
[i
].revents
))
5365 writefds
->fd_array
[k
++] = writefds
->fd_array
[i
];
5367 writefds
->fd_count
= k
;
5370 if (exceptfds
&& exceptfds
!= readfds
&& exceptfds
!= writefds
)
5372 for (i
= k
= 0; i
< exceptfds
->fd_count
; i
++)
5373 if (poll_exceptfds
[i
].revents
) exceptfds
->fd_array
[k
++] = exceptfds
->fd_array
[i
];
5374 exceptfds
->fd_count
= k
;
5380 /***********************************************************************
5381 * select (WS2_32.18)
5383 int WINAPI
WS_select(int nfds
, WS_fd_set
*ws_readfds
,
5384 WS_fd_set
*ws_writefds
, WS_fd_set
*ws_exceptfds
,
5385 const struct WS_timeval
* ws_timeout
)
5387 struct pollfd
*pollfds
;
5388 int count
, ret
, timeout
= -1;
5390 TRACE("read %p, write %p, excp %p timeout %p\n",
5391 ws_readfds
, ws_writefds
, ws_exceptfds
, ws_timeout
);
5393 if (!(pollfds
= fd_sets_to_poll( ws_readfds
, ws_writefds
, ws_exceptfds
, &count
)))
5394 return SOCKET_ERROR
;
5397 timeout
= (ws_timeout
->tv_sec
* 1000) + (ws_timeout
->tv_usec
+ 999) / 1000;
5399 ret
= do_poll(pollfds
, count
, timeout
);
5400 release_poll_fds( ws_readfds
, ws_writefds
, ws_exceptfds
, pollfds
);
5402 if (ret
== -1) SetLastError(wsaErrno());
5403 else ret
= get_poll_results( ws_readfds
, ws_writefds
, ws_exceptfds
, pollfds
);
5407 /***********************************************************************
5410 int WINAPI
WSAPoll(WSAPOLLFD
*wfds
, ULONG count
, int timeout
)
5413 struct pollfd
*ufds
;
5417 SetLastError(WSAEINVAL
);
5418 return SOCKET_ERROR
;
5422 SetLastError(WSAEFAULT
);
5423 return SOCKET_ERROR
;
5426 if (!(ufds
= HeapAlloc(GetProcessHeap(), 0, count
* sizeof(ufds
[0]))))
5428 SetLastError(WSAENOBUFS
);
5429 return SOCKET_ERROR
;
5432 for (i
= 0; i
< count
; i
++)
5434 ufds
[i
].fd
= get_sock_fd(wfds
[i
].fd
, 0, NULL
);
5435 ufds
[i
].events
= convert_poll_w2u(wfds
[i
].events
);
5436 ufds
[i
].revents
= 0;
5439 ret
= do_poll(ufds
, count
, timeout
);
5441 for (i
= 0; i
< count
; i
++)
5443 if (ufds
[i
].fd
!= -1)
5445 release_sock_fd(wfds
[i
].fd
, ufds
[i
].fd
);
5446 if (ufds
[i
].revents
& POLLHUP
)
5448 /* Check if the socket still exists */
5449 int fd
= get_sock_fd(wfds
[i
].fd
, 0, NULL
);
5452 wfds
[i
].revents
= WS_POLLHUP
;
5453 release_sock_fd(wfds
[i
].fd
, fd
);
5456 wfds
[i
].revents
= WS_POLLNVAL
;
5459 wfds
[i
].revents
= convert_poll_u2w(ufds
[i
].revents
);
5462 wfds
[i
].revents
= WS_POLLNVAL
;
5465 HeapFree(GetProcessHeap(), 0, ufds
);
5469 /* helper to send completion messages for client-only i/o operation case */
5470 static void WS_AddCompletion( SOCKET sock
, ULONG_PTR CompletionValue
, NTSTATUS CompletionStatus
,
5473 SERVER_START_REQ( add_fd_completion
)
5475 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(sock
) );
5476 req
->cvalue
= CompletionValue
;
5477 req
->status
= CompletionStatus
;
5478 req
->information
= Information
;
5479 wine_server_call( req
);
5485 /***********************************************************************
5488 int WINAPI
WS_send(SOCKET s
, const char *buf
, int len
, int flags
)
5494 wsabuf
.buf
= (char*) buf
;
5496 if ( WS2_sendto( s
, &wsabuf
, 1, &n
, flags
, NULL
, 0, NULL
, NULL
) == SOCKET_ERROR
)
5497 return SOCKET_ERROR
;
5502 /***********************************************************************
5503 * WSASend (WS2_32.72)
5505 INT WINAPI
WSASend( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
5506 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
5507 LPWSAOVERLAPPED lpOverlapped
,
5508 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
5510 return WS2_sendto( s
, lpBuffers
, dwBufferCount
, lpNumberOfBytesSent
, dwFlags
,
5511 NULL
, 0, lpOverlapped
, lpCompletionRoutine
);
5514 /***********************************************************************
5515 * WSASendDisconnect (WS2_32.73)
5517 INT WINAPI
WSASendDisconnect( SOCKET s
, LPWSABUF lpBuffers
)
5519 return WS_shutdown( s
, SD_SEND
);
5523 static int WS2_sendto( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
5524 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
5525 const struct WS_sockaddr
*to
, int tolen
,
5526 LPWSAOVERLAPPED lpOverlapped
,
5527 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
5529 unsigned int i
, options
;
5530 int n
, fd
, err
, overlapped
, flags
;
5531 struct ws2_async
*wsa
= NULL
, localwsa
;
5532 int totalLength
= 0;
5536 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
5537 s
, lpBuffers
, dwBufferCount
, dwFlags
,
5538 to
, tolen
, lpOverlapped
, lpCompletionRoutine
);
5540 fd
= get_sock_fd( s
, FILE_WRITE_DATA
, &options
);
5541 TRACE( "fd=%d, options=%x\n", fd
, options
);
5543 if ( fd
== -1 ) return SOCKET_ERROR
;
5545 if (!lpOverlapped
&& !lpNumberOfBytesSent
)
5551 overlapped
= (lpOverlapped
|| lpCompletionRoutine
) &&
5552 !(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
));
5553 if (overlapped
|| dwBufferCount
> 1)
5555 if (!(wsa
= (struct ws2_async
*)alloc_async_io( offsetof(struct ws2_async
, iovec
[dwBufferCount
]))))
5564 wsa
->hSocket
= SOCKET2HANDLE(s
);
5565 wsa
->addr
= (struct WS_sockaddr
*)to
;
5566 wsa
->addrlen
.val
= tolen
;
5567 wsa
->flags
= dwFlags
;
5568 wsa
->lpFlags
= &wsa
->flags
;
5569 wsa
->control
= NULL
;
5570 wsa
->n_iovecs
= dwBufferCount
;
5571 wsa
->first_iovec
= 0;
5572 for ( i
= 0; i
< dwBufferCount
; i
++ )
5574 wsa
->iovec
[i
].iov_base
= lpBuffers
[i
].buf
;
5575 wsa
->iovec
[i
].iov_len
= lpBuffers
[i
].len
;
5576 totalLength
+= lpBuffers
[i
].len
;
5579 flags
= convert_flags(dwFlags
);
5580 n
= WS2_send( fd
, wsa
, flags
);
5581 if (n
== -1 && errno
!= EAGAIN
)
5589 IO_STATUS_BLOCK
*iosb
= lpOverlapped
? (IO_STATUS_BLOCK
*)lpOverlapped
: &wsa
->local_iosb
;
5590 ULONG_PTR cvalue
= (lpOverlapped
&& ((ULONG_PTR
)lpOverlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)lpOverlapped
: 0;
5592 wsa
->user_overlapped
= lpOverlapped
;
5593 wsa
->completion_func
= lpCompletionRoutine
;
5594 release_sock_fd( s
, fd
);
5596 if (n
== -1 || n
< totalLength
)
5598 iosb
->u
.Status
= STATUS_PENDING
;
5599 iosb
->Information
= n
== -1 ? 0 : n
;
5601 if (wsa
->completion_func
)
5602 err
= register_async( ASYNC_TYPE_WRITE
, wsa
->hSocket
, WS2_async_send
, wsa
, NULL
,
5603 ws2_async_apc
, wsa
, iosb
);
5605 err
= register_async( ASYNC_TYPE_WRITE
, wsa
->hSocket
, WS2_async_send
, wsa
, lpOverlapped
->hEvent
,
5606 NULL
, (void *)cvalue
, iosb
);
5608 /* Enable the event only after starting the async. The server will deliver it as soon as
5609 the async is done. */
5610 _enable_event(SOCKET2HANDLE(s
), FD_WRITE
, 0, 0);
5612 if (err
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
5613 SetLastError(NtStatusToWSAError( err
));
5614 return SOCKET_ERROR
;
5617 iosb
->u
.Status
= STATUS_SUCCESS
;
5618 iosb
->Information
= n
;
5619 if (lpNumberOfBytesSent
) *lpNumberOfBytesSent
= n
;
5620 if (!wsa
->completion_func
)
5622 if (cvalue
) WS_AddCompletion( s
, cvalue
, STATUS_SUCCESS
, n
);
5623 if (lpOverlapped
->hEvent
) SetEvent( lpOverlapped
->hEvent
);
5624 HeapFree( GetProcessHeap(), 0, wsa
);
5626 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC
)ws2_async_apc
,
5627 (ULONG_PTR
)wsa
, (ULONG_PTR
)iosb
, 0 );
5628 SetLastError(ERROR_SUCCESS
);
5632 if ((err
= _is_blocking( s
, &is_blocking
)))
5634 err
= NtStatusToWSAError( err
);
5640 /* On a blocking non-overlapped stream socket,
5641 * sending blocks until the entire buffer is sent. */
5642 DWORD timeout_start
= GetTickCount();
5644 bytes_sent
= n
== -1 ? 0 : n
;
5646 while (wsa
->first_iovec
< wsa
->n_iovecs
)
5649 int poll_timeout
= -1;
5650 INT64 timeout
= get_rcvsnd_timeo(fd
, FALSE
);
5654 timeout
-= GetTickCount() - timeout_start
;
5655 if (timeout
< 0) poll_timeout
= 0;
5656 else poll_timeout
= timeout
<= INT_MAX
? timeout
: INT_MAX
;
5660 pfd
.events
= POLLOUT
;
5662 if (!poll_timeout
|| !poll( &pfd
, 1, poll_timeout
))
5665 goto error
; /* msdn says a timeout in send is fatal */
5668 n
= WS2_send( fd
, wsa
, flags
);
5669 if (n
== -1 && errno
!= EAGAIN
)
5679 else /* non-blocking */
5681 if (n
< totalLength
)
5682 _enable_event(SOCKET2HANDLE(s
), FD_WRITE
, 0, 0);
5685 err
= WSAEWOULDBLOCK
;
5691 TRACE(" -> %i bytes\n", bytes_sent
);
5693 if (lpNumberOfBytesSent
) *lpNumberOfBytesSent
= bytes_sent
;
5694 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
5695 release_sock_fd( s
, fd
);
5696 SetLastError(ERROR_SUCCESS
);
5700 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
5701 release_sock_fd( s
, fd
);
5702 WARN(" -> ERROR %d\n", err
);
5704 return SOCKET_ERROR
;
5707 /***********************************************************************
5708 * WSASendTo (WS2_32.74)
5710 INT WINAPI
WSASendTo( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
5711 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
5712 const struct WS_sockaddr
*to
, int tolen
,
5713 LPWSAOVERLAPPED lpOverlapped
,
5714 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
5716 return WS2_sendto( s
, lpBuffers
, dwBufferCount
,
5717 lpNumberOfBytesSent
, dwFlags
,
5719 lpOverlapped
, lpCompletionRoutine
);
5722 /***********************************************************************
5723 * sendto (WS2_32.20)
5725 int WINAPI
WS_sendto(SOCKET s
, const char *buf
, int len
, int flags
,
5726 const struct WS_sockaddr
*to
, int tolen
)
5732 wsabuf
.buf
= (char*) buf
;
5734 if ( WS2_sendto(s
, &wsabuf
, 1, &n
, flags
, to
, tolen
, NULL
, NULL
) == SOCKET_ERROR
)
5735 return SOCKET_ERROR
;
5740 /***********************************************************************
5741 * setsockopt (WS2_32.21)
5743 int WINAPI
WS_setsockopt(SOCKET s
, int level
, int optname
,
5744 const char *optval
, int optlen
)
5748 struct linger linger
;
5749 struct timeval tval
;
5751 TRACE("(socket %04lx, %s, optval %s, optlen %d)\n", s
,
5752 debugstr_sockopt(level
, optname
), debugstr_optval(optval
, optlen
),
5755 /* some broken apps pass the value directly instead of a pointer to it */
5756 if(optlen
&& IS_INTRESOURCE(optval
))
5758 SetLastError(WSAEFAULT
);
5759 return SOCKET_ERROR
;
5767 /* Some options need some conversion before they can be sent to
5768 * setsockopt. The conversions are done here, then they will fall through
5769 * to the general case. Special options that are not passed to
5770 * setsockopt follow below that.*/
5772 case WS_SO_DONTLINGER
:
5775 SetLastError(WSAEFAULT
);
5776 return SOCKET_ERROR
;
5778 linger
.l_onoff
= *(const int*)optval
== 0;
5779 linger
.l_linger
= 0;
5781 optname
= SO_LINGER
;
5782 optval
= (char*)&linger
;
5783 optlen
= sizeof(struct linger
);
5789 SetLastError(WSAEFAULT
);
5790 return SOCKET_ERROR
;
5792 linger
.l_onoff
= ((LINGER
*)optval
)->l_onoff
;
5793 linger
.l_linger
= ((LINGER
*)optval
)->l_linger
;
5795 optname
= SO_LINGER
;
5796 optval
= (char*)&linger
;
5797 optlen
= sizeof(struct linger
);
5801 if (*(const int*)optval
< 2048)
5803 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval
);
5808 /* The options listed here don't need any special handling. Thanks to
5809 * the conversion happening above, options from there will fall through
5811 case WS_SO_ACCEPTCONN
:
5812 case WS_SO_BROADCAST
:
5814 case WS_SO_KEEPALIVE
:
5815 case WS_SO_OOBINLINE
:
5816 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
5817 * however, using it the BSD way fixes bug 8513 and seems to be what
5818 * most programmers assume, anyway */
5819 case WS_SO_REUSEADDR
:
5822 convert_sockopt(&level
, &optname
);
5825 /* SO_DEBUG is a privileged operation, ignore it. */
5827 TRACE("Ignoring SO_DEBUG\n");
5830 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
5831 * socket. According to MSDN, this option is silently ignored.*/
5832 case WS_SO_DONTROUTE
:
5833 TRACE("Ignoring SO_DONTROUTE\n");
5836 /* Stops two sockets from being bound to the same port. Always happens
5837 * on unix systems, so just drop it. */
5838 case WS_SO_EXCLUSIVEADDRUSE
:
5839 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
5842 /* After a ConnectEx call succeeds, the socket can't be used with half of the
5843 * normal winsock functions on windows. We don't have that problem. */
5844 case WS_SO_UPDATE_CONNECT_CONTEXT
:
5845 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
5848 /* After a AcceptEx call succeeds, the socket can't be used with half of the
5849 * normal winsock functions on windows. We don't have that problem. */
5850 case WS_SO_UPDATE_ACCEPT_CONTEXT
:
5851 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
5854 /* SO_OPENTYPE does not require a valid socket handle. */
5855 case WS_SO_OPENTYPE
:
5856 if (!optlen
|| optlen
< sizeof(int) || !optval
)
5858 SetLastError(WSAEFAULT
);
5859 return SOCKET_ERROR
;
5861 get_per_thread_data()->opentype
= *(const int *)optval
;
5862 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval
) );
5866 case WS_SO_RCVTIMEO
:
5869 case WS_SO_SNDTIMEO
:
5871 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
5872 if (optval
&& optlen
== sizeof(UINT32
)) {
5873 /* WinSock passes milliseconds instead of struct timeval */
5874 tval
.tv_usec
= (*(const UINT32
*)optval
% 1000) * 1000;
5875 tval
.tv_sec
= *(const UINT32
*)optval
/ 1000;
5876 /* min of 500 milliseconds */
5877 if (tval
.tv_sec
== 0 && tval
.tv_usec
&& tval
.tv_usec
< 500000)
5878 tval
.tv_usec
= 500000;
5879 optlen
= sizeof(struct timeval
);
5880 optval
= (char*)&tval
;
5881 } else if (optlen
== sizeof(struct timeval
)) {
5882 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen
);
5884 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen
);
5887 convert_sockopt(&level
, &optname
);
5892 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname
);
5893 SetLastError(WSAENOPROTOOPT
);
5894 return SOCKET_ERROR
;
5896 break; /* case WS_SOL_SOCKET */
5899 case WS_NSPROTO_IPX
:
5903 return set_ipx_packettype(s
, *(int*)optval
);
5905 case WS_IPX_FILTERPTYPE
:
5906 /* Sets the receive filter packet type, at the moment we don't support it */
5907 FIXME("IPX_FILTERPTYPE: %x\n", *optval
);
5908 /* Returning 0 is better for now than returning a SOCKET_ERROR */
5912 FIXME("opt_name:%x\n", optname
);
5913 return SOCKET_ERROR
;
5915 break; /* case WS_NSPROTO_IPX */
5918 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
5919 case WS_IPPROTO_TCP
:
5922 case WS_TCP_NODELAY
:
5923 convert_sockopt(&level
, &optname
);
5926 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname
);
5927 return SOCKET_ERROR
;
5934 case WS_IP_ADD_MEMBERSHIP
:
5935 case WS_IP_DROP_MEMBERSHIP
:
5939 case WS_IP_MULTICAST_IF
:
5940 case WS_IP_MULTICAST_LOOP
:
5941 case WS_IP_MULTICAST_TTL
:
5948 #ifdef IP_UNICAST_IF
5949 case WS_IP_UNICAST_IF
:
5951 convert_sockopt(&level
, &optname
);
5953 case WS_IP_DONTFRAGMENT
:
5954 return set_dont_fragment(s
, IPPROTO_IP
, *(BOOL
*)optval
) ? 0 : SOCKET_ERROR
;
5956 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname
);
5957 return SOCKET_ERROR
;
5961 case WS_IPPROTO_IPV6
:
5964 #ifdef IPV6_ADD_MEMBERSHIP
5965 case WS_IPV6_ADD_MEMBERSHIP
:
5967 #ifdef IPV6_DROP_MEMBERSHIP
5968 case WS_IPV6_DROP_MEMBERSHIP
:
5970 case WS_IPV6_MULTICAST_IF
:
5971 case WS_IPV6_MULTICAST_HOPS
:
5972 case WS_IPV6_MULTICAST_LOOP
:
5973 case WS_IPV6_UNICAST_HOPS
:
5974 #ifdef IPV6_UNICAST_IF
5975 case WS_IPV6_UNICAST_IF
:
5977 convert_sockopt(&level
, &optname
);
5979 case WS_IPV6_DONTFRAG
:
5980 return set_dont_fragment(s
, IPPROTO_IPV6
, *(BOOL
*)optval
) ? 0 : SOCKET_ERROR
;
5981 case WS_IPV6_PROTECTION_LEVEL
:
5982 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
5984 case WS_IPV6_V6ONLY
:
5986 union generic_unix_sockaddr uaddr
;
5990 fd
= get_sock_fd( s
, 0, NULL
);
5991 if (fd
== -1) return SOCKET_ERROR
;
5993 bound
= is_fd_bound(fd
, &uaddr
, &uaddrlen
);
5994 release_sock_fd( s
, fd
);
5995 if (bound
== 0 && uaddr
.addr
.sa_family
== AF_INET
)
5997 /* Changing IPV6_V6ONLY succeeds on AF_INET (IPv4) socket
5998 * on Windows (with IPv6 support) if the socket is unbound.
5999 * It is essentially a noop, though Windows does store the value
6001 WARN("Silently ignoring IPPROTO_IPV6+IPV6_V6ONLY on AF_INET socket\n");
6004 level
= IPPROTO_IPV6
;
6005 optname
= IPV6_V6ONLY
;
6009 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname
);
6010 return SOCKET_ERROR
;
6015 WARN("Unknown level: 0x%08x\n", level
);
6016 SetLastError(WSAEINVAL
);
6017 return SOCKET_ERROR
;
6018 } /* end switch(level) */
6020 /* avoid endianness issues if argument is a 16-bit int */
6021 if (optval
&& optlen
< sizeof(int))
6023 woptval
= *((const INT16
*) optval
);
6024 optval
= (char*) &woptval
;
6025 woptval
&= (1 << optlen
* 8) - 1;
6028 fd
= get_sock_fd( s
, 0, NULL
);
6029 if (fd
== -1) return SOCKET_ERROR
;
6031 if (setsockopt(fd
, level
, optname
, optval
, optlen
) == 0)
6034 if (level
== SOL_SOCKET
&& optname
== SO_REUSEADDR
&&
6035 setsockopt(fd
, level
, SO_REUSEPORT
, optval
, optlen
) != 0)
6037 SetLastError(wsaErrno());
6038 release_sock_fd( s
, fd
);
6039 return SOCKET_ERROR
;
6042 release_sock_fd( s
, fd
);
6045 TRACE("Setting socket error, %d\n", wsaErrno());
6046 SetLastError(wsaErrno());
6047 release_sock_fd( s
, fd
);
6049 return SOCKET_ERROR
;
6052 /***********************************************************************
6053 * shutdown (WS2_32.22)
6055 int WINAPI
WS_shutdown(SOCKET s
, int how
)
6057 int fd
, err
= WSAENOTSOCK
;
6058 unsigned int options
= 0, clear_flags
= 0;
6060 fd
= get_sock_fd( s
, 0, &options
);
6061 TRACE("socket %04lx, how 0x%x, options 0x%x\n", s
, how
, options
);
6064 return SOCKET_ERROR
;
6068 case SD_RECEIVE
: /* drop receives */
6069 clear_flags
|= FD_READ
;
6071 case SD_SEND
: /* drop sends */
6072 clear_flags
|= FD_WRITE
;
6074 case SD_BOTH
: /* drop all */
6075 clear_flags
|= FD_READ
|FD_WRITE
;
6078 clear_flags
|= FD_WINE_LISTENING
;
6081 if (!(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
)))
6086 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_READ
);
6089 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_WRITE
);
6093 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_READ
);
6094 if (!err
) err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_WRITE
);
6097 if (err
) goto error
;
6099 else /* non-overlapped mode */
6101 if ( shutdown( fd
, how
) )
6108 release_sock_fd( s
, fd
);
6109 _enable_event( SOCKET2HANDLE(s
), 0, 0, clear_flags
);
6110 if ( how
> 1) WSAAsyncSelect( s
, 0, 0, 0 );
6114 release_sock_fd( s
, fd
);
6115 _enable_event( SOCKET2HANDLE(s
), 0, 0, clear_flags
);
6116 SetLastError( err
);
6117 return SOCKET_ERROR
;
6120 /***********************************************************************
6121 * socket (WS2_32.23)
6123 SOCKET WINAPI
WS_socket(int af
, int type
, int protocol
)
6125 TRACE("af=%d type=%d protocol=%d\n", af
, type
, protocol
);
6127 return WSASocketW( af
, type
, protocol
, NULL
, 0,
6128 get_per_thread_data()->opentype
? 0 : WSA_FLAG_OVERLAPPED
);
6132 /***********************************************************************
6133 * gethostbyaddr (WS2_32.51)
6135 struct WS_hostent
* WINAPI
WS_gethostbyaddr(const char *addr
, int len
, int type
)
6137 struct WS_hostent
*retval
= NULL
;
6138 struct hostent
* host
;
6139 int unixtype
= convert_af_w2u(type
);
6140 const char *paddr
= addr
;
6141 unsigned long loopback
;
6142 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6144 int ebufsize
= 1024;
6145 struct hostent hostentry
;
6146 int locerr
= ENOBUFS
;
6149 /* convert back the magic loopback address if necessary */
6150 if (unixtype
== AF_INET
&& len
== 4 && !memcmp(addr
, magic_loopback_addr
, 4))
6152 loopback
= htonl(INADDR_LOOPBACK
);
6153 paddr
= (char*) &loopback
;
6156 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6158 extrabuf
=HeapAlloc(GetProcessHeap(),0,ebufsize
) ;
6160 int res
= gethostbyaddr_r(paddr
, len
, unixtype
,
6161 &hostentry
, extrabuf
, ebufsize
, &host
, &locerr
);
6162 if (res
!= ERANGE
) break;
6164 extrabuf
=HeapReAlloc(GetProcessHeap(),0,extrabuf
,ebufsize
) ;
6166 if (host
) retval
= WS_dup_he(host
);
6167 else SetLastError((locerr
< 0) ? wsaErrno() : wsaHerrno(locerr
));
6168 HeapFree(GetProcessHeap(),0,extrabuf
);
6170 EnterCriticalSection( &csWSgetXXXbyYYY
);
6171 host
= gethostbyaddr(paddr
, len
, unixtype
);
6172 if (host
) retval
= WS_dup_he(host
);
6173 else SetLastError((h_errno
< 0) ? wsaErrno() : wsaHerrno(h_errno
));
6174 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6176 TRACE("ptr %p, len %d, type %d ret %p\n", addr
, len
, type
, retval
);
6180 /***********************************************************************
6181 * WS_compare_routes_by_metric_asc (INTERNAL)
6183 * Comparison function for qsort(), for sorting two routes (struct route)
6184 * by metric in ascending order.
6186 static int WS_compare_routes_by_metric_asc(const void *left
, const void *right
)
6188 const struct route
*a
= left
, *b
= right
;
6189 if (a
->default_route
&& b
->default_route
)
6190 return a
->default_route
- b
->default_route
;
6191 if (a
->default_route
&& !b
->default_route
)
6193 if (b
->default_route
&& !a
->default_route
)
6195 return a
->metric
- b
->metric
;
6198 /***********************************************************************
6199 * WS_get_local_ips (INTERNAL)
6201 * Returns the list of local IP addresses by going through the network
6202 * adapters and using the local routing table to sort the addresses
6203 * from highest routing priority to lowest routing priority. This
6204 * functionality is inferred from the description for obtaining local
6205 * IP addresses given in the Knowledge Base Article Q160215.
6207 * Please note that the returned hostent is only freed when the thread
6208 * closes and is replaced if another hostent is requested.
6210 static struct WS_hostent
* WS_get_local_ips( char *hostname
)
6212 int numroutes
= 0, i
, j
, default_routes
= 0;
6214 PIP_ADAPTER_INFO adapters
= NULL
, k
;
6215 struct WS_hostent
*hostlist
= NULL
;
6216 PMIB_IPFORWARDTABLE routes
= NULL
;
6217 struct route
*route_addrs
= NULL
;
6218 DWORD adap_size
, route_size
;
6220 /* Obtain the size of the adapter list and routing table, also allocate memory */
6221 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
6223 if (GetIpForwardTable(NULL
, &route_size
, FALSE
) != ERROR_INSUFFICIENT_BUFFER
)
6225 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
6226 routes
= HeapAlloc(GetProcessHeap(), 0, route_size
);
6227 route_addrs
= HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
6228 if (adapters
== NULL
|| routes
== NULL
|| route_addrs
== NULL
)
6230 /* Obtain the adapter list and the full routing table */
6231 if (GetAdaptersInfo(adapters
, &adap_size
) != NO_ERROR
)
6233 if (GetIpForwardTable(routes
, &route_size
, FALSE
) != NO_ERROR
)
6235 /* Store the interface associated with each route */
6236 for (n
= 0; n
< routes
->dwNumEntries
; n
++)
6239 DWORD ifmetric
, ifdefault
= 0;
6240 BOOL exists
= FALSE
;
6242 /* Check if this is a default route (there may be more than one) */
6243 if (!routes
->table
[n
].dwForwardDest
)
6244 ifdefault
= ++default_routes
;
6245 else if (routes
->table
[n
].u1
.ForwardType
!= MIB_IPROUTE_TYPE_DIRECT
)
6247 ifindex
= routes
->table
[n
].dwForwardIfIndex
;
6248 ifmetric
= routes
->table
[n
].dwForwardMetric1
;
6249 /* Only store the lowest valued metric for an interface */
6250 for (j
= 0; j
< numroutes
; j
++)
6252 if (route_addrs
[j
].interface
== ifindex
)
6254 if (route_addrs
[j
].metric
> ifmetric
)
6255 route_addrs
[j
].metric
= ifmetric
;
6261 route_addrs
= HeapReAlloc(GetProcessHeap(), 0, route_addrs
, (numroutes
+1)*sizeof(struct route
));
6262 if (route_addrs
== NULL
)
6263 goto cleanup
; /* Memory allocation error, fail gracefully */
6264 route_addrs
[numroutes
].interface
= ifindex
;
6265 route_addrs
[numroutes
].metric
= ifmetric
;
6266 route_addrs
[numroutes
].default_route
= ifdefault
;
6267 /* If no IP is found in the next step (for whatever reason)
6268 * then fall back to the magic loopback address.
6270 memcpy(&(route_addrs
[numroutes
].addr
.s_addr
), magic_loopback_addr
, 4);
6274 goto cleanup
; /* No routes, fall back to the Magic IP */
6275 /* Find the IP address associated with each found interface */
6276 for (i
= 0; i
< numroutes
; i
++)
6278 for (k
= adapters
; k
!= NULL
; k
= k
->Next
)
6280 char *ip
= k
->IpAddressList
.IpAddress
.String
;
6282 if (route_addrs
[i
].interface
== k
->Index
)
6283 route_addrs
[i
].addr
.s_addr
= (in_addr_t
) inet_addr(ip
);
6286 /* Allocate a hostent and enough memory for all the IPs,
6287 * including the NULL at the end of the list.
6289 hostlist
= WS_create_he(hostname
, 1, 0, numroutes
+1, sizeof(struct in_addr
));
6290 if (hostlist
== NULL
)
6291 goto cleanup
; /* Failed to allocate a hostent for the list of IPs */
6292 hostlist
->h_addr_list
[numroutes
] = NULL
; /* NULL-terminate the address list */
6293 hostlist
->h_aliases
[0] = NULL
; /* NULL-terminate the alias list */
6294 hostlist
->h_addrtype
= AF_INET
;
6295 hostlist
->h_length
= sizeof(struct in_addr
); /* = 4 */
6296 /* Reorder the entries before placing them in the host list. Windows expects
6297 * the IP list in order from highest priority to lowest (the critical thing
6298 * is that most applications expect the first IP to be the default route).
6301 qsort(route_addrs
, numroutes
, sizeof(struct route
), WS_compare_routes_by_metric_asc
);
6303 for (i
= 0; i
< numroutes
; i
++)
6304 (*(struct in_addr
*) hostlist
->h_addr_list
[i
]) = route_addrs
[i
].addr
;
6306 /* Cleanup all allocated memory except the address list,
6307 * the address list is used by the calling app.
6310 HeapFree(GetProcessHeap(), 0, route_addrs
);
6311 HeapFree(GetProcessHeap(), 0, adapters
);
6312 HeapFree(GetProcessHeap(), 0, routes
);
6316 /***********************************************************************
6317 * gethostbyname (WS2_32.52)
6319 struct WS_hostent
* WINAPI
WS_gethostbyname(const char* name
)
6321 struct WS_hostent
*retval
= NULL
;
6322 struct hostent
* host
;
6323 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6326 struct hostent hostentry
;
6327 int locerr
= ENOBUFS
;
6331 SetLastError(WSANOTINITIALISED
);
6334 if( gethostname( hostname
, 100) == -1) {
6335 SetLastError(WSAENOBUFS
); /* appropriate ? */
6338 if( !name
|| !name
[0]) {
6341 /* If the hostname of the local machine is requested then return the
6342 * complete list of local IP addresses */
6343 if(strcmp(name
, hostname
) == 0)
6344 retval
= WS_get_local_ips(hostname
);
6345 /* If any other hostname was requested (or the routing table lookup failed)
6346 * then return the IP found by the host OS */
6349 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6351 extrabuf
=HeapAlloc(GetProcessHeap(),0,ebufsize
) ;
6353 int res
= gethostbyname_r(name
, &hostentry
, extrabuf
, ebufsize
, &host
, &locerr
);
6354 if( res
!= ERANGE
) break;
6356 extrabuf
=HeapReAlloc(GetProcessHeap(),0,extrabuf
,ebufsize
) ;
6358 if (!host
) SetLastError((locerr
< 0) ? wsaErrno() : wsaHerrno(locerr
));
6360 EnterCriticalSection( &csWSgetXXXbyYYY
);
6361 host
= gethostbyname(name
);
6362 if (!host
) SetLastError((h_errno
< 0) ? wsaErrno() : wsaHerrno(h_errno
));
6364 if (host
) retval
= WS_dup_he(host
);
6365 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6366 HeapFree(GetProcessHeap(),0,extrabuf
);
6368 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6371 if (retval
&& retval
->h_addr_list
[0][0] == 127 &&
6372 strcmp(name
, "localhost") != 0)
6374 /* hostname != "localhost" but has loopback address. replace by our
6375 * special address.*/
6376 memcpy(retval
->h_addr_list
[0], magic_loopback_addr
, 4);
6378 TRACE( "%s ret %p\n", debugstr_a(name
), retval
);
6383 /***********************************************************************
6384 * getprotobyname (WS2_32.53)
6386 struct WS_protoent
* WINAPI
WS_getprotobyname(const char* name
)
6388 struct WS_protoent
* retval
= NULL
;
6389 #ifdef HAVE_GETPROTOBYNAME
6390 struct protoent
* proto
;
6391 EnterCriticalSection( &csWSgetXXXbyYYY
);
6392 if( (proto
= getprotobyname(name
)) != NULL
)
6394 retval
= WS_dup_pe(proto
);
6397 MESSAGE("protocol %s not found; You might want to add "
6398 "this to /etc/protocols\n", debugstr_a(name
) );
6399 SetLastError(WSANO_DATA
);
6401 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6403 TRACE( "%s ret %p\n", debugstr_a(name
), retval
);
6408 /***********************************************************************
6409 * getprotobynumber (WS2_32.54)
6411 struct WS_protoent
* WINAPI
WS_getprotobynumber(int number
)
6413 struct WS_protoent
* retval
= NULL
;
6414 #ifdef HAVE_GETPROTOBYNUMBER
6415 struct protoent
* proto
;
6416 EnterCriticalSection( &csWSgetXXXbyYYY
);
6417 if( (proto
= getprotobynumber(number
)) != NULL
)
6419 retval
= WS_dup_pe(proto
);
6422 MESSAGE("protocol number %d not found; You might want to add "
6423 "this to /etc/protocols\n", number
);
6424 SetLastError(WSANO_DATA
);
6426 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6428 TRACE("%i ret %p\n", number
, retval
);
6433 /***********************************************************************
6434 * getservbyname (WS2_32.55)
6436 struct WS_servent
* WINAPI
WS_getservbyname(const char *name
, const char *proto
)
6438 struct WS_servent
* retval
= NULL
;
6439 struct servent
* serv
;
6441 char *proto_str
= NULL
;
6443 if (!(name_str
= strdup_lower(name
))) return NULL
;
6445 if (proto
&& *proto
)
6447 if (!(proto_str
= strdup_lower(proto
)))
6449 HeapFree( GetProcessHeap(), 0, name_str
);
6454 EnterCriticalSection( &csWSgetXXXbyYYY
);
6455 serv
= getservbyname(name_str
, proto_str
);
6458 retval
= WS_dup_se(serv
);
6460 else SetLastError(WSANO_DATA
);
6461 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6462 HeapFree( GetProcessHeap(), 0, proto_str
);
6463 HeapFree( GetProcessHeap(), 0, name_str
);
6464 TRACE( "%s, %s ret %p\n", debugstr_a(name
), debugstr_a(proto
), retval
);
6468 /***********************************************************************
6469 * freeaddrinfo (WS2_32.@)
6471 void WINAPI
WS_freeaddrinfo(struct WS_addrinfo
*res
)
6474 struct WS_addrinfo
*next
;
6476 HeapFree(GetProcessHeap(),0,res
->ai_canonname
);
6477 HeapFree(GetProcessHeap(),0,res
->ai_addr
);
6478 next
= res
->ai_next
;
6479 HeapFree(GetProcessHeap(),0,res
);
6484 /* helper functions for getaddrinfo()/getnameinfo() */
6485 static int convert_aiflag_w2u(int winflags
) {
6489 for (i
=0;i
<sizeof(ws_aiflag_map
)/sizeof(ws_aiflag_map
[0]);i
++)
6490 if (ws_aiflag_map
[i
][0] & winflags
) {
6491 unixflags
|= ws_aiflag_map
[i
][1];
6492 winflags
&= ~ws_aiflag_map
[i
][0];
6495 FIXME("Unhandled windows AI_xxx flags 0x%x\n", winflags
);
6499 static int convert_niflag_w2u(int winflags
) {
6503 for (i
=0;i
<sizeof(ws_niflag_map
)/sizeof(ws_niflag_map
[0]);i
++)
6504 if (ws_niflag_map
[i
][0] & winflags
) {
6505 unixflags
|= ws_niflag_map
[i
][1];
6506 winflags
&= ~ws_niflag_map
[i
][0];
6509 FIXME("Unhandled windows NI_xxx flags 0x%x\n", winflags
);
6513 static int convert_aiflag_u2w(int unixflags
) {
6517 for (i
=0;i
<sizeof(ws_aiflag_map
)/sizeof(ws_aiflag_map
[0]);i
++)
6518 if (ws_aiflag_map
[i
][1] & unixflags
) {
6519 winflags
|= ws_aiflag_map
[i
][0];
6520 unixflags
&= ~ws_aiflag_map
[i
][1];
6523 WARN("Unhandled UNIX AI_xxx flags 0x%x\n", unixflags
);
6527 static int convert_eai_u2w(int unixret
) {
6530 if (!unixret
) return 0;
6532 for (i
=0;ws_eai_map
[i
][0];i
++)
6533 if (ws_eai_map
[i
][1] == unixret
)
6534 return ws_eai_map
[i
][0];
6536 if (unixret
== EAI_SYSTEM
)
6537 /* There are broken versions of glibc which return EAI_SYSTEM
6538 * and set errno to 0 instead of returning EAI_NONAME.
6540 return errno
? sock_get_error( errno
) : WS_EAI_NONAME
;
6542 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret
);
6546 static char *get_hostname(void)
6551 GetComputerNameExA( ComputerNamePhysicalDnsHostname
, NULL
, &size
);
6552 if (GetLastError() != ERROR_MORE_DATA
) return NULL
;
6553 if (!(ret
= HeapAlloc( GetProcessHeap(), 0, size
))) return NULL
;
6554 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname
, ret
, &size
))
6556 HeapFree( GetProcessHeap(), 0, ret
);
6562 /***********************************************************************
6563 * getaddrinfo (WS2_32.@)
6565 int WINAPI
WS_getaddrinfo(LPCSTR nodename
, LPCSTR servname
, const struct WS_addrinfo
*hints
, struct WS_addrinfo
**res
)
6567 #ifdef HAVE_GETADDRINFO
6568 struct addrinfo
*unixaires
= NULL
;
6570 struct addrinfo unixhints
, *punixhints
= NULL
;
6575 if (!nodename
&& !servname
)
6577 SetLastError(WSAHOST_NOT_FOUND
);
6578 return WSAHOST_NOT_FOUND
;
6581 hostname
= get_hostname();
6582 if (!hostname
) return WSA_NOT_ENOUGH_MEMORY
;
6586 else if (!nodename
[0])
6591 /* servname tweak required by OSX and BSD kernels */
6592 if (servname
&& !servname
[0]) servname
= "0";
6595 punixhints
= &unixhints
;
6597 memset(&unixhints
, 0, sizeof(unixhints
));
6598 punixhints
->ai_flags
= convert_aiflag_w2u(hints
->ai_flags
);
6600 /* zero is a wildcard, no need to convert */
6601 if (hints
->ai_family
)
6602 punixhints
->ai_family
= convert_af_w2u(hints
->ai_family
);
6603 if (hints
->ai_socktype
)
6604 punixhints
->ai_socktype
= convert_socktype_w2u(hints
->ai_socktype
);
6605 if (hints
->ai_protocol
)
6606 punixhints
->ai_protocol
= max(convert_proto_w2u(hints
->ai_protocol
), 0);
6608 if (punixhints
->ai_socktype
< 0)
6610 SetLastError(WSAESOCKTNOSUPPORT
);
6611 HeapFree(GetProcessHeap(), 0, hostname
);
6612 return SOCKET_ERROR
;
6615 /* windows allows invalid combinations of socket type and protocol, unix does not.
6616 * fix the parameters here to make getaddrinfo call always work */
6617 if (punixhints
->ai_protocol
== IPPROTO_TCP
&&
6618 punixhints
->ai_socktype
!= SOCK_STREAM
&& punixhints
->ai_socktype
!= SOCK_SEQPACKET
)
6619 punixhints
->ai_socktype
= 0;
6621 else if (punixhints
->ai_protocol
== IPPROTO_UDP
&& punixhints
->ai_socktype
!= SOCK_DGRAM
)
6622 punixhints
->ai_socktype
= 0;
6624 else if (IS_IPX_PROTO(punixhints
->ai_protocol
) && punixhints
->ai_socktype
!= SOCK_DGRAM
)
6625 punixhints
->ai_socktype
= 0;
6627 else if (punixhints
->ai_protocol
== IPPROTO_IPV6
)
6628 punixhints
->ai_protocol
= 0;
6631 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
6632 result
= getaddrinfo(node
, servname
, punixhints
, &unixaires
);
6634 if (result
&& !strcmp(hostname
, node
))
6636 /* If it didn't work it means the host name IP is not in /etc/hosts, try again
6637 * by sending a NULL host and avoid sending a NULL servname too because that
6639 ERR_(winediag
)("Failed to resolve your host name IP\n");
6640 result
= getaddrinfo(NULL
, servname
? servname
: "0", punixhints
, &unixaires
);
6642 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename
), debugstr_a(servname
), hints
, res
, result
);
6643 HeapFree(GetProcessHeap(), 0, hostname
);
6646 struct addrinfo
*xuai
= unixaires
;
6647 struct WS_addrinfo
**xai
= res
;
6651 struct WS_addrinfo
*ai
= HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY
, sizeof(struct WS_addrinfo
));
6657 *xai
= ai
;xai
= &ai
->ai_next
;
6658 ai
->ai_flags
= convert_aiflag_u2w(xuai
->ai_flags
);
6659 ai
->ai_family
= convert_af_u2w(xuai
->ai_family
);
6660 /* copy whatever was sent in the hints */
6662 ai
->ai_socktype
= hints
->ai_socktype
;
6663 ai
->ai_protocol
= hints
->ai_protocol
;
6665 ai
->ai_socktype
= convert_socktype_u2w(xuai
->ai_socktype
);
6666 ai
->ai_protocol
= convert_proto_u2w(xuai
->ai_protocol
);
6668 if (xuai
->ai_canonname
) {
6669 TRACE("canon name - %s\n",debugstr_a(xuai
->ai_canonname
));
6670 ai
->ai_canonname
= HeapAlloc(GetProcessHeap(),0,strlen(xuai
->ai_canonname
)+1);
6671 if (!ai
->ai_canonname
)
6673 strcpy(ai
->ai_canonname
,xuai
->ai_canonname
);
6675 len
= xuai
->ai_addrlen
;
6676 ai
->ai_addr
= HeapAlloc(GetProcessHeap(),0,len
);
6679 ai
->ai_addrlen
= len
;
6681 int winlen
= ai
->ai_addrlen
;
6683 if (!ws_sockaddr_u2ws(xuai
->ai_addr
, ai
->ai_addr
, &winlen
)) {
6684 ai
->ai_addrlen
= winlen
;
6688 ai
->ai_addr
= HeapReAlloc(GetProcessHeap(),0,ai
->ai_addr
,len
);
6691 ai
->ai_addrlen
= len
;
6693 xuai
= xuai
->ai_next
;
6695 freeaddrinfo(unixaires
);
6697 if (TRACE_ON(winsock
))
6699 struct WS_addrinfo
*ai
= *res
;
6702 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
6703 ai
, ai
->ai_flags
, ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
, ai
->ai_addrlen
,
6704 ai
->ai_canonname
, debugstr_sockaddr(ai
->ai_addr
));
6709 result
= convert_eai_u2w(result
);
6711 SetLastError(result
);
6715 if (*res
) WS_freeaddrinfo(*res
);
6716 if (unixaires
) freeaddrinfo(unixaires
);
6717 return WSA_NOT_ENOUGH_MEMORY
;
6719 FIXME("getaddrinfo() failed, not found during buildtime.\n");
6724 static struct WS_addrinfoW
*addrinfo_AtoW(const struct WS_addrinfo
*ai
)
6726 struct WS_addrinfoW
*ret
;
6728 if (!(ret
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW
)))) return NULL
;
6729 ret
->ai_flags
= ai
->ai_flags
;
6730 ret
->ai_family
= ai
->ai_family
;
6731 ret
->ai_socktype
= ai
->ai_socktype
;
6732 ret
->ai_protocol
= ai
->ai_protocol
;
6733 ret
->ai_addrlen
= ai
->ai_addrlen
;
6734 ret
->ai_canonname
= NULL
;
6735 ret
->ai_addr
= NULL
;
6736 ret
->ai_next
= NULL
;
6737 if (ai
->ai_canonname
)
6739 int len
= MultiByteToWideChar(CP_ACP
, 0, ai
->ai_canonname
, -1, NULL
, 0);
6740 if (!(ret
->ai_canonname
= HeapAlloc(GetProcessHeap(), 0, len
*sizeof(WCHAR
))))
6742 HeapFree(GetProcessHeap(), 0, ret
);
6745 MultiByteToWideChar(CP_ACP
, 0, ai
->ai_canonname
, -1, ret
->ai_canonname
, len
);
6749 if (!(ret
->ai_addr
= HeapAlloc(GetProcessHeap(), 0, ai
->ai_addrlen
)))
6751 HeapFree(GetProcessHeap(), 0, ret
->ai_canonname
);
6752 HeapFree(GetProcessHeap(), 0, ret
);
6755 memcpy(ret
->ai_addr
, ai
->ai_addr
, ai
->ai_addrlen
);
6760 static struct WS_addrinfoW
*addrinfo_list_AtoW(const struct WS_addrinfo
*info
)
6762 struct WS_addrinfoW
*ret
, *infoW
;
6764 if (!(ret
= infoW
= addrinfo_AtoW(info
))) return NULL
;
6765 while (info
->ai_next
)
6767 if (!(infoW
->ai_next
= addrinfo_AtoW(info
->ai_next
)))
6772 infoW
= infoW
->ai_next
;
6773 info
= info
->ai_next
;
6778 static struct WS_addrinfo
*addrinfo_WtoA(const struct WS_addrinfoW
*ai
)
6780 struct WS_addrinfo
*ret
;
6782 if (!(ret
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo
)))) return NULL
;
6783 ret
->ai_flags
= ai
->ai_flags
;
6784 ret
->ai_family
= ai
->ai_family
;
6785 ret
->ai_socktype
= ai
->ai_socktype
;
6786 ret
->ai_protocol
= ai
->ai_protocol
;
6787 ret
->ai_addrlen
= ai
->ai_addrlen
;
6788 ret
->ai_canonname
= NULL
;
6789 ret
->ai_addr
= NULL
;
6790 ret
->ai_next
= NULL
;
6791 if (ai
->ai_canonname
)
6793 int len
= WideCharToMultiByte(CP_ACP
, 0, ai
->ai_canonname
, -1, NULL
, 0, NULL
, NULL
);
6794 if (!(ret
->ai_canonname
= HeapAlloc(GetProcessHeap(), 0, len
)))
6796 HeapFree(GetProcessHeap(), 0, ret
);
6799 WideCharToMultiByte(CP_ACP
, 0, ai
->ai_canonname
, -1, ret
->ai_canonname
, len
, NULL
, NULL
);
6803 if (!(ret
->ai_addr
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr
))))
6805 HeapFree(GetProcessHeap(), 0, ret
->ai_canonname
);
6806 HeapFree(GetProcessHeap(), 0, ret
);
6809 memcpy(ret
->ai_addr
, ai
->ai_addr
, sizeof(struct WS_sockaddr
));
6814 /***********************************************************************
6815 * GetAddrInfoExW (WS2_32.@)
6817 int WINAPI
GetAddrInfoExW(const WCHAR
*name
, const WCHAR
*servname
, DWORD
namespace, GUID
*namespace_id
,
6818 const ADDRINFOEXW
*hints
, ADDRINFOEXW
**result
, struct timeval
*timeout
, OVERLAPPED
*overlapped
,
6819 LPLOOKUPSERVICE_COMPLETION_ROUTINE completion_routine
, HANDLE
*handle
)
6821 FIXME("(%s %s %x %s %p %p %p %p %p %p)\n", debugstr_w(name
), debugstr_w(servname
), namespace,
6822 debugstr_guid(namespace_id
), hints
, result
, timeout
, overlapped
, completion_routine
, handle
);
6823 return WSAHOST_NOT_FOUND
;
6826 /***********************************************************************
6827 * GetAddrInfoW (WS2_32.@)
6829 int WINAPI
GetAddrInfoW(LPCWSTR nodename
, LPCWSTR servname
, const ADDRINFOW
*hints
, PADDRINFOW
*res
)
6831 int ret
= EAI_MEMORY
, len
, i
;
6832 char *nodenameA
= NULL
, *servnameA
= NULL
;
6833 struct WS_addrinfo
*resA
, *hintsA
= NULL
;
6834 WCHAR
*local_nodenameW
= (WCHAR
*)nodename
;
6836 TRACE("nodename %s, servname %s, hints %p, result %p\n",
6837 debugstr_w(nodename
), debugstr_w(servname
), hints
, res
);
6842 /* Is this an IDN? Most likely if any char is above the Ascii table, this
6843 * is the simplest validation possible, further validation will be done by
6844 * the native getaddrinfo() */
6845 for (i
= 0; nodename
[i
]; i
++)
6847 if (nodename
[i
] > 'z')
6852 if (hints
&& (hints
->ai_flags
& WS_AI_DISABLE_IDN_ENCODING
))
6854 /* Name requires conversion but it was disabled */
6855 ret
= WSAHOST_NOT_FOUND
;
6856 WSASetLastError(ret
);
6860 len
= IdnToAscii(0, nodename
, -1, NULL
, 0);
6863 ERR("Failed to convert %s to punycode\n", debugstr_w(nodename
));
6867 if (!(local_nodenameW
= HeapAlloc(GetProcessHeap(), 0, len
* sizeof(WCHAR
)))) goto end
;
6868 IdnToAscii(0, nodename
, -1, local_nodenameW
, len
);
6871 if (local_nodenameW
)
6873 len
= WideCharToMultiByte(CP_ACP
, 0, local_nodenameW
, -1, NULL
, 0, NULL
, NULL
);
6874 if (!(nodenameA
= HeapAlloc(GetProcessHeap(), 0, len
))) goto end
;
6875 WideCharToMultiByte(CP_ACP
, 0, local_nodenameW
, -1, nodenameA
, len
, NULL
, NULL
);
6879 len
= WideCharToMultiByte(CP_ACP
, 0, servname
, -1, NULL
, 0, NULL
, NULL
);
6880 if (!(servnameA
= HeapAlloc(GetProcessHeap(), 0, len
))) goto end
;
6881 WideCharToMultiByte(CP_ACP
, 0, servname
, -1, servnameA
, len
, NULL
, NULL
);
6884 if (hints
) hintsA
= addrinfo_WtoA(hints
);
6885 ret
= WS_getaddrinfo(nodenameA
, servnameA
, hintsA
, &resA
);
6886 WS_freeaddrinfo(hintsA
);
6890 *res
= addrinfo_list_AtoW(resA
);
6891 WS_freeaddrinfo(resA
);
6895 if (local_nodenameW
!= nodename
)
6896 HeapFree(GetProcessHeap(), 0, local_nodenameW
);
6897 HeapFree(GetProcessHeap(), 0, nodenameA
);
6898 HeapFree(GetProcessHeap(), 0, servnameA
);
6902 /***********************************************************************
6903 * FreeAddrInfoW (WS2_32.@)
6905 void WINAPI
FreeAddrInfoW(PADDRINFOW ai
)
6910 HeapFree(GetProcessHeap(), 0, ai
->ai_canonname
);
6911 HeapFree(GetProcessHeap(), 0, ai
->ai_addr
);
6913 HeapFree(GetProcessHeap(), 0, ai
);
6918 /***********************************************************************
6919 * FreeAddrInfoExW (WS2_32.@)
6921 void WINAPI
FreeAddrInfoExW(ADDRINFOEXW
*ai
)
6926 int WINAPI
WS_getnameinfo(const SOCKADDR
*sa
, WS_socklen_t salen
, PCHAR host
,
6927 DWORD hostlen
, PCHAR serv
, DWORD servlen
, INT flags
)
6929 #ifdef HAVE_GETNAMEINFO
6931 union generic_unix_sockaddr sa_u
;
6934 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa
), salen
, host
, hostlen
,
6935 serv
, servlen
, flags
);
6937 size
= ws_sockaddr_ws2u(sa
, salen
, &sa_u
);
6940 SetLastError(WSAEFAULT
);
6941 return WSA_NOT_ENOUGH_MEMORY
;
6943 ret
= getnameinfo(&sa_u
.addr
, size
, host
, hostlen
, serv
, servlen
, convert_niflag_w2u(flags
));
6944 return convert_eai_u2w(ret
);
6946 FIXME("getnameinfo() failed, not found during buildtime.\n");
6951 int WINAPI
GetNameInfoW(const SOCKADDR
*sa
, WS_socklen_t salen
, PWCHAR host
,
6952 DWORD hostlen
, PWCHAR serv
, DWORD servlen
, INT flags
)
6955 char *hostA
= NULL
, *servA
= NULL
;
6957 if (host
&& (!(hostA
= HeapAlloc(GetProcessHeap(), 0, hostlen
)))) return EAI_MEMORY
;
6958 if (serv
&& (!(servA
= HeapAlloc(GetProcessHeap(), 0, servlen
))))
6960 HeapFree(GetProcessHeap(), 0, hostA
);
6964 ret
= WS_getnameinfo(sa
, salen
, hostA
, hostlen
, servA
, servlen
, flags
);
6967 if (host
) MultiByteToWideChar(CP_ACP
, 0, hostA
, -1, host
, hostlen
);
6968 if (serv
) MultiByteToWideChar(CP_ACP
, 0, servA
, -1, serv
, servlen
);
6971 HeapFree(GetProcessHeap(), 0, hostA
);
6972 HeapFree(GetProcessHeap(), 0, servA
);
6976 /***********************************************************************
6977 * getservbyport (WS2_32.56)
6979 struct WS_servent
* WINAPI
WS_getservbyport(int port
, const char *proto
)
6981 struct WS_servent
* retval
= NULL
;
6982 #ifdef HAVE_GETSERVBYPORT
6983 struct servent
* serv
;
6984 char *proto_str
= NULL
;
6986 if (proto
&& *proto
)
6988 if (!(proto_str
= strdup_lower(proto
))) return NULL
;
6990 EnterCriticalSection( &csWSgetXXXbyYYY
);
6991 if( (serv
= getservbyport(port
, proto_str
)) != NULL
) {
6992 retval
= WS_dup_se(serv
);
6994 else SetLastError(WSANO_DATA
);
6995 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6996 HeapFree( GetProcessHeap(), 0, proto_str
);
6998 TRACE("%d (i.e. port %d), %s ret %p\n", port
, (int)ntohl(port
), debugstr_a(proto
), retval
);
7003 /***********************************************************************
7004 * gethostname (WS2_32.57)
7006 int WINAPI
WS_gethostname(char *name
, int namelen
)
7011 TRACE("name %p, len %d\n", name
, namelen
);
7015 SetLastError(WSAEFAULT
);
7016 return SOCKET_ERROR
;
7019 if (gethostname(buf
, sizeof(buf
)) != 0)
7021 SetLastError(wsaErrno());
7022 return SOCKET_ERROR
;
7025 TRACE("<- '%s'\n", buf
);
7028 WARN("Windows supports NetBIOS name length up to 15 bytes!\n");
7031 SetLastError(WSAEFAULT
);
7032 WARN("<- not enough space for hostname, required %d, got %d!\n", len
+ 1, namelen
);
7033 return SOCKET_ERROR
;
7040 /* ------------------------------------- Windows sockets extensions -- *
7042 * ------------------------------------------------------------------- */
7044 /***********************************************************************
7045 * WSAEnumNetworkEvents (WS2_32.36)
7047 int WINAPI
WSAEnumNetworkEvents(SOCKET s
, WSAEVENT hEvent
, LPWSANETWORKEVENTS lpEvent
)
7051 int errors
[FD_MAX_EVENTS
];
7053 TRACE("%04lx, hEvent %p, lpEvent %p\n", s
, hEvent
, lpEvent
);
7055 SERVER_START_REQ( get_socket_event
)
7057 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
7058 req
->service
= TRUE
;
7059 req
->c_event
= wine_server_obj_handle( hEvent
);
7060 wine_server_set_reply( req
, errors
, sizeof(errors
) );
7061 if (!(ret
= wine_server_call(req
))) lpEvent
->lNetworkEvents
= reply
->pmask
& reply
->mask
;
7066 for (i
= 0; i
< FD_MAX_EVENTS
; i
++)
7067 lpEvent
->iErrorCode
[i
] = NtStatusToWSAError(errors
[i
]);
7070 SetLastError(WSAEINVAL
);
7071 return SOCKET_ERROR
;
7074 /***********************************************************************
7075 * WSAEventSelect (WS2_32.39)
7077 int WINAPI
WSAEventSelect(SOCKET s
, WSAEVENT hEvent
, LONG lEvent
)
7081 TRACE("%04lx, hEvent %p, event %08x\n", s
, hEvent
, lEvent
);
7083 SERVER_START_REQ( set_socket_event
)
7085 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
7087 req
->event
= wine_server_obj_handle( hEvent
);
7090 ret
= wine_server_call( req
);
7094 SetLastError(WSAEINVAL
);
7095 return SOCKET_ERROR
;
7098 /**********************************************************************
7099 * WSAGetOverlappedResult (WS2_32.40)
7101 BOOL WINAPI
WSAGetOverlappedResult( SOCKET s
, LPWSAOVERLAPPED lpOverlapped
,
7102 LPDWORD lpcbTransfer
, BOOL fWait
,
7107 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
7108 s
, lpOverlapped
, lpcbTransfer
, fWait
, lpdwFlags
);
7110 if ( lpOverlapped
== NULL
)
7112 ERR( "Invalid pointer\n" );
7113 SetLastError(WSA_INVALID_PARAMETER
);
7117 status
= lpOverlapped
->Internal
;
7118 if (status
== STATUS_PENDING
)
7122 SetLastError( WSA_IO_INCOMPLETE
);
7126 if (WaitForSingleObject( lpOverlapped
->hEvent
? lpOverlapped
->hEvent
: SOCKET2HANDLE(s
),
7127 INFINITE
) == WAIT_FAILED
)
7129 status
= lpOverlapped
->Internal
;
7133 *lpcbTransfer
= lpOverlapped
->InternalHigh
;
7136 *lpdwFlags
= lpOverlapped
->u
.s
.Offset
;
7138 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
7143 /***********************************************************************
7144 * WSAAsyncSelect (WS2_32.101)
7146 INT WINAPI
WSAAsyncSelect(SOCKET s
, HWND hWnd
, UINT uMsg
, LONG lEvent
)
7150 TRACE("%04lx, hWnd %p, uMsg %08x, event %08x\n", s
, hWnd
, uMsg
, lEvent
);
7152 SERVER_START_REQ( set_socket_event
)
7154 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
7157 req
->window
= wine_server_user_handle( hWnd
);
7159 ret
= wine_server_call( req
);
7163 SetLastError(WSAEINVAL
);
7164 return SOCKET_ERROR
;
7167 /***********************************************************************
7168 * WSACreateEvent (WS2_32.31)
7171 WSAEVENT WINAPI
WSACreateEvent(void)
7173 /* Create a manual-reset event, with initial state: unsignaled */
7176 return CreateEventW(NULL
, TRUE
, FALSE
, NULL
);
7179 /***********************************************************************
7180 * WSACloseEvent (WS2_32.29)
7183 BOOL WINAPI
WSACloseEvent(WSAEVENT event
)
7185 TRACE ("event=%p\n", event
);
7187 return CloseHandle(event
);
7190 /***********************************************************************
7191 * WSASocketA (WS2_32.78)
7194 SOCKET WINAPI
WSASocketA(int af
, int type
, int protocol
,
7195 LPWSAPROTOCOL_INFOA lpProtocolInfo
,
7196 GROUP g
, DWORD dwFlags
)
7199 WSAPROTOCOL_INFOW info
;
7201 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
7202 af
, type
, protocol
, lpProtocolInfo
, g
, dwFlags
);
7204 if (!lpProtocolInfo
) return WSASocketW(af
, type
, protocol
, NULL
, g
, dwFlags
);
7206 memcpy(&info
, lpProtocolInfo
, FIELD_OFFSET(WSAPROTOCOL_INFOW
, szProtocol
));
7207 len
= MultiByteToWideChar(CP_ACP
, 0, lpProtocolInfo
->szProtocol
, -1,
7208 info
.szProtocol
, WSAPROTOCOL_LEN
+ 1);
7212 SetLastError(WSAEINVAL
);
7213 return SOCKET_ERROR
;
7216 return WSASocketW(af
, type
, protocol
, &info
, g
, dwFlags
);
7219 /***********************************************************************
7220 * WSASocketW (WS2_32.79)
7223 SOCKET WINAPI
WSASocketW(int af
, int type
, int protocol
,
7224 LPWSAPROTOCOL_INFOW lpProtocolInfo
,
7225 GROUP g
, DWORD dwFlags
)
7229 int unixaf
, unixtype
, ipxptype
= -1;
7232 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
7233 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
7236 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
7237 af
, type
, protocol
, lpProtocolInfo
, g
, dwFlags
);
7241 err
= WSANOTINITIALISED
;
7245 /* hack for WSADuplicateSocket */
7246 if (lpProtocolInfo
&& lpProtocolInfo
->dwServiceFlags4
== 0xff00ff00) {
7247 ret
= lpProtocolInfo
->dwServiceFlags3
;
7248 TRACE("\tgot duplicate %04lx\n", ret
);
7254 if (af
== FROM_PROTOCOL_INFO
|| !af
)
7255 af
= lpProtocolInfo
->iAddressFamily
;
7256 if (type
== FROM_PROTOCOL_INFO
|| !type
)
7257 type
= lpProtocolInfo
->iSocketType
;
7258 if (protocol
== FROM_PROTOCOL_INFO
|| !protocol
)
7259 protocol
= lpProtocolInfo
->iProtocol
;
7262 if (!type
&& (af
|| protocol
))
7264 int autoproto
= protocol
;
7265 WSAPROTOCOL_INFOW infow
;
7267 /* default to the first valid protocol */
7269 autoproto
= valid_protocols
[0];
7270 else if(IS_IPX_PROTO(autoproto
))
7271 autoproto
= WS_NSPROTO_IPX
;
7273 if (WS_EnterSingleProtocolW(autoproto
, &infow
))
7275 type
= infow
.iSocketType
;
7277 /* after win2003 it's no longer possible to pass AF_UNSPEC
7278 using the protocol info struct */
7279 if (!lpProtocolInfo
&& af
== WS_AF_UNSPEC
)
7280 af
= infow
.iAddressFamily
;
7285 Windows has an extension to the IPX protocol that allows one to create sockets
7286 and set the IPX packet type at the same time, to do that a caller will use
7287 a protocol like NSPROTO_IPX + <PACKET TYPE>
7289 if (IS_IPX_PROTO(protocol
))
7290 ipxptype
= protocol
- WS_NSPROTO_IPX
;
7292 /* convert the socket family, type and protocol */
7293 unixaf
= convert_af_w2u(af
);
7294 unixtype
= convert_socktype_w2u(type
);
7295 protocol
= convert_proto_w2u(protocol
);
7296 if (unixaf
== AF_UNSPEC
) unixaf
= -1;
7298 /* filter invalid parameters */
7301 /* the type could not be converted */
7302 if (type
&& unixtype
< 0)
7304 err
= WSAESOCKTNOSUPPORT
;
7308 err
= WSAEPROTONOSUPPORT
;
7313 /* both family and protocol can't be invalid */
7320 /* family could not be converted and neither socket type */
7321 if (unixtype
< 0 && af
>= 0)
7324 err
= WSAESOCKTNOSUPPORT
;
7328 err
= WSAEAFNOSUPPORT
;
7332 SERVER_START_REQ( create_socket
)
7334 req
->family
= unixaf
;
7335 req
->type
= unixtype
;
7336 req
->protocol
= protocol
;
7337 req
->access
= GENERIC_READ
|GENERIC_WRITE
|SYNCHRONIZE
;
7338 req
->attributes
= (dwFlags
& WSA_FLAG_NO_HANDLE_INHERIT
) ? 0 : OBJ_INHERIT
;
7339 req
->flags
= dwFlags
& ~WSA_FLAG_NO_HANDLE_INHERIT
;
7340 set_error( wine_server_call( req
) );
7341 ret
= HANDLE2SOCKET( wine_server_ptr_handle( reply
->handle
));
7346 TRACE("\tcreated %04lx\n", ret
);
7348 set_ipx_packettype(ret
, ipxptype
);
7350 /* ensure IP_DONTFRAGMENT is disabled, in Linux the global default can be enabled */
7351 if (unixaf
== AF_INET
|| unixaf
== AF_INET6
)
7352 set_dont_fragment(ret
, unixaf
== AF_INET6
? IPPROTO_IPV6
: IPPROTO_IP
, FALSE
);
7355 if (unixaf
== AF_INET6
)
7357 int fd
= get_sock_fd(ret
, 0, NULL
);
7360 /* IPV6_V6ONLY is set by default on Windows */
7362 if (setsockopt(fd
, IPPROTO_IPV6
, IPV6_V6ONLY
, &enable
, sizeof(enable
)))
7363 WARN("\tsetting IPV6_V6ONLY failed - errno = %i\n", errno
);
7364 release_sock_fd(ret
, fd
);
7371 err
= GetLastError();
7372 if (err
== WSAEACCES
) /* raw socket denied */
7374 if (type
== SOCK_RAW
)
7375 ERR_(winediag
)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
7377 ERR_(winediag
)("Failed to create socket, this requires special permissions.\n");
7381 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
7382 if (err
== WSAEINVAL
)
7383 err
= WSAESOCKTNOSUPPORT
;
7384 else if (err
== WSAEOPNOTSUPP
)
7385 err
= WSAEPROTONOSUPPORT
;
7389 WARN("\t\tfailed, error %d!\n", err
);
7391 return INVALID_SOCKET
;
7394 /***********************************************************************
7395 * WSAJoinLeaf (WS2_32.58)
7398 SOCKET WINAPI
WSAJoinLeaf(
7400 const struct WS_sockaddr
*addr
,
7402 LPWSABUF lpCallerData
,
7403 LPWSABUF lpCalleeData
,
7409 return INVALID_SOCKET
;
7412 /***********************************************************************
7413 * __WSAFDIsSet (WS2_32.151)
7415 int WINAPI
__WSAFDIsSet(SOCKET s
, WS_fd_set
*set
)
7417 int i
= set
->fd_count
, ret
= 0;
7420 if (set
->fd_array
[i
] == s
)
7426 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s
, set
, set
->fd_count
, ret
);
7430 /***********************************************************************
7431 * WSAIsBlocking (WS2_32.114)
7433 BOOL WINAPI
WSAIsBlocking(void)
7435 /* By default WinSock should set all its sockets to non-blocking mode
7436 * and poll in PeekMessage loop when processing "blocking" ones. This
7437 * function is supposed to tell if the program is in this loop. Our
7438 * blocking calls are truly blocking so we always return FALSE.
7440 * Note: It is allowed to call this function without prior WSAStartup().
7447 /***********************************************************************
7448 * WSACancelBlockingCall (WS2_32.113)
7450 INT WINAPI
WSACancelBlockingCall(void)
7456 static INT WINAPI
WSA_DefaultBlockingHook( FARPROC x
)
7458 FIXME("How was this called?\n");
7463 /***********************************************************************
7464 * WSASetBlockingHook (WS2_32.109)
7466 FARPROC WINAPI
WSASetBlockingHook(FARPROC lpBlockFunc
)
7468 FARPROC prev
= blocking_hook
;
7469 blocking_hook
= lpBlockFunc
;
7470 TRACE("hook %p\n", lpBlockFunc
);
7475 /***********************************************************************
7476 * WSAUnhookBlockingHook (WS2_32.110)
7478 INT WINAPI
WSAUnhookBlockingHook(void)
7480 blocking_hook
= (FARPROC
)WSA_DefaultBlockingHook
;
7485 /* ----------------------------------- end of API stuff */
7487 /* ----------------------------------- helper functions -
7489 * TODO: Merge WS_dup_..() stuff into one function that
7490 * would operate with a generic structure containing internal
7491 * pointers (via a template of some kind).
7494 static int list_size(char** l
, int item_size
)
7499 j
+= (item_size
) ? item_size
: strlen(l
[i
]) + 1;
7500 j
+= (i
+ 1) * sizeof(char*); }
7504 static int list_dup(char** l_src
, char** l_to
, int item_size
)
7509 for (i
= 0; l_src
[i
]; i
++) ;
7510 p
= (char *)(l_to
+ i
+ 1);
7511 for (i
= 0; l_src
[i
]; i
++)
7513 int count
= ( item_size
) ? item_size
: strlen(l_src
[i
]) + 1;
7514 memcpy(p
, l_src
[i
], count
);
7519 return p
- (char *)l_to
;
7524 /* create a hostent entry
7526 * Creates the entry with enough memory for the name, aliases
7527 * addresses, and the address pointers. Also copies the name
7528 * and sets up all the pointers.
7530 * NOTE: The alias and address lists must be allocated with room
7531 * for the NULL item terminating the list. This is true even if
7532 * the list has no items ("aliases" and "addresses" must be
7533 * at least "1", a truly empty list is invalid).
7535 static struct WS_hostent
*WS_create_he(char *name
, int aliases
, int aliases_size
, int addresses
, int address_length
)
7537 struct WS_hostent
*p_to
;
7539 int size
= (sizeof(struct WS_hostent
) +
7541 sizeof(char *) * aliases
+
7543 sizeof(char *) * addresses
+
7544 address_length
* (addresses
- 1)), i
;
7546 if (!(p_to
= check_buffer_he(size
))) return NULL
;
7547 memset(p_to
, 0, size
);
7549 /* Use the memory in the same way winsock does.
7550 * First set the pointer for aliases, second set the pointers for addresses.
7551 * Third fill the addresses indexes, fourth jump aliases names size.
7552 * Fifth fill the hostname.
7553 * NOTE: This method is valid for OS version's >= XP.
7555 p
= (char *)(p_to
+ 1);
7556 p_to
->h_aliases
= (char **)p
;
7557 p
+= sizeof(char *)*aliases
;
7559 p_to
->h_addr_list
= (char **)p
;
7560 p
+= sizeof(char *)*addresses
;
7562 for (i
= 0, addresses
--; i
< addresses
; i
++, p
+= address_length
)
7563 p_to
->h_addr_list
[i
] = p
;
7565 /* NOTE: h_aliases must be filled in manually because we don't know each string
7566 * size, leave these pointers NULL (already set to NULL by memset earlier).
7576 /* duplicate hostent entry
7577 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
7578 * Ditto for protoent and servent.
7580 static struct WS_hostent
*WS_dup_he(const struct hostent
* p_he
)
7582 int i
, addresses
= 0, alias_size
= 0;
7583 struct WS_hostent
*p_to
;
7586 for( i
= 0; p_he
->h_aliases
[i
]; i
++) alias_size
+= strlen(p_he
->h_aliases
[i
]) + 1;
7587 while (p_he
->h_addr_list
[addresses
]) addresses
++;
7589 p_to
= WS_create_he(p_he
->h_name
, i
+ 1, alias_size
, addresses
+ 1, p_he
->h_length
);
7591 if (!p_to
) return NULL
;
7592 p_to
->h_addrtype
= convert_af_u2w(p_he
->h_addrtype
);
7593 p_to
->h_length
= p_he
->h_length
;
7595 for(i
= 0, p
= p_to
->h_addr_list
[0]; p_he
->h_addr_list
[i
]; i
++, p
+= p_to
->h_length
)
7596 memcpy(p
, p_he
->h_addr_list
[i
], p_to
->h_length
);
7598 /* Fill the aliases after the IP data */
7599 for(i
= 0; p_he
->h_aliases
[i
]; i
++)
7601 p_to
->h_aliases
[i
] = p
;
7602 strcpy(p
, p_he
->h_aliases
[i
]);
7609 /* ----- protoent */
7611 static struct WS_protoent
*WS_dup_pe(const struct protoent
* p_pe
)
7614 struct WS_protoent
*p_to
;
7616 int size
= (sizeof(*p_pe
) +
7617 strlen(p_pe
->p_name
) + 1 +
7618 list_size(p_pe
->p_aliases
, 0));
7620 if (!(p_to
= check_buffer_pe(size
))) return NULL
;
7621 p_to
->p_proto
= p_pe
->p_proto
;
7623 p
= (char *)(p_to
+ 1);
7625 strcpy(p
, p_pe
->p_name
);
7628 p_to
->p_aliases
= (char **)p
;
7629 list_dup(p_pe
->p_aliases
, p_to
->p_aliases
, 0);
7635 static struct WS_servent
*WS_dup_se(const struct servent
* p_se
)
7638 struct WS_servent
*p_to
;
7640 int size
= (sizeof(*p_se
) +
7641 strlen(p_se
->s_proto
) + 1 +
7642 strlen(p_se
->s_name
) + 1 +
7643 list_size(p_se
->s_aliases
, 0));
7645 if (!(p_to
= check_buffer_se(size
))) return NULL
;
7646 p_to
->s_port
= p_se
->s_port
;
7648 p
= (char *)(p_to
+ 1);
7650 strcpy(p
, p_se
->s_name
);
7654 strcpy(p
, p_se
->s_proto
);
7657 p_to
->s_aliases
= (char **)p
;
7658 list_dup(p_se
->s_aliases
, p_to
->s_aliases
, 0);
7663 /***********************************************************************
7664 * WSARecv (WS2_32.67)
7666 int WINAPI
WSARecv(SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
7667 LPDWORD NumberOfBytesReceived
, LPDWORD lpFlags
,
7668 LPWSAOVERLAPPED lpOverlapped
,
7669 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
7671 return WS2_recv_base(s
, lpBuffers
, dwBufferCount
, NumberOfBytesReceived
, lpFlags
,
7672 NULL
, NULL
, lpOverlapped
, lpCompletionRoutine
, NULL
);
7675 static int WS2_recv_base( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
7676 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
,
7677 struct WS_sockaddr
*lpFrom
,
7678 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
7679 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
,
7680 LPWSABUF lpControlBuffer
)
7682 unsigned int i
, options
;
7683 int n
, fd
, err
, overlapped
, flags
;
7684 struct ws2_async
*wsa
= NULL
, localwsa
;
7686 DWORD timeout_start
= GetTickCount();
7687 ULONG_PTR cvalue
= (lpOverlapped
&& ((ULONG_PTR
)lpOverlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)lpOverlapped
: 0;
7689 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
7690 s
, lpBuffers
, dwBufferCount
, *lpFlags
, lpFrom
,
7691 (lpFromlen
? *lpFromlen
: -1),
7692 lpOverlapped
, lpCompletionRoutine
);
7694 fd
= get_sock_fd( s
, FILE_READ_DATA
, &options
);
7695 TRACE( "fd=%d, options=%x\n", fd
, options
);
7697 if (fd
== -1) return SOCKET_ERROR
;
7699 if (*lpFlags
& WS_MSG_OOB
)
7701 /* It's invalid to receive OOB data from an OOBINLINED socket
7702 * as OOB data is turned into normal data. */
7704 if (!getsockopt(fd
, SOL_SOCKET
, SO_OOBINLINE
, (char*) &n
, &i
) && n
)
7711 overlapped
= (lpOverlapped
|| lpCompletionRoutine
) &&
7712 !(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
));
7713 if (overlapped
|| dwBufferCount
> 1)
7715 if (!(wsa
= (struct ws2_async
*)alloc_async_io( offsetof(struct ws2_async
, iovec
[dwBufferCount
]))))
7724 wsa
->hSocket
= SOCKET2HANDLE(s
);
7725 wsa
->flags
= *lpFlags
;
7726 wsa
->lpFlags
= lpFlags
;
7728 wsa
->addrlen
.ptr
= lpFromlen
;
7729 wsa
->control
= lpControlBuffer
;
7730 wsa
->n_iovecs
= dwBufferCount
;
7731 wsa
->first_iovec
= 0;
7732 for (i
= 0; i
< dwBufferCount
; i
++)
7734 /* check buffer first to trigger write watches */
7735 if (IsBadWritePtr( lpBuffers
[i
].buf
, lpBuffers
[i
].len
))
7740 wsa
->iovec
[i
].iov_base
= lpBuffers
[i
].buf
;
7741 wsa
->iovec
[i
].iov_len
= lpBuffers
[i
].len
;
7744 flags
= convert_flags(wsa
->flags
);
7747 n
= WS2_recv( fd
, wsa
, flags
);
7750 /* Unix-like systems return EINVAL when attempting to read OOB data from
7751 * an empty socket buffer, convert that to a Windows expected return. */
7752 if ((flags
& MSG_OOB
) && errno
== EINVAL
)
7753 errno
= EWOULDBLOCK
;
7755 if (errno
!= EAGAIN
)
7757 int loc_errno
= errno
;
7759 if (cvalue
) WS_AddCompletion( s
, cvalue
, sock_get_ntstatus(loc_errno
), 0 );
7763 else if (lpNumberOfBytesRecvd
) *lpNumberOfBytesRecvd
= n
;
7767 IO_STATUS_BLOCK
*iosb
= lpOverlapped
? (IO_STATUS_BLOCK
*)lpOverlapped
: &wsa
->local_iosb
;
7769 wsa
->user_overlapped
= lpOverlapped
;
7770 wsa
->completion_func
= lpCompletionRoutine
;
7771 release_sock_fd( s
, fd
);
7775 iosb
->u
.Status
= STATUS_PENDING
;
7776 iosb
->Information
= 0;
7778 if (wsa
->completion_func
)
7779 err
= register_async( ASYNC_TYPE_READ
, wsa
->hSocket
, WS2_async_recv
, wsa
, NULL
,
7780 ws2_async_apc
, wsa
, iosb
);
7782 err
= register_async( ASYNC_TYPE_READ
, wsa
->hSocket
, WS2_async_recv
, wsa
, lpOverlapped
->hEvent
,
7783 NULL
, (void *)cvalue
, iosb
);
7785 if (err
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
7786 SetLastError(NtStatusToWSAError( err
));
7787 return SOCKET_ERROR
;
7790 iosb
->u
.Status
= STATUS_SUCCESS
;
7791 iosb
->Information
= n
;
7792 if (!wsa
->completion_func
)
7794 if (cvalue
) WS_AddCompletion( s
, cvalue
, STATUS_SUCCESS
, n
);
7795 if (lpOverlapped
->hEvent
) SetEvent( lpOverlapped
->hEvent
);
7796 HeapFree( GetProcessHeap(), 0, wsa
);
7798 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC
)ws2_async_apc
,
7799 (ULONG_PTR
)wsa
, (ULONG_PTR
)iosb
, 0 );
7800 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7806 if ((err
= _is_blocking( s
, &is_blocking
)))
7808 err
= NtStatusToWSAError( err
);
7815 int poll_timeout
= -1;
7816 INT64 timeout
= get_rcvsnd_timeo(fd
, TRUE
);
7820 timeout
-= GetTickCount() - timeout_start
;
7821 if (timeout
< 0) poll_timeout
= 0;
7822 else poll_timeout
= timeout
<= INT_MAX
? timeout
: INT_MAX
;
7826 pfd
.events
= POLLIN
;
7827 if (*lpFlags
& WS_MSG_OOB
) pfd
.events
|= POLLPRI
;
7829 if (!poll_timeout
|| !poll( &pfd
, 1, poll_timeout
))
7832 /* a timeout is not fatal */
7833 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7839 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7840 err
= WSAEWOULDBLOCK
;
7845 TRACE(" -> %i bytes\n", n
);
7846 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
7847 release_sock_fd( s
, fd
);
7848 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7849 SetLastError(ERROR_SUCCESS
);
7854 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
7855 release_sock_fd( s
, fd
);
7856 WARN(" -> ERROR %d\n", err
);
7857 SetLastError( err
);
7858 return SOCKET_ERROR
;
7861 /***********************************************************************
7862 * WSARecvFrom (WS2_32.69)
7864 INT WINAPI
WSARecvFrom( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
7865 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
, struct WS_sockaddr
*lpFrom
,
7866 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
7867 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
7870 return WS2_recv_base( s
, lpBuffers
, dwBufferCount
,
7871 lpNumberOfBytesRecvd
, lpFlags
,
7873 lpOverlapped
, lpCompletionRoutine
, NULL
);
7876 /***********************************************************************
7877 * WSCInstallProvider (WS2_32.88)
7879 INT WINAPI
WSCInstallProvider( const LPGUID lpProviderId
,
7880 LPCWSTR lpszProviderDllPath
,
7881 const LPWSAPROTOCOL_INFOW lpProtocolInfoList
,
7882 DWORD dwNumberOfEntries
,
7885 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId
),
7886 debugstr_w(lpszProviderDllPath
), lpProtocolInfoList
,
7887 dwNumberOfEntries
, lpErrno
);
7893 /***********************************************************************
7894 * WSCDeinstallProvider (WS2_32.83)
7896 INT WINAPI
WSCDeinstallProvider(LPGUID lpProviderId
, LPINT lpErrno
)
7898 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId
), lpErrno
);
7904 /***********************************************************************
7905 * WSAAccept (WS2_32.26)
7907 SOCKET WINAPI
WSAAccept( SOCKET s
, struct WS_sockaddr
*addr
, LPINT addrlen
,
7908 LPCONDITIONPROC lpfnCondition
, DWORD_PTR dwCallbackData
)
7912 WSABUF CallerId
, CallerData
, CalleeId
, CalleeData
;
7913 /* QOS SQOS, GQOS; */
7916 SOCKADDR src_addr
, dst_addr
;
7918 TRACE("socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
7919 s
, addr
, addrlen
, lpfnCondition
, dwCallbackData
);
7921 cs
= WS_accept(s
, addr
, addrlen
);
7922 if (cs
== SOCKET_ERROR
) return SOCKET_ERROR
;
7923 if (!lpfnCondition
) return cs
;
7925 if (addr
&& addrlen
)
7927 CallerId
.buf
= (char *)addr
;
7928 CallerId
.len
= *addrlen
;
7932 size
= sizeof(src_addr
);
7933 WS_getpeername(cs
, &src_addr
, &size
);
7934 CallerId
.buf
= (char *)&src_addr
;
7935 CallerId
.len
= size
;
7937 CallerData
.buf
= NULL
;
7940 size
= sizeof(dst_addr
);
7941 WS_getsockname(cs
, &dst_addr
, &size
);
7943 CalleeId
.buf
= (char *)&dst_addr
;
7944 CalleeId
.len
= sizeof(dst_addr
);
7946 ret
= (*lpfnCondition
)(&CallerId
, &CallerData
, NULL
, NULL
,
7947 &CalleeId
, &CalleeData
, &g
, dwCallbackData
);
7954 SERVER_START_REQ( set_socket_deferred
)
7956 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
7957 req
->deferred
= wine_server_obj_handle( SOCKET2HANDLE(cs
) );
7958 if ( !wine_server_call_err ( req
) )
7960 SetLastError( WSATRY_AGAIN
);
7961 WS_closesocket( cs
);
7965 return SOCKET_ERROR
;
7968 SetLastError(WSAECONNREFUSED
);
7969 return SOCKET_ERROR
;
7971 FIXME("Unknown return type from Condition function\n");
7972 SetLastError(WSAENOTSOCK
);
7973 return SOCKET_ERROR
;
7977 /***********************************************************************
7978 * WSADuplicateSocketA (WS2_32.32)
7980 int WINAPI
WSADuplicateSocketA( SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOA lpProtocolInfo
)
7982 return WS_DuplicateSocket(FALSE
, s
, dwProcessId
, (LPWSAPROTOCOL_INFOW
) lpProtocolInfo
);
7985 /***********************************************************************
7986 * WSADuplicateSocketW (WS2_32.33)
7988 int WINAPI
WSADuplicateSocketW( SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOW lpProtocolInfo
)
7990 return WS_DuplicateSocket(TRUE
, s
, dwProcessId
, lpProtocolInfo
);
7993 /***********************************************************************
7994 * WSAInstallServiceClassA (WS2_32.48)
7996 int WINAPI
WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info
)
7998 FIXME("Request to install service %s\n",debugstr_a(info
->lpszServiceClassName
));
7999 SetLastError(WSAEACCES
);
8000 return SOCKET_ERROR
;
8003 /***********************************************************************
8004 * WSAInstallServiceClassW (WS2_32.49)
8006 int WINAPI
WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info
)
8008 FIXME("Request to install service %s\n",debugstr_w(info
->lpszServiceClassName
));
8009 SetLastError(WSAEACCES
);
8010 return SOCKET_ERROR
;
8013 /***********************************************************************
8014 * WSARemoveServiceClass (WS2_32.70)
8016 int WINAPI
WSARemoveServiceClass(LPGUID info
)
8018 FIXME("Request to remove service %s\n", debugstr_guid(info
));
8019 SetLastError(WSATYPE_NOT_FOUND
);
8020 return SOCKET_ERROR
;
8023 /***********************************************************************
8024 * inet_ntop (WS2_32.@)
8026 PCSTR WINAPI
WS_inet_ntop( INT family
, PVOID addr
, PSTR buffer
, SIZE_T len
)
8028 #ifdef HAVE_INET_NTOP
8029 struct WS_in6_addr
*in6
;
8030 struct WS_in_addr
*in
;
8033 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family
, addr
, buffer
, len
);
8036 SetLastError( STATUS_INVALID_PARAMETER
);
8045 pdst
= inet_ntop( AF_INET
, &in
->WS_s_addr
, buffer
, len
);
8051 pdst
= inet_ntop( AF_INET6
, in6
->WS_s6_addr
, buffer
, len
);
8055 SetLastError( WSAEAFNOSUPPORT
);
8059 if (!pdst
) SetLastError( STATUS_INVALID_PARAMETER
);
8062 FIXME( "not supported on this platform\n" );
8063 SetLastError( WSAEAFNOSUPPORT
);
8068 /***********************************************************************
8069 * inet_pton (WS2_32.@)
8071 INT WINAPI
WS_inet_pton( INT family
, PCSTR addr
, PVOID buffer
)
8073 #ifdef HAVE_INET_PTON
8076 TRACE("family %d, addr %s, buffer (%p)\n", family
, debugstr_a(addr
), buffer
);
8078 if (!addr
|| !buffer
)
8080 SetLastError(WSAEFAULT
);
8081 return SOCKET_ERROR
;
8084 unixaf
= convert_af_w2u(family
);
8085 if (unixaf
!= AF_INET
&& unixaf
!= AF_INET6
)
8087 SetLastError(WSAEAFNOSUPPORT
);
8088 return SOCKET_ERROR
;
8091 ret
= inet_pton(unixaf
, addr
, buffer
);
8092 if (ret
== -1) SetLastError(wsaErrno());
8095 FIXME( "not supported on this platform\n" );
8096 SetLastError( WSAEAFNOSUPPORT
);
8097 return SOCKET_ERROR
;
8101 /***********************************************************************
8102 * InetPtonW (WS2_32.@)
8104 INT WINAPI
InetPtonW(INT family
, PCWSTR addr
, PVOID buffer
)
8110 TRACE("family %d, addr %s, buffer (%p)\n", family
, debugstr_w(addr
), buffer
);
8114 SetLastError(WSAEFAULT
);
8115 return SOCKET_ERROR
;
8118 len
= WideCharToMultiByte(CP_ACP
, 0, addr
, -1, NULL
, 0, NULL
, NULL
);
8119 if (!(addrA
= HeapAlloc(GetProcessHeap(), 0, len
)))
8121 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8122 return SOCKET_ERROR
;
8124 WideCharToMultiByte(CP_ACP
, 0, addr
, -1, addrA
, len
, NULL
, NULL
);
8126 ret
= WS_inet_pton(family
, addrA
, buffer
);
8128 HeapFree(GetProcessHeap(), 0, addrA
);
8132 /***********************************************************************
8133 * InetNtopW (WS2_32.@)
8135 PCWSTR WINAPI
InetNtopW(INT family
, PVOID addr
, PWSTR buffer
, SIZE_T len
)
8137 char bufferA
[WS_INET6_ADDRSTRLEN
];
8140 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family
, addr
, buffer
, len
);
8142 if (WS_inet_ntop(family
, addr
, bufferA
, sizeof(bufferA
)))
8144 if (MultiByteToWideChar(CP_ACP
, 0, bufferA
, -1, buffer
, len
))
8147 SetLastError(ERROR_INVALID_PARAMETER
);
8152 /***********************************************************************
8153 * WSAStringToAddressA (WS2_32.80)
8155 INT WINAPI
WSAStringToAddressA(LPSTR AddressString
,
8157 LPWSAPROTOCOL_INFOA lpProtocolInfo
,
8158 LPSOCKADDR lpAddress
,
8159 LPINT lpAddressLength
)
8162 LPSTR workBuffer
=NULL
,ptrPort
;
8164 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString
), AddressFamily
,
8165 lpProtocolInfo
, lpAddress
, lpAddressLength
);
8167 if (!lpAddressLength
|| !lpAddress
) return SOCKET_ERROR
;
8171 SetLastError(WSAEINVAL
);
8172 return SOCKET_ERROR
;
8176 FIXME("ProtocolInfo not implemented.\n");
8178 workBuffer
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
,
8179 strlen(AddressString
) + 1);
8182 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8183 return SOCKET_ERROR
;
8186 strcpy(workBuffer
, AddressString
);
8188 switch(AddressFamily
)
8192 struct in_addr inetaddr
;
8194 /* If lpAddressLength is too small, tell caller the size we need */
8195 if (*lpAddressLength
< sizeof(SOCKADDR_IN
))
8197 *lpAddressLength
= sizeof(SOCKADDR_IN
);
8201 *lpAddressLength
= sizeof(SOCKADDR_IN
);
8202 memset(lpAddress
, 0, sizeof(SOCKADDR_IN
));
8204 ((LPSOCKADDR_IN
)lpAddress
)->sin_family
= WS_AF_INET
;
8206 ptrPort
= strchr(workBuffer
, ':');
8209 /* User may have entered an IPv6 and asked to parse as IPv4 */
8210 if(strchr(ptrPort
+ 1, ':'))
8215 ((LPSOCKADDR_IN
)lpAddress
)->sin_port
= htons(atoi(ptrPort
+1));
8219 if(inet_aton(workBuffer
, &inetaddr
) > 0)
8221 ((LPSOCKADDR_IN
)lpAddress
)->sin_addr
.WS_s_addr
= inetaddr
.s_addr
;
8231 struct in6_addr inetaddr
;
8232 char *ptrAddr
= workBuffer
;
8234 /* If lpAddressLength is too small, tell caller the size we need */
8235 if (*lpAddressLength
< sizeof(SOCKADDR_IN6
))
8237 *lpAddressLength
= sizeof(SOCKADDR_IN6
);
8241 #ifdef HAVE_INET_PTON
8242 *lpAddressLength
= sizeof(SOCKADDR_IN6
);
8243 memset(lpAddress
, 0, sizeof(SOCKADDR_IN6
));
8245 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_family
= WS_AF_INET6
;
8247 /* Valid IPv6 addresses can also be surrounded by [ ], and in this case
8248 * a port number may follow after like in [fd12:3456:7890::1]:12345
8249 * We need to cut the brackets and find the port if any. */
8251 if(*workBuffer
== '[')
8253 ptrPort
= strchr(workBuffer
, ']');
8256 SetLastError(WSAEINVAL
);
8257 return SOCKET_ERROR
;
8260 if (ptrPort
[1] == ':')
8261 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_port
= htons(atoi(ptrPort
+ 2));
8264 ptrAddr
= workBuffer
+ 1;
8267 if(inet_pton(AF_INET6
, ptrAddr
, &inetaddr
) > 0)
8269 memcpy(&((LPSOCKADDR_IN6
)lpAddress
)->sin6_addr
, &inetaddr
,
8270 sizeof(struct in6_addr
));
8274 #endif /* HAVE_INET_PTON */
8280 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
8281 TRACE("Unsupported address family specified: %d.\n", AddressFamily
);
8285 HeapFree(GetProcessHeap(), 0, workBuffer
);
8289 return SOCKET_ERROR
;
8292 /***********************************************************************
8293 * WSAStringToAddressW (WS2_32.81)
8295 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
8296 * If this should be the case, it would be required to map these digits
8297 * to Unicode digits (0-9) using FoldString first.
8299 INT WINAPI
WSAStringToAddressW(LPWSTR AddressString
,
8301 LPWSAPROTOCOL_INFOW lpProtocolInfo
,
8302 LPSOCKADDR lpAddress
,
8303 LPINT lpAddressLength
)
8306 LPSTR workBuffer
=NULL
;
8307 WSAPROTOCOL_INFOA infoA
;
8308 LPWSAPROTOCOL_INFOA lpProtoInfoA
= NULL
;
8310 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString
), AddressFamily
, lpProtocolInfo
,
8311 lpAddress
, lpAddressLength
);
8313 if (!lpAddressLength
|| !lpAddress
) return SOCKET_ERROR
;
8315 /* if ProtocolInfo is available - convert to ANSI variant */
8318 lpProtoInfoA
= &infoA
;
8319 memcpy( lpProtoInfoA
, lpProtocolInfo
, FIELD_OFFSET( WSAPROTOCOL_INFOA
, szProtocol
) );
8321 if (!WideCharToMultiByte( CP_ACP
, 0, lpProtocolInfo
->szProtocol
, -1,
8322 lpProtoInfoA
->szProtocol
, WSAPROTOCOL_LEN
+1, NULL
, NULL
))
8324 SetLastError(WSAEINVAL
);
8325 return SOCKET_ERROR
;
8331 /* Translate AddressString to ANSI code page - assumes that only
8332 standard digits 0-9 are used with this API call */
8333 sBuffer
= WideCharToMultiByte( CP_ACP
, 0, AddressString
, -1, NULL
, 0, NULL
, NULL
);
8334 workBuffer
= HeapAlloc( GetProcessHeap(), 0, sBuffer
);
8338 WideCharToMultiByte( CP_ACP
, 0, AddressString
, -1, workBuffer
, sBuffer
, NULL
, NULL
);
8339 res
= WSAStringToAddressA(workBuffer
,AddressFamily
,lpProtoInfoA
,
8340 lpAddress
,lpAddressLength
);
8341 HeapFree( GetProcessHeap(), 0, workBuffer
);
8345 res
= WSA_NOT_ENOUGH_MEMORY
;
8351 return SOCKET_ERROR
;
8354 /***********************************************************************
8355 * WSAAddressToStringA (WS2_32.27)
8357 * See WSAAddressToStringW
8359 INT WINAPI
WSAAddressToStringA( LPSOCKADDR sockaddr
, DWORD len
,
8360 LPWSAPROTOCOL_INFOA info
, LPSTR string
,
8364 CHAR buffer
[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8367 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr
, len
, info
, string
, lenstr
);
8369 if (!sockaddr
) return SOCKET_ERROR
;
8370 if (!string
|| !lenstr
) return SOCKET_ERROR
;
8372 switch(sockaddr
->sa_family
)
8376 unsigned int long_ip
= ntohl(((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
);
8377 if (len
< sizeof(SOCKADDR_IN
)) return SOCKET_ERROR
;
8378 sprintf( buffer
, "%u.%u.%u.%u:%u",
8379 (long_ip
>> 24) & 0xff,
8380 (long_ip
>> 16) & 0xff,
8381 (long_ip
>> 8) & 0xff,
8383 ntohs( ((SOCKADDR_IN
*)sockaddr
)->sin_port
) );
8385 p
= strchr( buffer
, ':' );
8386 if (!((SOCKADDR_IN
*)sockaddr
)->sin_port
) *p
= 0;
8391 struct WS_sockaddr_in6
*sockaddr6
= (LPSOCKADDR_IN6
) sockaddr
;
8395 if (len
< sizeof(SOCKADDR_IN6
)) return SOCKET_ERROR
;
8396 if ((sockaddr6
->sin6_port
))
8397 strcpy(buffer
, "[");
8398 slen
= strlen(buffer
);
8399 if (!WS_inet_ntop(WS_AF_INET6
, &sockaddr6
->sin6_addr
, &buffer
[slen
], sizeof(buffer
) - slen
))
8401 SetLastError(WSAEINVAL
);
8402 return SOCKET_ERROR
;
8404 if ((sockaddr6
->sin6_scope_id
))
8405 sprintf(buffer
+strlen(buffer
), "%%%u", sockaddr6
->sin6_scope_id
);
8406 if ((sockaddr6
->sin6_port
))
8407 sprintf(buffer
+strlen(buffer
), "]:%u", ntohs(sockaddr6
->sin6_port
));
8412 SetLastError(WSAEINVAL
);
8413 return SOCKET_ERROR
;
8416 size
= strlen( buffer
) + 1;
8421 SetLastError(WSAEFAULT
);
8422 return SOCKET_ERROR
;
8425 TRACE("=> %s,%u bytes\n", debugstr_a(buffer
), size
);
8427 strcpy( string
, buffer
);
8431 /***********************************************************************
8432 * WSAAddressToStringW (WS2_32.28)
8434 * Convert a sockaddr address into a readable address string.
8437 * sockaddr [I] Pointer to a sockaddr structure.
8438 * len [I] Size of the sockaddr structure.
8439 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
8440 * string [I/O] Pointer to a buffer to receive the address string.
8441 * lenstr [I/O] Size of the receive buffer in WCHARs.
8445 * Failure: SOCKET_ERROR
8448 * The 'info' parameter is ignored.
8450 INT WINAPI
WSAAddressToStringW( LPSOCKADDR sockaddr
, DWORD len
,
8451 LPWSAPROTOCOL_INFOW info
, LPWSTR string
,
8456 WCHAR buffer
[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8459 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr
, len
, info
, string
, lenstr
);
8462 ret
= WSAAddressToStringA(sockaddr
, len
, NULL
, bufAddr
, &size
);
8464 if (ret
) return ret
;
8466 MultiByteToWideChar( CP_ACP
, 0, bufAddr
, size
, buffer
, sizeof( buffer
)/sizeof(WCHAR
));
8471 SetLastError(WSAEFAULT
);
8472 return SOCKET_ERROR
;
8475 TRACE("=> %s,%u bytes\n", debugstr_w(buffer
), size
);
8477 lstrcpyW( string
, buffer
);
8481 /***********************************************************************
8482 * WSAEnumNameSpaceProvidersA (WS2_32.34)
8484 INT WINAPI
WSAEnumNameSpaceProvidersA( LPDWORD len
, LPWSANAMESPACE_INFOA buffer
)
8486 FIXME( "(%p %p) Stub!\n", len
, buffer
);
8490 /***********************************************************************
8491 * WSAEnumNameSpaceProvidersW (WS2_32.35)
8493 INT WINAPI
WSAEnumNameSpaceProvidersW( LPDWORD len
, LPWSANAMESPACE_INFOW buffer
)
8495 FIXME( "(%p %p) Stub!\n", len
, buffer
);
8499 /***********************************************************************
8500 * WSAGetQOSByName (WS2_32.41)
8502 BOOL WINAPI
WSAGetQOSByName( SOCKET s
, LPWSABUF lpQOSName
, LPQOS lpQOS
)
8504 FIXME( "(0x%04lx %p %p) Stub!\n", s
, lpQOSName
, lpQOS
);
8508 /***********************************************************************
8509 * WSAGetServiceClassInfoA (WS2_32.42)
8511 INT WINAPI
WSAGetServiceClassInfoA( LPGUID provider
, LPGUID service
, LPDWORD len
,
8512 LPWSASERVICECLASSINFOA info
)
8514 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider
), debugstr_guid(service
),
8516 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8517 return SOCKET_ERROR
;
8520 /***********************************************************************
8521 * WSAGetServiceClassInfoW (WS2_32.43)
8523 INT WINAPI
WSAGetServiceClassInfoW( LPGUID provider
, LPGUID service
, LPDWORD len
,
8524 LPWSASERVICECLASSINFOW info
)
8526 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider
), debugstr_guid(service
),
8528 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8529 return SOCKET_ERROR
;
8532 /***********************************************************************
8533 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
8535 INT WINAPI
WSAGetServiceClassNameByClassIdA( LPGUID
class, LPSTR service
, LPDWORD len
)
8537 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service
, len
);
8538 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8539 return SOCKET_ERROR
;
8542 /***********************************************************************
8543 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
8545 INT WINAPI
WSAGetServiceClassNameByClassIdW( LPGUID
class, LPWSTR service
, LPDWORD len
)
8547 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service
, len
);
8548 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8549 return SOCKET_ERROR
;
8552 /***********************************************************************
8553 * WSALookupServiceBeginA (WS2_32.59)
8555 INT WINAPI
WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions
,
8556 DWORD dwControlFlags
,
8559 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions
, dwControlFlags
,
8561 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8562 return SOCKET_ERROR
;
8565 /***********************************************************************
8566 * WSALookupServiceBeginW (WS2_32.60)
8568 INT WINAPI
WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions
,
8569 DWORD dwControlFlags
,
8572 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions
, dwControlFlags
,
8574 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8575 return SOCKET_ERROR
;
8578 /***********************************************************************
8579 * WSALookupServiceEnd (WS2_32.61)
8581 INT WINAPI
WSALookupServiceEnd( HANDLE lookup
)
8583 FIXME("(%p) Stub!\n", lookup
);
8587 /***********************************************************************
8588 * WSALookupServiceNextA (WS2_32.62)
8590 INT WINAPI
WSALookupServiceNextA( HANDLE lookup
, DWORD flags
, LPDWORD len
, LPWSAQUERYSETA results
)
8592 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup
, flags
, len
, results
);
8593 SetLastError(WSA_E_NO_MORE
);
8594 return SOCKET_ERROR
;
8597 /***********************************************************************
8598 * WSALookupServiceNextW (WS2_32.63)
8600 INT WINAPI
WSALookupServiceNextW( HANDLE lookup
, DWORD flags
, LPDWORD len
, LPWSAQUERYSETW results
)
8602 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup
, flags
, len
, results
);
8603 SetLastError(WSA_E_NO_MORE
);
8604 return SOCKET_ERROR
;
8607 /***********************************************************************
8608 * WSANtohl (WS2_32.64)
8610 INT WINAPI
WSANtohl( SOCKET s
, WS_u_long netlong
, WS_u_long
* lphostlong
)
8612 TRACE( "(%04lx 0x%08x %p)\n", s
, netlong
, lphostlong
);
8614 if (!lphostlong
) return WSAEFAULT
;
8616 *lphostlong
= ntohl( netlong
);
8620 /***********************************************************************
8621 * WSANtohs (WS2_32.65)
8623 INT WINAPI
WSANtohs( SOCKET s
, WS_u_short netshort
, WS_u_short
* lphostshort
)
8625 TRACE( "(%04lx 0x%08x %p)\n", s
, netshort
, lphostshort
);
8627 if (!lphostshort
) return WSAEFAULT
;
8629 *lphostshort
= ntohs( netshort
);
8633 /***********************************************************************
8634 * WSAProviderConfigChange (WS2_32.66)
8636 INT WINAPI
WSAProviderConfigChange( LPHANDLE handle
, LPWSAOVERLAPPED overlapped
,
8637 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
8639 FIXME( "(%p %p %p) Stub!\n", handle
, overlapped
, completion
);
8640 return SOCKET_ERROR
;
8643 /***********************************************************************
8644 * WSARecvDisconnect (WS2_32.68)
8646 INT WINAPI
WSARecvDisconnect( SOCKET s
, LPWSABUF disconnectdata
)
8648 TRACE( "(%04lx %p)\n", s
, disconnectdata
);
8650 return WS_shutdown( s
, SD_RECEIVE
);
8653 /***********************************************************************
8654 * WSASetServiceA (WS2_32.76)
8656 INT WINAPI
WSASetServiceA( LPWSAQUERYSETA query
, WSAESETSERVICEOP operation
, DWORD flags
)
8658 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query
, operation
, flags
);
8662 /***********************************************************************
8663 * WSASetServiceW (WS2_32.77)
8665 INT WINAPI
WSASetServiceW( LPWSAQUERYSETW query
, WSAESETSERVICEOP operation
, DWORD flags
)
8667 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query
, operation
, flags
);
8671 /***********************************************************************
8672 * WSCEnableNSProvider (WS2_32.84)
8674 INT WINAPI
WSCEnableNSProvider( LPGUID provider
, BOOL enable
)
8676 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider
), enable
);
8680 /***********************************************************************
8681 * WSCGetProviderPath (WS2_32.86)
8683 INT WINAPI
WSCGetProviderPath( LPGUID provider
, LPWSTR path
, LPINT len
, LPINT errcode
)
8685 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider
), path
, len
, errcode
);
8687 if (!errcode
|| !provider
|| !len
) return WSAEFAULT
;
8689 *errcode
= WSAEINVAL
;
8690 return SOCKET_ERROR
;
8693 /***********************************************************************
8694 * WSCInstallNameSpace (WS2_32.87)
8696 INT WINAPI
WSCInstallNameSpace( LPWSTR identifier
, LPWSTR path
, DWORD
namespace,
8697 DWORD version
, LPGUID provider
)
8699 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier
), debugstr_w(path
),
8700 namespace, version
, debugstr_guid(provider
) );
8704 /***********************************************************************
8705 * WSCUnInstallNameSpace (WS2_32.89)
8707 INT WINAPI
WSCUnInstallNameSpace( LPGUID lpProviderId
)
8709 FIXME("(%s) Stub!\n", debugstr_guid(lpProviderId
));
8713 /***********************************************************************
8714 * WSCWriteProviderOrder (WS2_32.91)
8716 INT WINAPI
WSCWriteProviderOrder( LPDWORD entry
, DWORD number
)
8718 FIXME("(%p 0x%08x) Stub!\n", entry
, number
);
8722 /***********************************************************************
8723 * WSANSPIoctl (WS2_32.91)
8725 INT WINAPI
WSANSPIoctl( HANDLE hLookup
, DWORD dwControlCode
, LPVOID lpvInBuffer
,
8726 DWORD cbInBuffer
, LPVOID lpvOutBuffer
, DWORD cbOutBuffer
,
8727 LPDWORD lpcbBytesReturned
, LPWSACOMPLETION lpCompletion
)
8729 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup
, dwControlCode
,
8730 lpvInBuffer
, cbInBuffer
, lpvOutBuffer
, cbOutBuffer
, lpcbBytesReturned
, lpCompletion
);
8731 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8732 return SOCKET_ERROR
;
8735 /*****************************************************************************
8736 * WSAEnumProtocolsA [WS2_32.@]
8738 * see function WSAEnumProtocolsW
8740 INT WINAPI
WSAEnumProtocolsA( LPINT protocols
, LPWSAPROTOCOL_INFOA buffer
, LPDWORD len
)
8742 return WS_EnumProtocols( FALSE
, protocols
, (LPWSAPROTOCOL_INFOW
) buffer
, len
);
8745 /*****************************************************************************
8746 * WSAEnumProtocolsW [WS2_32.@]
8748 * Retrieves information about specified set of active network protocols.
8751 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
8752 * retrieves information on all available protocols.
8753 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
8755 * len [I/O] Pointer to a variable specifying buffer size. On output
8756 * the variable holds the number of bytes needed when the
8757 * specified size is too small.
8760 * Success: number of WSAPROTOCOL_INFO structures in buffer.
8761 * Failure: SOCKET_ERROR
8764 * NT4SP5 does not return SPX if protocols == NULL
8767 * - NT4SP5 returns in addition these list of NETBIOS protocols
8768 * (address family 17), each entry two times one for socket type 2 and 5
8770 * iProtocol szProtocol
8771 * 0x80000000 \Device\NwlnkNb
8772 * 0xfffffffa \Device\NetBT_CBENT7
8773 * 0xfffffffb \Device\Nbf_CBENT7
8774 * 0xfffffffc \Device\NetBT_NdisWan5
8775 * 0xfffffffd \Device\NetBT_El9202
8776 * 0xfffffffe \Device\Nbf_El9202
8777 * 0xffffffff \Device\Nbf_NdisWan4
8779 * - there is no check that the operating system supports the returned
8782 INT WINAPI
WSAEnumProtocolsW( LPINT protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
)
8784 return WS_EnumProtocols( TRUE
, protocols
, buffer
, len
);
8787 /*****************************************************************************
8788 * WSCEnumProtocols [WS2_32.@]
8791 * protocols [I] Null-terminated array of iProtocol values.
8792 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
8793 * len [I/O] Size of buffer on input/output.
8794 * errno [O] Error code.
8797 * Success: number of protocols to be reported on.
8798 * Failure: SOCKET_ERROR. error is in errno.
8801 * Doesn't supply info on layered protocols.
8804 INT WINAPI
WSCEnumProtocols( LPINT protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
, LPINT err
)
8806 INT ret
= WSAEnumProtocolsW( protocols
, buffer
, len
);
8808 if (ret
== SOCKET_ERROR
) *err
= WSAENOBUFS
;