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 ****************************************************************/
473 typedef NTSTATUS
async_callback_t( void *user
, IO_STATUS_BLOCK
*io
, NTSTATUS status
);
477 async_callback_t
*callback
; /* must be the first field */
478 struct ws2_async_io
*next
;
481 struct ws2_async_shutdown
483 struct ws2_async_io io
;
485 IO_STATUS_BLOCK iosb
;
491 struct ws2_async_io io
;
493 LPWSAOVERLAPPED user_overlapped
;
494 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func
;
495 IO_STATUS_BLOCK local_iosb
;
496 struct WS_sockaddr
*addr
;
499 int val
; /* for send operations */
500 int *ptr
; /* for recv operations */
505 unsigned int n_iovecs
;
506 unsigned int first_iovec
;
507 struct iovec iovec
[1];
510 struct ws2_accept_async
512 struct ws2_async_io io
;
513 HANDLE listen_socket
;
514 HANDLE accept_socket
;
515 LPOVERLAPPED user_overlapped
;
517 PVOID buf
; /* buffer to write data to */
521 struct ws2_async
*read
;
524 struct ws2_transmitfile_async
526 struct ws2_async_io io
;
531 DWORD bytes_per_send
;
532 TRANSMIT_FILE_BUFFERS buffers
;
534 LARGE_INTEGER offset
;
535 struct ws2_async write
;
538 static struct ws2_async_io
*async_io_freelist
;
540 static void release_async_io( struct ws2_async_io
*io
)
544 struct ws2_async_io
*next
= async_io_freelist
;
546 if (InterlockedCompareExchangePointer( (void **)&async_io_freelist
, io
, next
) == next
) return;
550 static struct ws2_async_io
*alloc_async_io( DWORD size
, async_callback_t callback
)
552 /* first free remaining previous fileinfos */
554 struct ws2_async_io
*io
= InterlockedExchangePointer( (void **)&async_io_freelist
, NULL
);
558 struct ws2_async_io
*next
= io
->next
;
559 HeapFree( GetProcessHeap(), 0, io
);
563 io
= HeapAlloc( GetProcessHeap(), 0, size
);
564 if (io
) io
->callback
= callback
;
568 static NTSTATUS
register_async( int type
, HANDLE handle
, struct ws2_async_io
*async
, HANDLE event
,
569 PIO_APC_ROUTINE apc
, void *apc_context
, IO_STATUS_BLOCK
*io
)
573 SERVER_START_REQ( register_async
)
576 req
->async
.handle
= wine_server_obj_handle( handle
);
577 req
->async
.user
= wine_server_client_ptr( async
);
578 req
->async
.iosb
= wine_server_client_ptr( io
);
579 req
->async
.event
= wine_server_obj_handle( event
);
580 req
->async
.apc
= wine_server_client_ptr( apc
);
581 req
->async
.apc_context
= wine_server_client_ptr( apc_context
);
582 status
= wine_server_call( req
);
589 /****************************************************************/
591 /* ----------------------------------- internal data */
593 /* ws_... struct conversion flags */
595 typedef struct /* WSAAsyncSelect() control struct */
597 HANDLE service
, event
, sock
;
603 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
604 #define WS_MAX_UDP_DATAGRAM 1024
605 static INT WINAPI
WSA_DefaultBlockingHook( FARPROC x
);
607 /* hostent's, servent's and protent's are stored in one buffer per thread,
608 * as documented on MSDN for the functions that return any of the buffers */
609 struct per_thread_data
612 struct WS_hostent
*he_buffer
;
613 struct WS_servent
*se_buffer
;
614 struct WS_protoent
*pe_buffer
;
615 struct pollfd
*fd_cache
;
616 unsigned int fd_count
;
620 char ntoa_buffer
[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
623 /* internal: routing description information */
627 DWORD metric
, default_route
;
630 static INT num_startup
; /* reference counter */
631 static FARPROC blocking_hook
= (FARPROC
)WSA_DefaultBlockingHook
;
633 /* function prototypes */
634 static struct WS_hostent
*WS_create_he(char *name
, int aliases
, int aliases_size
, int addresses
, int address_length
);
635 static struct WS_hostent
*WS_dup_he(const struct hostent
* p_he
);
636 static struct WS_protoent
*WS_dup_pe(const struct protoent
* p_pe
);
637 static struct WS_servent
*WS_dup_se(const struct servent
* p_se
);
638 static int ws_protocol_info(SOCKET s
, int unicode
, WSAPROTOCOL_INFOW
*buffer
, int *size
);
640 int WSAIOCTL_GetInterfaceCount(void);
641 int WSAIOCTL_GetInterfaceName(int intNumber
, char *intName
);
643 static void WS_AddCompletion( SOCKET sock
, ULONG_PTR CompletionValue
, NTSTATUS CompletionStatus
, ULONG Information
);
645 #define MAP_OPTION(opt) { WS_##opt, opt }
647 static const int ws_flags_map
[][2] =
649 MAP_OPTION( MSG_OOB
),
650 MAP_OPTION( MSG_PEEK
),
651 MAP_OPTION( MSG_DONTROUTE
),
652 MAP_OPTION( MSG_WAITALL
),
653 { WS_MSG_PARTIAL
, 0 },
656 static const int ws_sock_map
[][2] =
658 MAP_OPTION( SO_DEBUG
),
659 MAP_OPTION( SO_ACCEPTCONN
),
660 MAP_OPTION( SO_REUSEADDR
),
661 MAP_OPTION( SO_KEEPALIVE
),
662 MAP_OPTION( SO_DONTROUTE
),
663 MAP_OPTION( SO_BROADCAST
),
664 MAP_OPTION( SO_LINGER
),
665 MAP_OPTION( SO_OOBINLINE
),
666 MAP_OPTION( SO_SNDBUF
),
667 MAP_OPTION( SO_RCVBUF
),
668 MAP_OPTION( SO_ERROR
),
669 MAP_OPTION( SO_TYPE
),
671 MAP_OPTION( SO_RCVTIMEO
),
674 MAP_OPTION( SO_SNDTIMEO
),
678 static const int ws_tcp_map
[][2] =
681 MAP_OPTION( TCP_NODELAY
),
685 static const int ws_ip_map
[][2] =
687 MAP_OPTION( IP_MULTICAST_IF
),
688 MAP_OPTION( IP_MULTICAST_TTL
),
689 MAP_OPTION( IP_MULTICAST_LOOP
),
690 MAP_OPTION( IP_ADD_MEMBERSHIP
),
691 MAP_OPTION( IP_DROP_MEMBERSHIP
),
692 MAP_OPTION( IP_OPTIONS
),
694 MAP_OPTION( IP_HDRINCL
),
696 MAP_OPTION( IP_TOS
),
697 MAP_OPTION( IP_TTL
),
699 MAP_OPTION( IP_PKTINFO
),
702 MAP_OPTION( IP_UNICAST_IF
),
706 static const int ws_ipv6_map
[][2] =
708 #ifdef IPV6_ADD_MEMBERSHIP
709 MAP_OPTION( IPV6_ADD_MEMBERSHIP
),
711 #ifdef IPV6_DROP_MEMBERSHIP
712 MAP_OPTION( IPV6_DROP_MEMBERSHIP
),
714 MAP_OPTION( IPV6_MULTICAST_IF
),
715 MAP_OPTION( IPV6_MULTICAST_HOPS
),
716 MAP_OPTION( IPV6_MULTICAST_LOOP
),
717 MAP_OPTION( IPV6_UNICAST_HOPS
),
718 MAP_OPTION( IPV6_V6ONLY
),
719 #ifdef IPV6_UNICAST_IF
720 MAP_OPTION( IPV6_UNICAST_IF
),
724 static const int ws_af_map
[][2] =
726 MAP_OPTION( AF_UNSPEC
),
727 MAP_OPTION( AF_INET
),
728 MAP_OPTION( AF_INET6
),
730 MAP_OPTION( AF_IPX
),
733 MAP_OPTION( AF_IRDA
),
735 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
738 static const int ws_socktype_map
[][2] =
740 MAP_OPTION( SOCK_DGRAM
),
741 MAP_OPTION( SOCK_STREAM
),
742 MAP_OPTION( SOCK_RAW
),
743 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
746 static const int ws_proto_map
[][2] =
748 MAP_OPTION( IPPROTO_IP
),
749 MAP_OPTION( IPPROTO_TCP
),
750 MAP_OPTION( IPPROTO_UDP
),
751 MAP_OPTION( IPPROTO_IPV6
),
752 MAP_OPTION( IPPROTO_ICMP
),
753 MAP_OPTION( IPPROTO_IGMP
),
754 MAP_OPTION( IPPROTO_RAW
),
755 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
758 static const int ws_aiflag_map
[][2] =
760 MAP_OPTION( AI_PASSIVE
),
761 MAP_OPTION( AI_CANONNAME
),
762 MAP_OPTION( AI_NUMERICHOST
),
763 #ifdef AI_NUMERICSERV
764 MAP_OPTION( AI_NUMERICSERV
),
767 MAP_OPTION( AI_V4MAPPED
),
769 MAP_OPTION( AI_ADDRCONFIG
),
772 static const int ws_niflag_map
[][2] =
774 MAP_OPTION( NI_NOFQDN
),
775 MAP_OPTION( NI_NUMERICHOST
),
776 MAP_OPTION( NI_NAMEREQD
),
777 MAP_OPTION( NI_NUMERICSERV
),
778 MAP_OPTION( NI_DGRAM
),
781 static const int ws_eai_map
[][2] =
783 MAP_OPTION( EAI_AGAIN
),
784 MAP_OPTION( EAI_BADFLAGS
),
785 MAP_OPTION( EAI_FAIL
),
786 MAP_OPTION( EAI_FAMILY
),
787 MAP_OPTION( EAI_MEMORY
),
788 /* Note: EAI_NODATA is deprecated, but still
789 * used by Windows and Linux... We map the newer
790 * EAI_NONAME to EAI_NODATA for now until Windows
794 MAP_OPTION( EAI_NODATA
),
797 { WS_EAI_NODATA
, EAI_NONAME
},
800 MAP_OPTION( EAI_SERVICE
),
801 MAP_OPTION( EAI_SOCKTYPE
),
805 static const int ws_poll_map
[][2] =
807 MAP_OPTION( POLLERR
),
808 MAP_OPTION( POLLHUP
),
809 MAP_OPTION( POLLNVAL
),
810 MAP_OPTION( POLLWRNORM
),
811 MAP_OPTION( POLLWRBAND
),
812 MAP_OPTION( POLLRDNORM
),
813 { WS_POLLRDBAND
, POLLPRI
}
816 static const char magic_loopback_addr
[] = {127, 12, 34, 56};
818 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
820 static inline WSACMSGHDR
*fill_control_message(int level
, int type
, WSACMSGHDR
*current
, ULONG
*maxsize
, void *data
, int len
)
822 ULONG msgsize
= sizeof(WSACMSGHDR
) + WSA_CMSG_ALIGN(len
);
823 char *ptr
= (char *) current
+ sizeof(WSACMSGHDR
);
825 /* Make sure there is at least enough room for this entry */
826 if (msgsize
> *maxsize
)
829 /* Fill in the entry */
830 current
->cmsg_len
= sizeof(WSACMSGHDR
) + len
;
831 current
->cmsg_level
= level
;
832 current
->cmsg_type
= type
;
833 memcpy(ptr
, data
, len
);
834 /* Return the pointer to where next entry should go */
835 return (WSACMSGHDR
*) (ptr
+ WSA_CMSG_ALIGN(len
));
837 #endif /* IP_PKTINFO */
839 static inline int convert_control_headers(struct msghdr
*hdr
, WSABUF
*control
)
842 WSACMSGHDR
*cmsg_win
= (WSACMSGHDR
*) control
->buf
, *ptr
;
843 ULONG ctlsize
= control
->len
;
844 struct cmsghdr
*cmsg_unix
;
847 /* Loop over all the headers, converting as appropriate */
848 for (cmsg_unix
= CMSG_FIRSTHDR(hdr
); cmsg_unix
!= NULL
; cmsg_unix
= CMSG_NXTHDR(hdr
, cmsg_unix
))
850 switch(cmsg_unix
->cmsg_level
)
853 switch(cmsg_unix
->cmsg_type
)
857 /* Convert the Unix IP_PKTINFO structure to the Windows version */
858 struct in_pktinfo
*data_unix
= (struct in_pktinfo
*) CMSG_DATA(cmsg_unix
);
859 struct WS_in_pktinfo data_win
;
861 memcpy(&data_win
.ipi_addr
,&data_unix
->ipi_addr
.s_addr
,4); /* 4 bytes = 32 address bits */
862 data_win
.ipi_ifindex
= data_unix
->ipi_ifindex
;
863 ptr
= fill_control_message(WS_IPPROTO_IP
, WS_IP_PKTINFO
, ptr
, &ctlsize
,
864 (void*)&data_win
, sizeof(data_win
));
865 if (!ptr
) goto error
;
868 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix
->cmsg_type
);
873 FIXME("Unhandled message header level %d\n", cmsg_unix
->cmsg_level
);
879 /* Set the length of the returned control headers */
880 control
->len
= (ptr
== NULL
? 0 : (char*)ptr
- (char*)cmsg_win
);
881 return (ptr
!= NULL
);
882 #else /* IP_PKTINFO */
885 #endif /* IP_PKTINFO */
887 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
889 /* ----------------------------------- error handling */
891 static NTSTATUS
sock_get_ntstatus( int err
)
895 case EBADF
: return STATUS_INVALID_HANDLE
;
896 case EBUSY
: return STATUS_DEVICE_BUSY
;
898 case EACCES
: return STATUS_ACCESS_DENIED
;
899 case EFAULT
: return STATUS_NO_MEMORY
;
900 case EINVAL
: return STATUS_INVALID_PARAMETER
;
902 case EMFILE
: return STATUS_TOO_MANY_OPENED_FILES
;
903 case EWOULDBLOCK
: return STATUS_CANT_WAIT
;
904 case EINPROGRESS
: return STATUS_PENDING
;
905 case EALREADY
: return STATUS_NETWORK_BUSY
;
906 case ENOTSOCK
: return STATUS_OBJECT_TYPE_MISMATCH
;
907 case EDESTADDRREQ
: return STATUS_INVALID_PARAMETER
;
908 case EMSGSIZE
: return STATUS_BUFFER_OVERFLOW
;
909 case EPROTONOSUPPORT
:
910 case ESOCKTNOSUPPORT
:
913 case EPROTOTYPE
: return STATUS_NOT_SUPPORTED
;
914 case ENOPROTOOPT
: return STATUS_INVALID_PARAMETER
;
915 case EOPNOTSUPP
: return STATUS_NOT_SUPPORTED
;
916 case EADDRINUSE
: return STATUS_ADDRESS_ALREADY_ASSOCIATED
;
917 case EADDRNOTAVAIL
: return STATUS_INVALID_PARAMETER
;
918 case ECONNREFUSED
: return STATUS_CONNECTION_REFUSED
;
919 case ESHUTDOWN
: return STATUS_PIPE_DISCONNECTED
;
920 case ENOTCONN
: return STATUS_CONNECTION_DISCONNECTED
;
921 case ETIMEDOUT
: return STATUS_IO_TIMEOUT
;
922 case ENETUNREACH
: return STATUS_NETWORK_UNREACHABLE
;
923 case ENETDOWN
: return STATUS_NETWORK_BUSY
;
925 case ECONNRESET
: return STATUS_CONNECTION_RESET
;
926 case ECONNABORTED
: return STATUS_CONNECTION_ABORTED
;
928 case 0: return STATUS_SUCCESS
;
930 WARN("Unknown errno %d!\n", err
);
931 return STATUS_UNSUCCESSFUL
;
935 static UINT
sock_get_error( int err
)
939 case EINTR
: return WSAEINTR
;
941 case EACCES
: return WSAEACCES
;
942 case EFAULT
: return WSAEFAULT
;
943 case EINVAL
: return WSAEINVAL
;
944 case EMFILE
: return WSAEMFILE
;
945 case EWOULDBLOCK
: return WSAEWOULDBLOCK
;
946 case EINPROGRESS
: return WSAEINPROGRESS
;
947 case EALREADY
: return WSAEALREADY
;
949 case ENOTSOCK
: return WSAENOTSOCK
;
950 case EDESTADDRREQ
: return WSAEDESTADDRREQ
;
951 case EMSGSIZE
: return WSAEMSGSIZE
;
952 case EPROTOTYPE
: return WSAEPROTOTYPE
;
953 case ENOPROTOOPT
: return WSAENOPROTOOPT
;
954 case EPROTONOSUPPORT
: return WSAEPROTONOSUPPORT
;
955 case ESOCKTNOSUPPORT
: return WSAESOCKTNOSUPPORT
;
956 case EOPNOTSUPP
: return WSAEOPNOTSUPP
;
957 case EPFNOSUPPORT
: return WSAEPFNOSUPPORT
;
958 case EAFNOSUPPORT
: return WSAEAFNOSUPPORT
;
959 case EADDRINUSE
: return WSAEADDRINUSE
;
960 case EADDRNOTAVAIL
: return WSAEADDRNOTAVAIL
;
961 case ENETDOWN
: return WSAENETDOWN
;
962 case ENETUNREACH
: return WSAENETUNREACH
;
963 case ENETRESET
: return WSAENETRESET
;
964 case ECONNABORTED
: return WSAECONNABORTED
;
966 case ECONNRESET
: return WSAECONNRESET
;
967 case ENOBUFS
: return WSAENOBUFS
;
968 case EISCONN
: return WSAEISCONN
;
969 case ENOTCONN
: return WSAENOTCONN
;
970 case ESHUTDOWN
: return WSAESHUTDOWN
;
971 case ETOOMANYREFS
: return WSAETOOMANYREFS
;
972 case ETIMEDOUT
: return WSAETIMEDOUT
;
973 case ECONNREFUSED
: return WSAECONNREFUSED
;
974 case ELOOP
: return WSAELOOP
;
975 case ENAMETOOLONG
: return WSAENAMETOOLONG
;
976 case EHOSTDOWN
: return WSAEHOSTDOWN
;
977 case EHOSTUNREACH
: return WSAEHOSTUNREACH
;
978 case ENOTEMPTY
: return WSAENOTEMPTY
;
980 case EPROCLIM
: return WSAEPROCLIM
;
983 case EUSERS
: return WSAEUSERS
;
986 case EDQUOT
: return WSAEDQUOT
;
989 case ESTALE
: return WSAESTALE
;
992 case EREMOTE
: return WSAEREMOTE
;
995 /* just in case we ever get here and there are no problems */
998 WARN("Unknown errno %d!\n", err
);
999 return WSAEOPNOTSUPP
;
1003 static UINT
wsaErrno(void)
1005 int loc_errno
= errno
;
1006 WARN("errno %d, (%s).\n", loc_errno
, strerror(loc_errno
));
1008 return sock_get_error( loc_errno
);
1011 /* most ws2 overlapped functions return an ntstatus-based error code */
1012 static NTSTATUS
wsaErrStatus(void)
1014 int loc_errno
= errno
;
1015 WARN("errno %d, (%s).\n", loc_errno
, strerror(loc_errno
));
1017 return sock_get_ntstatus(loc_errno
);
1020 static UINT
wsaHerrno(int loc_errno
)
1022 WARN("h_errno %d.\n", loc_errno
);
1026 case HOST_NOT_FOUND
: return WSAHOST_NOT_FOUND
;
1027 case TRY_AGAIN
: return WSATRY_AGAIN
;
1028 case NO_RECOVERY
: return WSANO_RECOVERY
;
1029 case NO_DATA
: return WSANO_DATA
;
1030 case ENOBUFS
: return WSAENOBUFS
;
1034 WARN("Unknown h_errno %d!\n", loc_errno
);
1035 return WSAEOPNOTSUPP
;
1039 static inline DWORD
NtStatusToWSAError( const DWORD status
)
1041 /* We only need to cover the status codes set by server async request handling */
1045 case STATUS_SUCCESS
: wserr
= 0; break;
1046 case STATUS_PENDING
: wserr
= WSA_IO_PENDING
; break;
1047 case STATUS_OBJECT_TYPE_MISMATCH
: wserr
= WSAENOTSOCK
; break;
1048 case STATUS_INVALID_HANDLE
: wserr
= WSAEBADF
; break;
1049 case STATUS_INVALID_PARAMETER
: wserr
= WSAEINVAL
; break;
1050 case STATUS_PIPE_DISCONNECTED
: wserr
= WSAESHUTDOWN
; break;
1051 case STATUS_NETWORK_BUSY
: wserr
= WSAEALREADY
; break;
1052 case STATUS_NETWORK_UNREACHABLE
: wserr
= WSAENETUNREACH
; break;
1053 case STATUS_CONNECTION_REFUSED
: wserr
= WSAECONNREFUSED
; break;
1054 case STATUS_CONNECTION_DISCONNECTED
: wserr
= WSAENOTCONN
; break;
1055 case STATUS_CONNECTION_RESET
: wserr
= WSAECONNRESET
; break;
1056 case STATUS_CONNECTION_ABORTED
: wserr
= WSAECONNABORTED
; break;
1057 case STATUS_CANCELLED
: wserr
= WSA_OPERATION_ABORTED
; break;
1058 case STATUS_ADDRESS_ALREADY_ASSOCIATED
: wserr
= WSAEADDRINUSE
; break;
1059 case STATUS_IO_TIMEOUT
:
1060 case STATUS_TIMEOUT
: wserr
= WSAETIMEDOUT
; break;
1061 case STATUS_NO_MEMORY
: wserr
= WSAEFAULT
; break;
1062 case STATUS_ACCESS_DENIED
: wserr
= WSAEACCES
; break;
1063 case STATUS_TOO_MANY_OPENED_FILES
: wserr
= WSAEMFILE
; break;
1064 case STATUS_CANT_WAIT
: wserr
= WSAEWOULDBLOCK
; break;
1065 case STATUS_BUFFER_OVERFLOW
: wserr
= WSAEMSGSIZE
; break;
1066 case STATUS_NOT_SUPPORTED
: wserr
= WSAEOPNOTSUPP
; break;
1067 case STATUS_HOST_UNREACHABLE
: wserr
= WSAEHOSTUNREACH
; break;
1070 wserr
= RtlNtStatusToDosError( status
);
1071 FIXME( "Status code %08x converted to DOS error code %x\n", status
, wserr
);
1076 /* set last error code from NT status without mapping WSA errors */
1077 static inline unsigned int set_error( unsigned int err
)
1081 err
= NtStatusToWSAError( err
);
1082 SetLastError( err
);
1087 static inline int get_sock_fd( SOCKET s
, DWORD access
, unsigned int *options
)
1090 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s
), access
, &fd
, options
) ))
1095 static inline void release_sock_fd( SOCKET s
, int fd
)
1097 wine_server_release_fd( SOCKET2HANDLE(s
), fd
);
1100 static void _enable_event( HANDLE s
, unsigned int event
,
1101 unsigned int sstate
, unsigned int cstate
)
1103 SERVER_START_REQ( enable_socket_event
)
1105 req
->handle
= wine_server_obj_handle( s
);
1107 req
->sstate
= sstate
;
1108 req
->cstate
= cstate
;
1109 wine_server_call( req
);
1114 static NTSTATUS
_is_blocking(SOCKET s
, BOOL
*ret
)
1117 SERVER_START_REQ( get_socket_event
)
1119 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1120 req
->service
= FALSE
;
1122 status
= wine_server_call( req
);
1123 *ret
= (reply
->state
& FD_WINE_NONBLOCKING
) == 0;
1129 static unsigned int _get_sock_mask(SOCKET s
)
1132 SERVER_START_REQ( get_socket_event
)
1134 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1135 req
->service
= FALSE
;
1137 wine_server_call( req
);
1144 static void _sync_sock_state(SOCKET s
)
1147 /* do a dummy wineserver request in order to let
1148 the wineserver run through its select loop once */
1149 (void)_is_blocking(s
, &dummy
);
1152 static void _get_sock_errors(SOCKET s
, int *events
)
1154 SERVER_START_REQ( get_socket_event
)
1156 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1157 req
->service
= FALSE
;
1159 wine_server_set_reply( req
, events
, sizeof(int) * FD_MAX_EVENTS
);
1160 wine_server_call( req
);
1165 static int _get_sock_error(SOCKET s
, unsigned int bit
)
1167 int events
[FD_MAX_EVENTS
];
1168 _get_sock_errors(s
, events
);
1172 static int _get_fd_type(int fd
)
1175 socklen_t optlen
= sizeof(sock_type
);
1176 getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char*) &sock_type
, &optlen
);
1180 static BOOL
set_dont_fragment(SOCKET s
, int level
, BOOL value
)
1184 if (level
== IPPROTO_IP
)
1187 optname
= IP_DONTFRAG
;
1188 #elif defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO) && defined(IP_PMTUDISC_DONT)
1189 optname
= IP_MTU_DISCOVER
;
1190 value
= value
? IP_PMTUDISC_DO
: IP_PMTUDISC_DONT
;
1194 FIXME("IP_DONTFRAGMENT for IPv4 not supported in this platform\n");
1195 return TRUE
; /* fake success */
1200 #ifdef IPV6_DONTFRAG
1201 optname
= IPV6_DONTFRAG
;
1202 #elif defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO) && defined(IPV6_PMTUDISC_DONT)
1203 optname
= IPV6_MTU_DISCOVER
;
1204 value
= value
? IPV6_PMTUDISC_DO
: IPV6_PMTUDISC_DONT
;
1208 FIXME("IP_DONTFRAGMENT for IPv6 not supported in this platform\n");
1209 return TRUE
; /* fake success */
1213 fd
= get_sock_fd(s
, 0, NULL
);
1214 if (fd
== -1) return FALSE
;
1216 if (!setsockopt(fd
, level
, optname
, &value
, sizeof(value
)))
1220 WSASetLastError(wsaErrno());
1224 release_sock_fd(s
, fd
);
1228 static BOOL
get_dont_fragment(SOCKET s
, int level
, BOOL
*out
)
1230 int fd
, optname
, value
, not_expected
;
1231 socklen_t optlen
= sizeof(value
);
1233 if (level
== IPPROTO_IP
)
1236 optname
= IP_DONTFRAG
;
1238 #elif defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
1239 optname
= IP_MTU_DISCOVER
;
1240 not_expected
= IP_PMTUDISC_DONT
;
1244 FIXME("IP_DONTFRAGMENT for IPv4 not supported in this platform\n");
1245 return TRUE
; /* fake success */
1250 #ifdef IPV6_DONTFRAG
1251 optname
= IPV6_DONTFRAG
;
1253 #elif defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DONT)
1254 optname
= IPV6_MTU_DISCOVER
;
1255 not_expected
= IPV6_PMTUDISC_DONT
;
1259 FIXME("IP_DONTFRAGMENT for IPv6 not supported in this platform\n");
1260 return TRUE
; /* fake success */
1264 fd
= get_sock_fd(s
, 0, NULL
);
1265 if (fd
== -1) return FALSE
;
1267 if (!getsockopt(fd
, level
, optname
, &value
, &optlen
))
1269 *out
= value
!= not_expected
;
1274 WSASetLastError(wsaErrno());
1278 release_sock_fd(s
, fd
);
1282 static struct per_thread_data
*get_per_thread_data(void)
1284 struct per_thread_data
* ptb
= NtCurrentTeb()->WinSockData
;
1285 /* lazy initialization */
1288 ptb
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(*ptb
) );
1289 NtCurrentTeb()->WinSockData
= ptb
;
1294 static void free_per_thread_data(void)
1296 struct per_thread_data
* ptb
= NtCurrentTeb()->WinSockData
;
1300 /* delete scratch buffers */
1301 HeapFree( GetProcessHeap(), 0, ptb
->he_buffer
);
1302 HeapFree( GetProcessHeap(), 0, ptb
->se_buffer
);
1303 HeapFree( GetProcessHeap(), 0, ptb
->pe_buffer
);
1304 HeapFree( GetProcessHeap(), 0, ptb
->fd_cache
);
1306 HeapFree( GetProcessHeap(), 0, ptb
);
1307 NtCurrentTeb()->WinSockData
= NULL
;
1310 /***********************************************************************
1311 * DllMain (WS2_32.init)
1313 BOOL WINAPI
DllMain(HINSTANCE hInstDLL
, DWORD fdwReason
, LPVOID fImpLoad
)
1315 TRACE("%p 0x%x %p\n", hInstDLL
, fdwReason
, fImpLoad
);
1316 switch (fdwReason
) {
1317 case DLL_PROCESS_ATTACH
:
1319 case DLL_PROCESS_DETACH
:
1320 if (fImpLoad
) break;
1321 free_per_thread_data();
1322 DeleteCriticalSection(&csWSgetXXXbyYYY
);
1324 case DLL_THREAD_DETACH
:
1325 free_per_thread_data();
1331 /***********************************************************************
1334 * Converts send/recv flags from Windows format.
1335 * Return the converted flag bits, unsupported flags remain unchanged.
1337 static int convert_flags(int flags
)
1340 if (!flags
) return 0;
1342 for (out
= i
= 0; flags
&& i
< sizeof(ws_flags_map
) / sizeof(ws_flags_map
[0]); i
++)
1344 if (ws_flags_map
[i
][0] & flags
)
1346 out
|= ws_flags_map
[i
][1];
1347 flags
&= ~ws_flags_map
[i
][0];
1352 FIXME("Unknown send/recv flags 0x%x, using anyway...\n", flags
);
1358 /***********************************************************************
1361 * Converts socket flags from Windows format.
1362 * Return 1 if converted, 0 if not (error).
1364 static int convert_sockopt(INT
*level
, INT
*optname
)
1370 *level
= SOL_SOCKET
;
1371 for(i
=0; i
<sizeof(ws_sock_map
)/sizeof(ws_sock_map
[0]); i
++) {
1372 if( ws_sock_map
[i
][0] == *optname
)
1374 *optname
= ws_sock_map
[i
][1];
1378 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname
);
1380 case WS_IPPROTO_TCP
:
1381 *level
= IPPROTO_TCP
;
1382 for(i
=0; i
<sizeof(ws_tcp_map
)/sizeof(ws_tcp_map
[0]); i
++) {
1383 if ( ws_tcp_map
[i
][0] == *optname
)
1385 *optname
= ws_tcp_map
[i
][1];
1389 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname
);
1392 *level
= IPPROTO_IP
;
1393 for(i
=0; i
<sizeof(ws_ip_map
)/sizeof(ws_ip_map
[0]); i
++) {
1394 if (ws_ip_map
[i
][0] == *optname
)
1396 *optname
= ws_ip_map
[i
][1];
1400 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname
);
1402 case WS_IPPROTO_IPV6
:
1403 *level
= IPPROTO_IPV6
;
1404 for(i
=0; i
<sizeof(ws_ipv6_map
)/sizeof(ws_ipv6_map
[0]); i
++) {
1405 if (ws_ipv6_map
[i
][0] == *optname
)
1407 *optname
= ws_ipv6_map
[i
][1];
1411 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname
);
1413 default: FIXME("Unimplemented or unknown socket level\n");
1418 /* ----------------------------------- Per-thread info (or per-process?) */
1420 static char *strdup_lower(const char *str
)
1423 char *ret
= HeapAlloc( GetProcessHeap(), 0, strlen(str
) + 1 );
1427 for (i
= 0; str
[i
]; i
++) ret
[i
] = tolower(str
[i
]);
1430 else SetLastError(WSAENOBUFS
);
1434 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1435 * from an fd and return the value converted to milli seconds
1436 * or 0 if there is an infinite time out */
1437 static inline INT64
get_rcvsnd_timeo( int fd
, BOOL is_recv
)
1440 socklen_t len
= sizeof(tv
);
1445 optname
= SO_RCVTIMEO
;
1451 optname
= SO_SNDTIMEO
;
1456 res
= getsockopt(fd
, SOL_SOCKET
, optname
, &tv
, &len
);
1459 return (UINT64
)tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000;
1462 /* utility: given an fd, will block until one of the events occurs */
1463 static inline int do_block( int fd
, int events
, int timeout
)
1469 pfd
.events
= events
;
1471 while ((ret
= poll(&pfd
, 1, timeout
)) < 0)
1482 convert_af_w2u(int windowsaf
) {
1485 for (i
=0;i
<sizeof(ws_af_map
)/sizeof(ws_af_map
[0]);i
++)
1486 if (ws_af_map
[i
][0] == windowsaf
)
1487 return ws_af_map
[i
][1];
1488 FIXME("unhandled Windows address family %d\n", windowsaf
);
1493 convert_af_u2w(int unixaf
) {
1496 for (i
=0;i
<sizeof(ws_af_map
)/sizeof(ws_af_map
[0]);i
++)
1497 if (ws_af_map
[i
][1] == unixaf
)
1498 return ws_af_map
[i
][0];
1499 FIXME("unhandled UNIX address family %d\n", unixaf
);
1504 convert_proto_w2u(int windowsproto
) {
1507 for (i
=0;i
<sizeof(ws_proto_map
)/sizeof(ws_proto_map
[0]);i
++)
1508 if (ws_proto_map
[i
][0] == windowsproto
)
1509 return ws_proto_map
[i
][1];
1511 /* check for extended IPX */
1512 if (IS_IPX_PROTO(windowsproto
))
1513 return windowsproto
;
1515 FIXME("unhandled Windows socket protocol %d\n", windowsproto
);
1520 convert_proto_u2w(int unixproto
) {
1523 for (i
=0;i
<sizeof(ws_proto_map
)/sizeof(ws_proto_map
[0]);i
++)
1524 if (ws_proto_map
[i
][1] == unixproto
)
1525 return ws_proto_map
[i
][0];
1527 /* if value is inside IPX range just return it - the kernel simply
1528 * echoes the value used in the socket() function */
1529 if (IS_IPX_PROTO(unixproto
))
1532 FIXME("unhandled UNIX socket protocol %d\n", unixproto
);
1537 convert_socktype_w2u(int windowssocktype
) {
1540 for (i
=0;i
<sizeof(ws_socktype_map
)/sizeof(ws_socktype_map
[0]);i
++)
1541 if (ws_socktype_map
[i
][0] == windowssocktype
)
1542 return ws_socktype_map
[i
][1];
1543 FIXME("unhandled Windows socket type %d\n", windowssocktype
);
1548 convert_socktype_u2w(int unixsocktype
) {
1551 for (i
=0;i
<sizeof(ws_socktype_map
)/sizeof(ws_socktype_map
[0]);i
++)
1552 if (ws_socktype_map
[i
][1] == unixsocktype
)
1553 return ws_socktype_map
[i
][0];
1554 FIXME("unhandled UNIX socket type %d\n", unixsocktype
);
1558 static int convert_poll_w2u(int events
)
1561 for (i
= ret
= 0; events
&& i
< sizeof(ws_poll_map
) / sizeof(ws_poll_map
[0]); i
++)
1563 if (ws_poll_map
[i
][0] & events
)
1565 ret
|= ws_poll_map
[i
][1];
1566 events
&= ~ws_poll_map
[i
][0];
1571 FIXME("Unsupported WSAPoll() flags 0x%x\n", events
);
1575 static int convert_poll_u2w(int events
)
1578 for (i
= ret
= 0; events
&& i
< sizeof(ws_poll_map
) / sizeof(ws_poll_map
[0]); i
++)
1580 if (ws_poll_map
[i
][1] & events
)
1582 ret
|= ws_poll_map
[i
][0];
1583 events
&= ~ws_poll_map
[i
][1];
1588 FIXME("Unsupported poll() flags 0x%x\n", events
);
1592 static int set_ipx_packettype(int sock
, int ptype
)
1595 int fd
= get_sock_fd( sock
, 0, NULL
), ret
= 0;
1596 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype
, fd
);
1598 if (fd
== -1) return SOCKET_ERROR
;
1600 /* We try to set the ipx type on ipx socket level. */
1602 if(setsockopt(fd
, SOL_IPX
, IPX_TYPE
, &ptype
, sizeof(ptype
)) == -1)
1604 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1610 /* Should we retrieve val using a getsockopt call and then
1611 * set the modified one? */
1613 setsockopt(fd
, 0, SO_DEFAULT_HEADERS
, &val
, sizeof(struct ipx
));
1616 release_sock_fd( sock
, fd
);
1619 WARN("IPX support is not enabled, can't set packet type\n");
1620 return SOCKET_ERROR
;
1624 /* ----------------------------------- API -----
1626 * Init / cleanup / error checking.
1629 /***********************************************************************
1630 * WSAStartup (WS2_32.115)
1632 int WINAPI
WSAStartup(WORD wVersionRequested
, LPWSADATA lpWSAData
)
1634 TRACE("verReq=%x\n", wVersionRequested
);
1636 if (LOBYTE(wVersionRequested
) < 1)
1637 return WSAVERNOTSUPPORTED
;
1639 if (!lpWSAData
) return WSAEINVAL
;
1643 /* that's the whole of the negotiation for now */
1644 lpWSAData
->wVersion
= wVersionRequested
;
1645 /* return winsock information */
1646 lpWSAData
->wHighVersion
= 0x0202;
1647 strcpy(lpWSAData
->szDescription
, "WinSock 2.0" );
1648 strcpy(lpWSAData
->szSystemStatus
, "Running" );
1649 lpWSAData
->iMaxSockets
= WS_MAX_SOCKETS_PER_PROCESS
;
1650 lpWSAData
->iMaxUdpDg
= WS_MAX_UDP_DATAGRAM
;
1651 /* don't do anything with lpWSAData->lpVendorInfo */
1652 /* (some apps don't allocate the space for this field) */
1654 TRACE("succeeded starts: %d\n", num_startup
);
1659 /***********************************************************************
1660 * WSACleanup (WS2_32.116)
1662 INT WINAPI
WSACleanup(void)
1666 TRACE("pending cleanups: %d\n", num_startup
);
1669 SetLastError(WSANOTINITIALISED
);
1670 return SOCKET_ERROR
;
1674 /***********************************************************************
1675 * WSAGetLastError (WS2_32.111)
1677 INT WINAPI
WSAGetLastError(void)
1679 return GetLastError();
1682 /***********************************************************************
1683 * WSASetLastError (WS2_32.112)
1685 void WINAPI
WSASetLastError(INT iError
) {
1686 SetLastError(iError
);
1689 static struct WS_hostent
*check_buffer_he(int size
)
1691 struct per_thread_data
* ptb
= get_per_thread_data();
1694 if (ptb
->he_len
>= size
) return ptb
->he_buffer
;
1695 HeapFree( GetProcessHeap(), 0, ptb
->he_buffer
);
1697 ptb
->he_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->he_len
= size
) );
1698 if (!ptb
->he_buffer
) SetLastError(WSAENOBUFS
);
1699 return ptb
->he_buffer
;
1702 static struct WS_servent
*check_buffer_se(int size
)
1704 struct per_thread_data
* ptb
= get_per_thread_data();
1707 if (ptb
->se_len
>= size
) return ptb
->se_buffer
;
1708 HeapFree( GetProcessHeap(), 0, ptb
->se_buffer
);
1710 ptb
->se_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->se_len
= size
) );
1711 if (!ptb
->se_buffer
) SetLastError(WSAENOBUFS
);
1712 return ptb
->se_buffer
;
1715 static struct WS_protoent
*check_buffer_pe(int size
)
1717 struct per_thread_data
* ptb
= get_per_thread_data();
1720 if (ptb
->pe_len
>= size
) return ptb
->pe_buffer
;
1721 HeapFree( GetProcessHeap(), 0, ptb
->pe_buffer
);
1723 ptb
->pe_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->pe_len
= size
) );
1724 if (!ptb
->pe_buffer
) SetLastError(WSAENOBUFS
);
1725 return ptb
->pe_buffer
;
1728 /* ----------------------------------- i/o APIs */
1730 static inline BOOL
supported_pf(int pf
)
1750 static inline BOOL
supported_protocol(int protocol
)
1753 for (i
= 0; i
< sizeof(valid_protocols
) / sizeof(valid_protocols
[0]); i
++)
1754 if (protocol
== valid_protocols
[i
])
1759 /**********************************************************************/
1761 /* Returns the length of the converted address if successful, 0 if it was too
1762 * small to start with or unknown family or invalid address buffer.
1764 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr
* wsaddr
, int wsaddrlen
,
1765 union generic_unix_sockaddr
*uaddr
)
1767 unsigned int uaddrlen
= 0;
1772 switch (wsaddr
->sa_family
)
1777 const struct WS_sockaddr_ipx
* wsipx
=(const struct WS_sockaddr_ipx
*)wsaddr
;
1778 struct sockaddr_ipx
* uipx
= (struct sockaddr_ipx
*)uaddr
;
1780 if (wsaddrlen
<sizeof(struct WS_sockaddr_ipx
))
1783 uaddrlen
= sizeof(struct sockaddr_ipx
);
1784 memset( uaddr
, 0, uaddrlen
);
1785 uipx
->sipx_family
=AF_IPX
;
1786 uipx
->sipx_port
=wsipx
->sa_socket
;
1787 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1790 memcpy(&uipx
->sipx_network
,wsipx
->sa_netnum
,sizeof(uipx
->sipx_network
)+sizeof(uipx
->sipx_node
));
1791 #ifdef IPX_FRAME_NONE
1792 uipx
->sipx_type
=IPX_FRAME_NONE
;
1798 struct sockaddr_in6
* uin6
= (struct sockaddr_in6
*)uaddr
;
1799 const struct WS_sockaddr_in6
* win6
= (const struct WS_sockaddr_in6
*)wsaddr
;
1801 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1802 * scope_id, one without.
1804 if (wsaddrlen
>= sizeof(struct WS_sockaddr_in6_old
)) {
1805 uaddrlen
= sizeof(struct sockaddr_in6
);
1806 memset( uaddr
, 0, uaddrlen
);
1807 uin6
->sin6_family
= AF_INET6
;
1808 uin6
->sin6_port
= win6
->sin6_port
;
1809 uin6
->sin6_flowinfo
= win6
->sin6_flowinfo
;
1810 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1811 if (wsaddrlen
>= sizeof(struct WS_sockaddr_in6
)) uin6
->sin6_scope_id
= win6
->sin6_scope_id
;
1813 memcpy(&uin6
->sin6_addr
,&win6
->sin6_addr
,16); /* 16 bytes = 128 address bits */
1816 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen
);
1820 struct sockaddr_in
* uin
= (struct sockaddr_in
*)uaddr
;
1821 const struct WS_sockaddr_in
* win
= (const struct WS_sockaddr_in
*)wsaddr
;
1823 if (wsaddrlen
<sizeof(struct WS_sockaddr_in
))
1825 uaddrlen
= sizeof(struct sockaddr_in
);
1826 memset( uaddr
, 0, uaddrlen
);
1827 uin
->sin_family
= AF_INET
;
1828 uin
->sin_port
= win
->sin_port
;
1829 memcpy(&uin
->sin_addr
,&win
->sin_addr
,4); /* 4 bytes = 32 address bits */
1834 struct sockaddr_irda
*uin
= (struct sockaddr_irda
*)uaddr
;
1835 const SOCKADDR_IRDA
*win
= (const SOCKADDR_IRDA
*)wsaddr
;
1837 if (wsaddrlen
< sizeof(SOCKADDR_IRDA
))
1839 uaddrlen
= sizeof(struct sockaddr_irda
);
1840 memset( uaddr
, 0, uaddrlen
);
1841 uin
->sir_family
= AF_IRDA
;
1842 if (!strncmp( win
->irdaServiceName
, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1844 unsigned int lsap_sel
= 0;
1846 sscanf( win
->irdaServiceName
, "LSAP-SEL%u", &lsap_sel
);
1847 uin
->sir_lsap_sel
= lsap_sel
;
1851 uin
->sir_lsap_sel
= LSAP_ANY
;
1852 memcpy( uin
->sir_name
, win
->irdaServiceName
, 25 );
1854 memcpy( &uin
->sir_addr
, win
->irdaDeviceID
, sizeof(uin
->sir_addr
) );
1858 case WS_AF_UNSPEC
: {
1859 /* Try to determine the needed space by the passed windows sockaddr space */
1860 switch (wsaddrlen
) {
1861 default: /* likely an ipv4 address */
1862 case sizeof(struct WS_sockaddr_in
):
1863 uaddrlen
= sizeof(struct sockaddr_in
);
1866 case sizeof(struct WS_sockaddr_ipx
):
1867 uaddrlen
= sizeof(struct sockaddr_ipx
);
1871 case sizeof(SOCKADDR_IRDA
):
1872 uaddrlen
= sizeof(struct sockaddr_irda
);
1875 case sizeof(struct WS_sockaddr_in6
):
1876 case sizeof(struct WS_sockaddr_in6_old
):
1877 uaddrlen
= sizeof(struct sockaddr_in6
);
1880 memset( uaddr
, 0, uaddrlen
);
1884 FIXME("Unknown address family %d, return NULL.\n", wsaddr
->sa_family
);
1890 static BOOL
is_sockaddr_bound(const struct sockaddr
*uaddr
, int uaddrlen
)
1892 switch (uaddr
->sa_family
)
1897 static const struct sockaddr_ipx emptyAddr
;
1898 struct sockaddr_ipx
*ipx
= (struct sockaddr_ipx
*) uaddr
;
1899 return ipx
->sipx_port
1900 || memcmp(&ipx
->sipx_network
, &emptyAddr
.sipx_network
, sizeof(emptyAddr
.sipx_network
))
1901 || memcmp(&ipx
->sipx_node
, &emptyAddr
.sipx_node
, sizeof(emptyAddr
.sipx_node
));
1906 static const struct sockaddr_in6 emptyAddr
;
1907 const struct sockaddr_in6
*in6
= (const struct sockaddr_in6
*) uaddr
;
1908 return in6
->sin6_port
|| memcmp(&in6
->sin6_addr
, &emptyAddr
.sin6_addr
, sizeof(struct in6_addr
));
1912 static const struct sockaddr_in emptyAddr
;
1913 const struct sockaddr_in
*in
= (const struct sockaddr_in
*) uaddr
;
1914 return in
->sin_port
|| memcmp(&in
->sin_addr
, &emptyAddr
.sin_addr
, sizeof(struct in_addr
));
1919 FIXME("unknown address family %d\n", uaddr
->sa_family
);
1924 /* Returns -1 if getsockname fails, 0 if not bound, 1 otherwise */
1925 static int is_fd_bound(int fd
, union generic_unix_sockaddr
*uaddr
, socklen_t
*uaddrlen
)
1927 union generic_unix_sockaddr inaddr
;
1931 if (!uaddr
) uaddr
= &inaddr
;
1932 if (!uaddrlen
) uaddrlen
= &inlen
;
1934 *uaddrlen
= sizeof(inaddr
);
1935 res
= getsockname(fd
, &uaddr
->addr
, uaddrlen
);
1936 if (!res
) res
= is_sockaddr_bound(&uaddr
->addr
, *uaddrlen
);
1940 /* Returns 0 if successful, -1 if the buffer is too small */
1941 static int ws_sockaddr_u2ws(const struct sockaddr
* uaddr
, struct WS_sockaddr
* wsaddr
, int* wsaddrlen
)
1945 switch(uaddr
->sa_family
)
1950 const struct sockaddr_ipx
* uipx
=(const struct sockaddr_ipx
*)uaddr
;
1951 struct WS_sockaddr_ipx
* wsipx
=(struct WS_sockaddr_ipx
*)wsaddr
;
1954 switch (*wsaddrlen
) /* how much can we copy? */
1958 *wsaddrlen
= sizeof(*wsipx
);
1959 wsipx
->sa_socket
=uipx
->sipx_port
;
1963 memcpy(wsipx
->sa_nodenum
,uipx
->sipx_node
,sizeof(wsipx
->sa_nodenum
));
1971 memcpy(wsipx
->sa_netnum
,&uipx
->sipx_network
,sizeof(wsipx
->sa_netnum
));
1977 wsipx
->sa_family
=WS_AF_IPX
;
1989 const struct sockaddr_irda
*uin
= (const struct sockaddr_irda
*)uaddr
;
1990 SOCKADDR_IRDA
*win
= (SOCKADDR_IRDA
*)wsaddr
;
1992 if (*wsaddrlen
< sizeof(SOCKADDR_IRDA
))
1994 win
->irdaAddressFamily
= WS_AF_IRDA
;
1995 memcpy( win
->irdaDeviceID
, &uin
->sir_addr
, sizeof(win
->irdaDeviceID
) );
1996 if (uin
->sir_lsap_sel
!= LSAP_ANY
)
1997 sprintf( win
->irdaServiceName
, "LSAP-SEL%u", uin
->sir_lsap_sel
);
1999 memcpy( win
->irdaServiceName
, uin
->sir_name
,
2000 sizeof(win
->irdaServiceName
) );
2005 const struct sockaddr_in6
* uin6
= (const struct sockaddr_in6
*)uaddr
;
2006 struct WS_sockaddr_in6_old
* win6old
= (struct WS_sockaddr_in6_old
*)wsaddr
;
2008 if (*wsaddrlen
< sizeof(struct WS_sockaddr_in6_old
))
2010 win6old
->sin6_family
= WS_AF_INET6
;
2011 win6old
->sin6_port
= uin6
->sin6_port
;
2012 win6old
->sin6_flowinfo
= uin6
->sin6_flowinfo
;
2013 memcpy(&win6old
->sin6_addr
,&uin6
->sin6_addr
,16); /* 16 bytes = 128 address bits */
2014 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
2015 if (*wsaddrlen
>= sizeof(struct WS_sockaddr_in6
)) {
2016 struct WS_sockaddr_in6
* win6
= (struct WS_sockaddr_in6
*)wsaddr
;
2017 win6
->sin6_scope_id
= uin6
->sin6_scope_id
;
2018 *wsaddrlen
= sizeof(struct WS_sockaddr_in6
);
2021 *wsaddrlen
= sizeof(struct WS_sockaddr_in6_old
);
2023 *wsaddrlen
= sizeof(struct WS_sockaddr_in6_old
);
2028 const struct sockaddr_in
* uin
= (const struct sockaddr_in
*)uaddr
;
2029 struct WS_sockaddr_in
* win
= (struct WS_sockaddr_in
*)wsaddr
;
2031 if (*wsaddrlen
< sizeof(struct WS_sockaddr_in
))
2033 win
->sin_family
= WS_AF_INET
;
2034 win
->sin_port
= uin
->sin_port
;
2035 memcpy(&win
->sin_addr
,&uin
->sin_addr
,4); /* 4 bytes = 32 address bits */
2036 memset(win
->sin_zero
, 0, 8); /* Make sure the null padding is null */
2037 *wsaddrlen
= sizeof(struct WS_sockaddr_in
);
2041 memset(wsaddr
,0,*wsaddrlen
);
2045 FIXME("Unknown address family %d\n", uaddr
->sa_family
);
2051 static INT
WS_DuplicateSocket(BOOL unicode
, SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOW lpProtocolInfo
)
2055 WSAPROTOCOL_INFOW infow
;
2057 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
2058 unicode
, s
, dwProcessId
, lpProtocolInfo
);
2060 if (!ws_protocol_info(s
, unicode
, &infow
, &size
))
2061 return SOCKET_ERROR
;
2063 if (!(hProcess
= OpenProcess(PROCESS_DUP_HANDLE
, FALSE
, dwProcessId
)))
2065 SetLastError(WSAEINVAL
);
2066 return SOCKET_ERROR
;
2069 if (!lpProtocolInfo
)
2071 CloseHandle(hProcess
);
2072 SetLastError(WSAEFAULT
);
2073 return SOCKET_ERROR
;
2076 /* I don't know what the real Windoze does next, this is a hack */
2077 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
2078 * the target use the global duplicate, or we could copy a reference to us to the structure
2079 * and let the target duplicate it from us, but let's do it as simple as possible */
2080 memcpy(lpProtocolInfo
, &infow
, size
);
2081 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s
),
2082 hProcess
, (LPHANDLE
)&lpProtocolInfo
->dwServiceFlags3
,
2083 0, FALSE
, DUPLICATE_SAME_ACCESS
);
2084 CloseHandle(hProcess
);
2085 lpProtocolInfo
->dwServiceFlags4
= 0xff00ff00; /* magic */
2089 /*****************************************************************************
2090 * WS_EnterSingleProtocolW [internal]
2092 * enters the protocol information of one given protocol into the given
2096 * TRUE if a protocol was entered into the buffer.
2099 * - only implemented for IPX, SPX, SPXII, TCP, UDP
2100 * - there is no check that the operating system supports the returned
2103 static BOOL
WS_EnterSingleProtocolW( INT protocol
, WSAPROTOCOL_INFOW
* info
)
2105 memset( info
, 0, sizeof(WSAPROTOCOL_INFOW
) );
2106 info
->iProtocol
= protocol
;
2110 case WS_IPPROTO_TCP
:
2111 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_EXPEDITED_DATA
|
2112 XP1_GRACEFUL_CLOSE
| XP1_GUARANTEED_ORDER
|
2113 XP1_GUARANTEED_DELIVERY
;
2114 info
->ProviderId
= ProviderIdIP
;
2115 info
->dwCatalogEntryId
= 0x3e9;
2116 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2117 info
->ProtocolChain
.ChainLen
= 1;
2119 info
->iAddressFamily
= WS_AF_INET
;
2120 info
->iMaxSockAddr
= 0x10;
2121 info
->iMinSockAddr
= 0x10;
2122 info
->iSocketType
= WS_SOCK_STREAM
;
2123 strcpyW( info
->szProtocol
, NameTcpW
);
2126 case WS_IPPROTO_UDP
:
2127 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_SUPPORT_BROADCAST
|
2128 XP1_SUPPORT_MULTIPOINT
| XP1_MESSAGE_ORIENTED
|
2130 info
->ProviderId
= ProviderIdIP
;
2131 info
->dwCatalogEntryId
= 0x3ea;
2132 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2133 info
->ProtocolChain
.ChainLen
= 1;
2135 info
->iAddressFamily
= WS_AF_INET
;
2136 info
->iMaxSockAddr
= 0x10;
2137 info
->iMinSockAddr
= 0x10;
2138 info
->iSocketType
= WS_SOCK_DGRAM
;
2139 info
->dwMessageSize
= 0xffbb;
2140 strcpyW( info
->szProtocol
, NameUdpW
);
2143 case WS_NSPROTO_IPX
:
2144 info
->dwServiceFlags1
= XP1_PARTIAL_MESSAGE
| XP1_SUPPORT_BROADCAST
|
2145 XP1_SUPPORT_MULTIPOINT
| XP1_MESSAGE_ORIENTED
|
2147 info
->ProviderId
= ProviderIdIPX
;
2148 info
->dwCatalogEntryId
= 0x406;
2149 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2150 info
->ProtocolChain
.ChainLen
= 1;
2152 info
->iAddressFamily
= WS_AF_IPX
;
2153 info
->iMaxSockAddr
= 0x10;
2154 info
->iMinSockAddr
= 0x0e;
2155 info
->iSocketType
= WS_SOCK_DGRAM
;
2156 info
->iProtocolMaxOffset
= 0xff;
2157 info
->dwMessageSize
= 0x240;
2158 strcpyW( info
->szProtocol
, NameIpxW
);
2161 case WS_NSPROTO_SPX
:
2162 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_PSEUDO_STREAM
|
2163 XP1_MESSAGE_ORIENTED
| XP1_GUARANTEED_ORDER
|
2164 XP1_GUARANTEED_DELIVERY
;
2165 info
->ProviderId
= ProviderIdSPX
;
2166 info
->dwCatalogEntryId
= 0x407;
2167 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2168 info
->ProtocolChain
.ChainLen
= 1;
2170 info
->iAddressFamily
= WS_AF_IPX
;
2171 info
->iMaxSockAddr
= 0x10;
2172 info
->iMinSockAddr
= 0x0e;
2173 info
->iSocketType
= WS_SOCK_SEQPACKET
;
2174 info
->dwMessageSize
= 0xffffffff;
2175 strcpyW( info
->szProtocol
, NameSpxW
);
2178 case WS_NSPROTO_SPXII
:
2179 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_GRACEFUL_CLOSE
|
2180 XP1_PSEUDO_STREAM
| XP1_MESSAGE_ORIENTED
|
2181 XP1_GUARANTEED_ORDER
| XP1_GUARANTEED_DELIVERY
;
2182 info
->ProviderId
= ProviderIdSPX
;
2183 info
->dwCatalogEntryId
= 0x409;
2184 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2185 info
->ProtocolChain
.ChainLen
= 1;
2187 info
->iAddressFamily
= WS_AF_IPX
;
2188 info
->iMaxSockAddr
= 0x10;
2189 info
->iMinSockAddr
= 0x0e;
2190 info
->iSocketType
= WS_SOCK_SEQPACKET
;
2191 info
->dwMessageSize
= 0xffffffff;
2192 strcpyW( info
->szProtocol
, NameSpxIIW
);
2196 FIXME("unknown Protocol <0x%08x>\n", protocol
);
2202 /*****************************************************************************
2203 * WS_EnterSingleProtocolA [internal]
2205 * see function WS_EnterSingleProtocolW
2208 static BOOL
WS_EnterSingleProtocolA( INT protocol
, WSAPROTOCOL_INFOA
* info
)
2210 WSAPROTOCOL_INFOW infow
;
2212 memset( info
, 0, sizeof(WSAPROTOCOL_INFOA
) );
2214 ret
= WS_EnterSingleProtocolW( protocol
, &infow
);
2217 /* convert the structure from W to A */
2218 memcpy( info
, &infow
, FIELD_OFFSET( WSAPROTOCOL_INFOA
, szProtocol
) );
2219 WideCharToMultiByte( CP_ACP
, 0, infow
.szProtocol
, -1,
2220 info
->szProtocol
, WSAPROTOCOL_LEN
+1, NULL
, NULL
);
2226 static INT
WS_EnumProtocols( BOOL unicode
, const INT
*protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
)
2228 INT i
= 0, items
= 0;
2232 LPWSAPROTOCOL_INFOA a
;
2233 LPWSAPROTOCOL_INFOW w
;
2237 if (!protocols
) protocols
= valid_protocols
;
2239 while (protocols
[i
])
2241 if(supported_protocol(protocols
[i
++]))
2245 size
= items
* (unicode
? sizeof(WSAPROTOCOL_INFOW
) : sizeof(WSAPROTOCOL_INFOA
));
2247 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
2248 unicode
, protocols
, buffer
, len
, len
? *len
: 0, items
, size
);
2250 if (*len
< size
|| !buffer
)
2253 SetLastError(WSAENOBUFS
);
2254 return SOCKET_ERROR
;
2257 for (i
= items
= 0; protocols
[i
]; i
++)
2259 if (!supported_protocol(protocols
[i
])) continue;
2262 if (WS_EnterSingleProtocolW( protocols
[i
], &info
.w
[items
] ))
2267 if (WS_EnterSingleProtocolA( protocols
[i
], &info
.a
[items
] ))
2274 static BOOL
ws_protocol_info(SOCKET s
, int unicode
, WSAPROTOCOL_INFOW
*buffer
, int *size
)
2278 *size
= unicode
? sizeof(WSAPROTOCOL_INFOW
) : sizeof(WSAPROTOCOL_INFOA
);
2279 memset(buffer
, 0, *size
);
2281 SERVER_START_REQ( get_socket_info
)
2283 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
2284 status
= wine_server_call( req
);
2287 buffer
->iAddressFamily
= convert_af_u2w(reply
->family
);
2288 buffer
->iSocketType
= convert_socktype_u2w(reply
->type
);
2289 buffer
->iProtocol
= convert_proto_u2w(reply
->protocol
);
2296 unsigned int err
= NtStatusToWSAError( status
);
2297 SetLastError( err
== WSAEBADF
? WSAENOTSOCK
: err
);
2302 WS_EnterSingleProtocolW( buffer
->iProtocol
, buffer
);
2304 WS_EnterSingleProtocolA( buffer
->iProtocol
, (WSAPROTOCOL_INFOA
*)buffer
);
2309 /**************************************************************************
2310 * Functions for handling overlapped I/O
2311 **************************************************************************/
2313 /* user APC called upon async completion */
2314 static void WINAPI
ws2_async_apc( void *arg
, IO_STATUS_BLOCK
*iosb
, ULONG reserved
)
2316 struct ws2_async
*wsa
= arg
;
2318 if (wsa
->completion_func
) wsa
->completion_func( NtStatusToWSAError(iosb
->u
.Status
),
2319 iosb
->Information
, wsa
->user_overlapped
,
2321 release_async_io( &wsa
->io
);
2324 /***********************************************************************
2325 * WS2_recv (INTERNAL)
2327 * Workhorse for both synchronous and asynchronous recv() operations.
2329 static int WS2_recv( int fd
, struct ws2_async
*wsa
, int flags
)
2331 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2335 union generic_unix_sockaddr unix_sockaddr
;
2338 hdr
.msg_name
= NULL
;
2342 hdr
.msg_namelen
= sizeof(unix_sockaddr
);
2343 hdr
.msg_name
= &unix_sockaddr
;
2346 hdr
.msg_namelen
= 0;
2348 hdr
.msg_iov
= wsa
->iovec
+ wsa
->first_iovec
;
2349 hdr
.msg_iovlen
= wsa
->n_iovecs
- wsa
->first_iovec
;
2350 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2351 hdr
.msg_accrights
= NULL
;
2352 hdr
.msg_accrightslen
= 0;
2354 hdr
.msg_control
= pktbuf
;
2355 hdr
.msg_controllen
= sizeof(pktbuf
);
2359 while ((n
= recvmsg(fd
, &hdr
, flags
)) == -1)
2365 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2368 ERR("Message control headers cannot be properly supported on this system.\n");
2369 wsa
->control
->len
= 0;
2372 if (wsa
->control
&& !convert_control_headers(&hdr
, wsa
->control
))
2374 WARN("Application passed insufficient room for control headers.\n");
2375 *wsa
->lpFlags
|= WS_MSG_CTRUNC
;
2381 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
2382 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
2384 * quoting linux 2.6 net/ipv4/tcp.c:
2385 * "According to UNIX98, msg_name/msg_namelen are ignored
2386 * on connected socket. I was just happy when found this 8) --ANK"
2388 * likewise MSDN says that lpFrom and lpFromlen are ignored for
2389 * connection-oriented sockets, so don't try to update lpFrom.
2391 if (wsa
->addr
&& hdr
.msg_namelen
)
2392 ws_sockaddr_u2ws( &unix_sockaddr
.addr
, wsa
->addr
, wsa
->addrlen
.ptr
);
2397 /***********************************************************************
2398 * WS2_async_recv (INTERNAL)
2400 * Handler for overlapped recv() operations.
2402 static NTSTATUS
WS2_async_recv( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
2404 struct ws2_async
*wsa
= user
;
2409 case STATUS_ALERTED
:
2410 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, FILE_READ_DATA
, &fd
, NULL
) ))
2413 result
= WS2_recv( fd
, wsa
, convert_flags(wsa
->flags
) );
2414 wine_server_release_fd( wsa
->hSocket
, fd
);
2417 status
= STATUS_SUCCESS
;
2418 _enable_event( wsa
->hSocket
, FD_READ
, 0, 0 );
2422 if (errno
== EAGAIN
)
2424 status
= STATUS_PENDING
;
2425 _enable_event( wsa
->hSocket
, FD_READ
, 0, 0 );
2430 status
= wsaErrStatus();
2435 if (status
!= STATUS_PENDING
)
2437 iosb
->u
.Status
= status
;
2438 iosb
->Information
= result
;
2439 if (!wsa
->completion_func
)
2440 release_async_io( &wsa
->io
);
2445 /***********************************************************************
2446 * WS2_async_accept_recv (INTERNAL)
2448 * This function is used to finish the read part of an accept request. It is
2449 * needed to place the completion on the correct socket (listener).
2451 static NTSTATUS
WS2_async_accept_recv( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
2453 struct ws2_accept_async
*wsa
= user
;
2455 status
= WS2_async_recv( wsa
->read
, iosb
, status
);
2456 if (status
== STATUS_PENDING
)
2460 WS_AddCompletion( HANDLE2SOCKET(wsa
->listen_socket
), wsa
->cvalue
, iosb
->u
.Status
, iosb
->Information
);
2462 release_async_io( &wsa
->io
);
2466 /***********************************************************************
2467 * WS2_async_accept (INTERNAL)
2469 * This is the function called to satisfy the AcceptEx callback
2471 static NTSTATUS
WS2_async_accept( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
2473 struct ws2_accept_async
*wsa
= user
;
2477 TRACE("status: 0x%x listen: %p, accept: %p\n", status
, wsa
->listen_socket
, wsa
->accept_socket
);
2479 if (status
== STATUS_ALERTED
)
2481 SERVER_START_REQ( accept_into_socket
)
2483 req
->lhandle
= wine_server_obj_handle( wsa
->listen_socket
);
2484 req
->ahandle
= wine_server_obj_handle( wsa
->accept_socket
);
2485 status
= wine_server_call( req
);
2489 if (status
== STATUS_CANT_WAIT
)
2490 return STATUS_PENDING
;
2492 if (status
== STATUS_INVALID_HANDLE
)
2494 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2495 status
= STATUS_CANCELLED
;
2498 else if (status
== STATUS_HANDLES_CLOSED
)
2499 status
= STATUS_CANCELLED
; /* strange windows behavior */
2501 if (status
!= STATUS_SUCCESS
)
2504 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2505 addr
= ((char *)wsa
->buf
) + wsa
->data_len
;
2506 len
= wsa
->local_len
- sizeof(int);
2507 WS_getsockname(HANDLE2SOCKET(wsa
->accept_socket
),
2508 (struct WS_sockaddr
*)(addr
+ sizeof(int)), &len
);
2511 addr
+= wsa
->local_len
;
2512 len
= wsa
->remote_len
- sizeof(int);
2513 WS_getpeername(HANDLE2SOCKET(wsa
->accept_socket
),
2514 (struct WS_sockaddr
*)(addr
+ sizeof(int)), &len
);
2520 wsa
->io
.callback
= WS2_async_accept_recv
;
2521 status
= register_async( ASYNC_TYPE_READ
, wsa
->accept_socket
, &wsa
->io
,
2522 wsa
->user_overlapped
->hEvent
, NULL
, NULL
, iosb
);
2524 if (status
!= STATUS_PENDING
)
2527 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2528 * needs to be performed by WS2_async_accept_recv() first. */
2529 return STATUS_MORE_PROCESSING_REQUIRED
;
2532 iosb
->u
.Status
= status
;
2533 iosb
->Information
= 0;
2535 if (wsa
->read
) release_async_io( &wsa
->read
->io
);
2536 release_async_io( &wsa
->io
);
2540 /***********************************************************************
2541 * WS2_send (INTERNAL)
2543 * Workhorse for both synchronous and asynchronous send() operations.
2545 static int WS2_send( int fd
, struct ws2_async
*wsa
, int flags
)
2548 union generic_unix_sockaddr unix_addr
;
2551 hdr
.msg_name
= NULL
;
2552 hdr
.msg_namelen
= 0;
2556 hdr
.msg_name
= &unix_addr
;
2557 hdr
.msg_namelen
= ws_sockaddr_ws2u( wsa
->addr
, wsa
->addrlen
.val
, &unix_addr
);
2558 if ( !hdr
.msg_namelen
)
2564 #if defined(HAS_IPX) && defined(SOL_IPX)
2565 if(wsa
->addr
->sa_family
== WS_AF_IPX
)
2567 struct sockaddr_ipx
* uipx
= (struct sockaddr_ipx
*)hdr
.msg_name
;
2569 socklen_t len
= sizeof(int);
2571 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2572 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2573 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2574 * ipx type in the sockaddr_opx structure with the stored value.
2576 if(getsockopt(fd
, SOL_IPX
, IPX_TYPE
, &val
, &len
) != -1)
2577 uipx
->sipx_type
= val
;
2582 hdr
.msg_iov
= wsa
->iovec
+ wsa
->first_iovec
;
2583 hdr
.msg_iovlen
= wsa
->n_iovecs
- wsa
->first_iovec
;
2584 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2585 hdr
.msg_accrights
= NULL
;
2586 hdr
.msg_accrightslen
= 0;
2588 hdr
.msg_control
= NULL
;
2589 hdr
.msg_controllen
= 0;
2593 while ((ret
= sendmsg(fd
, &hdr
, flags
)) == -1)
2600 while (wsa
->first_iovec
< wsa
->n_iovecs
&& wsa
->iovec
[wsa
->first_iovec
].iov_len
<= n
)
2601 n
-= wsa
->iovec
[wsa
->first_iovec
++].iov_len
;
2602 if (wsa
->first_iovec
< wsa
->n_iovecs
)
2604 wsa
->iovec
[wsa
->first_iovec
].iov_base
= (char*)wsa
->iovec
[wsa
->first_iovec
].iov_base
+ n
;
2605 wsa
->iovec
[wsa
->first_iovec
].iov_len
-= n
;
2610 /***********************************************************************
2611 * WS2_async_send (INTERNAL)
2613 * Handler for overlapped send() operations.
2615 static NTSTATUS
WS2_async_send( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
2617 struct ws2_async
*wsa
= user
;
2622 case STATUS_ALERTED
:
2623 if ( wsa
->n_iovecs
<= wsa
->first_iovec
)
2626 status
= STATUS_SUCCESS
;
2629 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, FILE_WRITE_DATA
, &fd
, NULL
) ))
2632 /* check to see if the data is ready (non-blocking) */
2633 result
= WS2_send( fd
, wsa
, convert_flags(wsa
->flags
) );
2634 wine_server_release_fd( wsa
->hSocket
, fd
);
2638 if (wsa
->first_iovec
< wsa
->n_iovecs
)
2639 status
= STATUS_PENDING
;
2641 status
= STATUS_SUCCESS
;
2643 iosb
->Information
+= result
;
2645 else if (errno
== EAGAIN
)
2647 status
= STATUS_PENDING
;
2651 status
= wsaErrStatus();
2655 if (status
!= STATUS_PENDING
)
2657 iosb
->u
.Status
= status
;
2658 if (!wsa
->completion_func
)
2659 release_async_io( &wsa
->io
);
2664 /***********************************************************************
2665 * WS2_async_shutdown (INTERNAL)
2667 * Handler for shutdown() operations on overlapped sockets.
2669 static NTSTATUS
WS2_async_shutdown( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
2671 struct ws2_async_shutdown
*wsa
= user
;
2676 case STATUS_ALERTED
:
2677 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, 0, &fd
, NULL
) ))
2680 switch ( wsa
->type
)
2682 case ASYNC_TYPE_READ
: err
= shutdown( fd
, 0 ); break;
2683 case ASYNC_TYPE_WRITE
: err
= shutdown( fd
, 1 ); break;
2685 status
= err
? wsaErrStatus() : STATUS_SUCCESS
;
2686 wine_server_release_fd( wsa
->hSocket
, fd
);
2689 iosb
->u
.Status
= status
;
2690 iosb
->Information
= 0;
2691 release_async_io( &wsa
->io
);
2695 /***********************************************************************
2696 * WS2_register_async_shutdown (INTERNAL)
2698 * Helper function for WS_shutdown() on overlapped sockets.
2700 static int WS2_register_async_shutdown( SOCKET s
, int type
)
2702 struct ws2_async_shutdown
*wsa
;
2705 TRACE("socket %04lx type %d\n", s
, type
);
2707 wsa
= (struct ws2_async_shutdown
*)alloc_async_io( sizeof(*wsa
), WS2_async_shutdown
);
2711 wsa
->hSocket
= SOCKET2HANDLE(s
);
2714 status
= register_async( type
, wsa
->hSocket
, &wsa
->io
, 0, NULL
, NULL
, &wsa
->iosb
);
2715 if (status
!= STATUS_PENDING
)
2717 HeapFree( GetProcessHeap(), 0, wsa
);
2718 return NtStatusToWSAError( status
);
2723 /***********************************************************************
2726 SOCKET WINAPI
WS_accept(SOCKET s
, struct WS_sockaddr
*addr
, int *addrlen32
)
2732 TRACE("socket %04lx\n", s
);
2733 status
= _is_blocking(s
, &is_blocking
);
2738 /* try accepting first (if there is a deferred connection) */
2739 SERVER_START_REQ( accept_socket
)
2741 req
->lhandle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
2742 req
->access
= GENERIC_READ
|GENERIC_WRITE
|SYNCHRONIZE
;
2743 req
->attributes
= OBJ_INHERIT
;
2744 status
= wine_server_call( req
);
2745 as
= HANDLE2SOCKET( wine_server_ptr_handle( reply
->handle
));
2750 if (addr
&& addrlen32
&& WS_getpeername(as
, addr
, addrlen32
))
2753 return SOCKET_ERROR
;
2755 TRACE("\taccepted %04lx\n", as
);
2758 if (is_blocking
&& status
== STATUS_CANT_WAIT
)
2760 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
2762 do_block(fd
, POLLIN
, -1);
2763 _sync_sock_state(s
); /* let wineserver notice connection */
2764 release_sock_fd( s
, fd
);
2766 } while (is_blocking
&& status
== STATUS_CANT_WAIT
);
2770 WARN(" -> ERROR %d\n", GetLastError());
2771 return INVALID_SOCKET
;
2774 /***********************************************************************
2777 static BOOL WINAPI
WS2_AcceptEx(SOCKET listener
, SOCKET acceptor
, PVOID dest
, DWORD dest_len
,
2778 DWORD local_addr_len
, DWORD rem_addr_len
, LPDWORD received
,
2779 LPOVERLAPPED overlapped
)
2782 struct ws2_accept_async
*wsa
;
2785 TRACE("(%04lx, %04lx, %p, %d, %d, %d, %p, %p)\n", listener
, acceptor
, dest
, dest_len
, local_addr_len
,
2786 rem_addr_len
, received
, overlapped
);
2790 SetLastError(WSAEINVAL
);
2796 SetLastError(WSA_INVALID_PARAMETER
);
2802 SetLastError(WSAEFAULT
);
2806 fd
= get_sock_fd( listener
, FILE_READ_DATA
, NULL
);
2809 SetLastError(WSAENOTSOCK
);
2812 release_sock_fd( listener
, fd
);
2814 fd
= get_sock_fd( acceptor
, FILE_READ_DATA
, NULL
);
2817 SetLastError(WSAENOTSOCK
);
2820 release_sock_fd( acceptor
, fd
);
2822 wsa
= (struct ws2_accept_async
*)alloc_async_io( sizeof(*wsa
), WS2_async_accept
);
2825 SetLastError(WSAEFAULT
);
2829 wsa
->listen_socket
= SOCKET2HANDLE(listener
);
2830 wsa
->accept_socket
= SOCKET2HANDLE(acceptor
);
2831 wsa
->user_overlapped
= overlapped
;
2832 wsa
->cvalue
= !((ULONG_PTR
)overlapped
->hEvent
& 1) ? (ULONG_PTR
)overlapped
: 0;
2834 wsa
->data_len
= dest_len
;
2835 wsa
->local_len
= local_addr_len
;
2836 wsa
->remote_len
= rem_addr_len
;
2841 /* set up a read request if we need it */
2842 wsa
->read
= (struct ws2_async
*)alloc_async_io( offsetof(struct ws2_async
, iovec
[1]), WS2_async_accept_recv
);
2845 HeapFree( GetProcessHeap(), 0, wsa
);
2846 SetLastError(WSAEFAULT
);
2850 wsa
->read
->hSocket
= wsa
->accept_socket
;
2851 wsa
->read
->flags
= 0;
2852 wsa
->read
->lpFlags
= &wsa
->read
->flags
;
2853 wsa
->read
->addr
= NULL
;
2854 wsa
->read
->addrlen
.ptr
= NULL
;
2855 wsa
->read
->control
= NULL
;
2856 wsa
->read
->n_iovecs
= 1;
2857 wsa
->read
->first_iovec
= 0;
2858 wsa
->read
->completion_func
= NULL
;
2859 wsa
->read
->iovec
[0].iov_base
= wsa
->buf
;
2860 wsa
->read
->iovec
[0].iov_len
= wsa
->data_len
;
2863 status
= register_async( ASYNC_TYPE_READ
, SOCKET2HANDLE(listener
), &wsa
->io
,
2864 overlapped
->hEvent
, NULL
, (void *)wsa
->cvalue
, (IO_STATUS_BLOCK
*)overlapped
);
2866 if(status
!= STATUS_PENDING
)
2868 HeapFree( GetProcessHeap(), 0, wsa
->read
);
2869 HeapFree( GetProcessHeap(), 0, wsa
);
2872 SetLastError( NtStatusToWSAError(status
) );
2876 /***********************************************************************
2877 * WS2_ReadFile (INTERNAL)
2879 * Perform an APC-safe ReadFile operation
2881 static NTSTATUS
WS2_ReadFile(HANDLE hFile
, PIO_STATUS_BLOCK io_status
, char* buffer
, ULONG length
,
2882 PLARGE_INTEGER offset
)
2884 int result
= -1, unix_handle
;
2885 unsigned int options
;
2888 TRACE( "(%p,%p,0x%08x)\n", hFile
, buffer
,length
);
2890 status
= wine_server_handle_to_fd( hFile
, FILE_READ_DATA
, &unix_handle
, &options
);
2891 if (status
) return status
;
2893 while (result
== -1)
2895 if (offset
->QuadPart
!= FILE_USE_FILE_POINTER_POSITION
)
2896 result
= pread( unix_handle
, buffer
, length
, offset
->QuadPart
);
2898 result
= read( unix_handle
, buffer
, length
);
2904 status
= (length
? STATUS_END_OF_FILE
: STATUS_SUCCESS
);
2905 else if (result
!= -1)
2906 status
= STATUS_SUCCESS
;
2907 else if (errno
!= EAGAIN
)
2908 status
= wsaErrStatus();
2910 status
= STATUS_PENDING
;
2912 wine_server_release_fd( hFile
, unix_handle
);
2913 TRACE("= 0x%08x (%d)\n", status
, result
);
2914 if (status
== STATUS_SUCCESS
|| status
== STATUS_END_OF_FILE
)
2916 io_status
->u
.Status
= status
;
2917 io_status
->Information
= result
;
2923 /***********************************************************************
2924 * WS2_transmitfile_getbuffer (INTERNAL)
2926 * Pick the appropriate buffer for a TransmitFile send operation.
2928 static NTSTATUS
WS2_transmitfile_getbuffer( int fd
, struct ws2_transmitfile_async
*wsa
)
2930 /* send any incomplete writes from a previous iteration */
2931 if (wsa
->write
.first_iovec
< wsa
->write
.n_iovecs
)
2932 return STATUS_PENDING
;
2934 /* process the header (if applicable) */
2935 if (wsa
->buffers
.Head
)
2937 wsa
->write
.first_iovec
= 0;
2938 wsa
->write
.n_iovecs
= 1;
2939 wsa
->write
.iovec
[0].iov_base
= wsa
->buffers
.Head
;
2940 wsa
->write
.iovec
[0].iov_len
= wsa
->buffers
.HeadLength
;
2941 wsa
->buffers
.Head
= NULL
;
2942 return STATUS_PENDING
;
2945 /* process the main file */
2948 DWORD bytes_per_send
= wsa
->bytes_per_send
;
2949 IO_STATUS_BLOCK iosb
;
2952 iosb
.Information
= 0;
2953 /* when the size of the transfer is limited ensure that we don't go past that limit */
2954 if (wsa
->file_bytes
!= 0)
2955 bytes_per_send
= min(bytes_per_send
, wsa
->file_bytes
- wsa
->file_read
);
2956 status
= WS2_ReadFile( wsa
->file
, &iosb
, wsa
->buffer
, bytes_per_send
, &wsa
->offset
);
2957 if (wsa
->offset
.QuadPart
!= FILE_USE_FILE_POINTER_POSITION
)
2958 wsa
->offset
.QuadPart
+= iosb
.Information
;
2959 if (status
== STATUS_END_OF_FILE
)
2960 wsa
->file
= NULL
; /* continue on to the footer */
2961 else if (status
!= STATUS_SUCCESS
)
2965 if (iosb
.Information
)
2967 wsa
->write
.first_iovec
= 0;
2968 wsa
->write
.n_iovecs
= 1;
2969 wsa
->write
.iovec
[0].iov_base
= wsa
->buffer
;
2970 wsa
->write
.iovec
[0].iov_len
= iosb
.Information
;
2971 wsa
->file_read
+= iosb
.Information
;
2974 if (wsa
->file_bytes
!= 0 && wsa
->file_read
>= wsa
->file_bytes
)
2977 return STATUS_PENDING
;
2981 /* send the footer (if applicable) */
2982 if (wsa
->buffers
.Tail
)
2984 wsa
->write
.first_iovec
= 0;
2985 wsa
->write
.n_iovecs
= 1;
2986 wsa
->write
.iovec
[0].iov_base
= wsa
->buffers
.Tail
;
2987 wsa
->write
.iovec
[0].iov_len
= wsa
->buffers
.TailLength
;
2988 wsa
->buffers
.Tail
= NULL
;
2989 return STATUS_PENDING
;
2992 return STATUS_SUCCESS
;
2995 /***********************************************************************
2996 * WS2_transmitfile_base (INTERNAL)
2998 * Shared implementation for both synchronous and asynchronous TransmitFile.
3000 static NTSTATUS
WS2_transmitfile_base( int fd
, struct ws2_transmitfile_async
*wsa
)
3004 status
= WS2_transmitfile_getbuffer( fd
, wsa
);
3005 if (status
== STATUS_PENDING
)
3007 IO_STATUS_BLOCK
*iosb
= (IO_STATUS_BLOCK
*)wsa
->write
.user_overlapped
;
3010 n
= WS2_send( fd
, &wsa
->write
, convert_flags(wsa
->write
.flags
) );
3013 if (iosb
) iosb
->Information
+= n
;
3015 else if (errno
!= EAGAIN
)
3016 return wsaErrStatus();
3022 /***********************************************************************
3023 * WS2_async_transmitfile (INTERNAL)
3025 * Asynchronous callback for overlapped TransmitFile operations.
3027 static NTSTATUS
WS2_async_transmitfile( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
3029 struct ws2_transmitfile_async
*wsa
= user
;
3032 if (status
== STATUS_ALERTED
)
3034 if (!(status
= wine_server_handle_to_fd( wsa
->write
.hSocket
, FILE_WRITE_DATA
, &fd
, NULL
)))
3036 status
= WS2_transmitfile_base( fd
, wsa
);
3037 wine_server_release_fd( wsa
->write
.hSocket
, fd
);
3039 if (status
== STATUS_PENDING
)
3043 iosb
->u
.Status
= status
;
3044 release_async_io( &wsa
->io
);
3048 /***********************************************************************
3051 static BOOL WINAPI
WS2_TransmitFile( SOCKET s
, HANDLE h
, DWORD file_bytes
, DWORD bytes_per_send
,
3052 LPOVERLAPPED overlapped
, LPTRANSMIT_FILE_BUFFERS buffers
,
3055 union generic_unix_sockaddr uaddr
;
3056 socklen_t uaddrlen
= sizeof(uaddr
);
3057 struct ws2_transmitfile_async
*wsa
;
3061 TRACE("(%lx, %p, %d, %d, %p, %p, %d)\n", s
, h
, file_bytes
, bytes_per_send
, overlapped
,
3064 fd
= get_sock_fd( s
, FILE_WRITE_DATA
, NULL
);
3067 WSASetLastError( WSAENOTSOCK
);
3070 if (getpeername( fd
, &uaddr
.addr
, &uaddrlen
) != 0)
3072 release_sock_fd( s
, fd
);
3073 WSASetLastError( WSAENOTCONN
);
3077 FIXME("Flags are not currently supported (0x%x).\n", flags
);
3079 if (h
&& GetFileType( h
) != FILE_TYPE_DISK
)
3081 FIXME("Non-disk file handles are not currently supported.\n");
3082 release_sock_fd( s
, fd
);
3083 WSASetLastError( WSAEOPNOTSUPP
);
3087 /* set reasonable defaults when requested */
3088 if (!bytes_per_send
)
3089 bytes_per_send
= (1 << 16); /* Depends on OS version: PAGE_SIZE, 2*PAGE_SIZE, or 2^16 */
3091 if (!(wsa
= (struct ws2_transmitfile_async
*)alloc_async_io( sizeof(*wsa
) + bytes_per_send
,
3092 WS2_async_transmitfile
)))
3094 release_sock_fd( s
, fd
);
3095 WSASetLastError( WSAEFAULT
);
3099 wsa
->buffers
= *buffers
;
3101 memset(&wsa
->buffers
, 0x0, sizeof(wsa
->buffers
));
3102 wsa
->buffer
= (char *)(wsa
+ 1);
3105 wsa
->file_bytes
= file_bytes
;
3106 wsa
->bytes_per_send
= bytes_per_send
;
3108 wsa
->offset
.QuadPart
= FILE_USE_FILE_POINTER_POSITION
;
3109 wsa
->write
.hSocket
= SOCKET2HANDLE(s
);
3110 wsa
->write
.addr
= NULL
;
3111 wsa
->write
.addrlen
.val
= 0;
3112 wsa
->write
.flags
= 0;
3113 wsa
->write
.lpFlags
= &wsa
->flags
;
3114 wsa
->write
.control
= NULL
;
3115 wsa
->write
.n_iovecs
= 0;
3116 wsa
->write
.first_iovec
= 0;
3117 wsa
->write
.user_overlapped
= overlapped
;
3120 IO_STATUS_BLOCK
*iosb
= (IO_STATUS_BLOCK
*)overlapped
;
3123 wsa
->offset
.u
.LowPart
= overlapped
->u
.s
.Offset
;
3124 wsa
->offset
.u
.HighPart
= overlapped
->u
.s
.OffsetHigh
;
3125 iosb
->u
.Status
= STATUS_PENDING
;
3126 iosb
->Information
= 0;
3127 status
= register_async( ASYNC_TYPE_WRITE
, SOCKET2HANDLE(s
), &wsa
->io
,
3128 overlapped
->hEvent
, NULL
, NULL
, iosb
);
3129 if(status
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
3130 release_sock_fd( s
, fd
);
3131 WSASetLastError( NtStatusToWSAError(status
) );
3137 status
= WS2_transmitfile_base( fd
, wsa
);
3138 if (status
== STATUS_PENDING
)
3141 do_block(fd
, POLLOUT
, -1);
3142 _sync_sock_state(s
); /* let wineserver notice connection */
3145 while (status
== STATUS_PENDING
);
3146 release_sock_fd( s
, fd
);
3148 if (status
!= STATUS_SUCCESS
)
3149 WSASetLastError( NtStatusToWSAError(status
) );
3150 HeapFree( GetProcessHeap(), 0, wsa
);
3151 return (status
== STATUS_SUCCESS
);
3154 /***********************************************************************
3155 * GetAcceptExSockaddrs
3157 static void WINAPI
WS2_GetAcceptExSockaddrs(PVOID buffer
, DWORD data_size
, DWORD local_size
, DWORD remote_size
,
3158 struct WS_sockaddr
**local_addr
, LPINT local_addr_len
,
3159 struct WS_sockaddr
**remote_addr
, LPINT remote_addr_len
)
3161 char *cbuf
= buffer
;
3162 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer
, data_size
, local_size
, remote_size
, local_addr
,
3163 local_addr_len
, remote_addr
, remote_addr_len
);
3166 *local_addr_len
= *(int *) cbuf
;
3167 *local_addr
= (struct WS_sockaddr
*)(cbuf
+ sizeof(int));
3171 *remote_addr_len
= *(int *) cbuf
;
3172 *remote_addr
= (struct WS_sockaddr
*)(cbuf
+ sizeof(int));
3175 /***********************************************************************
3178 int WINAPI
WSASendMsg( SOCKET s
, LPWSAMSG msg
, DWORD dwFlags
, LPDWORD lpNumberOfBytesSent
,
3179 LPWSAOVERLAPPED lpOverlapped
,
3180 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
3184 SetLastError( WSAEFAULT
);
3185 return SOCKET_ERROR
;
3188 return WS2_sendto( s
, msg
->lpBuffers
, msg
->dwBufferCount
, lpNumberOfBytesSent
,
3189 dwFlags
, msg
->name
, msg
->namelen
,
3190 lpOverlapped
, lpCompletionRoutine
);
3193 /***********************************************************************
3196 * Perform a receive operation that is capable of returning message
3197 * control headers. It is important to note that the WSAMSG parameter
3198 * must remain valid throughout the operation, even when an overlapped
3199 * receive is performed.
3201 static int WINAPI
WS2_WSARecvMsg( SOCKET s
, LPWSAMSG msg
, LPDWORD lpNumberOfBytesRecvd
,
3202 LPWSAOVERLAPPED lpOverlapped
,
3203 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
3207 SetLastError( WSAEFAULT
);
3208 return SOCKET_ERROR
;
3211 return WS2_recv_base( s
, msg
->lpBuffers
, msg
->dwBufferCount
, lpNumberOfBytesRecvd
,
3212 &msg
->dwFlags
, msg
->name
, &msg
->namelen
,
3213 lpOverlapped
, lpCompletionRoutine
, &msg
->Control
);
3216 /***********************************************************************
3217 * interface_bind (INTERNAL)
3219 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
3220 * operating only on the specified interface. This restriction consists of two components:
3221 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
3222 * 2) An incoming packet restriction dropping packets not meant for the interface.
3223 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
3224 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
3225 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
3226 * to receive broadcast packets on a socket that is bound to a specific network interface.
3228 static BOOL
interface_bind( SOCKET s
, int fd
, struct sockaddr
*addr
)
3230 struct sockaddr_in
*in_sock
= (struct sockaddr_in
*) addr
;
3231 in_addr_t bind_addr
= in_sock
->sin_addr
.s_addr
;
3232 PIP_ADAPTER_INFO adapters
= NULL
, adapter
;
3237 if (bind_addr
== htonl(INADDR_ANY
) || bind_addr
== htonl(INADDR_LOOPBACK
))
3238 return FALSE
; /* Not binding to a network adapter, special interface binding unnecessary. */
3239 if (_get_fd_type(fd
) != SOCK_DGRAM
)
3240 return FALSE
; /* Special interface binding is only necessary for UDP datagrams. */
3241 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
3243 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
3244 if (adapters
== NULL
|| GetAdaptersInfo(adapters
, &adap_size
) != NO_ERROR
)
3246 /* Search the IPv4 adapter list for the appropriate binding interface */
3247 for (adapter
= adapters
; adapter
!= NULL
; adapter
= adapter
->Next
)
3249 in_addr_t adapter_addr
= (in_addr_t
) inet_addr(adapter
->IpAddressList
.IpAddress
.String
);
3251 if (bind_addr
== adapter_addr
)
3253 #if defined(IP_BOUND_IF)
3254 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
3255 if (setsockopt(fd
, IPPROTO_IP
, IP_BOUND_IF
, &adapter
->Index
, sizeof(adapter
->Index
)) != 0)
3258 #elif defined(LINUX_BOUND_IF)
3259 in_addr_t ifindex
= (in_addr_t
) htonl(adapter
->Index
);
3260 struct interface_filter specific_interface_filter
;
3261 struct sock_fprog filter_prog
;
3263 if (setsockopt(fd
, IPPROTO_IP
, IP_UNICAST_IF
, &ifindex
, sizeof(ifindex
)) != 0)
3264 goto cleanup
; /* Failed to suggest egress interface */
3265 specific_interface_filter
= generic_interface_filter
;
3266 specific_interface_filter
.iface_rule
.k
= adapter
->Index
;
3267 specific_interface_filter
.ip_rule
.k
= htonl(adapter_addr
);
3268 filter_prog
.len
= sizeof(generic_interface_filter
)/sizeof(struct sock_filter
);
3269 filter_prog
.filter
= (struct sock_filter
*) &specific_interface_filter
;
3270 if (setsockopt(fd
, SOL_SOCKET
, SO_ATTACH_FILTER
, &filter_prog
, sizeof(filter_prog
)) != 0)
3271 goto cleanup
; /* Failed to specify incoming packet filter */
3274 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
3275 "receiving broadcast packets will not work on socket %04lx.\n", s
);
3280 /* Will soon be switching to INADDR_ANY: permit address reuse */
3281 if (ret
&& setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &enable
, sizeof(enable
)) == 0)
3282 TRACE("Socket %04lx bound to interface index %d\n", s
, adapter
->Index
);
3288 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s
);
3289 HeapFree(GetProcessHeap(), 0, adapters
);
3293 /***********************************************************************
3296 int WINAPI
WS_bind(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
)
3298 int fd
= get_sock_fd( s
, 0, NULL
);
3299 int res
= SOCKET_ERROR
;
3301 TRACE("socket %04lx, ptr %p %s, length %d\n", s
, name
, debugstr_sockaddr(name
), namelen
);
3305 if (!name
|| (name
->sa_family
&& !supported_pf(name
->sa_family
)))
3307 SetLastError(WSAEAFNOSUPPORT
);
3311 union generic_unix_sockaddr uaddr
;
3312 unsigned int uaddrlen
= ws_sockaddr_ws2u(name
, namelen
, &uaddr
);
3315 SetLastError(WSAEFAULT
);
3319 if (name
->sa_family
== WS_AF_INET
)
3321 struct sockaddr_in
*in4
= (struct sockaddr_in
*) &uaddr
;
3322 if (memcmp(&in4
->sin_addr
, magic_loopback_addr
, 4) == 0)
3324 /* Trying to bind to the default host interface, using
3325 * INADDR_ANY instead*/
3326 WARN("Trying to bind to magic IP address, using "
3327 "INADDR_ANY instead.\n");
3328 in4
->sin_addr
.s_addr
= htonl(INADDR_ANY
);
3330 else if (interface_bind(s
, fd
, &uaddr
.addr
))
3331 in4
->sin_addr
.s_addr
= htonl(INADDR_ANY
);
3333 if (bind(fd
, &uaddr
.addr
, uaddrlen
) < 0)
3335 int loc_errno
= errno
;
3336 WARN("\tfailure - errno = %i\n", errno
);
3341 SetLastError(WSAEINVAL
);
3346 socklen_t optlen
= sizeof(optval
);
3347 /* Windows >= 2003 will return different results depending on
3348 * SO_REUSEADDR, WSAEACCES may be returned representing that
3349 * the socket hijacking protection prevented the bind */
3350 if (!getsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&optval
, &optlen
) && optval
)
3352 SetLastError(WSAEACCES
);
3358 SetLastError(wsaErrno());
3364 res
=0; /* success */
3368 release_sock_fd( s
, fd
);
3373 /***********************************************************************
3374 * closesocket (WS2_32.3)
3376 int WINAPI
WS_closesocket(SOCKET s
)
3378 int res
= SOCKET_ERROR
, fd
;
3381 fd
= get_sock_fd(s
, FILE_READ_DATA
, NULL
);
3384 release_sock_fd(s
, fd
);
3385 if (CloseHandle(SOCKET2HANDLE(s
)))
3389 SetLastError(WSAENOTSOCK
);
3392 SetLastError(WSANOTINITIALISED
);
3393 TRACE("(socket %04lx) -> %d\n", s
, res
);
3397 static int do_connect(int fd
, const struct WS_sockaddr
* name
, int namelen
)
3399 union generic_unix_sockaddr uaddr
;
3400 unsigned int uaddrlen
= ws_sockaddr_ws2u(name
, namelen
, &uaddr
);
3405 if (name
->sa_family
== WS_AF_INET
)
3407 struct sockaddr_in
*in4
= (struct sockaddr_in
*) &uaddr
;
3408 if (memcmp(&in4
->sin_addr
, magic_loopback_addr
, 4) == 0)
3410 /* Trying to connect to magic replace-loopback address,
3411 * assuming we really want to connect to localhost */
3412 TRACE("Trying to connect to magic IP address, using "
3413 "INADDR_LOOPBACK instead.\n");
3414 in4
->sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
3418 if (connect(fd
, &uaddr
.addr
, uaddrlen
) == 0)
3424 /***********************************************************************
3425 * connect (WS2_32.4)
3427 int WINAPI
WS_connect(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
)
3429 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
3431 TRACE("socket %04lx, ptr %p %s, length %d\n", s
, name
, debugstr_sockaddr(name
), namelen
);
3437 int ret
= do_connect(fd
, name
, namelen
);
3439 goto connect_success
;
3441 if (ret
== WSAEINPROGRESS
)
3443 /* tell wineserver that a connection is in progress */
3444 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3446 FD_WINE_CONNECTED
|FD_WINE_LISTENING
);
3447 status
= _is_blocking( s
, &is_blocking
);
3450 release_sock_fd( s
, fd
);
3451 set_error( status
);
3452 return SOCKET_ERROR
;
3458 do_block(fd
, POLLIN
| POLLOUT
, -1);
3459 _sync_sock_state(s
); /* let wineserver notice connection */
3460 /* retrieve any error codes from it */
3461 result
= _get_sock_error(s
, FD_CONNECT_BIT
);
3463 SetLastError(NtStatusToWSAError(result
));
3466 goto connect_success
;
3471 SetLastError(WSAEWOULDBLOCK
);
3478 release_sock_fd( s
, fd
);
3480 return SOCKET_ERROR
;
3483 release_sock_fd( s
, fd
);
3484 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3485 FD_WINE_CONNECTED
|FD_READ
|FD_WRITE
,
3486 FD_CONNECT
|FD_WINE_LISTENING
);
3487 TRACE("\tconnected %04lx\n", s
);
3491 /***********************************************************************
3492 * WSAConnect (WS2_32.30)
3494 int WINAPI
WSAConnect( SOCKET s
, const struct WS_sockaddr
* name
, int namelen
,
3495 LPWSABUF lpCallerData
, LPWSABUF lpCalleeData
,
3496 LPQOS lpSQOS
, LPQOS lpGQOS
)
3498 if ( lpCallerData
|| lpCalleeData
|| lpSQOS
|| lpGQOS
)
3499 FIXME("unsupported parameters!\n");
3500 return WS_connect( s
, name
, namelen
);
3503 /***********************************************************************
3506 static BOOL WINAPI
WS2_ConnectEx(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
,
3507 PVOID sendBuf
, DWORD sendBufLen
, LPDWORD sent
, LPOVERLAPPED ov
)
3509 int fd
, ret
, status
;
3513 SetLastError( ERROR_INVALID_PARAMETER
);
3517 fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
3520 SetLastError( WSAENOTSOCK
);
3524 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
3525 s
, name
, debugstr_sockaddr(name
), namelen
, sendBuf
, sendBufLen
, ov
);
3527 ret
= is_fd_bound(fd
, NULL
, NULL
);
3530 SetLastError(ret
== -1 ? wsaErrno() : WSAEINVAL
);
3531 release_sock_fd( s
, fd
);
3535 ret
= do_connect(fd
, name
, namelen
);
3540 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3541 FD_WINE_CONNECTED
|FD_READ
|FD_WRITE
,
3542 FD_CONNECT
|FD_WINE_LISTENING
);
3544 wsabuf
.len
= sendBufLen
;
3545 wsabuf
.buf
= (char*) sendBuf
;
3547 /* WSASend takes care of completion if need be */
3548 if (WSASend(s
, &wsabuf
, sendBuf
? 1 : 0, sent
, 0, ov
, NULL
) != SOCKET_ERROR
)
3549 goto connection_success
;
3551 else if (ret
== WSAEINPROGRESS
)
3553 struct ws2_async
*wsa
;
3554 ULONG_PTR cvalue
= (((ULONG_PTR
)ov
->hEvent
& 1) == 0) ? (ULONG_PTR
)ov
: 0;
3556 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3558 FD_WINE_CONNECTED
|FD_WINE_LISTENING
);
3560 /* Indirectly call WSASend */
3561 if (!(wsa
= (struct ws2_async
*)alloc_async_io( offsetof( struct ws2_async
, iovec
[1] ), WS2_async_send
)))
3563 SetLastError(WSAEFAULT
);
3567 IO_STATUS_BLOCK
*iosb
= (IO_STATUS_BLOCK
*)ov
;
3568 iosb
->u
.Status
= STATUS_PENDING
;
3569 iosb
->Information
= 0;
3571 wsa
->hSocket
= SOCKET2HANDLE(s
);
3573 wsa
->addrlen
.val
= 0;
3575 wsa
->lpFlags
= &wsa
->flags
;
3576 wsa
->control
= NULL
;
3577 wsa
->n_iovecs
= sendBuf
? 1 : 0;
3578 wsa
->first_iovec
= 0;
3579 wsa
->completion_func
= NULL
;
3580 wsa
->iovec
[0].iov_base
= sendBuf
;
3581 wsa
->iovec
[0].iov_len
= sendBufLen
;
3583 status
= register_async( ASYNC_TYPE_WRITE
, wsa
->hSocket
, &wsa
->io
, ov
->hEvent
,
3584 NULL
, (void *)cvalue
, iosb
);
3585 if (status
!= STATUS_PENDING
) HeapFree(GetProcessHeap(), 0, wsa
);
3587 /* If the connect already failed */
3588 if (status
== STATUS_PIPE_DISCONNECTED
)
3590 ov
->Internal
= _get_sock_error(s
, FD_CONNECT_BIT
);
3591 ov
->InternalHigh
= 0;
3592 if (cvalue
) WS_AddCompletion( s
, cvalue
, ov
->Internal
, ov
->InternalHigh
);
3593 if (ov
->hEvent
) NtSetEvent( ov
->hEvent
, NULL
);
3594 status
= STATUS_PENDING
;
3596 SetLastError( NtStatusToWSAError(status
) );
3604 release_sock_fd( s
, fd
);
3608 release_sock_fd( s
, fd
);
3612 /***********************************************************************
3615 static BOOL WINAPI
WS2_DisconnectEx( SOCKET s
, LPOVERLAPPED ov
, DWORD flags
, DWORD reserved
)
3617 TRACE( "socket %04lx, ov %p, flags 0x%x, reserved 0x%x\n", s
, ov
, flags
, reserved
);
3619 if (flags
& TF_REUSE_SOCKET
)
3620 FIXME( "Reusing socket not supported yet\n" );
3624 ov
->Internal
= STATUS_PENDING
;
3625 ov
->InternalHigh
= 0;
3628 return !WS_shutdown( s
, SD_BOTH
);
3631 /***********************************************************************
3632 * getpeername (WS2_32.5)
3634 int WINAPI
WS_getpeername(SOCKET s
, struct WS_sockaddr
*name
, int *namelen
)
3639 TRACE("socket %04lx, ptr %p, len %08x\n", s
, name
, namelen
? *namelen
: 0);
3641 fd
= get_sock_fd( s
, 0, NULL
);
3646 union generic_unix_sockaddr uaddr
;
3647 socklen_t uaddrlen
= sizeof(uaddr
);
3649 if (getpeername(fd
, &uaddr
.addr
, &uaddrlen
) == 0)
3651 if (!name
|| !namelen
)
3652 SetLastError(WSAEFAULT
);
3653 else if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
3654 /* The buffer was too small */
3655 SetLastError(WSAEFAULT
);
3659 TRACE("=> %s\n", debugstr_sockaddr(name
));
3663 SetLastError(wsaErrno());
3664 release_sock_fd( s
, fd
);
3669 /* When binding to an UDP address with filter support the getsockname call on the socket
3670 * will always return 0.0.0.0 instead of the filtered interface address. This function
3671 * checks if the socket is interface-bound on UDP and return the correct address.
3672 * This is required because applications often do a bind() with port zero followed by a
3673 * getsockname() to retrieve the port and address acquired.
3675 static void interface_bind_check(int fd
, struct sockaddr_in
*addr
)
3677 #if !defined(IP_BOUND_IF) && !defined(LINUX_BOUND_IF)
3680 unsigned int ifindex
;
3684 /* Check for IPv4, address 0.0.0.0 and UDP socket */
3685 if (addr
->sin_family
!= AF_INET
|| addr
->sin_addr
.s_addr
!= 0)
3687 if (_get_fd_type(fd
) != SOCK_DGRAM
)
3690 len
= sizeof(ifindex
);
3691 #if defined(IP_BOUND_IF)
3692 ret
= getsockopt(fd
, IPPROTO_IP
, IP_BOUND_IF
, &ifindex
, &len
);
3693 #elif defined(LINUX_BOUND_IF)
3694 ret
= getsockopt(fd
, IPPROTO_IP
, IP_UNICAST_IF
, &ifindex
, &len
);
3695 if (!ret
) ifindex
= ntohl(ifindex
);
3699 PIP_ADAPTER_INFO adapters
, adapter
;
3702 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
3704 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
3705 if (adapters
&& GetAdaptersInfo(adapters
, &adap_size
) == NO_ERROR
)
3707 /* Search the IPv4 adapter list for the appropriate bound interface */
3708 for (adapter
= adapters
; adapter
!= NULL
; adapter
= adapter
->Next
)
3710 in_addr_t adapter_addr
;
3711 if (adapter
->Index
!= ifindex
) continue;
3713 adapter_addr
= inet_addr(adapter
->IpAddressList
.IpAddress
.String
);
3714 addr
->sin_addr
.s_addr
= adapter_addr
;
3715 TRACE("reporting interface address from adapter %d\n", ifindex
);
3719 HeapFree(GetProcessHeap(), 0, adapters
);
3724 /***********************************************************************
3725 * getsockname (WS2_32.6)
3727 int WINAPI
WS_getsockname(SOCKET s
, struct WS_sockaddr
*name
, int *namelen
)
3732 TRACE("socket %04lx, ptr %p, len %08x\n", s
, name
, namelen
? *namelen
: 0);
3734 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3735 if( (name
== NULL
) || (namelen
== NULL
) )
3737 SetLastError( WSAEFAULT
);
3738 return SOCKET_ERROR
;
3741 fd
= get_sock_fd( s
, 0, NULL
);
3746 union generic_unix_sockaddr uaddr
;
3748 int bound
= is_fd_bound(fd
, &uaddr
, &uaddrlen
);
3752 SetLastError(bound
== -1 ? wsaErrno() : WSAEINVAL
);
3754 else if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
3756 /* The buffer was too small */
3757 SetLastError(WSAEFAULT
);
3761 interface_bind_check(fd
, (struct sockaddr_in
*) &uaddr
);
3762 if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
3764 /* The buffer was too small */
3765 SetLastError(WSAEFAULT
);
3770 TRACE("=> %s\n", debugstr_sockaddr(name
));
3773 release_sock_fd( s
, fd
);
3778 /***********************************************************************
3779 * getsockopt (WS2_32.7)
3781 INT WINAPI
WS_getsockopt(SOCKET s
, INT level
,
3782 INT optname
, char *optval
, INT
*optlen
)
3787 TRACE("(socket %04lx, %s, optval %s, optlen %p (%d))\n", s
,
3788 debugstr_sockopt(level
, optname
), debugstr_optval(optval
, 0),
3789 optlen
, optlen
? *optlen
: 0);
3797 /* Handle common cases. The special cases are below, sorted
3799 case WS_SO_BROADCAST
:
3801 case WS_SO_KEEPALIVE
:
3802 case WS_SO_OOBINLINE
:
3804 case WS_SO_REUSEADDR
:
3806 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3807 return SOCKET_ERROR
;
3808 convert_sockopt(&level
, &optname
);
3809 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3811 SetLastError(wsaErrno());
3814 release_sock_fd( s
, fd
);
3816 case WS_SO_ACCEPTCONN
:
3817 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3818 return SOCKET_ERROR
;
3819 if (getsockopt(fd
, SOL_SOCKET
, SO_ACCEPTCONN
, optval
, (socklen_t
*)optlen
) != 0 )
3821 SetLastError(wsaErrno());
3826 /* BSD returns != 0 while Windows return exact == 1 */
3827 if (*(int *)optval
) *(int *)optval
= 1;
3829 release_sock_fd( s
, fd
);
3831 case WS_SO_BSP_STATE
:
3833 int req_size
, addr_size
;
3834 WSAPROTOCOL_INFOW infow
;
3835 CSADDR_INFO
*csinfo
;
3837 ret
= ws_protocol_info(s
, TRUE
, &infow
, &addr_size
);
3840 if (infow
.iAddressFamily
== WS_AF_INET
)
3841 addr_size
= sizeof(struct sockaddr_in
);
3842 else if (infow
.iAddressFamily
== WS_AF_INET6
)
3843 addr_size
= sizeof(struct sockaddr_in6
);
3846 FIXME("Family %d is unsupported for SO_BSP_STATE\n", infow
.iAddressFamily
);
3847 SetLastError(WSAEAFNOSUPPORT
);
3848 return SOCKET_ERROR
;
3851 req_size
= sizeof(CSADDR_INFO
) + addr_size
* 2;
3852 if (*optlen
< req_size
)
3855 SetLastError(WSAEFAULT
);
3859 union generic_unix_sockaddr uaddr
;
3862 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3863 return SOCKET_ERROR
;
3865 csinfo
= (CSADDR_INFO
*) optval
;
3867 /* Check if the sock is bound */
3868 if (is_fd_bound(fd
, &uaddr
, &uaddrlen
) == 1)
3870 csinfo
->LocalAddr
.lpSockaddr
=
3871 (LPSOCKADDR
) (optval
+ sizeof(CSADDR_INFO
));
3872 ws_sockaddr_u2ws(&uaddr
.addr
, csinfo
->LocalAddr
.lpSockaddr
, &addr_size
);
3873 csinfo
->LocalAddr
.iSockaddrLength
= addr_size
;
3877 csinfo
->LocalAddr
.lpSockaddr
= NULL
;
3878 csinfo
->LocalAddr
.iSockaddrLength
= 0;
3881 /* Check if the sock is connected */
3882 if (!getpeername(fd
, &uaddr
.addr
, &uaddrlen
) &&
3883 is_sockaddr_bound(&uaddr
.addr
, uaddrlen
))
3885 csinfo
->RemoteAddr
.lpSockaddr
=
3886 (LPSOCKADDR
) (optval
+ sizeof(CSADDR_INFO
) + addr_size
);
3887 ws_sockaddr_u2ws(&uaddr
.addr
, csinfo
->RemoteAddr
.lpSockaddr
, &addr_size
);
3888 csinfo
->RemoteAddr
.iSockaddrLength
= addr_size
;
3892 csinfo
->RemoteAddr
.lpSockaddr
= NULL
;
3893 csinfo
->RemoteAddr
.iSockaddrLength
= 0;
3896 csinfo
->iSocketType
= infow
.iSocketType
;
3897 csinfo
->iProtocol
= infow
.iProtocol
;
3898 release_sock_fd( s
, fd
);
3901 return ret
? 0 : SOCKET_ERROR
;
3903 case WS_SO_DONTLINGER
:
3905 struct linger lingval
;
3906 socklen_t len
= sizeof(struct linger
);
3908 if (!optlen
|| *optlen
< sizeof(BOOL
)|| !optval
)
3910 SetLastError(WSAEFAULT
);
3911 return SOCKET_ERROR
;
3913 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3914 return SOCKET_ERROR
;
3916 if (getsockopt(fd
, SOL_SOCKET
, SO_LINGER
, &lingval
, &len
) != 0 )
3918 SetLastError(wsaErrno());
3923 *(BOOL
*)optval
= !lingval
.l_onoff
;
3924 *optlen
= sizeof(BOOL
);
3927 release_sock_fd( s
, fd
);
3931 case WS_SO_CONNECT_TIME
:
3933 static int pretendtime
= 0;
3934 struct WS_sockaddr addr
;
3935 int len
= sizeof(addr
);
3937 if (!optlen
|| *optlen
< sizeof(DWORD
) || !optval
)
3939 SetLastError(WSAEFAULT
);
3940 return SOCKET_ERROR
;
3942 if (WS_getpeername(s
, &addr
, &len
) == SOCKET_ERROR
)
3943 *(DWORD
*)optval
= ~0u;
3946 if (!pretendtime
) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3947 *(DWORD
*)optval
= pretendtime
++;
3949 *optlen
= sizeof(DWORD
);
3952 /* As mentioned in setsockopt, Windows ignores this, so we
3953 * always return true here */
3954 case WS_SO_DONTROUTE
:
3955 if (!optlen
|| *optlen
< sizeof(BOOL
) || !optval
)
3957 SetLastError(WSAEFAULT
);
3958 return SOCKET_ERROR
;
3960 *(BOOL
*)optval
= TRUE
;
3961 *optlen
= sizeof(BOOL
);
3966 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3967 return SOCKET_ERROR
;
3968 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, optval
, (socklen_t
*)optlen
) != 0 )
3970 SetLastError(wsaErrno());
3973 release_sock_fd( s
, fd
);
3975 /* The wineserver may have swallowed the error before us */
3976 if (!ret
&& *(int*) optval
== 0)
3978 int i
, events
[FD_MAX_EVENTS
];
3979 _get_sock_errors(s
, events
);
3980 for (i
= 0; i
< FD_MAX_EVENTS
; i
++)
3984 events
[i
] = NtStatusToWSAError(events
[i
]);
3985 TRACE("returning SO_ERROR %d from wine server\n", events
[i
]);
3986 *(int*) optval
= events
[i
];
3996 struct linger lingval
;
3997 socklen_t len
= sizeof(struct linger
);
3999 /* struct linger and LINGER have different sizes */
4000 if (!optlen
|| *optlen
< sizeof(LINGER
) || !optval
)
4002 SetLastError(WSAEFAULT
);
4003 return SOCKET_ERROR
;
4005 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4006 return SOCKET_ERROR
;
4008 if (_get_fd_type(fd
) == SOCK_DGRAM
)
4010 SetLastError(WSAENOPROTOOPT
);
4013 else if (getsockopt(fd
, SOL_SOCKET
, SO_LINGER
, &lingval
, &len
) != 0)
4015 SetLastError(wsaErrno());
4020 ((LINGER
*)optval
)->l_onoff
= lingval
.l_onoff
;
4021 ((LINGER
*)optval
)->l_linger
= lingval
.l_linger
;
4022 *optlen
= sizeof(struct linger
);
4025 release_sock_fd( s
, fd
);
4029 case WS_SO_MAX_MSG_SIZE
:
4030 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
4032 SetLastError(WSAEFAULT
);
4033 return SOCKET_ERROR
;
4035 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
4036 *(int *)optval
= 65507;
4037 *optlen
= sizeof(int);
4040 /* SO_OPENTYPE does not require a valid socket handle. */
4041 case WS_SO_OPENTYPE
:
4042 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
4044 SetLastError(WSAEFAULT
);
4045 return SOCKET_ERROR
;
4047 *(int *)optval
= get_per_thread_data()->opentype
;
4048 *optlen
= sizeof(int);
4049 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval
) );
4051 case WS_SO_PROTOCOL_INFOA
:
4052 case WS_SO_PROTOCOL_INFOW
:
4055 WSAPROTOCOL_INFOW infow
;
4057 ret
= ws_protocol_info(s
, optname
== WS_SO_PROTOCOL_INFOW
, &infow
, &size
);
4060 if (!optlen
|| !optval
|| *optlen
< size
)
4062 if(optlen
) *optlen
= size
;
4064 SetLastError(WSAEFAULT
);
4067 memcpy(optval
, &infow
, size
);
4069 return ret
? 0 : SOCKET_ERROR
;
4071 case WS_SO_RCVTIMEO
:
4072 case WS_SO_SNDTIMEO
:
4076 if (!optlen
|| *optlen
< sizeof(int)|| !optval
)
4078 SetLastError(WSAEFAULT
);
4079 return SOCKET_ERROR
;
4081 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4082 return SOCKET_ERROR
;
4084 timeout
= get_rcvsnd_timeo(fd
, optname
== WS_SO_RCVTIMEO
);
4085 *(int *)optval
= timeout
<= UINT_MAX
? timeout
: UINT_MAX
;
4087 release_sock_fd( s
, fd
);
4093 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
4095 SetLastError(WSAEFAULT
);
4096 return SOCKET_ERROR
;
4098 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4099 return SOCKET_ERROR
;
4101 sock_type
= _get_fd_type(fd
);
4102 if (sock_type
== -1)
4104 SetLastError(wsaErrno());
4108 (*(int *)optval
) = convert_socktype_u2w(sock_type
);
4110 release_sock_fd( s
, fd
);
4114 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname
);
4115 SetLastError(WSAENOPROTOOPT
);
4116 return SOCKET_ERROR
;
4117 } /* end switch(optname) */
4118 }/* end case WS_SOL_SOCKET */
4120 case WS_NSPROTO_IPX
:
4122 struct WS_sockaddr_ipx addr
;
4123 IPX_ADDRESS_DATA
*data
;
4128 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
4130 if(getsockopt(fd
, SOL_IPX
, IPX_TYPE
, optval
, (socklen_t
*)optlen
) == -1)
4137 socklen_t len
=sizeof(struct ipx
);
4138 if(getsockopt(fd
, 0, SO_DEFAULT_HEADERS
, &val
, &len
) == -1 )
4141 *optval
= (int)val
.ipx_pt
;
4144 TRACE("ptype: %d (fd: %d)\n", *(int*)optval
, fd
);
4145 release_sock_fd( s
, fd
);
4148 case WS_IPX_ADDRESS
:
4150 * On a Win2000 system with one network card there are usually
4151 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
4152 * Using this call you can then retrieve info about this all.
4153 * In case of Linux it is a bit different. Usually you have
4154 * only "one" device active and further it is not possible to
4155 * query things like the linkspeed.
4157 FIXME("IPX_ADDRESS\n");
4158 namelen
= sizeof(struct WS_sockaddr_ipx
);
4159 memset(&addr
, 0, sizeof(struct WS_sockaddr_ipx
));
4160 WS_getsockname(s
, (struct WS_sockaddr
*)&addr
, &namelen
);
4162 data
= (IPX_ADDRESS_DATA
*)optval
;
4163 memcpy(data
->nodenum
,addr
.sa_nodenum
,sizeof(data
->nodenum
));
4164 memcpy(data
->netnum
,addr
.sa_netnum
,sizeof(data
->netnum
));
4165 data
->adapternum
= 0;
4166 data
->wan
= FALSE
; /* We are not on a wan for now .. */
4167 data
->status
= FALSE
; /* Since we are not on a wan, the wan link isn't up */
4168 data
->maxpkt
= 1467; /* This value is the default one, at least on Win2k/WinXP */
4169 data
->linkspeed
= 100000; /* Set the line speed in 100bit/s to 10 Mbit;
4170 * note 1MB = 1000kB in this case */
4173 case WS_IPX_MAX_ADAPTER_NUM
:
4174 FIXME("IPX_MAX_ADAPTER_NUM\n");
4175 *(int*)optval
= 1; /* As noted under IPX_ADDRESS we have just one card. */
4179 FIXME("IPX optname:%x\n", optname
);
4180 return SOCKET_ERROR
;
4181 }/* end switch(optname) */
4182 } /* end case WS_NSPROTO_IPX */
4186 #define MAX_IRDA_DEVICES 10
4191 case WS_IRLMP_ENUMDEVICES
:
4193 char buf
[sizeof(struct irda_device_list
) +
4194 (MAX_IRDA_DEVICES
- 1) * sizeof(struct irda_device_info
)];
4196 socklen_t len
= sizeof(buf
);
4198 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4199 return SOCKET_ERROR
;
4200 res
= getsockopt( fd
, SOL_IRLMP
, IRLMP_ENUMDEVICES
, buf
, &len
);
4201 release_sock_fd( s
, fd
);
4204 SetLastError(wsaErrno());
4205 return SOCKET_ERROR
;
4209 struct irda_device_list
*src
= (struct irda_device_list
*)buf
;
4210 DEVICELIST
*dst
= (DEVICELIST
*)optval
;
4211 INT needed
= sizeof(DEVICELIST
);
4215 needed
+= (src
->len
- 1) * sizeof(IRDA_DEVICE_INFO
);
4216 if (*optlen
< needed
)
4218 SetLastError(WSAEFAULT
);
4219 return SOCKET_ERROR
;
4222 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src
->len
);
4223 dst
->numDevice
= src
->len
;
4224 for (i
= 0; i
< src
->len
; i
++)
4226 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
4227 src
->dev
[i
].saddr
, src
->dev
[i
].daddr
,
4228 src
->dev
[i
].info
, src
->dev
[i
].hints
[0],
4229 src
->dev
[i
].hints
[1]);
4230 memcpy( dst
->Device
[i
].irdaDeviceID
,
4232 sizeof(dst
->Device
[i
].irdaDeviceID
) ) ;
4233 memcpy( dst
->Device
[i
].irdaDeviceName
,
4235 sizeof(dst
->Device
[i
].irdaDeviceName
) ) ;
4236 memcpy( &dst
->Device
[i
].irdaDeviceHints1
,
4237 &src
->dev
[i
].hints
[0],
4238 sizeof(dst
->Device
[i
].irdaDeviceHints1
) ) ;
4239 memcpy( &dst
->Device
[i
].irdaDeviceHints2
,
4240 &src
->dev
[i
].hints
[1],
4241 sizeof(dst
->Device
[i
].irdaDeviceHints2
) ) ;
4242 dst
->Device
[i
].irdaCharSet
= src
->dev
[i
].charset
;
4248 FIXME("IrDA optname:0x%x\n", optname
);
4249 return SOCKET_ERROR
;
4251 break; /* case WS_SOL_IRLMP */
4252 #undef MAX_IRDA_DEVICES
4255 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4256 case WS_IPPROTO_TCP
:
4259 case WS_TCP_NODELAY
:
4260 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4261 return SOCKET_ERROR
;
4262 convert_sockopt(&level
, &optname
);
4263 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
4265 SetLastError(wsaErrno());
4268 release_sock_fd( s
, fd
);
4271 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname
);
4272 return SOCKET_ERROR
;
4277 case WS_IP_ADD_MEMBERSHIP
:
4278 case WS_IP_DROP_MEMBERSHIP
:
4282 case WS_IP_MULTICAST_IF
:
4283 case WS_IP_MULTICAST_LOOP
:
4284 case WS_IP_MULTICAST_TTL
:
4291 #ifdef IP_UNICAST_IF
4292 case WS_IP_UNICAST_IF
:
4294 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4295 return SOCKET_ERROR
;
4296 convert_sockopt(&level
, &optname
);
4297 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
4299 SetLastError(wsaErrno());
4302 release_sock_fd( s
, fd
);
4304 case WS_IP_DONTFRAGMENT
:
4305 return get_dont_fragment(s
, IPPROTO_IP
, (BOOL
*)optval
) ? 0 : SOCKET_ERROR
;
4307 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname
);
4308 return SOCKET_ERROR
;
4310 case WS_IPPROTO_IPV6
:
4313 #ifdef IPV6_ADD_MEMBERSHIP
4314 case WS_IPV6_ADD_MEMBERSHIP
:
4316 #ifdef IPV6_DROP_MEMBERSHIP
4317 case WS_IPV6_DROP_MEMBERSHIP
:
4319 case WS_IPV6_MULTICAST_IF
:
4320 case WS_IPV6_MULTICAST_HOPS
:
4321 case WS_IPV6_MULTICAST_LOOP
:
4322 case WS_IPV6_UNICAST_HOPS
:
4323 case WS_IPV6_V6ONLY
:
4324 #ifdef IPV6_UNICAST_IF
4325 case WS_IPV6_UNICAST_IF
:
4327 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4328 return SOCKET_ERROR
;
4329 convert_sockopt(&level
, &optname
);
4330 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
4332 SetLastError(wsaErrno());
4335 release_sock_fd( s
, fd
);
4337 case WS_IPV6_DONTFRAG
:
4338 return get_dont_fragment(s
, IPPROTO_IPV6
, (BOOL
*)optval
) ? 0 : SOCKET_ERROR
;
4340 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname
);
4341 return SOCKET_ERROR
;
4344 WARN("Unknown level: 0x%08x\n", level
);
4345 SetLastError(WSAEINVAL
);
4346 return SOCKET_ERROR
;
4347 } /* end switch(level) */
4350 /***********************************************************************
4353 WS_u_long WINAPI
WS_htonl(WS_u_long hostlong
)
4355 return htonl(hostlong
);
4359 /***********************************************************************
4362 WS_u_short WINAPI
WS_htons(WS_u_short hostshort
)
4364 return htons(hostshort
);
4367 /***********************************************************************
4368 * WSAHtonl (WS2_32.46)
4369 * From MSDN description of error codes, this function should also
4370 * check if WinSock has been initialized and the socket is a valid
4371 * socket. But why? This function only translates a host byte order
4372 * u_long into a network byte order u_long...
4374 int WINAPI
WSAHtonl(SOCKET s
, WS_u_long hostlong
, WS_u_long
*lpnetlong
)
4378 *lpnetlong
= htonl(hostlong
);
4381 SetLastError(WSAEFAULT
);
4382 return SOCKET_ERROR
;
4385 /***********************************************************************
4386 * WSAHtons (WS2_32.47)
4387 * From MSDN description of error codes, this function should also
4388 * check if WinSock has been initialized and the socket is a valid
4389 * socket. But why? This function only translates a host byte order
4390 * u_short into a network byte order u_short...
4392 int WINAPI
WSAHtons(SOCKET s
, WS_u_short hostshort
, WS_u_short
*lpnetshort
)
4397 *lpnetshort
= htons(hostshort
);
4400 SetLastError(WSAEFAULT
);
4401 return SOCKET_ERROR
;
4405 /***********************************************************************
4406 * inet_addr (WS2_32.11)
4408 WS_u_long WINAPI
WS_inet_addr(const char *cp
)
4410 if (!cp
) return INADDR_NONE
;
4411 return inet_addr(cp
);
4415 /***********************************************************************
4418 WS_u_long WINAPI
WS_ntohl(WS_u_long netlong
)
4420 return ntohl(netlong
);
4424 /***********************************************************************
4427 WS_u_short WINAPI
WS_ntohs(WS_u_short netshort
)
4429 return ntohs(netshort
);
4433 /***********************************************************************
4434 * inet_ntoa (WS2_32.12)
4436 char* WINAPI
WS_inet_ntoa(struct WS_in_addr in
)
4438 unsigned int long_ip
= ntohl(in
.WS_s_addr
);
4439 struct per_thread_data
*data
= get_per_thread_data();
4441 sprintf( data
->ntoa_buffer
, "%u.%u.%u.%u",
4442 (long_ip
>> 24) & 0xff,
4443 (long_ip
>> 16) & 0xff,
4444 (long_ip
>> 8) & 0xff,
4447 return data
->ntoa_buffer
;
4450 static const char *debugstr_wsaioctl(DWORD code
)
4452 const char *name
= NULL
, *buf_type
, *family
;
4454 #define IOCTL_NAME(x) case x: name = #x; break
4457 IOCTL_NAME(WS_FIONBIO
);
4458 IOCTL_NAME(WS_FIONREAD
);
4459 IOCTL_NAME(WS_SIOCATMARK
);
4460 /* IOCTL_NAME(WS_SIO_ACQUIRE_PORT_RESERVATION); */
4461 IOCTL_NAME(WS_SIO_ADDRESS_LIST_CHANGE
);
4462 IOCTL_NAME(WS_SIO_ADDRESS_LIST_QUERY
);
4463 IOCTL_NAME(WS_SIO_ASSOCIATE_HANDLE
);
4464 /* IOCTL_NAME(WS_SIO_ASSOCIATE_PORT_RESERVATION);
4465 IOCTL_NAME(WS_SIO_BASE_HANDLE);
4466 IOCTL_NAME(WS_SIO_BSP_HANDLE);
4467 IOCTL_NAME(WS_SIO_BSP_HANDLE_SELECT);
4468 IOCTL_NAME(WS_SIO_BSP_HANDLE_POLL);
4469 IOCTL_NAME(WS_SIO_CHK_QOS); */
4470 IOCTL_NAME(WS_SIO_ENABLE_CIRCULAR_QUEUEING
);
4471 IOCTL_NAME(WS_SIO_FIND_ROUTE
);
4472 IOCTL_NAME(WS_SIO_FLUSH
);
4473 IOCTL_NAME(WS_SIO_GET_BROADCAST_ADDRESS
);
4474 IOCTL_NAME(WS_SIO_GET_EXTENSION_FUNCTION_POINTER
);
4475 IOCTL_NAME(WS_SIO_GET_GROUP_QOS
);
4476 IOCTL_NAME(WS_SIO_GET_INTERFACE_LIST
);
4477 /* IOCTL_NAME(WS_SIO_GET_INTERFACE_LIST_EX); */
4478 IOCTL_NAME(WS_SIO_GET_QOS
);
4479 /* IOCTL_NAME(WS_SIO_IDEAL_SEND_BACKLOG_CHANGE);
4480 IOCTL_NAME(WS_SIO_IDEAL_SEND_BACKLOG_QUERY); */
4481 IOCTL_NAME(WS_SIO_KEEPALIVE_VALS
);
4482 IOCTL_NAME(WS_SIO_MULTIPOINT_LOOPBACK
);
4483 IOCTL_NAME(WS_SIO_MULTICAST_SCOPE
);
4484 /* IOCTL_NAME(WS_SIO_QUERY_RSS_SCALABILITY_INFO);
4485 IOCTL_NAME(WS_SIO_QUERY_WFP_ALE_ENDPOINT_HANDLE); */
4486 IOCTL_NAME(WS_SIO_RCVALL
);
4487 IOCTL_NAME(WS_SIO_RCVALL_IGMPMCAST
);
4488 IOCTL_NAME(WS_SIO_RCVALL_MCAST
);
4489 /* IOCTL_NAME(WS_SIO_RELEASE_PORT_RESERVATION); */
4490 IOCTL_NAME(WS_SIO_ROUTING_INTERFACE_CHANGE
);
4491 IOCTL_NAME(WS_SIO_ROUTING_INTERFACE_QUERY
);
4492 IOCTL_NAME(WS_SIO_SET_COMPATIBILITY_MODE
);
4493 IOCTL_NAME(WS_SIO_SET_GROUP_QOS
);
4494 IOCTL_NAME(WS_SIO_SET_QOS
);
4495 IOCTL_NAME(WS_SIO_TRANSLATE_HANDLE
);
4496 IOCTL_NAME(WS_SIO_UDP_CONNRESET
);
4503 /* If this is not a known code split its bits */
4504 switch(code
& 0x18000000)
4509 case WS_IOC_PROTOCOL
:
4510 family
= "IOC_PROTOCOL";
4513 family
= "IOC_VENDOR";
4515 default: /* WS_IOC_UNIX */
4517 BYTE size
= (code
>> 16) & WS_IOCPARM_MASK
;
4518 char x
= (code
& 0xff00) >> 8;
4519 BYTE y
= code
& 0xff;
4522 switch (code
& (WS_IOC_VOID
|WS_IOC_INOUT
))
4526 sprintf(args
, "%d, %d", x
, y
);
4530 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
4534 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
4538 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
4541 return wine_dbg_sprintf("%s(%s)", buf_type
, args
);
4545 /* We are different from WS_IOC_UNIX. */
4546 switch (code
& (WS_IOC_VOID
|WS_IOC_INOUT
))
4549 buf_type
= "_WSAIO";
4552 buf_type
= "_WSAIORW";
4555 buf_type
= "_WSAIOW";
4558 buf_type
= "_WSAIOR";
4565 return wine_dbg_sprintf("%s(%s, %d)", buf_type
, family
,
4566 (USHORT
)(code
& 0xffff));
4569 /* do an ioctl call through the server */
4570 static DWORD
server_ioctl_sock( SOCKET s
, DWORD code
, LPVOID in_buff
, DWORD in_size
,
4571 LPVOID out_buff
, DWORD out_size
, LPDWORD ret_size
,
4572 LPWSAOVERLAPPED overlapped
,
4573 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
4575 HANDLE event
= overlapped
? overlapped
->hEvent
: 0;
4576 HANDLE handle
= SOCKET2HANDLE( s
);
4577 struct ws2_async
*wsa
= NULL
;
4578 IO_STATUS_BLOCK
*io
= (PIO_STATUS_BLOCK
)overlapped
, iosb
;
4579 void *cvalue
= NULL
;
4584 if (!(wsa
= (struct ws2_async
*)alloc_async_io( sizeof(*wsa
), NULL
)))
4585 return WSA_NOT_ENOUGH_MEMORY
;
4586 wsa
->hSocket
= handle
;
4587 wsa
->user_overlapped
= overlapped
;
4588 wsa
->completion_func
= completion
;
4589 if (!io
) io
= &wsa
->local_iosb
;
4594 else if (!((ULONG_PTR
)overlapped
->hEvent
& 1))
4595 cvalue
= overlapped
;
4597 status
= NtDeviceIoControlFile( handle
, event
, wsa
? ws2_async_apc
: NULL
, cvalue
, io
, code
,
4598 in_buff
, in_size
, out_buff
, out_size
);
4599 if (status
== STATUS_NOT_SUPPORTED
)
4601 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
4602 code
, code
>> 16, (code
>> 14) & 3, (code
>> 2) & 0xfff, code
& 3);
4604 else if (status
== STATUS_SUCCESS
)
4605 *ret_size
= io
->Information
; /* "Information" is the size written to the output buffer */
4607 if (status
!= STATUS_PENDING
) RtlFreeHeap( GetProcessHeap(), 0, wsa
);
4609 return NtStatusToWSAError( status
);
4612 /**********************************************************************
4613 * WSAIoctl (WS2_32.50)
4616 INT WINAPI
WSAIoctl(SOCKET s
, DWORD code
, LPVOID in_buff
, DWORD in_size
, LPVOID out_buff
,
4617 DWORD out_size
, LPDWORD ret_size
, LPWSAOVERLAPPED overlapped
,
4618 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
4621 DWORD status
= 0, total
= 0;
4623 TRACE("%04lx, %s, %p, %d, %p, %d, %p, %p, %p\n",
4624 s
, debugstr_wsaioctl(code
), in_buff
, in_size
, out_buff
, out_size
, ret_size
, overlapped
, completion
);
4629 if (in_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(in_buff
))
4631 SetLastError(WSAEFAULT
);
4632 return SOCKET_ERROR
;
4634 TRACE("-> FIONBIO (%x)\n", *(WS_u_long
*)in_buff
);
4635 if (_get_sock_mask(s
))
4637 /* AsyncSelect()'ed sockets are always nonblocking */
4638 if (!*(WS_u_long
*)in_buff
) status
= WSAEINVAL
;
4641 if (*(WS_u_long
*)in_buff
)
4642 _enable_event(SOCKET2HANDLE(s
), 0, FD_WINE_NONBLOCKING
, 0);
4644 _enable_event(SOCKET2HANDLE(s
), 0, 0, FD_WINE_NONBLOCKING
);
4649 if (out_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(out_buff
))
4651 SetLastError(WSAEFAULT
);
4652 return SOCKET_ERROR
;
4654 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
4655 if (ioctl(fd
, FIONREAD
, out_buff
) == -1)
4656 status
= wsaErrno();
4657 release_sock_fd( s
, fd
);
4663 unsigned int oob
= 0, atmark
= 0;
4664 socklen_t oobsize
= sizeof(int);
4665 if (out_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(out_buff
))
4667 SetLastError(WSAEFAULT
);
4668 return SOCKET_ERROR
;
4670 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
4671 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
4672 if ((getsockopt(fd
, SOL_SOCKET
, SO_OOBINLINE
, &oob
, &oobsize
) == -1)
4673 || (!oob
&& ioctl(fd
, SIOCATMARK
, &atmark
) == -1))
4674 status
= wsaErrno();
4677 /* The SIOCATMARK value read from ioctl() is reversed
4678 * because BSD returns TRUE if it's in the OOB mark
4679 * while Windows returns TRUE if there are NO OOB bytes.
4681 (*(WS_u_long
*) out_buff
) = oob
|| !atmark
;
4684 release_sock_fd( s
, fd
);
4689 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
4690 SetLastError(WSAEINVAL
);
4691 return SOCKET_ERROR
;
4693 case WS_SIO_GET_INTERFACE_LIST
:
4695 INTERFACE_INFO
* intArray
= out_buff
;
4696 DWORD size
, numInt
= 0, apiReturn
;
4698 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
4700 if (!out_buff
|| !ret_size
)
4702 SetLastError(WSAEFAULT
);
4703 return SOCKET_ERROR
;
4706 fd
= get_sock_fd( s
, 0, NULL
);
4707 if (fd
== -1) return SOCKET_ERROR
;
4709 apiReturn
= GetAdaptersInfo(NULL
, &size
);
4710 if (apiReturn
== ERROR_BUFFER_OVERFLOW
)
4712 PIP_ADAPTER_INFO table
= HeapAlloc(GetProcessHeap(),0,size
);
4716 if (GetAdaptersInfo(table
, &size
) == NO_ERROR
)
4718 PIP_ADAPTER_INFO ptr
;
4720 for (ptr
= table
, numInt
= 0; ptr
; ptr
= ptr
->Next
)
4722 unsigned int addr
, mask
, bcast
;
4723 struct ifreq ifInfo
;
4725 /* Skip interfaces without an IPv4 address. */
4726 if (ptr
->IpAddressList
.IpAddress
.String
[0] == '\0')
4729 if ((numInt
+ 1)*sizeof(INTERFACE_INFO
)/sizeof(IP_ADAPTER_INFO
) > out_size
)
4731 WARN("Buffer too small = %u, out_size = %u\n", numInt
+ 1, out_size
);
4736 /* Socket Status Flags */
4737 lstrcpynA(ifInfo
.ifr_name
, ptr
->AdapterName
, IFNAMSIZ
);
4738 if (ioctl(fd
, SIOCGIFFLAGS
, &ifInfo
) < 0)
4740 ERR("Error obtaining status flags for socket!\n");
4746 /* set flags; the values of IFF_* are not the same
4747 under Linux and Windows, therefore must generate
4749 intArray
->iiFlags
= 0;
4750 if (ifInfo
.ifr_flags
& IFF_BROADCAST
)
4751 intArray
->iiFlags
|= WS_IFF_BROADCAST
;
4752 #ifdef IFF_POINTOPOINT
4753 if (ifInfo
.ifr_flags
& IFF_POINTOPOINT
)
4754 intArray
->iiFlags
|= WS_IFF_POINTTOPOINT
;
4756 if (ifInfo
.ifr_flags
& IFF_LOOPBACK
)
4757 intArray
->iiFlags
|= WS_IFF_LOOPBACK
;
4758 if (ifInfo
.ifr_flags
& IFF_UP
)
4759 intArray
->iiFlags
|= WS_IFF_UP
;
4760 if (ifInfo
.ifr_flags
& IFF_MULTICAST
)
4761 intArray
->iiFlags
|= WS_IFF_MULTICAST
;
4764 addr
= inet_addr(ptr
->IpAddressList
.IpAddress
.String
);
4765 mask
= inet_addr(ptr
->IpAddressList
.IpMask
.String
);
4766 bcast
= addr
| ~mask
;
4767 intArray
->iiAddress
.AddressIn
.sin_family
= WS_AF_INET
;
4768 intArray
->iiAddress
.AddressIn
.sin_port
= 0;
4769 intArray
->iiAddress
.AddressIn
.sin_addr
.WS_s_addr
= addr
;
4771 intArray
->iiNetmask
.AddressIn
.sin_family
= WS_AF_INET
;
4772 intArray
->iiNetmask
.AddressIn
.sin_port
= 0;
4773 intArray
->iiNetmask
.AddressIn
.sin_addr
.WS_s_addr
= mask
;
4775 intArray
->iiBroadcastAddress
.AddressIn
.sin_family
= WS_AF_INET
;
4776 intArray
->iiBroadcastAddress
.AddressIn
.sin_port
= 0;
4777 intArray
->iiBroadcastAddress
.AddressIn
.sin_addr
.WS_s_addr
= bcast
;
4784 ERR("Unable to get interface table!\n");
4787 HeapFree(GetProcessHeap(),0,table
);
4789 else status
= WSAEINVAL
;
4791 else if (apiReturn
!= ERROR_NO_DATA
)
4793 ERR("Unable to get interface table!\n");
4796 /* Calculate the size of the array being returned */
4797 total
= sizeof(INTERFACE_INFO
) * numInt
;
4798 release_sock_fd( s
, fd
);
4802 case WS_SIO_ADDRESS_LIST_QUERY
:
4806 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
4810 SetLastError(WSAEFAULT
);
4811 return SOCKET_ERROR
;
4814 if (out_size
&& out_size
< FIELD_OFFSET(SOCKET_ADDRESS_LIST
, Address
[0]))
4817 SetLastError(WSAEINVAL
);
4818 return SOCKET_ERROR
;
4821 if (GetAdaptersInfo(NULL
, &size
) == ERROR_BUFFER_OVERFLOW
)
4823 IP_ADAPTER_INFO
*p
, *table
= HeapAlloc(GetProcessHeap(), 0, size
);
4824 SOCKET_ADDRESS_LIST
*sa_list
;
4825 SOCKADDR_IN
*sockaddr
;
4830 if (!table
|| GetAdaptersInfo(table
, &size
))
4832 HeapFree(GetProcessHeap(), 0, table
);
4837 for (p
= table
, num
= 0; p
; p
= p
->Next
)
4838 if (p
->IpAddressList
.IpAddress
.String
[0]) num
++;
4840 total
= FIELD_OFFSET(SOCKET_ADDRESS_LIST
, Address
[num
]) + num
* sizeof(*sockaddr
);
4841 if (total
> out_size
|| !out_buff
)
4844 HeapFree(GetProcessHeap(), 0, table
);
4850 sa
= sa_list
->Address
;
4851 sockaddr
= (SOCKADDR_IN
*)&sa
[num
];
4852 sa_list
->iAddressCount
= num
;
4854 for (p
= table
, i
= 0; p
; p
= p
->Next
)
4856 if (!p
->IpAddressList
.IpAddress
.String
[0]) continue;
4858 sa
[i
].lpSockaddr
= (SOCKADDR
*)&sockaddr
[i
];
4859 sa
[i
].iSockaddrLength
= sizeof(SOCKADDR
);
4861 sockaddr
[i
].sin_family
= WS_AF_INET
;
4862 sockaddr
[i
].sin_port
= 0;
4863 sockaddr
[i
].sin_addr
.WS_s_addr
= inet_addr(p
->IpAddressList
.IpAddress
.String
);
4867 HeapFree(GetProcessHeap(), 0, table
);
4871 WARN("unable to get IP address list\n");
4878 FIXME("SIO_FLUSH: stub.\n");
4881 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER
:
4883 #define EXTENSION_FUNCTION(x, y) { x, y, #y },
4890 EXTENSION_FUNCTION(WSAID_CONNECTEX
, WS2_ConnectEx
)
4891 EXTENSION_FUNCTION(WSAID_DISCONNECTEX
, WS2_DisconnectEx
)
4892 EXTENSION_FUNCTION(WSAID_ACCEPTEX
, WS2_AcceptEx
)
4893 EXTENSION_FUNCTION(WSAID_GETACCEPTEXSOCKADDRS
, WS2_GetAcceptExSockaddrs
)
4894 EXTENSION_FUNCTION(WSAID_TRANSMITFILE
, WS2_TransmitFile
)
4895 /* EXTENSION_FUNCTION(WSAID_TRANSMITPACKETS, WS2_TransmitPackets) */
4896 EXTENSION_FUNCTION(WSAID_WSARECVMSG
, WS2_WSARecvMsg
)
4897 EXTENSION_FUNCTION(WSAID_WSASENDMSG
, WSASendMsg
)
4899 #undef EXTENSION_FUNCTION
4903 for (i
= 0; i
< sizeof(guid_funcs
) / sizeof(guid_funcs
[0]); i
++)
4905 if (IsEqualGUID(&guid_funcs
[i
].guid
, in_buff
))
4914 TRACE("-> got %s\n", guid_funcs
[i
].name
);
4915 *(void **)out_buff
= guid_funcs
[i
].func_ptr
;
4916 total
= sizeof(void *);
4920 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff
));
4921 status
= WSAEOPNOTSUPP
;
4924 case WS_SIO_KEEPALIVE_VALS
:
4926 struct tcp_keepalive
*k
;
4927 int keepalive
, keepidle
, keepintvl
;
4929 if (!in_buff
|| in_size
< sizeof(struct tcp_keepalive
))
4931 SetLastError(WSAEFAULT
);
4932 return SOCKET_ERROR
;
4936 keepalive
= k
->onoff
? 1 : 0;
4937 keepidle
= max( 1, (k
->keepalivetime
+ 500) / 1000 );
4938 keepintvl
= max( 1, (k
->keepaliveinterval
+ 500) / 1000 );
4940 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive
, keepidle
, keepintvl
);
4942 fd
= get_sock_fd(s
, 0, NULL
);
4943 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&keepalive
, sizeof(int)) == -1)
4945 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPINTVL)
4946 /* these values need to be set only if SO_KEEPALIVE is enabled */
4949 #ifndef TCP_KEEPIDLE
4950 FIXME("ignoring keepalive timeout\n");
4952 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPIDLE
, (void *)&keepidle
, sizeof(int)) == -1)
4956 #ifdef TCP_KEEPINTVL
4957 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPINTVL
, (void *)&keepintvl
, sizeof(int)) == -1)
4960 FIXME("ignoring keepalive interval\n");
4965 FIXME("ignoring keepalive interval and timeout\n");
4967 release_sock_fd(s
, fd
);
4970 case WS_SIO_ROUTING_INTERFACE_QUERY
:
4972 struct WS_sockaddr
*daddr
= (struct WS_sockaddr
*)in_buff
;
4973 struct WS_sockaddr_in
*daddr_in
= (struct WS_sockaddr_in
*)daddr
;
4974 struct WS_sockaddr_in
*saddr_in
= out_buff
;
4975 MIB_IPFORWARDROW row
;
4976 PMIB_IPADDRTABLE ipAddrTable
= NULL
;
4977 DWORD size
, i
, found_index
;
4979 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4981 if (!in_buff
|| in_size
< sizeof(struct WS_sockaddr
) ||
4982 !out_buff
|| out_size
< sizeof(struct WS_sockaddr_in
) || !ret_size
)
4984 SetLastError(WSAEFAULT
);
4985 return SOCKET_ERROR
;
4987 if (daddr
->sa_family
!= WS_AF_INET
)
4989 FIXME("unsupported address family %d\n", daddr
->sa_family
);
4990 status
= WSAEAFNOSUPPORT
;
4993 if (GetBestRoute(daddr_in
->sin_addr
.S_un
.S_addr
, 0, &row
) != NOERROR
||
4994 GetIpAddrTable(NULL
, &size
, FALSE
) != ERROR_INSUFFICIENT_BUFFER
)
4999 ipAddrTable
= HeapAlloc(GetProcessHeap(), 0, size
);
5000 if (GetIpAddrTable(ipAddrTable
, &size
, FALSE
))
5002 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
5006 for (i
= 0, found_index
= ipAddrTable
->dwNumEntries
;
5007 i
< ipAddrTable
->dwNumEntries
; i
++)
5009 if (ipAddrTable
->table
[i
].dwIndex
== row
.dwForwardIfIndex
)
5012 if (found_index
== ipAddrTable
->dwNumEntries
)
5014 ERR("no matching IP address for interface %d\n",
5015 row
.dwForwardIfIndex
);
5016 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
5020 saddr_in
->sin_family
= WS_AF_INET
;
5021 saddr_in
->sin_addr
.S_un
.S_addr
= ipAddrTable
->table
[found_index
].dwAddr
;
5022 saddr_in
->sin_port
= 0;
5023 total
= sizeof(struct WS_sockaddr_in
);
5024 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
5027 case WS_SIO_SET_COMPATIBILITY_MODE
:
5028 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
5029 status
= WSAEOPNOTSUPP
;
5031 case WS_SIO_UDP_CONNRESET
:
5032 FIXME("WS_SIO_UDP_CONNRESET stub\n");
5034 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
5035 SetLastError(WSAEOPNOTSUPP
);
5036 return SOCKET_ERROR
;
5038 status
= WSAEOPNOTSUPP
;
5042 if (status
== WSAEOPNOTSUPP
)
5044 status
= server_ioctl_sock(s
, code
, in_buff
, in_size
, out_buff
, out_size
, &total
,
5045 overlapped
, completion
);
5046 if (status
!= WSAEOPNOTSUPP
)
5048 if (status
== 0 || status
== WSA_IO_PENDING
)
5049 TRACE("-> %s request\n", debugstr_wsaioctl(code
));
5051 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code
), status
);
5053 /* overlapped and completion operations will be handled by the server */
5058 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code
));
5063 FIXME( "completion routine %p not supported\n", completion
);
5065 else if (overlapped
)
5067 ULONG_PTR cvalue
= (overlapped
&& ((ULONG_PTR
)overlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)overlapped
: 0;
5068 overlapped
->Internal
= status
;
5069 overlapped
->InternalHigh
= total
;
5070 if (overlapped
->hEvent
) NtSetEvent( overlapped
->hEvent
, NULL
);
5071 if (cvalue
) WS_AddCompletion( HANDLE2SOCKET(s
), cvalue
, status
, total
);
5076 if (ret_size
) *ret_size
= total
;
5079 SetLastError( status
);
5080 return SOCKET_ERROR
;
5084 /***********************************************************************
5085 * ioctlsocket (WS2_32.10)
5087 int WINAPI
WS_ioctlsocket(SOCKET s
, LONG cmd
, WS_u_long
*argp
)
5090 return WSAIoctl( s
, cmd
, argp
, sizeof(WS_u_long
), argp
, sizeof(WS_u_long
), &ret_size
, NULL
, NULL
);
5093 /***********************************************************************
5094 * listen (WS2_32.13)
5096 int WINAPI
WS_listen(SOCKET s
, int backlog
)
5098 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
), ret
= SOCKET_ERROR
;
5100 TRACE("socket %04lx, backlog %d\n", s
, backlog
);
5103 int bound
= is_fd_bound(fd
, NULL
, NULL
);
5107 SetLastError(bound
== -1 ? wsaErrno() : WSAEINVAL
);
5109 else if (listen(fd
, backlog
) == 0)
5111 _enable_event(SOCKET2HANDLE(s
), FD_ACCEPT
,
5113 FD_CONNECT
|FD_WINE_CONNECTED
);
5117 SetLastError(wsaErrno());
5118 release_sock_fd( s
, fd
);
5121 SetLastError(WSAENOTSOCK
);
5125 /***********************************************************************
5128 int WINAPI
WS_recv(SOCKET s
, char *buf
, int len
, int flags
)
5130 DWORD n
, dwFlags
= flags
;
5136 if ( WS2_recv_base(s
, &wsabuf
, 1, &n
, &dwFlags
, NULL
, NULL
, NULL
, NULL
, NULL
) == SOCKET_ERROR
)
5137 return SOCKET_ERROR
;
5142 /***********************************************************************
5143 * recvfrom (WS2_32.17)
5145 int WINAPI
WS_recvfrom(SOCKET s
, char *buf
, INT len
, int flags
,
5146 struct WS_sockaddr
*from
, int *fromlen
)
5148 DWORD n
, dwFlags
= flags
;
5154 if ( WS2_recv_base(s
, &wsabuf
, 1, &n
, &dwFlags
, from
, fromlen
, NULL
, NULL
, NULL
) == SOCKET_ERROR
)
5155 return SOCKET_ERROR
;
5160 /* allocate a poll array for the corresponding fd sets */
5161 static struct pollfd
*fd_sets_to_poll( const WS_fd_set
*readfds
, const WS_fd_set
*writefds
,
5162 const WS_fd_set
*exceptfds
, int *count_ptr
)
5164 unsigned int i
, j
= 0, count
= 0;
5166 struct per_thread_data
*ptb
= get_per_thread_data();
5168 if (readfds
) count
+= readfds
->fd_count
;
5169 if (writefds
) count
+= writefds
->fd_count
;
5170 if (exceptfds
) count
+= exceptfds
->fd_count
;
5174 SetLastError(WSAEINVAL
);
5178 /* check if the cache can hold all descriptors, if not do the resizing */
5179 if (ptb
->fd_count
< count
)
5181 if (!(fds
= HeapAlloc(GetProcessHeap(), 0, count
* sizeof(fds
[0]))))
5183 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
5186 HeapFree(GetProcessHeap(), 0, ptb
->fd_cache
);
5187 ptb
->fd_cache
= fds
;
5188 ptb
->fd_count
= count
;
5191 fds
= ptb
->fd_cache
;
5194 for (i
= 0; i
< readfds
->fd_count
; i
++, j
++)
5196 fds
[j
].fd
= get_sock_fd( readfds
->fd_array
[i
], FILE_READ_DATA
, NULL
);
5197 if (fds
[j
].fd
== -1) goto failed
;
5199 if (is_fd_bound(fds
[j
].fd
, NULL
, NULL
) == 1)
5201 fds
[j
].events
= POLLIN
;
5205 release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
5211 for (i
= 0; i
< writefds
->fd_count
; i
++, j
++)
5213 fds
[j
].fd
= get_sock_fd( writefds
->fd_array
[i
], FILE_WRITE_DATA
, NULL
);
5214 if (fds
[j
].fd
== -1) goto failed
;
5216 if (is_fd_bound(fds
[j
].fd
, NULL
, NULL
) == 1 ||
5217 _get_fd_type(fds
[j
].fd
) == SOCK_DGRAM
)
5219 fds
[j
].events
= POLLOUT
;
5223 release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
5229 for (i
= 0; i
< exceptfds
->fd_count
; i
++, j
++)
5231 fds
[j
].fd
= get_sock_fd( exceptfds
->fd_array
[i
], 0, NULL
);
5232 if (fds
[j
].fd
== -1) goto failed
;
5234 if (is_fd_bound(fds
[j
].fd
, NULL
, NULL
) == 1)
5236 int oob_inlined
= 0;
5237 socklen_t olen
= sizeof(oob_inlined
);
5239 fds
[j
].events
= POLLHUP
;
5241 /* Check if we need to test for urgent data or not */
5242 getsockopt(fds
[j
].fd
, SOL_SOCKET
, SO_OOBINLINE
, (char*) &oob_inlined
, &olen
);
5244 fds
[j
].events
|= POLLPRI
;
5248 release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
5259 for (i
= 0; i
< readfds
->fd_count
&& j
< count
; i
++, j
++)
5260 if (fds
[j
].fd
!= -1) release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
5262 for (i
= 0; i
< writefds
->fd_count
&& j
< count
; i
++, j
++)
5263 if (fds
[j
].fd
!= -1) release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
5265 for (i
= 0; i
< exceptfds
->fd_count
&& j
< count
; i
++, j
++)
5266 if (fds
[j
].fd
!= -1) release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
5270 /* release the file descriptor obtained in fd_sets_to_poll */
5271 /* must be called with the original fd_set arrays, before calling get_poll_results */
5272 static void release_poll_fds( const WS_fd_set
*readfds
, const WS_fd_set
*writefds
,
5273 const WS_fd_set
*exceptfds
, struct pollfd
*fds
)
5275 unsigned int i
, j
= 0;
5279 for (i
= 0; i
< readfds
->fd_count
; i
++, j
++)
5280 if (fds
[j
].fd
!= -1) release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
5284 for (i
= 0; i
< writefds
->fd_count
; i
++, j
++)
5285 if (fds
[j
].fd
!= -1) release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
5289 for (i
= 0; i
< exceptfds
->fd_count
; i
++, j
++)
5291 if (fds
[j
].fd
== -1) continue;
5292 release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
5293 if (fds
[j
].revents
& POLLHUP
)
5295 int fd
= get_sock_fd( exceptfds
->fd_array
[i
], 0, NULL
);
5297 release_sock_fd( exceptfds
->fd_array
[i
], fd
);
5305 static int do_poll(struct pollfd
*pollfds
, int count
, int timeout
)
5307 struct timeval tv1
, tv2
;
5308 int ret
, torig
= timeout
;
5310 if (timeout
> 0) gettimeofday( &tv1
, 0 );
5312 while ((ret
= poll( pollfds
, count
, timeout
)) < 0)
5314 if (errno
!= EINTR
) break;
5315 if (timeout
< 0) continue;
5316 if (timeout
== 0) return 0;
5318 gettimeofday( &tv2
, 0 );
5320 tv2
.tv_sec
-= tv1
.tv_sec
;
5321 tv2
.tv_usec
-= tv1
.tv_usec
;
5322 if (tv2
.tv_usec
< 0)
5324 tv2
.tv_usec
+= 1000000;
5328 timeout
= torig
- (tv2
.tv_sec
* 1000) - (tv2
.tv_usec
+ 999) / 1000;
5329 if (timeout
<= 0) return 0;
5334 /* map the poll results back into the Windows fd sets */
5335 static int get_poll_results( WS_fd_set
*readfds
, WS_fd_set
*writefds
, WS_fd_set
*exceptfds
,
5336 const struct pollfd
*fds
)
5338 const struct pollfd
*poll_writefds
= fds
+ (readfds
? readfds
->fd_count
: 0);
5339 const struct pollfd
*poll_exceptfds
= poll_writefds
+ (writefds
? writefds
->fd_count
: 0);
5340 unsigned int i
, k
, total
= 0;
5344 for (i
= k
= 0; i
< readfds
->fd_count
; i
++)
5346 if (fds
[i
].revents
||
5347 (readfds
== writefds
&& (poll_writefds
[i
].revents
& POLLOUT
) && !(poll_writefds
[i
].revents
& POLLHUP
)) ||
5348 (readfds
== exceptfds
&& poll_exceptfds
[i
].revents
))
5349 readfds
->fd_array
[k
++] = readfds
->fd_array
[i
];
5351 readfds
->fd_count
= k
;
5354 if (writefds
&& writefds
!= readfds
)
5356 for (i
= k
= 0; i
< writefds
->fd_count
; i
++)
5358 if (((poll_writefds
[i
].revents
& POLLOUT
) && !(poll_writefds
[i
].revents
& POLLHUP
)) ||
5359 (writefds
== exceptfds
&& poll_exceptfds
[i
].revents
))
5360 writefds
->fd_array
[k
++] = writefds
->fd_array
[i
];
5362 writefds
->fd_count
= k
;
5365 if (exceptfds
&& exceptfds
!= readfds
&& exceptfds
!= writefds
)
5367 for (i
= k
= 0; i
< exceptfds
->fd_count
; i
++)
5368 if (poll_exceptfds
[i
].revents
) exceptfds
->fd_array
[k
++] = exceptfds
->fd_array
[i
];
5369 exceptfds
->fd_count
= k
;
5375 /***********************************************************************
5376 * select (WS2_32.18)
5378 int WINAPI
WS_select(int nfds
, WS_fd_set
*ws_readfds
,
5379 WS_fd_set
*ws_writefds
, WS_fd_set
*ws_exceptfds
,
5380 const struct WS_timeval
* ws_timeout
)
5382 struct pollfd
*pollfds
;
5383 int count
, ret
, timeout
= -1;
5385 TRACE("read %p, write %p, excp %p timeout %p\n",
5386 ws_readfds
, ws_writefds
, ws_exceptfds
, ws_timeout
);
5388 if (!(pollfds
= fd_sets_to_poll( ws_readfds
, ws_writefds
, ws_exceptfds
, &count
)))
5389 return SOCKET_ERROR
;
5392 timeout
= (ws_timeout
->tv_sec
* 1000) + (ws_timeout
->tv_usec
+ 999) / 1000;
5394 ret
= do_poll(pollfds
, count
, timeout
);
5395 release_poll_fds( ws_readfds
, ws_writefds
, ws_exceptfds
, pollfds
);
5397 if (ret
== -1) SetLastError(wsaErrno());
5398 else ret
= get_poll_results( ws_readfds
, ws_writefds
, ws_exceptfds
, pollfds
);
5402 /***********************************************************************
5405 int WINAPI
WSAPoll(WSAPOLLFD
*wfds
, ULONG count
, int timeout
)
5408 struct pollfd
*ufds
;
5412 SetLastError(WSAEINVAL
);
5413 return SOCKET_ERROR
;
5417 SetLastError(WSAEFAULT
);
5418 return SOCKET_ERROR
;
5421 if (!(ufds
= HeapAlloc(GetProcessHeap(), 0, count
* sizeof(ufds
[0]))))
5423 SetLastError(WSAENOBUFS
);
5424 return SOCKET_ERROR
;
5427 for (i
= 0; i
< count
; i
++)
5429 ufds
[i
].fd
= get_sock_fd(wfds
[i
].fd
, 0, NULL
);
5430 ufds
[i
].events
= convert_poll_w2u(wfds
[i
].events
);
5431 ufds
[i
].revents
= 0;
5434 ret
= do_poll(ufds
, count
, timeout
);
5436 for (i
= 0; i
< count
; i
++)
5438 if (ufds
[i
].fd
!= -1)
5440 release_sock_fd(wfds
[i
].fd
, ufds
[i
].fd
);
5441 if (ufds
[i
].revents
& POLLHUP
)
5443 /* Check if the socket still exists */
5444 int fd
= get_sock_fd(wfds
[i
].fd
, 0, NULL
);
5447 wfds
[i
].revents
= WS_POLLHUP
;
5448 release_sock_fd(wfds
[i
].fd
, fd
);
5451 wfds
[i
].revents
= WS_POLLNVAL
;
5454 wfds
[i
].revents
= convert_poll_u2w(ufds
[i
].revents
);
5457 wfds
[i
].revents
= WS_POLLNVAL
;
5460 HeapFree(GetProcessHeap(), 0, ufds
);
5464 /* helper to send completion messages for client-only i/o operation case */
5465 static void WS_AddCompletion( SOCKET sock
, ULONG_PTR CompletionValue
, NTSTATUS CompletionStatus
,
5468 SERVER_START_REQ( add_fd_completion
)
5470 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(sock
) );
5471 req
->cvalue
= CompletionValue
;
5472 req
->status
= CompletionStatus
;
5473 req
->information
= Information
;
5474 wine_server_call( req
);
5480 /***********************************************************************
5483 int WINAPI
WS_send(SOCKET s
, const char *buf
, int len
, int flags
)
5489 wsabuf
.buf
= (char*) buf
;
5491 if ( WS2_sendto( s
, &wsabuf
, 1, &n
, flags
, NULL
, 0, NULL
, NULL
) == SOCKET_ERROR
)
5492 return SOCKET_ERROR
;
5497 /***********************************************************************
5498 * WSASend (WS2_32.72)
5500 INT WINAPI
WSASend( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
5501 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
5502 LPWSAOVERLAPPED lpOverlapped
,
5503 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
5505 return WS2_sendto( s
, lpBuffers
, dwBufferCount
, lpNumberOfBytesSent
, dwFlags
,
5506 NULL
, 0, lpOverlapped
, lpCompletionRoutine
);
5509 /***********************************************************************
5510 * WSASendDisconnect (WS2_32.73)
5512 INT WINAPI
WSASendDisconnect( SOCKET s
, LPWSABUF lpBuffers
)
5514 return WS_shutdown( s
, SD_SEND
);
5518 static int WS2_sendto( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
5519 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
5520 const struct WS_sockaddr
*to
, int tolen
,
5521 LPWSAOVERLAPPED lpOverlapped
,
5522 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
5524 unsigned int i
, options
;
5525 int n
, fd
, err
, overlapped
, flags
;
5526 struct ws2_async
*wsa
= NULL
, localwsa
;
5527 int totalLength
= 0;
5531 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
5532 s
, lpBuffers
, dwBufferCount
, dwFlags
,
5533 to
, tolen
, lpOverlapped
, lpCompletionRoutine
);
5535 fd
= get_sock_fd( s
, FILE_WRITE_DATA
, &options
);
5536 TRACE( "fd=%d, options=%x\n", fd
, options
);
5538 if ( fd
== -1 ) return SOCKET_ERROR
;
5540 if (!lpOverlapped
&& !lpNumberOfBytesSent
)
5546 overlapped
= (lpOverlapped
|| lpCompletionRoutine
) &&
5547 !(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
));
5548 if (overlapped
|| dwBufferCount
> 1)
5550 if (!(wsa
= (struct ws2_async
*)alloc_async_io( offsetof(struct ws2_async
, iovec
[dwBufferCount
]),
5560 wsa
->hSocket
= SOCKET2HANDLE(s
);
5561 wsa
->addr
= (struct WS_sockaddr
*)to
;
5562 wsa
->addrlen
.val
= tolen
;
5563 wsa
->flags
= dwFlags
;
5564 wsa
->lpFlags
= &wsa
->flags
;
5565 wsa
->control
= NULL
;
5566 wsa
->n_iovecs
= dwBufferCount
;
5567 wsa
->first_iovec
= 0;
5568 for ( i
= 0; i
< dwBufferCount
; i
++ )
5570 wsa
->iovec
[i
].iov_base
= lpBuffers
[i
].buf
;
5571 wsa
->iovec
[i
].iov_len
= lpBuffers
[i
].len
;
5572 totalLength
+= lpBuffers
[i
].len
;
5575 flags
= convert_flags(dwFlags
);
5576 n
= WS2_send( fd
, wsa
, flags
);
5577 if (n
== -1 && errno
!= EAGAIN
)
5585 IO_STATUS_BLOCK
*iosb
= lpOverlapped
? (IO_STATUS_BLOCK
*)lpOverlapped
: &wsa
->local_iosb
;
5586 ULONG_PTR cvalue
= (lpOverlapped
&& ((ULONG_PTR
)lpOverlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)lpOverlapped
: 0;
5588 wsa
->user_overlapped
= lpOverlapped
;
5589 wsa
->completion_func
= lpCompletionRoutine
;
5590 release_sock_fd( s
, fd
);
5592 if (n
== -1 || n
< totalLength
)
5594 iosb
->u
.Status
= STATUS_PENDING
;
5595 iosb
->Information
= n
== -1 ? 0 : n
;
5597 if (wsa
->completion_func
)
5598 err
= register_async( ASYNC_TYPE_WRITE
, wsa
->hSocket
, &wsa
->io
, NULL
,
5599 ws2_async_apc
, wsa
, iosb
);
5601 err
= register_async( ASYNC_TYPE_WRITE
, wsa
->hSocket
, &wsa
->io
, lpOverlapped
->hEvent
,
5602 NULL
, (void *)cvalue
, iosb
);
5604 /* Enable the event only after starting the async. The server will deliver it as soon as
5605 the async is done. */
5606 _enable_event(SOCKET2HANDLE(s
), FD_WRITE
, 0, 0);
5608 if (err
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
5609 SetLastError(NtStatusToWSAError( err
));
5610 return SOCKET_ERROR
;
5613 iosb
->u
.Status
= STATUS_SUCCESS
;
5614 iosb
->Information
= n
;
5615 if (lpNumberOfBytesSent
) *lpNumberOfBytesSent
= n
;
5616 if (!wsa
->completion_func
)
5618 if (cvalue
) WS_AddCompletion( s
, cvalue
, STATUS_SUCCESS
, n
);
5619 if (lpOverlapped
->hEvent
) SetEvent( lpOverlapped
->hEvent
);
5620 HeapFree( GetProcessHeap(), 0, wsa
);
5622 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC
)ws2_async_apc
,
5623 (ULONG_PTR
)wsa
, (ULONG_PTR
)iosb
, 0 );
5624 SetLastError(ERROR_SUCCESS
);
5628 if ((err
= _is_blocking( s
, &is_blocking
)))
5630 err
= NtStatusToWSAError( err
);
5636 /* On a blocking non-overlapped stream socket,
5637 * sending blocks until the entire buffer is sent. */
5638 DWORD timeout_start
= GetTickCount();
5640 bytes_sent
= n
== -1 ? 0 : n
;
5642 while (wsa
->first_iovec
< wsa
->n_iovecs
)
5645 int poll_timeout
= -1;
5646 INT64 timeout
= get_rcvsnd_timeo(fd
, FALSE
);
5650 timeout
-= GetTickCount() - timeout_start
;
5651 if (timeout
< 0) poll_timeout
= 0;
5652 else poll_timeout
= timeout
<= INT_MAX
? timeout
: INT_MAX
;
5656 pfd
.events
= POLLOUT
;
5658 if (!poll_timeout
|| !poll( &pfd
, 1, poll_timeout
))
5661 goto error
; /* msdn says a timeout in send is fatal */
5664 n
= WS2_send( fd
, wsa
, flags
);
5665 if (n
== -1 && errno
!= EAGAIN
)
5675 else /* non-blocking */
5677 if (n
< totalLength
)
5678 _enable_event(SOCKET2HANDLE(s
), FD_WRITE
, 0, 0);
5681 err
= WSAEWOULDBLOCK
;
5687 TRACE(" -> %i bytes\n", bytes_sent
);
5689 if (lpNumberOfBytesSent
) *lpNumberOfBytesSent
= bytes_sent
;
5690 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
5691 release_sock_fd( s
, fd
);
5692 SetLastError(ERROR_SUCCESS
);
5696 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
5697 release_sock_fd( s
, fd
);
5698 WARN(" -> ERROR %d\n", err
);
5700 return SOCKET_ERROR
;
5703 /***********************************************************************
5704 * WSASendTo (WS2_32.74)
5706 INT WINAPI
WSASendTo( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
5707 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
5708 const struct WS_sockaddr
*to
, int tolen
,
5709 LPWSAOVERLAPPED lpOverlapped
,
5710 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
5712 return WS2_sendto( s
, lpBuffers
, dwBufferCount
,
5713 lpNumberOfBytesSent
, dwFlags
,
5715 lpOverlapped
, lpCompletionRoutine
);
5718 /***********************************************************************
5719 * sendto (WS2_32.20)
5721 int WINAPI
WS_sendto(SOCKET s
, const char *buf
, int len
, int flags
,
5722 const struct WS_sockaddr
*to
, int tolen
)
5728 wsabuf
.buf
= (char*) buf
;
5730 if ( WS2_sendto(s
, &wsabuf
, 1, &n
, flags
, to
, tolen
, NULL
, NULL
) == SOCKET_ERROR
)
5731 return SOCKET_ERROR
;
5736 /***********************************************************************
5737 * setsockopt (WS2_32.21)
5739 int WINAPI
WS_setsockopt(SOCKET s
, int level
, int optname
,
5740 const char *optval
, int optlen
)
5744 struct linger linger
;
5745 struct timeval tval
;
5747 TRACE("(socket %04lx, %s, optval %s, optlen %d)\n", s
,
5748 debugstr_sockopt(level
, optname
), debugstr_optval(optval
, optlen
),
5751 /* some broken apps pass the value directly instead of a pointer to it */
5752 if(optlen
&& IS_INTRESOURCE(optval
))
5754 SetLastError(WSAEFAULT
);
5755 return SOCKET_ERROR
;
5763 /* Some options need some conversion before they can be sent to
5764 * setsockopt. The conversions are done here, then they will fall through
5765 * to the general case. Special options that are not passed to
5766 * setsockopt follow below that.*/
5768 case WS_SO_DONTLINGER
:
5771 SetLastError(WSAEFAULT
);
5772 return SOCKET_ERROR
;
5774 linger
.l_onoff
= *(const int*)optval
== 0;
5775 linger
.l_linger
= 0;
5777 optname
= SO_LINGER
;
5778 optval
= (char*)&linger
;
5779 optlen
= sizeof(struct linger
);
5785 SetLastError(WSAEFAULT
);
5786 return SOCKET_ERROR
;
5788 linger
.l_onoff
= ((LINGER
*)optval
)->l_onoff
;
5789 linger
.l_linger
= ((LINGER
*)optval
)->l_linger
;
5791 optname
= SO_LINGER
;
5792 optval
= (char*)&linger
;
5793 optlen
= sizeof(struct linger
);
5797 if (*(const int*)optval
< 2048)
5799 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval
);
5804 /* The options listed here don't need any special handling. Thanks to
5805 * the conversion happening above, options from there will fall through
5807 case WS_SO_ACCEPTCONN
:
5808 case WS_SO_BROADCAST
:
5810 case WS_SO_KEEPALIVE
:
5811 case WS_SO_OOBINLINE
:
5812 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
5813 * however, using it the BSD way fixes bug 8513 and seems to be what
5814 * most programmers assume, anyway */
5815 case WS_SO_REUSEADDR
:
5818 convert_sockopt(&level
, &optname
);
5821 /* SO_DEBUG is a privileged operation, ignore it. */
5823 TRACE("Ignoring SO_DEBUG\n");
5826 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
5827 * socket. According to MSDN, this option is silently ignored.*/
5828 case WS_SO_DONTROUTE
:
5829 TRACE("Ignoring SO_DONTROUTE\n");
5832 /* Stops two sockets from being bound to the same port. Always happens
5833 * on unix systems, so just drop it. */
5834 case WS_SO_EXCLUSIVEADDRUSE
:
5835 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
5838 /* After a ConnectEx call succeeds, the socket can't be used with half of the
5839 * normal winsock functions on windows. We don't have that problem. */
5840 case WS_SO_UPDATE_CONNECT_CONTEXT
:
5841 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
5844 /* After a AcceptEx call succeeds, the socket can't be used with half of the
5845 * normal winsock functions on windows. We don't have that problem. */
5846 case WS_SO_UPDATE_ACCEPT_CONTEXT
:
5847 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
5850 /* SO_OPENTYPE does not require a valid socket handle. */
5851 case WS_SO_OPENTYPE
:
5852 if (!optlen
|| optlen
< sizeof(int) || !optval
)
5854 SetLastError(WSAEFAULT
);
5855 return SOCKET_ERROR
;
5857 get_per_thread_data()->opentype
= *(const int *)optval
;
5858 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval
) );
5862 case WS_SO_RCVTIMEO
:
5865 case WS_SO_SNDTIMEO
:
5867 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
5868 if (optval
&& optlen
== sizeof(UINT32
)) {
5869 /* WinSock passes milliseconds instead of struct timeval */
5870 tval
.tv_usec
= (*(const UINT32
*)optval
% 1000) * 1000;
5871 tval
.tv_sec
= *(const UINT32
*)optval
/ 1000;
5872 /* min of 500 milliseconds */
5873 if (tval
.tv_sec
== 0 && tval
.tv_usec
&& tval
.tv_usec
< 500000)
5874 tval
.tv_usec
= 500000;
5875 optlen
= sizeof(struct timeval
);
5876 optval
= (char*)&tval
;
5877 } else if (optlen
== sizeof(struct timeval
)) {
5878 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen
);
5880 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen
);
5883 convert_sockopt(&level
, &optname
);
5888 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname
);
5889 SetLastError(WSAENOPROTOOPT
);
5890 return SOCKET_ERROR
;
5892 break; /* case WS_SOL_SOCKET */
5895 case WS_NSPROTO_IPX
:
5899 return set_ipx_packettype(s
, *(int*)optval
);
5901 case WS_IPX_FILTERPTYPE
:
5902 /* Sets the receive filter packet type, at the moment we don't support it */
5903 FIXME("IPX_FILTERPTYPE: %x\n", *optval
);
5904 /* Returning 0 is better for now than returning a SOCKET_ERROR */
5908 FIXME("opt_name:%x\n", optname
);
5909 return SOCKET_ERROR
;
5911 break; /* case WS_NSPROTO_IPX */
5914 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
5915 case WS_IPPROTO_TCP
:
5918 case WS_TCP_NODELAY
:
5919 convert_sockopt(&level
, &optname
);
5922 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname
);
5923 return SOCKET_ERROR
;
5930 case WS_IP_ADD_MEMBERSHIP
:
5931 case WS_IP_DROP_MEMBERSHIP
:
5935 case WS_IP_MULTICAST_IF
:
5936 case WS_IP_MULTICAST_LOOP
:
5937 case WS_IP_MULTICAST_TTL
:
5944 #ifdef IP_UNICAST_IF
5945 case WS_IP_UNICAST_IF
:
5947 convert_sockopt(&level
, &optname
);
5949 case WS_IP_DONTFRAGMENT
:
5950 return set_dont_fragment(s
, IPPROTO_IP
, *(BOOL
*)optval
) ? 0 : SOCKET_ERROR
;
5952 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname
);
5953 return SOCKET_ERROR
;
5957 case WS_IPPROTO_IPV6
:
5960 #ifdef IPV6_ADD_MEMBERSHIP
5961 case WS_IPV6_ADD_MEMBERSHIP
:
5963 #ifdef IPV6_DROP_MEMBERSHIP
5964 case WS_IPV6_DROP_MEMBERSHIP
:
5966 case WS_IPV6_MULTICAST_IF
:
5967 case WS_IPV6_MULTICAST_HOPS
:
5968 case WS_IPV6_MULTICAST_LOOP
:
5969 case WS_IPV6_UNICAST_HOPS
:
5970 #ifdef IPV6_UNICAST_IF
5971 case WS_IPV6_UNICAST_IF
:
5973 convert_sockopt(&level
, &optname
);
5975 case WS_IPV6_DONTFRAG
:
5976 return set_dont_fragment(s
, IPPROTO_IPV6
, *(BOOL
*)optval
) ? 0 : SOCKET_ERROR
;
5977 case WS_IPV6_PROTECTION_LEVEL
:
5978 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
5980 case WS_IPV6_V6ONLY
:
5982 union generic_unix_sockaddr uaddr
;
5986 fd
= get_sock_fd( s
, 0, NULL
);
5987 if (fd
== -1) return SOCKET_ERROR
;
5989 bound
= is_fd_bound(fd
, &uaddr
, &uaddrlen
);
5990 release_sock_fd( s
, fd
);
5991 if (bound
== 0 && uaddr
.addr
.sa_family
== AF_INET
)
5993 /* Changing IPV6_V6ONLY succeeds on AF_INET (IPv4) socket
5994 * on Windows (with IPv6 support) if the socket is unbound.
5995 * It is essentially a noop, though Windows does store the value
5997 WARN("Silently ignoring IPPROTO_IPV6+IPV6_V6ONLY on AF_INET socket\n");
6000 level
= IPPROTO_IPV6
;
6001 optname
= IPV6_V6ONLY
;
6005 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname
);
6006 return SOCKET_ERROR
;
6011 WARN("Unknown level: 0x%08x\n", level
);
6012 SetLastError(WSAEINVAL
);
6013 return SOCKET_ERROR
;
6014 } /* end switch(level) */
6016 /* avoid endianness issues if argument is a 16-bit int */
6017 if (optval
&& optlen
< sizeof(int))
6019 woptval
= *((const INT16
*) optval
);
6020 optval
= (char*) &woptval
;
6021 woptval
&= (1 << optlen
* 8) - 1;
6024 fd
= get_sock_fd( s
, 0, NULL
);
6025 if (fd
== -1) return SOCKET_ERROR
;
6027 if (setsockopt(fd
, level
, optname
, optval
, optlen
) == 0)
6030 if (level
== SOL_SOCKET
&& optname
== SO_REUSEADDR
&&
6031 setsockopt(fd
, level
, SO_REUSEPORT
, optval
, optlen
) != 0)
6033 SetLastError(wsaErrno());
6034 release_sock_fd( s
, fd
);
6035 return SOCKET_ERROR
;
6038 release_sock_fd( s
, fd
);
6041 TRACE("Setting socket error, %d\n", wsaErrno());
6042 SetLastError(wsaErrno());
6043 release_sock_fd( s
, fd
);
6045 return SOCKET_ERROR
;
6048 /***********************************************************************
6049 * shutdown (WS2_32.22)
6051 int WINAPI
WS_shutdown(SOCKET s
, int how
)
6053 int fd
, err
= WSAENOTSOCK
;
6054 unsigned int options
= 0, clear_flags
= 0;
6056 fd
= get_sock_fd( s
, 0, &options
);
6057 TRACE("socket %04lx, how 0x%x, options 0x%x\n", s
, how
, options
);
6060 return SOCKET_ERROR
;
6064 case SD_RECEIVE
: /* drop receives */
6065 clear_flags
|= FD_READ
;
6067 case SD_SEND
: /* drop sends */
6068 clear_flags
|= FD_WRITE
;
6070 case SD_BOTH
: /* drop all */
6071 clear_flags
|= FD_READ
|FD_WRITE
;
6074 clear_flags
|= FD_WINE_LISTENING
;
6077 if (!(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
)))
6082 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_READ
);
6085 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_WRITE
);
6089 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_READ
);
6090 if (!err
) err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_WRITE
);
6093 if (err
) goto error
;
6095 else /* non-overlapped mode */
6097 if ( shutdown( fd
, how
) )
6104 release_sock_fd( s
, fd
);
6105 _enable_event( SOCKET2HANDLE(s
), 0, 0, clear_flags
);
6106 if ( how
> 1) WSAAsyncSelect( s
, 0, 0, 0 );
6110 release_sock_fd( s
, fd
);
6111 _enable_event( SOCKET2HANDLE(s
), 0, 0, clear_flags
);
6112 SetLastError( err
);
6113 return SOCKET_ERROR
;
6116 /***********************************************************************
6117 * socket (WS2_32.23)
6119 SOCKET WINAPI
WS_socket(int af
, int type
, int protocol
)
6121 TRACE("af=%d type=%d protocol=%d\n", af
, type
, protocol
);
6123 return WSASocketW( af
, type
, protocol
, NULL
, 0,
6124 get_per_thread_data()->opentype
? 0 : WSA_FLAG_OVERLAPPED
);
6128 /***********************************************************************
6129 * gethostbyaddr (WS2_32.51)
6131 struct WS_hostent
* WINAPI
WS_gethostbyaddr(const char *addr
, int len
, int type
)
6133 struct WS_hostent
*retval
= NULL
;
6134 struct hostent
* host
;
6135 int unixtype
= convert_af_w2u(type
);
6136 const char *paddr
= addr
;
6137 unsigned long loopback
;
6138 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6140 int ebufsize
= 1024;
6141 struct hostent hostentry
;
6142 int locerr
= ENOBUFS
;
6145 /* convert back the magic loopback address if necessary */
6146 if (unixtype
== AF_INET
&& len
== 4 && !memcmp(addr
, magic_loopback_addr
, 4))
6148 loopback
= htonl(INADDR_LOOPBACK
);
6149 paddr
= (char*) &loopback
;
6152 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6154 extrabuf
=HeapAlloc(GetProcessHeap(),0,ebufsize
) ;
6156 int res
= gethostbyaddr_r(paddr
, len
, unixtype
,
6157 &hostentry
, extrabuf
, ebufsize
, &host
, &locerr
);
6158 if (res
!= ERANGE
) break;
6160 extrabuf
=HeapReAlloc(GetProcessHeap(),0,extrabuf
,ebufsize
) ;
6162 if (host
) retval
= WS_dup_he(host
);
6163 else SetLastError((locerr
< 0) ? wsaErrno() : wsaHerrno(locerr
));
6164 HeapFree(GetProcessHeap(),0,extrabuf
);
6166 EnterCriticalSection( &csWSgetXXXbyYYY
);
6167 host
= gethostbyaddr(paddr
, len
, unixtype
);
6168 if (host
) retval
= WS_dup_he(host
);
6169 else SetLastError((h_errno
< 0) ? wsaErrno() : wsaHerrno(h_errno
));
6170 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6172 TRACE("ptr %p, len %d, type %d ret %p\n", addr
, len
, type
, retval
);
6176 /***********************************************************************
6177 * WS_compare_routes_by_metric_asc (INTERNAL)
6179 * Comparison function for qsort(), for sorting two routes (struct route)
6180 * by metric in ascending order.
6182 static int WS_compare_routes_by_metric_asc(const void *left
, const void *right
)
6184 const struct route
*a
= left
, *b
= right
;
6185 if (a
->default_route
&& b
->default_route
)
6186 return a
->default_route
- b
->default_route
;
6187 if (a
->default_route
&& !b
->default_route
)
6189 if (b
->default_route
&& !a
->default_route
)
6191 return a
->metric
- b
->metric
;
6194 /***********************************************************************
6195 * WS_get_local_ips (INTERNAL)
6197 * Returns the list of local IP addresses by going through the network
6198 * adapters and using the local routing table to sort the addresses
6199 * from highest routing priority to lowest routing priority. This
6200 * functionality is inferred from the description for obtaining local
6201 * IP addresses given in the Knowledge Base Article Q160215.
6203 * Please note that the returned hostent is only freed when the thread
6204 * closes and is replaced if another hostent is requested.
6206 static struct WS_hostent
* WS_get_local_ips( char *hostname
)
6208 int numroutes
= 0, i
, j
, default_routes
= 0;
6210 PIP_ADAPTER_INFO adapters
= NULL
, k
;
6211 struct WS_hostent
*hostlist
= NULL
;
6212 PMIB_IPFORWARDTABLE routes
= NULL
;
6213 struct route
*route_addrs
= NULL
;
6214 DWORD adap_size
, route_size
;
6216 /* Obtain the size of the adapter list and routing table, also allocate memory */
6217 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
6219 if (GetIpForwardTable(NULL
, &route_size
, FALSE
) != ERROR_INSUFFICIENT_BUFFER
)
6221 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
6222 routes
= HeapAlloc(GetProcessHeap(), 0, route_size
);
6223 route_addrs
= HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
6224 if (adapters
== NULL
|| routes
== NULL
|| route_addrs
== NULL
)
6226 /* Obtain the adapter list and the full routing table */
6227 if (GetAdaptersInfo(adapters
, &adap_size
) != NO_ERROR
)
6229 if (GetIpForwardTable(routes
, &route_size
, FALSE
) != NO_ERROR
)
6231 /* Store the interface associated with each route */
6232 for (n
= 0; n
< routes
->dwNumEntries
; n
++)
6235 DWORD ifmetric
, ifdefault
= 0;
6236 BOOL exists
= FALSE
;
6238 /* Check if this is a default route (there may be more than one) */
6239 if (!routes
->table
[n
].dwForwardDest
)
6240 ifdefault
= ++default_routes
;
6241 else if (routes
->table
[n
].u1
.ForwardType
!= MIB_IPROUTE_TYPE_DIRECT
)
6243 ifindex
= routes
->table
[n
].dwForwardIfIndex
;
6244 ifmetric
= routes
->table
[n
].dwForwardMetric1
;
6245 /* Only store the lowest valued metric for an interface */
6246 for (j
= 0; j
< numroutes
; j
++)
6248 if (route_addrs
[j
].interface
== ifindex
)
6250 if (route_addrs
[j
].metric
> ifmetric
)
6251 route_addrs
[j
].metric
= ifmetric
;
6257 route_addrs
= HeapReAlloc(GetProcessHeap(), 0, route_addrs
, (numroutes
+1)*sizeof(struct route
));
6258 if (route_addrs
== NULL
)
6259 goto cleanup
; /* Memory allocation error, fail gracefully */
6260 route_addrs
[numroutes
].interface
= ifindex
;
6261 route_addrs
[numroutes
].metric
= ifmetric
;
6262 route_addrs
[numroutes
].default_route
= ifdefault
;
6263 /* If no IP is found in the next step (for whatever reason)
6264 * then fall back to the magic loopback address.
6266 memcpy(&(route_addrs
[numroutes
].addr
.s_addr
), magic_loopback_addr
, 4);
6270 goto cleanup
; /* No routes, fall back to the Magic IP */
6271 /* Find the IP address associated with each found interface */
6272 for (i
= 0; i
< numroutes
; i
++)
6274 for (k
= adapters
; k
!= NULL
; k
= k
->Next
)
6276 char *ip
= k
->IpAddressList
.IpAddress
.String
;
6278 if (route_addrs
[i
].interface
== k
->Index
)
6279 route_addrs
[i
].addr
.s_addr
= (in_addr_t
) inet_addr(ip
);
6282 /* Allocate a hostent and enough memory for all the IPs,
6283 * including the NULL at the end of the list.
6285 hostlist
= WS_create_he(hostname
, 1, 0, numroutes
+1, sizeof(struct in_addr
));
6286 if (hostlist
== NULL
)
6287 goto cleanup
; /* Failed to allocate a hostent for the list of IPs */
6288 hostlist
->h_addr_list
[numroutes
] = NULL
; /* NULL-terminate the address list */
6289 hostlist
->h_aliases
[0] = NULL
; /* NULL-terminate the alias list */
6290 hostlist
->h_addrtype
= AF_INET
;
6291 hostlist
->h_length
= sizeof(struct in_addr
); /* = 4 */
6292 /* Reorder the entries before placing them in the host list. Windows expects
6293 * the IP list in order from highest priority to lowest (the critical thing
6294 * is that most applications expect the first IP to be the default route).
6297 qsort(route_addrs
, numroutes
, sizeof(struct route
), WS_compare_routes_by_metric_asc
);
6299 for (i
= 0; i
< numroutes
; i
++)
6300 (*(struct in_addr
*) hostlist
->h_addr_list
[i
]) = route_addrs
[i
].addr
;
6302 /* Cleanup all allocated memory except the address list,
6303 * the address list is used by the calling app.
6306 HeapFree(GetProcessHeap(), 0, route_addrs
);
6307 HeapFree(GetProcessHeap(), 0, adapters
);
6308 HeapFree(GetProcessHeap(), 0, routes
);
6312 /***********************************************************************
6313 * gethostbyname (WS2_32.52)
6315 struct WS_hostent
* WINAPI
WS_gethostbyname(const char* name
)
6317 struct WS_hostent
*retval
= NULL
;
6318 struct hostent
* host
;
6319 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6322 struct hostent hostentry
;
6323 int locerr
= ENOBUFS
;
6327 SetLastError(WSANOTINITIALISED
);
6330 if( gethostname( hostname
, 100) == -1) {
6331 SetLastError(WSAENOBUFS
); /* appropriate ? */
6334 if( !name
|| !name
[0]) {
6337 /* If the hostname of the local machine is requested then return the
6338 * complete list of local IP addresses */
6339 if(strcmp(name
, hostname
) == 0)
6340 retval
= WS_get_local_ips(hostname
);
6341 /* If any other hostname was requested (or the routing table lookup failed)
6342 * then return the IP found by the host OS */
6345 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6347 extrabuf
=HeapAlloc(GetProcessHeap(),0,ebufsize
) ;
6349 int res
= gethostbyname_r(name
, &hostentry
, extrabuf
, ebufsize
, &host
, &locerr
);
6350 if( res
!= ERANGE
) break;
6352 extrabuf
=HeapReAlloc(GetProcessHeap(),0,extrabuf
,ebufsize
) ;
6354 if (!host
) SetLastError((locerr
< 0) ? wsaErrno() : wsaHerrno(locerr
));
6356 EnterCriticalSection( &csWSgetXXXbyYYY
);
6357 host
= gethostbyname(name
);
6358 if (!host
) SetLastError((h_errno
< 0) ? wsaErrno() : wsaHerrno(h_errno
));
6360 if (host
) retval
= WS_dup_he(host
);
6361 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6362 HeapFree(GetProcessHeap(),0,extrabuf
);
6364 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6367 if (retval
&& retval
->h_addr_list
[0][0] == 127 &&
6368 strcmp(name
, "localhost") != 0)
6370 /* hostname != "localhost" but has loopback address. replace by our
6371 * special address.*/
6372 memcpy(retval
->h_addr_list
[0], magic_loopback_addr
, 4);
6374 TRACE( "%s ret %p\n", debugstr_a(name
), retval
);
6379 /***********************************************************************
6380 * getprotobyname (WS2_32.53)
6382 struct WS_protoent
* WINAPI
WS_getprotobyname(const char* name
)
6384 struct WS_protoent
* retval
= NULL
;
6385 #ifdef HAVE_GETPROTOBYNAME
6386 struct protoent
* proto
;
6387 EnterCriticalSection( &csWSgetXXXbyYYY
);
6388 if( (proto
= getprotobyname(name
)) != NULL
)
6390 retval
= WS_dup_pe(proto
);
6393 MESSAGE("protocol %s not found; You might want to add "
6394 "this to /etc/protocols\n", debugstr_a(name
) );
6395 SetLastError(WSANO_DATA
);
6397 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6399 TRACE( "%s ret %p\n", debugstr_a(name
), retval
);
6404 /***********************************************************************
6405 * getprotobynumber (WS2_32.54)
6407 struct WS_protoent
* WINAPI
WS_getprotobynumber(int number
)
6409 struct WS_protoent
* retval
= NULL
;
6410 #ifdef HAVE_GETPROTOBYNUMBER
6411 struct protoent
* proto
;
6412 EnterCriticalSection( &csWSgetXXXbyYYY
);
6413 if( (proto
= getprotobynumber(number
)) != NULL
)
6415 retval
= WS_dup_pe(proto
);
6418 MESSAGE("protocol number %d not found; You might want to add "
6419 "this to /etc/protocols\n", number
);
6420 SetLastError(WSANO_DATA
);
6422 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6424 TRACE("%i ret %p\n", number
, retval
);
6429 /***********************************************************************
6430 * getservbyname (WS2_32.55)
6432 struct WS_servent
* WINAPI
WS_getservbyname(const char *name
, const char *proto
)
6434 struct WS_servent
* retval
= NULL
;
6435 struct servent
* serv
;
6437 char *proto_str
= NULL
;
6439 if (!(name_str
= strdup_lower(name
))) return NULL
;
6441 if (proto
&& *proto
)
6443 if (!(proto_str
= strdup_lower(proto
)))
6445 HeapFree( GetProcessHeap(), 0, name_str
);
6450 EnterCriticalSection( &csWSgetXXXbyYYY
);
6451 serv
= getservbyname(name_str
, proto_str
);
6454 retval
= WS_dup_se(serv
);
6456 else SetLastError(WSANO_DATA
);
6457 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6458 HeapFree( GetProcessHeap(), 0, proto_str
);
6459 HeapFree( GetProcessHeap(), 0, name_str
);
6460 TRACE( "%s, %s ret %p\n", debugstr_a(name
), debugstr_a(proto
), retval
);
6464 /***********************************************************************
6465 * freeaddrinfo (WS2_32.@)
6467 void WINAPI
WS_freeaddrinfo(struct WS_addrinfo
*res
)
6470 struct WS_addrinfo
*next
;
6472 HeapFree(GetProcessHeap(),0,res
->ai_canonname
);
6473 HeapFree(GetProcessHeap(),0,res
->ai_addr
);
6474 next
= res
->ai_next
;
6475 HeapFree(GetProcessHeap(),0,res
);
6480 /* helper functions for getaddrinfo()/getnameinfo() */
6481 static int convert_aiflag_w2u(int winflags
) {
6485 for (i
=0;i
<sizeof(ws_aiflag_map
)/sizeof(ws_aiflag_map
[0]);i
++)
6486 if (ws_aiflag_map
[i
][0] & winflags
) {
6487 unixflags
|= ws_aiflag_map
[i
][1];
6488 winflags
&= ~ws_aiflag_map
[i
][0];
6491 FIXME("Unhandled windows AI_xxx flags 0x%x\n", winflags
);
6495 static int convert_niflag_w2u(int winflags
) {
6499 for (i
=0;i
<sizeof(ws_niflag_map
)/sizeof(ws_niflag_map
[0]);i
++)
6500 if (ws_niflag_map
[i
][0] & winflags
) {
6501 unixflags
|= ws_niflag_map
[i
][1];
6502 winflags
&= ~ws_niflag_map
[i
][0];
6505 FIXME("Unhandled windows NI_xxx flags 0x%x\n", winflags
);
6509 static int convert_aiflag_u2w(int unixflags
) {
6513 for (i
=0;i
<sizeof(ws_aiflag_map
)/sizeof(ws_aiflag_map
[0]);i
++)
6514 if (ws_aiflag_map
[i
][1] & unixflags
) {
6515 winflags
|= ws_aiflag_map
[i
][0];
6516 unixflags
&= ~ws_aiflag_map
[i
][1];
6519 WARN("Unhandled UNIX AI_xxx flags 0x%x\n", unixflags
);
6523 static int convert_eai_u2w(int unixret
) {
6526 if (!unixret
) return 0;
6528 for (i
=0;ws_eai_map
[i
][0];i
++)
6529 if (ws_eai_map
[i
][1] == unixret
)
6530 return ws_eai_map
[i
][0];
6532 if (unixret
== EAI_SYSTEM
)
6533 /* There are broken versions of glibc which return EAI_SYSTEM
6534 * and set errno to 0 instead of returning EAI_NONAME.
6536 return errno
? sock_get_error( errno
) : WS_EAI_NONAME
;
6538 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret
);
6542 static char *get_fqdn(void)
6547 GetComputerNameExA( ComputerNamePhysicalDnsFullyQualified
, NULL
, &size
);
6548 if (GetLastError() != ERROR_MORE_DATA
) return NULL
;
6549 if (!(ret
= HeapAlloc( GetProcessHeap(), 0, size
))) return NULL
;
6550 if (!GetComputerNameExA( ComputerNamePhysicalDnsFullyQualified
, ret
, &size
))
6552 HeapFree( GetProcessHeap(), 0, ret
);
6558 /***********************************************************************
6559 * getaddrinfo (WS2_32.@)
6561 int WINAPI
WS_getaddrinfo(LPCSTR nodename
, LPCSTR servname
, const struct WS_addrinfo
*hints
, struct WS_addrinfo
**res
)
6563 #ifdef HAVE_GETADDRINFO
6564 struct addrinfo
*unixaires
= NULL
;
6566 struct addrinfo unixhints
, *punixhints
= NULL
;
6567 char *dot
, *nodeV6
= NULL
, *fqdn
;
6569 size_t hostname_len
= 0;
6572 if (!nodename
&& !servname
)
6574 SetLastError(WSAHOST_NOT_FOUND
);
6575 return WSAHOST_NOT_FOUND
;
6579 if (!fqdn
) return WSA_NOT_ENOUGH_MEMORY
;
6580 dot
= strchr(fqdn
, '.');
6582 hostname_len
= dot
- fqdn
;
6586 else if (!nodename
[0])
6592 /* Check for [ipv6] or [ipv6]:portnumber, which are supported by Windows */
6593 if (!hints
|| hints
->ai_family
== WS_AF_UNSPEC
|| hints
->ai_family
== WS_AF_INET6
)
6595 char *close_bracket
;
6597 if (node
[0] == '[' && (close_bracket
= strchr(node
+ 1, ']')))
6599 nodeV6
= HeapAlloc(GetProcessHeap(), 0, close_bracket
- node
);
6602 HeapFree(GetProcessHeap(), 0, fqdn
);
6603 return WSA_NOT_ENOUGH_MEMORY
;
6605 lstrcpynA(nodeV6
, node
+ 1, close_bracket
- node
);
6611 /* servname tweak required by OSX and BSD kernels */
6612 if (servname
&& !servname
[0]) servname
= "0";
6615 punixhints
= &unixhints
;
6617 memset(&unixhints
, 0, sizeof(unixhints
));
6618 punixhints
->ai_flags
= convert_aiflag_w2u(hints
->ai_flags
);
6620 /* zero is a wildcard, no need to convert */
6621 if (hints
->ai_family
)
6622 punixhints
->ai_family
= convert_af_w2u(hints
->ai_family
);
6623 if (hints
->ai_socktype
)
6624 punixhints
->ai_socktype
= convert_socktype_w2u(hints
->ai_socktype
);
6625 if (hints
->ai_protocol
)
6626 punixhints
->ai_protocol
= max(convert_proto_w2u(hints
->ai_protocol
), 0);
6628 if (punixhints
->ai_socktype
< 0)
6630 SetLastError(WSAESOCKTNOSUPPORT
);
6631 HeapFree(GetProcessHeap(), 0, fqdn
);
6632 HeapFree(GetProcessHeap(), 0, nodeV6
);
6633 return SOCKET_ERROR
;
6636 /* windows allows invalid combinations of socket type and protocol, unix does not.
6637 * fix the parameters here to make getaddrinfo call always work */
6638 if (punixhints
->ai_protocol
== IPPROTO_TCP
&&
6639 punixhints
->ai_socktype
!= SOCK_STREAM
&& punixhints
->ai_socktype
!= SOCK_SEQPACKET
)
6640 punixhints
->ai_socktype
= 0;
6642 else if (punixhints
->ai_protocol
== IPPROTO_UDP
&& punixhints
->ai_socktype
!= SOCK_DGRAM
)
6643 punixhints
->ai_socktype
= 0;
6645 else if (IS_IPX_PROTO(punixhints
->ai_protocol
) && punixhints
->ai_socktype
!= SOCK_DGRAM
)
6646 punixhints
->ai_socktype
= 0;
6648 else if (punixhints
->ai_protocol
== IPPROTO_IPV6
)
6649 punixhints
->ai_protocol
= 0;
6652 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
6653 result
= getaddrinfo(node
, servname
, punixhints
, &unixaires
);
6655 if (result
&& (!hints
|| !(hints
->ai_flags
& WS_AI_NUMERICHOST
))
6656 && (!strcmp(fqdn
, node
) || (!strncmp(fqdn
, node
, hostname_len
) && !node
[hostname_len
])))
6658 /* If it didn't work it means the host name IP is not in /etc/hosts, try again
6659 * by sending a NULL host and avoid sending a NULL servname too because that
6661 ERR_(winediag
)("Failed to resolve your host name IP\n");
6662 result
= getaddrinfo(NULL
, servname
? servname
: "0", punixhints
, &unixaires
);
6664 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename
), debugstr_a(servname
), hints
, res
, result
);
6665 HeapFree(GetProcessHeap(), 0, fqdn
);
6666 HeapFree(GetProcessHeap(), 0, nodeV6
);
6669 struct addrinfo
*xuai
= unixaires
;
6670 struct WS_addrinfo
**xai
= res
;
6674 struct WS_addrinfo
*ai
= HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY
, sizeof(struct WS_addrinfo
));
6680 *xai
= ai
;xai
= &ai
->ai_next
;
6681 ai
->ai_flags
= convert_aiflag_u2w(xuai
->ai_flags
);
6682 ai
->ai_family
= convert_af_u2w(xuai
->ai_family
);
6683 /* copy whatever was sent in the hints */
6685 ai
->ai_socktype
= hints
->ai_socktype
;
6686 ai
->ai_protocol
= hints
->ai_protocol
;
6688 ai
->ai_socktype
= convert_socktype_u2w(xuai
->ai_socktype
);
6689 ai
->ai_protocol
= convert_proto_u2w(xuai
->ai_protocol
);
6691 if (xuai
->ai_canonname
) {
6692 TRACE("canon name - %s\n",debugstr_a(xuai
->ai_canonname
));
6693 ai
->ai_canonname
= HeapAlloc(GetProcessHeap(),0,strlen(xuai
->ai_canonname
)+1);
6694 if (!ai
->ai_canonname
)
6696 strcpy(ai
->ai_canonname
,xuai
->ai_canonname
);
6698 len
= xuai
->ai_addrlen
;
6699 ai
->ai_addr
= HeapAlloc(GetProcessHeap(),0,len
);
6702 ai
->ai_addrlen
= len
;
6704 int winlen
= ai
->ai_addrlen
;
6706 if (!ws_sockaddr_u2ws(xuai
->ai_addr
, ai
->ai_addr
, &winlen
)) {
6707 ai
->ai_addrlen
= winlen
;
6711 ai
->ai_addr
= HeapReAlloc(GetProcessHeap(),0,ai
->ai_addr
,len
);
6714 ai
->ai_addrlen
= len
;
6716 xuai
= xuai
->ai_next
;
6718 freeaddrinfo(unixaires
);
6720 if (TRACE_ON(winsock
))
6722 struct WS_addrinfo
*ai
= *res
;
6725 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
6726 ai
, ai
->ai_flags
, ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
, ai
->ai_addrlen
,
6727 ai
->ai_canonname
, debugstr_sockaddr(ai
->ai_addr
));
6732 result
= convert_eai_u2w(result
);
6734 SetLastError(result
);
6738 if (*res
) WS_freeaddrinfo(*res
);
6739 if (unixaires
) freeaddrinfo(unixaires
);
6740 return WSA_NOT_ENOUGH_MEMORY
;
6742 FIXME("getaddrinfo() failed, not found during buildtime.\n");
6747 static ADDRINFOEXW
*addrinfo_AtoW(const struct WS_addrinfo
*ai
)
6751 if (!(ret
= HeapAlloc(GetProcessHeap(), 0, sizeof(ADDRINFOEXW
)))) return NULL
;
6752 ret
->ai_flags
= ai
->ai_flags
;
6753 ret
->ai_family
= ai
->ai_family
;
6754 ret
->ai_socktype
= ai
->ai_socktype
;
6755 ret
->ai_protocol
= ai
->ai_protocol
;
6756 ret
->ai_addrlen
= ai
->ai_addrlen
;
6757 ret
->ai_canonname
= NULL
;
6758 ret
->ai_addr
= NULL
;
6759 ret
->ai_blob
= NULL
;
6760 ret
->ai_bloblen
= 0;
6761 ret
->ai_provider
= NULL
;
6762 ret
->ai_next
= NULL
;
6763 if (ai
->ai_canonname
)
6765 int len
= MultiByteToWideChar(CP_ACP
, 0, ai
->ai_canonname
, -1, NULL
, 0);
6766 if (!(ret
->ai_canonname
= HeapAlloc(GetProcessHeap(), 0, len
*sizeof(WCHAR
))))
6768 HeapFree(GetProcessHeap(), 0, ret
);
6771 MultiByteToWideChar(CP_ACP
, 0, ai
->ai_canonname
, -1, ret
->ai_canonname
, len
);
6775 if (!(ret
->ai_addr
= HeapAlloc(GetProcessHeap(), 0, ai
->ai_addrlen
)))
6777 HeapFree(GetProcessHeap(), 0, ret
->ai_canonname
);
6778 HeapFree(GetProcessHeap(), 0, ret
);
6781 memcpy(ret
->ai_addr
, ai
->ai_addr
, ai
->ai_addrlen
);
6786 static ADDRINFOEXW
*addrinfo_list_AtoW(const struct WS_addrinfo
*info
)
6788 ADDRINFOEXW
*ret
, *infoW
;
6790 if (!(ret
= infoW
= addrinfo_AtoW(info
))) return NULL
;
6791 while (info
->ai_next
)
6793 if (!(infoW
->ai_next
= addrinfo_AtoW(info
->ai_next
)))
6795 FreeAddrInfoExW(ret
);
6798 infoW
= infoW
->ai_next
;
6799 info
= info
->ai_next
;
6804 static struct WS_addrinfo
*addrinfo_WtoA(const struct WS_addrinfoW
*ai
)
6806 struct WS_addrinfo
*ret
;
6808 if (!(ret
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo
)))) return NULL
;
6809 ret
->ai_flags
= ai
->ai_flags
;
6810 ret
->ai_family
= ai
->ai_family
;
6811 ret
->ai_socktype
= ai
->ai_socktype
;
6812 ret
->ai_protocol
= ai
->ai_protocol
;
6813 ret
->ai_addrlen
= ai
->ai_addrlen
;
6814 ret
->ai_canonname
= NULL
;
6815 ret
->ai_addr
= NULL
;
6816 ret
->ai_next
= NULL
;
6817 if (ai
->ai_canonname
)
6819 int len
= WideCharToMultiByte(CP_ACP
, 0, ai
->ai_canonname
, -1, NULL
, 0, NULL
, NULL
);
6820 if (!(ret
->ai_canonname
= HeapAlloc(GetProcessHeap(), 0, len
)))
6822 HeapFree(GetProcessHeap(), 0, ret
);
6825 WideCharToMultiByte(CP_ACP
, 0, ai
->ai_canonname
, -1, ret
->ai_canonname
, len
, NULL
, NULL
);
6829 if (!(ret
->ai_addr
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr
))))
6831 HeapFree(GetProcessHeap(), 0, ret
->ai_canonname
);
6832 HeapFree(GetProcessHeap(), 0, ret
);
6835 memcpy(ret
->ai_addr
, ai
->ai_addr
, sizeof(struct WS_sockaddr
));
6840 struct getaddrinfo_args
6842 OVERLAPPED
*overlapped
;
6843 ADDRINFOEXW
**result
;
6848 static void WINAPI
getaddrinfo_callback(TP_CALLBACK_INSTANCE
*instance
, void *context
)
6850 struct getaddrinfo_args
*args
= context
;
6851 OVERLAPPED
*overlapped
= args
->overlapped
;
6852 HANDLE event
= overlapped
->hEvent
;
6853 struct WS_addrinfo
*res
;
6856 ret
= WS_getaddrinfo(args
->nodename
, args
->servname
, NULL
, &res
);
6859 *args
->result
= addrinfo_list_AtoW(res
);
6860 overlapped
->u
.Pointer
= args
->result
;
6861 WS_freeaddrinfo(res
);
6864 HeapFree(GetProcessHeap(), 0, args
->nodename
);
6865 HeapFree(GetProcessHeap(), 0, args
->servname
);
6866 HeapFree(GetProcessHeap(), 0, args
);
6868 overlapped
->Internal
= ret
;
6869 if (event
) SetEvent(event
);
6872 static int WS_getaddrinfoW(const WCHAR
*nodename
, const WCHAR
*servname
, const struct WS_addrinfo
*hints
, ADDRINFOEXW
**res
, OVERLAPPED
*overlapped
)
6874 int ret
= EAI_MEMORY
, len
, i
;
6875 char *nodenameA
= NULL
, *servnameA
= NULL
;
6876 struct WS_addrinfo
*resA
;
6877 WCHAR
*local_nodenameW
= (WCHAR
*)nodename
;
6882 /* Is this an IDN? Most likely if any char is above the Ascii table, this
6883 * is the simplest validation possible, further validation will be done by
6884 * the native getaddrinfo() */
6885 for (i
= 0; nodename
[i
]; i
++)
6887 if (nodename
[i
] > 'z')
6892 if (hints
&& (hints
->ai_flags
& WS_AI_DISABLE_IDN_ENCODING
))
6894 /* Name requires conversion but it was disabled */
6895 ret
= WSAHOST_NOT_FOUND
;
6896 WSASetLastError(ret
);
6900 len
= IdnToAscii(0, nodename
, -1, NULL
, 0);
6903 ERR("Failed to convert %s to punycode\n", debugstr_w(nodename
));
6907 if (!(local_nodenameW
= HeapAlloc(GetProcessHeap(), 0, len
* sizeof(WCHAR
)))) goto end
;
6908 IdnToAscii(0, nodename
, -1, local_nodenameW
, len
);
6911 if (local_nodenameW
)
6913 len
= WideCharToMultiByte(CP_ACP
, 0, local_nodenameW
, -1, NULL
, 0, NULL
, NULL
);
6914 if (!(nodenameA
= HeapAlloc(GetProcessHeap(), 0, len
))) goto end
;
6915 WideCharToMultiByte(CP_ACP
, 0, local_nodenameW
, -1, nodenameA
, len
, NULL
, NULL
);
6919 len
= WideCharToMultiByte(CP_ACP
, 0, servname
, -1, NULL
, 0, NULL
, NULL
);
6920 if (!(servnameA
= HeapAlloc(GetProcessHeap(), 0, len
))) goto end
;
6921 WideCharToMultiByte(CP_ACP
, 0, servname
, -1, servnameA
, len
, NULL
, NULL
);
6926 struct getaddrinfo_args
*args
;
6928 if (!(args
= HeapAlloc(GetProcessHeap(), 0, sizeof(*args
)))) goto end
;
6929 args
->overlapped
= overlapped
;
6931 args
->nodename
= nodenameA
;
6932 args
->servname
= servnameA
;
6934 overlapped
->Internal
= WSAEINPROGRESS
;
6935 if (!TrySubmitThreadpoolCallback(getaddrinfo_callback
, args
, NULL
))
6937 HeapFree(GetProcessHeap(), 0, args
);
6938 ret
= GetLastError();
6943 if (local_nodenameW
!= nodename
)
6944 HeapFree(GetProcessHeap(), 0, local_nodenameW
);
6945 WSASetLastError(ERROR_IO_PENDING
);
6946 return ERROR_IO_PENDING
;
6949 ret
= WS_getaddrinfo(nodenameA
, servnameA
, hints
, &resA
);
6952 *res
= addrinfo_list_AtoW(resA
);
6953 WS_freeaddrinfo(resA
);
6957 if (local_nodenameW
!= nodename
)
6958 HeapFree(GetProcessHeap(), 0, local_nodenameW
);
6959 HeapFree(GetProcessHeap(), 0, nodenameA
);
6960 HeapFree(GetProcessHeap(), 0, servnameA
);
6964 /***********************************************************************
6965 * GetAddrInfoExW (WS2_32.@)
6967 int WINAPI
GetAddrInfoExW(const WCHAR
*name
, const WCHAR
*servname
, DWORD
namespace, GUID
*namespace_id
,
6968 const ADDRINFOEXW
*hints
, ADDRINFOEXW
**result
, struct timeval
*timeout
, OVERLAPPED
*overlapped
,
6969 LPLOOKUPSERVICE_COMPLETION_ROUTINE completion_routine
, HANDLE
*handle
)
6973 TRACE("(%s %s %x %s %p %p %p %p %p %p)\n", debugstr_w(name
), debugstr_w(servname
), namespace,
6974 debugstr_guid(namespace_id
), hints
, result
, timeout
, overlapped
, completion_routine
, handle
);
6976 if (namespace != NS_DNS
)
6977 FIXME("Unsupported namespace %u\n", namespace);
6979 FIXME("Unsupported naemspace_id %s\n", debugstr_guid(namespace_id
));
6981 FIXME("Unsupported hints\n");
6983 FIXME("Unsupported timeout\n");
6984 if (completion_routine
)
6985 FIXME("Unsupported completion_routine\n");
6987 FIXME("Unsupported cancel handle\n");
6989 ret
= WS_getaddrinfoW(name
, servname
, NULL
, result
, overlapped
);
6990 if (ret
) return ret
;
6991 if (handle
) *handle
= (HANDLE
)0xdeadbeef;
6995 /***********************************************************************
6996 * GetAddrInfoExOverlappedResult (WS2_32.@)
6998 int WINAPI
GetAddrInfoExOverlappedResult(OVERLAPPED
*overlapped
)
7000 TRACE("(%p)\n", overlapped
);
7001 return overlapped
->Internal
;
7004 /***********************************************************************
7005 * GetAddrInfoExCancel (WS2_32.@)
7007 int WINAPI
GetAddrInfoExCancel(HANDLE
*handle
)
7009 FIXME("(%p)\n", handle
);
7010 return WSA_INVALID_HANDLE
;
7013 /***********************************************************************
7014 * GetAddrInfoW (WS2_32.@)
7016 int WINAPI
GetAddrInfoW(LPCWSTR nodename
, LPCWSTR servname
, const ADDRINFOW
*hints
, PADDRINFOW
*res
)
7018 struct WS_addrinfo
*hintsA
= NULL
;
7020 int ret
= EAI_MEMORY
;
7022 TRACE("nodename %s, servname %s, hints %p, result %p\n",
7023 debugstr_w(nodename
), debugstr_w(servname
), hints
, res
);
7026 if (hints
) hintsA
= addrinfo_WtoA(hints
);
7027 ret
= WS_getaddrinfoW(nodename
, servname
, hintsA
, &resex
, NULL
);
7028 WS_freeaddrinfo(hintsA
);
7029 if (ret
) return ret
;
7033 /* ADDRINFOEXW has layout compatible with ADDRINFOW except for ai_next field,
7034 * so we may convert it in place */
7035 *res
= (ADDRINFOW
*)resex
;
7037 ((ADDRINFOW
*)resex
)->ai_next
= (ADDRINFOW
*)resex
->ai_next
;
7038 resex
= resex
->ai_next
;
7044 /***********************************************************************
7045 * FreeAddrInfoW (WS2_32.@)
7047 void WINAPI
FreeAddrInfoW(PADDRINFOW ai
)
7052 HeapFree(GetProcessHeap(), 0, ai
->ai_canonname
);
7053 HeapFree(GetProcessHeap(), 0, ai
->ai_addr
);
7055 HeapFree(GetProcessHeap(), 0, ai
);
7060 /***********************************************************************
7061 * FreeAddrInfoExW (WS2_32.@)
7063 void WINAPI
FreeAddrInfoExW(ADDRINFOEXW
*ai
)
7065 TRACE("(%p)\n", ai
);
7070 HeapFree(GetProcessHeap(), 0, ai
->ai_canonname
);
7071 HeapFree(GetProcessHeap(), 0, ai
->ai_addr
);
7073 HeapFree(GetProcessHeap(), 0, ai
);
7078 int WINAPI
WS_getnameinfo(const SOCKADDR
*sa
, WS_socklen_t salen
, PCHAR host
,
7079 DWORD hostlen
, PCHAR serv
, DWORD servlen
, INT flags
)
7081 #ifdef HAVE_GETNAMEINFO
7083 union generic_unix_sockaddr sa_u
;
7086 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa
), salen
, host
, hostlen
,
7087 serv
, servlen
, flags
);
7089 size
= ws_sockaddr_ws2u(sa
, salen
, &sa_u
);
7092 SetLastError(WSAEFAULT
);
7093 return WSA_NOT_ENOUGH_MEMORY
;
7095 ret
= getnameinfo(&sa_u
.addr
, size
, host
, hostlen
, serv
, servlen
, convert_niflag_w2u(flags
));
7096 return convert_eai_u2w(ret
);
7098 FIXME("getnameinfo() failed, not found during buildtime.\n");
7103 int WINAPI
GetNameInfoW(const SOCKADDR
*sa
, WS_socklen_t salen
, PWCHAR host
,
7104 DWORD hostlen
, PWCHAR serv
, DWORD servlen
, INT flags
)
7107 char *hostA
= NULL
, *servA
= NULL
;
7109 if (host
&& (!(hostA
= HeapAlloc(GetProcessHeap(), 0, hostlen
)))) return EAI_MEMORY
;
7110 if (serv
&& (!(servA
= HeapAlloc(GetProcessHeap(), 0, servlen
))))
7112 HeapFree(GetProcessHeap(), 0, hostA
);
7116 ret
= WS_getnameinfo(sa
, salen
, hostA
, hostlen
, servA
, servlen
, flags
);
7119 if (host
) MultiByteToWideChar(CP_ACP
, 0, hostA
, -1, host
, hostlen
);
7120 if (serv
) MultiByteToWideChar(CP_ACP
, 0, servA
, -1, serv
, servlen
);
7123 HeapFree(GetProcessHeap(), 0, hostA
);
7124 HeapFree(GetProcessHeap(), 0, servA
);
7128 /***********************************************************************
7129 * getservbyport (WS2_32.56)
7131 struct WS_servent
* WINAPI
WS_getservbyport(int port
, const char *proto
)
7133 struct WS_servent
* retval
= NULL
;
7134 #ifdef HAVE_GETSERVBYPORT
7135 struct servent
* serv
;
7136 char *proto_str
= NULL
;
7138 if (proto
&& *proto
)
7140 if (!(proto_str
= strdup_lower(proto
))) return NULL
;
7142 EnterCriticalSection( &csWSgetXXXbyYYY
);
7143 if( (serv
= getservbyport(port
, proto_str
)) != NULL
) {
7144 retval
= WS_dup_se(serv
);
7146 else SetLastError(WSANO_DATA
);
7147 LeaveCriticalSection( &csWSgetXXXbyYYY
);
7148 HeapFree( GetProcessHeap(), 0, proto_str
);
7150 TRACE("%d (i.e. port %d), %s ret %p\n", port
, (int)ntohl(port
), debugstr_a(proto
), retval
);
7155 /***********************************************************************
7156 * gethostname (WS2_32.57)
7158 int WINAPI
WS_gethostname(char *name
, int namelen
)
7163 TRACE("name %p, len %d\n", name
, namelen
);
7167 SetLastError(WSAEFAULT
);
7168 return SOCKET_ERROR
;
7171 if (gethostname(buf
, sizeof(buf
)) != 0)
7173 SetLastError(wsaErrno());
7174 return SOCKET_ERROR
;
7177 TRACE("<- '%s'\n", buf
);
7180 WARN("Windows supports NetBIOS name length up to 15 bytes!\n");
7183 SetLastError(WSAEFAULT
);
7184 WARN("<- not enough space for hostname, required %d, got %d!\n", len
+ 1, namelen
);
7185 return SOCKET_ERROR
;
7192 /* ------------------------------------- Windows sockets extensions -- *
7194 * ------------------------------------------------------------------- */
7196 /***********************************************************************
7197 * WSAEnumNetworkEvents (WS2_32.36)
7199 int WINAPI
WSAEnumNetworkEvents(SOCKET s
, WSAEVENT hEvent
, LPWSANETWORKEVENTS lpEvent
)
7203 int errors
[FD_MAX_EVENTS
];
7205 TRACE("%04lx, hEvent %p, lpEvent %p\n", s
, hEvent
, lpEvent
);
7207 SERVER_START_REQ( get_socket_event
)
7209 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
7210 req
->service
= TRUE
;
7211 req
->c_event
= wine_server_obj_handle( hEvent
);
7212 wine_server_set_reply( req
, errors
, sizeof(errors
) );
7213 if (!(ret
= wine_server_call(req
))) lpEvent
->lNetworkEvents
= reply
->pmask
& reply
->mask
;
7218 for (i
= 0; i
< FD_MAX_EVENTS
; i
++)
7219 lpEvent
->iErrorCode
[i
] = NtStatusToWSAError(errors
[i
]);
7222 SetLastError(WSAEINVAL
);
7223 return SOCKET_ERROR
;
7226 /***********************************************************************
7227 * WSAEventSelect (WS2_32.39)
7229 int WINAPI
WSAEventSelect(SOCKET s
, WSAEVENT hEvent
, LONG lEvent
)
7233 TRACE("%04lx, hEvent %p, event %08x\n", s
, hEvent
, lEvent
);
7235 SERVER_START_REQ( set_socket_event
)
7237 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
7239 req
->event
= wine_server_obj_handle( hEvent
);
7242 ret
= wine_server_call( req
);
7246 SetLastError(WSAEINVAL
);
7247 return SOCKET_ERROR
;
7250 /**********************************************************************
7251 * WSAGetOverlappedResult (WS2_32.40)
7253 BOOL WINAPI
WSAGetOverlappedResult( SOCKET s
, LPWSAOVERLAPPED lpOverlapped
,
7254 LPDWORD lpcbTransfer
, BOOL fWait
,
7259 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
7260 s
, lpOverlapped
, lpcbTransfer
, fWait
, lpdwFlags
);
7262 if ( lpOverlapped
== NULL
)
7264 ERR( "Invalid pointer\n" );
7265 SetLastError(WSA_INVALID_PARAMETER
);
7269 status
= lpOverlapped
->Internal
;
7270 if (status
== STATUS_PENDING
)
7274 SetLastError( WSA_IO_INCOMPLETE
);
7278 if (WaitForSingleObject( lpOverlapped
->hEvent
? lpOverlapped
->hEvent
: SOCKET2HANDLE(s
),
7279 INFINITE
) == WAIT_FAILED
)
7281 status
= lpOverlapped
->Internal
;
7285 *lpcbTransfer
= lpOverlapped
->InternalHigh
;
7288 *lpdwFlags
= lpOverlapped
->u
.s
.Offset
;
7290 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
7295 /***********************************************************************
7296 * WSAAsyncSelect (WS2_32.101)
7298 INT WINAPI
WSAAsyncSelect(SOCKET s
, HWND hWnd
, UINT uMsg
, LONG lEvent
)
7302 TRACE("%04lx, hWnd %p, uMsg %08x, event %08x\n", s
, hWnd
, uMsg
, lEvent
);
7304 SERVER_START_REQ( set_socket_event
)
7306 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
7309 req
->window
= wine_server_user_handle( hWnd
);
7311 ret
= wine_server_call( req
);
7315 SetLastError(WSAEINVAL
);
7316 return SOCKET_ERROR
;
7319 /***********************************************************************
7320 * WSACreateEvent (WS2_32.31)
7323 WSAEVENT WINAPI
WSACreateEvent(void)
7325 /* Create a manual-reset event, with initial state: unsignaled */
7328 return CreateEventW(NULL
, TRUE
, FALSE
, NULL
);
7331 /***********************************************************************
7332 * WSACloseEvent (WS2_32.29)
7335 BOOL WINAPI
WSACloseEvent(WSAEVENT event
)
7337 TRACE ("event=%p\n", event
);
7339 return CloseHandle(event
);
7342 /***********************************************************************
7343 * WSASocketA (WS2_32.78)
7346 SOCKET WINAPI
WSASocketA(int af
, int type
, int protocol
,
7347 LPWSAPROTOCOL_INFOA lpProtocolInfo
,
7348 GROUP g
, DWORD dwFlags
)
7351 WSAPROTOCOL_INFOW info
;
7353 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
7354 af
, type
, protocol
, lpProtocolInfo
, g
, dwFlags
);
7356 if (!lpProtocolInfo
) return WSASocketW(af
, type
, protocol
, NULL
, g
, dwFlags
);
7358 memcpy(&info
, lpProtocolInfo
, FIELD_OFFSET(WSAPROTOCOL_INFOW
, szProtocol
));
7359 len
= MultiByteToWideChar(CP_ACP
, 0, lpProtocolInfo
->szProtocol
, -1,
7360 info
.szProtocol
, WSAPROTOCOL_LEN
+ 1);
7364 SetLastError(WSAEINVAL
);
7365 return SOCKET_ERROR
;
7368 return WSASocketW(af
, type
, protocol
, &info
, g
, dwFlags
);
7371 /***********************************************************************
7372 * WSASocketW (WS2_32.79)
7375 SOCKET WINAPI
WSASocketW(int af
, int type
, int protocol
,
7376 LPWSAPROTOCOL_INFOW lpProtocolInfo
,
7377 GROUP g
, DWORD dwFlags
)
7381 int unixaf
, unixtype
, ipxptype
= -1;
7384 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
7385 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
7388 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
7389 af
, type
, protocol
, lpProtocolInfo
, g
, dwFlags
);
7393 err
= WSANOTINITIALISED
;
7397 /* hack for WSADuplicateSocket */
7398 if (lpProtocolInfo
&& lpProtocolInfo
->dwServiceFlags4
== 0xff00ff00) {
7399 ret
= lpProtocolInfo
->dwServiceFlags3
;
7400 TRACE("\tgot duplicate %04lx\n", ret
);
7406 if (af
== FROM_PROTOCOL_INFO
|| !af
)
7407 af
= lpProtocolInfo
->iAddressFamily
;
7408 if (type
== FROM_PROTOCOL_INFO
|| !type
)
7409 type
= lpProtocolInfo
->iSocketType
;
7410 if (protocol
== FROM_PROTOCOL_INFO
|| !protocol
)
7411 protocol
= lpProtocolInfo
->iProtocol
;
7414 if (!type
&& (af
|| protocol
))
7416 int autoproto
= protocol
;
7417 WSAPROTOCOL_INFOW infow
;
7419 /* default to the first valid protocol */
7421 autoproto
= valid_protocols
[0];
7422 else if(IS_IPX_PROTO(autoproto
))
7423 autoproto
= WS_NSPROTO_IPX
;
7425 if (WS_EnterSingleProtocolW(autoproto
, &infow
))
7427 type
= infow
.iSocketType
;
7429 /* after win2003 it's no longer possible to pass AF_UNSPEC
7430 using the protocol info struct */
7431 if (!lpProtocolInfo
&& af
== WS_AF_UNSPEC
)
7432 af
= infow
.iAddressFamily
;
7437 Windows has an extension to the IPX protocol that allows one to create sockets
7438 and set the IPX packet type at the same time, to do that a caller will use
7439 a protocol like NSPROTO_IPX + <PACKET TYPE>
7441 if (IS_IPX_PROTO(protocol
))
7442 ipxptype
= protocol
- WS_NSPROTO_IPX
;
7444 /* convert the socket family, type and protocol */
7445 unixaf
= convert_af_w2u(af
);
7446 unixtype
= convert_socktype_w2u(type
);
7447 protocol
= convert_proto_w2u(protocol
);
7448 if (unixaf
== AF_UNSPEC
) unixaf
= -1;
7450 /* filter invalid parameters */
7453 /* the type could not be converted */
7454 if (type
&& unixtype
< 0)
7456 err
= WSAESOCKTNOSUPPORT
;
7460 err
= WSAEPROTONOSUPPORT
;
7465 /* both family and protocol can't be invalid */
7472 /* family could not be converted and neither socket type */
7473 if (unixtype
< 0 && af
>= 0)
7476 err
= WSAESOCKTNOSUPPORT
;
7480 err
= WSAEAFNOSUPPORT
;
7484 SERVER_START_REQ( create_socket
)
7486 req
->family
= unixaf
;
7487 req
->type
= unixtype
;
7488 req
->protocol
= protocol
;
7489 req
->access
= GENERIC_READ
|GENERIC_WRITE
|SYNCHRONIZE
;
7490 req
->attributes
= (dwFlags
& WSA_FLAG_NO_HANDLE_INHERIT
) ? 0 : OBJ_INHERIT
;
7491 req
->flags
= dwFlags
& ~WSA_FLAG_NO_HANDLE_INHERIT
;
7492 set_error( wine_server_call( req
) );
7493 ret
= HANDLE2SOCKET( wine_server_ptr_handle( reply
->handle
));
7498 TRACE("\tcreated %04lx\n", ret
);
7500 set_ipx_packettype(ret
, ipxptype
);
7502 /* ensure IP_DONTFRAGMENT is disabled, in Linux the global default can be enabled */
7503 if (unixaf
== AF_INET
|| unixaf
== AF_INET6
)
7504 set_dont_fragment(ret
, unixaf
== AF_INET6
? IPPROTO_IPV6
: IPPROTO_IP
, FALSE
);
7507 if (unixaf
== AF_INET6
)
7509 int fd
= get_sock_fd(ret
, 0, NULL
);
7512 /* IPV6_V6ONLY is set by default on Windows */
7514 if (setsockopt(fd
, IPPROTO_IPV6
, IPV6_V6ONLY
, &enable
, sizeof(enable
)))
7515 WARN("\tsetting IPV6_V6ONLY failed - errno = %i\n", errno
);
7516 release_sock_fd(ret
, fd
);
7523 err
= GetLastError();
7524 if (err
== WSAEACCES
) /* raw socket denied */
7526 if (type
== SOCK_RAW
)
7527 ERR_(winediag
)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
7529 ERR_(winediag
)("Failed to create socket, this requires special permissions.\n");
7533 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
7534 if (err
== WSAEINVAL
)
7535 err
= WSAESOCKTNOSUPPORT
;
7536 else if (err
== WSAEOPNOTSUPP
)
7537 err
= WSAEPROTONOSUPPORT
;
7541 WARN("\t\tfailed, error %d!\n", err
);
7543 return INVALID_SOCKET
;
7546 /***********************************************************************
7547 * WSAJoinLeaf (WS2_32.58)
7550 SOCKET WINAPI
WSAJoinLeaf(
7552 const struct WS_sockaddr
*addr
,
7554 LPWSABUF lpCallerData
,
7555 LPWSABUF lpCalleeData
,
7561 return INVALID_SOCKET
;
7564 /***********************************************************************
7565 * __WSAFDIsSet (WS2_32.151)
7567 int WINAPI
__WSAFDIsSet(SOCKET s
, WS_fd_set
*set
)
7569 int i
= set
->fd_count
, ret
= 0;
7572 if (set
->fd_array
[i
] == s
)
7578 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s
, set
, set
->fd_count
, ret
);
7582 /***********************************************************************
7583 * WSAIsBlocking (WS2_32.114)
7585 BOOL WINAPI
WSAIsBlocking(void)
7587 /* By default WinSock should set all its sockets to non-blocking mode
7588 * and poll in PeekMessage loop when processing "blocking" ones. This
7589 * function is supposed to tell if the program is in this loop. Our
7590 * blocking calls are truly blocking so we always return FALSE.
7592 * Note: It is allowed to call this function without prior WSAStartup().
7599 /***********************************************************************
7600 * WSACancelBlockingCall (WS2_32.113)
7602 INT WINAPI
WSACancelBlockingCall(void)
7608 static INT WINAPI
WSA_DefaultBlockingHook( FARPROC x
)
7610 FIXME("How was this called?\n");
7615 /***********************************************************************
7616 * WSASetBlockingHook (WS2_32.109)
7618 FARPROC WINAPI
WSASetBlockingHook(FARPROC lpBlockFunc
)
7620 FARPROC prev
= blocking_hook
;
7621 blocking_hook
= lpBlockFunc
;
7622 TRACE("hook %p\n", lpBlockFunc
);
7627 /***********************************************************************
7628 * WSAUnhookBlockingHook (WS2_32.110)
7630 INT WINAPI
WSAUnhookBlockingHook(void)
7632 blocking_hook
= (FARPROC
)WSA_DefaultBlockingHook
;
7637 /* ----------------------------------- end of API stuff */
7639 /* ----------------------------------- helper functions -
7641 * TODO: Merge WS_dup_..() stuff into one function that
7642 * would operate with a generic structure containing internal
7643 * pointers (via a template of some kind).
7646 static int list_size(char** l
, int item_size
)
7651 j
+= (item_size
) ? item_size
: strlen(l
[i
]) + 1;
7652 j
+= (i
+ 1) * sizeof(char*); }
7656 static int list_dup(char** l_src
, char** l_to
, int item_size
)
7661 for (i
= 0; l_src
[i
]; i
++) ;
7662 p
= (char *)(l_to
+ i
+ 1);
7663 for (i
= 0; l_src
[i
]; i
++)
7665 int count
= ( item_size
) ? item_size
: strlen(l_src
[i
]) + 1;
7666 memcpy(p
, l_src
[i
], count
);
7671 return p
- (char *)l_to
;
7676 /* create a hostent entry
7678 * Creates the entry with enough memory for the name, aliases
7679 * addresses, and the address pointers. Also copies the name
7680 * and sets up all the pointers.
7682 * NOTE: The alias and address lists must be allocated with room
7683 * for the NULL item terminating the list. This is true even if
7684 * the list has no items ("aliases" and "addresses" must be
7685 * at least "1", a truly empty list is invalid).
7687 static struct WS_hostent
*WS_create_he(char *name
, int aliases
, int aliases_size
, int addresses
, int address_length
)
7689 struct WS_hostent
*p_to
;
7691 int size
= (sizeof(struct WS_hostent
) +
7693 sizeof(char *) * aliases
+
7695 sizeof(char *) * addresses
+
7696 address_length
* (addresses
- 1)), i
;
7698 if (!(p_to
= check_buffer_he(size
))) return NULL
;
7699 memset(p_to
, 0, size
);
7701 /* Use the memory in the same way winsock does.
7702 * First set the pointer for aliases, second set the pointers for addresses.
7703 * Third fill the addresses indexes, fourth jump aliases names size.
7704 * Fifth fill the hostname.
7705 * NOTE: This method is valid for OS version's >= XP.
7707 p
= (char *)(p_to
+ 1);
7708 p_to
->h_aliases
= (char **)p
;
7709 p
+= sizeof(char *)*aliases
;
7711 p_to
->h_addr_list
= (char **)p
;
7712 p
+= sizeof(char *)*addresses
;
7714 for (i
= 0, addresses
--; i
< addresses
; i
++, p
+= address_length
)
7715 p_to
->h_addr_list
[i
] = p
;
7717 /* NOTE: h_aliases must be filled in manually because we don't know each string
7718 * size, leave these pointers NULL (already set to NULL by memset earlier).
7728 /* duplicate hostent entry
7729 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
7730 * Ditto for protoent and servent.
7732 static struct WS_hostent
*WS_dup_he(const struct hostent
* p_he
)
7734 int i
, addresses
= 0, alias_size
= 0;
7735 struct WS_hostent
*p_to
;
7738 for( i
= 0; p_he
->h_aliases
[i
]; i
++) alias_size
+= strlen(p_he
->h_aliases
[i
]) + 1;
7739 while (p_he
->h_addr_list
[addresses
]) addresses
++;
7741 p_to
= WS_create_he(p_he
->h_name
, i
+ 1, alias_size
, addresses
+ 1, p_he
->h_length
);
7743 if (!p_to
) return NULL
;
7744 p_to
->h_addrtype
= convert_af_u2w(p_he
->h_addrtype
);
7745 p_to
->h_length
= p_he
->h_length
;
7747 for(i
= 0, p
= p_to
->h_addr_list
[0]; p_he
->h_addr_list
[i
]; i
++, p
+= p_to
->h_length
)
7748 memcpy(p
, p_he
->h_addr_list
[i
], p_to
->h_length
);
7750 /* Fill the aliases after the IP data */
7751 for(i
= 0; p_he
->h_aliases
[i
]; i
++)
7753 p_to
->h_aliases
[i
] = p
;
7754 strcpy(p
, p_he
->h_aliases
[i
]);
7761 /* ----- protoent */
7763 static struct WS_protoent
*WS_dup_pe(const struct protoent
* p_pe
)
7766 struct WS_protoent
*p_to
;
7768 int size
= (sizeof(*p_pe
) +
7769 strlen(p_pe
->p_name
) + 1 +
7770 list_size(p_pe
->p_aliases
, 0));
7772 if (!(p_to
= check_buffer_pe(size
))) return NULL
;
7773 p_to
->p_proto
= p_pe
->p_proto
;
7775 p
= (char *)(p_to
+ 1);
7777 strcpy(p
, p_pe
->p_name
);
7780 p_to
->p_aliases
= (char **)p
;
7781 list_dup(p_pe
->p_aliases
, p_to
->p_aliases
, 0);
7787 static struct WS_servent
*WS_dup_se(const struct servent
* p_se
)
7790 struct WS_servent
*p_to
;
7792 int size
= (sizeof(*p_se
) +
7793 strlen(p_se
->s_proto
) + 1 +
7794 strlen(p_se
->s_name
) + 1 +
7795 list_size(p_se
->s_aliases
, 0));
7797 if (!(p_to
= check_buffer_se(size
))) return NULL
;
7798 p_to
->s_port
= p_se
->s_port
;
7800 p
= (char *)(p_to
+ 1);
7802 strcpy(p
, p_se
->s_name
);
7806 strcpy(p
, p_se
->s_proto
);
7809 p_to
->s_aliases
= (char **)p
;
7810 list_dup(p_se
->s_aliases
, p_to
->s_aliases
, 0);
7815 /***********************************************************************
7816 * WSARecv (WS2_32.67)
7818 int WINAPI
WSARecv(SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
7819 LPDWORD NumberOfBytesReceived
, LPDWORD lpFlags
,
7820 LPWSAOVERLAPPED lpOverlapped
,
7821 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
7823 return WS2_recv_base(s
, lpBuffers
, dwBufferCount
, NumberOfBytesReceived
, lpFlags
,
7824 NULL
, NULL
, lpOverlapped
, lpCompletionRoutine
, NULL
);
7827 static int WS2_recv_base( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
7828 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
,
7829 struct WS_sockaddr
*lpFrom
,
7830 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
7831 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
,
7832 LPWSABUF lpControlBuffer
)
7834 unsigned int i
, options
;
7835 int n
, fd
, err
, overlapped
, flags
;
7836 struct ws2_async
*wsa
= NULL
, localwsa
;
7838 DWORD timeout_start
= GetTickCount();
7839 ULONG_PTR cvalue
= (lpOverlapped
&& ((ULONG_PTR
)lpOverlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)lpOverlapped
: 0;
7841 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
7842 s
, lpBuffers
, dwBufferCount
, *lpFlags
, lpFrom
,
7843 (lpFromlen
? *lpFromlen
: -1),
7844 lpOverlapped
, lpCompletionRoutine
);
7846 fd
= get_sock_fd( s
, FILE_READ_DATA
, &options
);
7847 TRACE( "fd=%d, options=%x\n", fd
, options
);
7849 if (fd
== -1) return SOCKET_ERROR
;
7851 if (*lpFlags
& WS_MSG_OOB
)
7853 /* It's invalid to receive OOB data from an OOBINLINED socket
7854 * as OOB data is turned into normal data. */
7855 socklen_t len
= sizeof(n
);
7856 if (!getsockopt(fd
, SOL_SOCKET
, SO_OOBINLINE
, (char*) &n
, &len
) && n
)
7863 overlapped
= (lpOverlapped
|| lpCompletionRoutine
) &&
7864 !(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
));
7865 if (overlapped
|| dwBufferCount
> 1)
7867 if (!(wsa
= (struct ws2_async
*)alloc_async_io( offsetof(struct ws2_async
, iovec
[dwBufferCount
]),
7877 wsa
->hSocket
= SOCKET2HANDLE(s
);
7878 wsa
->flags
= *lpFlags
;
7879 wsa
->lpFlags
= lpFlags
;
7881 wsa
->addrlen
.ptr
= lpFromlen
;
7882 wsa
->control
= lpControlBuffer
;
7883 wsa
->n_iovecs
= dwBufferCount
;
7884 wsa
->first_iovec
= 0;
7885 for (i
= 0; i
< dwBufferCount
; i
++)
7887 /* check buffer first to trigger write watches */
7888 if (IsBadWritePtr( lpBuffers
[i
].buf
, lpBuffers
[i
].len
))
7893 wsa
->iovec
[i
].iov_base
= lpBuffers
[i
].buf
;
7894 wsa
->iovec
[i
].iov_len
= lpBuffers
[i
].len
;
7897 flags
= convert_flags(wsa
->flags
);
7900 n
= WS2_recv( fd
, wsa
, flags
);
7903 /* Unix-like systems return EINVAL when attempting to read OOB data from
7904 * an empty socket buffer, convert that to a Windows expected return. */
7905 if ((flags
& MSG_OOB
) && errno
== EINVAL
)
7906 errno
= EWOULDBLOCK
;
7908 if (errno
!= EAGAIN
)
7914 else if (lpNumberOfBytesRecvd
) *lpNumberOfBytesRecvd
= n
;
7918 IO_STATUS_BLOCK
*iosb
= lpOverlapped
? (IO_STATUS_BLOCK
*)lpOverlapped
: &wsa
->local_iosb
;
7920 wsa
->user_overlapped
= lpOverlapped
;
7921 wsa
->completion_func
= lpCompletionRoutine
;
7922 release_sock_fd( s
, fd
);
7926 iosb
->u
.Status
= STATUS_PENDING
;
7927 iosb
->Information
= 0;
7929 if (wsa
->completion_func
)
7930 err
= register_async( ASYNC_TYPE_READ
, wsa
->hSocket
, &wsa
->io
, NULL
,
7931 ws2_async_apc
, wsa
, iosb
);
7933 err
= register_async( ASYNC_TYPE_READ
, wsa
->hSocket
, &wsa
->io
, lpOverlapped
->hEvent
,
7934 NULL
, (void *)cvalue
, iosb
);
7936 if (err
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
7937 SetLastError(NtStatusToWSAError( err
));
7938 return SOCKET_ERROR
;
7941 iosb
->u
.Status
= STATUS_SUCCESS
;
7942 iosb
->Information
= n
;
7943 if (!wsa
->completion_func
)
7945 if (cvalue
) WS_AddCompletion( s
, cvalue
, STATUS_SUCCESS
, n
);
7946 if (lpOverlapped
->hEvent
) SetEvent( lpOverlapped
->hEvent
);
7947 HeapFree( GetProcessHeap(), 0, wsa
);
7949 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC
)ws2_async_apc
,
7950 (ULONG_PTR
)wsa
, (ULONG_PTR
)iosb
, 0 );
7951 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7957 if ((err
= _is_blocking( s
, &is_blocking
)))
7959 err
= NtStatusToWSAError( err
);
7966 int poll_timeout
= -1;
7967 INT64 timeout
= get_rcvsnd_timeo(fd
, TRUE
);
7971 timeout
-= GetTickCount() - timeout_start
;
7972 if (timeout
< 0) poll_timeout
= 0;
7973 else poll_timeout
= timeout
<= INT_MAX
? timeout
: INT_MAX
;
7977 pfd
.events
= POLLIN
;
7978 if (*lpFlags
& WS_MSG_OOB
) pfd
.events
|= POLLPRI
;
7980 if (!poll_timeout
|| !poll( &pfd
, 1, poll_timeout
))
7983 /* a timeout is not fatal */
7984 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7990 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7991 err
= WSAEWOULDBLOCK
;
7996 TRACE(" -> %i bytes\n", n
);
7997 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
7998 release_sock_fd( s
, fd
);
7999 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
8000 SetLastError(ERROR_SUCCESS
);
8005 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
8006 release_sock_fd( s
, fd
);
8007 WARN(" -> ERROR %d\n", err
);
8008 SetLastError( err
);
8009 return SOCKET_ERROR
;
8012 /***********************************************************************
8013 * WSARecvFrom (WS2_32.69)
8015 INT WINAPI
WSARecvFrom( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
8016 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
, struct WS_sockaddr
*lpFrom
,
8017 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
8018 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
8021 return WS2_recv_base( s
, lpBuffers
, dwBufferCount
,
8022 lpNumberOfBytesRecvd
, lpFlags
,
8024 lpOverlapped
, lpCompletionRoutine
, NULL
);
8027 /***********************************************************************
8028 * WSCInstallProvider (WS2_32.88)
8030 INT WINAPI
WSCInstallProvider( const LPGUID lpProviderId
,
8031 LPCWSTR lpszProviderDllPath
,
8032 const LPWSAPROTOCOL_INFOW lpProtocolInfoList
,
8033 DWORD dwNumberOfEntries
,
8036 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId
),
8037 debugstr_w(lpszProviderDllPath
), lpProtocolInfoList
,
8038 dwNumberOfEntries
, lpErrno
);
8044 /***********************************************************************
8045 * WSCDeinstallProvider (WS2_32.83)
8047 INT WINAPI
WSCDeinstallProvider(LPGUID lpProviderId
, LPINT lpErrno
)
8049 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId
), lpErrno
);
8055 /***********************************************************************
8056 * WSAAccept (WS2_32.26)
8058 SOCKET WINAPI
WSAAccept( SOCKET s
, struct WS_sockaddr
*addr
, LPINT addrlen
,
8059 LPCONDITIONPROC lpfnCondition
, DWORD_PTR dwCallbackData
)
8063 WSABUF CallerId
, CallerData
, CalleeId
, CalleeData
;
8064 /* QOS SQOS, GQOS; */
8067 SOCKADDR src_addr
, dst_addr
;
8069 TRACE("socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
8070 s
, addr
, addrlen
, lpfnCondition
, dwCallbackData
);
8072 cs
= WS_accept(s
, addr
, addrlen
);
8073 if (cs
== SOCKET_ERROR
) return SOCKET_ERROR
;
8074 if (!lpfnCondition
) return cs
;
8076 if (addr
&& addrlen
)
8078 CallerId
.buf
= (char *)addr
;
8079 CallerId
.len
= *addrlen
;
8083 size
= sizeof(src_addr
);
8084 WS_getpeername(cs
, &src_addr
, &size
);
8085 CallerId
.buf
= (char *)&src_addr
;
8086 CallerId
.len
= size
;
8088 CallerData
.buf
= NULL
;
8091 size
= sizeof(dst_addr
);
8092 WS_getsockname(cs
, &dst_addr
, &size
);
8094 CalleeId
.buf
= (char *)&dst_addr
;
8095 CalleeId
.len
= sizeof(dst_addr
);
8097 ret
= (*lpfnCondition
)(&CallerId
, &CallerData
, NULL
, NULL
,
8098 &CalleeId
, &CalleeData
, &g
, dwCallbackData
);
8105 SERVER_START_REQ( set_socket_deferred
)
8107 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
8108 req
->deferred
= wine_server_obj_handle( SOCKET2HANDLE(cs
) );
8109 if ( !wine_server_call_err ( req
) )
8111 SetLastError( WSATRY_AGAIN
);
8112 WS_closesocket( cs
);
8116 return SOCKET_ERROR
;
8119 SetLastError(WSAECONNREFUSED
);
8120 return SOCKET_ERROR
;
8122 FIXME("Unknown return type from Condition function\n");
8123 SetLastError(WSAENOTSOCK
);
8124 return SOCKET_ERROR
;
8128 /***********************************************************************
8129 * WSADuplicateSocketA (WS2_32.32)
8131 int WINAPI
WSADuplicateSocketA( SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOA lpProtocolInfo
)
8133 return WS_DuplicateSocket(FALSE
, s
, dwProcessId
, (LPWSAPROTOCOL_INFOW
) lpProtocolInfo
);
8136 /***********************************************************************
8137 * WSADuplicateSocketW (WS2_32.33)
8139 int WINAPI
WSADuplicateSocketW( SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOW lpProtocolInfo
)
8141 return WS_DuplicateSocket(TRUE
, s
, dwProcessId
, lpProtocolInfo
);
8144 /***********************************************************************
8145 * WSAInstallServiceClassA (WS2_32.48)
8147 int WINAPI
WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info
)
8149 FIXME("Request to install service %s\n",debugstr_a(info
->lpszServiceClassName
));
8150 SetLastError(WSAEACCES
);
8151 return SOCKET_ERROR
;
8154 /***********************************************************************
8155 * WSAInstallServiceClassW (WS2_32.49)
8157 int WINAPI
WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info
)
8159 FIXME("Request to install service %s\n",debugstr_w(info
->lpszServiceClassName
));
8160 SetLastError(WSAEACCES
);
8161 return SOCKET_ERROR
;
8164 /***********************************************************************
8165 * WSARemoveServiceClass (WS2_32.70)
8167 int WINAPI
WSARemoveServiceClass(LPGUID info
)
8169 FIXME("Request to remove service %s\n", debugstr_guid(info
));
8170 SetLastError(WSATYPE_NOT_FOUND
);
8171 return SOCKET_ERROR
;
8174 /***********************************************************************
8175 * inet_ntop (WS2_32.@)
8177 PCSTR WINAPI
WS_inet_ntop( INT family
, PVOID addr
, PSTR buffer
, SIZE_T len
)
8179 #ifdef HAVE_INET_NTOP
8180 struct WS_in6_addr
*in6
;
8181 struct WS_in_addr
*in
;
8184 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family
, addr
, buffer
, len
);
8187 SetLastError( STATUS_INVALID_PARAMETER
);
8196 pdst
= inet_ntop( AF_INET
, &in
->WS_s_addr
, buffer
, len
);
8202 pdst
= inet_ntop( AF_INET6
, in6
->WS_s6_addr
, buffer
, len
);
8206 SetLastError( WSAEAFNOSUPPORT
);
8210 if (!pdst
) SetLastError( STATUS_INVALID_PARAMETER
);
8213 FIXME( "not supported on this platform\n" );
8214 SetLastError( WSAEAFNOSUPPORT
);
8219 /***********************************************************************
8220 * inet_pton (WS2_32.@)
8222 INT WINAPI
WS_inet_pton( INT family
, PCSTR addr
, PVOID buffer
)
8224 #ifdef HAVE_INET_PTON
8227 TRACE("family %d, addr %s, buffer (%p)\n", family
, debugstr_a(addr
), buffer
);
8229 if (!addr
|| !buffer
)
8231 SetLastError(WSAEFAULT
);
8232 return SOCKET_ERROR
;
8235 unixaf
= convert_af_w2u(family
);
8236 if (unixaf
!= AF_INET
&& unixaf
!= AF_INET6
)
8238 SetLastError(WSAEAFNOSUPPORT
);
8239 return SOCKET_ERROR
;
8242 ret
= inet_pton(unixaf
, addr
, buffer
);
8243 if (ret
== -1) SetLastError(wsaErrno());
8246 FIXME( "not supported on this platform\n" );
8247 SetLastError( WSAEAFNOSUPPORT
);
8248 return SOCKET_ERROR
;
8252 /***********************************************************************
8253 * InetPtonW (WS2_32.@)
8255 INT WINAPI
InetPtonW(INT family
, PCWSTR addr
, PVOID buffer
)
8261 TRACE("family %d, addr %s, buffer (%p)\n", family
, debugstr_w(addr
), buffer
);
8265 SetLastError(WSAEFAULT
);
8266 return SOCKET_ERROR
;
8269 len
= WideCharToMultiByte(CP_ACP
, 0, addr
, -1, NULL
, 0, NULL
, NULL
);
8270 if (!(addrA
= HeapAlloc(GetProcessHeap(), 0, len
)))
8272 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8273 return SOCKET_ERROR
;
8275 WideCharToMultiByte(CP_ACP
, 0, addr
, -1, addrA
, len
, NULL
, NULL
);
8277 ret
= WS_inet_pton(family
, addrA
, buffer
);
8279 HeapFree(GetProcessHeap(), 0, addrA
);
8283 /***********************************************************************
8284 * InetNtopW (WS2_32.@)
8286 PCWSTR WINAPI
InetNtopW(INT family
, PVOID addr
, PWSTR buffer
, SIZE_T len
)
8288 char bufferA
[WS_INET6_ADDRSTRLEN
];
8291 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family
, addr
, buffer
, len
);
8293 if (WS_inet_ntop(family
, addr
, bufferA
, sizeof(bufferA
)))
8295 if (MultiByteToWideChar(CP_ACP
, 0, bufferA
, -1, buffer
, len
))
8298 SetLastError(ERROR_INVALID_PARAMETER
);
8303 /***********************************************************************
8304 * WSAStringToAddressA (WS2_32.80)
8306 INT WINAPI
WSAStringToAddressA(LPSTR AddressString
,
8308 LPWSAPROTOCOL_INFOA lpProtocolInfo
,
8309 LPSOCKADDR lpAddress
,
8310 LPINT lpAddressLength
)
8313 LPSTR workBuffer
=NULL
,ptrPort
;
8315 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString
), AddressFamily
,
8316 lpProtocolInfo
, lpAddress
, lpAddressLength
);
8318 if (!lpAddressLength
|| !lpAddress
) return SOCKET_ERROR
;
8322 SetLastError(WSAEINVAL
);
8323 return SOCKET_ERROR
;
8327 FIXME("ProtocolInfo not implemented.\n");
8329 workBuffer
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
,
8330 strlen(AddressString
) + 1);
8333 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8334 return SOCKET_ERROR
;
8337 strcpy(workBuffer
, AddressString
);
8339 switch(AddressFamily
)
8343 struct in_addr inetaddr
;
8345 /* If lpAddressLength is too small, tell caller the size we need */
8346 if (*lpAddressLength
< sizeof(SOCKADDR_IN
))
8348 *lpAddressLength
= sizeof(SOCKADDR_IN
);
8352 *lpAddressLength
= sizeof(SOCKADDR_IN
);
8353 memset(lpAddress
, 0, sizeof(SOCKADDR_IN
));
8355 ((LPSOCKADDR_IN
)lpAddress
)->sin_family
= WS_AF_INET
;
8357 ptrPort
= strchr(workBuffer
, ':');
8360 /* User may have entered an IPv6 and asked to parse as IPv4 */
8361 if(strchr(ptrPort
+ 1, ':'))
8366 ((LPSOCKADDR_IN
)lpAddress
)->sin_port
= htons(atoi(ptrPort
+1));
8370 if(inet_aton(workBuffer
, &inetaddr
) > 0)
8372 ((LPSOCKADDR_IN
)lpAddress
)->sin_addr
.WS_s_addr
= inetaddr
.s_addr
;
8382 struct in6_addr inetaddr
;
8383 char *ptrAddr
= workBuffer
;
8385 /* If lpAddressLength is too small, tell caller the size we need */
8386 if (*lpAddressLength
< sizeof(SOCKADDR_IN6
))
8388 *lpAddressLength
= sizeof(SOCKADDR_IN6
);
8392 #ifdef HAVE_INET_PTON
8393 *lpAddressLength
= sizeof(SOCKADDR_IN6
);
8394 memset(lpAddress
, 0, sizeof(SOCKADDR_IN6
));
8396 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_family
= WS_AF_INET6
;
8398 /* Valid IPv6 addresses can also be surrounded by [ ], and in this case
8399 * a port number may follow after like in [fd12:3456:7890::1]:12345
8400 * We need to cut the brackets and find the port if any. */
8402 if(*workBuffer
== '[')
8404 ptrPort
= strchr(workBuffer
, ']');
8407 SetLastError(WSAEINVAL
);
8408 return SOCKET_ERROR
;
8411 if (ptrPort
[1] == ':')
8412 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_port
= htons(atoi(ptrPort
+ 2));
8415 ptrAddr
= workBuffer
+ 1;
8418 if(inet_pton(AF_INET6
, ptrAddr
, &inetaddr
) > 0)
8420 memcpy(&((LPSOCKADDR_IN6
)lpAddress
)->sin6_addr
, &inetaddr
,
8421 sizeof(struct in6_addr
));
8425 #endif /* HAVE_INET_PTON */
8431 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
8432 TRACE("Unsupported address family specified: %d.\n", AddressFamily
);
8436 HeapFree(GetProcessHeap(), 0, workBuffer
);
8440 return SOCKET_ERROR
;
8443 /***********************************************************************
8444 * WSAStringToAddressW (WS2_32.81)
8446 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
8447 * If this should be the case, it would be required to map these digits
8448 * to Unicode digits (0-9) using FoldString first.
8450 INT WINAPI
WSAStringToAddressW(LPWSTR AddressString
,
8452 LPWSAPROTOCOL_INFOW lpProtocolInfo
,
8453 LPSOCKADDR lpAddress
,
8454 LPINT lpAddressLength
)
8457 LPSTR workBuffer
=NULL
;
8458 WSAPROTOCOL_INFOA infoA
;
8459 LPWSAPROTOCOL_INFOA lpProtoInfoA
= NULL
;
8461 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString
), AddressFamily
, lpProtocolInfo
,
8462 lpAddress
, lpAddressLength
);
8464 if (!lpAddressLength
|| !lpAddress
) return SOCKET_ERROR
;
8466 /* if ProtocolInfo is available - convert to ANSI variant */
8469 lpProtoInfoA
= &infoA
;
8470 memcpy( lpProtoInfoA
, lpProtocolInfo
, FIELD_OFFSET( WSAPROTOCOL_INFOA
, szProtocol
) );
8472 if (!WideCharToMultiByte( CP_ACP
, 0, lpProtocolInfo
->szProtocol
, -1,
8473 lpProtoInfoA
->szProtocol
, WSAPROTOCOL_LEN
+1, NULL
, NULL
))
8475 SetLastError(WSAEINVAL
);
8476 return SOCKET_ERROR
;
8482 /* Translate AddressString to ANSI code page - assumes that only
8483 standard digits 0-9 are used with this API call */
8484 sBuffer
= WideCharToMultiByte( CP_ACP
, 0, AddressString
, -1, NULL
, 0, NULL
, NULL
);
8485 workBuffer
= HeapAlloc( GetProcessHeap(), 0, sBuffer
);
8489 WideCharToMultiByte( CP_ACP
, 0, AddressString
, -1, workBuffer
, sBuffer
, NULL
, NULL
);
8490 res
= WSAStringToAddressA(workBuffer
,AddressFamily
,lpProtoInfoA
,
8491 lpAddress
,lpAddressLength
);
8492 HeapFree( GetProcessHeap(), 0, workBuffer
);
8496 res
= WSA_NOT_ENOUGH_MEMORY
;
8502 return SOCKET_ERROR
;
8505 /***********************************************************************
8506 * WSAAddressToStringA (WS2_32.27)
8508 * See WSAAddressToStringW
8510 INT WINAPI
WSAAddressToStringA( LPSOCKADDR sockaddr
, DWORD len
,
8511 LPWSAPROTOCOL_INFOA info
, LPSTR string
,
8515 CHAR buffer
[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8518 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr
, len
, info
, string
, lenstr
);
8520 if (!sockaddr
) return SOCKET_ERROR
;
8521 if (!string
|| !lenstr
) return SOCKET_ERROR
;
8523 switch(sockaddr
->sa_family
)
8527 unsigned int long_ip
= ntohl(((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
);
8528 if (len
< sizeof(SOCKADDR_IN
)) return SOCKET_ERROR
;
8529 sprintf( buffer
, "%u.%u.%u.%u:%u",
8530 (long_ip
>> 24) & 0xff,
8531 (long_ip
>> 16) & 0xff,
8532 (long_ip
>> 8) & 0xff,
8534 ntohs( ((SOCKADDR_IN
*)sockaddr
)->sin_port
) );
8536 p
= strchr( buffer
, ':' );
8537 if (!((SOCKADDR_IN
*)sockaddr
)->sin_port
) *p
= 0;
8542 struct WS_sockaddr_in6
*sockaddr6
= (LPSOCKADDR_IN6
) sockaddr
;
8546 if (len
< sizeof(SOCKADDR_IN6
)) return SOCKET_ERROR
;
8547 if ((sockaddr6
->sin6_port
))
8548 strcpy(buffer
, "[");
8549 slen
= strlen(buffer
);
8550 if (!WS_inet_ntop(WS_AF_INET6
, &sockaddr6
->sin6_addr
, &buffer
[slen
], sizeof(buffer
) - slen
))
8552 SetLastError(WSAEINVAL
);
8553 return SOCKET_ERROR
;
8555 if ((sockaddr6
->sin6_scope_id
))
8556 sprintf(buffer
+strlen(buffer
), "%%%u", sockaddr6
->sin6_scope_id
);
8557 if ((sockaddr6
->sin6_port
))
8558 sprintf(buffer
+strlen(buffer
), "]:%u", ntohs(sockaddr6
->sin6_port
));
8563 SetLastError(WSAEINVAL
);
8564 return SOCKET_ERROR
;
8567 size
= strlen( buffer
) + 1;
8572 SetLastError(WSAEFAULT
);
8573 return SOCKET_ERROR
;
8576 TRACE("=> %s,%u bytes\n", debugstr_a(buffer
), size
);
8578 strcpy( string
, buffer
);
8582 /***********************************************************************
8583 * WSAAddressToStringW (WS2_32.28)
8585 * Convert a sockaddr address into a readable address string.
8588 * sockaddr [I] Pointer to a sockaddr structure.
8589 * len [I] Size of the sockaddr structure.
8590 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
8591 * string [I/O] Pointer to a buffer to receive the address string.
8592 * lenstr [I/O] Size of the receive buffer in WCHARs.
8596 * Failure: SOCKET_ERROR
8599 * The 'info' parameter is ignored.
8601 INT WINAPI
WSAAddressToStringW( LPSOCKADDR sockaddr
, DWORD len
,
8602 LPWSAPROTOCOL_INFOW info
, LPWSTR string
,
8607 WCHAR buffer
[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8610 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr
, len
, info
, string
, lenstr
);
8613 ret
= WSAAddressToStringA(sockaddr
, len
, NULL
, bufAddr
, &size
);
8615 if (ret
) return ret
;
8617 MultiByteToWideChar( CP_ACP
, 0, bufAddr
, size
, buffer
, sizeof( buffer
)/sizeof(WCHAR
));
8622 SetLastError(WSAEFAULT
);
8623 return SOCKET_ERROR
;
8626 TRACE("=> %s,%u bytes\n", debugstr_w(buffer
), size
);
8628 lstrcpyW( string
, buffer
);
8632 /***********************************************************************
8633 * WSAEnumNameSpaceProvidersA (WS2_32.34)
8635 INT WINAPI
WSAEnumNameSpaceProvidersA( LPDWORD len
, LPWSANAMESPACE_INFOA buffer
)
8637 FIXME( "(%p %p) Stub!\n", len
, buffer
);
8641 /***********************************************************************
8642 * WSAEnumNameSpaceProvidersW (WS2_32.35)
8644 INT WINAPI
WSAEnumNameSpaceProvidersW( LPDWORD len
, LPWSANAMESPACE_INFOW buffer
)
8646 FIXME( "(%p %p) Stub!\n", len
, buffer
);
8650 /***********************************************************************
8651 * WSAGetQOSByName (WS2_32.41)
8653 BOOL WINAPI
WSAGetQOSByName( SOCKET s
, LPWSABUF lpQOSName
, LPQOS lpQOS
)
8655 FIXME( "(0x%04lx %p %p) Stub!\n", s
, lpQOSName
, lpQOS
);
8659 /***********************************************************************
8660 * WSAGetServiceClassInfoA (WS2_32.42)
8662 INT WINAPI
WSAGetServiceClassInfoA( LPGUID provider
, LPGUID service
, LPDWORD len
,
8663 LPWSASERVICECLASSINFOA info
)
8665 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider
), debugstr_guid(service
),
8667 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8668 return SOCKET_ERROR
;
8671 /***********************************************************************
8672 * WSAGetServiceClassInfoW (WS2_32.43)
8674 INT WINAPI
WSAGetServiceClassInfoW( LPGUID provider
, LPGUID service
, LPDWORD len
,
8675 LPWSASERVICECLASSINFOW info
)
8677 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider
), debugstr_guid(service
),
8679 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8680 return SOCKET_ERROR
;
8683 /***********************************************************************
8684 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
8686 INT WINAPI
WSAGetServiceClassNameByClassIdA( LPGUID
class, LPSTR service
, LPDWORD len
)
8688 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service
, len
);
8689 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8690 return SOCKET_ERROR
;
8693 /***********************************************************************
8694 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
8696 INT WINAPI
WSAGetServiceClassNameByClassIdW( LPGUID
class, LPWSTR service
, LPDWORD len
)
8698 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service
, len
);
8699 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8700 return SOCKET_ERROR
;
8703 /***********************************************************************
8704 * WSALookupServiceBeginA (WS2_32.59)
8706 INT WINAPI
WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions
,
8707 DWORD dwControlFlags
,
8710 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions
, dwControlFlags
,
8712 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8713 return SOCKET_ERROR
;
8716 /***********************************************************************
8717 * WSALookupServiceBeginW (WS2_32.60)
8719 INT WINAPI
WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions
,
8720 DWORD dwControlFlags
,
8723 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions
, dwControlFlags
,
8725 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8726 return SOCKET_ERROR
;
8729 /***********************************************************************
8730 * WSALookupServiceEnd (WS2_32.61)
8732 INT WINAPI
WSALookupServiceEnd( HANDLE lookup
)
8734 FIXME("(%p) Stub!\n", lookup
);
8738 /***********************************************************************
8739 * WSALookupServiceNextA (WS2_32.62)
8741 INT WINAPI
WSALookupServiceNextA( HANDLE lookup
, DWORD flags
, LPDWORD len
, LPWSAQUERYSETA results
)
8743 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup
, flags
, len
, results
);
8744 SetLastError(WSA_E_NO_MORE
);
8745 return SOCKET_ERROR
;
8748 /***********************************************************************
8749 * WSALookupServiceNextW (WS2_32.63)
8751 INT WINAPI
WSALookupServiceNextW( HANDLE lookup
, DWORD flags
, LPDWORD len
, LPWSAQUERYSETW results
)
8753 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup
, flags
, len
, results
);
8754 SetLastError(WSA_E_NO_MORE
);
8755 return SOCKET_ERROR
;
8758 /***********************************************************************
8759 * WSANtohl (WS2_32.64)
8761 INT WINAPI
WSANtohl( SOCKET s
, WS_u_long netlong
, WS_u_long
* lphostlong
)
8763 TRACE( "(%04lx 0x%08x %p)\n", s
, netlong
, lphostlong
);
8765 if (!lphostlong
) return WSAEFAULT
;
8767 *lphostlong
= ntohl( netlong
);
8771 /***********************************************************************
8772 * WSANtohs (WS2_32.65)
8774 INT WINAPI
WSANtohs( SOCKET s
, WS_u_short netshort
, WS_u_short
* lphostshort
)
8776 TRACE( "(%04lx 0x%08x %p)\n", s
, netshort
, lphostshort
);
8778 if (!lphostshort
) return WSAEFAULT
;
8780 *lphostshort
= ntohs( netshort
);
8784 /***********************************************************************
8785 * WSAProviderConfigChange (WS2_32.66)
8787 INT WINAPI
WSAProviderConfigChange( LPHANDLE handle
, LPWSAOVERLAPPED overlapped
,
8788 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
8790 FIXME( "(%p %p %p) Stub!\n", handle
, overlapped
, completion
);
8791 return SOCKET_ERROR
;
8794 /***********************************************************************
8795 * WSARecvDisconnect (WS2_32.68)
8797 INT WINAPI
WSARecvDisconnect( SOCKET s
, LPWSABUF disconnectdata
)
8799 TRACE( "(%04lx %p)\n", s
, disconnectdata
);
8801 return WS_shutdown( s
, SD_RECEIVE
);
8804 /***********************************************************************
8805 * WSASetServiceA (WS2_32.76)
8807 INT WINAPI
WSASetServiceA( LPWSAQUERYSETA query
, WSAESETSERVICEOP operation
, DWORD flags
)
8809 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query
, operation
, flags
);
8813 /***********************************************************************
8814 * WSASetServiceW (WS2_32.77)
8816 INT WINAPI
WSASetServiceW( LPWSAQUERYSETW query
, WSAESETSERVICEOP operation
, DWORD flags
)
8818 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query
, operation
, flags
);
8822 /***********************************************************************
8823 * WSCEnableNSProvider (WS2_32.84)
8825 INT WINAPI
WSCEnableNSProvider( LPGUID provider
, BOOL enable
)
8827 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider
), enable
);
8831 /***********************************************************************
8832 * WSCGetProviderPath (WS2_32.86)
8834 INT WINAPI
WSCGetProviderPath( LPGUID provider
, LPWSTR path
, LPINT len
, LPINT errcode
)
8836 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider
), path
, len
, errcode
);
8838 if (!errcode
|| !provider
|| !len
) return WSAEFAULT
;
8840 *errcode
= WSAEINVAL
;
8841 return SOCKET_ERROR
;
8844 /***********************************************************************
8845 * WSCInstallNameSpace (WS2_32.87)
8847 INT WINAPI
WSCInstallNameSpace( LPWSTR identifier
, LPWSTR path
, DWORD
namespace,
8848 DWORD version
, LPGUID provider
)
8850 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier
), debugstr_w(path
),
8851 namespace, version
, debugstr_guid(provider
) );
8855 /***********************************************************************
8856 * WSCUnInstallNameSpace (WS2_32.89)
8858 INT WINAPI
WSCUnInstallNameSpace( LPGUID lpProviderId
)
8860 FIXME("(%s) Stub!\n", debugstr_guid(lpProviderId
));
8864 /***********************************************************************
8865 * WSCWriteProviderOrder (WS2_32.91)
8867 INT WINAPI
WSCWriteProviderOrder( LPDWORD entry
, DWORD number
)
8869 FIXME("(%p 0x%08x) Stub!\n", entry
, number
);
8873 /***********************************************************************
8874 * WSANSPIoctl (WS2_32.91)
8876 INT WINAPI
WSANSPIoctl( HANDLE hLookup
, DWORD dwControlCode
, LPVOID lpvInBuffer
,
8877 DWORD cbInBuffer
, LPVOID lpvOutBuffer
, DWORD cbOutBuffer
,
8878 LPDWORD lpcbBytesReturned
, LPWSACOMPLETION lpCompletion
)
8880 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup
, dwControlCode
,
8881 lpvInBuffer
, cbInBuffer
, lpvOutBuffer
, cbOutBuffer
, lpcbBytesReturned
, lpCompletion
);
8882 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8883 return SOCKET_ERROR
;
8886 /*****************************************************************************
8887 * WSAEnumProtocolsA [WS2_32.@]
8889 * see function WSAEnumProtocolsW
8891 INT WINAPI
WSAEnumProtocolsA( LPINT protocols
, LPWSAPROTOCOL_INFOA buffer
, LPDWORD len
)
8893 return WS_EnumProtocols( FALSE
, protocols
, (LPWSAPROTOCOL_INFOW
) buffer
, len
);
8896 /*****************************************************************************
8897 * WSAEnumProtocolsW [WS2_32.@]
8899 * Retrieves information about specified set of active network protocols.
8902 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
8903 * retrieves information on all available protocols.
8904 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
8906 * len [I/O] Pointer to a variable specifying buffer size. On output
8907 * the variable holds the number of bytes needed when the
8908 * specified size is too small.
8911 * Success: number of WSAPROTOCOL_INFO structures in buffer.
8912 * Failure: SOCKET_ERROR
8915 * NT4SP5 does not return SPX if protocols == NULL
8918 * - NT4SP5 returns in addition these list of NETBIOS protocols
8919 * (address family 17), each entry two times one for socket type 2 and 5
8921 * iProtocol szProtocol
8922 * 0x80000000 \Device\NwlnkNb
8923 * 0xfffffffa \Device\NetBT_CBENT7
8924 * 0xfffffffb \Device\Nbf_CBENT7
8925 * 0xfffffffc \Device\NetBT_NdisWan5
8926 * 0xfffffffd \Device\NetBT_El9202
8927 * 0xfffffffe \Device\Nbf_El9202
8928 * 0xffffffff \Device\Nbf_NdisWan4
8930 * - there is no check that the operating system supports the returned
8933 INT WINAPI
WSAEnumProtocolsW( LPINT protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
)
8935 return WS_EnumProtocols( TRUE
, protocols
, buffer
, len
);
8938 /*****************************************************************************
8939 * WSCEnumProtocols [WS2_32.@]
8942 * protocols [I] Null-terminated array of iProtocol values.
8943 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
8944 * len [I/O] Size of buffer on input/output.
8945 * errno [O] Error code.
8948 * Success: number of protocols to be reported on.
8949 * Failure: SOCKET_ERROR. error is in errno.
8952 * Doesn't supply info on layered protocols.
8955 INT WINAPI
WSCEnumProtocols( LPINT protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
, LPINT err
)
8957 INT ret
= WSAEnumProtocolsW( protocols
, buffer
, len
);
8959 if (ret
== SOCKET_ERROR
) *err
= WSAENOBUFS
;