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 */
244 extern ssize_t CDECL
__wine_locked_recvmsg( int fd
, struct msghdr
*hdr
, int flags
);
247 * The actual definition of WSASendTo, wrapped in a different function name
248 * so that internal calls from ws2_32 itself will not trigger programs like
249 * Garena, which hooks WSASendTo/WSARecvFrom calls.
251 static int WS2_sendto( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
252 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
253 const struct WS_sockaddr
*to
, int tolen
,
254 LPWSAOVERLAPPED lpOverlapped
,
255 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);
258 * Internal fundamental receive function, essentially WSARecvFrom with an
259 * additional parameter to support message control headers.
261 static int WS2_recv_base( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
262 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
,
263 struct WS_sockaddr
*lpFrom
,
264 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
265 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
,
266 LPWSABUF lpControlBuffer
);
268 /* critical section to protect some non-reentrant net function */
269 static CRITICAL_SECTION csWSgetXXXbyYYY
;
270 static CRITICAL_SECTION_DEBUG critsect_debug
=
272 0, 0, &csWSgetXXXbyYYY
,
273 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
274 0, 0, { (DWORD_PTR
)(__FILE__
": csWSgetXXXbyYYY") }
276 static CRITICAL_SECTION csWSgetXXXbyYYY
= { &critsect_debug
, -1, 0, 0, 0, 0 };
278 union generic_unix_sockaddr
280 struct sockaddr addr
;
281 char data
[128]; /* should be big enough for all families */
284 static inline const char *debugstr_sockaddr( const struct WS_sockaddr
*a
)
286 if (!a
) return "(nil)";
287 switch (a
->sa_family
)
293 struct WS_sockaddr_in
*sin
= (struct WS_sockaddr_in
*)a
;
295 p
= WS_inet_ntop( WS_AF_INET
, &sin
->sin_addr
, buf
, sizeof(buf
) );
297 p
= "(unknown IPv4 address)";
299 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
300 p
, ntohs(sin
->sin_port
));
306 struct WS_sockaddr_in6
*sin
= (struct WS_sockaddr_in6
*)a
;
308 p
= WS_inet_ntop( WS_AF_INET6
, &sin
->sin6_addr
, buf
, sizeof(buf
) );
310 p
= "(unknown IPv6 address)";
311 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
312 p
, ntohs(sin
->sin6_port
));
317 char netnum
[16], nodenum
[16];
318 struct WS_sockaddr_ipx
*sin
= (struct WS_sockaddr_ipx
*)a
;
320 for (i
= 0;i
< 4; i
++) sprintf(netnum
+ i
* 2, "%02X", (unsigned char) sin
->sa_netnum
[i
]);
321 for (i
= 0;i
< 6; i
++) sprintf(nodenum
+ i
* 2, "%02X", (unsigned char) sin
->sa_nodenum
[i
]);
323 return wine_dbg_sprintf("{ family AF_IPX, address %s.%s, ipx socket %d }",
324 netnum
, nodenum
, sin
->sa_socket
);
330 memcpy( &addr
, ((const SOCKADDR_IRDA
*)a
)->irdaDeviceID
, sizeof(addr
) );
331 addr
= ntohl( addr
);
332 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
334 ((const SOCKADDR_IRDA
*)a
)->irdaServiceName
);
337 return wine_dbg_sprintf("{ family %d }", a
->sa_family
);
341 static inline const char *debugstr_sockopt(int level
, int optname
)
343 const char *stropt
= NULL
, *strlevel
= NULL
;
345 #define DEBUG_SOCKLEVEL(x) case (x): strlevel = #x
346 #define DEBUG_SOCKOPT(x) case (x): stropt = #x; break
350 DEBUG_SOCKLEVEL(WS_SOL_SOCKET
);
353 DEBUG_SOCKOPT(WS_SO_ACCEPTCONN
);
354 DEBUG_SOCKOPT(WS_SO_BROADCAST
);
355 DEBUG_SOCKOPT(WS_SO_BSP_STATE
);
356 DEBUG_SOCKOPT(WS_SO_CONDITIONAL_ACCEPT
);
357 DEBUG_SOCKOPT(WS_SO_CONNECT_TIME
);
358 DEBUG_SOCKOPT(WS_SO_DEBUG
);
359 DEBUG_SOCKOPT(WS_SO_DONTLINGER
);
360 DEBUG_SOCKOPT(WS_SO_DONTROUTE
);
361 DEBUG_SOCKOPT(WS_SO_ERROR
);
362 DEBUG_SOCKOPT(WS_SO_EXCLUSIVEADDRUSE
);
363 DEBUG_SOCKOPT(WS_SO_GROUP_ID
);
364 DEBUG_SOCKOPT(WS_SO_GROUP_PRIORITY
);
365 DEBUG_SOCKOPT(WS_SO_KEEPALIVE
);
366 DEBUG_SOCKOPT(WS_SO_LINGER
);
367 DEBUG_SOCKOPT(WS_SO_MAX_MSG_SIZE
);
368 DEBUG_SOCKOPT(WS_SO_OOBINLINE
);
369 DEBUG_SOCKOPT(WS_SO_OPENTYPE
);
370 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOA
);
371 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOW
);
372 DEBUG_SOCKOPT(WS_SO_RCVBUF
);
373 DEBUG_SOCKOPT(WS_SO_RCVTIMEO
);
374 DEBUG_SOCKOPT(WS_SO_REUSEADDR
);
375 DEBUG_SOCKOPT(WS_SO_SNDBUF
);
376 DEBUG_SOCKOPT(WS_SO_SNDTIMEO
);
377 DEBUG_SOCKOPT(WS_SO_TYPE
);
378 DEBUG_SOCKOPT(WS_SO_UPDATE_CONNECT_CONTEXT
);
382 DEBUG_SOCKLEVEL(WS_NSPROTO_IPX
);
385 DEBUG_SOCKOPT(WS_IPX_PTYPE
);
386 DEBUG_SOCKOPT(WS_IPX_FILTERPTYPE
);
387 DEBUG_SOCKOPT(WS_IPX_DSTYPE
);
388 DEBUG_SOCKOPT(WS_IPX_RECVHDR
);
389 DEBUG_SOCKOPT(WS_IPX_MAXSIZE
);
390 DEBUG_SOCKOPT(WS_IPX_ADDRESS
);
391 DEBUG_SOCKOPT(WS_IPX_MAX_ADAPTER_NUM
);
395 DEBUG_SOCKLEVEL(WS_SOL_IRLMP
);
398 DEBUG_SOCKOPT(WS_IRLMP_ENUMDEVICES
);
402 DEBUG_SOCKLEVEL(WS_IPPROTO_TCP
);
405 DEBUG_SOCKOPT(WS_TCP_BSDURGENT
);
406 DEBUG_SOCKOPT(WS_TCP_EXPEDITED_1122
);
407 DEBUG_SOCKOPT(WS_TCP_NODELAY
);
411 DEBUG_SOCKLEVEL(WS_IPPROTO_IP
);
414 DEBUG_SOCKOPT(WS_IP_ADD_MEMBERSHIP
);
415 DEBUG_SOCKOPT(WS_IP_DONTFRAGMENT
);
416 DEBUG_SOCKOPT(WS_IP_DROP_MEMBERSHIP
);
417 DEBUG_SOCKOPT(WS_IP_HDRINCL
);
418 DEBUG_SOCKOPT(WS_IP_MULTICAST_IF
);
419 DEBUG_SOCKOPT(WS_IP_MULTICAST_LOOP
);
420 DEBUG_SOCKOPT(WS_IP_MULTICAST_TTL
);
421 DEBUG_SOCKOPT(WS_IP_OPTIONS
);
422 DEBUG_SOCKOPT(WS_IP_PKTINFO
);
423 DEBUG_SOCKOPT(WS_IP_RECEIVE_BROADCAST
);
424 DEBUG_SOCKOPT(WS_IP_TOS
);
425 DEBUG_SOCKOPT(WS_IP_TTL
);
426 DEBUG_SOCKOPT(WS_IP_UNICAST_IF
);
430 DEBUG_SOCKLEVEL(WS_IPPROTO_IPV6
);
433 DEBUG_SOCKOPT(WS_IPV6_ADD_MEMBERSHIP
);
434 DEBUG_SOCKOPT(WS_IPV6_DROP_MEMBERSHIP
);
435 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_IF
);
436 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_HOPS
);
437 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_LOOP
);
438 DEBUG_SOCKOPT(WS_IPV6_UNICAST_HOPS
);
439 DEBUG_SOCKOPT(WS_IPV6_V6ONLY
);
440 DEBUG_SOCKOPT(WS_IPV6_UNICAST_IF
);
441 DEBUG_SOCKOPT(WS_IPV6_DONTFRAG
);
445 #undef DEBUG_SOCKLEVEL
449 strlevel
= wine_dbg_sprintf("WS_0x%x", level
);
451 stropt
= wine_dbg_sprintf("WS_0x%x", optname
);
453 return wine_dbg_sprintf("level %s, name %s", strlevel
+ 3, stropt
+ 3);
456 static inline const char *debugstr_optval(const char *optval
, int optlenval
)
458 if (optval
&& !IS_INTRESOURCE(optval
) && optlenval
>= 1 && optlenval
<= sizeof(DWORD
))
461 memcpy(&value
, optval
, optlenval
);
462 return wine_dbg_sprintf("%p (%u)", optval
, value
);
464 return wine_dbg_sprintf("%p", optval
);
467 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
468 #define SOCKET2HANDLE(s) ((HANDLE)(s))
469 #define HANDLE2SOCKET(h) ((SOCKET)(h))
471 /****************************************************************
472 * Async IO declarations
473 ****************************************************************/
475 typedef NTSTATUS
async_callback_t( void *user
, IO_STATUS_BLOCK
*io
, NTSTATUS status
);
479 async_callback_t
*callback
; /* must be the first field */
480 struct ws2_async_io
*next
;
483 struct ws2_async_shutdown
485 struct ws2_async_io io
;
487 IO_STATUS_BLOCK iosb
;
493 struct ws2_async_io io
;
495 LPWSAOVERLAPPED user_overlapped
;
496 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func
;
497 IO_STATUS_BLOCK local_iosb
;
498 struct WS_sockaddr
*addr
;
501 int val
; /* for send operations */
502 int *ptr
; /* for recv operations */
507 unsigned int n_iovecs
;
508 unsigned int first_iovec
;
509 struct iovec iovec
[1];
512 struct ws2_accept_async
514 struct ws2_async_io io
;
515 HANDLE listen_socket
;
516 HANDLE accept_socket
;
517 LPOVERLAPPED user_overlapped
;
519 PVOID buf
; /* buffer to write data to */
523 struct ws2_async
*read
;
526 struct ws2_transmitfile_async
528 struct ws2_async_io io
;
533 DWORD bytes_per_send
;
534 TRANSMIT_FILE_BUFFERS buffers
;
536 LARGE_INTEGER offset
;
537 struct ws2_async write
;
540 static struct ws2_async_io
*async_io_freelist
;
542 static void release_async_io( struct ws2_async_io
*io
)
546 struct ws2_async_io
*next
= async_io_freelist
;
548 if (InterlockedCompareExchangePointer( (void **)&async_io_freelist
, io
, next
) == next
) return;
552 static struct ws2_async_io
*alloc_async_io( DWORD size
, async_callback_t callback
)
554 /* first free remaining previous fileinfos */
556 struct ws2_async_io
*io
= InterlockedExchangePointer( (void **)&async_io_freelist
, NULL
);
560 struct ws2_async_io
*next
= io
->next
;
561 HeapFree( GetProcessHeap(), 0, io
);
565 io
= HeapAlloc( GetProcessHeap(), 0, size
);
566 if (io
) io
->callback
= callback
;
570 static NTSTATUS
register_async( int type
, HANDLE handle
, struct ws2_async_io
*async
, HANDLE event
,
571 PIO_APC_ROUTINE apc
, void *apc_context
, IO_STATUS_BLOCK
*io
)
575 SERVER_START_REQ( register_async
)
578 req
->async
.handle
= wine_server_obj_handle( handle
);
579 req
->async
.user
= wine_server_client_ptr( async
);
580 req
->async
.iosb
= wine_server_client_ptr( io
);
581 req
->async
.event
= wine_server_obj_handle( event
);
582 req
->async
.apc
= wine_server_client_ptr( apc
);
583 req
->async
.apc_context
= wine_server_client_ptr( apc_context
);
584 status
= wine_server_call( req
);
591 /****************************************************************/
593 /* ----------------------------------- internal data */
595 /* ws_... struct conversion flags */
597 typedef struct /* WSAAsyncSelect() control struct */
599 HANDLE service
, event
, sock
;
605 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
606 #define WS_MAX_UDP_DATAGRAM 1024
607 static INT WINAPI
WSA_DefaultBlockingHook( FARPROC x
);
609 /* hostent's, servent's and protent's are stored in one buffer per thread,
610 * as documented on MSDN for the functions that return any of the buffers */
611 struct per_thread_data
614 struct WS_hostent
*he_buffer
;
615 struct WS_servent
*se_buffer
;
616 struct WS_protoent
*pe_buffer
;
617 struct pollfd
*fd_cache
;
618 unsigned int fd_count
;
622 char ntoa_buffer
[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
625 /* internal: routing description information */
629 DWORD metric
, default_route
;
632 static INT num_startup
; /* reference counter */
633 static FARPROC blocking_hook
= (FARPROC
)WSA_DefaultBlockingHook
;
635 /* function prototypes */
636 static struct WS_hostent
*WS_create_he(char *name
, int aliases
, int aliases_size
, int addresses
, int address_length
);
637 static struct WS_hostent
*WS_dup_he(const struct hostent
* p_he
);
638 static struct WS_protoent
*WS_dup_pe(const struct protoent
* p_pe
);
639 static struct WS_servent
*WS_dup_se(const struct servent
* p_se
);
640 static int ws_protocol_info(SOCKET s
, int unicode
, WSAPROTOCOL_INFOW
*buffer
, int *size
);
642 int WSAIOCTL_GetInterfaceCount(void);
643 int WSAIOCTL_GetInterfaceName(int intNumber
, char *intName
);
645 static void WS_AddCompletion( SOCKET sock
, ULONG_PTR CompletionValue
, NTSTATUS CompletionStatus
, ULONG Information
);
647 #define MAP_OPTION(opt) { WS_##opt, opt }
649 static const int ws_flags_map
[][2] =
651 MAP_OPTION( MSG_OOB
),
652 MAP_OPTION( MSG_PEEK
),
653 MAP_OPTION( MSG_DONTROUTE
),
654 MAP_OPTION( MSG_WAITALL
),
655 { WS_MSG_PARTIAL
, 0 },
658 static const int ws_sock_map
[][2] =
660 MAP_OPTION( SO_DEBUG
),
661 MAP_OPTION( SO_ACCEPTCONN
),
662 MAP_OPTION( SO_REUSEADDR
),
663 MAP_OPTION( SO_KEEPALIVE
),
664 MAP_OPTION( SO_DONTROUTE
),
665 MAP_OPTION( SO_BROADCAST
),
666 MAP_OPTION( SO_LINGER
),
667 MAP_OPTION( SO_OOBINLINE
),
668 MAP_OPTION( SO_SNDBUF
),
669 MAP_OPTION( SO_RCVBUF
),
670 MAP_OPTION( SO_ERROR
),
671 MAP_OPTION( SO_TYPE
),
673 MAP_OPTION( SO_RCVTIMEO
),
676 MAP_OPTION( SO_SNDTIMEO
),
680 static const int ws_tcp_map
[][2] =
683 MAP_OPTION( TCP_NODELAY
),
687 static const int ws_ip_map
[][2] =
689 MAP_OPTION( IP_MULTICAST_IF
),
690 MAP_OPTION( IP_MULTICAST_TTL
),
691 MAP_OPTION( IP_MULTICAST_LOOP
),
692 MAP_OPTION( IP_ADD_MEMBERSHIP
),
693 MAP_OPTION( IP_DROP_MEMBERSHIP
),
694 MAP_OPTION( IP_OPTIONS
),
696 MAP_OPTION( IP_HDRINCL
),
698 MAP_OPTION( IP_TOS
),
699 MAP_OPTION( IP_TTL
),
701 MAP_OPTION( IP_PKTINFO
),
704 MAP_OPTION( IP_UNICAST_IF
),
708 static const int ws_ipv6_map
[][2] =
710 #ifdef IPV6_ADD_MEMBERSHIP
711 MAP_OPTION( IPV6_ADD_MEMBERSHIP
),
713 #ifdef IPV6_DROP_MEMBERSHIP
714 MAP_OPTION( IPV6_DROP_MEMBERSHIP
),
716 MAP_OPTION( IPV6_MULTICAST_IF
),
717 MAP_OPTION( IPV6_MULTICAST_HOPS
),
718 MAP_OPTION( IPV6_MULTICAST_LOOP
),
719 MAP_OPTION( IPV6_UNICAST_HOPS
),
720 MAP_OPTION( IPV6_V6ONLY
),
721 #ifdef IPV6_UNICAST_IF
722 MAP_OPTION( IPV6_UNICAST_IF
),
726 static const int ws_af_map
[][2] =
728 MAP_OPTION( AF_UNSPEC
),
729 MAP_OPTION( AF_INET
),
730 MAP_OPTION( AF_INET6
),
732 MAP_OPTION( AF_IPX
),
735 MAP_OPTION( AF_IRDA
),
737 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
740 static const int ws_socktype_map
[][2] =
742 MAP_OPTION( SOCK_DGRAM
),
743 MAP_OPTION( SOCK_STREAM
),
744 MAP_OPTION( SOCK_RAW
),
745 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
748 static const int ws_proto_map
[][2] =
750 MAP_OPTION( IPPROTO_IP
),
751 MAP_OPTION( IPPROTO_TCP
),
752 MAP_OPTION( IPPROTO_UDP
),
753 MAP_OPTION( IPPROTO_IPV6
),
754 MAP_OPTION( IPPROTO_ICMP
),
755 MAP_OPTION( IPPROTO_IGMP
),
756 MAP_OPTION( IPPROTO_RAW
),
757 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
760 static const int ws_aiflag_map
[][2] =
762 MAP_OPTION( AI_PASSIVE
),
763 MAP_OPTION( AI_CANONNAME
),
764 MAP_OPTION( AI_NUMERICHOST
),
765 #ifdef AI_NUMERICSERV
766 MAP_OPTION( AI_NUMERICSERV
),
769 MAP_OPTION( AI_V4MAPPED
),
771 MAP_OPTION( AI_ADDRCONFIG
),
774 static const int ws_niflag_map
[][2] =
776 MAP_OPTION( NI_NOFQDN
),
777 MAP_OPTION( NI_NUMERICHOST
),
778 MAP_OPTION( NI_NAMEREQD
),
779 MAP_OPTION( NI_NUMERICSERV
),
780 MAP_OPTION( NI_DGRAM
),
783 static const int ws_eai_map
[][2] =
785 MAP_OPTION( EAI_AGAIN
),
786 MAP_OPTION( EAI_BADFLAGS
),
787 MAP_OPTION( EAI_FAIL
),
788 MAP_OPTION( EAI_FAMILY
),
789 MAP_OPTION( EAI_MEMORY
),
790 /* Note: EAI_NODATA is deprecated, but still
791 * used by Windows and Linux... We map the newer
792 * EAI_NONAME to EAI_NODATA for now until Windows
796 MAP_OPTION( EAI_NODATA
),
799 { WS_EAI_NODATA
, EAI_NONAME
},
802 MAP_OPTION( EAI_SERVICE
),
803 MAP_OPTION( EAI_SOCKTYPE
),
807 static const int ws_poll_map
[][2] =
809 MAP_OPTION( POLLERR
),
810 MAP_OPTION( POLLHUP
),
811 MAP_OPTION( POLLNVAL
),
812 MAP_OPTION( POLLWRNORM
),
813 MAP_OPTION( POLLWRBAND
),
814 MAP_OPTION( POLLRDNORM
),
815 { WS_POLLRDBAND
, POLLPRI
}
818 static const char magic_loopback_addr
[] = {127, 12, 34, 56};
820 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
822 static inline WSACMSGHDR
*fill_control_message(int level
, int type
, WSACMSGHDR
*current
, ULONG
*maxsize
, void *data
, int len
)
824 ULONG msgsize
= sizeof(WSACMSGHDR
) + WSA_CMSG_ALIGN(len
);
825 char *ptr
= (char *) current
+ sizeof(WSACMSGHDR
);
827 /* Make sure there is at least enough room for this entry */
828 if (msgsize
> *maxsize
)
831 /* Fill in the entry */
832 current
->cmsg_len
= sizeof(WSACMSGHDR
) + len
;
833 current
->cmsg_level
= level
;
834 current
->cmsg_type
= type
;
835 memcpy(ptr
, data
, len
);
836 /* Return the pointer to where next entry should go */
837 return (WSACMSGHDR
*) (ptr
+ WSA_CMSG_ALIGN(len
));
839 #endif /* IP_PKTINFO */
841 static inline int convert_control_headers(struct msghdr
*hdr
, WSABUF
*control
)
844 WSACMSGHDR
*cmsg_win
= (WSACMSGHDR
*) control
->buf
, *ptr
;
845 ULONG ctlsize
= control
->len
;
846 struct cmsghdr
*cmsg_unix
;
849 /* Loop over all the headers, converting as appropriate */
850 for (cmsg_unix
= CMSG_FIRSTHDR(hdr
); cmsg_unix
!= NULL
; cmsg_unix
= CMSG_NXTHDR(hdr
, cmsg_unix
))
852 switch(cmsg_unix
->cmsg_level
)
855 switch(cmsg_unix
->cmsg_type
)
859 /* Convert the Unix IP_PKTINFO structure to the Windows version */
860 struct in_pktinfo
*data_unix
= (struct in_pktinfo
*) CMSG_DATA(cmsg_unix
);
861 struct WS_in_pktinfo data_win
;
863 memcpy(&data_win
.ipi_addr
,&data_unix
->ipi_addr
.s_addr
,4); /* 4 bytes = 32 address bits */
864 data_win
.ipi_ifindex
= data_unix
->ipi_ifindex
;
865 ptr
= fill_control_message(WS_IPPROTO_IP
, WS_IP_PKTINFO
, ptr
, &ctlsize
,
866 (void*)&data_win
, sizeof(data_win
));
867 if (!ptr
) goto error
;
870 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix
->cmsg_type
);
875 FIXME("Unhandled message header level %d\n", cmsg_unix
->cmsg_level
);
881 /* Set the length of the returned control headers */
882 control
->len
= (ptr
== NULL
? 0 : (char*)ptr
- (char*)cmsg_win
);
883 return (ptr
!= NULL
);
884 #else /* IP_PKTINFO */
887 #endif /* IP_PKTINFO */
889 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
891 /* ----------------------------------- error handling */
893 static NTSTATUS
sock_get_ntstatus( int err
)
897 case EBADF
: return STATUS_INVALID_HANDLE
;
898 case EBUSY
: return STATUS_DEVICE_BUSY
;
900 case EACCES
: return STATUS_ACCESS_DENIED
;
901 case EFAULT
: return STATUS_NO_MEMORY
;
902 case EINVAL
: return STATUS_INVALID_PARAMETER
;
904 case EMFILE
: return STATUS_TOO_MANY_OPENED_FILES
;
905 case EWOULDBLOCK
: return STATUS_CANT_WAIT
;
906 case EINPROGRESS
: return STATUS_PENDING
;
907 case EALREADY
: return STATUS_NETWORK_BUSY
;
908 case ENOTSOCK
: return STATUS_OBJECT_TYPE_MISMATCH
;
909 case EDESTADDRREQ
: return STATUS_INVALID_PARAMETER
;
910 case EMSGSIZE
: return STATUS_BUFFER_OVERFLOW
;
911 case EPROTONOSUPPORT
:
912 case ESOCKTNOSUPPORT
:
915 case EPROTOTYPE
: return STATUS_NOT_SUPPORTED
;
916 case ENOPROTOOPT
: return STATUS_INVALID_PARAMETER
;
917 case EOPNOTSUPP
: return STATUS_NOT_SUPPORTED
;
918 case EADDRINUSE
: return STATUS_ADDRESS_ALREADY_ASSOCIATED
;
919 case EADDRNOTAVAIL
: return STATUS_INVALID_PARAMETER
;
920 case ECONNREFUSED
: return STATUS_CONNECTION_REFUSED
;
921 case ESHUTDOWN
: return STATUS_PIPE_DISCONNECTED
;
922 case ENOTCONN
: return STATUS_CONNECTION_DISCONNECTED
;
923 case ETIMEDOUT
: return STATUS_IO_TIMEOUT
;
924 case ENETUNREACH
: return STATUS_NETWORK_UNREACHABLE
;
925 case ENETDOWN
: return STATUS_NETWORK_BUSY
;
927 case ECONNRESET
: return STATUS_CONNECTION_RESET
;
928 case ECONNABORTED
: return STATUS_CONNECTION_ABORTED
;
930 case 0: return STATUS_SUCCESS
;
932 WARN("Unknown errno %d!\n", err
);
933 return STATUS_UNSUCCESSFUL
;
937 static UINT
sock_get_error( int err
)
941 case EINTR
: return WSAEINTR
;
943 case EACCES
: return WSAEACCES
;
944 case EFAULT
: return WSAEFAULT
;
945 case EINVAL
: return WSAEINVAL
;
946 case EMFILE
: return WSAEMFILE
;
947 case EWOULDBLOCK
: return WSAEWOULDBLOCK
;
948 case EINPROGRESS
: return WSAEINPROGRESS
;
949 case EALREADY
: return WSAEALREADY
;
951 case ENOTSOCK
: return WSAENOTSOCK
;
952 case EDESTADDRREQ
: return WSAEDESTADDRREQ
;
953 case EMSGSIZE
: return WSAEMSGSIZE
;
954 case EPROTOTYPE
: return WSAEPROTOTYPE
;
955 case ENOPROTOOPT
: return WSAENOPROTOOPT
;
956 case EPROTONOSUPPORT
: return WSAEPROTONOSUPPORT
;
957 case ESOCKTNOSUPPORT
: return WSAESOCKTNOSUPPORT
;
958 case EOPNOTSUPP
: return WSAEOPNOTSUPP
;
959 case EPFNOSUPPORT
: return WSAEPFNOSUPPORT
;
960 case EAFNOSUPPORT
: return WSAEAFNOSUPPORT
;
961 case EADDRINUSE
: return WSAEADDRINUSE
;
962 case EADDRNOTAVAIL
: return WSAEADDRNOTAVAIL
;
963 case ENETDOWN
: return WSAENETDOWN
;
964 case ENETUNREACH
: return WSAENETUNREACH
;
965 case ENETRESET
: return WSAENETRESET
;
966 case ECONNABORTED
: return WSAECONNABORTED
;
968 case ECONNRESET
: return WSAECONNRESET
;
969 case ENOBUFS
: return WSAENOBUFS
;
970 case EISCONN
: return WSAEISCONN
;
971 case ENOTCONN
: return WSAENOTCONN
;
972 case ESHUTDOWN
: return WSAESHUTDOWN
;
973 case ETOOMANYREFS
: return WSAETOOMANYREFS
;
974 case ETIMEDOUT
: return WSAETIMEDOUT
;
975 case ECONNREFUSED
: return WSAECONNREFUSED
;
976 case ELOOP
: return WSAELOOP
;
977 case ENAMETOOLONG
: return WSAENAMETOOLONG
;
978 case EHOSTDOWN
: return WSAEHOSTDOWN
;
979 case EHOSTUNREACH
: return WSAEHOSTUNREACH
;
980 case ENOTEMPTY
: return WSAENOTEMPTY
;
982 case EPROCLIM
: return WSAEPROCLIM
;
985 case EUSERS
: return WSAEUSERS
;
988 case EDQUOT
: return WSAEDQUOT
;
991 case ESTALE
: return WSAESTALE
;
994 case EREMOTE
: return WSAEREMOTE
;
997 /* just in case we ever get here and there are no problems */
1000 WARN("Unknown errno %d!\n", err
);
1001 return WSAEOPNOTSUPP
;
1005 static UINT
wsaErrno(void)
1007 int loc_errno
= errno
;
1008 WARN("errno %d, (%s).\n", loc_errno
, strerror(loc_errno
));
1010 return sock_get_error( loc_errno
);
1013 /* most ws2 overlapped functions return an ntstatus-based error code */
1014 static NTSTATUS
wsaErrStatus(void)
1016 int loc_errno
= errno
;
1017 WARN("errno %d, (%s).\n", loc_errno
, strerror(loc_errno
));
1019 return sock_get_ntstatus(loc_errno
);
1022 static UINT
wsaHerrno(int loc_errno
)
1024 WARN("h_errno %d.\n", loc_errno
);
1028 case HOST_NOT_FOUND
: return WSAHOST_NOT_FOUND
;
1029 case TRY_AGAIN
: return WSATRY_AGAIN
;
1030 case NO_RECOVERY
: return WSANO_RECOVERY
;
1031 case NO_DATA
: return WSANO_DATA
;
1032 case ENOBUFS
: return WSAENOBUFS
;
1036 WARN("Unknown h_errno %d!\n", loc_errno
);
1037 return WSAEOPNOTSUPP
;
1041 static inline DWORD
NtStatusToWSAError( const DWORD status
)
1043 /* We only need to cover the status codes set by server async request handling */
1047 case STATUS_SUCCESS
: wserr
= 0; break;
1048 case STATUS_PENDING
: wserr
= WSA_IO_PENDING
; break;
1049 case STATUS_OBJECT_TYPE_MISMATCH
: wserr
= WSAENOTSOCK
; break;
1050 case STATUS_INVALID_HANDLE
: wserr
= WSAEBADF
; break;
1051 case STATUS_INVALID_PARAMETER
: wserr
= WSAEINVAL
; break;
1052 case STATUS_PIPE_DISCONNECTED
: wserr
= WSAESHUTDOWN
; break;
1053 case STATUS_NETWORK_BUSY
: wserr
= WSAEALREADY
; break;
1054 case STATUS_NETWORK_UNREACHABLE
: wserr
= WSAENETUNREACH
; break;
1055 case STATUS_CONNECTION_REFUSED
: wserr
= WSAECONNREFUSED
; break;
1056 case STATUS_CONNECTION_DISCONNECTED
: wserr
= WSAENOTCONN
; break;
1057 case STATUS_CONNECTION_RESET
: wserr
= WSAECONNRESET
; break;
1058 case STATUS_CONNECTION_ABORTED
: wserr
= WSAECONNABORTED
; break;
1059 case STATUS_CANCELLED
: wserr
= WSA_OPERATION_ABORTED
; break;
1060 case STATUS_ADDRESS_ALREADY_ASSOCIATED
: wserr
= WSAEADDRINUSE
; break;
1061 case STATUS_IO_TIMEOUT
:
1062 case STATUS_TIMEOUT
: wserr
= WSAETIMEDOUT
; break;
1063 case STATUS_NO_MEMORY
: wserr
= WSAEFAULT
; break;
1064 case STATUS_ACCESS_DENIED
: wserr
= WSAEACCES
; break;
1065 case STATUS_TOO_MANY_OPENED_FILES
: wserr
= WSAEMFILE
; break;
1066 case STATUS_CANT_WAIT
: wserr
= WSAEWOULDBLOCK
; break;
1067 case STATUS_BUFFER_OVERFLOW
: wserr
= WSAEMSGSIZE
; break;
1068 case STATUS_NOT_SUPPORTED
: wserr
= WSAEOPNOTSUPP
; break;
1069 case STATUS_HOST_UNREACHABLE
: wserr
= WSAEHOSTUNREACH
; break;
1072 wserr
= RtlNtStatusToDosError( status
);
1073 FIXME( "Status code %08x converted to DOS error code %x\n", status
, wserr
);
1078 /* set last error code from NT status without mapping WSA errors */
1079 static inline unsigned int set_error( unsigned int err
)
1083 err
= NtStatusToWSAError( err
);
1084 SetLastError( err
);
1089 static inline int get_sock_fd( SOCKET s
, DWORD access
, unsigned int *options
)
1092 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s
), access
, &fd
, options
) ))
1097 static inline void release_sock_fd( SOCKET s
, int fd
)
1099 wine_server_release_fd( SOCKET2HANDLE(s
), fd
);
1102 static void _enable_event( HANDLE s
, unsigned int event
,
1103 unsigned int sstate
, unsigned int cstate
)
1105 SERVER_START_REQ( enable_socket_event
)
1107 req
->handle
= wine_server_obj_handle( s
);
1109 req
->sstate
= sstate
;
1110 req
->cstate
= cstate
;
1111 wine_server_call( req
);
1116 static NTSTATUS
_is_blocking(SOCKET s
, BOOL
*ret
)
1119 SERVER_START_REQ( get_socket_event
)
1121 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1122 req
->service
= FALSE
;
1124 status
= wine_server_call( req
);
1125 *ret
= (reply
->state
& FD_WINE_NONBLOCKING
) == 0;
1131 static unsigned int _get_sock_mask(SOCKET s
)
1134 SERVER_START_REQ( get_socket_event
)
1136 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1137 req
->service
= FALSE
;
1139 wine_server_call( req
);
1146 static void _sync_sock_state(SOCKET s
)
1149 /* do a dummy wineserver request in order to let
1150 the wineserver run through its select loop once */
1151 (void)_is_blocking(s
, &dummy
);
1154 static void _get_sock_errors(SOCKET s
, int *events
)
1156 SERVER_START_REQ( get_socket_event
)
1158 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1159 req
->service
= FALSE
;
1161 wine_server_set_reply( req
, events
, sizeof(int) * FD_MAX_EVENTS
);
1162 wine_server_call( req
);
1167 static int _get_sock_error(SOCKET s
, unsigned int bit
)
1169 int events
[FD_MAX_EVENTS
];
1170 _get_sock_errors(s
, events
);
1174 static int _get_fd_type(int fd
)
1177 socklen_t optlen
= sizeof(sock_type
);
1178 getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char*) &sock_type
, &optlen
);
1182 static BOOL
set_dont_fragment(SOCKET s
, int level
, BOOL value
)
1186 if (level
== IPPROTO_IP
)
1189 optname
= IP_DONTFRAG
;
1190 #elif defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO) && defined(IP_PMTUDISC_DONT)
1191 optname
= IP_MTU_DISCOVER
;
1192 value
= value
? IP_PMTUDISC_DO
: IP_PMTUDISC_DONT
;
1196 FIXME("IP_DONTFRAGMENT for IPv4 not supported in this platform\n");
1197 return TRUE
; /* fake success */
1202 #ifdef IPV6_DONTFRAG
1203 optname
= IPV6_DONTFRAG
;
1204 #elif defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO) && defined(IPV6_PMTUDISC_DONT)
1205 optname
= IPV6_MTU_DISCOVER
;
1206 value
= value
? IPV6_PMTUDISC_DO
: IPV6_PMTUDISC_DONT
;
1210 FIXME("IP_DONTFRAGMENT for IPv6 not supported in this platform\n");
1211 return TRUE
; /* fake success */
1215 fd
= get_sock_fd(s
, 0, NULL
);
1216 if (fd
== -1) return FALSE
;
1218 if (!setsockopt(fd
, level
, optname
, &value
, sizeof(value
)))
1222 WSASetLastError(wsaErrno());
1226 release_sock_fd(s
, fd
);
1230 static BOOL
get_dont_fragment(SOCKET s
, int level
, BOOL
*out
)
1232 int fd
, optname
, value
, not_expected
;
1233 socklen_t optlen
= sizeof(value
);
1235 if (level
== IPPROTO_IP
)
1238 optname
= IP_DONTFRAG
;
1240 #elif defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
1241 optname
= IP_MTU_DISCOVER
;
1242 not_expected
= IP_PMTUDISC_DONT
;
1246 FIXME("IP_DONTFRAGMENT for IPv4 not supported in this platform\n");
1247 return TRUE
; /* fake success */
1252 #ifdef IPV6_DONTFRAG
1253 optname
= IPV6_DONTFRAG
;
1255 #elif defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DONT)
1256 optname
= IPV6_MTU_DISCOVER
;
1257 not_expected
= IPV6_PMTUDISC_DONT
;
1261 FIXME("IP_DONTFRAGMENT for IPv6 not supported in this platform\n");
1262 return TRUE
; /* fake success */
1266 fd
= get_sock_fd(s
, 0, NULL
);
1267 if (fd
== -1) return FALSE
;
1269 if (!getsockopt(fd
, level
, optname
, &value
, &optlen
))
1271 *out
= value
!= not_expected
;
1276 WSASetLastError(wsaErrno());
1280 release_sock_fd(s
, fd
);
1284 static struct per_thread_data
*get_per_thread_data(void)
1286 struct per_thread_data
* ptb
= NtCurrentTeb()->WinSockData
;
1287 /* lazy initialization */
1290 ptb
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(*ptb
) );
1291 NtCurrentTeb()->WinSockData
= ptb
;
1296 static void free_per_thread_data(void)
1298 struct per_thread_data
* ptb
= NtCurrentTeb()->WinSockData
;
1302 /* delete scratch buffers */
1303 HeapFree( GetProcessHeap(), 0, ptb
->he_buffer
);
1304 HeapFree( GetProcessHeap(), 0, ptb
->se_buffer
);
1305 HeapFree( GetProcessHeap(), 0, ptb
->pe_buffer
);
1306 HeapFree( GetProcessHeap(), 0, ptb
->fd_cache
);
1308 HeapFree( GetProcessHeap(), 0, ptb
);
1309 NtCurrentTeb()->WinSockData
= NULL
;
1312 /***********************************************************************
1313 * DllMain (WS2_32.init)
1315 BOOL WINAPI
DllMain(HINSTANCE hInstDLL
, DWORD fdwReason
, LPVOID fImpLoad
)
1317 TRACE("%p 0x%x %p\n", hInstDLL
, fdwReason
, fImpLoad
);
1318 switch (fdwReason
) {
1319 case DLL_PROCESS_ATTACH
:
1321 case DLL_PROCESS_DETACH
:
1322 if (fImpLoad
) break;
1323 free_per_thread_data();
1324 DeleteCriticalSection(&csWSgetXXXbyYYY
);
1326 case DLL_THREAD_DETACH
:
1327 free_per_thread_data();
1333 /***********************************************************************
1336 * Converts send/recv flags from Windows format.
1337 * Return the converted flag bits, unsupported flags remain unchanged.
1339 static int convert_flags(int flags
)
1342 if (!flags
) return 0;
1344 for (out
= i
= 0; flags
&& i
< sizeof(ws_flags_map
) / sizeof(ws_flags_map
[0]); i
++)
1346 if (ws_flags_map
[i
][0] & flags
)
1348 out
|= ws_flags_map
[i
][1];
1349 flags
&= ~ws_flags_map
[i
][0];
1354 FIXME("Unknown send/recv flags 0x%x, using anyway...\n", flags
);
1360 /***********************************************************************
1363 * Converts socket flags from Windows format.
1364 * Return 1 if converted, 0 if not (error).
1366 static int convert_sockopt(INT
*level
, INT
*optname
)
1372 *level
= SOL_SOCKET
;
1373 for(i
=0; i
<sizeof(ws_sock_map
)/sizeof(ws_sock_map
[0]); i
++) {
1374 if( ws_sock_map
[i
][0] == *optname
)
1376 *optname
= ws_sock_map
[i
][1];
1380 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname
);
1382 case WS_IPPROTO_TCP
:
1383 *level
= IPPROTO_TCP
;
1384 for(i
=0; i
<sizeof(ws_tcp_map
)/sizeof(ws_tcp_map
[0]); i
++) {
1385 if ( ws_tcp_map
[i
][0] == *optname
)
1387 *optname
= ws_tcp_map
[i
][1];
1391 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname
);
1394 *level
= IPPROTO_IP
;
1395 for(i
=0; i
<sizeof(ws_ip_map
)/sizeof(ws_ip_map
[0]); i
++) {
1396 if (ws_ip_map
[i
][0] == *optname
)
1398 *optname
= ws_ip_map
[i
][1];
1402 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname
);
1404 case WS_IPPROTO_IPV6
:
1405 *level
= IPPROTO_IPV6
;
1406 for(i
=0; i
<sizeof(ws_ipv6_map
)/sizeof(ws_ipv6_map
[0]); i
++) {
1407 if (ws_ipv6_map
[i
][0] == *optname
)
1409 *optname
= ws_ipv6_map
[i
][1];
1413 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname
);
1415 default: FIXME("Unimplemented or unknown socket level\n");
1420 /* ----------------------------------- Per-thread info (or per-process?) */
1422 static char *strdup_lower(const char *str
)
1425 char *ret
= HeapAlloc( GetProcessHeap(), 0, strlen(str
) + 1 );
1429 for (i
= 0; str
[i
]; i
++) ret
[i
] = tolower(str
[i
]);
1432 else SetLastError(WSAENOBUFS
);
1436 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1437 * from an fd and return the value converted to milli seconds
1438 * or 0 if there is an infinite time out */
1439 static inline INT64
get_rcvsnd_timeo( int fd
, BOOL is_recv
)
1442 socklen_t len
= sizeof(tv
);
1447 optname
= SO_RCVTIMEO
;
1453 optname
= SO_SNDTIMEO
;
1458 res
= getsockopt(fd
, SOL_SOCKET
, optname
, &tv
, &len
);
1461 return (UINT64
)tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000;
1464 /* utility: given an fd, will block until one of the events occurs */
1465 static inline int do_block( int fd
, int events
, int timeout
)
1471 pfd
.events
= events
;
1473 while ((ret
= poll(&pfd
, 1, timeout
)) < 0)
1484 convert_af_w2u(int windowsaf
) {
1487 for (i
=0;i
<sizeof(ws_af_map
)/sizeof(ws_af_map
[0]);i
++)
1488 if (ws_af_map
[i
][0] == windowsaf
)
1489 return ws_af_map
[i
][1];
1490 FIXME("unhandled Windows address family %d\n", windowsaf
);
1495 convert_af_u2w(int unixaf
) {
1498 for (i
=0;i
<sizeof(ws_af_map
)/sizeof(ws_af_map
[0]);i
++)
1499 if (ws_af_map
[i
][1] == unixaf
)
1500 return ws_af_map
[i
][0];
1501 FIXME("unhandled UNIX address family %d\n", unixaf
);
1506 convert_proto_w2u(int windowsproto
) {
1509 for (i
=0;i
<sizeof(ws_proto_map
)/sizeof(ws_proto_map
[0]);i
++)
1510 if (ws_proto_map
[i
][0] == windowsproto
)
1511 return ws_proto_map
[i
][1];
1513 /* check for extended IPX */
1514 if (IS_IPX_PROTO(windowsproto
))
1515 return windowsproto
;
1517 FIXME("unhandled Windows socket protocol %d\n", windowsproto
);
1522 convert_proto_u2w(int unixproto
) {
1525 for (i
=0;i
<sizeof(ws_proto_map
)/sizeof(ws_proto_map
[0]);i
++)
1526 if (ws_proto_map
[i
][1] == unixproto
)
1527 return ws_proto_map
[i
][0];
1529 /* if value is inside IPX range just return it - the kernel simply
1530 * echoes the value used in the socket() function */
1531 if (IS_IPX_PROTO(unixproto
))
1534 FIXME("unhandled UNIX socket protocol %d\n", unixproto
);
1539 convert_socktype_w2u(int windowssocktype
) {
1542 for (i
=0;i
<sizeof(ws_socktype_map
)/sizeof(ws_socktype_map
[0]);i
++)
1543 if (ws_socktype_map
[i
][0] == windowssocktype
)
1544 return ws_socktype_map
[i
][1];
1545 FIXME("unhandled Windows socket type %d\n", windowssocktype
);
1550 convert_socktype_u2w(int unixsocktype
) {
1553 for (i
=0;i
<sizeof(ws_socktype_map
)/sizeof(ws_socktype_map
[0]);i
++)
1554 if (ws_socktype_map
[i
][1] == unixsocktype
)
1555 return ws_socktype_map
[i
][0];
1556 FIXME("unhandled UNIX socket type %d\n", unixsocktype
);
1560 static int convert_poll_w2u(int events
)
1563 for (i
= ret
= 0; events
&& i
< sizeof(ws_poll_map
) / sizeof(ws_poll_map
[0]); i
++)
1565 if (ws_poll_map
[i
][0] & events
)
1567 ret
|= ws_poll_map
[i
][1];
1568 events
&= ~ws_poll_map
[i
][0];
1573 FIXME("Unsupported WSAPoll() flags 0x%x\n", events
);
1577 static int convert_poll_u2w(int events
)
1580 for (i
= ret
= 0; events
&& i
< sizeof(ws_poll_map
) / sizeof(ws_poll_map
[0]); i
++)
1582 if (ws_poll_map
[i
][1] & events
)
1584 ret
|= ws_poll_map
[i
][0];
1585 events
&= ~ws_poll_map
[i
][1];
1590 FIXME("Unsupported poll() flags 0x%x\n", events
);
1594 static int set_ipx_packettype(int sock
, int ptype
)
1597 int fd
= get_sock_fd( sock
, 0, NULL
), ret
= 0;
1598 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype
, fd
);
1600 if (fd
== -1) return SOCKET_ERROR
;
1602 /* We try to set the ipx type on ipx socket level. */
1604 if(setsockopt(fd
, SOL_IPX
, IPX_TYPE
, &ptype
, sizeof(ptype
)) == -1)
1606 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1612 /* Should we retrieve val using a getsockopt call and then
1613 * set the modified one? */
1615 setsockopt(fd
, 0, SO_DEFAULT_HEADERS
, &val
, sizeof(struct ipx
));
1618 release_sock_fd( sock
, fd
);
1621 WARN("IPX support is not enabled, can't set packet type\n");
1622 return SOCKET_ERROR
;
1626 /* ----------------------------------- API -----
1628 * Init / cleanup / error checking.
1631 /***********************************************************************
1632 * WSAStartup (WS2_32.115)
1634 int WINAPI
WSAStartup(WORD wVersionRequested
, LPWSADATA lpWSAData
)
1636 TRACE("verReq=%x\n", wVersionRequested
);
1638 if (LOBYTE(wVersionRequested
) < 1)
1639 return WSAVERNOTSUPPORTED
;
1641 if (!lpWSAData
) return WSAEINVAL
;
1645 /* that's the whole of the negotiation for now */
1646 lpWSAData
->wVersion
= wVersionRequested
;
1647 /* return winsock information */
1648 lpWSAData
->wHighVersion
= 0x0202;
1649 strcpy(lpWSAData
->szDescription
, "WinSock 2.0" );
1650 strcpy(lpWSAData
->szSystemStatus
, "Running" );
1651 lpWSAData
->iMaxSockets
= WS_MAX_SOCKETS_PER_PROCESS
;
1652 lpWSAData
->iMaxUdpDg
= WS_MAX_UDP_DATAGRAM
;
1653 /* don't do anything with lpWSAData->lpVendorInfo */
1654 /* (some apps don't allocate the space for this field) */
1656 TRACE("succeeded starts: %d\n", num_startup
);
1661 /***********************************************************************
1662 * WSACleanup (WS2_32.116)
1664 INT WINAPI
WSACleanup(void)
1668 TRACE("pending cleanups: %d\n", num_startup
);
1671 SetLastError(WSANOTINITIALISED
);
1672 return SOCKET_ERROR
;
1676 /***********************************************************************
1677 * WSAGetLastError (WS2_32.111)
1679 INT WINAPI
WSAGetLastError(void)
1681 return GetLastError();
1684 /***********************************************************************
1685 * WSASetLastError (WS2_32.112)
1687 void WINAPI
WSASetLastError(INT iError
) {
1688 SetLastError(iError
);
1691 static struct WS_hostent
*check_buffer_he(int size
)
1693 struct per_thread_data
* ptb
= get_per_thread_data();
1696 if (ptb
->he_len
>= size
) return ptb
->he_buffer
;
1697 HeapFree( GetProcessHeap(), 0, ptb
->he_buffer
);
1699 ptb
->he_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->he_len
= size
) );
1700 if (!ptb
->he_buffer
) SetLastError(WSAENOBUFS
);
1701 return ptb
->he_buffer
;
1704 static struct WS_servent
*check_buffer_se(int size
)
1706 struct per_thread_data
* ptb
= get_per_thread_data();
1709 if (ptb
->se_len
>= size
) return ptb
->se_buffer
;
1710 HeapFree( GetProcessHeap(), 0, ptb
->se_buffer
);
1712 ptb
->se_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->se_len
= size
) );
1713 if (!ptb
->se_buffer
) SetLastError(WSAENOBUFS
);
1714 return ptb
->se_buffer
;
1717 static struct WS_protoent
*check_buffer_pe(int size
)
1719 struct per_thread_data
* ptb
= get_per_thread_data();
1722 if (ptb
->pe_len
>= size
) return ptb
->pe_buffer
;
1723 HeapFree( GetProcessHeap(), 0, ptb
->pe_buffer
);
1725 ptb
->pe_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->pe_len
= size
) );
1726 if (!ptb
->pe_buffer
) SetLastError(WSAENOBUFS
);
1727 return ptb
->pe_buffer
;
1730 /* ----------------------------------- i/o APIs */
1732 static inline BOOL
supported_pf(int pf
)
1752 static inline BOOL
supported_protocol(int protocol
)
1755 for (i
= 0; i
< sizeof(valid_protocols
) / sizeof(valid_protocols
[0]); i
++)
1756 if (protocol
== valid_protocols
[i
])
1761 /**********************************************************************/
1763 /* Returns the length of the converted address if successful, 0 if it was too
1764 * small to start with or unknown family or invalid address buffer.
1766 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr
* wsaddr
, int wsaddrlen
,
1767 union generic_unix_sockaddr
*uaddr
)
1769 unsigned int uaddrlen
= 0;
1774 switch (wsaddr
->sa_family
)
1779 const struct WS_sockaddr_ipx
* wsipx
=(const struct WS_sockaddr_ipx
*)wsaddr
;
1780 struct sockaddr_ipx
* uipx
= (struct sockaddr_ipx
*)uaddr
;
1782 if (wsaddrlen
<sizeof(struct WS_sockaddr_ipx
))
1785 uaddrlen
= sizeof(struct sockaddr_ipx
);
1786 memset( uaddr
, 0, uaddrlen
);
1787 uipx
->sipx_family
=AF_IPX
;
1788 uipx
->sipx_port
=wsipx
->sa_socket
;
1789 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1792 memcpy(&uipx
->sipx_network
,wsipx
->sa_netnum
,sizeof(uipx
->sipx_network
)+sizeof(uipx
->sipx_node
));
1793 #ifdef IPX_FRAME_NONE
1794 uipx
->sipx_type
=IPX_FRAME_NONE
;
1800 struct sockaddr_in6
* uin6
= (struct sockaddr_in6
*)uaddr
;
1801 const struct WS_sockaddr_in6
* win6
= (const struct WS_sockaddr_in6
*)wsaddr
;
1803 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1804 * scope_id, one without.
1806 if (wsaddrlen
>= sizeof(struct WS_sockaddr_in6_old
)) {
1807 uaddrlen
= sizeof(struct sockaddr_in6
);
1808 memset( uaddr
, 0, uaddrlen
);
1809 uin6
->sin6_family
= AF_INET6
;
1810 uin6
->sin6_port
= win6
->sin6_port
;
1811 uin6
->sin6_flowinfo
= win6
->sin6_flowinfo
;
1812 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1813 if (wsaddrlen
>= sizeof(struct WS_sockaddr_in6
)) uin6
->sin6_scope_id
= win6
->sin6_scope_id
;
1815 memcpy(&uin6
->sin6_addr
,&win6
->sin6_addr
,16); /* 16 bytes = 128 address bits */
1818 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen
);
1822 struct sockaddr_in
* uin
= (struct sockaddr_in
*)uaddr
;
1823 const struct WS_sockaddr_in
* win
= (const struct WS_sockaddr_in
*)wsaddr
;
1825 if (wsaddrlen
<sizeof(struct WS_sockaddr_in
))
1827 uaddrlen
= sizeof(struct sockaddr_in
);
1828 memset( uaddr
, 0, uaddrlen
);
1829 uin
->sin_family
= AF_INET
;
1830 uin
->sin_port
= win
->sin_port
;
1831 memcpy(&uin
->sin_addr
,&win
->sin_addr
,4); /* 4 bytes = 32 address bits */
1836 struct sockaddr_irda
*uin
= (struct sockaddr_irda
*)uaddr
;
1837 const SOCKADDR_IRDA
*win
= (const SOCKADDR_IRDA
*)wsaddr
;
1839 if (wsaddrlen
< sizeof(SOCKADDR_IRDA
))
1841 uaddrlen
= sizeof(struct sockaddr_irda
);
1842 memset( uaddr
, 0, uaddrlen
);
1843 uin
->sir_family
= AF_IRDA
;
1844 if (!strncmp( win
->irdaServiceName
, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1846 unsigned int lsap_sel
= 0;
1848 sscanf( win
->irdaServiceName
, "LSAP-SEL%u", &lsap_sel
);
1849 uin
->sir_lsap_sel
= lsap_sel
;
1853 uin
->sir_lsap_sel
= LSAP_ANY
;
1854 memcpy( uin
->sir_name
, win
->irdaServiceName
, 25 );
1856 memcpy( &uin
->sir_addr
, win
->irdaDeviceID
, sizeof(uin
->sir_addr
) );
1860 case WS_AF_UNSPEC
: {
1861 /* Try to determine the needed space by the passed windows sockaddr space */
1862 switch (wsaddrlen
) {
1863 default: /* likely an ipv4 address */
1864 case sizeof(struct WS_sockaddr_in
):
1865 uaddrlen
= sizeof(struct sockaddr_in
);
1868 case sizeof(struct WS_sockaddr_ipx
):
1869 uaddrlen
= sizeof(struct sockaddr_ipx
);
1873 case sizeof(SOCKADDR_IRDA
):
1874 uaddrlen
= sizeof(struct sockaddr_irda
);
1877 case sizeof(struct WS_sockaddr_in6
):
1878 case sizeof(struct WS_sockaddr_in6_old
):
1879 uaddrlen
= sizeof(struct sockaddr_in6
);
1882 memset( uaddr
, 0, uaddrlen
);
1886 FIXME("Unknown address family %d, return NULL.\n", wsaddr
->sa_family
);
1892 static BOOL
is_sockaddr_bound(const struct sockaddr
*uaddr
, int uaddrlen
)
1894 switch (uaddr
->sa_family
)
1899 static const struct sockaddr_ipx emptyAddr
;
1900 struct sockaddr_ipx
*ipx
= (struct sockaddr_ipx
*) uaddr
;
1901 return ipx
->sipx_port
1902 || memcmp(&ipx
->sipx_network
, &emptyAddr
.sipx_network
, sizeof(emptyAddr
.sipx_network
))
1903 || memcmp(&ipx
->sipx_node
, &emptyAddr
.sipx_node
, sizeof(emptyAddr
.sipx_node
));
1908 static const struct sockaddr_in6 emptyAddr
;
1909 const struct sockaddr_in6
*in6
= (const struct sockaddr_in6
*) uaddr
;
1910 return in6
->sin6_port
|| memcmp(&in6
->sin6_addr
, &emptyAddr
.sin6_addr
, sizeof(struct in6_addr
));
1914 static const struct sockaddr_in emptyAddr
;
1915 const struct sockaddr_in
*in
= (const struct sockaddr_in
*) uaddr
;
1916 return in
->sin_port
|| memcmp(&in
->sin_addr
, &emptyAddr
.sin_addr
, sizeof(struct in_addr
));
1921 FIXME("unknown address family %d\n", uaddr
->sa_family
);
1926 /* Returns -1 if getsockname fails, 0 if not bound, 1 otherwise */
1927 static int is_fd_bound(int fd
, union generic_unix_sockaddr
*uaddr
, socklen_t
*uaddrlen
)
1929 union generic_unix_sockaddr inaddr
;
1933 if (!uaddr
) uaddr
= &inaddr
;
1934 if (!uaddrlen
) uaddrlen
= &inlen
;
1936 *uaddrlen
= sizeof(inaddr
);
1937 res
= getsockname(fd
, &uaddr
->addr
, uaddrlen
);
1938 if (!res
) res
= is_sockaddr_bound(&uaddr
->addr
, *uaddrlen
);
1942 /* Returns 0 if successful, -1 if the buffer is too small */
1943 static int ws_sockaddr_u2ws(const struct sockaddr
* uaddr
, struct WS_sockaddr
* wsaddr
, int* wsaddrlen
)
1947 switch(uaddr
->sa_family
)
1952 const struct sockaddr_ipx
* uipx
=(const struct sockaddr_ipx
*)uaddr
;
1953 struct WS_sockaddr_ipx
* wsipx
=(struct WS_sockaddr_ipx
*)wsaddr
;
1956 switch (*wsaddrlen
) /* how much can we copy? */
1960 *wsaddrlen
= sizeof(*wsipx
);
1961 wsipx
->sa_socket
=uipx
->sipx_port
;
1965 memcpy(wsipx
->sa_nodenum
,uipx
->sipx_node
,sizeof(wsipx
->sa_nodenum
));
1973 memcpy(wsipx
->sa_netnum
,&uipx
->sipx_network
,sizeof(wsipx
->sa_netnum
));
1979 wsipx
->sa_family
=WS_AF_IPX
;
1991 const struct sockaddr_irda
*uin
= (const struct sockaddr_irda
*)uaddr
;
1992 SOCKADDR_IRDA
*win
= (SOCKADDR_IRDA
*)wsaddr
;
1994 if (*wsaddrlen
< sizeof(SOCKADDR_IRDA
))
1996 win
->irdaAddressFamily
= WS_AF_IRDA
;
1997 memcpy( win
->irdaDeviceID
, &uin
->sir_addr
, sizeof(win
->irdaDeviceID
) );
1998 if (uin
->sir_lsap_sel
!= LSAP_ANY
)
1999 sprintf( win
->irdaServiceName
, "LSAP-SEL%u", uin
->sir_lsap_sel
);
2001 memcpy( win
->irdaServiceName
, uin
->sir_name
,
2002 sizeof(win
->irdaServiceName
) );
2007 const struct sockaddr_in6
* uin6
= (const struct sockaddr_in6
*)uaddr
;
2008 struct WS_sockaddr_in6_old
* win6old
= (struct WS_sockaddr_in6_old
*)wsaddr
;
2010 if (*wsaddrlen
< sizeof(struct WS_sockaddr_in6_old
))
2012 win6old
->sin6_family
= WS_AF_INET6
;
2013 win6old
->sin6_port
= uin6
->sin6_port
;
2014 win6old
->sin6_flowinfo
= uin6
->sin6_flowinfo
;
2015 memcpy(&win6old
->sin6_addr
,&uin6
->sin6_addr
,16); /* 16 bytes = 128 address bits */
2016 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
2017 if (*wsaddrlen
>= sizeof(struct WS_sockaddr_in6
)) {
2018 struct WS_sockaddr_in6
* win6
= (struct WS_sockaddr_in6
*)wsaddr
;
2019 win6
->sin6_scope_id
= uin6
->sin6_scope_id
;
2020 *wsaddrlen
= sizeof(struct WS_sockaddr_in6
);
2023 *wsaddrlen
= sizeof(struct WS_sockaddr_in6_old
);
2025 *wsaddrlen
= sizeof(struct WS_sockaddr_in6_old
);
2030 const struct sockaddr_in
* uin
= (const struct sockaddr_in
*)uaddr
;
2031 struct WS_sockaddr_in
* win
= (struct WS_sockaddr_in
*)wsaddr
;
2033 if (*wsaddrlen
< sizeof(struct WS_sockaddr_in
))
2035 win
->sin_family
= WS_AF_INET
;
2036 win
->sin_port
= uin
->sin_port
;
2037 memcpy(&win
->sin_addr
,&uin
->sin_addr
,4); /* 4 bytes = 32 address bits */
2038 memset(win
->sin_zero
, 0, 8); /* Make sure the null padding is null */
2039 *wsaddrlen
= sizeof(struct WS_sockaddr_in
);
2043 memset(wsaddr
,0,*wsaddrlen
);
2047 FIXME("Unknown address family %d\n", uaddr
->sa_family
);
2053 static INT
WS_DuplicateSocket(BOOL unicode
, SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOW lpProtocolInfo
)
2057 WSAPROTOCOL_INFOW infow
;
2059 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
2060 unicode
, s
, dwProcessId
, lpProtocolInfo
);
2062 if (!ws_protocol_info(s
, unicode
, &infow
, &size
))
2063 return SOCKET_ERROR
;
2065 if (!(hProcess
= OpenProcess(PROCESS_DUP_HANDLE
, FALSE
, dwProcessId
)))
2067 SetLastError(WSAEINVAL
);
2068 return SOCKET_ERROR
;
2071 if (!lpProtocolInfo
)
2073 CloseHandle(hProcess
);
2074 SetLastError(WSAEFAULT
);
2075 return SOCKET_ERROR
;
2078 /* I don't know what the real Windoze does next, this is a hack */
2079 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
2080 * the target use the global duplicate, or we could copy a reference to us to the structure
2081 * and let the target duplicate it from us, but let's do it as simple as possible */
2082 memcpy(lpProtocolInfo
, &infow
, size
);
2083 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s
),
2084 hProcess
, (LPHANDLE
)&lpProtocolInfo
->dwServiceFlags3
,
2085 0, FALSE
, DUPLICATE_SAME_ACCESS
);
2086 CloseHandle(hProcess
);
2087 lpProtocolInfo
->dwServiceFlags4
= 0xff00ff00; /* magic */
2091 /*****************************************************************************
2092 * WS_EnterSingleProtocolW [internal]
2094 * enters the protocol information of one given protocol into the given
2098 * TRUE if a protocol was entered into the buffer.
2101 * - only implemented for IPX, SPX, SPXII, TCP, UDP
2102 * - there is no check that the operating system supports the returned
2105 static BOOL
WS_EnterSingleProtocolW( INT protocol
, WSAPROTOCOL_INFOW
* info
)
2107 memset( info
, 0, sizeof(WSAPROTOCOL_INFOW
) );
2108 info
->iProtocol
= protocol
;
2112 case WS_IPPROTO_TCP
:
2113 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_EXPEDITED_DATA
|
2114 XP1_GRACEFUL_CLOSE
| XP1_GUARANTEED_ORDER
|
2115 XP1_GUARANTEED_DELIVERY
;
2116 info
->ProviderId
= ProviderIdIP
;
2117 info
->dwCatalogEntryId
= 0x3e9;
2118 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2119 info
->ProtocolChain
.ChainLen
= 1;
2121 info
->iAddressFamily
= WS_AF_INET
;
2122 info
->iMaxSockAddr
= 0x10;
2123 info
->iMinSockAddr
= 0x10;
2124 info
->iSocketType
= WS_SOCK_STREAM
;
2125 strcpyW( info
->szProtocol
, NameTcpW
);
2128 case WS_IPPROTO_UDP
:
2129 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_SUPPORT_BROADCAST
|
2130 XP1_SUPPORT_MULTIPOINT
| XP1_MESSAGE_ORIENTED
|
2132 info
->ProviderId
= ProviderIdIP
;
2133 info
->dwCatalogEntryId
= 0x3ea;
2134 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2135 info
->ProtocolChain
.ChainLen
= 1;
2137 info
->iAddressFamily
= WS_AF_INET
;
2138 info
->iMaxSockAddr
= 0x10;
2139 info
->iMinSockAddr
= 0x10;
2140 info
->iSocketType
= WS_SOCK_DGRAM
;
2141 info
->dwMessageSize
= 0xffbb;
2142 strcpyW( info
->szProtocol
, NameUdpW
);
2145 case WS_NSPROTO_IPX
:
2146 info
->dwServiceFlags1
= XP1_PARTIAL_MESSAGE
| XP1_SUPPORT_BROADCAST
|
2147 XP1_SUPPORT_MULTIPOINT
| XP1_MESSAGE_ORIENTED
|
2149 info
->ProviderId
= ProviderIdIPX
;
2150 info
->dwCatalogEntryId
= 0x406;
2151 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2152 info
->ProtocolChain
.ChainLen
= 1;
2154 info
->iAddressFamily
= WS_AF_IPX
;
2155 info
->iMaxSockAddr
= 0x10;
2156 info
->iMinSockAddr
= 0x0e;
2157 info
->iSocketType
= WS_SOCK_DGRAM
;
2158 info
->iProtocolMaxOffset
= 0xff;
2159 info
->dwMessageSize
= 0x240;
2160 strcpyW( info
->szProtocol
, NameIpxW
);
2163 case WS_NSPROTO_SPX
:
2164 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_PSEUDO_STREAM
|
2165 XP1_MESSAGE_ORIENTED
| XP1_GUARANTEED_ORDER
|
2166 XP1_GUARANTEED_DELIVERY
;
2167 info
->ProviderId
= ProviderIdSPX
;
2168 info
->dwCatalogEntryId
= 0x407;
2169 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2170 info
->ProtocolChain
.ChainLen
= 1;
2172 info
->iAddressFamily
= WS_AF_IPX
;
2173 info
->iMaxSockAddr
= 0x10;
2174 info
->iMinSockAddr
= 0x0e;
2175 info
->iSocketType
= WS_SOCK_SEQPACKET
;
2176 info
->dwMessageSize
= 0xffffffff;
2177 strcpyW( info
->szProtocol
, NameSpxW
);
2180 case WS_NSPROTO_SPXII
:
2181 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_GRACEFUL_CLOSE
|
2182 XP1_PSEUDO_STREAM
| XP1_MESSAGE_ORIENTED
|
2183 XP1_GUARANTEED_ORDER
| XP1_GUARANTEED_DELIVERY
;
2184 info
->ProviderId
= ProviderIdSPX
;
2185 info
->dwCatalogEntryId
= 0x409;
2186 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2187 info
->ProtocolChain
.ChainLen
= 1;
2189 info
->iAddressFamily
= WS_AF_IPX
;
2190 info
->iMaxSockAddr
= 0x10;
2191 info
->iMinSockAddr
= 0x0e;
2192 info
->iSocketType
= WS_SOCK_SEQPACKET
;
2193 info
->dwMessageSize
= 0xffffffff;
2194 strcpyW( info
->szProtocol
, NameSpxIIW
);
2198 FIXME("unknown Protocol <0x%08x>\n", protocol
);
2204 /*****************************************************************************
2205 * WS_EnterSingleProtocolA [internal]
2207 * see function WS_EnterSingleProtocolW
2210 static BOOL
WS_EnterSingleProtocolA( INT protocol
, WSAPROTOCOL_INFOA
* info
)
2212 WSAPROTOCOL_INFOW infow
;
2214 memset( info
, 0, sizeof(WSAPROTOCOL_INFOA
) );
2216 ret
= WS_EnterSingleProtocolW( protocol
, &infow
);
2219 /* convert the structure from W to A */
2220 memcpy( info
, &infow
, FIELD_OFFSET( WSAPROTOCOL_INFOA
, szProtocol
) );
2221 WideCharToMultiByte( CP_ACP
, 0, infow
.szProtocol
, -1,
2222 info
->szProtocol
, WSAPROTOCOL_LEN
+1, NULL
, NULL
);
2228 static INT
WS_EnumProtocols( BOOL unicode
, const INT
*protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
)
2230 INT i
= 0, items
= 0;
2234 LPWSAPROTOCOL_INFOA a
;
2235 LPWSAPROTOCOL_INFOW w
;
2239 if (!protocols
) protocols
= valid_protocols
;
2241 while (protocols
[i
])
2243 if(supported_protocol(protocols
[i
++]))
2247 size
= items
* (unicode
? sizeof(WSAPROTOCOL_INFOW
) : sizeof(WSAPROTOCOL_INFOA
));
2249 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
2250 unicode
, protocols
, buffer
, len
, len
? *len
: 0, items
, size
);
2252 if (*len
< size
|| !buffer
)
2255 SetLastError(WSAENOBUFS
);
2256 return SOCKET_ERROR
;
2259 for (i
= items
= 0; protocols
[i
]; i
++)
2261 if (!supported_protocol(protocols
[i
])) continue;
2264 if (WS_EnterSingleProtocolW( protocols
[i
], &info
.w
[items
] ))
2269 if (WS_EnterSingleProtocolA( protocols
[i
], &info
.a
[items
] ))
2276 static BOOL
ws_protocol_info(SOCKET s
, int unicode
, WSAPROTOCOL_INFOW
*buffer
, int *size
)
2280 *size
= unicode
? sizeof(WSAPROTOCOL_INFOW
) : sizeof(WSAPROTOCOL_INFOA
);
2281 memset(buffer
, 0, *size
);
2283 SERVER_START_REQ( get_socket_info
)
2285 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
2286 status
= wine_server_call( req
);
2289 buffer
->iAddressFamily
= convert_af_u2w(reply
->family
);
2290 buffer
->iSocketType
= convert_socktype_u2w(reply
->type
);
2291 buffer
->iProtocol
= convert_proto_u2w(reply
->protocol
);
2298 unsigned int err
= NtStatusToWSAError( status
);
2299 SetLastError( err
== WSAEBADF
? WSAENOTSOCK
: err
);
2304 WS_EnterSingleProtocolW( buffer
->iProtocol
, buffer
);
2306 WS_EnterSingleProtocolA( buffer
->iProtocol
, (WSAPROTOCOL_INFOA
*)buffer
);
2311 /**************************************************************************
2312 * Functions for handling overlapped I/O
2313 **************************************************************************/
2315 /* user APC called upon async completion */
2316 static void WINAPI
ws2_async_apc( void *arg
, IO_STATUS_BLOCK
*iosb
, ULONG reserved
)
2318 struct ws2_async
*wsa
= arg
;
2320 if (wsa
->completion_func
) wsa
->completion_func( NtStatusToWSAError(iosb
->u
.Status
),
2321 iosb
->Information
, wsa
->user_overlapped
,
2323 release_async_io( &wsa
->io
);
2326 /***********************************************************************
2327 * WS2_recv (INTERNAL)
2329 * Workhorse for both synchronous and asynchronous recv() operations.
2331 static int WS2_recv( int fd
, struct ws2_async
*wsa
, int flags
)
2333 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2337 union generic_unix_sockaddr unix_sockaddr
;
2340 hdr
.msg_name
= NULL
;
2344 hdr
.msg_namelen
= sizeof(unix_sockaddr
);
2345 hdr
.msg_name
= &unix_sockaddr
;
2348 hdr
.msg_namelen
= 0;
2350 hdr
.msg_iov
= wsa
->iovec
+ wsa
->first_iovec
;
2351 hdr
.msg_iovlen
= wsa
->n_iovecs
- wsa
->first_iovec
;
2352 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2353 hdr
.msg_accrights
= NULL
;
2354 hdr
.msg_accrightslen
= 0;
2356 hdr
.msg_control
= pktbuf
;
2357 hdr
.msg_controllen
= sizeof(pktbuf
);
2361 while ((n
= __wine_locked_recvmsg( fd
, &hdr
, flags
)) == -1)
2367 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2370 ERR("Message control headers cannot be properly supported on this system.\n");
2371 wsa
->control
->len
= 0;
2374 if (wsa
->control
&& !convert_control_headers(&hdr
, wsa
->control
))
2376 WARN("Application passed insufficient room for control headers.\n");
2377 *wsa
->lpFlags
|= WS_MSG_CTRUNC
;
2383 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
2384 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
2386 * quoting linux 2.6 net/ipv4/tcp.c:
2387 * "According to UNIX98, msg_name/msg_namelen are ignored
2388 * on connected socket. I was just happy when found this 8) --ANK"
2390 * likewise MSDN says that lpFrom and lpFromlen are ignored for
2391 * connection-oriented sockets, so don't try to update lpFrom.
2393 if (wsa
->addr
&& hdr
.msg_namelen
)
2394 ws_sockaddr_u2ws( &unix_sockaddr
.addr
, wsa
->addr
, wsa
->addrlen
.ptr
);
2399 /***********************************************************************
2400 * WS2_async_recv (INTERNAL)
2402 * Handler for overlapped recv() operations.
2404 static NTSTATUS
WS2_async_recv( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
2406 struct ws2_async
*wsa
= user
;
2411 case STATUS_ALERTED
:
2412 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, FILE_READ_DATA
, &fd
, NULL
) ))
2415 result
= WS2_recv( fd
, wsa
, convert_flags(wsa
->flags
) );
2416 wine_server_release_fd( wsa
->hSocket
, fd
);
2419 status
= STATUS_SUCCESS
;
2420 _enable_event( wsa
->hSocket
, FD_READ
, 0, 0 );
2424 if (errno
== EAGAIN
)
2426 status
= STATUS_PENDING
;
2427 _enable_event( wsa
->hSocket
, FD_READ
, 0, 0 );
2432 status
= wsaErrStatus();
2437 if (status
!= STATUS_PENDING
)
2439 iosb
->u
.Status
= status
;
2440 iosb
->Information
= result
;
2441 if (!wsa
->completion_func
)
2442 release_async_io( &wsa
->io
);
2447 /***********************************************************************
2448 * WS2_async_accept_recv (INTERNAL)
2450 * This function is used to finish the read part of an accept request. It is
2451 * needed to place the completion on the correct socket (listener).
2453 static NTSTATUS
WS2_async_accept_recv( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
2455 struct ws2_accept_async
*wsa
= user
;
2457 status
= WS2_async_recv( wsa
->read
, iosb
, status
);
2458 if (status
== STATUS_PENDING
)
2462 WS_AddCompletion( HANDLE2SOCKET(wsa
->listen_socket
), wsa
->cvalue
, iosb
->u
.Status
, iosb
->Information
);
2464 release_async_io( &wsa
->io
);
2468 /***********************************************************************
2469 * WS2_async_accept (INTERNAL)
2471 * This is the function called to satisfy the AcceptEx callback
2473 static NTSTATUS
WS2_async_accept( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
2475 struct ws2_accept_async
*wsa
= user
;
2479 TRACE("status: 0x%x listen: %p, accept: %p\n", status
, wsa
->listen_socket
, wsa
->accept_socket
);
2481 if (status
== STATUS_ALERTED
)
2483 SERVER_START_REQ( accept_into_socket
)
2485 req
->lhandle
= wine_server_obj_handle( wsa
->listen_socket
);
2486 req
->ahandle
= wine_server_obj_handle( wsa
->accept_socket
);
2487 status
= wine_server_call( req
);
2491 if (status
== STATUS_CANT_WAIT
)
2492 return STATUS_PENDING
;
2494 if (status
== STATUS_INVALID_HANDLE
)
2496 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2497 status
= STATUS_CANCELLED
;
2500 else if (status
== STATUS_HANDLES_CLOSED
)
2501 status
= STATUS_CANCELLED
; /* strange windows behavior */
2503 if (status
!= STATUS_SUCCESS
)
2506 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2507 addr
= ((char *)wsa
->buf
) + wsa
->data_len
;
2508 len
= wsa
->local_len
- sizeof(int);
2509 WS_getsockname(HANDLE2SOCKET(wsa
->accept_socket
),
2510 (struct WS_sockaddr
*)(addr
+ sizeof(int)), &len
);
2513 addr
+= wsa
->local_len
;
2514 len
= wsa
->remote_len
- sizeof(int);
2515 WS_getpeername(HANDLE2SOCKET(wsa
->accept_socket
),
2516 (struct WS_sockaddr
*)(addr
+ sizeof(int)), &len
);
2522 wsa
->io
.callback
= WS2_async_accept_recv
;
2523 status
= register_async( ASYNC_TYPE_READ
, wsa
->accept_socket
, &wsa
->io
,
2524 wsa
->user_overlapped
->hEvent
, NULL
, NULL
, iosb
);
2526 if (status
!= STATUS_PENDING
)
2529 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2530 * needs to be performed by WS2_async_accept_recv() first. */
2531 return STATUS_MORE_PROCESSING_REQUIRED
;
2534 iosb
->u
.Status
= status
;
2535 iosb
->Information
= 0;
2537 if (wsa
->read
) release_async_io( &wsa
->read
->io
);
2538 release_async_io( &wsa
->io
);
2542 /***********************************************************************
2543 * WS2_send (INTERNAL)
2545 * Workhorse for both synchronous and asynchronous send() operations.
2547 static int WS2_send( int fd
, struct ws2_async
*wsa
, int flags
)
2550 union generic_unix_sockaddr unix_addr
;
2553 hdr
.msg_name
= NULL
;
2554 hdr
.msg_namelen
= 0;
2558 hdr
.msg_name
= &unix_addr
;
2559 hdr
.msg_namelen
= ws_sockaddr_ws2u( wsa
->addr
, wsa
->addrlen
.val
, &unix_addr
);
2560 if ( !hdr
.msg_namelen
)
2566 #if defined(HAS_IPX) && defined(SOL_IPX)
2567 if(wsa
->addr
->sa_family
== WS_AF_IPX
)
2569 struct sockaddr_ipx
* uipx
= (struct sockaddr_ipx
*)hdr
.msg_name
;
2571 socklen_t len
= sizeof(int);
2573 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2574 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2575 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2576 * ipx type in the sockaddr_opx structure with the stored value.
2578 if(getsockopt(fd
, SOL_IPX
, IPX_TYPE
, &val
, &len
) != -1)
2579 uipx
->sipx_type
= val
;
2584 hdr
.msg_iov
= wsa
->iovec
+ wsa
->first_iovec
;
2585 hdr
.msg_iovlen
= wsa
->n_iovecs
- wsa
->first_iovec
;
2586 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2587 hdr
.msg_accrights
= NULL
;
2588 hdr
.msg_accrightslen
= 0;
2590 hdr
.msg_control
= NULL
;
2591 hdr
.msg_controllen
= 0;
2595 while ((ret
= sendmsg(fd
, &hdr
, flags
)) == -1)
2602 while (wsa
->first_iovec
< wsa
->n_iovecs
&& wsa
->iovec
[wsa
->first_iovec
].iov_len
<= n
)
2603 n
-= wsa
->iovec
[wsa
->first_iovec
++].iov_len
;
2604 if (wsa
->first_iovec
< wsa
->n_iovecs
)
2606 wsa
->iovec
[wsa
->first_iovec
].iov_base
= (char*)wsa
->iovec
[wsa
->first_iovec
].iov_base
+ n
;
2607 wsa
->iovec
[wsa
->first_iovec
].iov_len
-= n
;
2612 /***********************************************************************
2613 * WS2_async_send (INTERNAL)
2615 * Handler for overlapped send() operations.
2617 static NTSTATUS
WS2_async_send( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
2619 struct ws2_async
*wsa
= user
;
2624 case STATUS_ALERTED
:
2625 if ( wsa
->n_iovecs
<= wsa
->first_iovec
)
2628 status
= STATUS_SUCCESS
;
2631 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, FILE_WRITE_DATA
, &fd
, NULL
) ))
2634 /* check to see if the data is ready (non-blocking) */
2635 result
= WS2_send( fd
, wsa
, convert_flags(wsa
->flags
) );
2636 wine_server_release_fd( wsa
->hSocket
, fd
);
2640 if (wsa
->first_iovec
< wsa
->n_iovecs
)
2641 status
= STATUS_PENDING
;
2643 status
= STATUS_SUCCESS
;
2645 iosb
->Information
+= result
;
2647 else if (errno
== EAGAIN
)
2649 status
= STATUS_PENDING
;
2653 status
= wsaErrStatus();
2657 if (status
!= STATUS_PENDING
)
2659 iosb
->u
.Status
= status
;
2660 if (!wsa
->completion_func
)
2661 release_async_io( &wsa
->io
);
2666 /***********************************************************************
2667 * WS2_async_shutdown (INTERNAL)
2669 * Handler for shutdown() operations on overlapped sockets.
2671 static NTSTATUS
WS2_async_shutdown( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
2673 struct ws2_async_shutdown
*wsa
= user
;
2678 case STATUS_ALERTED
:
2679 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, 0, &fd
, NULL
) ))
2682 switch ( wsa
->type
)
2684 case ASYNC_TYPE_READ
: err
= shutdown( fd
, 0 ); break;
2685 case ASYNC_TYPE_WRITE
: err
= shutdown( fd
, 1 ); break;
2687 status
= err
? wsaErrStatus() : STATUS_SUCCESS
;
2688 wine_server_release_fd( wsa
->hSocket
, fd
);
2691 iosb
->u
.Status
= status
;
2692 iosb
->Information
= 0;
2693 release_async_io( &wsa
->io
);
2697 /***********************************************************************
2698 * WS2_register_async_shutdown (INTERNAL)
2700 * Helper function for WS_shutdown() on overlapped sockets.
2702 static int WS2_register_async_shutdown( SOCKET s
, int type
)
2704 struct ws2_async_shutdown
*wsa
;
2707 TRACE("socket %04lx type %d\n", s
, type
);
2709 wsa
= (struct ws2_async_shutdown
*)alloc_async_io( sizeof(*wsa
), WS2_async_shutdown
);
2713 wsa
->hSocket
= SOCKET2HANDLE(s
);
2716 status
= register_async( type
, wsa
->hSocket
, &wsa
->io
, 0, NULL
, NULL
, &wsa
->iosb
);
2717 if (status
!= STATUS_PENDING
)
2719 HeapFree( GetProcessHeap(), 0, wsa
);
2720 return NtStatusToWSAError( status
);
2725 /***********************************************************************
2728 SOCKET WINAPI
WS_accept(SOCKET s
, struct WS_sockaddr
*addr
, int *addrlen32
)
2734 TRACE("socket %04lx\n", s
);
2735 status
= _is_blocking(s
, &is_blocking
);
2740 /* try accepting first (if there is a deferred connection) */
2741 SERVER_START_REQ( accept_socket
)
2743 req
->lhandle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
2744 req
->access
= GENERIC_READ
|GENERIC_WRITE
|SYNCHRONIZE
;
2745 req
->attributes
= OBJ_INHERIT
;
2746 status
= wine_server_call( req
);
2747 as
= HANDLE2SOCKET( wine_server_ptr_handle( reply
->handle
));
2752 if (addr
&& addrlen32
&& WS_getpeername(as
, addr
, addrlen32
))
2755 return SOCKET_ERROR
;
2757 TRACE("\taccepted %04lx\n", as
);
2760 if (is_blocking
&& status
== STATUS_CANT_WAIT
)
2762 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
2764 do_block(fd
, POLLIN
, -1);
2765 _sync_sock_state(s
); /* let wineserver notice connection */
2766 release_sock_fd( s
, fd
);
2768 } while (is_blocking
&& status
== STATUS_CANT_WAIT
);
2772 WARN(" -> ERROR %d\n", GetLastError());
2773 return INVALID_SOCKET
;
2776 /***********************************************************************
2779 static BOOL WINAPI
WS2_AcceptEx(SOCKET listener
, SOCKET acceptor
, PVOID dest
, DWORD dest_len
,
2780 DWORD local_addr_len
, DWORD rem_addr_len
, LPDWORD received
,
2781 LPOVERLAPPED overlapped
)
2784 struct ws2_accept_async
*wsa
;
2787 TRACE("(%04lx, %04lx, %p, %d, %d, %d, %p, %p)\n", listener
, acceptor
, dest
, dest_len
, local_addr_len
,
2788 rem_addr_len
, received
, overlapped
);
2792 SetLastError(WSAEINVAL
);
2798 SetLastError(WSA_INVALID_PARAMETER
);
2804 SetLastError(WSAEFAULT
);
2808 fd
= get_sock_fd( listener
, FILE_READ_DATA
, NULL
);
2811 SetLastError(WSAENOTSOCK
);
2814 release_sock_fd( listener
, fd
);
2816 fd
= get_sock_fd( acceptor
, FILE_READ_DATA
, NULL
);
2819 SetLastError(WSAENOTSOCK
);
2822 release_sock_fd( acceptor
, fd
);
2824 wsa
= (struct ws2_accept_async
*)alloc_async_io( sizeof(*wsa
), WS2_async_accept
);
2827 SetLastError(WSAEFAULT
);
2831 wsa
->listen_socket
= SOCKET2HANDLE(listener
);
2832 wsa
->accept_socket
= SOCKET2HANDLE(acceptor
);
2833 wsa
->user_overlapped
= overlapped
;
2834 wsa
->cvalue
= !((ULONG_PTR
)overlapped
->hEvent
& 1) ? (ULONG_PTR
)overlapped
: 0;
2836 wsa
->data_len
= dest_len
;
2837 wsa
->local_len
= local_addr_len
;
2838 wsa
->remote_len
= rem_addr_len
;
2843 /* set up a read request if we need it */
2844 wsa
->read
= (struct ws2_async
*)alloc_async_io( offsetof(struct ws2_async
, iovec
[1]), WS2_async_accept_recv
);
2847 HeapFree( GetProcessHeap(), 0, wsa
);
2848 SetLastError(WSAEFAULT
);
2852 wsa
->read
->hSocket
= wsa
->accept_socket
;
2853 wsa
->read
->flags
= 0;
2854 wsa
->read
->lpFlags
= &wsa
->read
->flags
;
2855 wsa
->read
->addr
= NULL
;
2856 wsa
->read
->addrlen
.ptr
= NULL
;
2857 wsa
->read
->control
= NULL
;
2858 wsa
->read
->n_iovecs
= 1;
2859 wsa
->read
->first_iovec
= 0;
2860 wsa
->read
->completion_func
= NULL
;
2861 wsa
->read
->iovec
[0].iov_base
= wsa
->buf
;
2862 wsa
->read
->iovec
[0].iov_len
= wsa
->data_len
;
2865 status
= register_async( ASYNC_TYPE_READ
, SOCKET2HANDLE(listener
), &wsa
->io
,
2866 overlapped
->hEvent
, NULL
, (void *)wsa
->cvalue
, (IO_STATUS_BLOCK
*)overlapped
);
2868 if(status
!= STATUS_PENDING
)
2870 HeapFree( GetProcessHeap(), 0, wsa
->read
);
2871 HeapFree( GetProcessHeap(), 0, wsa
);
2874 SetLastError( NtStatusToWSAError(status
) );
2878 /***********************************************************************
2879 * WS2_ReadFile (INTERNAL)
2881 * Perform an APC-safe ReadFile operation
2883 static NTSTATUS
WS2_ReadFile(HANDLE hFile
, PIO_STATUS_BLOCK io_status
, char* buffer
, ULONG length
,
2884 PLARGE_INTEGER offset
)
2886 int result
= -1, unix_handle
;
2887 unsigned int options
;
2890 TRACE( "(%p,%p,0x%08x)\n", hFile
, buffer
,length
);
2892 status
= wine_server_handle_to_fd( hFile
, FILE_READ_DATA
, &unix_handle
, &options
);
2893 if (status
) return status
;
2895 while (result
== -1)
2897 if (offset
->QuadPart
!= FILE_USE_FILE_POINTER_POSITION
)
2898 result
= pread( unix_handle
, buffer
, length
, offset
->QuadPart
);
2900 result
= read( unix_handle
, buffer
, length
);
2906 status
= (length
? STATUS_END_OF_FILE
: STATUS_SUCCESS
);
2907 else if (result
!= -1)
2908 status
= STATUS_SUCCESS
;
2909 else if (errno
!= EAGAIN
)
2910 status
= wsaErrStatus();
2912 status
= STATUS_PENDING
;
2914 wine_server_release_fd( hFile
, unix_handle
);
2915 TRACE("= 0x%08x (%d)\n", status
, result
);
2916 if (status
== STATUS_SUCCESS
|| status
== STATUS_END_OF_FILE
)
2918 io_status
->u
.Status
= status
;
2919 io_status
->Information
= result
;
2925 /***********************************************************************
2926 * WS2_transmitfile_getbuffer (INTERNAL)
2928 * Pick the appropriate buffer for a TransmitFile send operation.
2930 static NTSTATUS
WS2_transmitfile_getbuffer( int fd
, struct ws2_transmitfile_async
*wsa
)
2932 /* send any incomplete writes from a previous iteration */
2933 if (wsa
->write
.first_iovec
< wsa
->write
.n_iovecs
)
2934 return STATUS_PENDING
;
2936 /* process the header (if applicable) */
2937 if (wsa
->buffers
.Head
)
2939 wsa
->write
.first_iovec
= 0;
2940 wsa
->write
.n_iovecs
= 1;
2941 wsa
->write
.iovec
[0].iov_base
= wsa
->buffers
.Head
;
2942 wsa
->write
.iovec
[0].iov_len
= wsa
->buffers
.HeadLength
;
2943 wsa
->buffers
.Head
= NULL
;
2944 return STATUS_PENDING
;
2947 /* process the main file */
2950 DWORD bytes_per_send
= wsa
->bytes_per_send
;
2951 IO_STATUS_BLOCK iosb
;
2954 iosb
.Information
= 0;
2955 /* when the size of the transfer is limited ensure that we don't go past that limit */
2956 if (wsa
->file_bytes
!= 0)
2957 bytes_per_send
= min(bytes_per_send
, wsa
->file_bytes
- wsa
->file_read
);
2958 status
= WS2_ReadFile( wsa
->file
, &iosb
, wsa
->buffer
, bytes_per_send
, &wsa
->offset
);
2959 if (wsa
->offset
.QuadPart
!= FILE_USE_FILE_POINTER_POSITION
)
2960 wsa
->offset
.QuadPart
+= iosb
.Information
;
2961 if (status
== STATUS_END_OF_FILE
)
2962 wsa
->file
= NULL
; /* continue on to the footer */
2963 else if (status
!= STATUS_SUCCESS
)
2967 if (iosb
.Information
)
2969 wsa
->write
.first_iovec
= 0;
2970 wsa
->write
.n_iovecs
= 1;
2971 wsa
->write
.iovec
[0].iov_base
= wsa
->buffer
;
2972 wsa
->write
.iovec
[0].iov_len
= iosb
.Information
;
2973 wsa
->file_read
+= iosb
.Information
;
2976 if (wsa
->file_bytes
!= 0 && wsa
->file_read
>= wsa
->file_bytes
)
2979 return STATUS_PENDING
;
2983 /* send the footer (if applicable) */
2984 if (wsa
->buffers
.Tail
)
2986 wsa
->write
.first_iovec
= 0;
2987 wsa
->write
.n_iovecs
= 1;
2988 wsa
->write
.iovec
[0].iov_base
= wsa
->buffers
.Tail
;
2989 wsa
->write
.iovec
[0].iov_len
= wsa
->buffers
.TailLength
;
2990 wsa
->buffers
.Tail
= NULL
;
2991 return STATUS_PENDING
;
2994 return STATUS_SUCCESS
;
2997 /***********************************************************************
2998 * WS2_transmitfile_base (INTERNAL)
3000 * Shared implementation for both synchronous and asynchronous TransmitFile.
3002 static NTSTATUS
WS2_transmitfile_base( int fd
, struct ws2_transmitfile_async
*wsa
)
3006 status
= WS2_transmitfile_getbuffer( fd
, wsa
);
3007 if (status
== STATUS_PENDING
)
3009 IO_STATUS_BLOCK
*iosb
= (IO_STATUS_BLOCK
*)wsa
->write
.user_overlapped
;
3012 n
= WS2_send( fd
, &wsa
->write
, convert_flags(wsa
->write
.flags
) );
3015 if (iosb
) iosb
->Information
+= n
;
3017 else if (errno
!= EAGAIN
)
3018 return wsaErrStatus();
3024 /***********************************************************************
3025 * WS2_async_transmitfile (INTERNAL)
3027 * Asynchronous callback for overlapped TransmitFile operations.
3029 static NTSTATUS
WS2_async_transmitfile( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
3031 struct ws2_transmitfile_async
*wsa
= user
;
3034 if (status
== STATUS_ALERTED
)
3036 if (!(status
= wine_server_handle_to_fd( wsa
->write
.hSocket
, FILE_WRITE_DATA
, &fd
, NULL
)))
3038 status
= WS2_transmitfile_base( fd
, wsa
);
3039 wine_server_release_fd( wsa
->write
.hSocket
, fd
);
3041 if (status
== STATUS_PENDING
)
3045 iosb
->u
.Status
= status
;
3046 release_async_io( &wsa
->io
);
3050 /***********************************************************************
3053 static BOOL WINAPI
WS2_TransmitFile( SOCKET s
, HANDLE h
, DWORD file_bytes
, DWORD bytes_per_send
,
3054 LPOVERLAPPED overlapped
, LPTRANSMIT_FILE_BUFFERS buffers
,
3057 union generic_unix_sockaddr uaddr
;
3058 socklen_t uaddrlen
= sizeof(uaddr
);
3059 struct ws2_transmitfile_async
*wsa
;
3063 TRACE("(%lx, %p, %d, %d, %p, %p, %d)\n", s
, h
, file_bytes
, bytes_per_send
, overlapped
,
3066 fd
= get_sock_fd( s
, FILE_WRITE_DATA
, NULL
);
3069 WSASetLastError( WSAENOTSOCK
);
3072 if (getpeername( fd
, &uaddr
.addr
, &uaddrlen
) != 0)
3074 release_sock_fd( s
, fd
);
3075 WSASetLastError( WSAENOTCONN
);
3079 FIXME("Flags are not currently supported (0x%x).\n", flags
);
3081 if (h
&& GetFileType( h
) != FILE_TYPE_DISK
)
3083 FIXME("Non-disk file handles are not currently supported.\n");
3084 release_sock_fd( s
, fd
);
3085 WSASetLastError( WSAEOPNOTSUPP
);
3089 /* set reasonable defaults when requested */
3090 if (!bytes_per_send
)
3091 bytes_per_send
= (1 << 16); /* Depends on OS version: PAGE_SIZE, 2*PAGE_SIZE, or 2^16 */
3093 if (!(wsa
= (struct ws2_transmitfile_async
*)alloc_async_io( sizeof(*wsa
) + bytes_per_send
,
3094 WS2_async_transmitfile
)))
3096 release_sock_fd( s
, fd
);
3097 WSASetLastError( WSAEFAULT
);
3101 wsa
->buffers
= *buffers
;
3103 memset(&wsa
->buffers
, 0x0, sizeof(wsa
->buffers
));
3104 wsa
->buffer
= (char *)(wsa
+ 1);
3107 wsa
->file_bytes
= file_bytes
;
3108 wsa
->bytes_per_send
= bytes_per_send
;
3110 wsa
->offset
.QuadPart
= FILE_USE_FILE_POINTER_POSITION
;
3111 wsa
->write
.hSocket
= SOCKET2HANDLE(s
);
3112 wsa
->write
.addr
= NULL
;
3113 wsa
->write
.addrlen
.val
= 0;
3114 wsa
->write
.flags
= 0;
3115 wsa
->write
.lpFlags
= &wsa
->flags
;
3116 wsa
->write
.control
= NULL
;
3117 wsa
->write
.n_iovecs
= 0;
3118 wsa
->write
.first_iovec
= 0;
3119 wsa
->write
.user_overlapped
= overlapped
;
3122 IO_STATUS_BLOCK
*iosb
= (IO_STATUS_BLOCK
*)overlapped
;
3125 wsa
->offset
.u
.LowPart
= overlapped
->u
.s
.Offset
;
3126 wsa
->offset
.u
.HighPart
= overlapped
->u
.s
.OffsetHigh
;
3127 iosb
->u
.Status
= STATUS_PENDING
;
3128 iosb
->Information
= 0;
3129 status
= register_async( ASYNC_TYPE_WRITE
, SOCKET2HANDLE(s
), &wsa
->io
,
3130 overlapped
->hEvent
, NULL
, NULL
, iosb
);
3131 if(status
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
3132 release_sock_fd( s
, fd
);
3133 WSASetLastError( NtStatusToWSAError(status
) );
3139 status
= WS2_transmitfile_base( fd
, wsa
);
3140 if (status
== STATUS_PENDING
)
3143 do_block(fd
, POLLOUT
, -1);
3144 _sync_sock_state(s
); /* let wineserver notice connection */
3147 while (status
== STATUS_PENDING
);
3148 release_sock_fd( s
, fd
);
3150 if (status
!= STATUS_SUCCESS
)
3151 WSASetLastError( NtStatusToWSAError(status
) );
3152 HeapFree( GetProcessHeap(), 0, wsa
);
3153 return (status
== STATUS_SUCCESS
);
3156 /***********************************************************************
3157 * GetAcceptExSockaddrs
3159 static void WINAPI
WS2_GetAcceptExSockaddrs(PVOID buffer
, DWORD data_size
, DWORD local_size
, DWORD remote_size
,
3160 struct WS_sockaddr
**local_addr
, LPINT local_addr_len
,
3161 struct WS_sockaddr
**remote_addr
, LPINT remote_addr_len
)
3163 char *cbuf
= buffer
;
3164 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer
, data_size
, local_size
, remote_size
, local_addr
,
3165 local_addr_len
, remote_addr
, remote_addr_len
);
3168 *local_addr_len
= *(int *) cbuf
;
3169 *local_addr
= (struct WS_sockaddr
*)(cbuf
+ sizeof(int));
3173 *remote_addr_len
= *(int *) cbuf
;
3174 *remote_addr
= (struct WS_sockaddr
*)(cbuf
+ sizeof(int));
3177 /***********************************************************************
3180 int WINAPI
WSASendMsg( SOCKET s
, LPWSAMSG msg
, DWORD dwFlags
, LPDWORD lpNumberOfBytesSent
,
3181 LPWSAOVERLAPPED lpOverlapped
,
3182 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
3186 SetLastError( WSAEFAULT
);
3187 return SOCKET_ERROR
;
3190 return WS2_sendto( s
, msg
->lpBuffers
, msg
->dwBufferCount
, lpNumberOfBytesSent
,
3191 dwFlags
, msg
->name
, msg
->namelen
,
3192 lpOverlapped
, lpCompletionRoutine
);
3195 /***********************************************************************
3198 * Perform a receive operation that is capable of returning message
3199 * control headers. It is important to note that the WSAMSG parameter
3200 * must remain valid throughout the operation, even when an overlapped
3201 * receive is performed.
3203 static int WINAPI
WS2_WSARecvMsg( SOCKET s
, LPWSAMSG msg
, LPDWORD lpNumberOfBytesRecvd
,
3204 LPWSAOVERLAPPED lpOverlapped
,
3205 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
3209 SetLastError( WSAEFAULT
);
3210 return SOCKET_ERROR
;
3213 return WS2_recv_base( s
, msg
->lpBuffers
, msg
->dwBufferCount
, lpNumberOfBytesRecvd
,
3214 &msg
->dwFlags
, msg
->name
, &msg
->namelen
,
3215 lpOverlapped
, lpCompletionRoutine
, &msg
->Control
);
3218 /***********************************************************************
3219 * interface_bind (INTERNAL)
3221 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
3222 * operating only on the specified interface. This restriction consists of two components:
3223 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
3224 * 2) An incoming packet restriction dropping packets not meant for the interface.
3225 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
3226 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
3227 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
3228 * to receive broadcast packets on a socket that is bound to a specific network interface.
3230 static BOOL
interface_bind( SOCKET s
, int fd
, struct sockaddr
*addr
)
3232 struct sockaddr_in
*in_sock
= (struct sockaddr_in
*) addr
;
3233 in_addr_t bind_addr
= in_sock
->sin_addr
.s_addr
;
3234 PIP_ADAPTER_INFO adapters
= NULL
, adapter
;
3239 if (bind_addr
== htonl(INADDR_ANY
) || bind_addr
== htonl(INADDR_LOOPBACK
))
3240 return FALSE
; /* Not binding to a network adapter, special interface binding unnecessary. */
3241 if (_get_fd_type(fd
) != SOCK_DGRAM
)
3242 return FALSE
; /* Special interface binding is only necessary for UDP datagrams. */
3243 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
3245 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
3246 if (adapters
== NULL
|| GetAdaptersInfo(adapters
, &adap_size
) != NO_ERROR
)
3248 /* Search the IPv4 adapter list for the appropriate binding interface */
3249 for (adapter
= adapters
; adapter
!= NULL
; adapter
= adapter
->Next
)
3251 in_addr_t adapter_addr
= (in_addr_t
) inet_addr(adapter
->IpAddressList
.IpAddress
.String
);
3253 if (bind_addr
== adapter_addr
)
3255 #if defined(IP_BOUND_IF)
3256 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
3257 if (setsockopt(fd
, IPPROTO_IP
, IP_BOUND_IF
, &adapter
->Index
, sizeof(adapter
->Index
)) != 0)
3260 #elif defined(LINUX_BOUND_IF)
3261 in_addr_t ifindex
= (in_addr_t
) htonl(adapter
->Index
);
3262 struct interface_filter specific_interface_filter
;
3263 struct sock_fprog filter_prog
;
3265 if (setsockopt(fd
, IPPROTO_IP
, IP_UNICAST_IF
, &ifindex
, sizeof(ifindex
)) != 0)
3266 goto cleanup
; /* Failed to suggest egress interface */
3267 specific_interface_filter
= generic_interface_filter
;
3268 specific_interface_filter
.iface_rule
.k
= adapter
->Index
;
3269 specific_interface_filter
.ip_rule
.k
= htonl(adapter_addr
);
3270 filter_prog
.len
= sizeof(generic_interface_filter
)/sizeof(struct sock_filter
);
3271 filter_prog
.filter
= (struct sock_filter
*) &specific_interface_filter
;
3272 if (setsockopt(fd
, SOL_SOCKET
, SO_ATTACH_FILTER
, &filter_prog
, sizeof(filter_prog
)) != 0)
3273 goto cleanup
; /* Failed to specify incoming packet filter */
3276 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
3277 "receiving broadcast packets will not work on socket %04lx.\n", s
);
3282 /* Will soon be switching to INADDR_ANY: permit address reuse */
3283 if (ret
&& setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &enable
, sizeof(enable
)) == 0)
3284 TRACE("Socket %04lx bound to interface index %d\n", s
, adapter
->Index
);
3290 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s
);
3291 HeapFree(GetProcessHeap(), 0, adapters
);
3295 /***********************************************************************
3298 int WINAPI
WS_bind(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
)
3300 int fd
= get_sock_fd( s
, 0, NULL
);
3301 int res
= SOCKET_ERROR
;
3303 TRACE("socket %04lx, ptr %p %s, length %d\n", s
, name
, debugstr_sockaddr(name
), namelen
);
3307 if (!name
|| (name
->sa_family
&& !supported_pf(name
->sa_family
)))
3309 SetLastError(WSAEAFNOSUPPORT
);
3313 union generic_unix_sockaddr uaddr
;
3314 unsigned int uaddrlen
= ws_sockaddr_ws2u(name
, namelen
, &uaddr
);
3317 SetLastError(WSAEFAULT
);
3321 if (name
->sa_family
== WS_AF_INET
)
3323 struct sockaddr_in
*in4
= (struct sockaddr_in
*) &uaddr
;
3324 if (memcmp(&in4
->sin_addr
, magic_loopback_addr
, 4) == 0)
3326 /* Trying to bind to the default host interface, using
3327 * INADDR_ANY instead*/
3328 WARN("Trying to bind to magic IP address, using "
3329 "INADDR_ANY instead.\n");
3330 in4
->sin_addr
.s_addr
= htonl(INADDR_ANY
);
3332 else if (interface_bind(s
, fd
, &uaddr
.addr
))
3333 in4
->sin_addr
.s_addr
= htonl(INADDR_ANY
);
3335 if (bind(fd
, &uaddr
.addr
, uaddrlen
) < 0)
3337 int loc_errno
= errno
;
3338 WARN("\tfailure - errno = %i\n", errno
);
3343 SetLastError(WSAEINVAL
);
3348 socklen_t optlen
= sizeof(optval
);
3349 /* Windows >= 2003 will return different results depending on
3350 * SO_REUSEADDR, WSAEACCES may be returned representing that
3351 * the socket hijacking protection prevented the bind */
3352 if (!getsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&optval
, &optlen
) && optval
)
3354 SetLastError(WSAEACCES
);
3360 SetLastError(wsaErrno());
3366 res
=0; /* success */
3370 release_sock_fd( s
, fd
);
3375 /***********************************************************************
3376 * closesocket (WS2_32.3)
3378 int WINAPI
WS_closesocket(SOCKET s
)
3380 int res
= SOCKET_ERROR
, fd
;
3383 fd
= get_sock_fd(s
, FILE_READ_DATA
, NULL
);
3386 release_sock_fd(s
, fd
);
3387 if (CloseHandle(SOCKET2HANDLE(s
)))
3391 SetLastError(WSAENOTSOCK
);
3394 SetLastError(WSANOTINITIALISED
);
3395 TRACE("(socket %04lx) -> %d\n", s
, res
);
3399 static int do_connect(int fd
, const struct WS_sockaddr
* name
, int namelen
)
3401 union generic_unix_sockaddr uaddr
;
3402 unsigned int uaddrlen
= ws_sockaddr_ws2u(name
, namelen
, &uaddr
);
3407 if (name
->sa_family
== WS_AF_INET
)
3409 struct sockaddr_in
*in4
= (struct sockaddr_in
*) &uaddr
;
3410 if (memcmp(&in4
->sin_addr
, magic_loopback_addr
, 4) == 0)
3412 /* Trying to connect to magic replace-loopback address,
3413 * assuming we really want to connect to localhost */
3414 TRACE("Trying to connect to magic IP address, using "
3415 "INADDR_LOOPBACK instead.\n");
3416 in4
->sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
3420 if (connect(fd
, &uaddr
.addr
, uaddrlen
) == 0)
3426 /***********************************************************************
3427 * connect (WS2_32.4)
3429 int WINAPI
WS_connect(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
)
3431 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
3433 TRACE("socket %04lx, ptr %p %s, length %d\n", s
, name
, debugstr_sockaddr(name
), namelen
);
3439 int ret
= do_connect(fd
, name
, namelen
);
3441 goto connect_success
;
3443 if (ret
== WSAEINPROGRESS
)
3445 /* tell wineserver that a connection is in progress */
3446 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3448 FD_WINE_CONNECTED
|FD_WINE_LISTENING
);
3449 status
= _is_blocking( s
, &is_blocking
);
3452 release_sock_fd( s
, fd
);
3453 set_error( status
);
3454 return SOCKET_ERROR
;
3460 do_block(fd
, POLLIN
| POLLOUT
, -1);
3461 _sync_sock_state(s
); /* let wineserver notice connection */
3462 /* retrieve any error codes from it */
3463 result
= _get_sock_error(s
, FD_CONNECT_BIT
);
3465 SetLastError(NtStatusToWSAError(result
));
3468 goto connect_success
;
3473 SetLastError(WSAEWOULDBLOCK
);
3480 release_sock_fd( s
, fd
);
3482 return SOCKET_ERROR
;
3485 release_sock_fd( s
, fd
);
3486 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3487 FD_WINE_CONNECTED
|FD_READ
|FD_WRITE
,
3488 FD_CONNECT
|FD_WINE_LISTENING
);
3489 TRACE("\tconnected %04lx\n", s
);
3493 /***********************************************************************
3494 * WSAConnect (WS2_32.30)
3496 int WINAPI
WSAConnect( SOCKET s
, const struct WS_sockaddr
* name
, int namelen
,
3497 LPWSABUF lpCallerData
, LPWSABUF lpCalleeData
,
3498 LPQOS lpSQOS
, LPQOS lpGQOS
)
3500 if ( lpCallerData
|| lpCalleeData
|| lpSQOS
|| lpGQOS
)
3501 FIXME("unsupported parameters!\n");
3502 return WS_connect( s
, name
, namelen
);
3505 /***********************************************************************
3508 static BOOL WINAPI
WS2_ConnectEx(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
,
3509 PVOID sendBuf
, DWORD sendBufLen
, LPDWORD sent
, LPOVERLAPPED ov
)
3511 int fd
, ret
, status
;
3515 SetLastError( ERROR_INVALID_PARAMETER
);
3519 fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
3522 SetLastError( WSAENOTSOCK
);
3526 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
3527 s
, name
, debugstr_sockaddr(name
), namelen
, sendBuf
, sendBufLen
, ov
);
3529 ret
= is_fd_bound(fd
, NULL
, NULL
);
3532 SetLastError(ret
== -1 ? wsaErrno() : WSAEINVAL
);
3533 release_sock_fd( s
, fd
);
3537 ret
= do_connect(fd
, name
, namelen
);
3542 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3543 FD_WINE_CONNECTED
|FD_READ
|FD_WRITE
,
3544 FD_CONNECT
|FD_WINE_LISTENING
);
3546 wsabuf
.len
= sendBufLen
;
3547 wsabuf
.buf
= (char*) sendBuf
;
3549 /* WSASend takes care of completion if need be */
3550 if (WSASend(s
, &wsabuf
, sendBuf
? 1 : 0, sent
, 0, ov
, NULL
) != SOCKET_ERROR
)
3551 goto connection_success
;
3553 else if (ret
== WSAEINPROGRESS
)
3555 struct ws2_async
*wsa
;
3556 ULONG_PTR cvalue
= (((ULONG_PTR
)ov
->hEvent
& 1) == 0) ? (ULONG_PTR
)ov
: 0;
3558 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3560 FD_WINE_CONNECTED
|FD_WINE_LISTENING
);
3562 /* Indirectly call WSASend */
3563 if (!(wsa
= (struct ws2_async
*)alloc_async_io( offsetof( struct ws2_async
, iovec
[1] ), WS2_async_send
)))
3565 SetLastError(WSAEFAULT
);
3569 IO_STATUS_BLOCK
*iosb
= (IO_STATUS_BLOCK
*)ov
;
3570 iosb
->u
.Status
= STATUS_PENDING
;
3571 iosb
->Information
= 0;
3573 wsa
->hSocket
= SOCKET2HANDLE(s
);
3575 wsa
->addrlen
.val
= 0;
3577 wsa
->lpFlags
= &wsa
->flags
;
3578 wsa
->control
= NULL
;
3579 wsa
->n_iovecs
= sendBuf
? 1 : 0;
3580 wsa
->first_iovec
= 0;
3581 wsa
->completion_func
= NULL
;
3582 wsa
->iovec
[0].iov_base
= sendBuf
;
3583 wsa
->iovec
[0].iov_len
= sendBufLen
;
3585 status
= register_async( ASYNC_TYPE_WRITE
, wsa
->hSocket
, &wsa
->io
, ov
->hEvent
,
3586 NULL
, (void *)cvalue
, iosb
);
3587 if (status
!= STATUS_PENDING
) HeapFree(GetProcessHeap(), 0, wsa
);
3589 /* If the connect already failed */
3590 if (status
== STATUS_PIPE_DISCONNECTED
)
3592 ov
->Internal
= _get_sock_error(s
, FD_CONNECT_BIT
);
3593 ov
->InternalHigh
= 0;
3594 if (cvalue
) WS_AddCompletion( s
, cvalue
, ov
->Internal
, ov
->InternalHigh
);
3595 if (ov
->hEvent
) NtSetEvent( ov
->hEvent
, NULL
);
3596 status
= STATUS_PENDING
;
3598 SetLastError( NtStatusToWSAError(status
) );
3606 release_sock_fd( s
, fd
);
3610 release_sock_fd( s
, fd
);
3614 /***********************************************************************
3617 static BOOL WINAPI
WS2_DisconnectEx( SOCKET s
, LPOVERLAPPED ov
, DWORD flags
, DWORD reserved
)
3619 TRACE( "socket %04lx, ov %p, flags 0x%x, reserved 0x%x\n", s
, ov
, flags
, reserved
);
3621 if (flags
& TF_REUSE_SOCKET
)
3622 FIXME( "Reusing socket not supported yet\n" );
3626 ov
->Internal
= STATUS_PENDING
;
3627 ov
->InternalHigh
= 0;
3630 return !WS_shutdown( s
, SD_BOTH
);
3633 /***********************************************************************
3634 * getpeername (WS2_32.5)
3636 int WINAPI
WS_getpeername(SOCKET s
, struct WS_sockaddr
*name
, int *namelen
)
3641 TRACE("socket %04lx, ptr %p, len %08x\n", s
, name
, namelen
? *namelen
: 0);
3643 fd
= get_sock_fd( s
, 0, NULL
);
3648 union generic_unix_sockaddr uaddr
;
3649 socklen_t uaddrlen
= sizeof(uaddr
);
3651 if (getpeername(fd
, &uaddr
.addr
, &uaddrlen
) == 0)
3653 if (!name
|| !namelen
)
3654 SetLastError(WSAEFAULT
);
3655 else if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
3656 /* The buffer was too small */
3657 SetLastError(WSAEFAULT
);
3661 TRACE("=> %s\n", debugstr_sockaddr(name
));
3665 SetLastError(wsaErrno());
3666 release_sock_fd( s
, fd
);
3671 /* When binding to an UDP address with filter support the getsockname call on the socket
3672 * will always return 0.0.0.0 instead of the filtered interface address. This function
3673 * checks if the socket is interface-bound on UDP and return the correct address.
3674 * This is required because applications often do a bind() with port zero followed by a
3675 * getsockname() to retrieve the port and address acquired.
3677 static void interface_bind_check(int fd
, struct sockaddr_in
*addr
)
3679 #if !defined(IP_BOUND_IF) && !defined(LINUX_BOUND_IF)
3682 unsigned int ifindex
;
3686 /* Check for IPv4, address 0.0.0.0 and UDP socket */
3687 if (addr
->sin_family
!= AF_INET
|| addr
->sin_addr
.s_addr
!= 0)
3689 if (_get_fd_type(fd
) != SOCK_DGRAM
)
3692 len
= sizeof(ifindex
);
3693 #if defined(IP_BOUND_IF)
3694 ret
= getsockopt(fd
, IPPROTO_IP
, IP_BOUND_IF
, &ifindex
, &len
);
3695 #elif defined(LINUX_BOUND_IF)
3696 ret
= getsockopt(fd
, IPPROTO_IP
, IP_UNICAST_IF
, &ifindex
, &len
);
3697 if (!ret
) ifindex
= ntohl(ifindex
);
3701 PIP_ADAPTER_INFO adapters
, adapter
;
3704 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
3706 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
3707 if (adapters
&& GetAdaptersInfo(adapters
, &adap_size
) == NO_ERROR
)
3709 /* Search the IPv4 adapter list for the appropriate bound interface */
3710 for (adapter
= adapters
; adapter
!= NULL
; adapter
= adapter
->Next
)
3712 in_addr_t adapter_addr
;
3713 if (adapter
->Index
!= ifindex
) continue;
3715 adapter_addr
= inet_addr(adapter
->IpAddressList
.IpAddress
.String
);
3716 addr
->sin_addr
.s_addr
= adapter_addr
;
3717 TRACE("reporting interface address from adapter %d\n", ifindex
);
3721 HeapFree(GetProcessHeap(), 0, adapters
);
3726 /***********************************************************************
3727 * getsockname (WS2_32.6)
3729 int WINAPI
WS_getsockname(SOCKET s
, struct WS_sockaddr
*name
, int *namelen
)
3734 TRACE("socket %04lx, ptr %p, len %08x\n", s
, name
, namelen
? *namelen
: 0);
3736 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3737 if( (name
== NULL
) || (namelen
== NULL
) )
3739 SetLastError( WSAEFAULT
);
3740 return SOCKET_ERROR
;
3743 fd
= get_sock_fd( s
, 0, NULL
);
3748 union generic_unix_sockaddr uaddr
;
3750 int bound
= is_fd_bound(fd
, &uaddr
, &uaddrlen
);
3754 SetLastError(bound
== -1 ? wsaErrno() : WSAEINVAL
);
3756 else if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
3758 /* The buffer was too small */
3759 SetLastError(WSAEFAULT
);
3763 interface_bind_check(fd
, (struct sockaddr_in
*) &uaddr
);
3764 if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
3766 /* The buffer was too small */
3767 SetLastError(WSAEFAULT
);
3772 TRACE("=> %s\n", debugstr_sockaddr(name
));
3775 release_sock_fd( s
, fd
);
3780 /***********************************************************************
3781 * getsockopt (WS2_32.7)
3783 INT WINAPI
WS_getsockopt(SOCKET s
, INT level
,
3784 INT optname
, char *optval
, INT
*optlen
)
3789 TRACE("(socket %04lx, %s, optval %s, optlen %p (%d))\n", s
,
3790 debugstr_sockopt(level
, optname
), debugstr_optval(optval
, 0),
3791 optlen
, optlen
? *optlen
: 0);
3799 /* Handle common cases. The special cases are below, sorted
3801 case WS_SO_BROADCAST
:
3803 case WS_SO_KEEPALIVE
:
3804 case WS_SO_OOBINLINE
:
3806 case WS_SO_REUSEADDR
:
3808 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3809 return SOCKET_ERROR
;
3810 convert_sockopt(&level
, &optname
);
3811 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3813 SetLastError(wsaErrno());
3816 release_sock_fd( s
, fd
);
3818 case WS_SO_ACCEPTCONN
:
3819 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3820 return SOCKET_ERROR
;
3821 if (getsockopt(fd
, SOL_SOCKET
, SO_ACCEPTCONN
, optval
, (socklen_t
*)optlen
) != 0 )
3823 SetLastError(wsaErrno());
3828 /* BSD returns != 0 while Windows return exact == 1 */
3829 if (*(int *)optval
) *(int *)optval
= 1;
3831 release_sock_fd( s
, fd
);
3833 case WS_SO_BSP_STATE
:
3835 int req_size
, addr_size
;
3836 WSAPROTOCOL_INFOW infow
;
3837 CSADDR_INFO
*csinfo
;
3839 ret
= ws_protocol_info(s
, TRUE
, &infow
, &addr_size
);
3842 if (infow
.iAddressFamily
== WS_AF_INET
)
3843 addr_size
= sizeof(struct sockaddr_in
);
3844 else if (infow
.iAddressFamily
== WS_AF_INET6
)
3845 addr_size
= sizeof(struct sockaddr_in6
);
3848 FIXME("Family %d is unsupported for SO_BSP_STATE\n", infow
.iAddressFamily
);
3849 SetLastError(WSAEAFNOSUPPORT
);
3850 return SOCKET_ERROR
;
3853 req_size
= sizeof(CSADDR_INFO
) + addr_size
* 2;
3854 if (*optlen
< req_size
)
3857 SetLastError(WSAEFAULT
);
3861 union generic_unix_sockaddr uaddr
;
3864 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3865 return SOCKET_ERROR
;
3867 csinfo
= (CSADDR_INFO
*) optval
;
3869 /* Check if the sock is bound */
3870 if (is_fd_bound(fd
, &uaddr
, &uaddrlen
) == 1)
3872 csinfo
->LocalAddr
.lpSockaddr
=
3873 (LPSOCKADDR
) (optval
+ sizeof(CSADDR_INFO
));
3874 ws_sockaddr_u2ws(&uaddr
.addr
, csinfo
->LocalAddr
.lpSockaddr
, &addr_size
);
3875 csinfo
->LocalAddr
.iSockaddrLength
= addr_size
;
3879 csinfo
->LocalAddr
.lpSockaddr
= NULL
;
3880 csinfo
->LocalAddr
.iSockaddrLength
= 0;
3883 /* Check if the sock is connected */
3884 if (!getpeername(fd
, &uaddr
.addr
, &uaddrlen
) &&
3885 is_sockaddr_bound(&uaddr
.addr
, uaddrlen
))
3887 csinfo
->RemoteAddr
.lpSockaddr
=
3888 (LPSOCKADDR
) (optval
+ sizeof(CSADDR_INFO
) + addr_size
);
3889 ws_sockaddr_u2ws(&uaddr
.addr
, csinfo
->RemoteAddr
.lpSockaddr
, &addr_size
);
3890 csinfo
->RemoteAddr
.iSockaddrLength
= addr_size
;
3894 csinfo
->RemoteAddr
.lpSockaddr
= NULL
;
3895 csinfo
->RemoteAddr
.iSockaddrLength
= 0;
3898 csinfo
->iSocketType
= infow
.iSocketType
;
3899 csinfo
->iProtocol
= infow
.iProtocol
;
3900 release_sock_fd( s
, fd
);
3903 return ret
? 0 : SOCKET_ERROR
;
3905 case WS_SO_DONTLINGER
:
3907 struct linger lingval
;
3908 socklen_t len
= sizeof(struct linger
);
3910 if (!optlen
|| *optlen
< sizeof(BOOL
)|| !optval
)
3912 SetLastError(WSAEFAULT
);
3913 return SOCKET_ERROR
;
3915 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3916 return SOCKET_ERROR
;
3918 if (getsockopt(fd
, SOL_SOCKET
, SO_LINGER
, &lingval
, &len
) != 0 )
3920 SetLastError(wsaErrno());
3925 *(BOOL
*)optval
= !lingval
.l_onoff
;
3926 *optlen
= sizeof(BOOL
);
3929 release_sock_fd( s
, fd
);
3933 case WS_SO_CONNECT_TIME
:
3935 static int pretendtime
= 0;
3936 struct WS_sockaddr addr
;
3937 int len
= sizeof(addr
);
3939 if (!optlen
|| *optlen
< sizeof(DWORD
) || !optval
)
3941 SetLastError(WSAEFAULT
);
3942 return SOCKET_ERROR
;
3944 if (WS_getpeername(s
, &addr
, &len
) == SOCKET_ERROR
)
3945 *(DWORD
*)optval
= ~0u;
3948 if (!pretendtime
) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3949 *(DWORD
*)optval
= pretendtime
++;
3951 *optlen
= sizeof(DWORD
);
3954 /* As mentioned in setsockopt, Windows ignores this, so we
3955 * always return true here */
3956 case WS_SO_DONTROUTE
:
3957 if (!optlen
|| *optlen
< sizeof(BOOL
) || !optval
)
3959 SetLastError(WSAEFAULT
);
3960 return SOCKET_ERROR
;
3962 *(BOOL
*)optval
= TRUE
;
3963 *optlen
= sizeof(BOOL
);
3968 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3969 return SOCKET_ERROR
;
3970 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, optval
, (socklen_t
*)optlen
) != 0 )
3972 SetLastError(wsaErrno());
3975 release_sock_fd( s
, fd
);
3977 /* The wineserver may have swallowed the error before us */
3978 if (!ret
&& *(int*) optval
== 0)
3980 int i
, events
[FD_MAX_EVENTS
];
3981 _get_sock_errors(s
, events
);
3982 for (i
= 0; i
< FD_MAX_EVENTS
; i
++)
3986 events
[i
] = NtStatusToWSAError(events
[i
]);
3987 TRACE("returning SO_ERROR %d from wine server\n", events
[i
]);
3988 *(int*) optval
= events
[i
];
3998 struct linger lingval
;
3999 socklen_t len
= sizeof(struct linger
);
4001 /* struct linger and LINGER have different sizes */
4002 if (!optlen
|| *optlen
< sizeof(LINGER
) || !optval
)
4004 SetLastError(WSAEFAULT
);
4005 return SOCKET_ERROR
;
4007 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4008 return SOCKET_ERROR
;
4010 if (_get_fd_type(fd
) == SOCK_DGRAM
)
4012 SetLastError(WSAENOPROTOOPT
);
4015 else if (getsockopt(fd
, SOL_SOCKET
, SO_LINGER
, &lingval
, &len
) != 0)
4017 SetLastError(wsaErrno());
4022 ((LINGER
*)optval
)->l_onoff
= lingval
.l_onoff
;
4023 ((LINGER
*)optval
)->l_linger
= lingval
.l_linger
;
4024 *optlen
= sizeof(struct linger
);
4027 release_sock_fd( s
, fd
);
4031 case WS_SO_MAX_MSG_SIZE
:
4032 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
4034 SetLastError(WSAEFAULT
);
4035 return SOCKET_ERROR
;
4037 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
4038 *(int *)optval
= 65507;
4039 *optlen
= sizeof(int);
4042 /* SO_OPENTYPE does not require a valid socket handle. */
4043 case WS_SO_OPENTYPE
:
4044 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
4046 SetLastError(WSAEFAULT
);
4047 return SOCKET_ERROR
;
4049 *(int *)optval
= get_per_thread_data()->opentype
;
4050 *optlen
= sizeof(int);
4051 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval
) );
4053 case WS_SO_PROTOCOL_INFOA
:
4054 case WS_SO_PROTOCOL_INFOW
:
4057 WSAPROTOCOL_INFOW infow
;
4059 ret
= ws_protocol_info(s
, optname
== WS_SO_PROTOCOL_INFOW
, &infow
, &size
);
4062 if (!optlen
|| !optval
|| *optlen
< size
)
4064 if(optlen
) *optlen
= size
;
4066 SetLastError(WSAEFAULT
);
4069 memcpy(optval
, &infow
, size
);
4071 return ret
? 0 : SOCKET_ERROR
;
4073 case WS_SO_RCVTIMEO
:
4074 case WS_SO_SNDTIMEO
:
4078 if (!optlen
|| *optlen
< sizeof(int)|| !optval
)
4080 SetLastError(WSAEFAULT
);
4081 return SOCKET_ERROR
;
4083 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4084 return SOCKET_ERROR
;
4086 timeout
= get_rcvsnd_timeo(fd
, optname
== WS_SO_RCVTIMEO
);
4087 *(int *)optval
= timeout
<= UINT_MAX
? timeout
: UINT_MAX
;
4089 release_sock_fd( s
, fd
);
4095 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
4097 SetLastError(WSAEFAULT
);
4098 return SOCKET_ERROR
;
4100 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4101 return SOCKET_ERROR
;
4103 sock_type
= _get_fd_type(fd
);
4104 if (sock_type
== -1)
4106 SetLastError(wsaErrno());
4110 (*(int *)optval
) = convert_socktype_u2w(sock_type
);
4112 release_sock_fd( s
, fd
);
4116 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname
);
4117 SetLastError(WSAENOPROTOOPT
);
4118 return SOCKET_ERROR
;
4119 } /* end switch(optname) */
4120 }/* end case WS_SOL_SOCKET */
4122 case WS_NSPROTO_IPX
:
4124 struct WS_sockaddr_ipx addr
;
4125 IPX_ADDRESS_DATA
*data
;
4130 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
4132 if(getsockopt(fd
, SOL_IPX
, IPX_TYPE
, optval
, (socklen_t
*)optlen
) == -1)
4139 socklen_t len
=sizeof(struct ipx
);
4140 if(getsockopt(fd
, 0, SO_DEFAULT_HEADERS
, &val
, &len
) == -1 )
4143 *optval
= (int)val
.ipx_pt
;
4146 TRACE("ptype: %d (fd: %d)\n", *(int*)optval
, fd
);
4147 release_sock_fd( s
, fd
);
4150 case WS_IPX_ADDRESS
:
4152 * On a Win2000 system with one network card there are usually
4153 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
4154 * Using this call you can then retrieve info about this all.
4155 * In case of Linux it is a bit different. Usually you have
4156 * only "one" device active and further it is not possible to
4157 * query things like the linkspeed.
4159 FIXME("IPX_ADDRESS\n");
4160 namelen
= sizeof(struct WS_sockaddr_ipx
);
4161 memset(&addr
, 0, sizeof(struct WS_sockaddr_ipx
));
4162 WS_getsockname(s
, (struct WS_sockaddr
*)&addr
, &namelen
);
4164 data
= (IPX_ADDRESS_DATA
*)optval
;
4165 memcpy(data
->nodenum
,addr
.sa_nodenum
,sizeof(data
->nodenum
));
4166 memcpy(data
->netnum
,addr
.sa_netnum
,sizeof(data
->netnum
));
4167 data
->adapternum
= 0;
4168 data
->wan
= FALSE
; /* We are not on a wan for now .. */
4169 data
->status
= FALSE
; /* Since we are not on a wan, the wan link isn't up */
4170 data
->maxpkt
= 1467; /* This value is the default one, at least on Win2k/WinXP */
4171 data
->linkspeed
= 100000; /* Set the line speed in 100bit/s to 10 Mbit;
4172 * note 1MB = 1000kB in this case */
4175 case WS_IPX_MAX_ADAPTER_NUM
:
4176 FIXME("IPX_MAX_ADAPTER_NUM\n");
4177 *(int*)optval
= 1; /* As noted under IPX_ADDRESS we have just one card. */
4181 FIXME("IPX optname:%x\n", optname
);
4182 return SOCKET_ERROR
;
4183 }/* end switch(optname) */
4184 } /* end case WS_NSPROTO_IPX */
4188 #define MAX_IRDA_DEVICES 10
4193 case WS_IRLMP_ENUMDEVICES
:
4195 char buf
[sizeof(struct irda_device_list
) +
4196 (MAX_IRDA_DEVICES
- 1) * sizeof(struct irda_device_info
)];
4198 socklen_t len
= sizeof(buf
);
4200 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4201 return SOCKET_ERROR
;
4202 res
= getsockopt( fd
, SOL_IRLMP
, IRLMP_ENUMDEVICES
, buf
, &len
);
4203 release_sock_fd( s
, fd
);
4206 SetLastError(wsaErrno());
4207 return SOCKET_ERROR
;
4211 struct irda_device_list
*src
= (struct irda_device_list
*)buf
;
4212 DEVICELIST
*dst
= (DEVICELIST
*)optval
;
4213 INT needed
= sizeof(DEVICELIST
);
4217 needed
+= (src
->len
- 1) * sizeof(IRDA_DEVICE_INFO
);
4218 if (*optlen
< needed
)
4220 SetLastError(WSAEFAULT
);
4221 return SOCKET_ERROR
;
4224 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src
->len
);
4225 dst
->numDevice
= src
->len
;
4226 for (i
= 0; i
< src
->len
; i
++)
4228 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
4229 src
->dev
[i
].saddr
, src
->dev
[i
].daddr
,
4230 src
->dev
[i
].info
, src
->dev
[i
].hints
[0],
4231 src
->dev
[i
].hints
[1]);
4232 memcpy( dst
->Device
[i
].irdaDeviceID
,
4234 sizeof(dst
->Device
[i
].irdaDeviceID
) ) ;
4235 memcpy( dst
->Device
[i
].irdaDeviceName
,
4237 sizeof(dst
->Device
[i
].irdaDeviceName
) ) ;
4238 memcpy( &dst
->Device
[i
].irdaDeviceHints1
,
4239 &src
->dev
[i
].hints
[0],
4240 sizeof(dst
->Device
[i
].irdaDeviceHints1
) ) ;
4241 memcpy( &dst
->Device
[i
].irdaDeviceHints2
,
4242 &src
->dev
[i
].hints
[1],
4243 sizeof(dst
->Device
[i
].irdaDeviceHints2
) ) ;
4244 dst
->Device
[i
].irdaCharSet
= src
->dev
[i
].charset
;
4250 FIXME("IrDA optname:0x%x\n", optname
);
4251 return SOCKET_ERROR
;
4253 break; /* case WS_SOL_IRLMP */
4254 #undef MAX_IRDA_DEVICES
4257 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4258 case WS_IPPROTO_TCP
:
4261 case WS_TCP_NODELAY
:
4262 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4263 return SOCKET_ERROR
;
4264 convert_sockopt(&level
, &optname
);
4265 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
4267 SetLastError(wsaErrno());
4270 release_sock_fd( s
, fd
);
4273 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname
);
4274 return SOCKET_ERROR
;
4279 case WS_IP_ADD_MEMBERSHIP
:
4280 case WS_IP_DROP_MEMBERSHIP
:
4284 case WS_IP_MULTICAST_IF
:
4285 case WS_IP_MULTICAST_LOOP
:
4286 case WS_IP_MULTICAST_TTL
:
4293 #ifdef IP_UNICAST_IF
4294 case WS_IP_UNICAST_IF
:
4296 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4297 return SOCKET_ERROR
;
4298 convert_sockopt(&level
, &optname
);
4299 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
4301 SetLastError(wsaErrno());
4304 release_sock_fd( s
, fd
);
4306 case WS_IP_DONTFRAGMENT
:
4307 return get_dont_fragment(s
, IPPROTO_IP
, (BOOL
*)optval
) ? 0 : SOCKET_ERROR
;
4309 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname
);
4310 return SOCKET_ERROR
;
4312 case WS_IPPROTO_IPV6
:
4315 #ifdef IPV6_ADD_MEMBERSHIP
4316 case WS_IPV6_ADD_MEMBERSHIP
:
4318 #ifdef IPV6_DROP_MEMBERSHIP
4319 case WS_IPV6_DROP_MEMBERSHIP
:
4321 case WS_IPV6_MULTICAST_IF
:
4322 case WS_IPV6_MULTICAST_HOPS
:
4323 case WS_IPV6_MULTICAST_LOOP
:
4324 case WS_IPV6_UNICAST_HOPS
:
4325 case WS_IPV6_V6ONLY
:
4326 #ifdef IPV6_UNICAST_IF
4327 case WS_IPV6_UNICAST_IF
:
4329 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4330 return SOCKET_ERROR
;
4331 convert_sockopt(&level
, &optname
);
4332 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
4334 SetLastError(wsaErrno());
4337 release_sock_fd( s
, fd
);
4339 case WS_IPV6_DONTFRAG
:
4340 return get_dont_fragment(s
, IPPROTO_IPV6
, (BOOL
*)optval
) ? 0 : SOCKET_ERROR
;
4342 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname
);
4343 return SOCKET_ERROR
;
4346 WARN("Unknown level: 0x%08x\n", level
);
4347 SetLastError(WSAEINVAL
);
4348 return SOCKET_ERROR
;
4349 } /* end switch(level) */
4352 /***********************************************************************
4355 WS_u_long WINAPI
WS_htonl(WS_u_long hostlong
)
4357 return htonl(hostlong
);
4361 /***********************************************************************
4364 WS_u_short WINAPI
WS_htons(WS_u_short hostshort
)
4366 return htons(hostshort
);
4369 /***********************************************************************
4370 * WSAHtonl (WS2_32.46)
4371 * From MSDN description of error codes, this function should also
4372 * check if WinSock has been initialized and the socket is a valid
4373 * socket. But why? This function only translates a host byte order
4374 * u_long into a network byte order u_long...
4376 int WINAPI
WSAHtonl(SOCKET s
, WS_u_long hostlong
, WS_u_long
*lpnetlong
)
4380 *lpnetlong
= htonl(hostlong
);
4383 SetLastError(WSAEFAULT
);
4384 return SOCKET_ERROR
;
4387 /***********************************************************************
4388 * WSAHtons (WS2_32.47)
4389 * From MSDN description of error codes, this function should also
4390 * check if WinSock has been initialized and the socket is a valid
4391 * socket. But why? This function only translates a host byte order
4392 * u_short into a network byte order u_short...
4394 int WINAPI
WSAHtons(SOCKET s
, WS_u_short hostshort
, WS_u_short
*lpnetshort
)
4399 *lpnetshort
= htons(hostshort
);
4402 SetLastError(WSAEFAULT
);
4403 return SOCKET_ERROR
;
4407 /***********************************************************************
4408 * inet_addr (WS2_32.11)
4410 WS_u_long WINAPI
WS_inet_addr(const char *cp
)
4412 if (!cp
) return INADDR_NONE
;
4413 return inet_addr(cp
);
4417 /***********************************************************************
4420 WS_u_long WINAPI
WS_ntohl(WS_u_long netlong
)
4422 return ntohl(netlong
);
4426 /***********************************************************************
4429 WS_u_short WINAPI
WS_ntohs(WS_u_short netshort
)
4431 return ntohs(netshort
);
4435 /***********************************************************************
4436 * inet_ntoa (WS2_32.12)
4438 char* WINAPI
WS_inet_ntoa(struct WS_in_addr in
)
4440 unsigned int long_ip
= ntohl(in
.WS_s_addr
);
4441 struct per_thread_data
*data
= get_per_thread_data();
4443 sprintf( data
->ntoa_buffer
, "%u.%u.%u.%u",
4444 (long_ip
>> 24) & 0xff,
4445 (long_ip
>> 16) & 0xff,
4446 (long_ip
>> 8) & 0xff,
4449 return data
->ntoa_buffer
;
4452 static const char *debugstr_wsaioctl(DWORD code
)
4454 const char *name
= NULL
, *buf_type
, *family
;
4456 #define IOCTL_NAME(x) case x: name = #x; break
4459 IOCTL_NAME(WS_FIONBIO
);
4460 IOCTL_NAME(WS_FIONREAD
);
4461 IOCTL_NAME(WS_SIOCATMARK
);
4462 /* IOCTL_NAME(WS_SIO_ACQUIRE_PORT_RESERVATION); */
4463 IOCTL_NAME(WS_SIO_ADDRESS_LIST_CHANGE
);
4464 IOCTL_NAME(WS_SIO_ADDRESS_LIST_QUERY
);
4465 IOCTL_NAME(WS_SIO_ASSOCIATE_HANDLE
);
4466 /* IOCTL_NAME(WS_SIO_ASSOCIATE_PORT_RESERVATION);
4467 IOCTL_NAME(WS_SIO_BASE_HANDLE);
4468 IOCTL_NAME(WS_SIO_BSP_HANDLE);
4469 IOCTL_NAME(WS_SIO_BSP_HANDLE_SELECT);
4470 IOCTL_NAME(WS_SIO_BSP_HANDLE_POLL);
4471 IOCTL_NAME(WS_SIO_CHK_QOS); */
4472 IOCTL_NAME(WS_SIO_ENABLE_CIRCULAR_QUEUEING
);
4473 IOCTL_NAME(WS_SIO_FIND_ROUTE
);
4474 IOCTL_NAME(WS_SIO_FLUSH
);
4475 IOCTL_NAME(WS_SIO_GET_BROADCAST_ADDRESS
);
4476 IOCTL_NAME(WS_SIO_GET_EXTENSION_FUNCTION_POINTER
);
4477 IOCTL_NAME(WS_SIO_GET_GROUP_QOS
);
4478 IOCTL_NAME(WS_SIO_GET_INTERFACE_LIST
);
4479 /* IOCTL_NAME(WS_SIO_GET_INTERFACE_LIST_EX); */
4480 IOCTL_NAME(WS_SIO_GET_QOS
);
4481 /* IOCTL_NAME(WS_SIO_IDEAL_SEND_BACKLOG_CHANGE);
4482 IOCTL_NAME(WS_SIO_IDEAL_SEND_BACKLOG_QUERY); */
4483 IOCTL_NAME(WS_SIO_KEEPALIVE_VALS
);
4484 IOCTL_NAME(WS_SIO_MULTIPOINT_LOOPBACK
);
4485 IOCTL_NAME(WS_SIO_MULTICAST_SCOPE
);
4486 /* IOCTL_NAME(WS_SIO_QUERY_RSS_SCALABILITY_INFO);
4487 IOCTL_NAME(WS_SIO_QUERY_WFP_ALE_ENDPOINT_HANDLE); */
4488 IOCTL_NAME(WS_SIO_RCVALL
);
4489 IOCTL_NAME(WS_SIO_RCVALL_IGMPMCAST
);
4490 IOCTL_NAME(WS_SIO_RCVALL_MCAST
);
4491 /* IOCTL_NAME(WS_SIO_RELEASE_PORT_RESERVATION); */
4492 IOCTL_NAME(WS_SIO_ROUTING_INTERFACE_CHANGE
);
4493 IOCTL_NAME(WS_SIO_ROUTING_INTERFACE_QUERY
);
4494 IOCTL_NAME(WS_SIO_SET_COMPATIBILITY_MODE
);
4495 IOCTL_NAME(WS_SIO_SET_GROUP_QOS
);
4496 IOCTL_NAME(WS_SIO_SET_QOS
);
4497 IOCTL_NAME(WS_SIO_TRANSLATE_HANDLE
);
4498 IOCTL_NAME(WS_SIO_UDP_CONNRESET
);
4505 /* If this is not a known code split its bits */
4506 switch(code
& 0x18000000)
4511 case WS_IOC_PROTOCOL
:
4512 family
= "IOC_PROTOCOL";
4515 family
= "IOC_VENDOR";
4517 default: /* WS_IOC_UNIX */
4519 BYTE size
= (code
>> 16) & WS_IOCPARM_MASK
;
4520 char x
= (code
& 0xff00) >> 8;
4521 BYTE y
= code
& 0xff;
4524 switch (code
& (WS_IOC_VOID
|WS_IOC_INOUT
))
4528 sprintf(args
, "%d, %d", x
, y
);
4532 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
4536 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
4540 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
4543 return wine_dbg_sprintf("%s(%s)", buf_type
, args
);
4547 /* We are different from WS_IOC_UNIX. */
4548 switch (code
& (WS_IOC_VOID
|WS_IOC_INOUT
))
4551 buf_type
= "_WSAIO";
4554 buf_type
= "_WSAIORW";
4557 buf_type
= "_WSAIOW";
4560 buf_type
= "_WSAIOR";
4567 return wine_dbg_sprintf("%s(%s, %d)", buf_type
, family
,
4568 (USHORT
)(code
& 0xffff));
4571 /* do an ioctl call through the server */
4572 static DWORD
server_ioctl_sock( SOCKET s
, DWORD code
, LPVOID in_buff
, DWORD in_size
,
4573 LPVOID out_buff
, DWORD out_size
, LPDWORD ret_size
,
4574 LPWSAOVERLAPPED overlapped
,
4575 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
4577 HANDLE event
= overlapped
? overlapped
->hEvent
: 0;
4578 HANDLE handle
= SOCKET2HANDLE( s
);
4579 struct ws2_async
*wsa
= NULL
;
4580 IO_STATUS_BLOCK
*io
= (PIO_STATUS_BLOCK
)overlapped
, iosb
;
4581 void *cvalue
= NULL
;
4586 if (!(wsa
= (struct ws2_async
*)alloc_async_io( sizeof(*wsa
), NULL
)))
4587 return WSA_NOT_ENOUGH_MEMORY
;
4588 wsa
->hSocket
= handle
;
4589 wsa
->user_overlapped
= overlapped
;
4590 wsa
->completion_func
= completion
;
4591 if (!io
) io
= &wsa
->local_iosb
;
4596 else if (!((ULONG_PTR
)overlapped
->hEvent
& 1))
4597 cvalue
= overlapped
;
4599 status
= NtDeviceIoControlFile( handle
, event
, wsa
? ws2_async_apc
: NULL
, cvalue
, io
, code
,
4600 in_buff
, in_size
, out_buff
, out_size
);
4601 if (status
== STATUS_NOT_SUPPORTED
)
4603 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
4604 code
, code
>> 16, (code
>> 14) & 3, (code
>> 2) & 0xfff, code
& 3);
4606 else if (status
== STATUS_SUCCESS
)
4607 *ret_size
= io
->Information
; /* "Information" is the size written to the output buffer */
4609 if (status
!= STATUS_PENDING
) RtlFreeHeap( GetProcessHeap(), 0, wsa
);
4611 return NtStatusToWSAError( status
);
4614 /**********************************************************************
4615 * WSAIoctl (WS2_32.50)
4618 INT WINAPI
WSAIoctl(SOCKET s
, DWORD code
, LPVOID in_buff
, DWORD in_size
, LPVOID out_buff
,
4619 DWORD out_size
, LPDWORD ret_size
, LPWSAOVERLAPPED overlapped
,
4620 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
4623 DWORD status
= 0, total
= 0;
4625 TRACE("%04lx, %s, %p, %d, %p, %d, %p, %p, %p\n",
4626 s
, debugstr_wsaioctl(code
), in_buff
, in_size
, out_buff
, out_size
, ret_size
, overlapped
, completion
);
4631 if (in_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(in_buff
))
4633 SetLastError(WSAEFAULT
);
4634 return SOCKET_ERROR
;
4636 TRACE("-> FIONBIO (%x)\n", *(WS_u_long
*)in_buff
);
4637 if (_get_sock_mask(s
))
4639 /* AsyncSelect()'ed sockets are always nonblocking */
4640 if (!*(WS_u_long
*)in_buff
) status
= WSAEINVAL
;
4643 if (*(WS_u_long
*)in_buff
)
4644 _enable_event(SOCKET2HANDLE(s
), 0, FD_WINE_NONBLOCKING
, 0);
4646 _enable_event(SOCKET2HANDLE(s
), 0, 0, FD_WINE_NONBLOCKING
);
4651 if (out_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(out_buff
))
4653 SetLastError(WSAEFAULT
);
4654 return SOCKET_ERROR
;
4656 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
4657 if (ioctl(fd
, FIONREAD
, out_buff
) == -1)
4658 status
= wsaErrno();
4659 release_sock_fd( s
, fd
);
4665 unsigned int oob
= 0, atmark
= 0;
4666 socklen_t oobsize
= sizeof(int);
4667 if (out_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(out_buff
))
4669 SetLastError(WSAEFAULT
);
4670 return SOCKET_ERROR
;
4672 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
4673 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
4674 if ((getsockopt(fd
, SOL_SOCKET
, SO_OOBINLINE
, &oob
, &oobsize
) == -1)
4675 || (!oob
&& ioctl(fd
, SIOCATMARK
, &atmark
) == -1))
4676 status
= wsaErrno();
4679 /* The SIOCATMARK value read from ioctl() is reversed
4680 * because BSD returns TRUE if it's in the OOB mark
4681 * while Windows returns TRUE if there are NO OOB bytes.
4683 (*(WS_u_long
*) out_buff
) = oob
|| !atmark
;
4686 release_sock_fd( s
, fd
);
4691 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
4692 SetLastError(WSAEINVAL
);
4693 return SOCKET_ERROR
;
4695 case WS_SIO_GET_INTERFACE_LIST
:
4697 INTERFACE_INFO
* intArray
= out_buff
;
4698 DWORD size
, numInt
= 0, apiReturn
;
4700 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
4702 if (!out_buff
|| !ret_size
)
4704 SetLastError(WSAEFAULT
);
4705 return SOCKET_ERROR
;
4708 fd
= get_sock_fd( s
, 0, NULL
);
4709 if (fd
== -1) return SOCKET_ERROR
;
4711 apiReturn
= GetAdaptersInfo(NULL
, &size
);
4712 if (apiReturn
== ERROR_BUFFER_OVERFLOW
)
4714 PIP_ADAPTER_INFO table
= HeapAlloc(GetProcessHeap(),0,size
);
4718 if (GetAdaptersInfo(table
, &size
) == NO_ERROR
)
4720 PIP_ADAPTER_INFO ptr
;
4722 for (ptr
= table
, numInt
= 0; ptr
; ptr
= ptr
->Next
)
4724 unsigned int addr
, mask
, bcast
;
4725 struct ifreq ifInfo
;
4727 /* Skip interfaces without an IPv4 address. */
4728 if (ptr
->IpAddressList
.IpAddress
.String
[0] == '\0')
4731 if ((numInt
+ 1)*sizeof(INTERFACE_INFO
)/sizeof(IP_ADAPTER_INFO
) > out_size
)
4733 WARN("Buffer too small = %u, out_size = %u\n", numInt
+ 1, out_size
);
4738 /* Socket Status Flags */
4739 lstrcpynA(ifInfo
.ifr_name
, ptr
->AdapterName
, IFNAMSIZ
);
4740 if (ioctl(fd
, SIOCGIFFLAGS
, &ifInfo
) < 0)
4742 ERR("Error obtaining status flags for socket!\n");
4748 /* set flags; the values of IFF_* are not the same
4749 under Linux and Windows, therefore must generate
4751 intArray
->iiFlags
= 0;
4752 if (ifInfo
.ifr_flags
& IFF_BROADCAST
)
4753 intArray
->iiFlags
|= WS_IFF_BROADCAST
;
4754 #ifdef IFF_POINTOPOINT
4755 if (ifInfo
.ifr_flags
& IFF_POINTOPOINT
)
4756 intArray
->iiFlags
|= WS_IFF_POINTTOPOINT
;
4758 if (ifInfo
.ifr_flags
& IFF_LOOPBACK
)
4759 intArray
->iiFlags
|= WS_IFF_LOOPBACK
;
4760 if (ifInfo
.ifr_flags
& IFF_UP
)
4761 intArray
->iiFlags
|= WS_IFF_UP
;
4762 if (ifInfo
.ifr_flags
& IFF_MULTICAST
)
4763 intArray
->iiFlags
|= WS_IFF_MULTICAST
;
4766 addr
= inet_addr(ptr
->IpAddressList
.IpAddress
.String
);
4767 mask
= inet_addr(ptr
->IpAddressList
.IpMask
.String
);
4768 bcast
= addr
| ~mask
;
4769 intArray
->iiAddress
.AddressIn
.sin_family
= WS_AF_INET
;
4770 intArray
->iiAddress
.AddressIn
.sin_port
= 0;
4771 intArray
->iiAddress
.AddressIn
.sin_addr
.WS_s_addr
= addr
;
4773 intArray
->iiNetmask
.AddressIn
.sin_family
= WS_AF_INET
;
4774 intArray
->iiNetmask
.AddressIn
.sin_port
= 0;
4775 intArray
->iiNetmask
.AddressIn
.sin_addr
.WS_s_addr
= mask
;
4777 intArray
->iiBroadcastAddress
.AddressIn
.sin_family
= WS_AF_INET
;
4778 intArray
->iiBroadcastAddress
.AddressIn
.sin_port
= 0;
4779 intArray
->iiBroadcastAddress
.AddressIn
.sin_addr
.WS_s_addr
= bcast
;
4786 ERR("Unable to get interface table!\n");
4789 HeapFree(GetProcessHeap(),0,table
);
4791 else status
= WSAEINVAL
;
4793 else if (apiReturn
!= ERROR_NO_DATA
)
4795 ERR("Unable to get interface table!\n");
4798 /* Calculate the size of the array being returned */
4799 total
= sizeof(INTERFACE_INFO
) * numInt
;
4800 release_sock_fd( s
, fd
);
4804 case WS_SIO_ADDRESS_LIST_QUERY
:
4808 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
4812 SetLastError(WSAEFAULT
);
4813 return SOCKET_ERROR
;
4816 if (out_size
&& out_size
< FIELD_OFFSET(SOCKET_ADDRESS_LIST
, Address
[0]))
4819 SetLastError(WSAEINVAL
);
4820 return SOCKET_ERROR
;
4823 if (GetAdaptersInfo(NULL
, &size
) == ERROR_BUFFER_OVERFLOW
)
4825 IP_ADAPTER_INFO
*p
, *table
= HeapAlloc(GetProcessHeap(), 0, size
);
4826 SOCKET_ADDRESS_LIST
*sa_list
;
4827 SOCKADDR_IN
*sockaddr
;
4832 if (!table
|| GetAdaptersInfo(table
, &size
))
4834 HeapFree(GetProcessHeap(), 0, table
);
4839 for (p
= table
, num
= 0; p
; p
= p
->Next
)
4840 if (p
->IpAddressList
.IpAddress
.String
[0]) num
++;
4842 total
= FIELD_OFFSET(SOCKET_ADDRESS_LIST
, Address
[num
]) + num
* sizeof(*sockaddr
);
4843 if (total
> out_size
|| !out_buff
)
4846 HeapFree(GetProcessHeap(), 0, table
);
4852 sa
= sa_list
->Address
;
4853 sockaddr
= (SOCKADDR_IN
*)&sa
[num
];
4854 sa_list
->iAddressCount
= num
;
4856 for (p
= table
, i
= 0; p
; p
= p
->Next
)
4858 if (!p
->IpAddressList
.IpAddress
.String
[0]) continue;
4860 sa
[i
].lpSockaddr
= (SOCKADDR
*)&sockaddr
[i
];
4861 sa
[i
].iSockaddrLength
= sizeof(SOCKADDR
);
4863 sockaddr
[i
].sin_family
= WS_AF_INET
;
4864 sockaddr
[i
].sin_port
= 0;
4865 sockaddr
[i
].sin_addr
.WS_s_addr
= inet_addr(p
->IpAddressList
.IpAddress
.String
);
4869 HeapFree(GetProcessHeap(), 0, table
);
4873 WARN("unable to get IP address list\n");
4880 FIXME("SIO_FLUSH: stub.\n");
4883 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER
:
4885 #define EXTENSION_FUNCTION(x, y) { x, y, #y },
4892 EXTENSION_FUNCTION(WSAID_CONNECTEX
, WS2_ConnectEx
)
4893 EXTENSION_FUNCTION(WSAID_DISCONNECTEX
, WS2_DisconnectEx
)
4894 EXTENSION_FUNCTION(WSAID_ACCEPTEX
, WS2_AcceptEx
)
4895 EXTENSION_FUNCTION(WSAID_GETACCEPTEXSOCKADDRS
, WS2_GetAcceptExSockaddrs
)
4896 EXTENSION_FUNCTION(WSAID_TRANSMITFILE
, WS2_TransmitFile
)
4897 /* EXTENSION_FUNCTION(WSAID_TRANSMITPACKETS, WS2_TransmitPackets) */
4898 EXTENSION_FUNCTION(WSAID_WSARECVMSG
, WS2_WSARecvMsg
)
4899 EXTENSION_FUNCTION(WSAID_WSASENDMSG
, WSASendMsg
)
4901 #undef EXTENSION_FUNCTION
4905 for (i
= 0; i
< sizeof(guid_funcs
) / sizeof(guid_funcs
[0]); i
++)
4907 if (IsEqualGUID(&guid_funcs
[i
].guid
, in_buff
))
4916 TRACE("-> got %s\n", guid_funcs
[i
].name
);
4917 *(void **)out_buff
= guid_funcs
[i
].func_ptr
;
4918 total
= sizeof(void *);
4922 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff
));
4923 status
= WSAEOPNOTSUPP
;
4926 case WS_SIO_KEEPALIVE_VALS
:
4928 struct tcp_keepalive
*k
;
4929 int keepalive
, keepidle
, keepintvl
;
4931 if (!in_buff
|| in_size
< sizeof(struct tcp_keepalive
))
4933 SetLastError(WSAEFAULT
);
4934 return SOCKET_ERROR
;
4938 keepalive
= k
->onoff
? 1 : 0;
4939 keepidle
= max( 1, (k
->keepalivetime
+ 500) / 1000 );
4940 keepintvl
= max( 1, (k
->keepaliveinterval
+ 500) / 1000 );
4942 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive
, keepidle
, keepintvl
);
4944 fd
= get_sock_fd(s
, 0, NULL
);
4945 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&keepalive
, sizeof(int)) == -1)
4947 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPINTVL)
4948 /* these values need to be set only if SO_KEEPALIVE is enabled */
4951 #ifndef TCP_KEEPIDLE
4952 FIXME("ignoring keepalive timeout\n");
4954 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPIDLE
, (void *)&keepidle
, sizeof(int)) == -1)
4958 #ifdef TCP_KEEPINTVL
4959 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPINTVL
, (void *)&keepintvl
, sizeof(int)) == -1)
4962 FIXME("ignoring keepalive interval\n");
4967 FIXME("ignoring keepalive interval and timeout\n");
4969 release_sock_fd(s
, fd
);
4972 case WS_SIO_ROUTING_INTERFACE_QUERY
:
4974 struct WS_sockaddr
*daddr
= (struct WS_sockaddr
*)in_buff
;
4975 struct WS_sockaddr_in
*daddr_in
= (struct WS_sockaddr_in
*)daddr
;
4976 struct WS_sockaddr_in
*saddr_in
= out_buff
;
4977 MIB_IPFORWARDROW row
;
4978 PMIB_IPADDRTABLE ipAddrTable
= NULL
;
4979 DWORD size
, i
, found_index
;
4981 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4983 if (!in_buff
|| in_size
< sizeof(struct WS_sockaddr
) ||
4984 !out_buff
|| out_size
< sizeof(struct WS_sockaddr_in
) || !ret_size
)
4986 SetLastError(WSAEFAULT
);
4987 return SOCKET_ERROR
;
4989 if (daddr
->sa_family
!= WS_AF_INET
)
4991 FIXME("unsupported address family %d\n", daddr
->sa_family
);
4992 status
= WSAEAFNOSUPPORT
;
4995 if (GetBestRoute(daddr_in
->sin_addr
.S_un
.S_addr
, 0, &row
) != NOERROR
||
4996 GetIpAddrTable(NULL
, &size
, FALSE
) != ERROR_INSUFFICIENT_BUFFER
)
5001 ipAddrTable
= HeapAlloc(GetProcessHeap(), 0, size
);
5002 if (GetIpAddrTable(ipAddrTable
, &size
, FALSE
))
5004 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
5008 for (i
= 0, found_index
= ipAddrTable
->dwNumEntries
;
5009 i
< ipAddrTable
->dwNumEntries
; i
++)
5011 if (ipAddrTable
->table
[i
].dwIndex
== row
.dwForwardIfIndex
)
5014 if (found_index
== ipAddrTable
->dwNumEntries
)
5016 ERR("no matching IP address for interface %d\n",
5017 row
.dwForwardIfIndex
);
5018 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
5022 saddr_in
->sin_family
= WS_AF_INET
;
5023 saddr_in
->sin_addr
.S_un
.S_addr
= ipAddrTable
->table
[found_index
].dwAddr
;
5024 saddr_in
->sin_port
= 0;
5025 total
= sizeof(struct WS_sockaddr_in
);
5026 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
5029 case WS_SIO_SET_COMPATIBILITY_MODE
:
5030 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
5031 status
= WSAEOPNOTSUPP
;
5033 case WS_SIO_UDP_CONNRESET
:
5034 FIXME("WS_SIO_UDP_CONNRESET stub\n");
5036 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
5037 SetLastError(WSAEOPNOTSUPP
);
5038 return SOCKET_ERROR
;
5040 status
= WSAEOPNOTSUPP
;
5044 if (status
== WSAEOPNOTSUPP
)
5046 status
= server_ioctl_sock(s
, code
, in_buff
, in_size
, out_buff
, out_size
, &total
,
5047 overlapped
, completion
);
5048 if (status
!= WSAEOPNOTSUPP
)
5050 if (status
== 0 || status
== WSA_IO_PENDING
)
5051 TRACE("-> %s request\n", debugstr_wsaioctl(code
));
5053 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code
), status
);
5055 /* overlapped and completion operations will be handled by the server */
5060 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code
));
5065 FIXME( "completion routine %p not supported\n", completion
);
5067 else if (overlapped
)
5069 ULONG_PTR cvalue
= (overlapped
&& ((ULONG_PTR
)overlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)overlapped
: 0;
5070 overlapped
->Internal
= status
;
5071 overlapped
->InternalHigh
= total
;
5072 if (overlapped
->hEvent
) NtSetEvent( overlapped
->hEvent
, NULL
);
5073 if (cvalue
) WS_AddCompletion( HANDLE2SOCKET(s
), cvalue
, status
, total
);
5078 if (ret_size
) *ret_size
= total
;
5081 SetLastError( status
);
5082 return SOCKET_ERROR
;
5086 /***********************************************************************
5087 * ioctlsocket (WS2_32.10)
5089 int WINAPI
WS_ioctlsocket(SOCKET s
, LONG cmd
, WS_u_long
*argp
)
5092 return WSAIoctl( s
, cmd
, argp
, sizeof(WS_u_long
), argp
, sizeof(WS_u_long
), &ret_size
, NULL
, NULL
);
5095 /***********************************************************************
5096 * listen (WS2_32.13)
5098 int WINAPI
WS_listen(SOCKET s
, int backlog
)
5100 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
), ret
= SOCKET_ERROR
;
5102 TRACE("socket %04lx, backlog %d\n", s
, backlog
);
5105 int bound
= is_fd_bound(fd
, NULL
, NULL
);
5109 SetLastError(bound
== -1 ? wsaErrno() : WSAEINVAL
);
5111 else if (listen(fd
, backlog
) == 0)
5113 _enable_event(SOCKET2HANDLE(s
), FD_ACCEPT
,
5115 FD_CONNECT
|FD_WINE_CONNECTED
);
5119 SetLastError(wsaErrno());
5120 release_sock_fd( s
, fd
);
5123 SetLastError(WSAENOTSOCK
);
5127 /***********************************************************************
5130 int WINAPI
WS_recv(SOCKET s
, char *buf
, int len
, int flags
)
5132 DWORD n
, dwFlags
= flags
;
5138 if ( WS2_recv_base(s
, &wsabuf
, 1, &n
, &dwFlags
, NULL
, NULL
, NULL
, NULL
, NULL
) == SOCKET_ERROR
)
5139 return SOCKET_ERROR
;
5144 /***********************************************************************
5145 * recvfrom (WS2_32.17)
5147 int WINAPI
WS_recvfrom(SOCKET s
, char *buf
, INT len
, int flags
,
5148 struct WS_sockaddr
*from
, int *fromlen
)
5150 DWORD n
, dwFlags
= flags
;
5156 if ( WS2_recv_base(s
, &wsabuf
, 1, &n
, &dwFlags
, from
, fromlen
, NULL
, NULL
, NULL
) == SOCKET_ERROR
)
5157 return SOCKET_ERROR
;
5162 /* allocate a poll array for the corresponding fd sets */
5163 static struct pollfd
*fd_sets_to_poll( const WS_fd_set
*readfds
, const WS_fd_set
*writefds
,
5164 const WS_fd_set
*exceptfds
, int *count_ptr
)
5166 unsigned int i
, j
= 0, count
= 0;
5168 struct per_thread_data
*ptb
= get_per_thread_data();
5170 if (readfds
) count
+= readfds
->fd_count
;
5171 if (writefds
) count
+= writefds
->fd_count
;
5172 if (exceptfds
) count
+= exceptfds
->fd_count
;
5176 SetLastError(WSAEINVAL
);
5180 /* check if the cache can hold all descriptors, if not do the resizing */
5181 if (ptb
->fd_count
< count
)
5183 if (!(fds
= HeapAlloc(GetProcessHeap(), 0, count
* sizeof(fds
[0]))))
5185 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
5188 HeapFree(GetProcessHeap(), 0, ptb
->fd_cache
);
5189 ptb
->fd_cache
= fds
;
5190 ptb
->fd_count
= count
;
5193 fds
= ptb
->fd_cache
;
5196 for (i
= 0; i
< readfds
->fd_count
; i
++, j
++)
5198 fds
[j
].fd
= get_sock_fd( readfds
->fd_array
[i
], FILE_READ_DATA
, NULL
);
5199 if (fds
[j
].fd
== -1) goto failed
;
5201 if (is_fd_bound(fds
[j
].fd
, NULL
, NULL
) == 1)
5203 fds
[j
].events
= POLLIN
;
5207 release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
5213 for (i
= 0; i
< writefds
->fd_count
; i
++, j
++)
5215 fds
[j
].fd
= get_sock_fd( writefds
->fd_array
[i
], FILE_WRITE_DATA
, NULL
);
5216 if (fds
[j
].fd
== -1) goto failed
;
5218 if (is_fd_bound(fds
[j
].fd
, NULL
, NULL
) == 1 ||
5219 _get_fd_type(fds
[j
].fd
) == SOCK_DGRAM
)
5221 fds
[j
].events
= POLLOUT
;
5225 release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
5231 for (i
= 0; i
< exceptfds
->fd_count
; i
++, j
++)
5233 fds
[j
].fd
= get_sock_fd( exceptfds
->fd_array
[i
], 0, NULL
);
5234 if (fds
[j
].fd
== -1) goto failed
;
5236 if (is_fd_bound(fds
[j
].fd
, NULL
, NULL
) == 1)
5238 int oob_inlined
= 0;
5239 socklen_t olen
= sizeof(oob_inlined
);
5241 fds
[j
].events
= POLLHUP
;
5243 /* Check if we need to test for urgent data or not */
5244 getsockopt(fds
[j
].fd
, SOL_SOCKET
, SO_OOBINLINE
, (char*) &oob_inlined
, &olen
);
5246 fds
[j
].events
|= POLLPRI
;
5250 release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
5261 for (i
= 0; i
< readfds
->fd_count
&& j
< count
; i
++, j
++)
5262 if (fds
[j
].fd
!= -1) release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
5264 for (i
= 0; i
< writefds
->fd_count
&& j
< count
; i
++, j
++)
5265 if (fds
[j
].fd
!= -1) release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
5267 for (i
= 0; i
< exceptfds
->fd_count
&& j
< count
; i
++, j
++)
5268 if (fds
[j
].fd
!= -1) release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
5272 /* release the file descriptor obtained in fd_sets_to_poll */
5273 /* must be called with the original fd_set arrays, before calling get_poll_results */
5274 static void release_poll_fds( const WS_fd_set
*readfds
, const WS_fd_set
*writefds
,
5275 const WS_fd_set
*exceptfds
, struct pollfd
*fds
)
5277 unsigned int i
, j
= 0;
5281 for (i
= 0; i
< readfds
->fd_count
; i
++, j
++)
5282 if (fds
[j
].fd
!= -1) release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
5286 for (i
= 0; i
< writefds
->fd_count
; i
++, j
++)
5287 if (fds
[j
].fd
!= -1) release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
5291 for (i
= 0; i
< exceptfds
->fd_count
; i
++, j
++)
5293 if (fds
[j
].fd
== -1) continue;
5294 release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
5295 if (fds
[j
].revents
& POLLHUP
)
5297 int fd
= get_sock_fd( exceptfds
->fd_array
[i
], 0, NULL
);
5299 release_sock_fd( exceptfds
->fd_array
[i
], fd
);
5307 static int do_poll(struct pollfd
*pollfds
, int count
, int timeout
)
5309 struct timeval tv1
, tv2
;
5310 int ret
, torig
= timeout
;
5312 if (timeout
> 0) gettimeofday( &tv1
, 0 );
5314 while ((ret
= poll( pollfds
, count
, timeout
)) < 0)
5316 if (errno
!= EINTR
) break;
5317 if (timeout
< 0) continue;
5318 if (timeout
== 0) return 0;
5320 gettimeofday( &tv2
, 0 );
5322 tv2
.tv_sec
-= tv1
.tv_sec
;
5323 tv2
.tv_usec
-= tv1
.tv_usec
;
5324 if (tv2
.tv_usec
< 0)
5326 tv2
.tv_usec
+= 1000000;
5330 timeout
= torig
- (tv2
.tv_sec
* 1000) - (tv2
.tv_usec
+ 999) / 1000;
5331 if (timeout
<= 0) return 0;
5336 /* map the poll results back into the Windows fd sets */
5337 static int get_poll_results( WS_fd_set
*readfds
, WS_fd_set
*writefds
, WS_fd_set
*exceptfds
,
5338 const struct pollfd
*fds
)
5340 const struct pollfd
*poll_writefds
= fds
+ (readfds
? readfds
->fd_count
: 0);
5341 const struct pollfd
*poll_exceptfds
= poll_writefds
+ (writefds
? writefds
->fd_count
: 0);
5342 unsigned int i
, k
, total
= 0;
5346 for (i
= k
= 0; i
< readfds
->fd_count
; i
++)
5348 if (fds
[i
].revents
||
5349 (readfds
== writefds
&& (poll_writefds
[i
].revents
& POLLOUT
) && !(poll_writefds
[i
].revents
& POLLHUP
)) ||
5350 (readfds
== exceptfds
&& poll_exceptfds
[i
].revents
))
5351 readfds
->fd_array
[k
++] = readfds
->fd_array
[i
];
5353 readfds
->fd_count
= k
;
5356 if (writefds
&& writefds
!= readfds
)
5358 for (i
= k
= 0; i
< writefds
->fd_count
; i
++)
5360 if (((poll_writefds
[i
].revents
& POLLOUT
) && !(poll_writefds
[i
].revents
& POLLHUP
)) ||
5361 (writefds
== exceptfds
&& poll_exceptfds
[i
].revents
))
5362 writefds
->fd_array
[k
++] = writefds
->fd_array
[i
];
5364 writefds
->fd_count
= k
;
5367 if (exceptfds
&& exceptfds
!= readfds
&& exceptfds
!= writefds
)
5369 for (i
= k
= 0; i
< exceptfds
->fd_count
; i
++)
5370 if (poll_exceptfds
[i
].revents
) exceptfds
->fd_array
[k
++] = exceptfds
->fd_array
[i
];
5371 exceptfds
->fd_count
= k
;
5377 /***********************************************************************
5378 * select (WS2_32.18)
5380 int WINAPI
WS_select(int nfds
, WS_fd_set
*ws_readfds
,
5381 WS_fd_set
*ws_writefds
, WS_fd_set
*ws_exceptfds
,
5382 const struct WS_timeval
* ws_timeout
)
5384 struct pollfd
*pollfds
;
5385 int count
, ret
, timeout
= -1;
5387 TRACE("read %p, write %p, excp %p timeout %p\n",
5388 ws_readfds
, ws_writefds
, ws_exceptfds
, ws_timeout
);
5390 if (!(pollfds
= fd_sets_to_poll( ws_readfds
, ws_writefds
, ws_exceptfds
, &count
)))
5391 return SOCKET_ERROR
;
5394 timeout
= (ws_timeout
->tv_sec
* 1000) + (ws_timeout
->tv_usec
+ 999) / 1000;
5396 ret
= do_poll(pollfds
, count
, timeout
);
5397 release_poll_fds( ws_readfds
, ws_writefds
, ws_exceptfds
, pollfds
);
5399 if (ret
== -1) SetLastError(wsaErrno());
5400 else ret
= get_poll_results( ws_readfds
, ws_writefds
, ws_exceptfds
, pollfds
);
5404 /***********************************************************************
5407 int WINAPI
WSAPoll(WSAPOLLFD
*wfds
, ULONG count
, int timeout
)
5410 struct pollfd
*ufds
;
5414 SetLastError(WSAEINVAL
);
5415 return SOCKET_ERROR
;
5419 SetLastError(WSAEFAULT
);
5420 return SOCKET_ERROR
;
5423 if (!(ufds
= HeapAlloc(GetProcessHeap(), 0, count
* sizeof(ufds
[0]))))
5425 SetLastError(WSAENOBUFS
);
5426 return SOCKET_ERROR
;
5429 for (i
= 0; i
< count
; i
++)
5431 ufds
[i
].fd
= get_sock_fd(wfds
[i
].fd
, 0, NULL
);
5432 ufds
[i
].events
= convert_poll_w2u(wfds
[i
].events
);
5433 ufds
[i
].revents
= 0;
5436 ret
= do_poll(ufds
, count
, timeout
);
5438 for (i
= 0; i
< count
; i
++)
5440 if (ufds
[i
].fd
!= -1)
5442 release_sock_fd(wfds
[i
].fd
, ufds
[i
].fd
);
5443 if (ufds
[i
].revents
& POLLHUP
)
5445 /* Check if the socket still exists */
5446 int fd
= get_sock_fd(wfds
[i
].fd
, 0, NULL
);
5449 wfds
[i
].revents
= WS_POLLHUP
;
5450 release_sock_fd(wfds
[i
].fd
, fd
);
5453 wfds
[i
].revents
= WS_POLLNVAL
;
5456 wfds
[i
].revents
= convert_poll_u2w(ufds
[i
].revents
);
5459 wfds
[i
].revents
= WS_POLLNVAL
;
5462 HeapFree(GetProcessHeap(), 0, ufds
);
5466 /* helper to send completion messages for client-only i/o operation case */
5467 static void WS_AddCompletion( SOCKET sock
, ULONG_PTR CompletionValue
, NTSTATUS CompletionStatus
,
5470 SERVER_START_REQ( add_fd_completion
)
5472 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(sock
) );
5473 req
->cvalue
= CompletionValue
;
5474 req
->status
= CompletionStatus
;
5475 req
->information
= Information
;
5476 wine_server_call( req
);
5482 /***********************************************************************
5485 int WINAPI
WS_send(SOCKET s
, const char *buf
, int len
, int flags
)
5491 wsabuf
.buf
= (char*) buf
;
5493 if ( WS2_sendto( s
, &wsabuf
, 1, &n
, flags
, NULL
, 0, NULL
, NULL
) == SOCKET_ERROR
)
5494 return SOCKET_ERROR
;
5499 /***********************************************************************
5500 * WSASend (WS2_32.72)
5502 INT WINAPI
WSASend( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
5503 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
5504 LPWSAOVERLAPPED lpOverlapped
,
5505 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
5507 return WS2_sendto( s
, lpBuffers
, dwBufferCount
, lpNumberOfBytesSent
, dwFlags
,
5508 NULL
, 0, lpOverlapped
, lpCompletionRoutine
);
5511 /***********************************************************************
5512 * WSASendDisconnect (WS2_32.73)
5514 INT WINAPI
WSASendDisconnect( SOCKET s
, LPWSABUF lpBuffers
)
5516 return WS_shutdown( s
, SD_SEND
);
5520 static int WS2_sendto( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
5521 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
5522 const struct WS_sockaddr
*to
, int tolen
,
5523 LPWSAOVERLAPPED lpOverlapped
,
5524 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
5526 unsigned int i
, options
;
5527 int n
, fd
, err
, overlapped
, flags
;
5528 struct ws2_async
*wsa
= NULL
, localwsa
;
5529 int totalLength
= 0;
5533 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
5534 s
, lpBuffers
, dwBufferCount
, dwFlags
,
5535 to
, tolen
, lpOverlapped
, lpCompletionRoutine
);
5537 fd
= get_sock_fd( s
, FILE_WRITE_DATA
, &options
);
5538 TRACE( "fd=%d, options=%x\n", fd
, options
);
5540 if ( fd
== -1 ) return SOCKET_ERROR
;
5542 if (!lpOverlapped
&& !lpNumberOfBytesSent
)
5548 overlapped
= (lpOverlapped
|| lpCompletionRoutine
) &&
5549 !(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
));
5550 if (overlapped
|| dwBufferCount
> 1)
5552 if (!(wsa
= (struct ws2_async
*)alloc_async_io( offsetof(struct ws2_async
, iovec
[dwBufferCount
]),
5562 wsa
->hSocket
= SOCKET2HANDLE(s
);
5563 wsa
->addr
= (struct WS_sockaddr
*)to
;
5564 wsa
->addrlen
.val
= tolen
;
5565 wsa
->flags
= dwFlags
;
5566 wsa
->lpFlags
= &wsa
->flags
;
5567 wsa
->control
= NULL
;
5568 wsa
->n_iovecs
= dwBufferCount
;
5569 wsa
->first_iovec
= 0;
5570 for ( i
= 0; i
< dwBufferCount
; i
++ )
5572 wsa
->iovec
[i
].iov_base
= lpBuffers
[i
].buf
;
5573 wsa
->iovec
[i
].iov_len
= lpBuffers
[i
].len
;
5574 totalLength
+= lpBuffers
[i
].len
;
5577 flags
= convert_flags(dwFlags
);
5578 n
= WS2_send( fd
, wsa
, flags
);
5579 if (n
== -1 && errno
!= EAGAIN
)
5587 IO_STATUS_BLOCK
*iosb
= lpOverlapped
? (IO_STATUS_BLOCK
*)lpOverlapped
: &wsa
->local_iosb
;
5588 ULONG_PTR cvalue
= (lpOverlapped
&& ((ULONG_PTR
)lpOverlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)lpOverlapped
: 0;
5590 wsa
->user_overlapped
= lpOverlapped
;
5591 wsa
->completion_func
= lpCompletionRoutine
;
5592 release_sock_fd( s
, fd
);
5594 if (n
== -1 || n
< totalLength
)
5596 iosb
->u
.Status
= STATUS_PENDING
;
5597 iosb
->Information
= n
== -1 ? 0 : n
;
5599 if (wsa
->completion_func
)
5600 err
= register_async( ASYNC_TYPE_WRITE
, wsa
->hSocket
, &wsa
->io
, NULL
,
5601 ws2_async_apc
, wsa
, iosb
);
5603 err
= register_async( ASYNC_TYPE_WRITE
, wsa
->hSocket
, &wsa
->io
, lpOverlapped
->hEvent
,
5604 NULL
, (void *)cvalue
, iosb
);
5606 /* Enable the event only after starting the async. The server will deliver it as soon as
5607 the async is done. */
5608 _enable_event(SOCKET2HANDLE(s
), FD_WRITE
, 0, 0);
5610 if (err
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
5611 SetLastError(NtStatusToWSAError( err
));
5612 return SOCKET_ERROR
;
5615 iosb
->u
.Status
= STATUS_SUCCESS
;
5616 iosb
->Information
= n
;
5617 if (lpNumberOfBytesSent
) *lpNumberOfBytesSent
= n
;
5618 if (!wsa
->completion_func
)
5620 if (cvalue
) WS_AddCompletion( s
, cvalue
, STATUS_SUCCESS
, n
);
5621 if (lpOverlapped
->hEvent
) SetEvent( lpOverlapped
->hEvent
);
5622 HeapFree( GetProcessHeap(), 0, wsa
);
5624 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC
)ws2_async_apc
,
5625 (ULONG_PTR
)wsa
, (ULONG_PTR
)iosb
, 0 );
5626 SetLastError(ERROR_SUCCESS
);
5630 if ((err
= _is_blocking( s
, &is_blocking
)))
5632 err
= NtStatusToWSAError( err
);
5638 /* On a blocking non-overlapped stream socket,
5639 * sending blocks until the entire buffer is sent. */
5640 DWORD timeout_start
= GetTickCount();
5642 bytes_sent
= n
== -1 ? 0 : n
;
5644 while (wsa
->first_iovec
< wsa
->n_iovecs
)
5647 int poll_timeout
= -1;
5648 INT64 timeout
= get_rcvsnd_timeo(fd
, FALSE
);
5652 timeout
-= GetTickCount() - timeout_start
;
5653 if (timeout
< 0) poll_timeout
= 0;
5654 else poll_timeout
= timeout
<= INT_MAX
? timeout
: INT_MAX
;
5658 pfd
.events
= POLLOUT
;
5660 if (!poll_timeout
|| !poll( &pfd
, 1, poll_timeout
))
5663 goto error
; /* msdn says a timeout in send is fatal */
5666 n
= WS2_send( fd
, wsa
, flags
);
5667 if (n
== -1 && errno
!= EAGAIN
)
5677 else /* non-blocking */
5679 if (n
< totalLength
)
5680 _enable_event(SOCKET2HANDLE(s
), FD_WRITE
, 0, 0);
5683 err
= WSAEWOULDBLOCK
;
5689 TRACE(" -> %i bytes\n", bytes_sent
);
5691 if (lpNumberOfBytesSent
) *lpNumberOfBytesSent
= bytes_sent
;
5692 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
5693 release_sock_fd( s
, fd
);
5694 SetLastError(ERROR_SUCCESS
);
5698 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
5699 release_sock_fd( s
, fd
);
5700 WARN(" -> ERROR %d\n", err
);
5702 return SOCKET_ERROR
;
5705 /***********************************************************************
5706 * WSASendTo (WS2_32.74)
5708 INT WINAPI
WSASendTo( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
5709 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
5710 const struct WS_sockaddr
*to
, int tolen
,
5711 LPWSAOVERLAPPED lpOverlapped
,
5712 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
5714 return WS2_sendto( s
, lpBuffers
, dwBufferCount
,
5715 lpNumberOfBytesSent
, dwFlags
,
5717 lpOverlapped
, lpCompletionRoutine
);
5720 /***********************************************************************
5721 * sendto (WS2_32.20)
5723 int WINAPI
WS_sendto(SOCKET s
, const char *buf
, int len
, int flags
,
5724 const struct WS_sockaddr
*to
, int tolen
)
5730 wsabuf
.buf
= (char*) buf
;
5732 if ( WS2_sendto(s
, &wsabuf
, 1, &n
, flags
, to
, tolen
, NULL
, NULL
) == SOCKET_ERROR
)
5733 return SOCKET_ERROR
;
5738 /***********************************************************************
5739 * setsockopt (WS2_32.21)
5741 int WINAPI
WS_setsockopt(SOCKET s
, int level
, int optname
,
5742 const char *optval
, int optlen
)
5746 struct linger linger
;
5747 struct timeval tval
;
5749 TRACE("(socket %04lx, %s, optval %s, optlen %d)\n", s
,
5750 debugstr_sockopt(level
, optname
), debugstr_optval(optval
, optlen
),
5753 /* some broken apps pass the value directly instead of a pointer to it */
5754 if(optlen
&& IS_INTRESOURCE(optval
))
5756 SetLastError(WSAEFAULT
);
5757 return SOCKET_ERROR
;
5765 /* Some options need some conversion before they can be sent to
5766 * setsockopt. The conversions are done here, then they will fall through
5767 * to the general case. Special options that are not passed to
5768 * setsockopt follow below that.*/
5770 case WS_SO_DONTLINGER
:
5773 SetLastError(WSAEFAULT
);
5774 return SOCKET_ERROR
;
5776 linger
.l_onoff
= *(const int*)optval
== 0;
5777 linger
.l_linger
= 0;
5779 optname
= SO_LINGER
;
5780 optval
= (char*)&linger
;
5781 optlen
= sizeof(struct linger
);
5787 SetLastError(WSAEFAULT
);
5788 return SOCKET_ERROR
;
5790 linger
.l_onoff
= ((LINGER
*)optval
)->l_onoff
;
5791 linger
.l_linger
= ((LINGER
*)optval
)->l_linger
;
5793 optname
= SO_LINGER
;
5794 optval
= (char*)&linger
;
5795 optlen
= sizeof(struct linger
);
5799 if (*(const int*)optval
< 2048)
5801 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval
);
5806 /* The options listed here don't need any special handling. Thanks to
5807 * the conversion happening above, options from there will fall through
5809 case WS_SO_ACCEPTCONN
:
5810 case WS_SO_BROADCAST
:
5812 case WS_SO_KEEPALIVE
:
5813 case WS_SO_OOBINLINE
:
5814 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
5815 * however, using it the BSD way fixes bug 8513 and seems to be what
5816 * most programmers assume, anyway */
5817 case WS_SO_REUSEADDR
:
5820 convert_sockopt(&level
, &optname
);
5823 /* SO_DEBUG is a privileged operation, ignore it. */
5825 TRACE("Ignoring SO_DEBUG\n");
5828 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
5829 * socket. According to MSDN, this option is silently ignored.*/
5830 case WS_SO_DONTROUTE
:
5831 TRACE("Ignoring SO_DONTROUTE\n");
5834 /* Stops two sockets from being bound to the same port. Always happens
5835 * on unix systems, so just drop it. */
5836 case WS_SO_EXCLUSIVEADDRUSE
:
5837 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
5840 /* After a ConnectEx call succeeds, the socket can't be used with half of the
5841 * normal winsock functions on windows. We don't have that problem. */
5842 case WS_SO_UPDATE_CONNECT_CONTEXT
:
5843 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
5846 /* After a AcceptEx call succeeds, the socket can't be used with half of the
5847 * normal winsock functions on windows. We don't have that problem. */
5848 case WS_SO_UPDATE_ACCEPT_CONTEXT
:
5849 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
5852 /* SO_OPENTYPE does not require a valid socket handle. */
5853 case WS_SO_OPENTYPE
:
5854 if (!optlen
|| optlen
< sizeof(int) || !optval
)
5856 SetLastError(WSAEFAULT
);
5857 return SOCKET_ERROR
;
5859 get_per_thread_data()->opentype
= *(const int *)optval
;
5860 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval
) );
5864 case WS_SO_RCVTIMEO
:
5867 case WS_SO_SNDTIMEO
:
5869 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
5870 if (optval
&& optlen
== sizeof(UINT32
)) {
5871 /* WinSock passes milliseconds instead of struct timeval */
5872 tval
.tv_usec
= (*(const UINT32
*)optval
% 1000) * 1000;
5873 tval
.tv_sec
= *(const UINT32
*)optval
/ 1000;
5874 /* min of 500 milliseconds */
5875 if (tval
.tv_sec
== 0 && tval
.tv_usec
&& tval
.tv_usec
< 500000)
5876 tval
.tv_usec
= 500000;
5877 optlen
= sizeof(struct timeval
);
5878 optval
= (char*)&tval
;
5879 } else if (optlen
== sizeof(struct timeval
)) {
5880 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen
);
5882 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen
);
5885 convert_sockopt(&level
, &optname
);
5890 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname
);
5891 SetLastError(WSAENOPROTOOPT
);
5892 return SOCKET_ERROR
;
5894 break; /* case WS_SOL_SOCKET */
5897 case WS_NSPROTO_IPX
:
5901 return set_ipx_packettype(s
, *(int*)optval
);
5903 case WS_IPX_FILTERPTYPE
:
5904 /* Sets the receive filter packet type, at the moment we don't support it */
5905 FIXME("IPX_FILTERPTYPE: %x\n", *optval
);
5906 /* Returning 0 is better for now than returning a SOCKET_ERROR */
5910 FIXME("opt_name:%x\n", optname
);
5911 return SOCKET_ERROR
;
5913 break; /* case WS_NSPROTO_IPX */
5916 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
5917 case WS_IPPROTO_TCP
:
5920 case WS_TCP_NODELAY
:
5921 convert_sockopt(&level
, &optname
);
5924 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname
);
5925 return SOCKET_ERROR
;
5932 case WS_IP_ADD_MEMBERSHIP
:
5933 case WS_IP_DROP_MEMBERSHIP
:
5937 case WS_IP_MULTICAST_IF
:
5938 case WS_IP_MULTICAST_LOOP
:
5939 case WS_IP_MULTICAST_TTL
:
5946 #ifdef IP_UNICAST_IF
5947 case WS_IP_UNICAST_IF
:
5949 convert_sockopt(&level
, &optname
);
5951 case WS_IP_DONTFRAGMENT
:
5952 return set_dont_fragment(s
, IPPROTO_IP
, *(BOOL
*)optval
) ? 0 : SOCKET_ERROR
;
5954 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname
);
5955 return SOCKET_ERROR
;
5959 case WS_IPPROTO_IPV6
:
5962 #ifdef IPV6_ADD_MEMBERSHIP
5963 case WS_IPV6_ADD_MEMBERSHIP
:
5965 #ifdef IPV6_DROP_MEMBERSHIP
5966 case WS_IPV6_DROP_MEMBERSHIP
:
5968 case WS_IPV6_MULTICAST_IF
:
5969 case WS_IPV6_MULTICAST_HOPS
:
5970 case WS_IPV6_MULTICAST_LOOP
:
5971 case WS_IPV6_UNICAST_HOPS
:
5972 #ifdef IPV6_UNICAST_IF
5973 case WS_IPV6_UNICAST_IF
:
5975 convert_sockopt(&level
, &optname
);
5977 case WS_IPV6_DONTFRAG
:
5978 return set_dont_fragment(s
, IPPROTO_IPV6
, *(BOOL
*)optval
) ? 0 : SOCKET_ERROR
;
5979 case WS_IPV6_PROTECTION_LEVEL
:
5980 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
5982 case WS_IPV6_V6ONLY
:
5984 union generic_unix_sockaddr uaddr
;
5988 fd
= get_sock_fd( s
, 0, NULL
);
5989 if (fd
== -1) return SOCKET_ERROR
;
5991 bound
= is_fd_bound(fd
, &uaddr
, &uaddrlen
);
5992 release_sock_fd( s
, fd
);
5993 if (bound
== 0 && uaddr
.addr
.sa_family
== AF_INET
)
5995 /* Changing IPV6_V6ONLY succeeds on AF_INET (IPv4) socket
5996 * on Windows (with IPv6 support) if the socket is unbound.
5997 * It is essentially a noop, though Windows does store the value
5999 WARN("Silently ignoring IPPROTO_IPV6+IPV6_V6ONLY on AF_INET socket\n");
6002 level
= IPPROTO_IPV6
;
6003 optname
= IPV6_V6ONLY
;
6007 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname
);
6008 return SOCKET_ERROR
;
6013 WARN("Unknown level: 0x%08x\n", level
);
6014 SetLastError(WSAEINVAL
);
6015 return SOCKET_ERROR
;
6016 } /* end switch(level) */
6018 /* avoid endianness issues if argument is a 16-bit int */
6019 if (optval
&& optlen
< sizeof(int))
6021 woptval
= *((const INT16
*) optval
);
6022 optval
= (char*) &woptval
;
6023 woptval
&= (1 << optlen
* 8) - 1;
6026 fd
= get_sock_fd( s
, 0, NULL
);
6027 if (fd
== -1) return SOCKET_ERROR
;
6029 if (setsockopt(fd
, level
, optname
, optval
, optlen
) == 0)
6032 if (level
== SOL_SOCKET
&& optname
== SO_REUSEADDR
&&
6033 setsockopt(fd
, level
, SO_REUSEPORT
, optval
, optlen
) != 0)
6035 SetLastError(wsaErrno());
6036 release_sock_fd( s
, fd
);
6037 return SOCKET_ERROR
;
6040 release_sock_fd( s
, fd
);
6043 TRACE("Setting socket error, %d\n", wsaErrno());
6044 SetLastError(wsaErrno());
6045 release_sock_fd( s
, fd
);
6047 return SOCKET_ERROR
;
6050 /***********************************************************************
6051 * shutdown (WS2_32.22)
6053 int WINAPI
WS_shutdown(SOCKET s
, int how
)
6055 int fd
, err
= WSAENOTSOCK
;
6056 unsigned int options
= 0, clear_flags
= 0;
6058 fd
= get_sock_fd( s
, 0, &options
);
6059 TRACE("socket %04lx, how 0x%x, options 0x%x\n", s
, how
, options
);
6062 return SOCKET_ERROR
;
6066 case SD_RECEIVE
: /* drop receives */
6067 clear_flags
|= FD_READ
;
6069 case SD_SEND
: /* drop sends */
6070 clear_flags
|= FD_WRITE
;
6072 case SD_BOTH
: /* drop all */
6073 clear_flags
|= FD_READ
|FD_WRITE
;
6076 clear_flags
|= FD_WINE_LISTENING
;
6079 if (!(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
)))
6084 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_READ
);
6087 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_WRITE
);
6091 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_READ
);
6092 if (!err
) err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_WRITE
);
6095 if (err
) goto error
;
6097 else /* non-overlapped mode */
6099 if ( shutdown( fd
, how
) )
6106 release_sock_fd( s
, fd
);
6107 _enable_event( SOCKET2HANDLE(s
), 0, 0, clear_flags
);
6108 if ( how
> 1) WSAAsyncSelect( s
, 0, 0, 0 );
6112 release_sock_fd( s
, fd
);
6113 _enable_event( SOCKET2HANDLE(s
), 0, 0, clear_flags
);
6114 SetLastError( err
);
6115 return SOCKET_ERROR
;
6118 /***********************************************************************
6119 * socket (WS2_32.23)
6121 SOCKET WINAPI
WS_socket(int af
, int type
, int protocol
)
6123 TRACE("af=%d type=%d protocol=%d\n", af
, type
, protocol
);
6125 return WSASocketW( af
, type
, protocol
, NULL
, 0,
6126 get_per_thread_data()->opentype
? 0 : WSA_FLAG_OVERLAPPED
);
6130 /***********************************************************************
6131 * gethostbyaddr (WS2_32.51)
6133 struct WS_hostent
* WINAPI
WS_gethostbyaddr(const char *addr
, int len
, int type
)
6135 struct WS_hostent
*retval
= NULL
;
6136 struct hostent
* host
;
6137 int unixtype
= convert_af_w2u(type
);
6138 const char *paddr
= addr
;
6139 unsigned long loopback
;
6140 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6142 int ebufsize
= 1024;
6143 struct hostent hostentry
;
6144 int locerr
= ENOBUFS
;
6147 /* convert back the magic loopback address if necessary */
6148 if (unixtype
== AF_INET
&& len
== 4 && !memcmp(addr
, magic_loopback_addr
, 4))
6150 loopback
= htonl(INADDR_LOOPBACK
);
6151 paddr
= (char*) &loopback
;
6154 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6156 extrabuf
=HeapAlloc(GetProcessHeap(),0,ebufsize
) ;
6158 int res
= gethostbyaddr_r(paddr
, len
, unixtype
,
6159 &hostentry
, extrabuf
, ebufsize
, &host
, &locerr
);
6160 if (res
!= ERANGE
) break;
6162 extrabuf
=HeapReAlloc(GetProcessHeap(),0,extrabuf
,ebufsize
) ;
6164 if (host
) retval
= WS_dup_he(host
);
6165 else SetLastError((locerr
< 0) ? wsaErrno() : wsaHerrno(locerr
));
6166 HeapFree(GetProcessHeap(),0,extrabuf
);
6168 EnterCriticalSection( &csWSgetXXXbyYYY
);
6169 host
= gethostbyaddr(paddr
, len
, unixtype
);
6170 if (host
) retval
= WS_dup_he(host
);
6171 else SetLastError((h_errno
< 0) ? wsaErrno() : wsaHerrno(h_errno
));
6172 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6174 TRACE("ptr %p, len %d, type %d ret %p\n", addr
, len
, type
, retval
);
6178 /***********************************************************************
6179 * WS_compare_routes_by_metric_asc (INTERNAL)
6181 * Comparison function for qsort(), for sorting two routes (struct route)
6182 * by metric in ascending order.
6184 static int WS_compare_routes_by_metric_asc(const void *left
, const void *right
)
6186 const struct route
*a
= left
, *b
= right
;
6187 if (a
->default_route
&& b
->default_route
)
6188 return a
->default_route
- b
->default_route
;
6189 if (a
->default_route
&& !b
->default_route
)
6191 if (b
->default_route
&& !a
->default_route
)
6193 return a
->metric
- b
->metric
;
6196 /***********************************************************************
6197 * WS_get_local_ips (INTERNAL)
6199 * Returns the list of local IP addresses by going through the network
6200 * adapters and using the local routing table to sort the addresses
6201 * from highest routing priority to lowest routing priority. This
6202 * functionality is inferred from the description for obtaining local
6203 * IP addresses given in the Knowledge Base Article Q160215.
6205 * Please note that the returned hostent is only freed when the thread
6206 * closes and is replaced if another hostent is requested.
6208 static struct WS_hostent
* WS_get_local_ips( char *hostname
)
6210 int numroutes
= 0, i
, j
, default_routes
= 0;
6212 PIP_ADAPTER_INFO adapters
= NULL
, k
;
6213 struct WS_hostent
*hostlist
= NULL
;
6214 PMIB_IPFORWARDTABLE routes
= NULL
;
6215 struct route
*route_addrs
= NULL
;
6216 DWORD adap_size
, route_size
;
6218 /* Obtain the size of the adapter list and routing table, also allocate memory */
6219 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
6221 if (GetIpForwardTable(NULL
, &route_size
, FALSE
) != ERROR_INSUFFICIENT_BUFFER
)
6223 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
6224 routes
= HeapAlloc(GetProcessHeap(), 0, route_size
);
6225 route_addrs
= HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
6226 if (adapters
== NULL
|| routes
== NULL
|| route_addrs
== NULL
)
6228 /* Obtain the adapter list and the full routing table */
6229 if (GetAdaptersInfo(adapters
, &adap_size
) != NO_ERROR
)
6231 if (GetIpForwardTable(routes
, &route_size
, FALSE
) != NO_ERROR
)
6233 /* Store the interface associated with each route */
6234 for (n
= 0; n
< routes
->dwNumEntries
; n
++)
6237 DWORD ifmetric
, ifdefault
= 0;
6238 BOOL exists
= FALSE
;
6240 /* Check if this is a default route (there may be more than one) */
6241 if (!routes
->table
[n
].dwForwardDest
)
6242 ifdefault
= ++default_routes
;
6243 else if (routes
->table
[n
].u1
.ForwardType
!= MIB_IPROUTE_TYPE_DIRECT
)
6245 ifindex
= routes
->table
[n
].dwForwardIfIndex
;
6246 ifmetric
= routes
->table
[n
].dwForwardMetric1
;
6247 /* Only store the lowest valued metric for an interface */
6248 for (j
= 0; j
< numroutes
; j
++)
6250 if (route_addrs
[j
].interface
== ifindex
)
6252 if (route_addrs
[j
].metric
> ifmetric
)
6253 route_addrs
[j
].metric
= ifmetric
;
6259 route_addrs
= HeapReAlloc(GetProcessHeap(), 0, route_addrs
, (numroutes
+1)*sizeof(struct route
));
6260 if (route_addrs
== NULL
)
6261 goto cleanup
; /* Memory allocation error, fail gracefully */
6262 route_addrs
[numroutes
].interface
= ifindex
;
6263 route_addrs
[numroutes
].metric
= ifmetric
;
6264 route_addrs
[numroutes
].default_route
= ifdefault
;
6265 /* If no IP is found in the next step (for whatever reason)
6266 * then fall back to the magic loopback address.
6268 memcpy(&(route_addrs
[numroutes
].addr
.s_addr
), magic_loopback_addr
, 4);
6272 goto cleanup
; /* No routes, fall back to the Magic IP */
6273 /* Find the IP address associated with each found interface */
6274 for (i
= 0; i
< numroutes
; i
++)
6276 for (k
= adapters
; k
!= NULL
; k
= k
->Next
)
6278 char *ip
= k
->IpAddressList
.IpAddress
.String
;
6280 if (route_addrs
[i
].interface
== k
->Index
)
6281 route_addrs
[i
].addr
.s_addr
= (in_addr_t
) inet_addr(ip
);
6284 /* Allocate a hostent and enough memory for all the IPs,
6285 * including the NULL at the end of the list.
6287 hostlist
= WS_create_he(hostname
, 1, 0, numroutes
+1, sizeof(struct in_addr
));
6288 if (hostlist
== NULL
)
6289 goto cleanup
; /* Failed to allocate a hostent for the list of IPs */
6290 hostlist
->h_addr_list
[numroutes
] = NULL
; /* NULL-terminate the address list */
6291 hostlist
->h_aliases
[0] = NULL
; /* NULL-terminate the alias list */
6292 hostlist
->h_addrtype
= AF_INET
;
6293 hostlist
->h_length
= sizeof(struct in_addr
); /* = 4 */
6294 /* Reorder the entries before placing them in the host list. Windows expects
6295 * the IP list in order from highest priority to lowest (the critical thing
6296 * is that most applications expect the first IP to be the default route).
6299 qsort(route_addrs
, numroutes
, sizeof(struct route
), WS_compare_routes_by_metric_asc
);
6301 for (i
= 0; i
< numroutes
; i
++)
6302 (*(struct in_addr
*) hostlist
->h_addr_list
[i
]) = route_addrs
[i
].addr
;
6304 /* Cleanup all allocated memory except the address list,
6305 * the address list is used by the calling app.
6308 HeapFree(GetProcessHeap(), 0, route_addrs
);
6309 HeapFree(GetProcessHeap(), 0, adapters
);
6310 HeapFree(GetProcessHeap(), 0, routes
);
6314 /***********************************************************************
6315 * gethostbyname (WS2_32.52)
6317 struct WS_hostent
* WINAPI
WS_gethostbyname(const char* name
)
6319 struct WS_hostent
*retval
= NULL
;
6320 struct hostent
* host
;
6321 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6324 struct hostent hostentry
;
6325 int locerr
= ENOBUFS
;
6329 SetLastError(WSANOTINITIALISED
);
6332 if( gethostname( hostname
, 100) == -1) {
6333 SetLastError(WSAENOBUFS
); /* appropriate ? */
6336 if( !name
|| !name
[0]) {
6339 /* If the hostname of the local machine is requested then return the
6340 * complete list of local IP addresses */
6341 if(strcmp(name
, hostname
) == 0)
6342 retval
= WS_get_local_ips(hostname
);
6343 /* If any other hostname was requested (or the routing table lookup failed)
6344 * then return the IP found by the host OS */
6347 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6349 extrabuf
=HeapAlloc(GetProcessHeap(),0,ebufsize
) ;
6351 int res
= gethostbyname_r(name
, &hostentry
, extrabuf
, ebufsize
, &host
, &locerr
);
6352 if( res
!= ERANGE
) break;
6354 extrabuf
=HeapReAlloc(GetProcessHeap(),0,extrabuf
,ebufsize
) ;
6356 if (!host
) SetLastError((locerr
< 0) ? wsaErrno() : wsaHerrno(locerr
));
6358 EnterCriticalSection( &csWSgetXXXbyYYY
);
6359 host
= gethostbyname(name
);
6360 if (!host
) SetLastError((h_errno
< 0) ? wsaErrno() : wsaHerrno(h_errno
));
6362 if (host
) retval
= WS_dup_he(host
);
6363 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6364 HeapFree(GetProcessHeap(),0,extrabuf
);
6366 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6369 if (retval
&& retval
->h_addr_list
[0][0] == 127 &&
6370 strcmp(name
, "localhost") != 0)
6372 /* hostname != "localhost" but has loopback address. replace by our
6373 * special address.*/
6374 memcpy(retval
->h_addr_list
[0], magic_loopback_addr
, 4);
6376 TRACE( "%s ret %p\n", debugstr_a(name
), retval
);
6381 /***********************************************************************
6382 * getprotobyname (WS2_32.53)
6384 struct WS_protoent
* WINAPI
WS_getprotobyname(const char* name
)
6386 struct WS_protoent
* retval
= NULL
;
6387 #ifdef HAVE_GETPROTOBYNAME
6388 struct protoent
* proto
;
6389 EnterCriticalSection( &csWSgetXXXbyYYY
);
6390 if( (proto
= getprotobyname(name
)) != NULL
)
6392 retval
= WS_dup_pe(proto
);
6395 MESSAGE("protocol %s not found; You might want to add "
6396 "this to /etc/protocols\n", debugstr_a(name
) );
6397 SetLastError(WSANO_DATA
);
6399 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6401 TRACE( "%s ret %p\n", debugstr_a(name
), retval
);
6406 /***********************************************************************
6407 * getprotobynumber (WS2_32.54)
6409 struct WS_protoent
* WINAPI
WS_getprotobynumber(int number
)
6411 struct WS_protoent
* retval
= NULL
;
6412 #ifdef HAVE_GETPROTOBYNUMBER
6413 struct protoent
* proto
;
6414 EnterCriticalSection( &csWSgetXXXbyYYY
);
6415 if( (proto
= getprotobynumber(number
)) != NULL
)
6417 retval
= WS_dup_pe(proto
);
6420 MESSAGE("protocol number %d not found; You might want to add "
6421 "this to /etc/protocols\n", number
);
6422 SetLastError(WSANO_DATA
);
6424 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6426 TRACE("%i ret %p\n", number
, retval
);
6431 /***********************************************************************
6432 * getservbyname (WS2_32.55)
6434 struct WS_servent
* WINAPI
WS_getservbyname(const char *name
, const char *proto
)
6436 struct WS_servent
* retval
= NULL
;
6437 struct servent
* serv
;
6439 char *proto_str
= NULL
;
6441 if (!(name_str
= strdup_lower(name
))) return NULL
;
6443 if (proto
&& *proto
)
6445 if (!(proto_str
= strdup_lower(proto
)))
6447 HeapFree( GetProcessHeap(), 0, name_str
);
6452 EnterCriticalSection( &csWSgetXXXbyYYY
);
6453 serv
= getservbyname(name_str
, proto_str
);
6456 retval
= WS_dup_se(serv
);
6458 else SetLastError(WSANO_DATA
);
6459 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6460 HeapFree( GetProcessHeap(), 0, proto_str
);
6461 HeapFree( GetProcessHeap(), 0, name_str
);
6462 TRACE( "%s, %s ret %p\n", debugstr_a(name
), debugstr_a(proto
), retval
);
6466 /***********************************************************************
6467 * freeaddrinfo (WS2_32.@)
6469 void WINAPI
WS_freeaddrinfo(struct WS_addrinfo
*res
)
6472 struct WS_addrinfo
*next
;
6474 HeapFree(GetProcessHeap(),0,res
->ai_canonname
);
6475 HeapFree(GetProcessHeap(),0,res
->ai_addr
);
6476 next
= res
->ai_next
;
6477 HeapFree(GetProcessHeap(),0,res
);
6482 /* helper functions for getaddrinfo()/getnameinfo() */
6483 static int convert_aiflag_w2u(int winflags
) {
6487 for (i
=0;i
<sizeof(ws_aiflag_map
)/sizeof(ws_aiflag_map
[0]);i
++)
6488 if (ws_aiflag_map
[i
][0] & winflags
) {
6489 unixflags
|= ws_aiflag_map
[i
][1];
6490 winflags
&= ~ws_aiflag_map
[i
][0];
6493 FIXME("Unhandled windows AI_xxx flags 0x%x\n", winflags
);
6497 static int convert_niflag_w2u(int winflags
) {
6501 for (i
=0;i
<sizeof(ws_niflag_map
)/sizeof(ws_niflag_map
[0]);i
++)
6502 if (ws_niflag_map
[i
][0] & winflags
) {
6503 unixflags
|= ws_niflag_map
[i
][1];
6504 winflags
&= ~ws_niflag_map
[i
][0];
6507 FIXME("Unhandled windows NI_xxx flags 0x%x\n", winflags
);
6511 static int convert_aiflag_u2w(int unixflags
) {
6515 for (i
=0;i
<sizeof(ws_aiflag_map
)/sizeof(ws_aiflag_map
[0]);i
++)
6516 if (ws_aiflag_map
[i
][1] & unixflags
) {
6517 winflags
|= ws_aiflag_map
[i
][0];
6518 unixflags
&= ~ws_aiflag_map
[i
][1];
6521 WARN("Unhandled UNIX AI_xxx flags 0x%x\n", unixflags
);
6525 static int convert_eai_u2w(int unixret
) {
6528 if (!unixret
) return 0;
6530 for (i
=0;ws_eai_map
[i
][0];i
++)
6531 if (ws_eai_map
[i
][1] == unixret
)
6532 return ws_eai_map
[i
][0];
6534 if (unixret
== EAI_SYSTEM
)
6535 /* There are broken versions of glibc which return EAI_SYSTEM
6536 * and set errno to 0 instead of returning EAI_NONAME.
6538 return errno
? sock_get_error( errno
) : WS_EAI_NONAME
;
6540 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret
);
6544 static char *get_fqdn(void)
6549 GetComputerNameExA( ComputerNamePhysicalDnsFullyQualified
, NULL
, &size
);
6550 if (GetLastError() != ERROR_MORE_DATA
) return NULL
;
6551 if (!(ret
= HeapAlloc( GetProcessHeap(), 0, size
))) return NULL
;
6552 if (!GetComputerNameExA( ComputerNamePhysicalDnsFullyQualified
, ret
, &size
))
6554 HeapFree( GetProcessHeap(), 0, ret
);
6560 /***********************************************************************
6561 * getaddrinfo (WS2_32.@)
6563 int WINAPI
WS_getaddrinfo(LPCSTR nodename
, LPCSTR servname
, const struct WS_addrinfo
*hints
, struct WS_addrinfo
**res
)
6565 #ifdef HAVE_GETADDRINFO
6566 struct addrinfo
*unixaires
= NULL
;
6568 struct addrinfo unixhints
, *punixhints
= NULL
;
6569 char *dot
, *nodeV6
= NULL
, *fqdn
;
6571 size_t hostname_len
= 0;
6574 if (!nodename
&& !servname
)
6576 SetLastError(WSAHOST_NOT_FOUND
);
6577 return WSAHOST_NOT_FOUND
;
6581 if (!fqdn
) return WSA_NOT_ENOUGH_MEMORY
;
6582 dot
= strchr(fqdn
, '.');
6584 hostname_len
= dot
- fqdn
;
6588 else if (!nodename
[0])
6594 /* Check for [ipv6] or [ipv6]:portnumber, which are supported by Windows */
6595 if (!hints
|| hints
->ai_family
== WS_AF_UNSPEC
|| hints
->ai_family
== WS_AF_INET6
)
6597 char *close_bracket
;
6599 if (node
[0] == '[' && (close_bracket
= strchr(node
+ 1, ']')))
6601 nodeV6
= HeapAlloc(GetProcessHeap(), 0, close_bracket
- node
);
6604 HeapFree(GetProcessHeap(), 0, fqdn
);
6605 return WSA_NOT_ENOUGH_MEMORY
;
6607 lstrcpynA(nodeV6
, node
+ 1, close_bracket
- node
);
6613 /* servname tweak required by OSX and BSD kernels */
6614 if (servname
&& !servname
[0]) servname
= "0";
6617 punixhints
= &unixhints
;
6619 memset(&unixhints
, 0, sizeof(unixhints
));
6620 punixhints
->ai_flags
= convert_aiflag_w2u(hints
->ai_flags
);
6622 /* zero is a wildcard, no need to convert */
6623 if (hints
->ai_family
)
6624 punixhints
->ai_family
= convert_af_w2u(hints
->ai_family
);
6625 if (hints
->ai_socktype
)
6626 punixhints
->ai_socktype
= convert_socktype_w2u(hints
->ai_socktype
);
6627 if (hints
->ai_protocol
)
6628 punixhints
->ai_protocol
= max(convert_proto_w2u(hints
->ai_protocol
), 0);
6630 if (punixhints
->ai_socktype
< 0)
6632 SetLastError(WSAESOCKTNOSUPPORT
);
6633 HeapFree(GetProcessHeap(), 0, fqdn
);
6634 HeapFree(GetProcessHeap(), 0, nodeV6
);
6635 return SOCKET_ERROR
;
6638 /* windows allows invalid combinations of socket type and protocol, unix does not.
6639 * fix the parameters here to make getaddrinfo call always work */
6640 if (punixhints
->ai_protocol
== IPPROTO_TCP
&&
6641 punixhints
->ai_socktype
!= SOCK_STREAM
&& punixhints
->ai_socktype
!= SOCK_SEQPACKET
)
6642 punixhints
->ai_socktype
= 0;
6644 else if (punixhints
->ai_protocol
== IPPROTO_UDP
&& punixhints
->ai_socktype
!= SOCK_DGRAM
)
6645 punixhints
->ai_socktype
= 0;
6647 else if (IS_IPX_PROTO(punixhints
->ai_protocol
) && punixhints
->ai_socktype
!= SOCK_DGRAM
)
6648 punixhints
->ai_socktype
= 0;
6650 else if (punixhints
->ai_protocol
== IPPROTO_IPV6
)
6651 punixhints
->ai_protocol
= 0;
6654 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
6655 result
= getaddrinfo(node
, servname
, punixhints
, &unixaires
);
6657 if (result
&& (!hints
|| !(hints
->ai_flags
& WS_AI_NUMERICHOST
))
6658 && (!strcmp(fqdn
, node
) || (!strncmp(fqdn
, node
, hostname_len
) && !node
[hostname_len
])))
6660 /* If it didn't work it means the host name IP is not in /etc/hosts, try again
6661 * by sending a NULL host and avoid sending a NULL servname too because that
6663 ERR_(winediag
)("Failed to resolve your host name IP\n");
6664 result
= getaddrinfo(NULL
, servname
? servname
: "0", punixhints
, &unixaires
);
6666 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename
), debugstr_a(servname
), hints
, res
, result
);
6667 HeapFree(GetProcessHeap(), 0, fqdn
);
6668 HeapFree(GetProcessHeap(), 0, nodeV6
);
6671 struct addrinfo
*xuai
= unixaires
;
6672 struct WS_addrinfo
**xai
= res
;
6676 struct WS_addrinfo
*ai
= HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY
, sizeof(struct WS_addrinfo
));
6682 *xai
= ai
;xai
= &ai
->ai_next
;
6683 ai
->ai_flags
= convert_aiflag_u2w(xuai
->ai_flags
);
6684 ai
->ai_family
= convert_af_u2w(xuai
->ai_family
);
6685 /* copy whatever was sent in the hints */
6687 ai
->ai_socktype
= hints
->ai_socktype
;
6688 ai
->ai_protocol
= hints
->ai_protocol
;
6690 ai
->ai_socktype
= convert_socktype_u2w(xuai
->ai_socktype
);
6691 ai
->ai_protocol
= convert_proto_u2w(xuai
->ai_protocol
);
6693 if (xuai
->ai_canonname
) {
6694 TRACE("canon name - %s\n",debugstr_a(xuai
->ai_canonname
));
6695 ai
->ai_canonname
= HeapAlloc(GetProcessHeap(),0,strlen(xuai
->ai_canonname
)+1);
6696 if (!ai
->ai_canonname
)
6698 strcpy(ai
->ai_canonname
,xuai
->ai_canonname
);
6700 len
= xuai
->ai_addrlen
;
6701 ai
->ai_addr
= HeapAlloc(GetProcessHeap(),0,len
);
6704 ai
->ai_addrlen
= len
;
6706 int winlen
= ai
->ai_addrlen
;
6708 if (!ws_sockaddr_u2ws(xuai
->ai_addr
, ai
->ai_addr
, &winlen
)) {
6709 ai
->ai_addrlen
= winlen
;
6713 ai
->ai_addr
= HeapReAlloc(GetProcessHeap(),0,ai
->ai_addr
,len
);
6716 ai
->ai_addrlen
= len
;
6718 xuai
= xuai
->ai_next
;
6720 freeaddrinfo(unixaires
);
6722 if (TRACE_ON(winsock
))
6724 struct WS_addrinfo
*ai
= *res
;
6727 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
6728 ai
, ai
->ai_flags
, ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
, ai
->ai_addrlen
,
6729 ai
->ai_canonname
, debugstr_sockaddr(ai
->ai_addr
));
6734 result
= convert_eai_u2w(result
);
6736 SetLastError(result
);
6740 if (*res
) WS_freeaddrinfo(*res
);
6741 if (unixaires
) freeaddrinfo(unixaires
);
6742 return WSA_NOT_ENOUGH_MEMORY
;
6744 FIXME("getaddrinfo() failed, not found during buildtime.\n");
6749 static ADDRINFOEXW
*addrinfo_AtoW(const struct WS_addrinfo
*ai
)
6753 if (!(ret
= HeapAlloc(GetProcessHeap(), 0, sizeof(ADDRINFOEXW
)))) return NULL
;
6754 ret
->ai_flags
= ai
->ai_flags
;
6755 ret
->ai_family
= ai
->ai_family
;
6756 ret
->ai_socktype
= ai
->ai_socktype
;
6757 ret
->ai_protocol
= ai
->ai_protocol
;
6758 ret
->ai_addrlen
= ai
->ai_addrlen
;
6759 ret
->ai_canonname
= NULL
;
6760 ret
->ai_addr
= NULL
;
6761 ret
->ai_blob
= NULL
;
6762 ret
->ai_bloblen
= 0;
6763 ret
->ai_provider
= NULL
;
6764 ret
->ai_next
= NULL
;
6765 if (ai
->ai_canonname
)
6767 int len
= MultiByteToWideChar(CP_ACP
, 0, ai
->ai_canonname
, -1, NULL
, 0);
6768 if (!(ret
->ai_canonname
= HeapAlloc(GetProcessHeap(), 0, len
*sizeof(WCHAR
))))
6770 HeapFree(GetProcessHeap(), 0, ret
);
6773 MultiByteToWideChar(CP_ACP
, 0, ai
->ai_canonname
, -1, ret
->ai_canonname
, len
);
6777 if (!(ret
->ai_addr
= HeapAlloc(GetProcessHeap(), 0, ai
->ai_addrlen
)))
6779 HeapFree(GetProcessHeap(), 0, ret
->ai_canonname
);
6780 HeapFree(GetProcessHeap(), 0, ret
);
6783 memcpy(ret
->ai_addr
, ai
->ai_addr
, ai
->ai_addrlen
);
6788 static ADDRINFOEXW
*addrinfo_list_AtoW(const struct WS_addrinfo
*info
)
6790 ADDRINFOEXW
*ret
, *infoW
;
6792 if (!(ret
= infoW
= addrinfo_AtoW(info
))) return NULL
;
6793 while (info
->ai_next
)
6795 if (!(infoW
->ai_next
= addrinfo_AtoW(info
->ai_next
)))
6797 FreeAddrInfoExW(ret
);
6800 infoW
= infoW
->ai_next
;
6801 info
= info
->ai_next
;
6806 static struct WS_addrinfo
*addrinfo_WtoA(const struct WS_addrinfoW
*ai
)
6808 struct WS_addrinfo
*ret
;
6810 if (!(ret
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo
)))) return NULL
;
6811 ret
->ai_flags
= ai
->ai_flags
;
6812 ret
->ai_family
= ai
->ai_family
;
6813 ret
->ai_socktype
= ai
->ai_socktype
;
6814 ret
->ai_protocol
= ai
->ai_protocol
;
6815 ret
->ai_addrlen
= ai
->ai_addrlen
;
6816 ret
->ai_canonname
= NULL
;
6817 ret
->ai_addr
= NULL
;
6818 ret
->ai_next
= NULL
;
6819 if (ai
->ai_canonname
)
6821 int len
= WideCharToMultiByte(CP_ACP
, 0, ai
->ai_canonname
, -1, NULL
, 0, NULL
, NULL
);
6822 if (!(ret
->ai_canonname
= HeapAlloc(GetProcessHeap(), 0, len
)))
6824 HeapFree(GetProcessHeap(), 0, ret
);
6827 WideCharToMultiByte(CP_ACP
, 0, ai
->ai_canonname
, -1, ret
->ai_canonname
, len
, NULL
, NULL
);
6831 if (!(ret
->ai_addr
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr
))))
6833 HeapFree(GetProcessHeap(), 0, ret
->ai_canonname
);
6834 HeapFree(GetProcessHeap(), 0, ret
);
6837 memcpy(ret
->ai_addr
, ai
->ai_addr
, sizeof(struct WS_sockaddr
));
6842 struct getaddrinfo_args
6844 OVERLAPPED
*overlapped
;
6845 ADDRINFOEXW
**result
;
6850 static void WINAPI
getaddrinfo_callback(TP_CALLBACK_INSTANCE
*instance
, void *context
)
6852 struct getaddrinfo_args
*args
= context
;
6853 OVERLAPPED
*overlapped
= args
->overlapped
;
6854 HANDLE event
= overlapped
->hEvent
;
6855 struct WS_addrinfo
*res
;
6858 ret
= WS_getaddrinfo(args
->nodename
, args
->servname
, NULL
, &res
);
6861 *args
->result
= addrinfo_list_AtoW(res
);
6862 overlapped
->u
.Pointer
= args
->result
;
6863 WS_freeaddrinfo(res
);
6866 HeapFree(GetProcessHeap(), 0, args
->nodename
);
6867 HeapFree(GetProcessHeap(), 0, args
->servname
);
6868 HeapFree(GetProcessHeap(), 0, args
);
6870 overlapped
->Internal
= ret
;
6871 if (event
) SetEvent(event
);
6874 static int WS_getaddrinfoW(const WCHAR
*nodename
, const WCHAR
*servname
, const struct WS_addrinfo
*hints
, ADDRINFOEXW
**res
, OVERLAPPED
*overlapped
)
6876 int ret
= EAI_MEMORY
, len
, i
;
6877 char *nodenameA
= NULL
, *servnameA
= NULL
;
6878 struct WS_addrinfo
*resA
;
6879 WCHAR
*local_nodenameW
= (WCHAR
*)nodename
;
6884 /* Is this an IDN? Most likely if any char is above the Ascii table, this
6885 * is the simplest validation possible, further validation will be done by
6886 * the native getaddrinfo() */
6887 for (i
= 0; nodename
[i
]; i
++)
6889 if (nodename
[i
] > 'z')
6894 if (hints
&& (hints
->ai_flags
& WS_AI_DISABLE_IDN_ENCODING
))
6896 /* Name requires conversion but it was disabled */
6897 ret
= WSAHOST_NOT_FOUND
;
6898 WSASetLastError(ret
);
6902 len
= IdnToAscii(0, nodename
, -1, NULL
, 0);
6905 ERR("Failed to convert %s to punycode\n", debugstr_w(nodename
));
6909 if (!(local_nodenameW
= HeapAlloc(GetProcessHeap(), 0, len
* sizeof(WCHAR
)))) goto end
;
6910 IdnToAscii(0, nodename
, -1, local_nodenameW
, len
);
6913 if (local_nodenameW
)
6915 len
= WideCharToMultiByte(CP_ACP
, 0, local_nodenameW
, -1, NULL
, 0, NULL
, NULL
);
6916 if (!(nodenameA
= HeapAlloc(GetProcessHeap(), 0, len
))) goto end
;
6917 WideCharToMultiByte(CP_ACP
, 0, local_nodenameW
, -1, nodenameA
, len
, NULL
, NULL
);
6921 len
= WideCharToMultiByte(CP_ACP
, 0, servname
, -1, NULL
, 0, NULL
, NULL
);
6922 if (!(servnameA
= HeapAlloc(GetProcessHeap(), 0, len
))) goto end
;
6923 WideCharToMultiByte(CP_ACP
, 0, servname
, -1, servnameA
, len
, NULL
, NULL
);
6928 struct getaddrinfo_args
*args
;
6930 if (!(args
= HeapAlloc(GetProcessHeap(), 0, sizeof(*args
)))) goto end
;
6931 args
->overlapped
= overlapped
;
6933 args
->nodename
= nodenameA
;
6934 args
->servname
= servnameA
;
6936 overlapped
->Internal
= WSAEINPROGRESS
;
6937 if (!TrySubmitThreadpoolCallback(getaddrinfo_callback
, args
, NULL
))
6939 HeapFree(GetProcessHeap(), 0, args
);
6940 ret
= GetLastError();
6945 if (local_nodenameW
!= nodename
)
6946 HeapFree(GetProcessHeap(), 0, local_nodenameW
);
6947 WSASetLastError(ERROR_IO_PENDING
);
6948 return ERROR_IO_PENDING
;
6951 ret
= WS_getaddrinfo(nodenameA
, servnameA
, hints
, &resA
);
6954 *res
= addrinfo_list_AtoW(resA
);
6955 WS_freeaddrinfo(resA
);
6959 if (local_nodenameW
!= nodename
)
6960 HeapFree(GetProcessHeap(), 0, local_nodenameW
);
6961 HeapFree(GetProcessHeap(), 0, nodenameA
);
6962 HeapFree(GetProcessHeap(), 0, servnameA
);
6966 /***********************************************************************
6967 * GetAddrInfoExW (WS2_32.@)
6969 int WINAPI
GetAddrInfoExW(const WCHAR
*name
, const WCHAR
*servname
, DWORD
namespace, GUID
*namespace_id
,
6970 const ADDRINFOEXW
*hints
, ADDRINFOEXW
**result
, struct timeval
*timeout
, OVERLAPPED
*overlapped
,
6971 LPLOOKUPSERVICE_COMPLETION_ROUTINE completion_routine
, HANDLE
*handle
)
6975 TRACE("(%s %s %x %s %p %p %p %p %p %p)\n", debugstr_w(name
), debugstr_w(servname
), namespace,
6976 debugstr_guid(namespace_id
), hints
, result
, timeout
, overlapped
, completion_routine
, handle
);
6978 if (namespace != NS_DNS
)
6979 FIXME("Unsupported namespace %u\n", namespace);
6981 FIXME("Unsupported naemspace_id %s\n", debugstr_guid(namespace_id
));
6983 FIXME("Unsupported hints\n");
6985 FIXME("Unsupported timeout\n");
6986 if (completion_routine
)
6987 FIXME("Unsupported completion_routine\n");
6989 FIXME("Unsupported cancel handle\n");
6991 ret
= WS_getaddrinfoW(name
, servname
, NULL
, result
, overlapped
);
6992 if (ret
) return ret
;
6993 if (handle
) *handle
= (HANDLE
)0xdeadbeef;
6997 /***********************************************************************
6998 * GetAddrInfoExOverlappedResult (WS2_32.@)
7000 int WINAPI
GetAddrInfoExOverlappedResult(OVERLAPPED
*overlapped
)
7002 TRACE("(%p)\n", overlapped
);
7003 return overlapped
->Internal
;
7006 /***********************************************************************
7007 * GetAddrInfoExCancel (WS2_32.@)
7009 int WINAPI
GetAddrInfoExCancel(HANDLE
*handle
)
7011 FIXME("(%p)\n", handle
);
7012 return WSA_INVALID_HANDLE
;
7015 /***********************************************************************
7016 * GetAddrInfoW (WS2_32.@)
7018 int WINAPI
GetAddrInfoW(LPCWSTR nodename
, LPCWSTR servname
, const ADDRINFOW
*hints
, PADDRINFOW
*res
)
7020 struct WS_addrinfo
*hintsA
= NULL
;
7022 int ret
= EAI_MEMORY
;
7024 TRACE("nodename %s, servname %s, hints %p, result %p\n",
7025 debugstr_w(nodename
), debugstr_w(servname
), hints
, res
);
7028 if (hints
) hintsA
= addrinfo_WtoA(hints
);
7029 ret
= WS_getaddrinfoW(nodename
, servname
, hintsA
, &resex
, NULL
);
7030 WS_freeaddrinfo(hintsA
);
7031 if (ret
) return ret
;
7035 /* ADDRINFOEXW has layout compatible with ADDRINFOW except for ai_next field,
7036 * so we may convert it in place */
7037 *res
= (ADDRINFOW
*)resex
;
7039 ((ADDRINFOW
*)resex
)->ai_next
= (ADDRINFOW
*)resex
->ai_next
;
7040 resex
= resex
->ai_next
;
7046 /***********************************************************************
7047 * FreeAddrInfoW (WS2_32.@)
7049 void WINAPI
FreeAddrInfoW(PADDRINFOW ai
)
7054 HeapFree(GetProcessHeap(), 0, ai
->ai_canonname
);
7055 HeapFree(GetProcessHeap(), 0, ai
->ai_addr
);
7057 HeapFree(GetProcessHeap(), 0, ai
);
7062 /***********************************************************************
7063 * FreeAddrInfoExW (WS2_32.@)
7065 void WINAPI
FreeAddrInfoExW(ADDRINFOEXW
*ai
)
7067 TRACE("(%p)\n", ai
);
7072 HeapFree(GetProcessHeap(), 0, ai
->ai_canonname
);
7073 HeapFree(GetProcessHeap(), 0, ai
->ai_addr
);
7075 HeapFree(GetProcessHeap(), 0, ai
);
7080 int WINAPI
WS_getnameinfo(const SOCKADDR
*sa
, WS_socklen_t salen
, PCHAR host
,
7081 DWORD hostlen
, PCHAR serv
, DWORD servlen
, INT flags
)
7083 #ifdef HAVE_GETNAMEINFO
7085 union generic_unix_sockaddr sa_u
;
7088 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa
), salen
, host
, hostlen
,
7089 serv
, servlen
, flags
);
7091 size
= ws_sockaddr_ws2u(sa
, salen
, &sa_u
);
7094 SetLastError(WSAEFAULT
);
7095 return WSA_NOT_ENOUGH_MEMORY
;
7097 ret
= getnameinfo(&sa_u
.addr
, size
, host
, hostlen
, serv
, servlen
, convert_niflag_w2u(flags
));
7098 return convert_eai_u2w(ret
);
7100 FIXME("getnameinfo() failed, not found during buildtime.\n");
7105 int WINAPI
GetNameInfoW(const SOCKADDR
*sa
, WS_socklen_t salen
, PWCHAR host
,
7106 DWORD hostlen
, PWCHAR serv
, DWORD servlen
, INT flags
)
7109 char *hostA
= NULL
, *servA
= NULL
;
7111 if (host
&& (!(hostA
= HeapAlloc(GetProcessHeap(), 0, hostlen
)))) return EAI_MEMORY
;
7112 if (serv
&& (!(servA
= HeapAlloc(GetProcessHeap(), 0, servlen
))))
7114 HeapFree(GetProcessHeap(), 0, hostA
);
7118 ret
= WS_getnameinfo(sa
, salen
, hostA
, hostlen
, servA
, servlen
, flags
);
7121 if (host
) MultiByteToWideChar(CP_ACP
, 0, hostA
, -1, host
, hostlen
);
7122 if (serv
) MultiByteToWideChar(CP_ACP
, 0, servA
, -1, serv
, servlen
);
7125 HeapFree(GetProcessHeap(), 0, hostA
);
7126 HeapFree(GetProcessHeap(), 0, servA
);
7130 /***********************************************************************
7131 * getservbyport (WS2_32.56)
7133 struct WS_servent
* WINAPI
WS_getservbyport(int port
, const char *proto
)
7135 struct WS_servent
* retval
= NULL
;
7136 #ifdef HAVE_GETSERVBYPORT
7137 struct servent
* serv
;
7138 char *proto_str
= NULL
;
7140 if (proto
&& *proto
)
7142 if (!(proto_str
= strdup_lower(proto
))) return NULL
;
7144 EnterCriticalSection( &csWSgetXXXbyYYY
);
7145 if( (serv
= getservbyport(port
, proto_str
)) != NULL
) {
7146 retval
= WS_dup_se(serv
);
7148 else SetLastError(WSANO_DATA
);
7149 LeaveCriticalSection( &csWSgetXXXbyYYY
);
7150 HeapFree( GetProcessHeap(), 0, proto_str
);
7152 TRACE("%d (i.e. port %d), %s ret %p\n", port
, (int)ntohl(port
), debugstr_a(proto
), retval
);
7157 /***********************************************************************
7158 * gethostname (WS2_32.57)
7160 int WINAPI
WS_gethostname(char *name
, int namelen
)
7165 TRACE("name %p, len %d\n", name
, namelen
);
7169 SetLastError(WSAEFAULT
);
7170 return SOCKET_ERROR
;
7173 if (gethostname(buf
, sizeof(buf
)) != 0)
7175 SetLastError(wsaErrno());
7176 return SOCKET_ERROR
;
7179 TRACE("<- '%s'\n", buf
);
7182 WARN("Windows supports NetBIOS name length up to 15 bytes!\n");
7185 SetLastError(WSAEFAULT
);
7186 WARN("<- not enough space for hostname, required %d, got %d!\n", len
+ 1, namelen
);
7187 return SOCKET_ERROR
;
7194 /* ------------------------------------- Windows sockets extensions -- *
7196 * ------------------------------------------------------------------- */
7198 /***********************************************************************
7199 * WSAEnumNetworkEvents (WS2_32.36)
7201 int WINAPI
WSAEnumNetworkEvents(SOCKET s
, WSAEVENT hEvent
, LPWSANETWORKEVENTS lpEvent
)
7205 int errors
[FD_MAX_EVENTS
];
7207 TRACE("%04lx, hEvent %p, lpEvent %p\n", s
, hEvent
, lpEvent
);
7209 SERVER_START_REQ( get_socket_event
)
7211 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
7212 req
->service
= TRUE
;
7213 req
->c_event
= wine_server_obj_handle( hEvent
);
7214 wine_server_set_reply( req
, errors
, sizeof(errors
) );
7215 if (!(ret
= wine_server_call(req
))) lpEvent
->lNetworkEvents
= reply
->pmask
& reply
->mask
;
7220 for (i
= 0; i
< FD_MAX_EVENTS
; i
++)
7221 lpEvent
->iErrorCode
[i
] = NtStatusToWSAError(errors
[i
]);
7224 SetLastError(WSAEINVAL
);
7225 return SOCKET_ERROR
;
7228 /***********************************************************************
7229 * WSAEventSelect (WS2_32.39)
7231 int WINAPI
WSAEventSelect(SOCKET s
, WSAEVENT hEvent
, LONG lEvent
)
7235 TRACE("%04lx, hEvent %p, event %08x\n", s
, hEvent
, lEvent
);
7237 SERVER_START_REQ( set_socket_event
)
7239 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
7241 req
->event
= wine_server_obj_handle( hEvent
);
7244 ret
= wine_server_call( req
);
7248 SetLastError(WSAEINVAL
);
7249 return SOCKET_ERROR
;
7252 /**********************************************************************
7253 * WSAGetOverlappedResult (WS2_32.40)
7255 BOOL WINAPI
WSAGetOverlappedResult( SOCKET s
, LPWSAOVERLAPPED lpOverlapped
,
7256 LPDWORD lpcbTransfer
, BOOL fWait
,
7261 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
7262 s
, lpOverlapped
, lpcbTransfer
, fWait
, lpdwFlags
);
7264 if ( lpOverlapped
== NULL
)
7266 ERR( "Invalid pointer\n" );
7267 SetLastError(WSA_INVALID_PARAMETER
);
7271 status
= lpOverlapped
->Internal
;
7272 if (status
== STATUS_PENDING
)
7276 SetLastError( WSA_IO_INCOMPLETE
);
7280 if (WaitForSingleObject( lpOverlapped
->hEvent
? lpOverlapped
->hEvent
: SOCKET2HANDLE(s
),
7281 INFINITE
) == WAIT_FAILED
)
7283 status
= lpOverlapped
->Internal
;
7287 *lpcbTransfer
= lpOverlapped
->InternalHigh
;
7290 *lpdwFlags
= lpOverlapped
->u
.s
.Offset
;
7292 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
7297 /***********************************************************************
7298 * WSAAsyncSelect (WS2_32.101)
7300 INT WINAPI
WSAAsyncSelect(SOCKET s
, HWND hWnd
, UINT uMsg
, LONG lEvent
)
7304 TRACE("%04lx, hWnd %p, uMsg %08x, event %08x\n", s
, hWnd
, uMsg
, lEvent
);
7306 SERVER_START_REQ( set_socket_event
)
7308 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
7311 req
->window
= wine_server_user_handle( hWnd
);
7313 ret
= wine_server_call( req
);
7317 SetLastError(WSAEINVAL
);
7318 return SOCKET_ERROR
;
7321 /***********************************************************************
7322 * WSACreateEvent (WS2_32.31)
7325 WSAEVENT WINAPI
WSACreateEvent(void)
7327 /* Create a manual-reset event, with initial state: unsignaled */
7330 return CreateEventW(NULL
, TRUE
, FALSE
, NULL
);
7333 /***********************************************************************
7334 * WSACloseEvent (WS2_32.29)
7337 BOOL WINAPI
WSACloseEvent(WSAEVENT event
)
7339 TRACE ("event=%p\n", event
);
7341 return CloseHandle(event
);
7344 /***********************************************************************
7345 * WSASocketA (WS2_32.78)
7348 SOCKET WINAPI
WSASocketA(int af
, int type
, int protocol
,
7349 LPWSAPROTOCOL_INFOA lpProtocolInfo
,
7350 GROUP g
, DWORD dwFlags
)
7353 WSAPROTOCOL_INFOW info
;
7355 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
7356 af
, type
, protocol
, lpProtocolInfo
, g
, dwFlags
);
7358 if (!lpProtocolInfo
) return WSASocketW(af
, type
, protocol
, NULL
, g
, dwFlags
);
7360 memcpy(&info
, lpProtocolInfo
, FIELD_OFFSET(WSAPROTOCOL_INFOW
, szProtocol
));
7361 len
= MultiByteToWideChar(CP_ACP
, 0, lpProtocolInfo
->szProtocol
, -1,
7362 info
.szProtocol
, WSAPROTOCOL_LEN
+ 1);
7366 SetLastError(WSAEINVAL
);
7367 return SOCKET_ERROR
;
7370 return WSASocketW(af
, type
, protocol
, &info
, g
, dwFlags
);
7373 /***********************************************************************
7374 * WSASocketW (WS2_32.79)
7377 SOCKET WINAPI
WSASocketW(int af
, int type
, int protocol
,
7378 LPWSAPROTOCOL_INFOW lpProtocolInfo
,
7379 GROUP g
, DWORD dwFlags
)
7383 int unixaf
, unixtype
, ipxptype
= -1;
7386 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
7387 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
7390 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
7391 af
, type
, protocol
, lpProtocolInfo
, g
, dwFlags
);
7395 err
= WSANOTINITIALISED
;
7399 /* hack for WSADuplicateSocket */
7400 if (lpProtocolInfo
&& lpProtocolInfo
->dwServiceFlags4
== 0xff00ff00) {
7401 ret
= lpProtocolInfo
->dwServiceFlags3
;
7402 TRACE("\tgot duplicate %04lx\n", ret
);
7408 if (af
== FROM_PROTOCOL_INFO
|| !af
)
7409 af
= lpProtocolInfo
->iAddressFamily
;
7410 if (type
== FROM_PROTOCOL_INFO
|| !type
)
7411 type
= lpProtocolInfo
->iSocketType
;
7412 if (protocol
== FROM_PROTOCOL_INFO
|| !protocol
)
7413 protocol
= lpProtocolInfo
->iProtocol
;
7416 if (!type
&& (af
|| protocol
))
7418 int autoproto
= protocol
;
7419 WSAPROTOCOL_INFOW infow
;
7421 /* default to the first valid protocol */
7423 autoproto
= valid_protocols
[0];
7424 else if(IS_IPX_PROTO(autoproto
))
7425 autoproto
= WS_NSPROTO_IPX
;
7427 if (WS_EnterSingleProtocolW(autoproto
, &infow
))
7429 type
= infow
.iSocketType
;
7431 /* after win2003 it's no longer possible to pass AF_UNSPEC
7432 using the protocol info struct */
7433 if (!lpProtocolInfo
&& af
== WS_AF_UNSPEC
)
7434 af
= infow
.iAddressFamily
;
7439 Windows has an extension to the IPX protocol that allows one to create sockets
7440 and set the IPX packet type at the same time, to do that a caller will use
7441 a protocol like NSPROTO_IPX + <PACKET TYPE>
7443 if (IS_IPX_PROTO(protocol
))
7444 ipxptype
= protocol
- WS_NSPROTO_IPX
;
7446 /* convert the socket family, type and protocol */
7447 unixaf
= convert_af_w2u(af
);
7448 unixtype
= convert_socktype_w2u(type
);
7449 protocol
= convert_proto_w2u(protocol
);
7450 if (unixaf
== AF_UNSPEC
) unixaf
= -1;
7452 /* filter invalid parameters */
7455 /* the type could not be converted */
7456 if (type
&& unixtype
< 0)
7458 err
= WSAESOCKTNOSUPPORT
;
7462 err
= WSAEPROTONOSUPPORT
;
7467 /* both family and protocol can't be invalid */
7474 /* family could not be converted and neither socket type */
7475 if (unixtype
< 0 && af
>= 0)
7478 err
= WSAESOCKTNOSUPPORT
;
7482 err
= WSAEAFNOSUPPORT
;
7486 SERVER_START_REQ( create_socket
)
7488 req
->family
= unixaf
;
7489 req
->type
= unixtype
;
7490 req
->protocol
= protocol
;
7491 req
->access
= GENERIC_READ
|GENERIC_WRITE
|SYNCHRONIZE
;
7492 req
->attributes
= (dwFlags
& WSA_FLAG_NO_HANDLE_INHERIT
) ? 0 : OBJ_INHERIT
;
7493 req
->flags
= dwFlags
& ~WSA_FLAG_NO_HANDLE_INHERIT
;
7494 set_error( wine_server_call( req
) );
7495 ret
= HANDLE2SOCKET( wine_server_ptr_handle( reply
->handle
));
7500 TRACE("\tcreated %04lx\n", ret
);
7502 set_ipx_packettype(ret
, ipxptype
);
7504 /* ensure IP_DONTFRAGMENT is disabled, in Linux the global default can be enabled */
7505 if (unixaf
== AF_INET
|| unixaf
== AF_INET6
)
7506 set_dont_fragment(ret
, unixaf
== AF_INET6
? IPPROTO_IPV6
: IPPROTO_IP
, FALSE
);
7509 if (unixaf
== AF_INET6
)
7511 int fd
= get_sock_fd(ret
, 0, NULL
);
7514 /* IPV6_V6ONLY is set by default on Windows */
7516 if (setsockopt(fd
, IPPROTO_IPV6
, IPV6_V6ONLY
, &enable
, sizeof(enable
)))
7517 WARN("\tsetting IPV6_V6ONLY failed - errno = %i\n", errno
);
7518 release_sock_fd(ret
, fd
);
7525 err
= GetLastError();
7526 if (err
== WSAEACCES
) /* raw socket denied */
7528 if (type
== SOCK_RAW
)
7529 ERR_(winediag
)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
7531 ERR_(winediag
)("Failed to create socket, this requires special permissions.\n");
7535 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
7536 if (err
== WSAEINVAL
)
7537 err
= WSAESOCKTNOSUPPORT
;
7538 else if (err
== WSAEOPNOTSUPP
)
7539 err
= WSAEPROTONOSUPPORT
;
7543 WARN("\t\tfailed, error %d!\n", err
);
7545 return INVALID_SOCKET
;
7548 /***********************************************************************
7549 * WSAJoinLeaf (WS2_32.58)
7552 SOCKET WINAPI
WSAJoinLeaf(
7554 const struct WS_sockaddr
*addr
,
7556 LPWSABUF lpCallerData
,
7557 LPWSABUF lpCalleeData
,
7563 return INVALID_SOCKET
;
7566 /***********************************************************************
7567 * __WSAFDIsSet (WS2_32.151)
7569 int WINAPI
__WSAFDIsSet(SOCKET s
, WS_fd_set
*set
)
7571 int i
= set
->fd_count
, ret
= 0;
7574 if (set
->fd_array
[i
] == s
)
7580 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s
, set
, set
->fd_count
, ret
);
7584 /***********************************************************************
7585 * WSAIsBlocking (WS2_32.114)
7587 BOOL WINAPI
WSAIsBlocking(void)
7589 /* By default WinSock should set all its sockets to non-blocking mode
7590 * and poll in PeekMessage loop when processing "blocking" ones. This
7591 * function is supposed to tell if the program is in this loop. Our
7592 * blocking calls are truly blocking so we always return FALSE.
7594 * Note: It is allowed to call this function without prior WSAStartup().
7601 /***********************************************************************
7602 * WSACancelBlockingCall (WS2_32.113)
7604 INT WINAPI
WSACancelBlockingCall(void)
7610 static INT WINAPI
WSA_DefaultBlockingHook( FARPROC x
)
7612 FIXME("How was this called?\n");
7617 /***********************************************************************
7618 * WSASetBlockingHook (WS2_32.109)
7620 FARPROC WINAPI
WSASetBlockingHook(FARPROC lpBlockFunc
)
7622 FARPROC prev
= blocking_hook
;
7623 blocking_hook
= lpBlockFunc
;
7624 TRACE("hook %p\n", lpBlockFunc
);
7629 /***********************************************************************
7630 * WSAUnhookBlockingHook (WS2_32.110)
7632 INT WINAPI
WSAUnhookBlockingHook(void)
7634 blocking_hook
= (FARPROC
)WSA_DefaultBlockingHook
;
7639 /* ----------------------------------- end of API stuff */
7641 /* ----------------------------------- helper functions -
7643 * TODO: Merge WS_dup_..() stuff into one function that
7644 * would operate with a generic structure containing internal
7645 * pointers (via a template of some kind).
7648 static int list_size(char** l
, int item_size
)
7653 j
+= (item_size
) ? item_size
: strlen(l
[i
]) + 1;
7654 j
+= (i
+ 1) * sizeof(char*); }
7658 static int list_dup(char** l_src
, char** l_to
, int item_size
)
7663 for (i
= 0; l_src
[i
]; i
++) ;
7664 p
= (char *)(l_to
+ i
+ 1);
7665 for (i
= 0; l_src
[i
]; i
++)
7667 int count
= ( item_size
) ? item_size
: strlen(l_src
[i
]) + 1;
7668 memcpy(p
, l_src
[i
], count
);
7673 return p
- (char *)l_to
;
7678 /* create a hostent entry
7680 * Creates the entry with enough memory for the name, aliases
7681 * addresses, and the address pointers. Also copies the name
7682 * and sets up all the pointers.
7684 * NOTE: The alias and address lists must be allocated with room
7685 * for the NULL item terminating the list. This is true even if
7686 * the list has no items ("aliases" and "addresses" must be
7687 * at least "1", a truly empty list is invalid).
7689 static struct WS_hostent
*WS_create_he(char *name
, int aliases
, int aliases_size
, int addresses
, int address_length
)
7691 struct WS_hostent
*p_to
;
7693 int size
= (sizeof(struct WS_hostent
) +
7695 sizeof(char *) * aliases
+
7697 sizeof(char *) * addresses
+
7698 address_length
* (addresses
- 1)), i
;
7700 if (!(p_to
= check_buffer_he(size
))) return NULL
;
7701 memset(p_to
, 0, size
);
7703 /* Use the memory in the same way winsock does.
7704 * First set the pointer for aliases, second set the pointers for addresses.
7705 * Third fill the addresses indexes, fourth jump aliases names size.
7706 * Fifth fill the hostname.
7707 * NOTE: This method is valid for OS version's >= XP.
7709 p
= (char *)(p_to
+ 1);
7710 p_to
->h_aliases
= (char **)p
;
7711 p
+= sizeof(char *)*aliases
;
7713 p_to
->h_addr_list
= (char **)p
;
7714 p
+= sizeof(char *)*addresses
;
7716 for (i
= 0, addresses
--; i
< addresses
; i
++, p
+= address_length
)
7717 p_to
->h_addr_list
[i
] = p
;
7719 /* NOTE: h_aliases must be filled in manually because we don't know each string
7720 * size, leave these pointers NULL (already set to NULL by memset earlier).
7730 /* duplicate hostent entry
7731 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
7732 * Ditto for protoent and servent.
7734 static struct WS_hostent
*WS_dup_he(const struct hostent
* p_he
)
7736 int i
, addresses
= 0, alias_size
= 0;
7737 struct WS_hostent
*p_to
;
7740 for( i
= 0; p_he
->h_aliases
[i
]; i
++) alias_size
+= strlen(p_he
->h_aliases
[i
]) + 1;
7741 while (p_he
->h_addr_list
[addresses
]) addresses
++;
7743 p_to
= WS_create_he(p_he
->h_name
, i
+ 1, alias_size
, addresses
+ 1, p_he
->h_length
);
7745 if (!p_to
) return NULL
;
7746 p_to
->h_addrtype
= convert_af_u2w(p_he
->h_addrtype
);
7747 p_to
->h_length
= p_he
->h_length
;
7749 for(i
= 0, p
= p_to
->h_addr_list
[0]; p_he
->h_addr_list
[i
]; i
++, p
+= p_to
->h_length
)
7750 memcpy(p
, p_he
->h_addr_list
[i
], p_to
->h_length
);
7752 /* Fill the aliases after the IP data */
7753 for(i
= 0; p_he
->h_aliases
[i
]; i
++)
7755 p_to
->h_aliases
[i
] = p
;
7756 strcpy(p
, p_he
->h_aliases
[i
]);
7763 /* ----- protoent */
7765 static struct WS_protoent
*WS_dup_pe(const struct protoent
* p_pe
)
7768 struct WS_protoent
*p_to
;
7770 int size
= (sizeof(*p_pe
) +
7771 strlen(p_pe
->p_name
) + 1 +
7772 list_size(p_pe
->p_aliases
, 0));
7774 if (!(p_to
= check_buffer_pe(size
))) return NULL
;
7775 p_to
->p_proto
= p_pe
->p_proto
;
7777 p
= (char *)(p_to
+ 1);
7779 strcpy(p
, p_pe
->p_name
);
7782 p_to
->p_aliases
= (char **)p
;
7783 list_dup(p_pe
->p_aliases
, p_to
->p_aliases
, 0);
7789 static struct WS_servent
*WS_dup_se(const struct servent
* p_se
)
7792 struct WS_servent
*p_to
;
7794 int size
= (sizeof(*p_se
) +
7795 strlen(p_se
->s_proto
) + 1 +
7796 strlen(p_se
->s_name
) + 1 +
7797 list_size(p_se
->s_aliases
, 0));
7799 if (!(p_to
= check_buffer_se(size
))) return NULL
;
7800 p_to
->s_port
= p_se
->s_port
;
7802 p
= (char *)(p_to
+ 1);
7804 strcpy(p
, p_se
->s_name
);
7808 strcpy(p
, p_se
->s_proto
);
7811 p_to
->s_aliases
= (char **)p
;
7812 list_dup(p_se
->s_aliases
, p_to
->s_aliases
, 0);
7817 /***********************************************************************
7818 * WSARecv (WS2_32.67)
7820 int WINAPI
WSARecv(SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
7821 LPDWORD NumberOfBytesReceived
, LPDWORD lpFlags
,
7822 LPWSAOVERLAPPED lpOverlapped
,
7823 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
7825 return WS2_recv_base(s
, lpBuffers
, dwBufferCount
, NumberOfBytesReceived
, lpFlags
,
7826 NULL
, NULL
, lpOverlapped
, lpCompletionRoutine
, NULL
);
7829 static int WS2_recv_base( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
7830 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
,
7831 struct WS_sockaddr
*lpFrom
,
7832 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
7833 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
,
7834 LPWSABUF lpControlBuffer
)
7836 unsigned int i
, options
;
7837 int n
, fd
, err
, overlapped
, flags
;
7838 struct ws2_async
*wsa
= NULL
, localwsa
;
7840 DWORD timeout_start
= GetTickCount();
7841 ULONG_PTR cvalue
= (lpOverlapped
&& ((ULONG_PTR
)lpOverlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)lpOverlapped
: 0;
7843 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
7844 s
, lpBuffers
, dwBufferCount
, *lpFlags
, lpFrom
,
7845 (lpFromlen
? *lpFromlen
: -1),
7846 lpOverlapped
, lpCompletionRoutine
);
7848 fd
= get_sock_fd( s
, FILE_READ_DATA
, &options
);
7849 TRACE( "fd=%d, options=%x\n", fd
, options
);
7851 if (fd
== -1) return SOCKET_ERROR
;
7853 if (*lpFlags
& WS_MSG_OOB
)
7855 /* It's invalid to receive OOB data from an OOBINLINED socket
7856 * as OOB data is turned into normal data. */
7857 socklen_t len
= sizeof(n
);
7858 if (!getsockopt(fd
, SOL_SOCKET
, SO_OOBINLINE
, (char*) &n
, &len
) && n
)
7865 overlapped
= (lpOverlapped
|| lpCompletionRoutine
) &&
7866 !(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
));
7867 if (overlapped
|| dwBufferCount
> 1)
7869 if (!(wsa
= (struct ws2_async
*)alloc_async_io( offsetof(struct ws2_async
, iovec
[dwBufferCount
]),
7879 wsa
->hSocket
= SOCKET2HANDLE(s
);
7880 wsa
->flags
= *lpFlags
;
7881 wsa
->lpFlags
= lpFlags
;
7883 wsa
->addrlen
.ptr
= lpFromlen
;
7884 wsa
->control
= lpControlBuffer
;
7885 wsa
->n_iovecs
= dwBufferCount
;
7886 wsa
->first_iovec
= 0;
7887 for (i
= 0; i
< dwBufferCount
; i
++)
7889 /* check buffer first to trigger write watches */
7890 if (IsBadWritePtr( lpBuffers
[i
].buf
, lpBuffers
[i
].len
))
7895 wsa
->iovec
[i
].iov_base
= lpBuffers
[i
].buf
;
7896 wsa
->iovec
[i
].iov_len
= lpBuffers
[i
].len
;
7899 flags
= convert_flags(wsa
->flags
);
7902 n
= WS2_recv( fd
, wsa
, flags
);
7905 /* Unix-like systems return EINVAL when attempting to read OOB data from
7906 * an empty socket buffer, convert that to a Windows expected return. */
7907 if ((flags
& MSG_OOB
) && errno
== EINVAL
)
7908 errno
= EWOULDBLOCK
;
7910 if (errno
!= EAGAIN
)
7916 else if (lpNumberOfBytesRecvd
) *lpNumberOfBytesRecvd
= n
;
7920 IO_STATUS_BLOCK
*iosb
= lpOverlapped
? (IO_STATUS_BLOCK
*)lpOverlapped
: &wsa
->local_iosb
;
7922 wsa
->user_overlapped
= lpOverlapped
;
7923 wsa
->completion_func
= lpCompletionRoutine
;
7924 release_sock_fd( s
, fd
);
7928 iosb
->u
.Status
= STATUS_PENDING
;
7929 iosb
->Information
= 0;
7931 if (wsa
->completion_func
)
7932 err
= register_async( ASYNC_TYPE_READ
, wsa
->hSocket
, &wsa
->io
, NULL
,
7933 ws2_async_apc
, wsa
, iosb
);
7935 err
= register_async( ASYNC_TYPE_READ
, wsa
->hSocket
, &wsa
->io
, lpOverlapped
->hEvent
,
7936 NULL
, (void *)cvalue
, iosb
);
7938 if (err
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
7939 SetLastError(NtStatusToWSAError( err
));
7940 return SOCKET_ERROR
;
7943 iosb
->u
.Status
= STATUS_SUCCESS
;
7944 iosb
->Information
= n
;
7945 if (!wsa
->completion_func
)
7947 if (cvalue
) WS_AddCompletion( s
, cvalue
, STATUS_SUCCESS
, n
);
7948 if (lpOverlapped
->hEvent
) SetEvent( lpOverlapped
->hEvent
);
7949 HeapFree( GetProcessHeap(), 0, wsa
);
7951 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC
)ws2_async_apc
,
7952 (ULONG_PTR
)wsa
, (ULONG_PTR
)iosb
, 0 );
7953 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7959 if ((err
= _is_blocking( s
, &is_blocking
)))
7961 err
= NtStatusToWSAError( err
);
7968 int poll_timeout
= -1;
7969 INT64 timeout
= get_rcvsnd_timeo(fd
, TRUE
);
7973 timeout
-= GetTickCount() - timeout_start
;
7974 if (timeout
< 0) poll_timeout
= 0;
7975 else poll_timeout
= timeout
<= INT_MAX
? timeout
: INT_MAX
;
7979 pfd
.events
= POLLIN
;
7980 if (*lpFlags
& WS_MSG_OOB
) pfd
.events
|= POLLPRI
;
7982 if (!poll_timeout
|| !poll( &pfd
, 1, poll_timeout
))
7985 /* a timeout is not fatal */
7986 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7992 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7993 err
= WSAEWOULDBLOCK
;
7998 TRACE(" -> %i bytes\n", n
);
7999 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
8000 release_sock_fd( s
, fd
);
8001 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
8002 SetLastError(ERROR_SUCCESS
);
8007 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
8008 release_sock_fd( s
, fd
);
8009 WARN(" -> ERROR %d\n", err
);
8010 SetLastError( err
);
8011 return SOCKET_ERROR
;
8014 /***********************************************************************
8015 * WSARecvFrom (WS2_32.69)
8017 INT WINAPI
WSARecvFrom( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
8018 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
, struct WS_sockaddr
*lpFrom
,
8019 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
8020 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
8023 return WS2_recv_base( s
, lpBuffers
, dwBufferCount
,
8024 lpNumberOfBytesRecvd
, lpFlags
,
8026 lpOverlapped
, lpCompletionRoutine
, NULL
);
8029 /***********************************************************************
8030 * WSCInstallProvider (WS2_32.88)
8032 INT WINAPI
WSCInstallProvider( const LPGUID lpProviderId
,
8033 LPCWSTR lpszProviderDllPath
,
8034 const LPWSAPROTOCOL_INFOW lpProtocolInfoList
,
8035 DWORD dwNumberOfEntries
,
8038 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId
),
8039 debugstr_w(lpszProviderDllPath
), lpProtocolInfoList
,
8040 dwNumberOfEntries
, lpErrno
);
8046 /***********************************************************************
8047 * WSCDeinstallProvider (WS2_32.83)
8049 INT WINAPI
WSCDeinstallProvider(LPGUID lpProviderId
, LPINT lpErrno
)
8051 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId
), lpErrno
);
8057 /***********************************************************************
8058 * WSAAccept (WS2_32.26)
8060 SOCKET WINAPI
WSAAccept( SOCKET s
, struct WS_sockaddr
*addr
, LPINT addrlen
,
8061 LPCONDITIONPROC lpfnCondition
, DWORD_PTR dwCallbackData
)
8065 WSABUF CallerId
, CallerData
, CalleeId
, CalleeData
;
8066 /* QOS SQOS, GQOS; */
8069 SOCKADDR src_addr
, dst_addr
;
8071 TRACE("socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
8072 s
, addr
, addrlen
, lpfnCondition
, dwCallbackData
);
8074 cs
= WS_accept(s
, addr
, addrlen
);
8075 if (cs
== SOCKET_ERROR
) return SOCKET_ERROR
;
8076 if (!lpfnCondition
) return cs
;
8078 if (addr
&& addrlen
)
8080 CallerId
.buf
= (char *)addr
;
8081 CallerId
.len
= *addrlen
;
8085 size
= sizeof(src_addr
);
8086 WS_getpeername(cs
, &src_addr
, &size
);
8087 CallerId
.buf
= (char *)&src_addr
;
8088 CallerId
.len
= size
;
8090 CallerData
.buf
= NULL
;
8093 size
= sizeof(dst_addr
);
8094 WS_getsockname(cs
, &dst_addr
, &size
);
8096 CalleeId
.buf
= (char *)&dst_addr
;
8097 CalleeId
.len
= sizeof(dst_addr
);
8099 ret
= (*lpfnCondition
)(&CallerId
, &CallerData
, NULL
, NULL
,
8100 &CalleeId
, &CalleeData
, &g
, dwCallbackData
);
8107 SERVER_START_REQ( set_socket_deferred
)
8109 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
8110 req
->deferred
= wine_server_obj_handle( SOCKET2HANDLE(cs
) );
8111 if ( !wine_server_call_err ( req
) )
8113 SetLastError( WSATRY_AGAIN
);
8114 WS_closesocket( cs
);
8118 return SOCKET_ERROR
;
8121 SetLastError(WSAECONNREFUSED
);
8122 return SOCKET_ERROR
;
8124 FIXME("Unknown return type from Condition function\n");
8125 SetLastError(WSAENOTSOCK
);
8126 return SOCKET_ERROR
;
8130 /***********************************************************************
8131 * WSADuplicateSocketA (WS2_32.32)
8133 int WINAPI
WSADuplicateSocketA( SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOA lpProtocolInfo
)
8135 return WS_DuplicateSocket(FALSE
, s
, dwProcessId
, (LPWSAPROTOCOL_INFOW
) lpProtocolInfo
);
8138 /***********************************************************************
8139 * WSADuplicateSocketW (WS2_32.33)
8141 int WINAPI
WSADuplicateSocketW( SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOW lpProtocolInfo
)
8143 return WS_DuplicateSocket(TRUE
, s
, dwProcessId
, lpProtocolInfo
);
8146 /***********************************************************************
8147 * WSAInstallServiceClassA (WS2_32.48)
8149 int WINAPI
WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info
)
8151 FIXME("Request to install service %s\n",debugstr_a(info
->lpszServiceClassName
));
8152 SetLastError(WSAEACCES
);
8153 return SOCKET_ERROR
;
8156 /***********************************************************************
8157 * WSAInstallServiceClassW (WS2_32.49)
8159 int WINAPI
WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info
)
8161 FIXME("Request to install service %s\n",debugstr_w(info
->lpszServiceClassName
));
8162 SetLastError(WSAEACCES
);
8163 return SOCKET_ERROR
;
8166 /***********************************************************************
8167 * WSARemoveServiceClass (WS2_32.70)
8169 int WINAPI
WSARemoveServiceClass(LPGUID info
)
8171 FIXME("Request to remove service %s\n", debugstr_guid(info
));
8172 SetLastError(WSATYPE_NOT_FOUND
);
8173 return SOCKET_ERROR
;
8176 /***********************************************************************
8177 * inet_ntop (WS2_32.@)
8179 PCSTR WINAPI
WS_inet_ntop( INT family
, PVOID addr
, PSTR buffer
, SIZE_T len
)
8181 #ifdef HAVE_INET_NTOP
8182 struct WS_in6_addr
*in6
;
8183 struct WS_in_addr
*in
;
8186 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family
, addr
, buffer
, len
);
8189 SetLastError( STATUS_INVALID_PARAMETER
);
8198 pdst
= inet_ntop( AF_INET
, &in
->WS_s_addr
, buffer
, len
);
8204 pdst
= inet_ntop( AF_INET6
, in6
->WS_s6_addr
, buffer
, len
);
8208 SetLastError( WSAEAFNOSUPPORT
);
8212 if (!pdst
) SetLastError( STATUS_INVALID_PARAMETER
);
8215 FIXME( "not supported on this platform\n" );
8216 SetLastError( WSAEAFNOSUPPORT
);
8221 /***********************************************************************
8222 * inet_pton (WS2_32.@)
8224 INT WINAPI
WS_inet_pton( INT family
, PCSTR addr
, PVOID buffer
)
8226 #ifdef HAVE_INET_PTON
8229 TRACE("family %d, addr %s, buffer (%p)\n", family
, debugstr_a(addr
), buffer
);
8231 if (!addr
|| !buffer
)
8233 SetLastError(WSAEFAULT
);
8234 return SOCKET_ERROR
;
8237 unixaf
= convert_af_w2u(family
);
8238 if (unixaf
!= AF_INET
&& unixaf
!= AF_INET6
)
8240 SetLastError(WSAEAFNOSUPPORT
);
8241 return SOCKET_ERROR
;
8244 ret
= inet_pton(unixaf
, addr
, buffer
);
8245 if (ret
== -1) SetLastError(wsaErrno());
8248 FIXME( "not supported on this platform\n" );
8249 SetLastError( WSAEAFNOSUPPORT
);
8250 return SOCKET_ERROR
;
8254 /***********************************************************************
8255 * InetPtonW (WS2_32.@)
8257 INT WINAPI
InetPtonW(INT family
, PCWSTR addr
, PVOID buffer
)
8263 TRACE("family %d, addr %s, buffer (%p)\n", family
, debugstr_w(addr
), buffer
);
8267 SetLastError(WSAEFAULT
);
8268 return SOCKET_ERROR
;
8271 len
= WideCharToMultiByte(CP_ACP
, 0, addr
, -1, NULL
, 0, NULL
, NULL
);
8272 if (!(addrA
= HeapAlloc(GetProcessHeap(), 0, len
)))
8274 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8275 return SOCKET_ERROR
;
8277 WideCharToMultiByte(CP_ACP
, 0, addr
, -1, addrA
, len
, NULL
, NULL
);
8279 ret
= WS_inet_pton(family
, addrA
, buffer
);
8281 HeapFree(GetProcessHeap(), 0, addrA
);
8285 /***********************************************************************
8286 * InetNtopW (WS2_32.@)
8288 PCWSTR WINAPI
InetNtopW(INT family
, PVOID addr
, PWSTR buffer
, SIZE_T len
)
8290 char bufferA
[WS_INET6_ADDRSTRLEN
];
8293 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family
, addr
, buffer
, len
);
8295 if (WS_inet_ntop(family
, addr
, bufferA
, sizeof(bufferA
)))
8297 if (MultiByteToWideChar(CP_ACP
, 0, bufferA
, -1, buffer
, len
))
8300 SetLastError(ERROR_INVALID_PARAMETER
);
8305 /***********************************************************************
8306 * WSAStringToAddressA (WS2_32.80)
8308 INT WINAPI
WSAStringToAddressA(LPSTR AddressString
,
8310 LPWSAPROTOCOL_INFOA lpProtocolInfo
,
8311 LPSOCKADDR lpAddress
,
8312 LPINT lpAddressLength
)
8315 LPSTR workBuffer
=NULL
,ptrPort
;
8317 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString
), AddressFamily
,
8318 lpProtocolInfo
, lpAddress
, lpAddressLength
);
8320 if (!lpAddressLength
|| !lpAddress
) return SOCKET_ERROR
;
8324 SetLastError(WSAEINVAL
);
8325 return SOCKET_ERROR
;
8329 FIXME("ProtocolInfo not implemented.\n");
8331 workBuffer
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
,
8332 strlen(AddressString
) + 1);
8335 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8336 return SOCKET_ERROR
;
8339 strcpy(workBuffer
, AddressString
);
8341 switch(AddressFamily
)
8345 struct in_addr inetaddr
;
8347 /* If lpAddressLength is too small, tell caller the size we need */
8348 if (*lpAddressLength
< sizeof(SOCKADDR_IN
))
8350 *lpAddressLength
= sizeof(SOCKADDR_IN
);
8354 *lpAddressLength
= sizeof(SOCKADDR_IN
);
8355 memset(lpAddress
, 0, sizeof(SOCKADDR_IN
));
8357 ((LPSOCKADDR_IN
)lpAddress
)->sin_family
= WS_AF_INET
;
8359 ptrPort
= strchr(workBuffer
, ':');
8362 /* User may have entered an IPv6 and asked to parse as IPv4 */
8363 if(strchr(ptrPort
+ 1, ':'))
8368 ((LPSOCKADDR_IN
)lpAddress
)->sin_port
= htons(atoi(ptrPort
+1));
8372 if(inet_aton(workBuffer
, &inetaddr
) > 0)
8374 ((LPSOCKADDR_IN
)lpAddress
)->sin_addr
.WS_s_addr
= inetaddr
.s_addr
;
8384 struct in6_addr inetaddr
;
8385 char *ptrAddr
= workBuffer
;
8387 /* If lpAddressLength is too small, tell caller the size we need */
8388 if (*lpAddressLength
< sizeof(SOCKADDR_IN6
))
8390 *lpAddressLength
= sizeof(SOCKADDR_IN6
);
8394 #ifdef HAVE_INET_PTON
8395 *lpAddressLength
= sizeof(SOCKADDR_IN6
);
8396 memset(lpAddress
, 0, sizeof(SOCKADDR_IN6
));
8398 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_family
= WS_AF_INET6
;
8400 /* Valid IPv6 addresses can also be surrounded by [ ], and in this case
8401 * a port number may follow after like in [fd12:3456:7890::1]:12345
8402 * We need to cut the brackets and find the port if any. */
8404 if(*workBuffer
== '[')
8406 ptrPort
= strchr(workBuffer
, ']');
8409 SetLastError(WSAEINVAL
);
8410 return SOCKET_ERROR
;
8413 if (ptrPort
[1] == ':')
8414 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_port
= htons(atoi(ptrPort
+ 2));
8417 ptrAddr
= workBuffer
+ 1;
8420 if(inet_pton(AF_INET6
, ptrAddr
, &inetaddr
) > 0)
8422 memcpy(&((LPSOCKADDR_IN6
)lpAddress
)->sin6_addr
, &inetaddr
,
8423 sizeof(struct in6_addr
));
8427 #endif /* HAVE_INET_PTON */
8433 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
8434 TRACE("Unsupported address family specified: %d.\n", AddressFamily
);
8438 HeapFree(GetProcessHeap(), 0, workBuffer
);
8442 return SOCKET_ERROR
;
8445 /***********************************************************************
8446 * WSAStringToAddressW (WS2_32.81)
8448 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
8449 * If this should be the case, it would be required to map these digits
8450 * to Unicode digits (0-9) using FoldString first.
8452 INT WINAPI
WSAStringToAddressW(LPWSTR AddressString
,
8454 LPWSAPROTOCOL_INFOW lpProtocolInfo
,
8455 LPSOCKADDR lpAddress
,
8456 LPINT lpAddressLength
)
8459 LPSTR workBuffer
=NULL
;
8460 WSAPROTOCOL_INFOA infoA
;
8461 LPWSAPROTOCOL_INFOA lpProtoInfoA
= NULL
;
8463 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString
), AddressFamily
, lpProtocolInfo
,
8464 lpAddress
, lpAddressLength
);
8466 if (!lpAddressLength
|| !lpAddress
) return SOCKET_ERROR
;
8468 /* if ProtocolInfo is available - convert to ANSI variant */
8471 lpProtoInfoA
= &infoA
;
8472 memcpy( lpProtoInfoA
, lpProtocolInfo
, FIELD_OFFSET( WSAPROTOCOL_INFOA
, szProtocol
) );
8474 if (!WideCharToMultiByte( CP_ACP
, 0, lpProtocolInfo
->szProtocol
, -1,
8475 lpProtoInfoA
->szProtocol
, WSAPROTOCOL_LEN
+1, NULL
, NULL
))
8477 SetLastError(WSAEINVAL
);
8478 return SOCKET_ERROR
;
8484 /* Translate AddressString to ANSI code page - assumes that only
8485 standard digits 0-9 are used with this API call */
8486 sBuffer
= WideCharToMultiByte( CP_ACP
, 0, AddressString
, -1, NULL
, 0, NULL
, NULL
);
8487 workBuffer
= HeapAlloc( GetProcessHeap(), 0, sBuffer
);
8491 WideCharToMultiByte( CP_ACP
, 0, AddressString
, -1, workBuffer
, sBuffer
, NULL
, NULL
);
8492 res
= WSAStringToAddressA(workBuffer
,AddressFamily
,lpProtoInfoA
,
8493 lpAddress
,lpAddressLength
);
8494 HeapFree( GetProcessHeap(), 0, workBuffer
);
8498 res
= WSA_NOT_ENOUGH_MEMORY
;
8504 return SOCKET_ERROR
;
8507 /***********************************************************************
8508 * WSAAddressToStringA (WS2_32.27)
8510 * See WSAAddressToStringW
8512 INT WINAPI
WSAAddressToStringA( LPSOCKADDR sockaddr
, DWORD len
,
8513 LPWSAPROTOCOL_INFOA info
, LPSTR string
,
8517 CHAR buffer
[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8520 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr
, len
, info
, string
, lenstr
);
8522 if (!sockaddr
) return SOCKET_ERROR
;
8523 if (!string
|| !lenstr
) return SOCKET_ERROR
;
8525 switch(sockaddr
->sa_family
)
8529 unsigned int long_ip
= ntohl(((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
);
8530 if (len
< sizeof(SOCKADDR_IN
)) return SOCKET_ERROR
;
8531 sprintf( buffer
, "%u.%u.%u.%u:%u",
8532 (long_ip
>> 24) & 0xff,
8533 (long_ip
>> 16) & 0xff,
8534 (long_ip
>> 8) & 0xff,
8536 ntohs( ((SOCKADDR_IN
*)sockaddr
)->sin_port
) );
8538 p
= strchr( buffer
, ':' );
8539 if (!((SOCKADDR_IN
*)sockaddr
)->sin_port
) *p
= 0;
8544 struct WS_sockaddr_in6
*sockaddr6
= (LPSOCKADDR_IN6
) sockaddr
;
8548 if (len
< sizeof(SOCKADDR_IN6
)) return SOCKET_ERROR
;
8549 if ((sockaddr6
->sin6_port
))
8550 strcpy(buffer
, "[");
8551 slen
= strlen(buffer
);
8552 if (!WS_inet_ntop(WS_AF_INET6
, &sockaddr6
->sin6_addr
, &buffer
[slen
], sizeof(buffer
) - slen
))
8554 SetLastError(WSAEINVAL
);
8555 return SOCKET_ERROR
;
8557 if ((sockaddr6
->sin6_scope_id
))
8558 sprintf(buffer
+strlen(buffer
), "%%%u", sockaddr6
->sin6_scope_id
);
8559 if ((sockaddr6
->sin6_port
))
8560 sprintf(buffer
+strlen(buffer
), "]:%u", ntohs(sockaddr6
->sin6_port
));
8565 SetLastError(WSAEINVAL
);
8566 return SOCKET_ERROR
;
8569 size
= strlen( buffer
) + 1;
8574 SetLastError(WSAEFAULT
);
8575 return SOCKET_ERROR
;
8578 TRACE("=> %s,%u bytes\n", debugstr_a(buffer
), size
);
8580 strcpy( string
, buffer
);
8584 /***********************************************************************
8585 * WSAAddressToStringW (WS2_32.28)
8587 * Convert a sockaddr address into a readable address string.
8590 * sockaddr [I] Pointer to a sockaddr structure.
8591 * len [I] Size of the sockaddr structure.
8592 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
8593 * string [I/O] Pointer to a buffer to receive the address string.
8594 * lenstr [I/O] Size of the receive buffer in WCHARs.
8598 * Failure: SOCKET_ERROR
8601 * The 'info' parameter is ignored.
8603 INT WINAPI
WSAAddressToStringW( LPSOCKADDR sockaddr
, DWORD len
,
8604 LPWSAPROTOCOL_INFOW info
, LPWSTR string
,
8609 WCHAR buffer
[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8612 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr
, len
, info
, string
, lenstr
);
8615 ret
= WSAAddressToStringA(sockaddr
, len
, NULL
, bufAddr
, &size
);
8617 if (ret
) return ret
;
8619 MultiByteToWideChar( CP_ACP
, 0, bufAddr
, size
, buffer
, sizeof( buffer
)/sizeof(WCHAR
));
8624 SetLastError(WSAEFAULT
);
8625 return SOCKET_ERROR
;
8628 TRACE("=> %s,%u bytes\n", debugstr_w(buffer
), size
);
8630 lstrcpyW( string
, buffer
);
8634 /***********************************************************************
8635 * WSAEnumNameSpaceProvidersA (WS2_32.34)
8637 INT WINAPI
WSAEnumNameSpaceProvidersA( LPDWORD len
, LPWSANAMESPACE_INFOA buffer
)
8639 FIXME( "(%p %p) Stub!\n", len
, buffer
);
8643 /***********************************************************************
8644 * WSAEnumNameSpaceProvidersW (WS2_32.35)
8646 INT WINAPI
WSAEnumNameSpaceProvidersW( LPDWORD len
, LPWSANAMESPACE_INFOW buffer
)
8648 FIXME( "(%p %p) Stub!\n", len
, buffer
);
8652 /***********************************************************************
8653 * WSAGetQOSByName (WS2_32.41)
8655 BOOL WINAPI
WSAGetQOSByName( SOCKET s
, LPWSABUF lpQOSName
, LPQOS lpQOS
)
8657 FIXME( "(0x%04lx %p %p) Stub!\n", s
, lpQOSName
, lpQOS
);
8661 /***********************************************************************
8662 * WSAGetServiceClassInfoA (WS2_32.42)
8664 INT WINAPI
WSAGetServiceClassInfoA( LPGUID provider
, LPGUID service
, LPDWORD len
,
8665 LPWSASERVICECLASSINFOA info
)
8667 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider
), debugstr_guid(service
),
8669 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8670 return SOCKET_ERROR
;
8673 /***********************************************************************
8674 * WSAGetServiceClassInfoW (WS2_32.43)
8676 INT WINAPI
WSAGetServiceClassInfoW( LPGUID provider
, LPGUID service
, LPDWORD len
,
8677 LPWSASERVICECLASSINFOW info
)
8679 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider
), debugstr_guid(service
),
8681 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8682 return SOCKET_ERROR
;
8685 /***********************************************************************
8686 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
8688 INT WINAPI
WSAGetServiceClassNameByClassIdA( LPGUID
class, LPSTR service
, LPDWORD len
)
8690 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service
, len
);
8691 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8692 return SOCKET_ERROR
;
8695 /***********************************************************************
8696 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
8698 INT WINAPI
WSAGetServiceClassNameByClassIdW( LPGUID
class, LPWSTR service
, LPDWORD len
)
8700 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service
, len
);
8701 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8702 return SOCKET_ERROR
;
8705 /***********************************************************************
8706 * WSALookupServiceBeginA (WS2_32.59)
8708 INT WINAPI
WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions
,
8709 DWORD dwControlFlags
,
8712 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions
, dwControlFlags
,
8714 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8715 return SOCKET_ERROR
;
8718 /***********************************************************************
8719 * WSALookupServiceBeginW (WS2_32.60)
8721 INT WINAPI
WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions
,
8722 DWORD dwControlFlags
,
8725 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions
, dwControlFlags
,
8727 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8728 return SOCKET_ERROR
;
8731 /***********************************************************************
8732 * WSALookupServiceEnd (WS2_32.61)
8734 INT WINAPI
WSALookupServiceEnd( HANDLE lookup
)
8736 FIXME("(%p) Stub!\n", lookup
);
8740 /***********************************************************************
8741 * WSALookupServiceNextA (WS2_32.62)
8743 INT WINAPI
WSALookupServiceNextA( HANDLE lookup
, DWORD flags
, LPDWORD len
, LPWSAQUERYSETA results
)
8745 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup
, flags
, len
, results
);
8746 SetLastError(WSA_E_NO_MORE
);
8747 return SOCKET_ERROR
;
8750 /***********************************************************************
8751 * WSALookupServiceNextW (WS2_32.63)
8753 INT WINAPI
WSALookupServiceNextW( HANDLE lookup
, DWORD flags
, LPDWORD len
, LPWSAQUERYSETW results
)
8755 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup
, flags
, len
, results
);
8756 SetLastError(WSA_E_NO_MORE
);
8757 return SOCKET_ERROR
;
8760 /***********************************************************************
8761 * WSANtohl (WS2_32.64)
8763 INT WINAPI
WSANtohl( SOCKET s
, WS_u_long netlong
, WS_u_long
* lphostlong
)
8765 TRACE( "(%04lx 0x%08x %p)\n", s
, netlong
, lphostlong
);
8767 if (!lphostlong
) return WSAEFAULT
;
8769 *lphostlong
= ntohl( netlong
);
8773 /***********************************************************************
8774 * WSANtohs (WS2_32.65)
8776 INT WINAPI
WSANtohs( SOCKET s
, WS_u_short netshort
, WS_u_short
* lphostshort
)
8778 TRACE( "(%04lx 0x%08x %p)\n", s
, netshort
, lphostshort
);
8780 if (!lphostshort
) return WSAEFAULT
;
8782 *lphostshort
= ntohs( netshort
);
8786 /***********************************************************************
8787 * WSAProviderConfigChange (WS2_32.66)
8789 INT WINAPI
WSAProviderConfigChange( LPHANDLE handle
, LPWSAOVERLAPPED overlapped
,
8790 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
8792 FIXME( "(%p %p %p) Stub!\n", handle
, overlapped
, completion
);
8793 return SOCKET_ERROR
;
8796 /***********************************************************************
8797 * WSARecvDisconnect (WS2_32.68)
8799 INT WINAPI
WSARecvDisconnect( SOCKET s
, LPWSABUF disconnectdata
)
8801 TRACE( "(%04lx %p)\n", s
, disconnectdata
);
8803 return WS_shutdown( s
, SD_RECEIVE
);
8806 /***********************************************************************
8807 * WSASetServiceA (WS2_32.76)
8809 INT WINAPI
WSASetServiceA( LPWSAQUERYSETA query
, WSAESETSERVICEOP operation
, DWORD flags
)
8811 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query
, operation
, flags
);
8815 /***********************************************************************
8816 * WSASetServiceW (WS2_32.77)
8818 INT WINAPI
WSASetServiceW( LPWSAQUERYSETW query
, WSAESETSERVICEOP operation
, DWORD flags
)
8820 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query
, operation
, flags
);
8824 /***********************************************************************
8825 * WSCEnableNSProvider (WS2_32.84)
8827 INT WINAPI
WSCEnableNSProvider( LPGUID provider
, BOOL enable
)
8829 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider
), enable
);
8833 /***********************************************************************
8834 * WSCGetProviderPath (WS2_32.86)
8836 INT WINAPI
WSCGetProviderPath( LPGUID provider
, LPWSTR path
, LPINT len
, LPINT errcode
)
8838 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider
), path
, len
, errcode
);
8840 if (!errcode
|| !provider
|| !len
) return WSAEFAULT
;
8842 *errcode
= WSAEINVAL
;
8843 return SOCKET_ERROR
;
8846 /***********************************************************************
8847 * WSCInstallNameSpace (WS2_32.87)
8849 INT WINAPI
WSCInstallNameSpace( LPWSTR identifier
, LPWSTR path
, DWORD
namespace,
8850 DWORD version
, LPGUID provider
)
8852 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier
), debugstr_w(path
),
8853 namespace, version
, debugstr_guid(provider
) );
8857 /***********************************************************************
8858 * WSCUnInstallNameSpace (WS2_32.89)
8860 INT WINAPI
WSCUnInstallNameSpace( LPGUID lpProviderId
)
8862 FIXME("(%s) Stub!\n", debugstr_guid(lpProviderId
));
8866 /***********************************************************************
8867 * WSCWriteProviderOrder (WS2_32.91)
8869 INT WINAPI
WSCWriteProviderOrder( LPDWORD entry
, DWORD number
)
8871 FIXME("(%p 0x%08x) Stub!\n", entry
, number
);
8875 /***********************************************************************
8876 * WSANSPIoctl (WS2_32.91)
8878 INT WINAPI
WSANSPIoctl( HANDLE hLookup
, DWORD dwControlCode
, LPVOID lpvInBuffer
,
8879 DWORD cbInBuffer
, LPVOID lpvOutBuffer
, DWORD cbOutBuffer
,
8880 LPDWORD lpcbBytesReturned
, LPWSACOMPLETION lpCompletion
)
8882 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup
, dwControlCode
,
8883 lpvInBuffer
, cbInBuffer
, lpvOutBuffer
, cbOutBuffer
, lpcbBytesReturned
, lpCompletion
);
8884 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8885 return SOCKET_ERROR
;
8888 /*****************************************************************************
8889 * WSAEnumProtocolsA [WS2_32.@]
8891 * see function WSAEnumProtocolsW
8893 INT WINAPI
WSAEnumProtocolsA( LPINT protocols
, LPWSAPROTOCOL_INFOA buffer
, LPDWORD len
)
8895 return WS_EnumProtocols( FALSE
, protocols
, (LPWSAPROTOCOL_INFOW
) buffer
, len
);
8898 /*****************************************************************************
8899 * WSAEnumProtocolsW [WS2_32.@]
8901 * Retrieves information about specified set of active network protocols.
8904 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
8905 * retrieves information on all available protocols.
8906 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
8908 * len [I/O] Pointer to a variable specifying buffer size. On output
8909 * the variable holds the number of bytes needed when the
8910 * specified size is too small.
8913 * Success: number of WSAPROTOCOL_INFO structures in buffer.
8914 * Failure: SOCKET_ERROR
8917 * NT4SP5 does not return SPX if protocols == NULL
8920 * - NT4SP5 returns in addition these list of NETBIOS protocols
8921 * (address family 17), each entry two times one for socket type 2 and 5
8923 * iProtocol szProtocol
8924 * 0x80000000 \Device\NwlnkNb
8925 * 0xfffffffa \Device\NetBT_CBENT7
8926 * 0xfffffffb \Device\Nbf_CBENT7
8927 * 0xfffffffc \Device\NetBT_NdisWan5
8928 * 0xfffffffd \Device\NetBT_El9202
8929 * 0xfffffffe \Device\Nbf_El9202
8930 * 0xffffffff \Device\Nbf_NdisWan4
8932 * - there is no check that the operating system supports the returned
8935 INT WINAPI
WSAEnumProtocolsW( LPINT protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
)
8937 return WS_EnumProtocols( TRUE
, protocols
, buffer
, len
);
8940 /*****************************************************************************
8941 * WSCEnumProtocols [WS2_32.@]
8944 * protocols [I] Null-terminated array of iProtocol values.
8945 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
8946 * len [I/O] Size of buffer on input/output.
8947 * errno [O] Error code.
8950 * Success: number of protocols to be reported on.
8951 * Failure: SOCKET_ERROR. error is in errno.
8954 * Doesn't supply info on layered protocols.
8957 INT WINAPI
WSCEnumProtocols( LPINT protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
, LPINT err
)
8959 INT ret
= WSAEnumProtocolsW( protocols
, buffer
, len
);
8961 if (ret
== SOCKET_ERROR
) *err
= WSAENOBUFS
;