2 * based on Windows Sockets 1.1 specs
4 * Copyright (C) 1993,1994,1996,1997 John Brezak, Erik Bos, Alex Korobka.
5 * Copyright (C) 2001 Stefan Leichter
6 * Copyright (C) 2004 Hans Leidekker
7 * Copyright (C) 2005 Marcus Meissner
8 * Copyright (C) 2006-2008 Kai Blin
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 * NOTE: If you make any changes to fix a particular app, make sure
25 * they don't break something else like Netscape or telnet and ftp
26 * clients and servers (www.winsite.com got a lot of those).
30 #include "wine/port.h"
35 #include <sys/types.h>
40 #ifdef HAVE_SYS_IOCTL_H
41 # include <sys/ioctl.h>
43 #ifdef HAVE_SYS_FILIO_H
44 # include <sys/filio.h>
46 #ifdef HAVE_SYS_SOCKIO_H
47 # include <sys/sockio.h>
51 # include <sys/so_ioctl.h>
54 #ifdef HAVE_SYS_PARAM_H
55 # include <sys/param.h>
61 #ifdef HAVE_SYS_WAIT_H
62 # include <sys/wait.h>
67 #ifdef HAVE_SYS_SOCKET_H
68 #include <sys/socket.h>
70 #ifdef HAVE_NETINET_IN_H
71 # include <netinet/in.h>
73 #ifdef HAVE_NETINET_TCP_H
74 # include <netinet/tcp.h>
76 #ifdef HAVE_ARPA_INET_H
77 # include <arpa/inet.h>
89 #ifdef HAVE_ARPA_NAMESER_H
90 # include <arpa/nameser.h>
98 #ifdef HAVE_LINUX_FILTER_H
99 # include <linux/filter.h>
102 #ifdef HAVE_NETIPX_IPX_H
103 # include <netipx/ipx.h>
104 #elif defined(HAVE_LINUX_IPX_H)
105 # ifdef HAVE_ASM_TYPES_H
106 # include <asm/types.h>
108 # ifdef HAVE_LINUX_TYPES_H
109 # include <linux/types.h>
111 # include <linux/ipx.h>
113 #if defined(SOL_IPX) || defined(SO_DEFAULT_HEADERS)
117 #ifdef HAVE_LINUX_IRDA_H
118 # ifdef HAVE_LINUX_TYPES_H
119 # include <linux/types.h>
121 # include <linux/irda.h>
128 #ifdef HAVE_SYS_POLL_H
129 # include <sys/poll.h>
131 #ifdef HAVE_SYS_TIME_H
132 # include <sys/time.h>
135 #define NONAMELESSUNION
136 #define NONAMELESSSTRUCT
137 #include "ntstatus.h"
138 #define WIN32_NO_STATUS
143 #include "winerror.h"
145 #include "winsock2.h"
147 #include "ws2tcpip.h"
150 #include "wsnwlink.h"
151 #include "wshisotp.h"
155 #define USE_WC_PREFIX /* For CMSG_DATA */
156 #include "iphlpapi.h"
157 #include "wine/server.h"
158 #include "wine/debug.h"
159 #include "wine/exception.h"
160 #include "wine/unicode.h"
162 #if defined(linux) && !defined(IP_UNICAST_IF)
163 #define IP_UNICAST_IF 50
166 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
167 # define sipx_network sipx_addr.x_net
168 # define sipx_node sipx_addr.x_host.c_host
169 #endif /* __FreeBSD__ */
172 #define INADDR_NONE ~0UL
175 #if !defined(TCP_KEEPIDLE) && defined(TCP_KEEPALIVE)
176 /* TCP_KEEPALIVE is the Mac OS name for TCP_KEEPIDLE */
177 #define TCP_KEEPIDLE TCP_KEEPALIVE
180 #define FILE_USE_FILE_POINTER_POSITION ((LONGLONG)-2)
182 WINE_DEFAULT_DEBUG_CHANNEL(winsock
);
183 WINE_DECLARE_DEBUG_CHANNEL(winediag
);
185 /* names of the protocols */
186 static const WCHAR NameIpxW
[] = {'I', 'P', 'X', '\0'};
187 static const WCHAR NameSpxW
[] = {'S', 'P', 'X', '\0'};
188 static const WCHAR NameSpxIIW
[] = {'S', 'P', 'X', ' ', 'I', 'I', '\0'};
189 static const WCHAR NameTcpW
[] = {'T', 'C', 'P', '/', 'I', 'P', '\0'};
190 static const WCHAR NameUdpW
[] = {'U', 'D', 'P', '/', 'I', 'P', '\0'};
192 /* Taken from Win2k */
193 static const GUID ProviderIdIP
= { 0xe70f1aa0, 0xab8b, 0x11cf,
194 { 0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
195 static const GUID ProviderIdIPX
= { 0x11058240, 0xbe47, 0x11cf,
196 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
197 static const GUID ProviderIdSPX
= { 0x11058241, 0xbe47, 0x11cf,
198 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
200 static const INT valid_protocols
[] =
210 #define IS_IPX_PROTO(X) ((X) >= WS_NSPROTO_IPX && (X) <= WS_NSPROTO_IPX + 255)
212 #if defined(IP_UNICAST_IF) && defined(SO_ATTACH_FILTER)
213 # define LINUX_BOUND_IF
214 struct interface_filter
{
215 struct sock_filter iface_memaddr
;
216 struct sock_filter iface_rule
;
217 struct sock_filter ip_memaddr
;
218 struct sock_filter ip_rule
;
219 struct sock_filter return_keep
;
220 struct sock_filter return_dump
;
222 # define FILTER_JUMP_DUMP(here) (u_char)(offsetof(struct interface_filter, return_dump) \
223 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
224 /sizeof(struct sock_filter)
225 # define FILTER_JUMP_KEEP(here) (u_char)(offsetof(struct interface_filter, return_keep) \
226 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
227 /sizeof(struct sock_filter)
228 # define FILTER_JUMP_NEXT() (u_char)(0)
229 # define SKF_NET_DESTIP 16 /* offset in the network header to the destination IP */
230 static struct interface_filter generic_interface_filter
= {
231 /* This filter rule allows incoming packets on the specified interface, which works for all
232 * remotely generated packets and for locally generated broadcast packets. */
233 BPF_STMT(BPF_LD
+BPF_W
+BPF_ABS
, SKF_AD_OFF
+SKF_AD_IFINDEX
),
234 BPF_JUMP(BPF_JMP
+BPF_JEQ
+BPF_K
, 0xdeadbeef, FILTER_JUMP_KEEP(iface_rule
), FILTER_JUMP_NEXT()),
235 /* This rule allows locally generated packets targeted at the specific IP address of the chosen
236 * adapter (local packets not destined for the broadcast address do not have IFINDEX set) */
237 BPF_STMT(BPF_LD
+BPF_W
+BPF_ABS
, SKF_NET_OFF
+SKF_NET_DESTIP
),
238 BPF_JUMP(BPF_JMP
+BPF_JEQ
+BPF_K
, 0xdeadbeef, FILTER_JUMP_KEEP(ip_rule
), FILTER_JUMP_DUMP(ip_rule
)),
239 BPF_STMT(BPF_RET
+BPF_K
, (u_int
)-1), /* keep packet */
240 BPF_STMT(BPF_RET
+BPF_K
, 0) /* dump packet */
242 #endif /* LINUX_BOUND_IF */
245 * The actual definition of WSASendTo, wrapped in a different function name
246 * so that internal calls from ws2_32 itself will not trigger programs like
247 * Garena, which hooks WSASendTo/WSARecvFrom calls.
249 static int WS2_sendto( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
250 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
251 const struct WS_sockaddr
*to
, int tolen
,
252 LPWSAOVERLAPPED lpOverlapped
,
253 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);
256 * Internal fundamental receive function, essentially WSARecvFrom with an
257 * additional parameter to support message control headers.
259 static int WS2_recv_base( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
260 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
,
261 struct WS_sockaddr
*lpFrom
,
262 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
263 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
,
264 LPWSABUF lpControlBuffer
);
266 /* critical section to protect some non-reentrant net function */
267 static CRITICAL_SECTION csWSgetXXXbyYYY
;
268 static CRITICAL_SECTION_DEBUG critsect_debug
=
270 0, 0, &csWSgetXXXbyYYY
,
271 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
272 0, 0, { (DWORD_PTR
)(__FILE__
": csWSgetXXXbyYYY") }
274 static CRITICAL_SECTION csWSgetXXXbyYYY
= { &critsect_debug
, -1, 0, 0, 0, 0 };
276 union generic_unix_sockaddr
278 struct sockaddr addr
;
279 char data
[128]; /* should be big enough for all families */
282 static inline const char *debugstr_sockaddr( const struct WS_sockaddr
*a
)
284 if (!a
) return "(nil)";
285 switch (a
->sa_family
)
291 struct WS_sockaddr_in
*sin
= (struct WS_sockaddr_in
*)a
;
293 p
= WS_inet_ntop( WS_AF_INET
, &sin
->sin_addr
, buf
, sizeof(buf
) );
295 p
= "(unknown IPv4 address)";
297 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
298 p
, ntohs(sin
->sin_port
));
304 struct WS_sockaddr_in6
*sin
= (struct WS_sockaddr_in6
*)a
;
306 p
= WS_inet_ntop( WS_AF_INET6
, &sin
->sin6_addr
, buf
, sizeof(buf
) );
308 p
= "(unknown IPv6 address)";
309 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
310 p
, ntohs(sin
->sin6_port
));
315 char netnum
[16], nodenum
[16];
316 struct WS_sockaddr_ipx
*sin
= (struct WS_sockaddr_ipx
*)a
;
318 for (i
= 0;i
< 4; i
++) sprintf(netnum
+ i
* 2, "%02X", (unsigned char) sin
->sa_netnum
[i
]);
319 for (i
= 0;i
< 6; i
++) sprintf(nodenum
+ i
* 2, "%02X", (unsigned char) sin
->sa_nodenum
[i
]);
321 return wine_dbg_sprintf("{ family AF_IPX, address %s.%s, ipx socket %d }",
322 netnum
, nodenum
, sin
->sa_socket
);
328 memcpy( &addr
, ((const SOCKADDR_IRDA
*)a
)->irdaDeviceID
, sizeof(addr
) );
329 addr
= ntohl( addr
);
330 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
332 ((const SOCKADDR_IRDA
*)a
)->irdaServiceName
);
335 return wine_dbg_sprintf("{ family %d }", a
->sa_family
);
339 static inline const char *debugstr_sockopt(int level
, int optname
)
341 const char *stropt
= NULL
, *strlevel
= NULL
;
343 #define DEBUG_SOCKLEVEL(x) case (x): strlevel = #x
344 #define DEBUG_SOCKOPT(x) case (x): stropt = #x; break
348 DEBUG_SOCKLEVEL(WS_SOL_SOCKET
);
351 DEBUG_SOCKOPT(WS_SO_ACCEPTCONN
);
352 DEBUG_SOCKOPT(WS_SO_BROADCAST
);
353 DEBUG_SOCKOPT(WS_SO_BSP_STATE
);
354 DEBUG_SOCKOPT(WS_SO_CONDITIONAL_ACCEPT
);
355 DEBUG_SOCKOPT(WS_SO_CONNECT_TIME
);
356 DEBUG_SOCKOPT(WS_SO_DEBUG
);
357 DEBUG_SOCKOPT(WS_SO_DONTLINGER
);
358 DEBUG_SOCKOPT(WS_SO_DONTROUTE
);
359 DEBUG_SOCKOPT(WS_SO_ERROR
);
360 DEBUG_SOCKOPT(WS_SO_EXCLUSIVEADDRUSE
);
361 DEBUG_SOCKOPT(WS_SO_GROUP_ID
);
362 DEBUG_SOCKOPT(WS_SO_GROUP_PRIORITY
);
363 DEBUG_SOCKOPT(WS_SO_KEEPALIVE
);
364 DEBUG_SOCKOPT(WS_SO_LINGER
);
365 DEBUG_SOCKOPT(WS_SO_MAX_MSG_SIZE
);
366 DEBUG_SOCKOPT(WS_SO_OOBINLINE
);
367 DEBUG_SOCKOPT(WS_SO_OPENTYPE
);
368 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOA
);
369 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOW
);
370 DEBUG_SOCKOPT(WS_SO_RCVBUF
);
371 DEBUG_SOCKOPT(WS_SO_RCVTIMEO
);
372 DEBUG_SOCKOPT(WS_SO_REUSEADDR
);
373 DEBUG_SOCKOPT(WS_SO_SNDBUF
);
374 DEBUG_SOCKOPT(WS_SO_SNDTIMEO
);
375 DEBUG_SOCKOPT(WS_SO_TYPE
);
376 DEBUG_SOCKOPT(WS_SO_UPDATE_CONNECT_CONTEXT
);
380 DEBUG_SOCKLEVEL(WS_NSPROTO_IPX
);
383 DEBUG_SOCKOPT(WS_IPX_PTYPE
);
384 DEBUG_SOCKOPT(WS_IPX_FILTERPTYPE
);
385 DEBUG_SOCKOPT(WS_IPX_DSTYPE
);
386 DEBUG_SOCKOPT(WS_IPX_RECVHDR
);
387 DEBUG_SOCKOPT(WS_IPX_MAXSIZE
);
388 DEBUG_SOCKOPT(WS_IPX_ADDRESS
);
389 DEBUG_SOCKOPT(WS_IPX_MAX_ADAPTER_NUM
);
393 DEBUG_SOCKLEVEL(WS_SOL_IRLMP
);
396 DEBUG_SOCKOPT(WS_IRLMP_ENUMDEVICES
);
400 DEBUG_SOCKLEVEL(WS_IPPROTO_TCP
);
403 DEBUG_SOCKOPT(WS_TCP_BSDURGENT
);
404 DEBUG_SOCKOPT(WS_TCP_EXPEDITED_1122
);
405 DEBUG_SOCKOPT(WS_TCP_NODELAY
);
409 DEBUG_SOCKLEVEL(WS_IPPROTO_IP
);
412 DEBUG_SOCKOPT(WS_IP_ADD_MEMBERSHIP
);
413 DEBUG_SOCKOPT(WS_IP_DONTFRAGMENT
);
414 DEBUG_SOCKOPT(WS_IP_DROP_MEMBERSHIP
);
415 DEBUG_SOCKOPT(WS_IP_HDRINCL
);
416 DEBUG_SOCKOPT(WS_IP_MULTICAST_IF
);
417 DEBUG_SOCKOPT(WS_IP_MULTICAST_LOOP
);
418 DEBUG_SOCKOPT(WS_IP_MULTICAST_TTL
);
419 DEBUG_SOCKOPT(WS_IP_OPTIONS
);
420 DEBUG_SOCKOPT(WS_IP_PKTINFO
);
421 DEBUG_SOCKOPT(WS_IP_RECEIVE_BROADCAST
);
422 DEBUG_SOCKOPT(WS_IP_TOS
);
423 DEBUG_SOCKOPT(WS_IP_TTL
);
424 DEBUG_SOCKOPT(WS_IP_UNICAST_IF
);
428 DEBUG_SOCKLEVEL(WS_IPPROTO_IPV6
);
431 DEBUG_SOCKOPT(WS_IPV6_ADD_MEMBERSHIP
);
432 DEBUG_SOCKOPT(WS_IPV6_DROP_MEMBERSHIP
);
433 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_IF
);
434 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_HOPS
);
435 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_LOOP
);
436 DEBUG_SOCKOPT(WS_IPV6_UNICAST_HOPS
);
437 DEBUG_SOCKOPT(WS_IPV6_V6ONLY
);
438 DEBUG_SOCKOPT(WS_IPV6_UNICAST_IF
);
439 DEBUG_SOCKOPT(WS_IPV6_DONTFRAG
);
443 #undef DEBUG_SOCKLEVEL
447 strlevel
= wine_dbg_sprintf("WS_0x%x", level
);
449 stropt
= wine_dbg_sprintf("WS_0x%x", optname
);
451 return wine_dbg_sprintf("level %s, name %s", strlevel
+ 3, stropt
+ 3);
454 static inline const char *debugstr_optval(const char *optval
, int optlenval
)
456 if (optval
&& !IS_INTRESOURCE(optval
) && optlenval
>= 1 && optlenval
<= sizeof(DWORD
))
459 memcpy(&value
, optval
, optlenval
);
460 return wine_dbg_sprintf("%p (%u)", optval
, value
);
462 return wine_dbg_sprintf("%p", optval
);
465 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
466 #define SOCKET2HANDLE(s) ((HANDLE)(s))
467 #define HANDLE2SOCKET(h) ((SOCKET)(h))
469 /****************************************************************
470 * Async IO declarations
471 ****************************************************************/
473 typedef NTSTATUS
async_callback_t( void *user
, IO_STATUS_BLOCK
*io
, NTSTATUS status
);
477 async_callback_t
*callback
; /* must be the first field */
478 struct ws2_async_io
*next
;
481 struct ws2_async_shutdown
483 struct ws2_async_io io
;
485 IO_STATUS_BLOCK iosb
;
491 struct ws2_async_io io
;
493 LPWSAOVERLAPPED user_overlapped
;
494 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func
;
495 IO_STATUS_BLOCK local_iosb
;
496 struct WS_sockaddr
*addr
;
499 int val
; /* for send operations */
500 int *ptr
; /* for recv operations */
505 unsigned int n_iovecs
;
506 unsigned int first_iovec
;
507 struct iovec iovec
[1];
510 struct ws2_accept_async
512 struct ws2_async_io io
;
513 HANDLE listen_socket
;
514 HANDLE accept_socket
;
515 LPOVERLAPPED user_overlapped
;
517 PVOID buf
; /* buffer to write data to */
521 struct ws2_async
*read
;
524 struct ws2_transmitfile_async
526 struct ws2_async_io io
;
531 DWORD bytes_per_send
;
532 TRANSMIT_FILE_BUFFERS buffers
;
534 LARGE_INTEGER offset
;
535 struct ws2_async write
;
538 static struct ws2_async_io
*async_io_freelist
;
540 static void release_async_io( struct ws2_async_io
*io
)
544 struct ws2_async_io
*next
= async_io_freelist
;
546 if (InterlockedCompareExchangePointer( (void **)&async_io_freelist
, io
, next
) == next
) return;
550 static struct ws2_async_io
*alloc_async_io( DWORD size
, async_callback_t callback
)
552 /* first free remaining previous fileinfos */
554 struct ws2_async_io
*io
= InterlockedExchangePointer( (void **)&async_io_freelist
, NULL
);
558 struct ws2_async_io
*next
= io
->next
;
559 HeapFree( GetProcessHeap(), 0, io
);
563 io
= HeapAlloc( GetProcessHeap(), 0, size
);
564 if (io
) io
->callback
= callback
;
568 static NTSTATUS
register_async( int type
, HANDLE handle
, struct ws2_async_io
*async
, HANDLE event
,
569 PIO_APC_ROUTINE apc
, void *apc_context
, IO_STATUS_BLOCK
*io
)
573 SERVER_START_REQ( register_async
)
576 req
->async
.handle
= wine_server_obj_handle( handle
);
577 req
->async
.user
= wine_server_client_ptr( async
);
578 req
->async
.iosb
= wine_server_client_ptr( io
);
579 req
->async
.event
= wine_server_obj_handle( event
);
580 req
->async
.apc
= wine_server_client_ptr( apc
);
581 req
->async
.apc_context
= wine_server_client_ptr( apc_context
);
582 status
= wine_server_call( req
);
589 /****************************************************************/
591 /* ----------------------------------- internal data */
593 /* ws_... struct conversion flags */
595 typedef struct /* WSAAsyncSelect() control struct */
597 HANDLE service
, event
, sock
;
603 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
604 #define WS_MAX_UDP_DATAGRAM 1024
605 static INT WINAPI
WSA_DefaultBlockingHook( FARPROC x
);
607 /* hostent's, servent's and protent's are stored in one buffer per thread,
608 * as documented on MSDN for the functions that return any of the buffers */
609 struct per_thread_data
612 struct WS_hostent
*he_buffer
;
613 struct WS_servent
*se_buffer
;
614 struct WS_protoent
*pe_buffer
;
615 struct pollfd
*fd_cache
;
616 unsigned int fd_count
;
620 char ntoa_buffer
[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
623 /* internal: routing description information */
627 DWORD metric
, default_route
;
630 static INT num_startup
; /* reference counter */
631 static FARPROC blocking_hook
= (FARPROC
)WSA_DefaultBlockingHook
;
633 /* function prototypes */
634 static struct WS_hostent
*WS_create_he(char *name
, int aliases
, int aliases_size
, int addresses
, int address_length
);
635 static struct WS_hostent
*WS_dup_he(const struct hostent
* p_he
);
636 static struct WS_protoent
*WS_dup_pe(const struct protoent
* p_pe
);
637 static struct WS_servent
*WS_dup_se(const struct servent
* p_se
);
638 static int ws_protocol_info(SOCKET s
, int unicode
, WSAPROTOCOL_INFOW
*buffer
, int *size
);
640 int WSAIOCTL_GetInterfaceCount(void);
641 int WSAIOCTL_GetInterfaceName(int intNumber
, char *intName
);
643 static void WS_AddCompletion( SOCKET sock
, ULONG_PTR CompletionValue
, NTSTATUS CompletionStatus
, ULONG Information
);
645 #define MAP_OPTION(opt) { WS_##opt, opt }
647 static const int ws_flags_map
[][2] =
649 MAP_OPTION( MSG_OOB
),
650 MAP_OPTION( MSG_PEEK
),
651 MAP_OPTION( MSG_DONTROUTE
),
652 MAP_OPTION( MSG_WAITALL
),
653 { WS_MSG_PARTIAL
, 0 },
656 static const int ws_sock_map
[][2] =
658 MAP_OPTION( SO_DEBUG
),
659 MAP_OPTION( SO_ACCEPTCONN
),
660 MAP_OPTION( SO_REUSEADDR
),
661 MAP_OPTION( SO_KEEPALIVE
),
662 MAP_OPTION( SO_DONTROUTE
),
663 MAP_OPTION( SO_BROADCAST
),
664 MAP_OPTION( SO_LINGER
),
665 MAP_OPTION( SO_OOBINLINE
),
666 MAP_OPTION( SO_SNDBUF
),
667 MAP_OPTION( SO_RCVBUF
),
668 MAP_OPTION( SO_ERROR
),
669 MAP_OPTION( SO_TYPE
),
671 MAP_OPTION( SO_RCVTIMEO
),
674 MAP_OPTION( SO_SNDTIMEO
),
678 static const int ws_tcp_map
[][2] =
681 MAP_OPTION( TCP_NODELAY
),
685 static const int ws_ip_map
[][2] =
687 MAP_OPTION( IP_MULTICAST_IF
),
688 MAP_OPTION( IP_MULTICAST_TTL
),
689 MAP_OPTION( IP_MULTICAST_LOOP
),
690 MAP_OPTION( IP_ADD_MEMBERSHIP
),
691 MAP_OPTION( IP_DROP_MEMBERSHIP
),
692 MAP_OPTION( IP_OPTIONS
),
694 MAP_OPTION( IP_HDRINCL
),
696 MAP_OPTION( IP_TOS
),
697 MAP_OPTION( IP_TTL
),
699 MAP_OPTION( IP_PKTINFO
),
702 MAP_OPTION( IP_UNICAST_IF
),
706 static const int ws_ipv6_map
[][2] =
708 #ifdef IPV6_ADD_MEMBERSHIP
709 MAP_OPTION( IPV6_ADD_MEMBERSHIP
),
711 #ifdef IPV6_DROP_MEMBERSHIP
712 MAP_OPTION( IPV6_DROP_MEMBERSHIP
),
714 MAP_OPTION( IPV6_MULTICAST_IF
),
715 MAP_OPTION( IPV6_MULTICAST_HOPS
),
716 MAP_OPTION( IPV6_MULTICAST_LOOP
),
717 MAP_OPTION( IPV6_UNICAST_HOPS
),
718 MAP_OPTION( IPV6_V6ONLY
),
719 #ifdef IPV6_UNICAST_IF
720 MAP_OPTION( IPV6_UNICAST_IF
),
724 static const int ws_af_map
[][2] =
726 MAP_OPTION( AF_UNSPEC
),
727 MAP_OPTION( AF_INET
),
728 MAP_OPTION( AF_INET6
),
730 MAP_OPTION( AF_IPX
),
733 MAP_OPTION( AF_IRDA
),
735 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
738 static const int ws_socktype_map
[][2] =
740 MAP_OPTION( SOCK_DGRAM
),
741 MAP_OPTION( SOCK_STREAM
),
742 MAP_OPTION( SOCK_RAW
),
743 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
746 static const int ws_proto_map
[][2] =
748 MAP_OPTION( IPPROTO_IP
),
749 MAP_OPTION( IPPROTO_TCP
),
750 MAP_OPTION( IPPROTO_UDP
),
751 MAP_OPTION( IPPROTO_IPV6
),
752 MAP_OPTION( IPPROTO_ICMP
),
753 MAP_OPTION( IPPROTO_IGMP
),
754 MAP_OPTION( IPPROTO_RAW
),
755 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
758 static const int ws_aiflag_map
[][2] =
760 MAP_OPTION( AI_PASSIVE
),
761 MAP_OPTION( AI_CANONNAME
),
762 MAP_OPTION( AI_NUMERICHOST
),
763 #ifdef AI_NUMERICSERV
764 MAP_OPTION( AI_NUMERICSERV
),
767 MAP_OPTION( AI_V4MAPPED
),
769 MAP_OPTION( AI_ADDRCONFIG
),
772 static const int ws_niflag_map
[][2] =
774 MAP_OPTION( NI_NOFQDN
),
775 MAP_OPTION( NI_NUMERICHOST
),
776 MAP_OPTION( NI_NAMEREQD
),
777 MAP_OPTION( NI_NUMERICSERV
),
778 MAP_OPTION( NI_DGRAM
),
781 static const int ws_eai_map
[][2] =
783 MAP_OPTION( EAI_AGAIN
),
784 MAP_OPTION( EAI_BADFLAGS
),
785 MAP_OPTION( EAI_FAIL
),
786 MAP_OPTION( EAI_FAMILY
),
787 MAP_OPTION( EAI_MEMORY
),
788 /* Note: EAI_NODATA is deprecated, but still
789 * used by Windows and Linux... We map the newer
790 * EAI_NONAME to EAI_NODATA for now until Windows
794 MAP_OPTION( EAI_NODATA
),
797 { WS_EAI_NODATA
, EAI_NONAME
},
800 MAP_OPTION( EAI_SERVICE
),
801 MAP_OPTION( EAI_SOCKTYPE
),
805 static const int ws_poll_map
[][2] =
807 MAP_OPTION( POLLERR
),
808 MAP_OPTION( POLLHUP
),
809 MAP_OPTION( POLLNVAL
),
810 MAP_OPTION( POLLWRNORM
),
811 MAP_OPTION( POLLWRBAND
),
812 MAP_OPTION( POLLRDNORM
),
813 { WS_POLLRDBAND
, POLLPRI
}
816 static const char magic_loopback_addr
[] = {127, 12, 34, 56};
818 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
820 static inline WSACMSGHDR
*fill_control_message(int level
, int type
, WSACMSGHDR
*current
, ULONG
*maxsize
, void *data
, int len
)
822 ULONG msgsize
= sizeof(WSACMSGHDR
) + WSA_CMSG_ALIGN(len
);
823 char *ptr
= (char *) current
+ sizeof(WSACMSGHDR
);
825 /* Make sure there is at least enough room for this entry */
826 if (msgsize
> *maxsize
)
829 /* Fill in the entry */
830 current
->cmsg_len
= sizeof(WSACMSGHDR
) + len
;
831 current
->cmsg_level
= level
;
832 current
->cmsg_type
= type
;
833 memcpy(ptr
, data
, len
);
834 /* Return the pointer to where next entry should go */
835 return (WSACMSGHDR
*) (ptr
+ WSA_CMSG_ALIGN(len
));
837 #endif /* IP_PKTINFO */
839 static inline int convert_control_headers(struct msghdr
*hdr
, WSABUF
*control
)
842 WSACMSGHDR
*cmsg_win
= (WSACMSGHDR
*) control
->buf
, *ptr
;
843 ULONG ctlsize
= control
->len
;
844 struct cmsghdr
*cmsg_unix
;
847 /* Loop over all the headers, converting as appropriate */
848 for (cmsg_unix
= CMSG_FIRSTHDR(hdr
); cmsg_unix
!= NULL
; cmsg_unix
= CMSG_NXTHDR(hdr
, cmsg_unix
))
850 switch(cmsg_unix
->cmsg_level
)
853 switch(cmsg_unix
->cmsg_type
)
857 /* Convert the Unix IP_PKTINFO structure to the Windows version */
858 struct in_pktinfo
*data_unix
= (struct in_pktinfo
*) CMSG_DATA(cmsg_unix
);
859 struct WS_in_pktinfo data_win
;
861 memcpy(&data_win
.ipi_addr
,&data_unix
->ipi_addr
.s_addr
,4); /* 4 bytes = 32 address bits */
862 data_win
.ipi_ifindex
= data_unix
->ipi_ifindex
;
863 ptr
= fill_control_message(WS_IPPROTO_IP
, WS_IP_PKTINFO
, ptr
, &ctlsize
,
864 (void*)&data_win
, sizeof(data_win
));
865 if (!ptr
) goto error
;
868 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix
->cmsg_type
);
873 FIXME("Unhandled message header level %d\n", cmsg_unix
->cmsg_level
);
879 /* Set the length of the returned control headers */
880 control
->len
= (ptr
== NULL
? 0 : (char*)ptr
- (char*)cmsg_win
);
881 return (ptr
!= NULL
);
882 #else /* IP_PKTINFO */
885 #endif /* IP_PKTINFO */
887 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
889 /* ----------------------------------- error handling */
891 static NTSTATUS
sock_get_ntstatus( int err
)
895 case EBADF
: return STATUS_INVALID_HANDLE
;
896 case EBUSY
: return STATUS_DEVICE_BUSY
;
898 case EACCES
: return STATUS_ACCESS_DENIED
;
899 case EFAULT
: return STATUS_NO_MEMORY
;
900 case EINVAL
: return STATUS_INVALID_PARAMETER
;
902 case EMFILE
: return STATUS_TOO_MANY_OPENED_FILES
;
903 case EWOULDBLOCK
: return STATUS_CANT_WAIT
;
904 case EINPROGRESS
: return STATUS_PENDING
;
905 case EALREADY
: return STATUS_NETWORK_BUSY
;
906 case ENOTSOCK
: return STATUS_OBJECT_TYPE_MISMATCH
;
907 case EDESTADDRREQ
: return STATUS_INVALID_PARAMETER
;
908 case EMSGSIZE
: return STATUS_BUFFER_OVERFLOW
;
909 case EPROTONOSUPPORT
:
910 case ESOCKTNOSUPPORT
:
913 case EPROTOTYPE
: return STATUS_NOT_SUPPORTED
;
914 case ENOPROTOOPT
: return STATUS_INVALID_PARAMETER
;
915 case EOPNOTSUPP
: return STATUS_NOT_SUPPORTED
;
916 case EADDRINUSE
: return STATUS_ADDRESS_ALREADY_ASSOCIATED
;
917 case EADDRNOTAVAIL
: return STATUS_INVALID_PARAMETER
;
918 case ECONNREFUSED
: return STATUS_CONNECTION_REFUSED
;
919 case ESHUTDOWN
: return STATUS_PIPE_DISCONNECTED
;
920 case ENOTCONN
: return STATUS_CONNECTION_DISCONNECTED
;
921 case ETIMEDOUT
: return STATUS_IO_TIMEOUT
;
922 case ENETUNREACH
: return STATUS_NETWORK_UNREACHABLE
;
923 case ENETDOWN
: return STATUS_NETWORK_BUSY
;
925 case ECONNRESET
: return STATUS_CONNECTION_RESET
;
926 case ECONNABORTED
: return STATUS_CONNECTION_ABORTED
;
928 case 0: return STATUS_SUCCESS
;
930 WARN("Unknown errno %d!\n", err
);
931 return STATUS_UNSUCCESSFUL
;
935 static UINT
sock_get_error( int err
)
939 case EINTR
: return WSAEINTR
;
941 case EACCES
: return WSAEACCES
;
942 case EFAULT
: return WSAEFAULT
;
943 case EINVAL
: return WSAEINVAL
;
944 case EMFILE
: return WSAEMFILE
;
945 case EWOULDBLOCK
: return WSAEWOULDBLOCK
;
946 case EINPROGRESS
: return WSAEINPROGRESS
;
947 case EALREADY
: return WSAEALREADY
;
949 case ENOTSOCK
: return WSAENOTSOCK
;
950 case EDESTADDRREQ
: return WSAEDESTADDRREQ
;
951 case EMSGSIZE
: return WSAEMSGSIZE
;
952 case EPROTOTYPE
: return WSAEPROTOTYPE
;
953 case ENOPROTOOPT
: return WSAENOPROTOOPT
;
954 case EPROTONOSUPPORT
: return WSAEPROTONOSUPPORT
;
955 case ESOCKTNOSUPPORT
: return WSAESOCKTNOSUPPORT
;
956 case EOPNOTSUPP
: return WSAEOPNOTSUPP
;
957 case EPFNOSUPPORT
: return WSAEPFNOSUPPORT
;
958 case EAFNOSUPPORT
: return WSAEAFNOSUPPORT
;
959 case EADDRINUSE
: return WSAEADDRINUSE
;
960 case EADDRNOTAVAIL
: return WSAEADDRNOTAVAIL
;
961 case ENETDOWN
: return WSAENETDOWN
;
962 case ENETUNREACH
: return WSAENETUNREACH
;
963 case ENETRESET
: return WSAENETRESET
;
964 case ECONNABORTED
: return WSAECONNABORTED
;
966 case ECONNRESET
: return WSAECONNRESET
;
967 case ENOBUFS
: return WSAENOBUFS
;
968 case EISCONN
: return WSAEISCONN
;
969 case ENOTCONN
: return WSAENOTCONN
;
970 case ESHUTDOWN
: return WSAESHUTDOWN
;
971 case ETOOMANYREFS
: return WSAETOOMANYREFS
;
972 case ETIMEDOUT
: return WSAETIMEDOUT
;
973 case ECONNREFUSED
: return WSAECONNREFUSED
;
974 case ELOOP
: return WSAELOOP
;
975 case ENAMETOOLONG
: return WSAENAMETOOLONG
;
976 case EHOSTDOWN
: return WSAEHOSTDOWN
;
977 case EHOSTUNREACH
: return WSAEHOSTUNREACH
;
978 case ENOTEMPTY
: return WSAENOTEMPTY
;
980 case EPROCLIM
: return WSAEPROCLIM
;
983 case EUSERS
: return WSAEUSERS
;
986 case EDQUOT
: return WSAEDQUOT
;
989 case ESTALE
: return WSAESTALE
;
992 case EREMOTE
: return WSAEREMOTE
;
995 /* just in case we ever get here and there are no problems */
998 WARN("Unknown errno %d!\n", err
);
999 return WSAEOPNOTSUPP
;
1003 static UINT
wsaErrno(void)
1005 int loc_errno
= errno
;
1006 WARN("errno %d, (%s).\n", loc_errno
, strerror(loc_errno
));
1008 return sock_get_error( loc_errno
);
1011 /* most ws2 overlapped functions return an ntstatus-based error code */
1012 static NTSTATUS
wsaErrStatus(void)
1014 int loc_errno
= errno
;
1015 WARN("errno %d, (%s).\n", loc_errno
, strerror(loc_errno
));
1017 return sock_get_ntstatus(loc_errno
);
1020 static UINT
wsaHerrno(int loc_errno
)
1022 WARN("h_errno %d.\n", loc_errno
);
1026 case HOST_NOT_FOUND
: return WSAHOST_NOT_FOUND
;
1027 case TRY_AGAIN
: return WSATRY_AGAIN
;
1028 case NO_RECOVERY
: return WSANO_RECOVERY
;
1029 case NO_DATA
: return WSANO_DATA
;
1030 case ENOBUFS
: return WSAENOBUFS
;
1034 WARN("Unknown h_errno %d!\n", loc_errno
);
1035 return WSAEOPNOTSUPP
;
1039 static inline DWORD
NtStatusToWSAError( const DWORD status
)
1041 /* We only need to cover the status codes set by server async request handling */
1045 case STATUS_SUCCESS
: wserr
= 0; break;
1046 case STATUS_PENDING
: wserr
= WSA_IO_PENDING
; break;
1047 case STATUS_OBJECT_TYPE_MISMATCH
: wserr
= WSAENOTSOCK
; break;
1048 case STATUS_INVALID_HANDLE
: wserr
= WSAEBADF
; break;
1049 case STATUS_INVALID_PARAMETER
: wserr
= WSAEINVAL
; break;
1050 case STATUS_PIPE_DISCONNECTED
: wserr
= WSAESHUTDOWN
; break;
1051 case STATUS_NETWORK_BUSY
: wserr
= WSAEALREADY
; break;
1052 case STATUS_NETWORK_UNREACHABLE
: wserr
= WSAENETUNREACH
; break;
1053 case STATUS_CONNECTION_REFUSED
: wserr
= WSAECONNREFUSED
; break;
1054 case STATUS_CONNECTION_DISCONNECTED
: wserr
= WSAENOTCONN
; break;
1055 case STATUS_CONNECTION_RESET
: wserr
= WSAECONNRESET
; break;
1056 case STATUS_CONNECTION_ABORTED
: wserr
= WSAECONNABORTED
; break;
1057 case STATUS_CANCELLED
: wserr
= WSA_OPERATION_ABORTED
; break;
1058 case STATUS_ADDRESS_ALREADY_ASSOCIATED
: wserr
= WSAEADDRINUSE
; break;
1059 case STATUS_IO_TIMEOUT
:
1060 case STATUS_TIMEOUT
: wserr
= WSAETIMEDOUT
; break;
1061 case STATUS_NO_MEMORY
: wserr
= WSAEFAULT
; break;
1062 case STATUS_ACCESS_DENIED
: wserr
= WSAEACCES
; break;
1063 case STATUS_TOO_MANY_OPENED_FILES
: wserr
= WSAEMFILE
; break;
1064 case STATUS_CANT_WAIT
: wserr
= WSAEWOULDBLOCK
; break;
1065 case STATUS_BUFFER_OVERFLOW
: wserr
= WSAEMSGSIZE
; break;
1066 case STATUS_NOT_SUPPORTED
: wserr
= WSAEOPNOTSUPP
; break;
1067 case STATUS_HOST_UNREACHABLE
: wserr
= WSAEHOSTUNREACH
; break;
1070 wserr
= RtlNtStatusToDosError( status
);
1071 FIXME( "Status code %08x converted to DOS error code %x\n", status
, wserr
);
1076 /* set last error code from NT status without mapping WSA errors */
1077 static inline unsigned int set_error( unsigned int err
)
1081 err
= NtStatusToWSAError( err
);
1082 SetLastError( err
);
1087 static inline int get_sock_fd( SOCKET s
, DWORD access
, unsigned int *options
)
1090 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s
), access
, &fd
, options
) ))
1095 static inline void release_sock_fd( SOCKET s
, int fd
)
1097 wine_server_release_fd( SOCKET2HANDLE(s
), fd
);
1100 static void _enable_event( HANDLE s
, unsigned int event
,
1101 unsigned int sstate
, unsigned int cstate
)
1103 SERVER_START_REQ( enable_socket_event
)
1105 req
->handle
= wine_server_obj_handle( s
);
1107 req
->sstate
= sstate
;
1108 req
->cstate
= cstate
;
1109 wine_server_call( req
);
1114 static NTSTATUS
_is_blocking(SOCKET s
, BOOL
*ret
)
1117 SERVER_START_REQ( get_socket_event
)
1119 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1120 req
->service
= FALSE
;
1122 status
= wine_server_call( req
);
1123 *ret
= (reply
->state
& FD_WINE_NONBLOCKING
) == 0;
1129 static unsigned int _get_sock_mask(SOCKET s
)
1132 SERVER_START_REQ( get_socket_event
)
1134 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1135 req
->service
= FALSE
;
1137 wine_server_call( req
);
1144 static void _sync_sock_state(SOCKET s
)
1147 /* do a dummy wineserver request in order to let
1148 the wineserver run through its select loop once */
1149 (void)_is_blocking(s
, &dummy
);
1152 static void _get_sock_errors(SOCKET s
, int *events
)
1154 SERVER_START_REQ( get_socket_event
)
1156 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1157 req
->service
= FALSE
;
1159 wine_server_set_reply( req
, events
, sizeof(int) * FD_MAX_EVENTS
);
1160 wine_server_call( req
);
1165 static int _get_sock_error(SOCKET s
, unsigned int bit
)
1167 int events
[FD_MAX_EVENTS
];
1168 _get_sock_errors(s
, events
);
1172 static int _get_fd_type(int fd
)
1175 socklen_t optlen
= sizeof(sock_type
);
1176 getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char*) &sock_type
, &optlen
);
1180 static BOOL
set_dont_fragment(SOCKET s
, int level
, BOOL value
)
1184 if (level
== IPPROTO_IP
)
1187 optname
= IP_DONTFRAG
;
1188 #elif defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO) && defined(IP_PMTUDISC_DONT)
1189 optname
= IP_MTU_DISCOVER
;
1190 value
= value
? IP_PMTUDISC_DO
: IP_PMTUDISC_DONT
;
1194 FIXME("IP_DONTFRAGMENT for IPv4 not supported in this platform\n");
1195 return TRUE
; /* fake success */
1200 #ifdef IPV6_DONTFRAG
1201 optname
= IPV6_DONTFRAG
;
1202 #elif defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO) && defined(IPV6_PMTUDISC_DONT)
1203 optname
= IPV6_MTU_DISCOVER
;
1204 value
= value
? IPV6_PMTUDISC_DO
: IPV6_PMTUDISC_DONT
;
1208 FIXME("IP_DONTFRAGMENT for IPv6 not supported in this platform\n");
1209 return TRUE
; /* fake success */
1213 fd
= get_sock_fd(s
, 0, NULL
);
1214 if (fd
== -1) return FALSE
;
1216 if (!setsockopt(fd
, level
, optname
, &value
, sizeof(value
)))
1220 WSASetLastError(wsaErrno());
1224 release_sock_fd(s
, fd
);
1228 static BOOL
get_dont_fragment(SOCKET s
, int level
, BOOL
*out
)
1230 int fd
, optname
, value
, not_expected
;
1231 socklen_t optlen
= sizeof(value
);
1233 if (level
== IPPROTO_IP
)
1236 optname
= IP_DONTFRAG
;
1238 #elif defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
1239 optname
= IP_MTU_DISCOVER
;
1240 not_expected
= IP_PMTUDISC_DONT
;
1244 FIXME("IP_DONTFRAGMENT for IPv4 not supported in this platform\n");
1245 return TRUE
; /* fake success */
1250 #ifdef IPV6_DONTFRAG
1251 optname
= IPV6_DONTFRAG
;
1253 #elif defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DONT)
1254 optname
= IPV6_MTU_DISCOVER
;
1255 not_expected
= IPV6_PMTUDISC_DONT
;
1259 FIXME("IP_DONTFRAGMENT for IPv6 not supported in this platform\n");
1260 return TRUE
; /* fake success */
1264 fd
= get_sock_fd(s
, 0, NULL
);
1265 if (fd
== -1) return FALSE
;
1267 if (!getsockopt(fd
, level
, optname
, &value
, &optlen
))
1269 *out
= value
!= not_expected
;
1274 WSASetLastError(wsaErrno());
1278 release_sock_fd(s
, fd
);
1282 static struct per_thread_data
*get_per_thread_data(void)
1284 struct per_thread_data
* ptb
= NtCurrentTeb()->WinSockData
;
1285 /* lazy initialization */
1288 ptb
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(*ptb
) );
1289 NtCurrentTeb()->WinSockData
= ptb
;
1294 static void free_per_thread_data(void)
1296 struct per_thread_data
* ptb
= NtCurrentTeb()->WinSockData
;
1300 /* delete scratch buffers */
1301 HeapFree( GetProcessHeap(), 0, ptb
->he_buffer
);
1302 HeapFree( GetProcessHeap(), 0, ptb
->se_buffer
);
1303 HeapFree( GetProcessHeap(), 0, ptb
->pe_buffer
);
1304 HeapFree( GetProcessHeap(), 0, ptb
->fd_cache
);
1306 HeapFree( GetProcessHeap(), 0, ptb
);
1307 NtCurrentTeb()->WinSockData
= NULL
;
1310 /***********************************************************************
1311 * DllMain (WS2_32.init)
1313 BOOL WINAPI
DllMain(HINSTANCE hInstDLL
, DWORD fdwReason
, LPVOID fImpLoad
)
1315 TRACE("%p 0x%x %p\n", hInstDLL
, fdwReason
, fImpLoad
);
1316 switch (fdwReason
) {
1317 case DLL_PROCESS_ATTACH
:
1319 case DLL_PROCESS_DETACH
:
1320 if (fImpLoad
) break;
1321 free_per_thread_data();
1322 DeleteCriticalSection(&csWSgetXXXbyYYY
);
1324 case DLL_THREAD_DETACH
:
1325 free_per_thread_data();
1331 /***********************************************************************
1334 * Converts send/recv flags from Windows format.
1335 * Return the converted flag bits, unsupported flags remain unchanged.
1337 static int convert_flags(int flags
)
1340 if (!flags
) return 0;
1342 for (out
= i
= 0; flags
&& i
< sizeof(ws_flags_map
) / sizeof(ws_flags_map
[0]); i
++)
1344 if (ws_flags_map
[i
][0] & flags
)
1346 out
|= ws_flags_map
[i
][1];
1347 flags
&= ~ws_flags_map
[i
][0];
1352 FIXME("Unknown send/recv flags 0x%x, using anyway...\n", flags
);
1358 /***********************************************************************
1361 * Converts socket flags from Windows format.
1362 * Return 1 if converted, 0 if not (error).
1364 static int convert_sockopt(INT
*level
, INT
*optname
)
1370 *level
= SOL_SOCKET
;
1371 for(i
=0; i
<sizeof(ws_sock_map
)/sizeof(ws_sock_map
[0]); i
++) {
1372 if( ws_sock_map
[i
][0] == *optname
)
1374 *optname
= ws_sock_map
[i
][1];
1378 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname
);
1380 case WS_IPPROTO_TCP
:
1381 *level
= IPPROTO_TCP
;
1382 for(i
=0; i
<sizeof(ws_tcp_map
)/sizeof(ws_tcp_map
[0]); i
++) {
1383 if ( ws_tcp_map
[i
][0] == *optname
)
1385 *optname
= ws_tcp_map
[i
][1];
1389 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname
);
1392 *level
= IPPROTO_IP
;
1393 for(i
=0; i
<sizeof(ws_ip_map
)/sizeof(ws_ip_map
[0]); i
++) {
1394 if (ws_ip_map
[i
][0] == *optname
)
1396 *optname
= ws_ip_map
[i
][1];
1400 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname
);
1402 case WS_IPPROTO_IPV6
:
1403 *level
= IPPROTO_IPV6
;
1404 for(i
=0; i
<sizeof(ws_ipv6_map
)/sizeof(ws_ipv6_map
[0]); i
++) {
1405 if (ws_ipv6_map
[i
][0] == *optname
)
1407 *optname
= ws_ipv6_map
[i
][1];
1411 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname
);
1413 default: FIXME("Unimplemented or unknown socket level\n");
1418 /* ----------------------------------- Per-thread info (or per-process?) */
1420 static char *strdup_lower(const char *str
)
1423 char *ret
= HeapAlloc( GetProcessHeap(), 0, strlen(str
) + 1 );
1427 for (i
= 0; str
[i
]; i
++) ret
[i
] = tolower(str
[i
]);
1430 else SetLastError(WSAENOBUFS
);
1434 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1435 * from an fd and return the value converted to milli seconds
1436 * or 0 if there is an infinite time out */
1437 static inline INT64
get_rcvsnd_timeo( int fd
, BOOL is_recv
)
1440 socklen_t len
= sizeof(tv
);
1445 optname
= SO_RCVTIMEO
;
1451 optname
= SO_SNDTIMEO
;
1456 res
= getsockopt(fd
, SOL_SOCKET
, optname
, &tv
, &len
);
1459 return (UINT64
)tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000;
1462 /* utility: given an fd, will block until one of the events occurs */
1463 static inline int do_block( int fd
, int events
, int timeout
)
1469 pfd
.events
= events
;
1471 while ((ret
= poll(&pfd
, 1, timeout
)) < 0)
1482 convert_af_w2u(int windowsaf
) {
1485 for (i
=0;i
<sizeof(ws_af_map
)/sizeof(ws_af_map
[0]);i
++)
1486 if (ws_af_map
[i
][0] == windowsaf
)
1487 return ws_af_map
[i
][1];
1488 FIXME("unhandled Windows address family %d\n", windowsaf
);
1493 convert_af_u2w(int unixaf
) {
1496 for (i
=0;i
<sizeof(ws_af_map
)/sizeof(ws_af_map
[0]);i
++)
1497 if (ws_af_map
[i
][1] == unixaf
)
1498 return ws_af_map
[i
][0];
1499 FIXME("unhandled UNIX address family %d\n", unixaf
);
1504 convert_proto_w2u(int windowsproto
) {
1507 for (i
=0;i
<sizeof(ws_proto_map
)/sizeof(ws_proto_map
[0]);i
++)
1508 if (ws_proto_map
[i
][0] == windowsproto
)
1509 return ws_proto_map
[i
][1];
1511 /* check for extended IPX */
1512 if (IS_IPX_PROTO(windowsproto
))
1513 return windowsproto
;
1515 FIXME("unhandled Windows socket protocol %d\n", windowsproto
);
1520 convert_proto_u2w(int unixproto
) {
1523 for (i
=0;i
<sizeof(ws_proto_map
)/sizeof(ws_proto_map
[0]);i
++)
1524 if (ws_proto_map
[i
][1] == unixproto
)
1525 return ws_proto_map
[i
][0];
1527 /* if value is inside IPX range just return it - the kernel simply
1528 * echoes the value used in the socket() function */
1529 if (IS_IPX_PROTO(unixproto
))
1532 FIXME("unhandled UNIX socket protocol %d\n", unixproto
);
1537 convert_socktype_w2u(int windowssocktype
) {
1540 for (i
=0;i
<sizeof(ws_socktype_map
)/sizeof(ws_socktype_map
[0]);i
++)
1541 if (ws_socktype_map
[i
][0] == windowssocktype
)
1542 return ws_socktype_map
[i
][1];
1543 FIXME("unhandled Windows socket type %d\n", windowssocktype
);
1548 convert_socktype_u2w(int unixsocktype
) {
1551 for (i
=0;i
<sizeof(ws_socktype_map
)/sizeof(ws_socktype_map
[0]);i
++)
1552 if (ws_socktype_map
[i
][1] == unixsocktype
)
1553 return ws_socktype_map
[i
][0];
1554 FIXME("unhandled UNIX socket type %d\n", unixsocktype
);
1558 static int convert_poll_w2u(int events
)
1561 for (i
= ret
= 0; events
&& i
< sizeof(ws_poll_map
) / sizeof(ws_poll_map
[0]); i
++)
1563 if (ws_poll_map
[i
][0] & events
)
1565 ret
|= ws_poll_map
[i
][1];
1566 events
&= ~ws_poll_map
[i
][0];
1571 FIXME("Unsupported WSAPoll() flags 0x%x\n", events
);
1575 static int convert_poll_u2w(int events
)
1578 for (i
= ret
= 0; events
&& i
< sizeof(ws_poll_map
) / sizeof(ws_poll_map
[0]); i
++)
1580 if (ws_poll_map
[i
][1] & events
)
1582 ret
|= ws_poll_map
[i
][0];
1583 events
&= ~ws_poll_map
[i
][1];
1588 FIXME("Unsupported poll() flags 0x%x\n", events
);
1592 static int set_ipx_packettype(int sock
, int ptype
)
1595 int fd
= get_sock_fd( sock
, 0, NULL
), ret
= 0;
1596 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype
, fd
);
1598 if (fd
== -1) return SOCKET_ERROR
;
1600 /* We try to set the ipx type on ipx socket level. */
1602 if(setsockopt(fd
, SOL_IPX
, IPX_TYPE
, &ptype
, sizeof(ptype
)) == -1)
1604 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1610 /* Should we retrieve val using a getsockopt call and then
1611 * set the modified one? */
1613 setsockopt(fd
, 0, SO_DEFAULT_HEADERS
, &val
, sizeof(struct ipx
));
1616 release_sock_fd( sock
, fd
);
1619 WARN("IPX support is not enabled, can't set packet type\n");
1620 return SOCKET_ERROR
;
1624 /* ----------------------------------- API -----
1626 * Init / cleanup / error checking.
1629 /***********************************************************************
1630 * WSAStartup (WS2_32.115)
1632 int WINAPI
WSAStartup(WORD wVersionRequested
, LPWSADATA lpWSAData
)
1634 TRACE("verReq=%x\n", wVersionRequested
);
1636 if (LOBYTE(wVersionRequested
) < 1)
1637 return WSAVERNOTSUPPORTED
;
1639 if (!lpWSAData
) return WSAEINVAL
;
1643 /* that's the whole of the negotiation for now */
1644 lpWSAData
->wVersion
= wVersionRequested
;
1645 /* return winsock information */
1646 lpWSAData
->wHighVersion
= 0x0202;
1647 strcpy(lpWSAData
->szDescription
, "WinSock 2.0" );
1648 strcpy(lpWSAData
->szSystemStatus
, "Running" );
1649 lpWSAData
->iMaxSockets
= WS_MAX_SOCKETS_PER_PROCESS
;
1650 lpWSAData
->iMaxUdpDg
= WS_MAX_UDP_DATAGRAM
;
1651 /* don't do anything with lpWSAData->lpVendorInfo */
1652 /* (some apps don't allocate the space for this field) */
1654 TRACE("succeeded starts: %d\n", num_startup
);
1659 /***********************************************************************
1660 * WSACleanup (WS2_32.116)
1662 INT WINAPI
WSACleanup(void)
1666 TRACE("pending cleanups: %d\n", num_startup
);
1669 SetLastError(WSANOTINITIALISED
);
1670 return SOCKET_ERROR
;
1674 /***********************************************************************
1675 * WSAGetLastError (WS2_32.111)
1677 INT WINAPI
WSAGetLastError(void)
1679 return GetLastError();
1682 /***********************************************************************
1683 * WSASetLastError (WS2_32.112)
1685 void WINAPI
WSASetLastError(INT iError
) {
1686 SetLastError(iError
);
1689 static struct WS_hostent
*check_buffer_he(int size
)
1691 struct per_thread_data
* ptb
= get_per_thread_data();
1694 if (ptb
->he_len
>= size
) return ptb
->he_buffer
;
1695 HeapFree( GetProcessHeap(), 0, ptb
->he_buffer
);
1697 ptb
->he_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->he_len
= size
) );
1698 if (!ptb
->he_buffer
) SetLastError(WSAENOBUFS
);
1699 return ptb
->he_buffer
;
1702 static struct WS_servent
*check_buffer_se(int size
)
1704 struct per_thread_data
* ptb
= get_per_thread_data();
1707 if (ptb
->se_len
>= size
) return ptb
->se_buffer
;
1708 HeapFree( GetProcessHeap(), 0, ptb
->se_buffer
);
1710 ptb
->se_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->se_len
= size
) );
1711 if (!ptb
->se_buffer
) SetLastError(WSAENOBUFS
);
1712 return ptb
->se_buffer
;
1715 static struct WS_protoent
*check_buffer_pe(int size
)
1717 struct per_thread_data
* ptb
= get_per_thread_data();
1720 if (ptb
->pe_len
>= size
) return ptb
->pe_buffer
;
1721 HeapFree( GetProcessHeap(), 0, ptb
->pe_buffer
);
1723 ptb
->pe_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->pe_len
= size
) );
1724 if (!ptb
->pe_buffer
) SetLastError(WSAENOBUFS
);
1725 return ptb
->pe_buffer
;
1728 /* ----------------------------------- i/o APIs */
1730 static inline BOOL
supported_pf(int pf
)
1750 static inline BOOL
supported_protocol(int protocol
)
1753 for (i
= 0; i
< sizeof(valid_protocols
) / sizeof(valid_protocols
[0]); i
++)
1754 if (protocol
== valid_protocols
[i
])
1759 /**********************************************************************/
1761 /* Returns the length of the converted address if successful, 0 if it was too
1762 * small to start with or unknown family or invalid address buffer.
1764 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr
* wsaddr
, int wsaddrlen
,
1765 union generic_unix_sockaddr
*uaddr
)
1767 unsigned int uaddrlen
= 0;
1772 switch (wsaddr
->sa_family
)
1777 const struct WS_sockaddr_ipx
* wsipx
=(const struct WS_sockaddr_ipx
*)wsaddr
;
1778 struct sockaddr_ipx
* uipx
= (struct sockaddr_ipx
*)uaddr
;
1780 if (wsaddrlen
<sizeof(struct WS_sockaddr_ipx
))
1783 uaddrlen
= sizeof(struct sockaddr_ipx
);
1784 memset( uaddr
, 0, uaddrlen
);
1785 uipx
->sipx_family
=AF_IPX
;
1786 uipx
->sipx_port
=wsipx
->sa_socket
;
1787 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1790 memcpy(&uipx
->sipx_network
,wsipx
->sa_netnum
,sizeof(uipx
->sipx_network
)+sizeof(uipx
->sipx_node
));
1791 #ifdef IPX_FRAME_NONE
1792 uipx
->sipx_type
=IPX_FRAME_NONE
;
1798 struct sockaddr_in6
* uin6
= (struct sockaddr_in6
*)uaddr
;
1799 const struct WS_sockaddr_in6
* win6
= (const struct WS_sockaddr_in6
*)wsaddr
;
1801 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1802 * scope_id, one without.
1804 if (wsaddrlen
>= sizeof(struct WS_sockaddr_in6_old
)) {
1805 uaddrlen
= sizeof(struct sockaddr_in6
);
1806 memset( uaddr
, 0, uaddrlen
);
1807 uin6
->sin6_family
= AF_INET6
;
1808 uin6
->sin6_port
= win6
->sin6_port
;
1809 uin6
->sin6_flowinfo
= win6
->sin6_flowinfo
;
1810 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1811 if (wsaddrlen
>= sizeof(struct WS_sockaddr_in6
)) uin6
->sin6_scope_id
= win6
->sin6_scope_id
;
1813 memcpy(&uin6
->sin6_addr
,&win6
->sin6_addr
,16); /* 16 bytes = 128 address bits */
1816 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen
);
1820 struct sockaddr_in
* uin
= (struct sockaddr_in
*)uaddr
;
1821 const struct WS_sockaddr_in
* win
= (const struct WS_sockaddr_in
*)wsaddr
;
1823 if (wsaddrlen
<sizeof(struct WS_sockaddr_in
))
1825 uaddrlen
= sizeof(struct sockaddr_in
);
1826 memset( uaddr
, 0, uaddrlen
);
1827 uin
->sin_family
= AF_INET
;
1828 uin
->sin_port
= win
->sin_port
;
1829 memcpy(&uin
->sin_addr
,&win
->sin_addr
,4); /* 4 bytes = 32 address bits */
1834 struct sockaddr_irda
*uin
= (struct sockaddr_irda
*)uaddr
;
1835 const SOCKADDR_IRDA
*win
= (const SOCKADDR_IRDA
*)wsaddr
;
1837 if (wsaddrlen
< sizeof(SOCKADDR_IRDA
))
1839 uaddrlen
= sizeof(struct sockaddr_irda
);
1840 memset( uaddr
, 0, uaddrlen
);
1841 uin
->sir_family
= AF_IRDA
;
1842 if (!strncmp( win
->irdaServiceName
, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1844 unsigned int lsap_sel
= 0;
1846 sscanf( win
->irdaServiceName
, "LSAP-SEL%u", &lsap_sel
);
1847 uin
->sir_lsap_sel
= lsap_sel
;
1851 uin
->sir_lsap_sel
= LSAP_ANY
;
1852 memcpy( uin
->sir_name
, win
->irdaServiceName
, 25 );
1854 memcpy( &uin
->sir_addr
, win
->irdaDeviceID
, sizeof(uin
->sir_addr
) );
1858 case WS_AF_UNSPEC
: {
1859 /* Try to determine the needed space by the passed windows sockaddr space */
1860 switch (wsaddrlen
) {
1861 default: /* likely an ipv4 address */
1862 case sizeof(struct WS_sockaddr_in
):
1863 uaddrlen
= sizeof(struct sockaddr_in
);
1866 case sizeof(struct WS_sockaddr_ipx
):
1867 uaddrlen
= sizeof(struct sockaddr_ipx
);
1871 case sizeof(SOCKADDR_IRDA
):
1872 uaddrlen
= sizeof(struct sockaddr_irda
);
1875 case sizeof(struct WS_sockaddr_in6
):
1876 case sizeof(struct WS_sockaddr_in6_old
):
1877 uaddrlen
= sizeof(struct sockaddr_in6
);
1880 memset( uaddr
, 0, uaddrlen
);
1884 FIXME("Unknown address family %d, return NULL.\n", wsaddr
->sa_family
);
1890 static BOOL
is_sockaddr_bound(const struct sockaddr
*uaddr
, int uaddrlen
)
1892 switch (uaddr
->sa_family
)
1897 static const struct sockaddr_ipx emptyAddr
;
1898 struct sockaddr_ipx
*ipx
= (struct sockaddr_ipx
*) uaddr
;
1899 return ipx
->sipx_port
1900 || memcmp(&ipx
->sipx_network
, &emptyAddr
.sipx_network
, sizeof(emptyAddr
.sipx_network
))
1901 || memcmp(&ipx
->sipx_node
, &emptyAddr
.sipx_node
, sizeof(emptyAddr
.sipx_node
));
1906 static const struct sockaddr_in6 emptyAddr
;
1907 const struct sockaddr_in6
*in6
= (const struct sockaddr_in6
*) uaddr
;
1908 return in6
->sin6_port
|| memcmp(&in6
->sin6_addr
, &emptyAddr
.sin6_addr
, sizeof(struct in6_addr
));
1912 static const struct sockaddr_in emptyAddr
;
1913 const struct sockaddr_in
*in
= (const struct sockaddr_in
*) uaddr
;
1914 return in
->sin_port
|| memcmp(&in
->sin_addr
, &emptyAddr
.sin_addr
, sizeof(struct in_addr
));
1919 FIXME("unknown address family %d\n", uaddr
->sa_family
);
1924 /* Returns -1 if getsockname fails, 0 if not bound, 1 otherwise */
1925 static int is_fd_bound(int fd
, union generic_unix_sockaddr
*uaddr
, socklen_t
*uaddrlen
)
1927 union generic_unix_sockaddr inaddr
;
1931 if (!uaddr
) uaddr
= &inaddr
;
1932 if (!uaddrlen
) uaddrlen
= &inlen
;
1934 *uaddrlen
= sizeof(inaddr
);
1935 res
= getsockname(fd
, &uaddr
->addr
, uaddrlen
);
1936 if (!res
) res
= is_sockaddr_bound(&uaddr
->addr
, *uaddrlen
);
1940 /* Returns 0 if successful, -1 if the buffer is too small */
1941 static int ws_sockaddr_u2ws(const struct sockaddr
* uaddr
, struct WS_sockaddr
* wsaddr
, int* wsaddrlen
)
1945 switch(uaddr
->sa_family
)
1950 const struct sockaddr_ipx
* uipx
=(const struct sockaddr_ipx
*)uaddr
;
1951 struct WS_sockaddr_ipx
* wsipx
=(struct WS_sockaddr_ipx
*)wsaddr
;
1954 switch (*wsaddrlen
) /* how much can we copy? */
1958 *wsaddrlen
= sizeof(*wsipx
);
1959 wsipx
->sa_socket
=uipx
->sipx_port
;
1963 memcpy(wsipx
->sa_nodenum
,uipx
->sipx_node
,sizeof(wsipx
->sa_nodenum
));
1971 memcpy(wsipx
->sa_netnum
,&uipx
->sipx_network
,sizeof(wsipx
->sa_netnum
));
1977 wsipx
->sa_family
=WS_AF_IPX
;
1989 const struct sockaddr_irda
*uin
= (const struct sockaddr_irda
*)uaddr
;
1990 SOCKADDR_IRDA
*win
= (SOCKADDR_IRDA
*)wsaddr
;
1992 if (*wsaddrlen
< sizeof(SOCKADDR_IRDA
))
1994 win
->irdaAddressFamily
= WS_AF_IRDA
;
1995 memcpy( win
->irdaDeviceID
, &uin
->sir_addr
, sizeof(win
->irdaDeviceID
) );
1996 if (uin
->sir_lsap_sel
!= LSAP_ANY
)
1997 sprintf( win
->irdaServiceName
, "LSAP-SEL%u", uin
->sir_lsap_sel
);
1999 memcpy( win
->irdaServiceName
, uin
->sir_name
,
2000 sizeof(win
->irdaServiceName
) );
2005 const struct sockaddr_in6
* uin6
= (const struct sockaddr_in6
*)uaddr
;
2006 struct WS_sockaddr_in6_old
* win6old
= (struct WS_sockaddr_in6_old
*)wsaddr
;
2008 if (*wsaddrlen
< sizeof(struct WS_sockaddr_in6_old
))
2010 win6old
->sin6_family
= WS_AF_INET6
;
2011 win6old
->sin6_port
= uin6
->sin6_port
;
2012 win6old
->sin6_flowinfo
= uin6
->sin6_flowinfo
;
2013 memcpy(&win6old
->sin6_addr
,&uin6
->sin6_addr
,16); /* 16 bytes = 128 address bits */
2014 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
2015 if (*wsaddrlen
>= sizeof(struct WS_sockaddr_in6
)) {
2016 struct WS_sockaddr_in6
* win6
= (struct WS_sockaddr_in6
*)wsaddr
;
2017 win6
->sin6_scope_id
= uin6
->sin6_scope_id
;
2018 *wsaddrlen
= sizeof(struct WS_sockaddr_in6
);
2021 *wsaddrlen
= sizeof(struct WS_sockaddr_in6_old
);
2023 *wsaddrlen
= sizeof(struct WS_sockaddr_in6_old
);
2028 const struct sockaddr_in
* uin
= (const struct sockaddr_in
*)uaddr
;
2029 struct WS_sockaddr_in
* win
= (struct WS_sockaddr_in
*)wsaddr
;
2031 if (*wsaddrlen
< sizeof(struct WS_sockaddr_in
))
2033 win
->sin_family
= WS_AF_INET
;
2034 win
->sin_port
= uin
->sin_port
;
2035 memcpy(&win
->sin_addr
,&uin
->sin_addr
,4); /* 4 bytes = 32 address bits */
2036 memset(win
->sin_zero
, 0, 8); /* Make sure the null padding is null */
2037 *wsaddrlen
= sizeof(struct WS_sockaddr_in
);
2041 memset(wsaddr
,0,*wsaddrlen
);
2045 FIXME("Unknown address family %d\n", uaddr
->sa_family
);
2051 static INT
WS_DuplicateSocket(BOOL unicode
, SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOW lpProtocolInfo
)
2055 WSAPROTOCOL_INFOW infow
;
2057 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
2058 unicode
, s
, dwProcessId
, lpProtocolInfo
);
2060 if (!ws_protocol_info(s
, unicode
, &infow
, &size
))
2061 return SOCKET_ERROR
;
2063 if (!(hProcess
= OpenProcess(PROCESS_DUP_HANDLE
, FALSE
, dwProcessId
)))
2065 SetLastError(WSAEINVAL
);
2066 return SOCKET_ERROR
;
2069 if (!lpProtocolInfo
)
2071 CloseHandle(hProcess
);
2072 SetLastError(WSAEFAULT
);
2073 return SOCKET_ERROR
;
2076 /* I don't know what the real Windoze does next, this is a hack */
2077 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
2078 * the target use the global duplicate, or we could copy a reference to us to the structure
2079 * and let the target duplicate it from us, but let's do it as simple as possible */
2080 memcpy(lpProtocolInfo
, &infow
, size
);
2081 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s
),
2082 hProcess
, (LPHANDLE
)&lpProtocolInfo
->dwServiceFlags3
,
2083 0, FALSE
, DUPLICATE_SAME_ACCESS
);
2084 CloseHandle(hProcess
);
2085 lpProtocolInfo
->dwServiceFlags4
= 0xff00ff00; /* magic */
2089 /*****************************************************************************
2090 * WS_EnterSingleProtocolW [internal]
2092 * enters the protocol information of one given protocol into the given
2096 * TRUE if a protocol was entered into the buffer.
2099 * - only implemented for IPX, SPX, SPXII, TCP, UDP
2100 * - there is no check that the operating system supports the returned
2103 static BOOL
WS_EnterSingleProtocolW( INT protocol
, WSAPROTOCOL_INFOW
* info
)
2105 memset( info
, 0, sizeof(WSAPROTOCOL_INFOW
) );
2106 info
->iProtocol
= protocol
;
2110 case WS_IPPROTO_TCP
:
2111 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_EXPEDITED_DATA
|
2112 XP1_GRACEFUL_CLOSE
| XP1_GUARANTEED_ORDER
|
2113 XP1_GUARANTEED_DELIVERY
;
2114 info
->ProviderId
= ProviderIdIP
;
2115 info
->dwCatalogEntryId
= 0x3e9;
2116 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2117 info
->ProtocolChain
.ChainLen
= 1;
2119 info
->iAddressFamily
= WS_AF_INET
;
2120 info
->iMaxSockAddr
= 0x10;
2121 info
->iMinSockAddr
= 0x10;
2122 info
->iSocketType
= WS_SOCK_STREAM
;
2123 strcpyW( info
->szProtocol
, NameTcpW
);
2126 case WS_IPPROTO_UDP
:
2127 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_SUPPORT_BROADCAST
|
2128 XP1_SUPPORT_MULTIPOINT
| XP1_MESSAGE_ORIENTED
|
2130 info
->ProviderId
= ProviderIdIP
;
2131 info
->dwCatalogEntryId
= 0x3ea;
2132 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2133 info
->ProtocolChain
.ChainLen
= 1;
2135 info
->iAddressFamily
= WS_AF_INET
;
2136 info
->iMaxSockAddr
= 0x10;
2137 info
->iMinSockAddr
= 0x10;
2138 info
->iSocketType
= WS_SOCK_DGRAM
;
2139 info
->dwMessageSize
= 0xffbb;
2140 strcpyW( info
->szProtocol
, NameUdpW
);
2143 case WS_NSPROTO_IPX
:
2144 info
->dwServiceFlags1
= XP1_PARTIAL_MESSAGE
| XP1_SUPPORT_BROADCAST
|
2145 XP1_SUPPORT_MULTIPOINT
| XP1_MESSAGE_ORIENTED
|
2147 info
->ProviderId
= ProviderIdIPX
;
2148 info
->dwCatalogEntryId
= 0x406;
2149 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2150 info
->ProtocolChain
.ChainLen
= 1;
2152 info
->iAddressFamily
= WS_AF_IPX
;
2153 info
->iMaxSockAddr
= 0x10;
2154 info
->iMinSockAddr
= 0x0e;
2155 info
->iSocketType
= WS_SOCK_DGRAM
;
2156 info
->iProtocolMaxOffset
= 0xff;
2157 info
->dwMessageSize
= 0x240;
2158 strcpyW( info
->szProtocol
, NameIpxW
);
2161 case WS_NSPROTO_SPX
:
2162 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_PSEUDO_STREAM
|
2163 XP1_MESSAGE_ORIENTED
| XP1_GUARANTEED_ORDER
|
2164 XP1_GUARANTEED_DELIVERY
;
2165 info
->ProviderId
= ProviderIdSPX
;
2166 info
->dwCatalogEntryId
= 0x407;
2167 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2168 info
->ProtocolChain
.ChainLen
= 1;
2170 info
->iAddressFamily
= WS_AF_IPX
;
2171 info
->iMaxSockAddr
= 0x10;
2172 info
->iMinSockAddr
= 0x0e;
2173 info
->iSocketType
= WS_SOCK_SEQPACKET
;
2174 info
->dwMessageSize
= 0xffffffff;
2175 strcpyW( info
->szProtocol
, NameSpxW
);
2178 case WS_NSPROTO_SPXII
:
2179 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_GRACEFUL_CLOSE
|
2180 XP1_PSEUDO_STREAM
| XP1_MESSAGE_ORIENTED
|
2181 XP1_GUARANTEED_ORDER
| XP1_GUARANTEED_DELIVERY
;
2182 info
->ProviderId
= ProviderIdSPX
;
2183 info
->dwCatalogEntryId
= 0x409;
2184 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2185 info
->ProtocolChain
.ChainLen
= 1;
2187 info
->iAddressFamily
= WS_AF_IPX
;
2188 info
->iMaxSockAddr
= 0x10;
2189 info
->iMinSockAddr
= 0x0e;
2190 info
->iSocketType
= WS_SOCK_SEQPACKET
;
2191 info
->dwMessageSize
= 0xffffffff;
2192 strcpyW( info
->szProtocol
, NameSpxIIW
);
2196 FIXME("unknown Protocol <0x%08x>\n", protocol
);
2202 /*****************************************************************************
2203 * WS_EnterSingleProtocolA [internal]
2205 * see function WS_EnterSingleProtocolW
2208 static BOOL
WS_EnterSingleProtocolA( INT protocol
, WSAPROTOCOL_INFOA
* info
)
2210 WSAPROTOCOL_INFOW infow
;
2212 memset( info
, 0, sizeof(WSAPROTOCOL_INFOA
) );
2214 ret
= WS_EnterSingleProtocolW( protocol
, &infow
);
2217 /* convert the structure from W to A */
2218 memcpy( info
, &infow
, FIELD_OFFSET( WSAPROTOCOL_INFOA
, szProtocol
) );
2219 WideCharToMultiByte( CP_ACP
, 0, infow
.szProtocol
, -1,
2220 info
->szProtocol
, WSAPROTOCOL_LEN
+1, NULL
, NULL
);
2226 static INT
WS_EnumProtocols( BOOL unicode
, const INT
*protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
)
2228 INT i
= 0, items
= 0;
2232 LPWSAPROTOCOL_INFOA a
;
2233 LPWSAPROTOCOL_INFOW w
;
2237 if (!protocols
) protocols
= valid_protocols
;
2239 while (protocols
[i
])
2241 if(supported_protocol(protocols
[i
++]))
2245 size
= items
* (unicode
? sizeof(WSAPROTOCOL_INFOW
) : sizeof(WSAPROTOCOL_INFOA
));
2247 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
2248 unicode
, protocols
, buffer
, len
, len
? *len
: 0, items
, size
);
2250 if (*len
< size
|| !buffer
)
2253 SetLastError(WSAENOBUFS
);
2254 return SOCKET_ERROR
;
2257 for (i
= items
= 0; protocols
[i
]; i
++)
2259 if (!supported_protocol(protocols
[i
])) continue;
2262 if (WS_EnterSingleProtocolW( protocols
[i
], &info
.w
[items
] ))
2267 if (WS_EnterSingleProtocolA( protocols
[i
], &info
.a
[items
] ))
2274 static BOOL
ws_protocol_info(SOCKET s
, int unicode
, WSAPROTOCOL_INFOW
*buffer
, int *size
)
2278 *size
= unicode
? sizeof(WSAPROTOCOL_INFOW
) : sizeof(WSAPROTOCOL_INFOA
);
2279 memset(buffer
, 0, *size
);
2281 SERVER_START_REQ( get_socket_info
)
2283 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
2284 status
= wine_server_call( req
);
2287 buffer
->iAddressFamily
= convert_af_u2w(reply
->family
);
2288 buffer
->iSocketType
= convert_socktype_u2w(reply
->type
);
2289 buffer
->iProtocol
= convert_proto_u2w(reply
->protocol
);
2296 unsigned int err
= NtStatusToWSAError( status
);
2297 SetLastError( err
== WSAEBADF
? WSAENOTSOCK
: err
);
2302 WS_EnterSingleProtocolW( buffer
->iProtocol
, buffer
);
2304 WS_EnterSingleProtocolA( buffer
->iProtocol
, (WSAPROTOCOL_INFOA
*)buffer
);
2309 /**************************************************************************
2310 * Functions for handling overlapped I/O
2311 **************************************************************************/
2313 /* user APC called upon async completion */
2314 static void WINAPI
ws2_async_apc( void *arg
, IO_STATUS_BLOCK
*iosb
, ULONG reserved
)
2316 struct ws2_async
*wsa
= arg
;
2318 if (wsa
->completion_func
) wsa
->completion_func( NtStatusToWSAError(iosb
->u
.Status
),
2319 iosb
->Information
, wsa
->user_overlapped
,
2321 release_async_io( &wsa
->io
);
2324 /***********************************************************************
2325 * WS2_recv (INTERNAL)
2327 * Workhorse for both synchronous and asynchronous recv() operations.
2329 static int WS2_recv( int fd
, struct ws2_async
*wsa
, int flags
)
2331 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2335 union generic_unix_sockaddr unix_sockaddr
;
2338 hdr
.msg_name
= NULL
;
2342 hdr
.msg_namelen
= sizeof(unix_sockaddr
);
2343 hdr
.msg_name
= &unix_sockaddr
;
2346 hdr
.msg_namelen
= 0;
2348 hdr
.msg_iov
= wsa
->iovec
+ wsa
->first_iovec
;
2349 hdr
.msg_iovlen
= wsa
->n_iovecs
- wsa
->first_iovec
;
2350 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2351 hdr
.msg_accrights
= NULL
;
2352 hdr
.msg_accrightslen
= 0;
2354 hdr
.msg_control
= pktbuf
;
2355 hdr
.msg_controllen
= sizeof(pktbuf
);
2359 while ((n
= recvmsg(fd
, &hdr
, flags
)) == -1)
2365 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2368 ERR("Message control headers cannot be properly supported on this system.\n");
2369 wsa
->control
->len
= 0;
2372 if (wsa
->control
&& !convert_control_headers(&hdr
, wsa
->control
))
2374 WARN("Application passed insufficient room for control headers.\n");
2375 *wsa
->lpFlags
|= WS_MSG_CTRUNC
;
2381 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
2382 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
2384 * quoting linux 2.6 net/ipv4/tcp.c:
2385 * "According to UNIX98, msg_name/msg_namelen are ignored
2386 * on connected socket. I was just happy when found this 8) --ANK"
2388 * likewise MSDN says that lpFrom and lpFromlen are ignored for
2389 * connection-oriented sockets, so don't try to update lpFrom.
2391 if (wsa
->addr
&& hdr
.msg_namelen
)
2392 ws_sockaddr_u2ws( &unix_sockaddr
.addr
, wsa
->addr
, wsa
->addrlen
.ptr
);
2397 /***********************************************************************
2398 * WS2_async_recv (INTERNAL)
2400 * Handler for overlapped recv() operations.
2402 static NTSTATUS
WS2_async_recv( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
2404 struct ws2_async
*wsa
= user
;
2409 case STATUS_ALERTED
:
2410 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, FILE_READ_DATA
, &fd
, NULL
) ))
2413 result
= WS2_recv( fd
, wsa
, convert_flags(wsa
->flags
) );
2414 wine_server_release_fd( wsa
->hSocket
, fd
);
2417 status
= STATUS_SUCCESS
;
2418 _enable_event( wsa
->hSocket
, FD_READ
, 0, 0 );
2422 if (errno
== EAGAIN
)
2424 status
= STATUS_PENDING
;
2425 _enable_event( wsa
->hSocket
, FD_READ
, 0, 0 );
2430 status
= wsaErrStatus();
2435 if (status
!= STATUS_PENDING
)
2437 iosb
->u
.Status
= status
;
2438 iosb
->Information
= result
;
2439 if (!wsa
->completion_func
)
2440 release_async_io( &wsa
->io
);
2445 /***********************************************************************
2446 * WS2_async_accept_recv (INTERNAL)
2448 * This function is used to finish the read part of an accept request. It is
2449 * needed to place the completion on the correct socket (listener).
2451 static NTSTATUS
WS2_async_accept_recv( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
2453 struct ws2_accept_async
*wsa
= user
;
2455 status
= WS2_async_recv( wsa
->read
, iosb
, status
);
2456 if (status
== STATUS_PENDING
)
2460 WS_AddCompletion( HANDLE2SOCKET(wsa
->listen_socket
), wsa
->cvalue
, iosb
->u
.Status
, iosb
->Information
);
2462 release_async_io( &wsa
->io
);
2466 /***********************************************************************
2467 * WS2_async_accept (INTERNAL)
2469 * This is the function called to satisfy the AcceptEx callback
2471 static NTSTATUS
WS2_async_accept( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
2473 struct ws2_accept_async
*wsa
= user
;
2477 TRACE("status: 0x%x listen: %p, accept: %p\n", status
, wsa
->listen_socket
, wsa
->accept_socket
);
2479 if (status
== STATUS_ALERTED
)
2481 SERVER_START_REQ( accept_into_socket
)
2483 req
->lhandle
= wine_server_obj_handle( wsa
->listen_socket
);
2484 req
->ahandle
= wine_server_obj_handle( wsa
->accept_socket
);
2485 status
= wine_server_call( req
);
2489 if (status
== STATUS_CANT_WAIT
)
2490 return STATUS_PENDING
;
2492 if (status
== STATUS_INVALID_HANDLE
)
2494 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2495 status
= STATUS_CANCELLED
;
2498 else if (status
== STATUS_HANDLES_CLOSED
)
2499 status
= STATUS_CANCELLED
; /* strange windows behavior */
2501 if (status
!= STATUS_SUCCESS
)
2504 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2505 addr
= ((char *)wsa
->buf
) + wsa
->data_len
;
2506 len
= wsa
->local_len
- sizeof(int);
2507 WS_getsockname(HANDLE2SOCKET(wsa
->accept_socket
),
2508 (struct WS_sockaddr
*)(addr
+ sizeof(int)), &len
);
2511 addr
+= wsa
->local_len
;
2512 len
= wsa
->remote_len
- sizeof(int);
2513 WS_getpeername(HANDLE2SOCKET(wsa
->accept_socket
),
2514 (struct WS_sockaddr
*)(addr
+ sizeof(int)), &len
);
2520 wsa
->io
.callback
= WS2_async_accept_recv
;
2521 status
= register_async( ASYNC_TYPE_READ
, wsa
->accept_socket
, &wsa
->io
,
2522 wsa
->user_overlapped
->hEvent
, NULL
, NULL
, iosb
);
2524 if (status
!= STATUS_PENDING
)
2527 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2528 * needs to be performed by WS2_async_accept_recv() first. */
2529 return STATUS_MORE_PROCESSING_REQUIRED
;
2532 iosb
->u
.Status
= status
;
2533 iosb
->Information
= 0;
2535 if (wsa
->read
) release_async_io( &wsa
->read
->io
);
2536 release_async_io( &wsa
->io
);
2540 /***********************************************************************
2541 * WS2_send (INTERNAL)
2543 * Workhorse for both synchronous and asynchronous send() operations.
2545 static int WS2_send( int fd
, struct ws2_async
*wsa
, int flags
)
2548 union generic_unix_sockaddr unix_addr
;
2551 hdr
.msg_name
= NULL
;
2552 hdr
.msg_namelen
= 0;
2556 hdr
.msg_name
= &unix_addr
;
2557 hdr
.msg_namelen
= ws_sockaddr_ws2u( wsa
->addr
, wsa
->addrlen
.val
, &unix_addr
);
2558 if ( !hdr
.msg_namelen
)
2564 #if defined(HAS_IPX) && defined(SOL_IPX)
2565 if(wsa
->addr
->sa_family
== WS_AF_IPX
)
2567 struct sockaddr_ipx
* uipx
= (struct sockaddr_ipx
*)hdr
.msg_name
;
2569 socklen_t len
= sizeof(int);
2571 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2572 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2573 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2574 * ipx type in the sockaddr_opx structure with the stored value.
2576 if(getsockopt(fd
, SOL_IPX
, IPX_TYPE
, &val
, &len
) != -1)
2577 uipx
->sipx_type
= val
;
2582 hdr
.msg_iov
= wsa
->iovec
+ wsa
->first_iovec
;
2583 hdr
.msg_iovlen
= wsa
->n_iovecs
- wsa
->first_iovec
;
2584 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2585 hdr
.msg_accrights
= NULL
;
2586 hdr
.msg_accrightslen
= 0;
2588 hdr
.msg_control
= NULL
;
2589 hdr
.msg_controllen
= 0;
2593 while ((ret
= sendmsg(fd
, &hdr
, flags
)) == -1)
2600 while (wsa
->first_iovec
< wsa
->n_iovecs
&& wsa
->iovec
[wsa
->first_iovec
].iov_len
<= n
)
2601 n
-= wsa
->iovec
[wsa
->first_iovec
++].iov_len
;
2602 if (wsa
->first_iovec
< wsa
->n_iovecs
)
2604 wsa
->iovec
[wsa
->first_iovec
].iov_base
= (char*)wsa
->iovec
[wsa
->first_iovec
].iov_base
+ n
;
2605 wsa
->iovec
[wsa
->first_iovec
].iov_len
-= n
;
2610 /***********************************************************************
2611 * WS2_async_send (INTERNAL)
2613 * Handler for overlapped send() operations.
2615 static NTSTATUS
WS2_async_send( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
2617 struct ws2_async
*wsa
= user
;
2622 case STATUS_ALERTED
:
2623 if ( wsa
->n_iovecs
<= wsa
->first_iovec
)
2626 status
= STATUS_SUCCESS
;
2629 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, FILE_WRITE_DATA
, &fd
, NULL
) ))
2632 /* check to see if the data is ready (non-blocking) */
2633 result
= WS2_send( fd
, wsa
, convert_flags(wsa
->flags
) );
2634 wine_server_release_fd( wsa
->hSocket
, fd
);
2638 if (wsa
->first_iovec
< wsa
->n_iovecs
)
2639 status
= STATUS_PENDING
;
2641 status
= STATUS_SUCCESS
;
2643 iosb
->Information
+= result
;
2645 else if (errno
== EAGAIN
)
2647 status
= STATUS_PENDING
;
2651 status
= wsaErrStatus();
2655 if (status
!= STATUS_PENDING
)
2657 iosb
->u
.Status
= status
;
2658 if (!wsa
->completion_func
)
2659 release_async_io( &wsa
->io
);
2664 /***********************************************************************
2665 * WS2_async_shutdown (INTERNAL)
2667 * Handler for shutdown() operations on overlapped sockets.
2669 static NTSTATUS
WS2_async_shutdown( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
2671 struct ws2_async_shutdown
*wsa
= user
;
2676 case STATUS_ALERTED
:
2677 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, 0, &fd
, NULL
) ))
2680 switch ( wsa
->type
)
2682 case ASYNC_TYPE_READ
: err
= shutdown( fd
, 0 ); break;
2683 case ASYNC_TYPE_WRITE
: err
= shutdown( fd
, 1 ); break;
2685 status
= err
? wsaErrStatus() : STATUS_SUCCESS
;
2686 wine_server_release_fd( wsa
->hSocket
, fd
);
2689 iosb
->u
.Status
= status
;
2690 iosb
->Information
= 0;
2691 release_async_io( &wsa
->io
);
2695 /***********************************************************************
2696 * WS2_register_async_shutdown (INTERNAL)
2698 * Helper function for WS_shutdown() on overlapped sockets.
2700 static int WS2_register_async_shutdown( SOCKET s
, int type
)
2702 struct ws2_async_shutdown
*wsa
;
2705 TRACE("socket %04lx type %d\n", s
, type
);
2707 wsa
= (struct ws2_async_shutdown
*)alloc_async_io( sizeof(*wsa
), WS2_async_shutdown
);
2711 wsa
->hSocket
= SOCKET2HANDLE(s
);
2714 status
= register_async( type
, wsa
->hSocket
, &wsa
->io
, 0, NULL
, NULL
, &wsa
->iosb
);
2715 if (status
!= STATUS_PENDING
)
2717 HeapFree( GetProcessHeap(), 0, wsa
);
2718 return NtStatusToWSAError( status
);
2723 /***********************************************************************
2726 SOCKET WINAPI
WS_accept(SOCKET s
, struct WS_sockaddr
*addr
, int *addrlen32
)
2732 TRACE("socket %04lx\n", s
);
2733 status
= _is_blocking(s
, &is_blocking
);
2738 /* try accepting first (if there is a deferred connection) */
2739 SERVER_START_REQ( accept_socket
)
2741 req
->lhandle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
2742 req
->access
= GENERIC_READ
|GENERIC_WRITE
|SYNCHRONIZE
;
2743 req
->attributes
= OBJ_INHERIT
;
2744 status
= wine_server_call( req
);
2745 as
= HANDLE2SOCKET( wine_server_ptr_handle( reply
->handle
));
2750 if (addr
&& addrlen32
&& WS_getpeername(as
, addr
, addrlen32
))
2753 return SOCKET_ERROR
;
2755 TRACE("\taccepted %04lx\n", as
);
2758 if (is_blocking
&& status
== STATUS_CANT_WAIT
)
2760 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
2762 do_block(fd
, POLLIN
, -1);
2763 _sync_sock_state(s
); /* let wineserver notice connection */
2764 release_sock_fd( s
, fd
);
2766 } while (is_blocking
&& status
== STATUS_CANT_WAIT
);
2770 WARN(" -> ERROR %d\n", GetLastError());
2771 return INVALID_SOCKET
;
2774 /***********************************************************************
2777 static BOOL WINAPI
WS2_AcceptEx(SOCKET listener
, SOCKET acceptor
, PVOID dest
, DWORD dest_len
,
2778 DWORD local_addr_len
, DWORD rem_addr_len
, LPDWORD received
,
2779 LPOVERLAPPED overlapped
)
2782 struct ws2_accept_async
*wsa
;
2785 TRACE("(%04lx, %04lx, %p, %d, %d, %d, %p, %p)\n", listener
, acceptor
, dest
, dest_len
, local_addr_len
,
2786 rem_addr_len
, received
, overlapped
);
2790 SetLastError(WSAEINVAL
);
2796 SetLastError(WSA_INVALID_PARAMETER
);
2802 SetLastError(WSAEFAULT
);
2806 fd
= get_sock_fd( listener
, FILE_READ_DATA
, NULL
);
2809 SetLastError(WSAENOTSOCK
);
2812 release_sock_fd( listener
, fd
);
2814 fd
= get_sock_fd( acceptor
, FILE_READ_DATA
, NULL
);
2817 SetLastError(WSAENOTSOCK
);
2820 release_sock_fd( acceptor
, fd
);
2822 wsa
= (struct ws2_accept_async
*)alloc_async_io( sizeof(*wsa
), WS2_async_accept
);
2825 SetLastError(WSAEFAULT
);
2829 wsa
->listen_socket
= SOCKET2HANDLE(listener
);
2830 wsa
->accept_socket
= SOCKET2HANDLE(acceptor
);
2831 wsa
->user_overlapped
= overlapped
;
2832 wsa
->cvalue
= !((ULONG_PTR
)overlapped
->hEvent
& 1) ? (ULONG_PTR
)overlapped
: 0;
2834 wsa
->data_len
= dest_len
;
2835 wsa
->local_len
= local_addr_len
;
2836 wsa
->remote_len
= rem_addr_len
;
2841 /* set up a read request if we need it */
2842 wsa
->read
= (struct ws2_async
*)alloc_async_io( offsetof(struct ws2_async
, iovec
[1]), WS2_async_accept_recv
);
2845 HeapFree( GetProcessHeap(), 0, wsa
);
2846 SetLastError(WSAEFAULT
);
2850 wsa
->read
->hSocket
= wsa
->accept_socket
;
2851 wsa
->read
->flags
= 0;
2852 wsa
->read
->lpFlags
= &wsa
->read
->flags
;
2853 wsa
->read
->addr
= NULL
;
2854 wsa
->read
->addrlen
.ptr
= NULL
;
2855 wsa
->read
->control
= NULL
;
2856 wsa
->read
->n_iovecs
= 1;
2857 wsa
->read
->first_iovec
= 0;
2858 wsa
->read
->completion_func
= NULL
;
2859 wsa
->read
->iovec
[0].iov_base
= wsa
->buf
;
2860 wsa
->read
->iovec
[0].iov_len
= wsa
->data_len
;
2863 status
= register_async( ASYNC_TYPE_READ
, SOCKET2HANDLE(listener
), &wsa
->io
,
2864 overlapped
->hEvent
, NULL
, (void *)wsa
->cvalue
, (IO_STATUS_BLOCK
*)overlapped
);
2866 if(status
!= STATUS_PENDING
)
2868 HeapFree( GetProcessHeap(), 0, wsa
->read
);
2869 HeapFree( GetProcessHeap(), 0, wsa
);
2872 SetLastError( NtStatusToWSAError(status
) );
2876 /***********************************************************************
2877 * WS2_ReadFile (INTERNAL)
2879 * Perform an APC-safe ReadFile operation
2881 static NTSTATUS
WS2_ReadFile(HANDLE hFile
, PIO_STATUS_BLOCK io_status
, char* buffer
, ULONG length
,
2882 PLARGE_INTEGER offset
)
2884 int result
= -1, unix_handle
;
2885 unsigned int options
;
2888 TRACE( "(%p,%p,0x%08x)\n", hFile
, buffer
,length
);
2890 status
= wine_server_handle_to_fd( hFile
, FILE_READ_DATA
, &unix_handle
, &options
);
2891 if (status
) return status
;
2893 while (result
== -1)
2895 if (offset
->QuadPart
!= FILE_USE_FILE_POINTER_POSITION
)
2896 result
= pread( unix_handle
, buffer
, length
, offset
->QuadPart
);
2898 result
= read( unix_handle
, buffer
, length
);
2904 status
= (length
? STATUS_END_OF_FILE
: STATUS_SUCCESS
);
2905 else if (result
!= -1)
2906 status
= STATUS_SUCCESS
;
2907 else if (errno
!= EAGAIN
)
2908 status
= wsaErrStatus();
2910 status
= STATUS_PENDING
;
2912 wine_server_release_fd( hFile
, unix_handle
);
2913 TRACE("= 0x%08x (%d)\n", status
, result
);
2914 if (status
== STATUS_SUCCESS
|| status
== STATUS_END_OF_FILE
)
2916 io_status
->u
.Status
= status
;
2917 io_status
->Information
= result
;
2923 /***********************************************************************
2924 * WS2_transmitfile_getbuffer (INTERNAL)
2926 * Pick the appropriate buffer for a TransmitFile send operation.
2928 static NTSTATUS
WS2_transmitfile_getbuffer( int fd
, struct ws2_transmitfile_async
*wsa
)
2930 /* send any incomplete writes from a previous iteration */
2931 if (wsa
->write
.first_iovec
< wsa
->write
.n_iovecs
)
2932 return STATUS_PENDING
;
2934 /* process the header (if applicable) */
2935 if (wsa
->buffers
.Head
)
2937 wsa
->write
.first_iovec
= 0;
2938 wsa
->write
.n_iovecs
= 1;
2939 wsa
->write
.iovec
[0].iov_base
= wsa
->buffers
.Head
;
2940 wsa
->write
.iovec
[0].iov_len
= wsa
->buffers
.HeadLength
;
2941 wsa
->buffers
.Head
= NULL
;
2942 return STATUS_PENDING
;
2945 /* process the main file */
2948 DWORD bytes_per_send
= wsa
->bytes_per_send
;
2949 IO_STATUS_BLOCK iosb
;
2952 iosb
.Information
= 0;
2953 /* when the size of the transfer is limited ensure that we don't go past that limit */
2954 if (wsa
->file_bytes
!= 0)
2955 bytes_per_send
= min(bytes_per_send
, wsa
->file_bytes
- wsa
->file_read
);
2956 status
= WS2_ReadFile( wsa
->file
, &iosb
, wsa
->buffer
, bytes_per_send
, &wsa
->offset
);
2957 if (wsa
->offset
.QuadPart
!= FILE_USE_FILE_POINTER_POSITION
)
2958 wsa
->offset
.QuadPart
+= iosb
.Information
;
2959 if (status
== STATUS_END_OF_FILE
)
2960 wsa
->file
= NULL
; /* continue on to the footer */
2961 else if (status
!= STATUS_SUCCESS
)
2965 if (iosb
.Information
)
2967 wsa
->write
.first_iovec
= 0;
2968 wsa
->write
.n_iovecs
= 1;
2969 wsa
->write
.iovec
[0].iov_base
= wsa
->buffer
;
2970 wsa
->write
.iovec
[0].iov_len
= iosb
.Information
;
2971 wsa
->file_read
+= iosb
.Information
;
2974 if (wsa
->file_bytes
!= 0 && wsa
->file_read
>= wsa
->file_bytes
)
2977 return STATUS_PENDING
;
2981 /* send the footer (if applicable) */
2982 if (wsa
->buffers
.Tail
)
2984 wsa
->write
.first_iovec
= 0;
2985 wsa
->write
.n_iovecs
= 1;
2986 wsa
->write
.iovec
[0].iov_base
= wsa
->buffers
.Tail
;
2987 wsa
->write
.iovec
[0].iov_len
= wsa
->buffers
.TailLength
;
2988 wsa
->buffers
.Tail
= NULL
;
2989 return STATUS_PENDING
;
2992 return STATUS_SUCCESS
;
2995 /***********************************************************************
2996 * WS2_transmitfile_base (INTERNAL)
2998 * Shared implementation for both synchronous and asynchronous TransmitFile.
3000 static NTSTATUS
WS2_transmitfile_base( int fd
, struct ws2_transmitfile_async
*wsa
)
3004 status
= WS2_transmitfile_getbuffer( fd
, wsa
);
3005 if (status
== STATUS_PENDING
)
3007 IO_STATUS_BLOCK
*iosb
= (IO_STATUS_BLOCK
*)wsa
->write
.user_overlapped
;
3010 n
= WS2_send( fd
, &wsa
->write
, convert_flags(wsa
->write
.flags
) );
3013 if (iosb
) iosb
->Information
+= n
;
3015 else if (errno
!= EAGAIN
)
3016 return wsaErrStatus();
3022 /***********************************************************************
3023 * WS2_async_transmitfile (INTERNAL)
3025 * Asynchronous callback for overlapped TransmitFile operations.
3027 static NTSTATUS
WS2_async_transmitfile( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
3029 struct ws2_transmitfile_async
*wsa
= user
;
3032 if (status
== STATUS_ALERTED
)
3034 if (!(status
= wine_server_handle_to_fd( wsa
->write
.hSocket
, FILE_WRITE_DATA
, &fd
, NULL
)))
3036 status
= WS2_transmitfile_base( fd
, wsa
);
3037 wine_server_release_fd( wsa
->write
.hSocket
, fd
);
3039 if (status
== STATUS_PENDING
)
3043 iosb
->u
.Status
= status
;
3044 release_async_io( &wsa
->io
);
3048 /***********************************************************************
3051 static BOOL WINAPI
WS2_TransmitFile( SOCKET s
, HANDLE h
, DWORD file_bytes
, DWORD bytes_per_send
,
3052 LPOVERLAPPED overlapped
, LPTRANSMIT_FILE_BUFFERS buffers
,
3055 union generic_unix_sockaddr uaddr
;
3056 unsigned int uaddrlen
= sizeof(uaddr
);
3057 struct ws2_transmitfile_async
*wsa
;
3061 TRACE("(%lx, %p, %d, %d, %p, %p, %d)\n", s
, h
, file_bytes
, bytes_per_send
, overlapped
,
3064 fd
= get_sock_fd( s
, FILE_WRITE_DATA
, NULL
);
3067 WSASetLastError( WSAENOTSOCK
);
3070 if (getpeername( fd
, &uaddr
.addr
, &uaddrlen
) != 0)
3072 release_sock_fd( s
, fd
);
3073 WSASetLastError( WSAENOTCONN
);
3077 FIXME("Flags are not currently supported (0x%x).\n", flags
);
3079 if (h
&& GetFileType( h
) != FILE_TYPE_DISK
)
3081 FIXME("Non-disk file handles are not currently supported.\n");
3082 release_sock_fd( s
, fd
);
3083 WSASetLastError( WSAEOPNOTSUPP
);
3087 /* set reasonable defaults when requested */
3088 if (!bytes_per_send
)
3089 bytes_per_send
= (1 << 16); /* Depends on OS version: PAGE_SIZE, 2*PAGE_SIZE, or 2^16 */
3091 if (!(wsa
= (struct ws2_transmitfile_async
*)alloc_async_io( sizeof(*wsa
) + bytes_per_send
,
3092 WS2_async_transmitfile
)))
3094 release_sock_fd( s
, fd
);
3095 WSASetLastError( WSAEFAULT
);
3099 wsa
->buffers
= *buffers
;
3101 memset(&wsa
->buffers
, 0x0, sizeof(wsa
->buffers
));
3102 wsa
->buffer
= (char *)(wsa
+ 1);
3105 wsa
->file_bytes
= file_bytes
;
3106 wsa
->bytes_per_send
= bytes_per_send
;
3108 wsa
->offset
.QuadPart
= FILE_USE_FILE_POINTER_POSITION
;
3109 wsa
->write
.hSocket
= SOCKET2HANDLE(s
);
3110 wsa
->write
.addr
= NULL
;
3111 wsa
->write
.addrlen
.val
= 0;
3112 wsa
->write
.flags
= 0;
3113 wsa
->write
.lpFlags
= &wsa
->flags
;
3114 wsa
->write
.control
= NULL
;
3115 wsa
->write
.n_iovecs
= 0;
3116 wsa
->write
.first_iovec
= 0;
3117 wsa
->write
.user_overlapped
= overlapped
;
3120 IO_STATUS_BLOCK
*iosb
= (IO_STATUS_BLOCK
*)overlapped
;
3123 wsa
->offset
.u
.LowPart
= overlapped
->u
.s
.Offset
;
3124 wsa
->offset
.u
.HighPart
= overlapped
->u
.s
.OffsetHigh
;
3125 iosb
->u
.Status
= STATUS_PENDING
;
3126 iosb
->Information
= 0;
3127 status
= register_async( ASYNC_TYPE_WRITE
, SOCKET2HANDLE(s
), &wsa
->io
,
3128 overlapped
->hEvent
, NULL
, NULL
, iosb
);
3129 if(status
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
3130 release_sock_fd( s
, fd
);
3131 WSASetLastError( NtStatusToWSAError(status
) );
3137 status
= WS2_transmitfile_base( fd
, wsa
);
3138 if (status
== STATUS_PENDING
)
3141 do_block(fd
, POLLOUT
, -1);
3142 _sync_sock_state(s
); /* let wineserver notice connection */
3145 while (status
== STATUS_PENDING
);
3146 release_sock_fd( s
, fd
);
3148 if (status
!= STATUS_SUCCESS
)
3149 WSASetLastError( NtStatusToWSAError(status
) );
3150 HeapFree( GetProcessHeap(), 0, wsa
);
3151 return (status
== STATUS_SUCCESS
);
3154 /***********************************************************************
3155 * GetAcceptExSockaddrs
3157 static void WINAPI
WS2_GetAcceptExSockaddrs(PVOID buffer
, DWORD data_size
, DWORD local_size
, DWORD remote_size
,
3158 struct WS_sockaddr
**local_addr
, LPINT local_addr_len
,
3159 struct WS_sockaddr
**remote_addr
, LPINT remote_addr_len
)
3161 char *cbuf
= buffer
;
3162 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer
, data_size
, local_size
, remote_size
, local_addr
,
3163 local_addr_len
, remote_addr
, remote_addr_len
);
3166 *local_addr_len
= *(int *) cbuf
;
3167 *local_addr
= (struct WS_sockaddr
*)(cbuf
+ sizeof(int));
3171 *remote_addr_len
= *(int *) cbuf
;
3172 *remote_addr
= (struct WS_sockaddr
*)(cbuf
+ sizeof(int));
3175 /***********************************************************************
3178 int WINAPI
WSASendMsg( SOCKET s
, LPWSAMSG msg
, DWORD dwFlags
, LPDWORD lpNumberOfBytesSent
,
3179 LPWSAOVERLAPPED lpOverlapped
,
3180 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
3184 SetLastError( WSAEFAULT
);
3185 return SOCKET_ERROR
;
3188 return WS2_sendto( s
, msg
->lpBuffers
, msg
->dwBufferCount
, lpNumberOfBytesSent
,
3189 dwFlags
, msg
->name
, msg
->namelen
,
3190 lpOverlapped
, lpCompletionRoutine
);
3193 /***********************************************************************
3196 * Perform a receive operation that is capable of returning message
3197 * control headers. It is important to note that the WSAMSG parameter
3198 * must remain valid throughout the operation, even when an overlapped
3199 * receive is performed.
3201 static int WINAPI
WS2_WSARecvMsg( SOCKET s
, LPWSAMSG msg
, LPDWORD lpNumberOfBytesRecvd
,
3202 LPWSAOVERLAPPED lpOverlapped
,
3203 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
3207 SetLastError( WSAEFAULT
);
3208 return SOCKET_ERROR
;
3211 return WS2_recv_base( s
, msg
->lpBuffers
, msg
->dwBufferCount
, lpNumberOfBytesRecvd
,
3212 &msg
->dwFlags
, msg
->name
, &msg
->namelen
,
3213 lpOverlapped
, lpCompletionRoutine
, &msg
->Control
);
3216 /***********************************************************************
3217 * interface_bind (INTERNAL)
3219 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
3220 * operating only on the specified interface. This restriction consists of two components:
3221 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
3222 * 2) An incoming packet restriction dropping packets not meant for the interface.
3223 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
3224 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
3225 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
3226 * to receive broadcast packets on a socket that is bound to a specific network interface.
3228 static BOOL
interface_bind( SOCKET s
, int fd
, struct sockaddr
*addr
)
3230 struct sockaddr_in
*in_sock
= (struct sockaddr_in
*) addr
;
3231 in_addr_t bind_addr
= in_sock
->sin_addr
.s_addr
;
3232 PIP_ADAPTER_INFO adapters
= NULL
, adapter
;
3237 if (bind_addr
== htonl(INADDR_ANY
) || bind_addr
== htonl(INADDR_LOOPBACK
))
3238 return FALSE
; /* Not binding to a network adapter, special interface binding unnecessary. */
3239 if (_get_fd_type(fd
) != SOCK_DGRAM
)
3240 return FALSE
; /* Special interface binding is only necessary for UDP datagrams. */
3241 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
3243 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
3244 if (adapters
== NULL
|| GetAdaptersInfo(adapters
, &adap_size
) != NO_ERROR
)
3246 /* Search the IPv4 adapter list for the appropriate binding interface */
3247 for (adapter
= adapters
; adapter
!= NULL
; adapter
= adapter
->Next
)
3249 in_addr_t adapter_addr
= (in_addr_t
) inet_addr(adapter
->IpAddressList
.IpAddress
.String
);
3251 if (bind_addr
== adapter_addr
)
3253 #if defined(IP_BOUND_IF)
3254 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
3255 if (setsockopt(fd
, IPPROTO_IP
, IP_BOUND_IF
, &adapter
->Index
, sizeof(adapter
->Index
)) != 0)
3258 #elif defined(LINUX_BOUND_IF)
3259 in_addr_t ifindex
= (in_addr_t
) htonl(adapter
->Index
);
3260 struct interface_filter specific_interface_filter
;
3261 struct sock_fprog filter_prog
;
3263 if (setsockopt(fd
, IPPROTO_IP
, IP_UNICAST_IF
, &ifindex
, sizeof(ifindex
)) != 0)
3264 goto cleanup
; /* Failed to suggest egress interface */
3265 specific_interface_filter
= generic_interface_filter
;
3266 specific_interface_filter
.iface_rule
.k
= adapter
->Index
;
3267 specific_interface_filter
.ip_rule
.k
= htonl(adapter_addr
);
3268 filter_prog
.len
= sizeof(generic_interface_filter
)/sizeof(struct sock_filter
);
3269 filter_prog
.filter
= (struct sock_filter
*) &specific_interface_filter
;
3270 if (setsockopt(fd
, SOL_SOCKET
, SO_ATTACH_FILTER
, &filter_prog
, sizeof(filter_prog
)) != 0)
3271 goto cleanup
; /* Failed to specify incoming packet filter */
3274 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
3275 "receiving broadcast packets will not work on socket %04lx.\n", s
);
3280 /* Will soon be switching to INADDR_ANY: permit address reuse */
3281 if (ret
&& setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &enable
, sizeof(enable
)) == 0)
3282 TRACE("Socket %04lx bound to interface index %d\n", s
, adapter
->Index
);
3288 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s
);
3289 HeapFree(GetProcessHeap(), 0, adapters
);
3293 /***********************************************************************
3296 int WINAPI
WS_bind(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
)
3298 int fd
= get_sock_fd( s
, 0, NULL
);
3299 int res
= SOCKET_ERROR
;
3301 TRACE("socket %04lx, ptr %p %s, length %d\n", s
, name
, debugstr_sockaddr(name
), namelen
);
3305 if (!name
|| (name
->sa_family
&& !supported_pf(name
->sa_family
)))
3307 SetLastError(WSAEAFNOSUPPORT
);
3311 union generic_unix_sockaddr uaddr
;
3312 unsigned int uaddrlen
= ws_sockaddr_ws2u(name
, namelen
, &uaddr
);
3315 SetLastError(WSAEFAULT
);
3319 if (name
->sa_family
== WS_AF_INET
)
3321 struct sockaddr_in
*in4
= (struct sockaddr_in
*) &uaddr
;
3322 if (memcmp(&in4
->sin_addr
, magic_loopback_addr
, 4) == 0)
3324 /* Trying to bind to the default host interface, using
3325 * INADDR_ANY instead*/
3326 WARN("Trying to bind to magic IP address, using "
3327 "INADDR_ANY instead.\n");
3328 in4
->sin_addr
.s_addr
= htonl(INADDR_ANY
);
3330 else if (interface_bind(s
, fd
, &uaddr
.addr
))
3331 in4
->sin_addr
.s_addr
= htonl(INADDR_ANY
);
3333 if (bind(fd
, &uaddr
.addr
, uaddrlen
) < 0)
3335 int loc_errno
= errno
;
3336 WARN("\tfailure - errno = %i\n", errno
);
3341 SetLastError(WSAEINVAL
);
3346 socklen_t optlen
= sizeof(optval
);
3347 /* Windows >= 2003 will return different results depending on
3348 * SO_REUSEADDR, WSAEACCES may be returned representing that
3349 * the socket hijacking protection prevented the bind */
3350 if (!getsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&optval
, &optlen
) && optval
)
3352 SetLastError(WSAEACCES
);
3358 SetLastError(wsaErrno());
3364 res
=0; /* success */
3368 release_sock_fd( s
, fd
);
3373 /***********************************************************************
3374 * closesocket (WS2_32.3)
3376 int WINAPI
WS_closesocket(SOCKET s
)
3378 int res
= SOCKET_ERROR
, fd
;
3381 fd
= get_sock_fd(s
, FILE_READ_DATA
, NULL
);
3384 release_sock_fd(s
, fd
);
3385 if (CloseHandle(SOCKET2HANDLE(s
)))
3389 SetLastError(WSAENOTSOCK
);
3392 SetLastError(WSANOTINITIALISED
);
3393 TRACE("(socket %04lx) -> %d\n", s
, res
);
3397 static int do_connect(int fd
, const struct WS_sockaddr
* name
, int namelen
)
3399 union generic_unix_sockaddr uaddr
;
3400 unsigned int uaddrlen
= ws_sockaddr_ws2u(name
, namelen
, &uaddr
);
3405 if (name
->sa_family
== WS_AF_INET
)
3407 struct sockaddr_in
*in4
= (struct sockaddr_in
*) &uaddr
;
3408 if (memcmp(&in4
->sin_addr
, magic_loopback_addr
, 4) == 0)
3410 /* Trying to connect to magic replace-loopback address,
3411 * assuming we really want to connect to localhost */
3412 TRACE("Trying to connect to magic IP address, using "
3413 "INADDR_LOOPBACK instead.\n");
3414 in4
->sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
3418 if (connect(fd
, &uaddr
.addr
, uaddrlen
) == 0)
3424 /***********************************************************************
3425 * connect (WS2_32.4)
3427 int WINAPI
WS_connect(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
)
3429 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
3431 TRACE("socket %04lx, ptr %p %s, length %d\n", s
, name
, debugstr_sockaddr(name
), namelen
);
3437 int ret
= do_connect(fd
, name
, namelen
);
3439 goto connect_success
;
3441 if (ret
== WSAEINPROGRESS
)
3443 /* tell wineserver that a connection is in progress */
3444 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3446 FD_WINE_CONNECTED
|FD_WINE_LISTENING
);
3447 status
= _is_blocking( s
, &is_blocking
);
3450 release_sock_fd( s
, fd
);
3451 set_error( status
);
3452 return SOCKET_ERROR
;
3458 do_block(fd
, POLLIN
| POLLOUT
, -1);
3459 _sync_sock_state(s
); /* let wineserver notice connection */
3460 /* retrieve any error codes from it */
3461 result
= _get_sock_error(s
, FD_CONNECT_BIT
);
3463 SetLastError(NtStatusToWSAError(result
));
3466 goto connect_success
;
3471 SetLastError(WSAEWOULDBLOCK
);
3478 release_sock_fd( s
, fd
);
3480 return SOCKET_ERROR
;
3483 release_sock_fd( s
, fd
);
3484 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3485 FD_WINE_CONNECTED
|FD_READ
|FD_WRITE
,
3486 FD_CONNECT
|FD_WINE_LISTENING
);
3487 TRACE("\tconnected %04lx\n", s
);
3491 /***********************************************************************
3492 * WSAConnect (WS2_32.30)
3494 int WINAPI
WSAConnect( SOCKET s
, const struct WS_sockaddr
* name
, int namelen
,
3495 LPWSABUF lpCallerData
, LPWSABUF lpCalleeData
,
3496 LPQOS lpSQOS
, LPQOS lpGQOS
)
3498 if ( lpCallerData
|| lpCalleeData
|| lpSQOS
|| lpGQOS
)
3499 FIXME("unsupported parameters!\n");
3500 return WS_connect( s
, name
, namelen
);
3503 /***********************************************************************
3506 static BOOL WINAPI
WS2_ConnectEx(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
,
3507 PVOID sendBuf
, DWORD sendBufLen
, LPDWORD sent
, LPOVERLAPPED ov
)
3509 int fd
, ret
, status
;
3513 SetLastError( ERROR_INVALID_PARAMETER
);
3517 fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
3520 SetLastError( WSAENOTSOCK
);
3524 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
3525 s
, name
, debugstr_sockaddr(name
), namelen
, sendBuf
, sendBufLen
, ov
);
3527 ret
= is_fd_bound(fd
, NULL
, NULL
);
3530 SetLastError(ret
== -1 ? wsaErrno() : WSAEINVAL
);
3531 release_sock_fd( s
, fd
);
3535 ret
= do_connect(fd
, name
, namelen
);
3540 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3541 FD_WINE_CONNECTED
|FD_READ
|FD_WRITE
,
3542 FD_CONNECT
|FD_WINE_LISTENING
);
3544 wsabuf
.len
= sendBufLen
;
3545 wsabuf
.buf
= (char*) sendBuf
;
3547 /* WSASend takes care of completion if need be */
3548 if (WSASend(s
, &wsabuf
, sendBuf
? 1 : 0, sent
, 0, ov
, NULL
) != SOCKET_ERROR
)
3549 goto connection_success
;
3551 else if (ret
== WSAEINPROGRESS
)
3553 struct ws2_async
*wsa
;
3554 ULONG_PTR cvalue
= (((ULONG_PTR
)ov
->hEvent
& 1) == 0) ? (ULONG_PTR
)ov
: 0;
3556 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3558 FD_WINE_CONNECTED
|FD_WINE_LISTENING
);
3560 /* Indirectly call WSASend */
3561 if (!(wsa
= (struct ws2_async
*)alloc_async_io( offsetof( struct ws2_async
, iovec
[1] ), WS2_async_send
)))
3563 SetLastError(WSAEFAULT
);
3567 IO_STATUS_BLOCK
*iosb
= (IO_STATUS_BLOCK
*)ov
;
3568 iosb
->u
.Status
= STATUS_PENDING
;
3569 iosb
->Information
= 0;
3571 wsa
->hSocket
= SOCKET2HANDLE(s
);
3573 wsa
->addrlen
.val
= 0;
3575 wsa
->lpFlags
= &wsa
->flags
;
3576 wsa
->control
= NULL
;
3577 wsa
->n_iovecs
= sendBuf
? 1 : 0;
3578 wsa
->first_iovec
= 0;
3579 wsa
->completion_func
= NULL
;
3580 wsa
->iovec
[0].iov_base
= sendBuf
;
3581 wsa
->iovec
[0].iov_len
= sendBufLen
;
3583 status
= register_async( ASYNC_TYPE_WRITE
, wsa
->hSocket
, &wsa
->io
, ov
->hEvent
,
3584 NULL
, (void *)cvalue
, iosb
);
3585 if (status
!= STATUS_PENDING
) HeapFree(GetProcessHeap(), 0, wsa
);
3587 /* If the connect already failed */
3588 if (status
== STATUS_PIPE_DISCONNECTED
)
3589 status
= _get_sock_error(s
, FD_CONNECT_BIT
);
3590 SetLastError( NtStatusToWSAError(status
) );
3598 release_sock_fd( s
, fd
);
3602 release_sock_fd( s
, fd
);
3606 /***********************************************************************
3609 static BOOL WINAPI
WS2_DisconnectEx( SOCKET s
, LPOVERLAPPED ov
, DWORD flags
, DWORD reserved
)
3611 TRACE( "socket %04lx, ov %p, flags 0x%x, reserved 0x%x\n", s
, ov
, flags
, reserved
);
3613 if (flags
& TF_REUSE_SOCKET
)
3614 FIXME( "Reusing socket not supported yet\n" );
3618 ov
->Internal
= STATUS_PENDING
;
3619 ov
->InternalHigh
= 0;
3622 return !WS_shutdown( s
, SD_BOTH
);
3625 /***********************************************************************
3626 * getpeername (WS2_32.5)
3628 int WINAPI
WS_getpeername(SOCKET s
, struct WS_sockaddr
*name
, int *namelen
)
3633 TRACE("socket %04lx, ptr %p, len %08x\n", s
, name
, namelen
? *namelen
: 0);
3635 fd
= get_sock_fd( s
, 0, NULL
);
3640 union generic_unix_sockaddr uaddr
;
3641 socklen_t uaddrlen
= sizeof(uaddr
);
3643 if (getpeername(fd
, &uaddr
.addr
, &uaddrlen
) == 0)
3645 if (!name
|| !namelen
)
3646 SetLastError(WSAEFAULT
);
3647 else if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
3648 /* The buffer was too small */
3649 SetLastError(WSAEFAULT
);
3653 TRACE("=> %s\n", debugstr_sockaddr(name
));
3657 SetLastError(wsaErrno());
3658 release_sock_fd( s
, fd
);
3663 /* When binding to an UDP address with filter support the getsockname call on the socket
3664 * will always return 0.0.0.0 instead of the filtered interface address. This function
3665 * checks if the socket is interface-bound on UDP and return the correct address.
3666 * This is required because applications often do a bind() with port zero followed by a
3667 * getsockname() to retrieve the port and address acquired.
3669 static void interface_bind_check(int fd
, struct sockaddr_in
*addr
)
3671 #if !defined(IP_BOUND_IF) && !defined(LINUX_BOUND_IF)
3677 /* Check for IPv4, address 0.0.0.0 and UDP socket */
3678 if (addr
->sin_family
!= AF_INET
|| addr
->sin_addr
.s_addr
!= 0)
3680 if (_get_fd_type(fd
) != SOCK_DGRAM
)
3684 len
= sizeof(ifindex
);
3685 #if defined(IP_BOUND_IF)
3686 getsockopt(fd
, IPPROTO_IP
, IP_BOUND_IF
, &ifindex
, &len
);
3687 #elif defined(LINUX_BOUND_IF)
3688 getsockopt(fd
, IPPROTO_IP
, IP_UNICAST_IF
, &ifindex
, &len
);
3689 if (ifindex
> 0) ifindex
= ntohl(ifindex
);
3693 PIP_ADAPTER_INFO adapters
, adapter
;
3696 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
3698 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
3699 if (adapters
&& GetAdaptersInfo(adapters
, &adap_size
) == NO_ERROR
)
3701 /* Search the IPv4 adapter list for the appropriate bound interface */
3702 for (adapter
= adapters
; adapter
!= NULL
; adapter
= adapter
->Next
)
3704 in_addr_t adapter_addr
;
3705 if (adapter
->Index
!= ifindex
) continue;
3707 adapter_addr
= inet_addr(adapter
->IpAddressList
.IpAddress
.String
);
3708 addr
->sin_addr
.s_addr
= adapter_addr
;
3709 TRACE("reporting interface address from adapter %d\n", ifindex
);
3713 HeapFree(GetProcessHeap(), 0, adapters
);
3718 /***********************************************************************
3719 * getsockname (WS2_32.6)
3721 int WINAPI
WS_getsockname(SOCKET s
, struct WS_sockaddr
*name
, int *namelen
)
3726 TRACE("socket %04lx, ptr %p, len %08x\n", s
, name
, namelen
? *namelen
: 0);
3728 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3729 if( (name
== NULL
) || (namelen
== NULL
) )
3731 SetLastError( WSAEFAULT
);
3732 return SOCKET_ERROR
;
3735 fd
= get_sock_fd( s
, 0, NULL
);
3740 union generic_unix_sockaddr uaddr
;
3742 int bound
= is_fd_bound(fd
, &uaddr
, &uaddrlen
);
3746 SetLastError(bound
== -1 ? wsaErrno() : WSAEINVAL
);
3748 else if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
3750 /* The buffer was too small */
3751 SetLastError(WSAEFAULT
);
3755 interface_bind_check(fd
, (struct sockaddr_in
*) &uaddr
);
3756 if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
3758 /* The buffer was too small */
3759 SetLastError(WSAEFAULT
);
3764 TRACE("=> %s\n", debugstr_sockaddr(name
));
3767 release_sock_fd( s
, fd
);
3772 /***********************************************************************
3773 * getsockopt (WS2_32.7)
3775 INT WINAPI
WS_getsockopt(SOCKET s
, INT level
,
3776 INT optname
, char *optval
, INT
*optlen
)
3781 TRACE("(socket %04lx, %s, optval %s, optlen %p (%d))\n", s
,
3782 debugstr_sockopt(level
, optname
), debugstr_optval(optval
, 0),
3783 optlen
, optlen
? *optlen
: 0);
3791 /* Handle common cases. The special cases are below, sorted
3793 case WS_SO_BROADCAST
:
3795 case WS_SO_KEEPALIVE
:
3796 case WS_SO_OOBINLINE
:
3798 case WS_SO_REUSEADDR
:
3800 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3801 return SOCKET_ERROR
;
3802 convert_sockopt(&level
, &optname
);
3803 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3805 SetLastError(wsaErrno());
3808 release_sock_fd( s
, fd
);
3810 case WS_SO_ACCEPTCONN
:
3811 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3812 return SOCKET_ERROR
;
3813 if (getsockopt(fd
, SOL_SOCKET
, SO_ACCEPTCONN
, optval
, (socklen_t
*)optlen
) != 0 )
3815 SetLastError(wsaErrno());
3820 /* BSD returns != 0 while Windows return exact == 1 */
3821 if (*(int *)optval
) *(int *)optval
= 1;
3823 release_sock_fd( s
, fd
);
3825 case WS_SO_BSP_STATE
:
3827 int req_size
, addr_size
;
3828 WSAPROTOCOL_INFOW infow
;
3829 CSADDR_INFO
*csinfo
;
3831 ret
= ws_protocol_info(s
, TRUE
, &infow
, &addr_size
);
3834 if (infow
.iAddressFamily
== WS_AF_INET
)
3835 addr_size
= sizeof(struct sockaddr_in
);
3836 else if (infow
.iAddressFamily
== WS_AF_INET6
)
3837 addr_size
= sizeof(struct sockaddr_in6
);
3840 FIXME("Family %d is unsupported for SO_BSP_STATE\n", infow
.iAddressFamily
);
3841 SetLastError(WSAEAFNOSUPPORT
);
3842 return SOCKET_ERROR
;
3845 req_size
= sizeof(CSADDR_INFO
) + addr_size
* 2;
3846 if (*optlen
< req_size
)
3849 SetLastError(WSAEFAULT
);
3853 union generic_unix_sockaddr uaddr
;
3856 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3857 return SOCKET_ERROR
;
3859 csinfo
= (CSADDR_INFO
*) optval
;
3861 /* Check if the sock is bound */
3862 if (is_fd_bound(fd
, &uaddr
, &uaddrlen
) == 1)
3864 csinfo
->LocalAddr
.lpSockaddr
=
3865 (LPSOCKADDR
) (optval
+ sizeof(CSADDR_INFO
));
3866 ws_sockaddr_u2ws(&uaddr
.addr
, csinfo
->LocalAddr
.lpSockaddr
, &addr_size
);
3867 csinfo
->LocalAddr
.iSockaddrLength
= addr_size
;
3871 csinfo
->LocalAddr
.lpSockaddr
= NULL
;
3872 csinfo
->LocalAddr
.iSockaddrLength
= 0;
3875 /* Check if the sock is connected */
3876 if (!getpeername(fd
, &uaddr
.addr
, &uaddrlen
) &&
3877 is_sockaddr_bound(&uaddr
.addr
, uaddrlen
))
3879 csinfo
->RemoteAddr
.lpSockaddr
=
3880 (LPSOCKADDR
) (optval
+ sizeof(CSADDR_INFO
) + addr_size
);
3881 ws_sockaddr_u2ws(&uaddr
.addr
, csinfo
->RemoteAddr
.lpSockaddr
, &addr_size
);
3882 csinfo
->RemoteAddr
.iSockaddrLength
= addr_size
;
3886 csinfo
->RemoteAddr
.lpSockaddr
= NULL
;
3887 csinfo
->RemoteAddr
.iSockaddrLength
= 0;
3890 csinfo
->iSocketType
= infow
.iSocketType
;
3891 csinfo
->iProtocol
= infow
.iProtocol
;
3892 release_sock_fd( s
, fd
);
3895 return ret
? 0 : SOCKET_ERROR
;
3897 case WS_SO_DONTLINGER
:
3899 struct linger lingval
;
3900 socklen_t len
= sizeof(struct linger
);
3902 if (!optlen
|| *optlen
< sizeof(BOOL
)|| !optval
)
3904 SetLastError(WSAEFAULT
);
3905 return SOCKET_ERROR
;
3907 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3908 return SOCKET_ERROR
;
3910 if (getsockopt(fd
, SOL_SOCKET
, SO_LINGER
, &lingval
, &len
) != 0 )
3912 SetLastError(wsaErrno());
3917 *(BOOL
*)optval
= !lingval
.l_onoff
;
3918 *optlen
= sizeof(BOOL
);
3921 release_sock_fd( s
, fd
);
3925 case WS_SO_CONNECT_TIME
:
3927 static int pretendtime
= 0;
3928 struct WS_sockaddr addr
;
3929 int len
= sizeof(addr
);
3931 if (!optlen
|| *optlen
< sizeof(DWORD
) || !optval
)
3933 SetLastError(WSAEFAULT
);
3934 return SOCKET_ERROR
;
3936 if (WS_getpeername(s
, &addr
, &len
) == SOCKET_ERROR
)
3937 *(DWORD
*)optval
= ~0u;
3940 if (!pretendtime
) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3941 *(DWORD
*)optval
= pretendtime
++;
3943 *optlen
= sizeof(DWORD
);
3946 /* As mentioned in setsockopt, Windows ignores this, so we
3947 * always return true here */
3948 case WS_SO_DONTROUTE
:
3949 if (!optlen
|| *optlen
< sizeof(BOOL
) || !optval
)
3951 SetLastError(WSAEFAULT
);
3952 return SOCKET_ERROR
;
3954 *(BOOL
*)optval
= TRUE
;
3955 *optlen
= sizeof(BOOL
);
3960 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3961 return SOCKET_ERROR
;
3962 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, optval
, (socklen_t
*)optlen
) != 0 )
3964 SetLastError(wsaErrno());
3967 release_sock_fd( s
, fd
);
3969 /* The wineserver may have swallowed the error before us */
3970 if (!ret
&& *(int*) optval
== 0)
3972 int i
, events
[FD_MAX_EVENTS
];
3973 _get_sock_errors(s
, events
);
3974 for (i
= 0; i
< FD_MAX_EVENTS
; i
++)
3978 events
[i
] = NtStatusToWSAError(events
[i
]);
3979 TRACE("returning SO_ERROR %d from wine server\n", events
[i
]);
3980 *(int*) optval
= events
[i
];
3990 struct linger lingval
;
3991 socklen_t len
= sizeof(struct linger
);
3993 /* struct linger and LINGER have different sizes */
3994 if (!optlen
|| *optlen
< sizeof(LINGER
) || !optval
)
3996 SetLastError(WSAEFAULT
);
3997 return SOCKET_ERROR
;
3999 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4000 return SOCKET_ERROR
;
4002 if (_get_fd_type(fd
) == SOCK_DGRAM
)
4004 SetLastError(WSAENOPROTOOPT
);
4007 else if (getsockopt(fd
, SOL_SOCKET
, SO_LINGER
, &lingval
, &len
) != 0)
4009 SetLastError(wsaErrno());
4014 ((LINGER
*)optval
)->l_onoff
= lingval
.l_onoff
;
4015 ((LINGER
*)optval
)->l_linger
= lingval
.l_linger
;
4016 *optlen
= sizeof(struct linger
);
4019 release_sock_fd( s
, fd
);
4023 case WS_SO_MAX_MSG_SIZE
:
4024 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
4026 SetLastError(WSAEFAULT
);
4027 return SOCKET_ERROR
;
4029 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
4030 *(int *)optval
= 65507;
4031 *optlen
= sizeof(int);
4034 /* SO_OPENTYPE does not require a valid socket handle. */
4035 case WS_SO_OPENTYPE
:
4036 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
4038 SetLastError(WSAEFAULT
);
4039 return SOCKET_ERROR
;
4041 *(int *)optval
= get_per_thread_data()->opentype
;
4042 *optlen
= sizeof(int);
4043 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval
) );
4045 case WS_SO_PROTOCOL_INFOA
:
4046 case WS_SO_PROTOCOL_INFOW
:
4049 WSAPROTOCOL_INFOW infow
;
4051 ret
= ws_protocol_info(s
, optname
== WS_SO_PROTOCOL_INFOW
, &infow
, &size
);
4054 if (!optlen
|| !optval
|| *optlen
< size
)
4056 if(optlen
) *optlen
= size
;
4058 SetLastError(WSAEFAULT
);
4061 memcpy(optval
, &infow
, size
);
4063 return ret
? 0 : SOCKET_ERROR
;
4065 case WS_SO_RCVTIMEO
:
4066 case WS_SO_SNDTIMEO
:
4070 if (!optlen
|| *optlen
< sizeof(int)|| !optval
)
4072 SetLastError(WSAEFAULT
);
4073 return SOCKET_ERROR
;
4075 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4076 return SOCKET_ERROR
;
4078 timeout
= get_rcvsnd_timeo(fd
, optname
== WS_SO_RCVTIMEO
);
4079 *(int *)optval
= timeout
<= UINT_MAX
? timeout
: UINT_MAX
;
4081 release_sock_fd( s
, fd
);
4087 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
4089 SetLastError(WSAEFAULT
);
4090 return SOCKET_ERROR
;
4092 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4093 return SOCKET_ERROR
;
4095 sock_type
= _get_fd_type(fd
);
4096 if (sock_type
== -1)
4098 SetLastError(wsaErrno());
4102 (*(int *)optval
) = convert_socktype_u2w(sock_type
);
4104 release_sock_fd( s
, fd
);
4108 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname
);
4109 SetLastError(WSAENOPROTOOPT
);
4110 return SOCKET_ERROR
;
4111 } /* end switch(optname) */
4112 }/* end case WS_SOL_SOCKET */
4114 case WS_NSPROTO_IPX
:
4116 struct WS_sockaddr_ipx addr
;
4117 IPX_ADDRESS_DATA
*data
;
4122 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
4124 if(getsockopt(fd
, SOL_IPX
, IPX_TYPE
, optval
, (socklen_t
*)optlen
) == -1)
4131 socklen_t len
=sizeof(struct ipx
);
4132 if(getsockopt(fd
, 0, SO_DEFAULT_HEADERS
, &val
, &len
) == -1 )
4135 *optval
= (int)val
.ipx_pt
;
4138 TRACE("ptype: %d (fd: %d)\n", *(int*)optval
, fd
);
4139 release_sock_fd( s
, fd
);
4142 case WS_IPX_ADDRESS
:
4144 * On a Win2000 system with one network card there are usually
4145 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
4146 * Using this call you can then retrieve info about this all.
4147 * In case of Linux it is a bit different. Usually you have
4148 * only "one" device active and further it is not possible to
4149 * query things like the linkspeed.
4151 FIXME("IPX_ADDRESS\n");
4152 namelen
= sizeof(struct WS_sockaddr_ipx
);
4153 memset(&addr
, 0, sizeof(struct WS_sockaddr_ipx
));
4154 WS_getsockname(s
, (struct WS_sockaddr
*)&addr
, &namelen
);
4156 data
= (IPX_ADDRESS_DATA
*)optval
;
4157 memcpy(data
->nodenum
,addr
.sa_nodenum
,sizeof(data
->nodenum
));
4158 memcpy(data
->netnum
,addr
.sa_netnum
,sizeof(data
->netnum
));
4159 data
->adapternum
= 0;
4160 data
->wan
= FALSE
; /* We are not on a wan for now .. */
4161 data
->status
= FALSE
; /* Since we are not on a wan, the wan link isn't up */
4162 data
->maxpkt
= 1467; /* This value is the default one, at least on Win2k/WinXP */
4163 data
->linkspeed
= 100000; /* Set the line speed in 100bit/s to 10 Mbit;
4164 * note 1MB = 1000kB in this case */
4167 case WS_IPX_MAX_ADAPTER_NUM
:
4168 FIXME("IPX_MAX_ADAPTER_NUM\n");
4169 *(int*)optval
= 1; /* As noted under IPX_ADDRESS we have just one card. */
4173 FIXME("IPX optname:%x\n", optname
);
4174 return SOCKET_ERROR
;
4175 }/* end switch(optname) */
4176 } /* end case WS_NSPROTO_IPX */
4180 #define MAX_IRDA_DEVICES 10
4185 case WS_IRLMP_ENUMDEVICES
:
4187 char buf
[sizeof(struct irda_device_list
) +
4188 (MAX_IRDA_DEVICES
- 1) * sizeof(struct irda_device_info
)];
4190 socklen_t len
= sizeof(buf
);
4192 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4193 return SOCKET_ERROR
;
4194 res
= getsockopt( fd
, SOL_IRLMP
, IRLMP_ENUMDEVICES
, buf
, &len
);
4195 release_sock_fd( s
, fd
);
4198 SetLastError(wsaErrno());
4199 return SOCKET_ERROR
;
4203 struct irda_device_list
*src
= (struct irda_device_list
*)buf
;
4204 DEVICELIST
*dst
= (DEVICELIST
*)optval
;
4205 INT needed
= sizeof(DEVICELIST
);
4209 needed
+= (src
->len
- 1) * sizeof(IRDA_DEVICE_INFO
);
4210 if (*optlen
< needed
)
4212 SetLastError(WSAEFAULT
);
4213 return SOCKET_ERROR
;
4216 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src
->len
);
4217 dst
->numDevice
= src
->len
;
4218 for (i
= 0; i
< src
->len
; i
++)
4220 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
4221 src
->dev
[i
].saddr
, src
->dev
[i
].daddr
,
4222 src
->dev
[i
].info
, src
->dev
[i
].hints
[0],
4223 src
->dev
[i
].hints
[1]);
4224 memcpy( dst
->Device
[i
].irdaDeviceID
,
4226 sizeof(dst
->Device
[i
].irdaDeviceID
) ) ;
4227 memcpy( dst
->Device
[i
].irdaDeviceName
,
4229 sizeof(dst
->Device
[i
].irdaDeviceName
) ) ;
4230 memcpy( &dst
->Device
[i
].irdaDeviceHints1
,
4231 &src
->dev
[i
].hints
[0],
4232 sizeof(dst
->Device
[i
].irdaDeviceHints1
) ) ;
4233 memcpy( &dst
->Device
[i
].irdaDeviceHints2
,
4234 &src
->dev
[i
].hints
[1],
4235 sizeof(dst
->Device
[i
].irdaDeviceHints2
) ) ;
4236 dst
->Device
[i
].irdaCharSet
= src
->dev
[i
].charset
;
4242 FIXME("IrDA optname:0x%x\n", optname
);
4243 return SOCKET_ERROR
;
4245 break; /* case WS_SOL_IRLMP */
4246 #undef MAX_IRDA_DEVICES
4249 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4250 case WS_IPPROTO_TCP
:
4253 case WS_TCP_NODELAY
:
4254 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4255 return SOCKET_ERROR
;
4256 convert_sockopt(&level
, &optname
);
4257 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
4259 SetLastError(wsaErrno());
4262 release_sock_fd( s
, fd
);
4265 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname
);
4266 return SOCKET_ERROR
;
4271 case WS_IP_ADD_MEMBERSHIP
:
4272 case WS_IP_DROP_MEMBERSHIP
:
4276 case WS_IP_MULTICAST_IF
:
4277 case WS_IP_MULTICAST_LOOP
:
4278 case WS_IP_MULTICAST_TTL
:
4285 #ifdef IP_UNICAST_IF
4286 case WS_IP_UNICAST_IF
:
4288 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4289 return SOCKET_ERROR
;
4290 convert_sockopt(&level
, &optname
);
4291 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
4293 SetLastError(wsaErrno());
4296 release_sock_fd( s
, fd
);
4298 case WS_IP_DONTFRAGMENT
:
4299 return get_dont_fragment(s
, IPPROTO_IP
, (BOOL
*)optval
) ? 0 : SOCKET_ERROR
;
4301 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname
);
4302 return SOCKET_ERROR
;
4304 case WS_IPPROTO_IPV6
:
4307 #ifdef IPV6_ADD_MEMBERSHIP
4308 case WS_IPV6_ADD_MEMBERSHIP
:
4310 #ifdef IPV6_DROP_MEMBERSHIP
4311 case WS_IPV6_DROP_MEMBERSHIP
:
4313 case WS_IPV6_MULTICAST_IF
:
4314 case WS_IPV6_MULTICAST_HOPS
:
4315 case WS_IPV6_MULTICAST_LOOP
:
4316 case WS_IPV6_UNICAST_HOPS
:
4317 case WS_IPV6_V6ONLY
:
4318 #ifdef IPV6_UNICAST_IF
4319 case WS_IPV6_UNICAST_IF
:
4321 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
4322 return SOCKET_ERROR
;
4323 convert_sockopt(&level
, &optname
);
4324 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
4326 SetLastError(wsaErrno());
4329 release_sock_fd( s
, fd
);
4331 case WS_IPV6_DONTFRAG
:
4332 return get_dont_fragment(s
, IPPROTO_IPV6
, (BOOL
*)optval
) ? 0 : SOCKET_ERROR
;
4334 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname
);
4335 return SOCKET_ERROR
;
4338 WARN("Unknown level: 0x%08x\n", level
);
4339 SetLastError(WSAEINVAL
);
4340 return SOCKET_ERROR
;
4341 } /* end switch(level) */
4344 /***********************************************************************
4347 WS_u_long WINAPI
WS_htonl(WS_u_long hostlong
)
4349 return htonl(hostlong
);
4353 /***********************************************************************
4356 WS_u_short WINAPI
WS_htons(WS_u_short hostshort
)
4358 return htons(hostshort
);
4361 /***********************************************************************
4362 * WSAHtonl (WS2_32.46)
4363 * From MSDN description of error codes, this function should also
4364 * check if WinSock has been initialized and the socket is a valid
4365 * socket. But why? This function only translates a host byte order
4366 * u_long into a network byte order u_long...
4368 int WINAPI
WSAHtonl(SOCKET s
, WS_u_long hostlong
, WS_u_long
*lpnetlong
)
4372 *lpnetlong
= htonl(hostlong
);
4375 SetLastError(WSAEFAULT
);
4376 return SOCKET_ERROR
;
4379 /***********************************************************************
4380 * WSAHtons (WS2_32.47)
4381 * From MSDN description of error codes, this function should also
4382 * check if WinSock has been initialized and the socket is a valid
4383 * socket. But why? This function only translates a host byte order
4384 * u_short into a network byte order u_short...
4386 int WINAPI
WSAHtons(SOCKET s
, WS_u_short hostshort
, WS_u_short
*lpnetshort
)
4391 *lpnetshort
= htons(hostshort
);
4394 SetLastError(WSAEFAULT
);
4395 return SOCKET_ERROR
;
4399 /***********************************************************************
4400 * inet_addr (WS2_32.11)
4402 WS_u_long WINAPI
WS_inet_addr(const char *cp
)
4404 if (!cp
) return INADDR_NONE
;
4405 return inet_addr(cp
);
4409 /***********************************************************************
4412 WS_u_long WINAPI
WS_ntohl(WS_u_long netlong
)
4414 return ntohl(netlong
);
4418 /***********************************************************************
4421 WS_u_short WINAPI
WS_ntohs(WS_u_short netshort
)
4423 return ntohs(netshort
);
4427 /***********************************************************************
4428 * inet_ntoa (WS2_32.12)
4430 char* WINAPI
WS_inet_ntoa(struct WS_in_addr in
)
4432 unsigned int long_ip
= ntohl(in
.WS_s_addr
);
4433 struct per_thread_data
*data
= get_per_thread_data();
4435 sprintf( data
->ntoa_buffer
, "%u.%u.%u.%u",
4436 (long_ip
>> 24) & 0xff,
4437 (long_ip
>> 16) & 0xff,
4438 (long_ip
>> 8) & 0xff,
4441 return data
->ntoa_buffer
;
4444 static const char *debugstr_wsaioctl(DWORD code
)
4446 const char *name
= NULL
, *buf_type
, *family
;
4448 #define IOCTL_NAME(x) case x: name = #x; break
4451 IOCTL_NAME(WS_FIONBIO
);
4452 IOCTL_NAME(WS_FIONREAD
);
4453 IOCTL_NAME(WS_SIOCATMARK
);
4454 /* IOCTL_NAME(WS_SIO_ACQUIRE_PORT_RESERVATION); */
4455 IOCTL_NAME(WS_SIO_ADDRESS_LIST_CHANGE
);
4456 IOCTL_NAME(WS_SIO_ADDRESS_LIST_QUERY
);
4457 IOCTL_NAME(WS_SIO_ASSOCIATE_HANDLE
);
4458 /* IOCTL_NAME(WS_SIO_ASSOCIATE_PORT_RESERVATION);
4459 IOCTL_NAME(WS_SIO_BASE_HANDLE);
4460 IOCTL_NAME(WS_SIO_BSP_HANDLE);
4461 IOCTL_NAME(WS_SIO_BSP_HANDLE_SELECT);
4462 IOCTL_NAME(WS_SIO_BSP_HANDLE_POLL);
4463 IOCTL_NAME(WS_SIO_CHK_QOS); */
4464 IOCTL_NAME(WS_SIO_ENABLE_CIRCULAR_QUEUEING
);
4465 IOCTL_NAME(WS_SIO_FIND_ROUTE
);
4466 IOCTL_NAME(WS_SIO_FLUSH
);
4467 IOCTL_NAME(WS_SIO_GET_BROADCAST_ADDRESS
);
4468 IOCTL_NAME(WS_SIO_GET_EXTENSION_FUNCTION_POINTER
);
4469 IOCTL_NAME(WS_SIO_GET_GROUP_QOS
);
4470 IOCTL_NAME(WS_SIO_GET_INTERFACE_LIST
);
4471 /* IOCTL_NAME(WS_SIO_GET_INTERFACE_LIST_EX); */
4472 IOCTL_NAME(WS_SIO_GET_QOS
);
4473 /* IOCTL_NAME(WS_SIO_IDEAL_SEND_BACKLOG_CHANGE);
4474 IOCTL_NAME(WS_SIO_IDEAL_SEND_BACKLOG_QUERY); */
4475 IOCTL_NAME(WS_SIO_KEEPALIVE_VALS
);
4476 IOCTL_NAME(WS_SIO_MULTIPOINT_LOOPBACK
);
4477 IOCTL_NAME(WS_SIO_MULTICAST_SCOPE
);
4478 /* IOCTL_NAME(WS_SIO_QUERY_RSS_SCALABILITY_INFO);
4479 IOCTL_NAME(WS_SIO_QUERY_WFP_ALE_ENDPOINT_HANDLE); */
4480 IOCTL_NAME(WS_SIO_RCVALL
);
4481 IOCTL_NAME(WS_SIO_RCVALL_IGMPMCAST
);
4482 IOCTL_NAME(WS_SIO_RCVALL_MCAST
);
4483 /* IOCTL_NAME(WS_SIO_RELEASE_PORT_RESERVATION); */
4484 IOCTL_NAME(WS_SIO_ROUTING_INTERFACE_CHANGE
);
4485 IOCTL_NAME(WS_SIO_ROUTING_INTERFACE_QUERY
);
4486 IOCTL_NAME(WS_SIO_SET_COMPATIBILITY_MODE
);
4487 IOCTL_NAME(WS_SIO_SET_GROUP_QOS
);
4488 IOCTL_NAME(WS_SIO_SET_QOS
);
4489 IOCTL_NAME(WS_SIO_TRANSLATE_HANDLE
);
4490 IOCTL_NAME(WS_SIO_UDP_CONNRESET
);
4497 /* If this is not a known code split its bits */
4498 switch(code
& 0x18000000)
4503 case WS_IOC_PROTOCOL
:
4504 family
= "IOC_PROTOCOL";
4507 family
= "IOC_VENDOR";
4509 default: /* WS_IOC_UNIX */
4511 BYTE size
= (code
>> 16) & WS_IOCPARM_MASK
;
4512 char x
= (code
& 0xff00) >> 8;
4513 BYTE y
= code
& 0xff;
4516 switch (code
& (WS_IOC_VOID
|WS_IOC_INOUT
))
4520 sprintf(args
, "%d, %d", x
, y
);
4524 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
4528 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
4532 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
4535 return wine_dbg_sprintf("%s(%s)", buf_type
, args
);
4539 /* We are different from WS_IOC_UNIX. */
4540 switch (code
& (WS_IOC_VOID
|WS_IOC_INOUT
))
4543 buf_type
= "_WSAIO";
4546 buf_type
= "_WSAIORW";
4549 buf_type
= "_WSAIOW";
4552 buf_type
= "_WSAIOR";
4559 return wine_dbg_sprintf("%s(%s, %d)", buf_type
, family
,
4560 (USHORT
)(code
& 0xffff));
4563 /* do an ioctl call through the server */
4564 static DWORD
server_ioctl_sock( SOCKET s
, DWORD code
, LPVOID in_buff
, DWORD in_size
,
4565 LPVOID out_buff
, DWORD out_size
, LPDWORD ret_size
,
4566 LPWSAOVERLAPPED overlapped
,
4567 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
4569 HANDLE event
= overlapped
? overlapped
->hEvent
: 0;
4570 HANDLE handle
= SOCKET2HANDLE( s
);
4571 struct ws2_async
*wsa
= NULL
;
4572 IO_STATUS_BLOCK
*io
= (PIO_STATUS_BLOCK
)overlapped
, iosb
;
4573 void *cvalue
= NULL
;
4578 if (!(wsa
= (struct ws2_async
*)alloc_async_io( sizeof(*wsa
), NULL
)))
4579 return WSA_NOT_ENOUGH_MEMORY
;
4580 wsa
->hSocket
= handle
;
4581 wsa
->user_overlapped
= overlapped
;
4582 wsa
->completion_func
= completion
;
4583 if (!io
) io
= &wsa
->local_iosb
;
4588 else if (!((ULONG_PTR
)overlapped
->hEvent
& 1))
4589 cvalue
= overlapped
;
4591 status
= NtDeviceIoControlFile( handle
, event
, wsa
? ws2_async_apc
: NULL
, cvalue
, io
, code
,
4592 in_buff
, in_size
, out_buff
, out_size
);
4593 if (status
== STATUS_NOT_SUPPORTED
)
4595 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
4596 code
, code
>> 16, (code
>> 14) & 3, (code
>> 2) & 0xfff, code
& 3);
4598 else if (status
== STATUS_SUCCESS
)
4599 *ret_size
= io
->Information
; /* "Information" is the size written to the output buffer */
4601 if (status
!= STATUS_PENDING
) RtlFreeHeap( GetProcessHeap(), 0, wsa
);
4603 return NtStatusToWSAError( status
);
4606 /**********************************************************************
4607 * WSAIoctl (WS2_32.50)
4610 INT WINAPI
WSAIoctl(SOCKET s
, DWORD code
, LPVOID in_buff
, DWORD in_size
, LPVOID out_buff
,
4611 DWORD out_size
, LPDWORD ret_size
, LPWSAOVERLAPPED overlapped
,
4612 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
4615 DWORD status
= 0, total
= 0;
4617 TRACE("%04lx, %s, %p, %d, %p, %d, %p, %p, %p\n",
4618 s
, debugstr_wsaioctl(code
), in_buff
, in_size
, out_buff
, out_size
, ret_size
, overlapped
, completion
);
4623 if (in_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(in_buff
))
4625 SetLastError(WSAEFAULT
);
4626 return SOCKET_ERROR
;
4628 TRACE("-> FIONBIO (%x)\n", *(WS_u_long
*)in_buff
);
4629 if (_get_sock_mask(s
))
4631 /* AsyncSelect()'ed sockets are always nonblocking */
4632 if (!*(WS_u_long
*)in_buff
) status
= WSAEINVAL
;
4635 if (*(WS_u_long
*)in_buff
)
4636 _enable_event(SOCKET2HANDLE(s
), 0, FD_WINE_NONBLOCKING
, 0);
4638 _enable_event(SOCKET2HANDLE(s
), 0, 0, FD_WINE_NONBLOCKING
);
4643 if (out_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(out_buff
))
4645 SetLastError(WSAEFAULT
);
4646 return SOCKET_ERROR
;
4648 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
4649 if (ioctl(fd
, FIONREAD
, out_buff
) == -1)
4650 status
= wsaErrno();
4651 release_sock_fd( s
, fd
);
4657 unsigned int oob
= 0, atmark
= 0;
4658 socklen_t oobsize
= sizeof(int);
4659 if (out_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(out_buff
))
4661 SetLastError(WSAEFAULT
);
4662 return SOCKET_ERROR
;
4664 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
4665 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
4666 if ((getsockopt(fd
, SOL_SOCKET
, SO_OOBINLINE
, &oob
, &oobsize
) == -1)
4667 || (!oob
&& ioctl(fd
, SIOCATMARK
, &atmark
) == -1))
4668 status
= wsaErrno();
4671 /* The SIOCATMARK value read from ioctl() is reversed
4672 * because BSD returns TRUE if it's in the OOB mark
4673 * while Windows returns TRUE if there are NO OOB bytes.
4675 (*(WS_u_long
*) out_buff
) = oob
|| !atmark
;
4678 release_sock_fd( s
, fd
);
4683 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
4684 SetLastError(WSAEINVAL
);
4685 return SOCKET_ERROR
;
4687 case WS_SIO_GET_INTERFACE_LIST
:
4689 INTERFACE_INFO
* intArray
= out_buff
;
4690 DWORD size
, numInt
= 0, apiReturn
;
4692 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
4694 if (!out_buff
|| !ret_size
)
4696 SetLastError(WSAEFAULT
);
4697 return SOCKET_ERROR
;
4700 fd
= get_sock_fd( s
, 0, NULL
);
4701 if (fd
== -1) return SOCKET_ERROR
;
4703 apiReturn
= GetAdaptersInfo(NULL
, &size
);
4704 if (apiReturn
== ERROR_BUFFER_OVERFLOW
)
4706 PIP_ADAPTER_INFO table
= HeapAlloc(GetProcessHeap(),0,size
);
4710 if (GetAdaptersInfo(table
, &size
) == NO_ERROR
)
4712 PIP_ADAPTER_INFO ptr
;
4714 for (ptr
= table
, numInt
= 0; ptr
; ptr
= ptr
->Next
)
4716 unsigned int addr
, mask
, bcast
;
4717 struct ifreq ifInfo
;
4719 /* Skip interfaces without an IPv4 address. */
4720 if (ptr
->IpAddressList
.IpAddress
.String
[0] == '\0')
4723 if ((numInt
+ 1)*sizeof(INTERFACE_INFO
)/sizeof(IP_ADAPTER_INFO
) > out_size
)
4725 WARN("Buffer too small = %u, out_size = %u\n", numInt
+ 1, out_size
);
4730 /* Socket Status Flags */
4731 lstrcpynA(ifInfo
.ifr_name
, ptr
->AdapterName
, IFNAMSIZ
);
4732 if (ioctl(fd
, SIOCGIFFLAGS
, &ifInfo
) < 0)
4734 ERR("Error obtaining status flags for socket!\n");
4740 /* set flags; the values of IFF_* are not the same
4741 under Linux and Windows, therefore must generate
4743 intArray
->iiFlags
= 0;
4744 if (ifInfo
.ifr_flags
& IFF_BROADCAST
)
4745 intArray
->iiFlags
|= WS_IFF_BROADCAST
;
4746 #ifdef IFF_POINTOPOINT
4747 if (ifInfo
.ifr_flags
& IFF_POINTOPOINT
)
4748 intArray
->iiFlags
|= WS_IFF_POINTTOPOINT
;
4750 if (ifInfo
.ifr_flags
& IFF_LOOPBACK
)
4751 intArray
->iiFlags
|= WS_IFF_LOOPBACK
;
4752 if (ifInfo
.ifr_flags
& IFF_UP
)
4753 intArray
->iiFlags
|= WS_IFF_UP
;
4754 if (ifInfo
.ifr_flags
& IFF_MULTICAST
)
4755 intArray
->iiFlags
|= WS_IFF_MULTICAST
;
4758 addr
= inet_addr(ptr
->IpAddressList
.IpAddress
.String
);
4759 mask
= inet_addr(ptr
->IpAddressList
.IpMask
.String
);
4760 bcast
= addr
| ~mask
;
4761 intArray
->iiAddress
.AddressIn
.sin_family
= WS_AF_INET
;
4762 intArray
->iiAddress
.AddressIn
.sin_port
= 0;
4763 intArray
->iiAddress
.AddressIn
.sin_addr
.WS_s_addr
= addr
;
4765 intArray
->iiNetmask
.AddressIn
.sin_family
= WS_AF_INET
;
4766 intArray
->iiNetmask
.AddressIn
.sin_port
= 0;
4767 intArray
->iiNetmask
.AddressIn
.sin_addr
.WS_s_addr
= mask
;
4769 intArray
->iiBroadcastAddress
.AddressIn
.sin_family
= WS_AF_INET
;
4770 intArray
->iiBroadcastAddress
.AddressIn
.sin_port
= 0;
4771 intArray
->iiBroadcastAddress
.AddressIn
.sin_addr
.WS_s_addr
= bcast
;
4778 ERR("Unable to get interface table!\n");
4781 HeapFree(GetProcessHeap(),0,table
);
4783 else status
= WSAEINVAL
;
4785 else if (apiReturn
!= ERROR_NO_DATA
)
4787 ERR("Unable to get interface table!\n");
4790 /* Calculate the size of the array being returned */
4791 total
= sizeof(INTERFACE_INFO
) * numInt
;
4792 release_sock_fd( s
, fd
);
4796 case WS_SIO_ADDRESS_LIST_QUERY
:
4800 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
4804 SetLastError(WSAEFAULT
);
4805 return SOCKET_ERROR
;
4808 if (out_size
&& out_size
< FIELD_OFFSET(SOCKET_ADDRESS_LIST
, Address
[0]))
4811 SetLastError(WSAEINVAL
);
4812 return SOCKET_ERROR
;
4815 if (GetAdaptersInfo(NULL
, &size
) == ERROR_BUFFER_OVERFLOW
)
4817 IP_ADAPTER_INFO
*p
, *table
= HeapAlloc(GetProcessHeap(), 0, size
);
4818 SOCKET_ADDRESS_LIST
*sa_list
;
4819 SOCKADDR_IN
*sockaddr
;
4824 if (!table
|| GetAdaptersInfo(table
, &size
))
4826 HeapFree(GetProcessHeap(), 0, table
);
4831 for (p
= table
, num
= 0; p
; p
= p
->Next
)
4832 if (p
->IpAddressList
.IpAddress
.String
[0]) num
++;
4834 total
= FIELD_OFFSET(SOCKET_ADDRESS_LIST
, Address
[num
]) + num
* sizeof(*sockaddr
);
4835 if (total
> out_size
|| !out_buff
)
4838 HeapFree(GetProcessHeap(), 0, table
);
4844 sa
= sa_list
->Address
;
4845 sockaddr
= (SOCKADDR_IN
*)&sa
[num
];
4846 sa_list
->iAddressCount
= num
;
4848 for (p
= table
, i
= 0; p
; p
= p
->Next
)
4850 if (!p
->IpAddressList
.IpAddress
.String
[0]) continue;
4852 sa
[i
].lpSockaddr
= (SOCKADDR
*)&sockaddr
[i
];
4853 sa
[i
].iSockaddrLength
= sizeof(SOCKADDR
);
4855 sockaddr
[i
].sin_family
= WS_AF_INET
;
4856 sockaddr
[i
].sin_port
= 0;
4857 sockaddr
[i
].sin_addr
.WS_s_addr
= inet_addr(p
->IpAddressList
.IpAddress
.String
);
4861 HeapFree(GetProcessHeap(), 0, table
);
4865 WARN("unable to get IP address list\n");
4872 FIXME("SIO_FLUSH: stub.\n");
4875 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER
:
4877 #define EXTENSION_FUNCTION(x, y) { x, y, #y },
4884 EXTENSION_FUNCTION(WSAID_CONNECTEX
, WS2_ConnectEx
)
4885 EXTENSION_FUNCTION(WSAID_DISCONNECTEX
, WS2_DisconnectEx
)
4886 EXTENSION_FUNCTION(WSAID_ACCEPTEX
, WS2_AcceptEx
)
4887 EXTENSION_FUNCTION(WSAID_GETACCEPTEXSOCKADDRS
, WS2_GetAcceptExSockaddrs
)
4888 EXTENSION_FUNCTION(WSAID_TRANSMITFILE
, WS2_TransmitFile
)
4889 /* EXTENSION_FUNCTION(WSAID_TRANSMITPACKETS, WS2_TransmitPackets) */
4890 EXTENSION_FUNCTION(WSAID_WSARECVMSG
, WS2_WSARecvMsg
)
4891 EXTENSION_FUNCTION(WSAID_WSASENDMSG
, WSASendMsg
)
4893 #undef EXTENSION_FUNCTION
4897 for (i
= 0; i
< sizeof(guid_funcs
) / sizeof(guid_funcs
[0]); i
++)
4899 if (IsEqualGUID(&guid_funcs
[i
].guid
, in_buff
))
4908 TRACE("-> got %s\n", guid_funcs
[i
].name
);
4909 *(void **)out_buff
= guid_funcs
[i
].func_ptr
;
4913 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff
));
4914 status
= WSAEOPNOTSUPP
;
4917 case WS_SIO_KEEPALIVE_VALS
:
4919 struct tcp_keepalive
*k
;
4920 int keepalive
, keepidle
, keepintvl
;
4922 if (!in_buff
|| in_size
< sizeof(struct tcp_keepalive
))
4924 SetLastError(WSAEFAULT
);
4925 return SOCKET_ERROR
;
4929 keepalive
= k
->onoff
? 1 : 0;
4930 keepidle
= max( 1, (k
->keepalivetime
+ 500) / 1000 );
4931 keepintvl
= max( 1, (k
->keepaliveinterval
+ 500) / 1000 );
4933 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive
, keepidle
, keepintvl
);
4935 fd
= get_sock_fd(s
, 0, NULL
);
4936 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&keepalive
, sizeof(int)) == -1)
4938 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPINTVL)
4939 /* these values need to be set only if SO_KEEPALIVE is enabled */
4942 #ifndef TCP_KEEPIDLE
4943 FIXME("ignoring keepalive timeout\n");
4945 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPIDLE
, (void *)&keepidle
, sizeof(int)) == -1)
4949 #ifdef TCP_KEEPINTVL
4950 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPINTVL
, (void *)&keepintvl
, sizeof(int)) == -1)
4953 FIXME("ignoring keepalive interval\n");
4958 FIXME("ignoring keepalive interval and timeout\n");
4960 release_sock_fd(s
, fd
);
4963 case WS_SIO_ROUTING_INTERFACE_QUERY
:
4965 struct WS_sockaddr
*daddr
= (struct WS_sockaddr
*)in_buff
;
4966 struct WS_sockaddr_in
*daddr_in
= (struct WS_sockaddr_in
*)daddr
;
4967 struct WS_sockaddr_in
*saddr_in
= out_buff
;
4968 MIB_IPFORWARDROW row
;
4969 PMIB_IPADDRTABLE ipAddrTable
= NULL
;
4970 DWORD size
, i
, found_index
;
4972 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4974 if (!in_buff
|| in_size
< sizeof(struct WS_sockaddr
) ||
4975 !out_buff
|| out_size
< sizeof(struct WS_sockaddr_in
) || !ret_size
)
4977 SetLastError(WSAEFAULT
);
4978 return SOCKET_ERROR
;
4980 if (daddr
->sa_family
!= WS_AF_INET
)
4982 FIXME("unsupported address family %d\n", daddr
->sa_family
);
4983 status
= WSAEAFNOSUPPORT
;
4986 if (GetBestRoute(daddr_in
->sin_addr
.S_un
.S_addr
, 0, &row
) != NOERROR
||
4987 GetIpAddrTable(NULL
, &size
, FALSE
) != ERROR_INSUFFICIENT_BUFFER
)
4992 ipAddrTable
= HeapAlloc(GetProcessHeap(), 0, size
);
4993 if (GetIpAddrTable(ipAddrTable
, &size
, FALSE
))
4995 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
4999 for (i
= 0, found_index
= ipAddrTable
->dwNumEntries
;
5000 i
< ipAddrTable
->dwNumEntries
; i
++)
5002 if (ipAddrTable
->table
[i
].dwIndex
== row
.dwForwardIfIndex
)
5005 if (found_index
== ipAddrTable
->dwNumEntries
)
5007 ERR("no matching IP address for interface %d\n",
5008 row
.dwForwardIfIndex
);
5009 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
5013 saddr_in
->sin_family
= WS_AF_INET
;
5014 saddr_in
->sin_addr
.S_un
.S_addr
= ipAddrTable
->table
[found_index
].dwAddr
;
5015 saddr_in
->sin_port
= 0;
5016 total
= sizeof(struct WS_sockaddr_in
);
5017 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
5020 case WS_SIO_SET_COMPATIBILITY_MODE
:
5021 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
5022 status
= WSAEOPNOTSUPP
;
5024 case WS_SIO_UDP_CONNRESET
:
5025 FIXME("WS_SIO_UDP_CONNRESET stub\n");
5027 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
5028 SetLastError(WSAEOPNOTSUPP
);
5029 return SOCKET_ERROR
;
5031 status
= WSAEOPNOTSUPP
;
5035 if (status
== WSAEOPNOTSUPP
)
5037 status
= server_ioctl_sock(s
, code
, in_buff
, in_size
, out_buff
, out_size
, &total
,
5038 overlapped
, completion
);
5039 if (status
!= WSAEOPNOTSUPP
)
5041 if (status
== 0 || status
== WSA_IO_PENDING
)
5042 TRACE("-> %s request\n", debugstr_wsaioctl(code
));
5044 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code
), status
);
5046 /* overlapped and completion operations will be handled by the server */
5051 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code
));
5056 FIXME( "completion routine %p not supported\n", completion
);
5058 else if (overlapped
)
5060 ULONG_PTR cvalue
= (overlapped
&& ((ULONG_PTR
)overlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)overlapped
: 0;
5061 overlapped
->Internal
= status
;
5062 overlapped
->InternalHigh
= total
;
5063 if (overlapped
->hEvent
) NtSetEvent( overlapped
->hEvent
, NULL
);
5064 if (cvalue
) WS_AddCompletion( HANDLE2SOCKET(s
), cvalue
, status
, total
);
5069 if (ret_size
) *ret_size
= total
;
5072 SetLastError( status
);
5073 return SOCKET_ERROR
;
5077 /***********************************************************************
5078 * ioctlsocket (WS2_32.10)
5080 int WINAPI
WS_ioctlsocket(SOCKET s
, LONG cmd
, WS_u_long
*argp
)
5083 return WSAIoctl( s
, cmd
, argp
, sizeof(WS_u_long
), argp
, sizeof(WS_u_long
), &ret_size
, NULL
, NULL
);
5086 /***********************************************************************
5087 * listen (WS2_32.13)
5089 int WINAPI
WS_listen(SOCKET s
, int backlog
)
5091 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
), ret
= SOCKET_ERROR
;
5093 TRACE("socket %04lx, backlog %d\n", s
, backlog
);
5096 int bound
= is_fd_bound(fd
, NULL
, NULL
);
5100 SetLastError(bound
== -1 ? wsaErrno() : WSAEINVAL
);
5102 else if (listen(fd
, backlog
) == 0)
5104 _enable_event(SOCKET2HANDLE(s
), FD_ACCEPT
,
5106 FD_CONNECT
|FD_WINE_CONNECTED
);
5110 SetLastError(wsaErrno());
5111 release_sock_fd( s
, fd
);
5114 SetLastError(WSAENOTSOCK
);
5118 /***********************************************************************
5121 int WINAPI
WS_recv(SOCKET s
, char *buf
, int len
, int flags
)
5123 DWORD n
, dwFlags
= flags
;
5129 if ( WS2_recv_base(s
, &wsabuf
, 1, &n
, &dwFlags
, NULL
, NULL
, NULL
, NULL
, NULL
) == SOCKET_ERROR
)
5130 return SOCKET_ERROR
;
5135 /***********************************************************************
5136 * recvfrom (WS2_32.17)
5138 int WINAPI
WS_recvfrom(SOCKET s
, char *buf
, INT len
, int flags
,
5139 struct WS_sockaddr
*from
, int *fromlen
)
5141 DWORD n
, dwFlags
= flags
;
5147 if ( WS2_recv_base(s
, &wsabuf
, 1, &n
, &dwFlags
, from
, fromlen
, NULL
, NULL
, NULL
) == SOCKET_ERROR
)
5148 return SOCKET_ERROR
;
5153 /* allocate a poll array for the corresponding fd sets */
5154 static struct pollfd
*fd_sets_to_poll( const WS_fd_set
*readfds
, const WS_fd_set
*writefds
,
5155 const WS_fd_set
*exceptfds
, int *count_ptr
)
5157 unsigned int i
, j
= 0, count
= 0;
5159 struct per_thread_data
*ptb
= get_per_thread_data();
5161 if (readfds
) count
+= readfds
->fd_count
;
5162 if (writefds
) count
+= writefds
->fd_count
;
5163 if (exceptfds
) count
+= exceptfds
->fd_count
;
5167 SetLastError(WSAEINVAL
);
5171 /* check if the cache can hold all descriptors, if not do the resizing */
5172 if (ptb
->fd_count
< count
)
5174 if (!(fds
= HeapAlloc(GetProcessHeap(), 0, count
* sizeof(fds
[0]))))
5176 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
5179 HeapFree(GetProcessHeap(), 0, ptb
->fd_cache
);
5180 ptb
->fd_cache
= fds
;
5181 ptb
->fd_count
= count
;
5184 fds
= ptb
->fd_cache
;
5187 for (i
= 0; i
< readfds
->fd_count
; i
++, j
++)
5189 fds
[j
].fd
= get_sock_fd( readfds
->fd_array
[i
], FILE_READ_DATA
, NULL
);
5190 if (fds
[j
].fd
== -1) goto failed
;
5192 if (is_fd_bound(fds
[j
].fd
, NULL
, NULL
) == 1)
5194 fds
[j
].events
= POLLIN
;
5198 release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
5204 for (i
= 0; i
< writefds
->fd_count
; i
++, j
++)
5206 fds
[j
].fd
= get_sock_fd( writefds
->fd_array
[i
], FILE_WRITE_DATA
, NULL
);
5207 if (fds
[j
].fd
== -1) goto failed
;
5209 if (is_fd_bound(fds
[j
].fd
, NULL
, NULL
) == 1 ||
5210 _get_fd_type(fds
[j
].fd
) == SOCK_DGRAM
)
5212 fds
[j
].events
= POLLOUT
;
5216 release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
5222 for (i
= 0; i
< exceptfds
->fd_count
; i
++, j
++)
5224 fds
[j
].fd
= get_sock_fd( exceptfds
->fd_array
[i
], 0, NULL
);
5225 if (fds
[j
].fd
== -1) goto failed
;
5227 if (is_fd_bound(fds
[j
].fd
, NULL
, NULL
) == 1)
5229 int oob_inlined
= 0;
5230 socklen_t olen
= sizeof(oob_inlined
);
5232 fds
[j
].events
= POLLHUP
;
5234 /* Check if we need to test for urgent data or not */
5235 getsockopt(fds
[j
].fd
, SOL_SOCKET
, SO_OOBINLINE
, (char*) &oob_inlined
, &olen
);
5237 fds
[j
].events
|= POLLPRI
;
5241 release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
5252 for (i
= 0; i
< readfds
->fd_count
&& j
< count
; i
++, j
++)
5253 if (fds
[j
].fd
!= -1) release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
5255 for (i
= 0; i
< writefds
->fd_count
&& j
< count
; i
++, j
++)
5256 if (fds
[j
].fd
!= -1) release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
5258 for (i
= 0; i
< exceptfds
->fd_count
&& j
< count
; i
++, j
++)
5259 if (fds
[j
].fd
!= -1) release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
5263 /* release the file descriptor obtained in fd_sets_to_poll */
5264 /* must be called with the original fd_set arrays, before calling get_poll_results */
5265 static void release_poll_fds( const WS_fd_set
*readfds
, const WS_fd_set
*writefds
,
5266 const WS_fd_set
*exceptfds
, struct pollfd
*fds
)
5268 unsigned int i
, j
= 0;
5272 for (i
= 0; i
< readfds
->fd_count
; i
++, j
++)
5273 if (fds
[j
].fd
!= -1) release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
5277 for (i
= 0; i
< writefds
->fd_count
; i
++, j
++)
5278 if (fds
[j
].fd
!= -1) release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
5282 for (i
= 0; i
< exceptfds
->fd_count
; i
++, j
++)
5284 if (fds
[j
].fd
== -1) continue;
5285 release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
5286 if (fds
[j
].revents
& POLLHUP
)
5288 int fd
= get_sock_fd( exceptfds
->fd_array
[i
], 0, NULL
);
5290 release_sock_fd( exceptfds
->fd_array
[i
], fd
);
5298 static int do_poll(struct pollfd
*pollfds
, int count
, int timeout
)
5300 struct timeval tv1
, tv2
;
5301 int ret
, torig
= timeout
;
5303 if (timeout
> 0) gettimeofday( &tv1
, 0 );
5305 while ((ret
= poll( pollfds
, count
, timeout
)) < 0)
5307 if (errno
!= EINTR
) break;
5308 if (timeout
< 0) continue;
5309 if (timeout
== 0) return 0;
5311 gettimeofday( &tv2
, 0 );
5313 tv2
.tv_sec
-= tv1
.tv_sec
;
5314 tv2
.tv_usec
-= tv1
.tv_usec
;
5315 if (tv2
.tv_usec
< 0)
5317 tv2
.tv_usec
+= 1000000;
5321 timeout
= torig
- (tv2
.tv_sec
* 1000) - (tv2
.tv_usec
+ 999) / 1000;
5322 if (timeout
<= 0) return 0;
5327 /* map the poll results back into the Windows fd sets */
5328 static int get_poll_results( WS_fd_set
*readfds
, WS_fd_set
*writefds
, WS_fd_set
*exceptfds
,
5329 const struct pollfd
*fds
)
5331 const struct pollfd
*poll_writefds
= fds
+ (readfds
? readfds
->fd_count
: 0);
5332 const struct pollfd
*poll_exceptfds
= poll_writefds
+ (writefds
? writefds
->fd_count
: 0);
5333 unsigned int i
, k
, total
= 0;
5337 for (i
= k
= 0; i
< readfds
->fd_count
; i
++)
5339 if (fds
[i
].revents
||
5340 (readfds
== writefds
&& (poll_writefds
[i
].revents
& POLLOUT
) && !(poll_writefds
[i
].revents
& POLLHUP
)) ||
5341 (readfds
== exceptfds
&& poll_exceptfds
[i
].revents
))
5342 readfds
->fd_array
[k
++] = readfds
->fd_array
[i
];
5344 readfds
->fd_count
= k
;
5347 if (writefds
&& writefds
!= readfds
)
5349 for (i
= k
= 0; i
< writefds
->fd_count
; i
++)
5351 if (((poll_writefds
[i
].revents
& POLLOUT
) && !(poll_writefds
[i
].revents
& POLLHUP
)) ||
5352 (writefds
== exceptfds
&& poll_exceptfds
[i
].revents
))
5353 writefds
->fd_array
[k
++] = writefds
->fd_array
[i
];
5355 writefds
->fd_count
= k
;
5358 if (exceptfds
&& exceptfds
!= readfds
&& exceptfds
!= writefds
)
5360 for (i
= k
= 0; i
< exceptfds
->fd_count
; i
++)
5361 if (poll_exceptfds
[i
].revents
) exceptfds
->fd_array
[k
++] = exceptfds
->fd_array
[i
];
5362 exceptfds
->fd_count
= k
;
5368 /***********************************************************************
5369 * select (WS2_32.18)
5371 int WINAPI
WS_select(int nfds
, WS_fd_set
*ws_readfds
,
5372 WS_fd_set
*ws_writefds
, WS_fd_set
*ws_exceptfds
,
5373 const struct WS_timeval
* ws_timeout
)
5375 struct pollfd
*pollfds
;
5376 int count
, ret
, timeout
= -1;
5378 TRACE("read %p, write %p, excp %p timeout %p\n",
5379 ws_readfds
, ws_writefds
, ws_exceptfds
, ws_timeout
);
5381 if (!(pollfds
= fd_sets_to_poll( ws_readfds
, ws_writefds
, ws_exceptfds
, &count
)))
5382 return SOCKET_ERROR
;
5385 timeout
= (ws_timeout
->tv_sec
* 1000) + (ws_timeout
->tv_usec
+ 999) / 1000;
5387 ret
= do_poll(pollfds
, count
, timeout
);
5388 release_poll_fds( ws_readfds
, ws_writefds
, ws_exceptfds
, pollfds
);
5390 if (ret
== -1) SetLastError(wsaErrno());
5391 else ret
= get_poll_results( ws_readfds
, ws_writefds
, ws_exceptfds
, pollfds
);
5395 /***********************************************************************
5398 int WINAPI
WSAPoll(WSAPOLLFD
*wfds
, ULONG count
, int timeout
)
5401 struct pollfd
*ufds
;
5405 SetLastError(WSAEINVAL
);
5406 return SOCKET_ERROR
;
5410 SetLastError(WSAEFAULT
);
5411 return SOCKET_ERROR
;
5414 if (!(ufds
= HeapAlloc(GetProcessHeap(), 0, count
* sizeof(ufds
[0]))))
5416 SetLastError(WSAENOBUFS
);
5417 return SOCKET_ERROR
;
5420 for (i
= 0; i
< count
; i
++)
5422 ufds
[i
].fd
= get_sock_fd(wfds
[i
].fd
, 0, NULL
);
5423 ufds
[i
].events
= convert_poll_w2u(wfds
[i
].events
);
5424 ufds
[i
].revents
= 0;
5427 ret
= do_poll(ufds
, count
, timeout
);
5429 for (i
= 0; i
< count
; i
++)
5431 if (ufds
[i
].fd
!= -1)
5433 release_sock_fd(wfds
[i
].fd
, ufds
[i
].fd
);
5434 if (ufds
[i
].revents
& POLLHUP
)
5436 /* Check if the socket still exists */
5437 int fd
= get_sock_fd(wfds
[i
].fd
, 0, NULL
);
5440 wfds
[i
].revents
= WS_POLLHUP
;
5441 release_sock_fd(wfds
[i
].fd
, fd
);
5444 wfds
[i
].revents
= WS_POLLNVAL
;
5447 wfds
[i
].revents
= convert_poll_u2w(ufds
[i
].revents
);
5450 wfds
[i
].revents
= WS_POLLNVAL
;
5453 HeapFree(GetProcessHeap(), 0, ufds
);
5457 /* helper to send completion messages for client-only i/o operation case */
5458 static void WS_AddCompletion( SOCKET sock
, ULONG_PTR CompletionValue
, NTSTATUS CompletionStatus
,
5461 SERVER_START_REQ( add_fd_completion
)
5463 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(sock
) );
5464 req
->cvalue
= CompletionValue
;
5465 req
->status
= CompletionStatus
;
5466 req
->information
= Information
;
5467 wine_server_call( req
);
5473 /***********************************************************************
5476 int WINAPI
WS_send(SOCKET s
, const char *buf
, int len
, int flags
)
5482 wsabuf
.buf
= (char*) buf
;
5484 if ( WS2_sendto( s
, &wsabuf
, 1, &n
, flags
, NULL
, 0, NULL
, NULL
) == SOCKET_ERROR
)
5485 return SOCKET_ERROR
;
5490 /***********************************************************************
5491 * WSASend (WS2_32.72)
5493 INT WINAPI
WSASend( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
5494 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
5495 LPWSAOVERLAPPED lpOverlapped
,
5496 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
5498 return WS2_sendto( s
, lpBuffers
, dwBufferCount
, lpNumberOfBytesSent
, dwFlags
,
5499 NULL
, 0, lpOverlapped
, lpCompletionRoutine
);
5502 /***********************************************************************
5503 * WSASendDisconnect (WS2_32.73)
5505 INT WINAPI
WSASendDisconnect( SOCKET s
, LPWSABUF lpBuffers
)
5507 return WS_shutdown( s
, SD_SEND
);
5511 static int WS2_sendto( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
5512 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
5513 const struct WS_sockaddr
*to
, int tolen
,
5514 LPWSAOVERLAPPED lpOverlapped
,
5515 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
5517 unsigned int i
, options
;
5518 int n
, fd
, err
, overlapped
, flags
;
5519 struct ws2_async
*wsa
= NULL
, localwsa
;
5520 int totalLength
= 0;
5524 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
5525 s
, lpBuffers
, dwBufferCount
, dwFlags
,
5526 to
, tolen
, lpOverlapped
, lpCompletionRoutine
);
5528 fd
= get_sock_fd( s
, FILE_WRITE_DATA
, &options
);
5529 TRACE( "fd=%d, options=%x\n", fd
, options
);
5531 if ( fd
== -1 ) return SOCKET_ERROR
;
5533 if (!lpOverlapped
&& !lpNumberOfBytesSent
)
5539 overlapped
= (lpOverlapped
|| lpCompletionRoutine
) &&
5540 !(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
));
5541 if (overlapped
|| dwBufferCount
> 1)
5543 if (!(wsa
= (struct ws2_async
*)alloc_async_io( offsetof(struct ws2_async
, iovec
[dwBufferCount
]),
5553 wsa
->hSocket
= SOCKET2HANDLE(s
);
5554 wsa
->addr
= (struct WS_sockaddr
*)to
;
5555 wsa
->addrlen
.val
= tolen
;
5556 wsa
->flags
= dwFlags
;
5557 wsa
->lpFlags
= &wsa
->flags
;
5558 wsa
->control
= NULL
;
5559 wsa
->n_iovecs
= dwBufferCount
;
5560 wsa
->first_iovec
= 0;
5561 for ( i
= 0; i
< dwBufferCount
; i
++ )
5563 wsa
->iovec
[i
].iov_base
= lpBuffers
[i
].buf
;
5564 wsa
->iovec
[i
].iov_len
= lpBuffers
[i
].len
;
5565 totalLength
+= lpBuffers
[i
].len
;
5568 flags
= convert_flags(dwFlags
);
5569 n
= WS2_send( fd
, wsa
, flags
);
5570 if (n
== -1 && errno
!= EAGAIN
)
5578 IO_STATUS_BLOCK
*iosb
= lpOverlapped
? (IO_STATUS_BLOCK
*)lpOverlapped
: &wsa
->local_iosb
;
5579 ULONG_PTR cvalue
= (lpOverlapped
&& ((ULONG_PTR
)lpOverlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)lpOverlapped
: 0;
5581 wsa
->user_overlapped
= lpOverlapped
;
5582 wsa
->completion_func
= lpCompletionRoutine
;
5583 release_sock_fd( s
, fd
);
5585 if (n
== -1 || n
< totalLength
)
5587 iosb
->u
.Status
= STATUS_PENDING
;
5588 iosb
->Information
= n
== -1 ? 0 : n
;
5590 if (wsa
->completion_func
)
5591 err
= register_async( ASYNC_TYPE_WRITE
, wsa
->hSocket
, &wsa
->io
, NULL
,
5592 ws2_async_apc
, wsa
, iosb
);
5594 err
= register_async( ASYNC_TYPE_WRITE
, wsa
->hSocket
, &wsa
->io
, lpOverlapped
->hEvent
,
5595 NULL
, (void *)cvalue
, iosb
);
5597 /* Enable the event only after starting the async. The server will deliver it as soon as
5598 the async is done. */
5599 _enable_event(SOCKET2HANDLE(s
), FD_WRITE
, 0, 0);
5601 if (err
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
5602 SetLastError(NtStatusToWSAError( err
));
5603 return SOCKET_ERROR
;
5606 iosb
->u
.Status
= STATUS_SUCCESS
;
5607 iosb
->Information
= n
;
5608 if (lpNumberOfBytesSent
) *lpNumberOfBytesSent
= n
;
5609 if (!wsa
->completion_func
)
5611 if (cvalue
) WS_AddCompletion( s
, cvalue
, STATUS_SUCCESS
, n
);
5612 if (lpOverlapped
->hEvent
) SetEvent( lpOverlapped
->hEvent
);
5613 HeapFree( GetProcessHeap(), 0, wsa
);
5615 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC
)ws2_async_apc
,
5616 (ULONG_PTR
)wsa
, (ULONG_PTR
)iosb
, 0 );
5617 SetLastError(ERROR_SUCCESS
);
5621 if ((err
= _is_blocking( s
, &is_blocking
)))
5623 err
= NtStatusToWSAError( err
);
5629 /* On a blocking non-overlapped stream socket,
5630 * sending blocks until the entire buffer is sent. */
5631 DWORD timeout_start
= GetTickCount();
5633 bytes_sent
= n
== -1 ? 0 : n
;
5635 while (wsa
->first_iovec
< wsa
->n_iovecs
)
5638 int poll_timeout
= -1;
5639 INT64 timeout
= get_rcvsnd_timeo(fd
, FALSE
);
5643 timeout
-= GetTickCount() - timeout_start
;
5644 if (timeout
< 0) poll_timeout
= 0;
5645 else poll_timeout
= timeout
<= INT_MAX
? timeout
: INT_MAX
;
5649 pfd
.events
= POLLOUT
;
5651 if (!poll_timeout
|| !poll( &pfd
, 1, poll_timeout
))
5654 goto error
; /* msdn says a timeout in send is fatal */
5657 n
= WS2_send( fd
, wsa
, flags
);
5658 if (n
== -1 && errno
!= EAGAIN
)
5668 else /* non-blocking */
5670 if (n
< totalLength
)
5671 _enable_event(SOCKET2HANDLE(s
), FD_WRITE
, 0, 0);
5674 err
= WSAEWOULDBLOCK
;
5680 TRACE(" -> %i bytes\n", bytes_sent
);
5682 if (lpNumberOfBytesSent
) *lpNumberOfBytesSent
= bytes_sent
;
5683 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
5684 release_sock_fd( s
, fd
);
5685 SetLastError(ERROR_SUCCESS
);
5689 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
5690 release_sock_fd( s
, fd
);
5691 WARN(" -> ERROR %d\n", err
);
5693 return SOCKET_ERROR
;
5696 /***********************************************************************
5697 * WSASendTo (WS2_32.74)
5699 INT WINAPI
WSASendTo( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
5700 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
5701 const struct WS_sockaddr
*to
, int tolen
,
5702 LPWSAOVERLAPPED lpOverlapped
,
5703 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
5705 return WS2_sendto( s
, lpBuffers
, dwBufferCount
,
5706 lpNumberOfBytesSent
, dwFlags
,
5708 lpOverlapped
, lpCompletionRoutine
);
5711 /***********************************************************************
5712 * sendto (WS2_32.20)
5714 int WINAPI
WS_sendto(SOCKET s
, const char *buf
, int len
, int flags
,
5715 const struct WS_sockaddr
*to
, int tolen
)
5721 wsabuf
.buf
= (char*) buf
;
5723 if ( WS2_sendto(s
, &wsabuf
, 1, &n
, flags
, to
, tolen
, NULL
, NULL
) == SOCKET_ERROR
)
5724 return SOCKET_ERROR
;
5729 /***********************************************************************
5730 * setsockopt (WS2_32.21)
5732 int WINAPI
WS_setsockopt(SOCKET s
, int level
, int optname
,
5733 const char *optval
, int optlen
)
5737 struct linger linger
;
5738 struct timeval tval
;
5740 TRACE("(socket %04lx, %s, optval %s, optlen %d)\n", s
,
5741 debugstr_sockopt(level
, optname
), debugstr_optval(optval
, optlen
),
5744 /* some broken apps pass the value directly instead of a pointer to it */
5745 if(optlen
&& IS_INTRESOURCE(optval
))
5747 SetLastError(WSAEFAULT
);
5748 return SOCKET_ERROR
;
5756 /* Some options need some conversion before they can be sent to
5757 * setsockopt. The conversions are done here, then they will fall through
5758 * to the general case. Special options that are not passed to
5759 * setsockopt follow below that.*/
5761 case WS_SO_DONTLINGER
:
5764 SetLastError(WSAEFAULT
);
5765 return SOCKET_ERROR
;
5767 linger
.l_onoff
= *(const int*)optval
== 0;
5768 linger
.l_linger
= 0;
5770 optname
= SO_LINGER
;
5771 optval
= (char*)&linger
;
5772 optlen
= sizeof(struct linger
);
5778 SetLastError(WSAEFAULT
);
5779 return SOCKET_ERROR
;
5781 linger
.l_onoff
= ((LINGER
*)optval
)->l_onoff
;
5782 linger
.l_linger
= ((LINGER
*)optval
)->l_linger
;
5784 optname
= SO_LINGER
;
5785 optval
= (char*)&linger
;
5786 optlen
= sizeof(struct linger
);
5790 if (*(const int*)optval
< 2048)
5792 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval
);
5797 /* The options listed here don't need any special handling. Thanks to
5798 * the conversion happening above, options from there will fall through
5800 case WS_SO_ACCEPTCONN
:
5801 case WS_SO_BROADCAST
:
5803 case WS_SO_KEEPALIVE
:
5804 case WS_SO_OOBINLINE
:
5805 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
5806 * however, using it the BSD way fixes bug 8513 and seems to be what
5807 * most programmers assume, anyway */
5808 case WS_SO_REUSEADDR
:
5811 convert_sockopt(&level
, &optname
);
5814 /* SO_DEBUG is a privileged operation, ignore it. */
5816 TRACE("Ignoring SO_DEBUG\n");
5819 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
5820 * socket. According to MSDN, this option is silently ignored.*/
5821 case WS_SO_DONTROUTE
:
5822 TRACE("Ignoring SO_DONTROUTE\n");
5825 /* Stops two sockets from being bound to the same port. Always happens
5826 * on unix systems, so just drop it. */
5827 case WS_SO_EXCLUSIVEADDRUSE
:
5828 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
5831 /* After a ConnectEx call succeeds, the socket can't be used with half of the
5832 * normal winsock functions on windows. We don't have that problem. */
5833 case WS_SO_UPDATE_CONNECT_CONTEXT
:
5834 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
5837 /* After a AcceptEx call succeeds, the socket can't be used with half of the
5838 * normal winsock functions on windows. We don't have that problem. */
5839 case WS_SO_UPDATE_ACCEPT_CONTEXT
:
5840 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
5843 /* SO_OPENTYPE does not require a valid socket handle. */
5844 case WS_SO_OPENTYPE
:
5845 if (!optlen
|| optlen
< sizeof(int) || !optval
)
5847 SetLastError(WSAEFAULT
);
5848 return SOCKET_ERROR
;
5850 get_per_thread_data()->opentype
= *(const int *)optval
;
5851 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval
) );
5855 case WS_SO_RCVTIMEO
:
5858 case WS_SO_SNDTIMEO
:
5860 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
5861 if (optval
&& optlen
== sizeof(UINT32
)) {
5862 /* WinSock passes milliseconds instead of struct timeval */
5863 tval
.tv_usec
= (*(const UINT32
*)optval
% 1000) * 1000;
5864 tval
.tv_sec
= *(const UINT32
*)optval
/ 1000;
5865 /* min of 500 milliseconds */
5866 if (tval
.tv_sec
== 0 && tval
.tv_usec
&& tval
.tv_usec
< 500000)
5867 tval
.tv_usec
= 500000;
5868 optlen
= sizeof(struct timeval
);
5869 optval
= (char*)&tval
;
5870 } else if (optlen
== sizeof(struct timeval
)) {
5871 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen
);
5873 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen
);
5876 convert_sockopt(&level
, &optname
);
5881 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname
);
5882 SetLastError(WSAENOPROTOOPT
);
5883 return SOCKET_ERROR
;
5885 break; /* case WS_SOL_SOCKET */
5888 case WS_NSPROTO_IPX
:
5892 return set_ipx_packettype(s
, *(int*)optval
);
5894 case WS_IPX_FILTERPTYPE
:
5895 /* Sets the receive filter packet type, at the moment we don't support it */
5896 FIXME("IPX_FILTERPTYPE: %x\n", *optval
);
5897 /* Returning 0 is better for now than returning a SOCKET_ERROR */
5901 FIXME("opt_name:%x\n", optname
);
5902 return SOCKET_ERROR
;
5904 break; /* case WS_NSPROTO_IPX */
5907 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
5908 case WS_IPPROTO_TCP
:
5911 case WS_TCP_NODELAY
:
5912 convert_sockopt(&level
, &optname
);
5915 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname
);
5916 return SOCKET_ERROR
;
5923 case WS_IP_ADD_MEMBERSHIP
:
5924 case WS_IP_DROP_MEMBERSHIP
:
5928 case WS_IP_MULTICAST_IF
:
5929 case WS_IP_MULTICAST_LOOP
:
5930 case WS_IP_MULTICAST_TTL
:
5937 #ifdef IP_UNICAST_IF
5938 case WS_IP_UNICAST_IF
:
5940 convert_sockopt(&level
, &optname
);
5942 case WS_IP_DONTFRAGMENT
:
5943 return set_dont_fragment(s
, IPPROTO_IP
, *(BOOL
*)optval
) ? 0 : SOCKET_ERROR
;
5945 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname
);
5946 return SOCKET_ERROR
;
5950 case WS_IPPROTO_IPV6
:
5953 #ifdef IPV6_ADD_MEMBERSHIP
5954 case WS_IPV6_ADD_MEMBERSHIP
:
5956 #ifdef IPV6_DROP_MEMBERSHIP
5957 case WS_IPV6_DROP_MEMBERSHIP
:
5959 case WS_IPV6_MULTICAST_IF
:
5960 case WS_IPV6_MULTICAST_HOPS
:
5961 case WS_IPV6_MULTICAST_LOOP
:
5962 case WS_IPV6_UNICAST_HOPS
:
5963 #ifdef IPV6_UNICAST_IF
5964 case WS_IPV6_UNICAST_IF
:
5966 convert_sockopt(&level
, &optname
);
5968 case WS_IPV6_DONTFRAG
:
5969 return set_dont_fragment(s
, IPPROTO_IPV6
, *(BOOL
*)optval
) ? 0 : SOCKET_ERROR
;
5970 case WS_IPV6_PROTECTION_LEVEL
:
5971 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
5973 case WS_IPV6_V6ONLY
:
5975 union generic_unix_sockaddr uaddr
;
5979 fd
= get_sock_fd( s
, 0, NULL
);
5980 if (fd
== -1) return SOCKET_ERROR
;
5982 bound
= is_fd_bound(fd
, &uaddr
, &uaddrlen
);
5983 release_sock_fd( s
, fd
);
5984 if (bound
== 0 && uaddr
.addr
.sa_family
== AF_INET
)
5986 /* Changing IPV6_V6ONLY succeeds on AF_INET (IPv4) socket
5987 * on Windows (with IPv6 support) if the socket is unbound.
5988 * It is essentially a noop, though Windows does store the value
5990 WARN("Silently ignoring IPPROTO_IPV6+IPV6_V6ONLY on AF_INET socket\n");
5993 level
= IPPROTO_IPV6
;
5994 optname
= IPV6_V6ONLY
;
5998 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname
);
5999 return SOCKET_ERROR
;
6004 WARN("Unknown level: 0x%08x\n", level
);
6005 SetLastError(WSAEINVAL
);
6006 return SOCKET_ERROR
;
6007 } /* end switch(level) */
6009 /* avoid endianness issues if argument is a 16-bit int */
6010 if (optval
&& optlen
< sizeof(int))
6012 woptval
= *((const INT16
*) optval
);
6013 optval
= (char*) &woptval
;
6014 woptval
&= (1 << optlen
* 8) - 1;
6017 fd
= get_sock_fd( s
, 0, NULL
);
6018 if (fd
== -1) return SOCKET_ERROR
;
6020 if (setsockopt(fd
, level
, optname
, optval
, optlen
) == 0)
6023 if (level
== SOL_SOCKET
&& optname
== SO_REUSEADDR
&&
6024 setsockopt(fd
, level
, SO_REUSEPORT
, optval
, optlen
) != 0)
6026 SetLastError(wsaErrno());
6027 release_sock_fd( s
, fd
);
6028 return SOCKET_ERROR
;
6031 release_sock_fd( s
, fd
);
6034 TRACE("Setting socket error, %d\n", wsaErrno());
6035 SetLastError(wsaErrno());
6036 release_sock_fd( s
, fd
);
6038 return SOCKET_ERROR
;
6041 /***********************************************************************
6042 * shutdown (WS2_32.22)
6044 int WINAPI
WS_shutdown(SOCKET s
, int how
)
6046 int fd
, err
= WSAENOTSOCK
;
6047 unsigned int options
= 0, clear_flags
= 0;
6049 fd
= get_sock_fd( s
, 0, &options
);
6050 TRACE("socket %04lx, how 0x%x, options 0x%x\n", s
, how
, options
);
6053 return SOCKET_ERROR
;
6057 case SD_RECEIVE
: /* drop receives */
6058 clear_flags
|= FD_READ
;
6060 case SD_SEND
: /* drop sends */
6061 clear_flags
|= FD_WRITE
;
6063 case SD_BOTH
: /* drop all */
6064 clear_flags
|= FD_READ
|FD_WRITE
;
6067 clear_flags
|= FD_WINE_LISTENING
;
6070 if (!(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
)))
6075 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_READ
);
6078 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_WRITE
);
6082 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_READ
);
6083 if (!err
) err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_WRITE
);
6086 if (err
) goto error
;
6088 else /* non-overlapped mode */
6090 if ( shutdown( fd
, how
) )
6097 release_sock_fd( s
, fd
);
6098 _enable_event( SOCKET2HANDLE(s
), 0, 0, clear_flags
);
6099 if ( how
> 1) WSAAsyncSelect( s
, 0, 0, 0 );
6103 release_sock_fd( s
, fd
);
6104 _enable_event( SOCKET2HANDLE(s
), 0, 0, clear_flags
);
6105 SetLastError( err
);
6106 return SOCKET_ERROR
;
6109 /***********************************************************************
6110 * socket (WS2_32.23)
6112 SOCKET WINAPI
WS_socket(int af
, int type
, int protocol
)
6114 TRACE("af=%d type=%d protocol=%d\n", af
, type
, protocol
);
6116 return WSASocketW( af
, type
, protocol
, NULL
, 0,
6117 get_per_thread_data()->opentype
? 0 : WSA_FLAG_OVERLAPPED
);
6121 /***********************************************************************
6122 * gethostbyaddr (WS2_32.51)
6124 struct WS_hostent
* WINAPI
WS_gethostbyaddr(const char *addr
, int len
, int type
)
6126 struct WS_hostent
*retval
= NULL
;
6127 struct hostent
* host
;
6128 int unixtype
= convert_af_w2u(type
);
6129 const char *paddr
= addr
;
6130 unsigned long loopback
;
6131 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6133 int ebufsize
= 1024;
6134 struct hostent hostentry
;
6135 int locerr
= ENOBUFS
;
6138 /* convert back the magic loopback address if necessary */
6139 if (unixtype
== AF_INET
&& len
== 4 && !memcmp(addr
, magic_loopback_addr
, 4))
6141 loopback
= htonl(INADDR_LOOPBACK
);
6142 paddr
= (char*) &loopback
;
6145 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6147 extrabuf
=HeapAlloc(GetProcessHeap(),0,ebufsize
) ;
6149 int res
= gethostbyaddr_r(paddr
, len
, unixtype
,
6150 &hostentry
, extrabuf
, ebufsize
, &host
, &locerr
);
6151 if (res
!= ERANGE
) break;
6153 extrabuf
=HeapReAlloc(GetProcessHeap(),0,extrabuf
,ebufsize
) ;
6155 if (host
) retval
= WS_dup_he(host
);
6156 else SetLastError((locerr
< 0) ? wsaErrno() : wsaHerrno(locerr
));
6157 HeapFree(GetProcessHeap(),0,extrabuf
);
6159 EnterCriticalSection( &csWSgetXXXbyYYY
);
6160 host
= gethostbyaddr(paddr
, len
, unixtype
);
6161 if (host
) retval
= WS_dup_he(host
);
6162 else SetLastError((h_errno
< 0) ? wsaErrno() : wsaHerrno(h_errno
));
6163 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6165 TRACE("ptr %p, len %d, type %d ret %p\n", addr
, len
, type
, retval
);
6169 /***********************************************************************
6170 * WS_compare_routes_by_metric_asc (INTERNAL)
6172 * Comparison function for qsort(), for sorting two routes (struct route)
6173 * by metric in ascending order.
6175 static int WS_compare_routes_by_metric_asc(const void *left
, const void *right
)
6177 const struct route
*a
= left
, *b
= right
;
6178 if (a
->default_route
&& b
->default_route
)
6179 return a
->default_route
- b
->default_route
;
6180 if (a
->default_route
&& !b
->default_route
)
6182 if (b
->default_route
&& !a
->default_route
)
6184 return a
->metric
- b
->metric
;
6187 /***********************************************************************
6188 * WS_get_local_ips (INTERNAL)
6190 * Returns the list of local IP addresses by going through the network
6191 * adapters and using the local routing table to sort the addresses
6192 * from highest routing priority to lowest routing priority. This
6193 * functionality is inferred from the description for obtaining local
6194 * IP addresses given in the Knowledge Base Article Q160215.
6196 * Please note that the returned hostent is only freed when the thread
6197 * closes and is replaced if another hostent is requested.
6199 static struct WS_hostent
* WS_get_local_ips( char *hostname
)
6201 int numroutes
= 0, i
, j
, default_routes
= 0;
6203 PIP_ADAPTER_INFO adapters
= NULL
, k
;
6204 struct WS_hostent
*hostlist
= NULL
;
6205 PMIB_IPFORWARDTABLE routes
= NULL
;
6206 struct route
*route_addrs
= NULL
;
6207 DWORD adap_size
, route_size
;
6209 /* Obtain the size of the adapter list and routing table, also allocate memory */
6210 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
6212 if (GetIpForwardTable(NULL
, &route_size
, FALSE
) != ERROR_INSUFFICIENT_BUFFER
)
6214 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
6215 routes
= HeapAlloc(GetProcessHeap(), 0, route_size
);
6216 route_addrs
= HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
6217 if (adapters
== NULL
|| routes
== NULL
|| route_addrs
== NULL
)
6219 /* Obtain the adapter list and the full routing table */
6220 if (GetAdaptersInfo(adapters
, &adap_size
) != NO_ERROR
)
6222 if (GetIpForwardTable(routes
, &route_size
, FALSE
) != NO_ERROR
)
6224 /* Store the interface associated with each route */
6225 for (n
= 0; n
< routes
->dwNumEntries
; n
++)
6228 DWORD ifmetric
, ifdefault
= 0;
6229 BOOL exists
= FALSE
;
6231 /* Check if this is a default route (there may be more than one) */
6232 if (!routes
->table
[n
].dwForwardDest
)
6233 ifdefault
= ++default_routes
;
6234 else if (routes
->table
[n
].u1
.ForwardType
!= MIB_IPROUTE_TYPE_DIRECT
)
6236 ifindex
= routes
->table
[n
].dwForwardIfIndex
;
6237 ifmetric
= routes
->table
[n
].dwForwardMetric1
;
6238 /* Only store the lowest valued metric for an interface */
6239 for (j
= 0; j
< numroutes
; j
++)
6241 if (route_addrs
[j
].interface
== ifindex
)
6243 if (route_addrs
[j
].metric
> ifmetric
)
6244 route_addrs
[j
].metric
= ifmetric
;
6250 route_addrs
= HeapReAlloc(GetProcessHeap(), 0, route_addrs
, (numroutes
+1)*sizeof(struct route
));
6251 if (route_addrs
== NULL
)
6252 goto cleanup
; /* Memory allocation error, fail gracefully */
6253 route_addrs
[numroutes
].interface
= ifindex
;
6254 route_addrs
[numroutes
].metric
= ifmetric
;
6255 route_addrs
[numroutes
].default_route
= ifdefault
;
6256 /* If no IP is found in the next step (for whatever reason)
6257 * then fall back to the magic loopback address.
6259 memcpy(&(route_addrs
[numroutes
].addr
.s_addr
), magic_loopback_addr
, 4);
6263 goto cleanup
; /* No routes, fall back to the Magic IP */
6264 /* Find the IP address associated with each found interface */
6265 for (i
= 0; i
< numroutes
; i
++)
6267 for (k
= adapters
; k
!= NULL
; k
= k
->Next
)
6269 char *ip
= k
->IpAddressList
.IpAddress
.String
;
6271 if (route_addrs
[i
].interface
== k
->Index
)
6272 route_addrs
[i
].addr
.s_addr
= (in_addr_t
) inet_addr(ip
);
6275 /* Allocate a hostent and enough memory for all the IPs,
6276 * including the NULL at the end of the list.
6278 hostlist
= WS_create_he(hostname
, 1, 0, numroutes
+1, sizeof(struct in_addr
));
6279 if (hostlist
== NULL
)
6280 goto cleanup
; /* Failed to allocate a hostent for the list of IPs */
6281 hostlist
->h_addr_list
[numroutes
] = NULL
; /* NULL-terminate the address list */
6282 hostlist
->h_aliases
[0] = NULL
; /* NULL-terminate the alias list */
6283 hostlist
->h_addrtype
= AF_INET
;
6284 hostlist
->h_length
= sizeof(struct in_addr
); /* = 4 */
6285 /* Reorder the entries before placing them in the host list. Windows expects
6286 * the IP list in order from highest priority to lowest (the critical thing
6287 * is that most applications expect the first IP to be the default route).
6290 qsort(route_addrs
, numroutes
, sizeof(struct route
), WS_compare_routes_by_metric_asc
);
6292 for (i
= 0; i
< numroutes
; i
++)
6293 (*(struct in_addr
*) hostlist
->h_addr_list
[i
]) = route_addrs
[i
].addr
;
6295 /* Cleanup all allocated memory except the address list,
6296 * the address list is used by the calling app.
6299 HeapFree(GetProcessHeap(), 0, route_addrs
);
6300 HeapFree(GetProcessHeap(), 0, adapters
);
6301 HeapFree(GetProcessHeap(), 0, routes
);
6305 /***********************************************************************
6306 * gethostbyname (WS2_32.52)
6308 struct WS_hostent
* WINAPI
WS_gethostbyname(const char* name
)
6310 struct WS_hostent
*retval
= NULL
;
6311 struct hostent
* host
;
6312 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6315 struct hostent hostentry
;
6316 int locerr
= ENOBUFS
;
6320 SetLastError(WSANOTINITIALISED
);
6323 if( gethostname( hostname
, 100) == -1) {
6324 SetLastError(WSAENOBUFS
); /* appropriate ? */
6327 if( !name
|| !name
[0]) {
6330 /* If the hostname of the local machine is requested then return the
6331 * complete list of local IP addresses */
6332 if(strcmp(name
, hostname
) == 0)
6333 retval
= WS_get_local_ips(hostname
);
6334 /* If any other hostname was requested (or the routing table lookup failed)
6335 * then return the IP found by the host OS */
6338 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6340 extrabuf
=HeapAlloc(GetProcessHeap(),0,ebufsize
) ;
6342 int res
= gethostbyname_r(name
, &hostentry
, extrabuf
, ebufsize
, &host
, &locerr
);
6343 if( res
!= ERANGE
) break;
6345 extrabuf
=HeapReAlloc(GetProcessHeap(),0,extrabuf
,ebufsize
) ;
6347 if (!host
) SetLastError((locerr
< 0) ? wsaErrno() : wsaHerrno(locerr
));
6349 EnterCriticalSection( &csWSgetXXXbyYYY
);
6350 host
= gethostbyname(name
);
6351 if (!host
) SetLastError((h_errno
< 0) ? wsaErrno() : wsaHerrno(h_errno
));
6353 if (host
) retval
= WS_dup_he(host
);
6354 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6355 HeapFree(GetProcessHeap(),0,extrabuf
);
6357 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6360 if (retval
&& retval
->h_addr_list
[0][0] == 127 &&
6361 strcmp(name
, "localhost") != 0)
6363 /* hostname != "localhost" but has loopback address. replace by our
6364 * special address.*/
6365 memcpy(retval
->h_addr_list
[0], magic_loopback_addr
, 4);
6367 TRACE( "%s ret %p\n", debugstr_a(name
), retval
);
6372 /***********************************************************************
6373 * getprotobyname (WS2_32.53)
6375 struct WS_protoent
* WINAPI
WS_getprotobyname(const char* name
)
6377 struct WS_protoent
* retval
= NULL
;
6378 #ifdef HAVE_GETPROTOBYNAME
6379 struct protoent
* proto
;
6380 EnterCriticalSection( &csWSgetXXXbyYYY
);
6381 if( (proto
= getprotobyname(name
)) != NULL
)
6383 retval
= WS_dup_pe(proto
);
6386 MESSAGE("protocol %s not found; You might want to add "
6387 "this to /etc/protocols\n", debugstr_a(name
) );
6388 SetLastError(WSANO_DATA
);
6390 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6392 TRACE( "%s ret %p\n", debugstr_a(name
), retval
);
6397 /***********************************************************************
6398 * getprotobynumber (WS2_32.54)
6400 struct WS_protoent
* WINAPI
WS_getprotobynumber(int number
)
6402 struct WS_protoent
* retval
= NULL
;
6403 #ifdef HAVE_GETPROTOBYNUMBER
6404 struct protoent
* proto
;
6405 EnterCriticalSection( &csWSgetXXXbyYYY
);
6406 if( (proto
= getprotobynumber(number
)) != NULL
)
6408 retval
= WS_dup_pe(proto
);
6411 MESSAGE("protocol number %d not found; You might want to add "
6412 "this to /etc/protocols\n", number
);
6413 SetLastError(WSANO_DATA
);
6415 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6417 TRACE("%i ret %p\n", number
, retval
);
6422 /***********************************************************************
6423 * getservbyname (WS2_32.55)
6425 struct WS_servent
* WINAPI
WS_getservbyname(const char *name
, const char *proto
)
6427 struct WS_servent
* retval
= NULL
;
6428 struct servent
* serv
;
6430 char *proto_str
= NULL
;
6432 if (!(name_str
= strdup_lower(name
))) return NULL
;
6434 if (proto
&& *proto
)
6436 if (!(proto_str
= strdup_lower(proto
)))
6438 HeapFree( GetProcessHeap(), 0, name_str
);
6443 EnterCriticalSection( &csWSgetXXXbyYYY
);
6444 serv
= getservbyname(name_str
, proto_str
);
6447 retval
= WS_dup_se(serv
);
6449 else SetLastError(WSANO_DATA
);
6450 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6451 HeapFree( GetProcessHeap(), 0, proto_str
);
6452 HeapFree( GetProcessHeap(), 0, name_str
);
6453 TRACE( "%s, %s ret %p\n", debugstr_a(name
), debugstr_a(proto
), retval
);
6457 /***********************************************************************
6458 * freeaddrinfo (WS2_32.@)
6460 void WINAPI
WS_freeaddrinfo(struct WS_addrinfo
*res
)
6463 struct WS_addrinfo
*next
;
6465 HeapFree(GetProcessHeap(),0,res
->ai_canonname
);
6466 HeapFree(GetProcessHeap(),0,res
->ai_addr
);
6467 next
= res
->ai_next
;
6468 HeapFree(GetProcessHeap(),0,res
);
6473 /* helper functions for getaddrinfo()/getnameinfo() */
6474 static int convert_aiflag_w2u(int winflags
) {
6478 for (i
=0;i
<sizeof(ws_aiflag_map
)/sizeof(ws_aiflag_map
[0]);i
++)
6479 if (ws_aiflag_map
[i
][0] & winflags
) {
6480 unixflags
|= ws_aiflag_map
[i
][1];
6481 winflags
&= ~ws_aiflag_map
[i
][0];
6484 FIXME("Unhandled windows AI_xxx flags 0x%x\n", winflags
);
6488 static int convert_niflag_w2u(int winflags
) {
6492 for (i
=0;i
<sizeof(ws_niflag_map
)/sizeof(ws_niflag_map
[0]);i
++)
6493 if (ws_niflag_map
[i
][0] & winflags
) {
6494 unixflags
|= ws_niflag_map
[i
][1];
6495 winflags
&= ~ws_niflag_map
[i
][0];
6498 FIXME("Unhandled windows NI_xxx flags 0x%x\n", winflags
);
6502 static int convert_aiflag_u2w(int unixflags
) {
6506 for (i
=0;i
<sizeof(ws_aiflag_map
)/sizeof(ws_aiflag_map
[0]);i
++)
6507 if (ws_aiflag_map
[i
][1] & unixflags
) {
6508 winflags
|= ws_aiflag_map
[i
][0];
6509 unixflags
&= ~ws_aiflag_map
[i
][1];
6512 WARN("Unhandled UNIX AI_xxx flags 0x%x\n", unixflags
);
6516 static int convert_eai_u2w(int unixret
) {
6519 if (!unixret
) return 0;
6521 for (i
=0;ws_eai_map
[i
][0];i
++)
6522 if (ws_eai_map
[i
][1] == unixret
)
6523 return ws_eai_map
[i
][0];
6525 if (unixret
== EAI_SYSTEM
)
6526 /* There are broken versions of glibc which return EAI_SYSTEM
6527 * and set errno to 0 instead of returning EAI_NONAME.
6529 return errno
? sock_get_error( errno
) : WS_EAI_NONAME
;
6531 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret
);
6535 static char *get_hostname(void)
6540 GetComputerNameExA( ComputerNamePhysicalDnsHostname
, NULL
, &size
);
6541 if (GetLastError() != ERROR_MORE_DATA
) return NULL
;
6542 if (!(ret
= HeapAlloc( GetProcessHeap(), 0, size
))) return NULL
;
6543 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname
, ret
, &size
))
6545 HeapFree( GetProcessHeap(), 0, ret
);
6551 /***********************************************************************
6552 * getaddrinfo (WS2_32.@)
6554 int WINAPI
WS_getaddrinfo(LPCSTR nodename
, LPCSTR servname
, const struct WS_addrinfo
*hints
, struct WS_addrinfo
**res
)
6556 #ifdef HAVE_GETADDRINFO
6557 struct addrinfo
*unixaires
= NULL
;
6559 struct addrinfo unixhints
, *punixhints
= NULL
;
6564 if (!nodename
&& !servname
)
6566 SetLastError(WSAHOST_NOT_FOUND
);
6567 return WSAHOST_NOT_FOUND
;
6570 hostname
= get_hostname();
6571 if (!hostname
) return WSA_NOT_ENOUGH_MEMORY
;
6575 else if (!nodename
[0])
6580 /* servname tweak required by OSX and BSD kernels */
6581 if (servname
&& !servname
[0]) servname
= "0";
6584 punixhints
= &unixhints
;
6586 memset(&unixhints
, 0, sizeof(unixhints
));
6587 punixhints
->ai_flags
= convert_aiflag_w2u(hints
->ai_flags
);
6589 /* zero is a wildcard, no need to convert */
6590 if (hints
->ai_family
)
6591 punixhints
->ai_family
= convert_af_w2u(hints
->ai_family
);
6592 if (hints
->ai_socktype
)
6593 punixhints
->ai_socktype
= convert_socktype_w2u(hints
->ai_socktype
);
6594 if (hints
->ai_protocol
)
6595 punixhints
->ai_protocol
= max(convert_proto_w2u(hints
->ai_protocol
), 0);
6597 if (punixhints
->ai_socktype
< 0)
6599 SetLastError(WSAESOCKTNOSUPPORT
);
6600 HeapFree(GetProcessHeap(), 0, hostname
);
6601 return SOCKET_ERROR
;
6604 /* windows allows invalid combinations of socket type and protocol, unix does not.
6605 * fix the parameters here to make getaddrinfo call always work */
6606 if (punixhints
->ai_protocol
== IPPROTO_TCP
&&
6607 punixhints
->ai_socktype
!= SOCK_STREAM
&& punixhints
->ai_socktype
!= SOCK_SEQPACKET
)
6608 punixhints
->ai_socktype
= 0;
6610 else if (punixhints
->ai_protocol
== IPPROTO_UDP
&& punixhints
->ai_socktype
!= SOCK_DGRAM
)
6611 punixhints
->ai_socktype
= 0;
6613 else if (IS_IPX_PROTO(punixhints
->ai_protocol
) && punixhints
->ai_socktype
!= SOCK_DGRAM
)
6614 punixhints
->ai_socktype
= 0;
6616 else if (punixhints
->ai_protocol
== IPPROTO_IPV6
)
6617 punixhints
->ai_protocol
= 0;
6620 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
6621 result
= getaddrinfo(node
, servname
, punixhints
, &unixaires
);
6623 if (result
&& !strcmp(hostname
, node
))
6625 /* If it didn't work it means the host name IP is not in /etc/hosts, try again
6626 * by sending a NULL host and avoid sending a NULL servname too because that
6628 ERR_(winediag
)("Failed to resolve your host name IP\n");
6629 result
= getaddrinfo(NULL
, servname
? servname
: "0", punixhints
, &unixaires
);
6631 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename
), debugstr_a(servname
), hints
, res
, result
);
6632 HeapFree(GetProcessHeap(), 0, hostname
);
6635 struct addrinfo
*xuai
= unixaires
;
6636 struct WS_addrinfo
**xai
= res
;
6640 struct WS_addrinfo
*ai
= HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY
, sizeof(struct WS_addrinfo
));
6646 *xai
= ai
;xai
= &ai
->ai_next
;
6647 ai
->ai_flags
= convert_aiflag_u2w(xuai
->ai_flags
);
6648 ai
->ai_family
= convert_af_u2w(xuai
->ai_family
);
6649 /* copy whatever was sent in the hints */
6651 ai
->ai_socktype
= hints
->ai_socktype
;
6652 ai
->ai_protocol
= hints
->ai_protocol
;
6654 ai
->ai_socktype
= convert_socktype_u2w(xuai
->ai_socktype
);
6655 ai
->ai_protocol
= convert_proto_u2w(xuai
->ai_protocol
);
6657 if (xuai
->ai_canonname
) {
6658 TRACE("canon name - %s\n",debugstr_a(xuai
->ai_canonname
));
6659 ai
->ai_canonname
= HeapAlloc(GetProcessHeap(),0,strlen(xuai
->ai_canonname
)+1);
6660 if (!ai
->ai_canonname
)
6662 strcpy(ai
->ai_canonname
,xuai
->ai_canonname
);
6664 len
= xuai
->ai_addrlen
;
6665 ai
->ai_addr
= HeapAlloc(GetProcessHeap(),0,len
);
6668 ai
->ai_addrlen
= len
;
6670 int winlen
= ai
->ai_addrlen
;
6672 if (!ws_sockaddr_u2ws(xuai
->ai_addr
, ai
->ai_addr
, &winlen
)) {
6673 ai
->ai_addrlen
= winlen
;
6677 ai
->ai_addr
= HeapReAlloc(GetProcessHeap(),0,ai
->ai_addr
,len
);
6680 ai
->ai_addrlen
= len
;
6682 xuai
= xuai
->ai_next
;
6684 freeaddrinfo(unixaires
);
6686 if (TRACE_ON(winsock
))
6688 struct WS_addrinfo
*ai
= *res
;
6691 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
6692 ai
, ai
->ai_flags
, ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
, ai
->ai_addrlen
,
6693 ai
->ai_canonname
, debugstr_sockaddr(ai
->ai_addr
));
6698 result
= convert_eai_u2w(result
);
6700 SetLastError(result
);
6704 if (*res
) WS_freeaddrinfo(*res
);
6705 if (unixaires
) freeaddrinfo(unixaires
);
6706 return WSA_NOT_ENOUGH_MEMORY
;
6708 FIXME("getaddrinfo() failed, not found during buildtime.\n");
6713 static struct WS_addrinfoW
*addrinfo_AtoW(const struct WS_addrinfo
*ai
)
6715 struct WS_addrinfoW
*ret
;
6717 if (!(ret
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW
)))) return NULL
;
6718 ret
->ai_flags
= ai
->ai_flags
;
6719 ret
->ai_family
= ai
->ai_family
;
6720 ret
->ai_socktype
= ai
->ai_socktype
;
6721 ret
->ai_protocol
= ai
->ai_protocol
;
6722 ret
->ai_addrlen
= ai
->ai_addrlen
;
6723 ret
->ai_canonname
= NULL
;
6724 ret
->ai_addr
= NULL
;
6725 ret
->ai_next
= NULL
;
6726 if (ai
->ai_canonname
)
6728 int len
= MultiByteToWideChar(CP_ACP
, 0, ai
->ai_canonname
, -1, NULL
, 0);
6729 if (!(ret
->ai_canonname
= HeapAlloc(GetProcessHeap(), 0, len
*sizeof(WCHAR
))))
6731 HeapFree(GetProcessHeap(), 0, ret
);
6734 MultiByteToWideChar(CP_ACP
, 0, ai
->ai_canonname
, -1, ret
->ai_canonname
, len
);
6738 if (!(ret
->ai_addr
= HeapAlloc(GetProcessHeap(), 0, ai
->ai_addrlen
)))
6740 HeapFree(GetProcessHeap(), 0, ret
->ai_canonname
);
6741 HeapFree(GetProcessHeap(), 0, ret
);
6744 memcpy(ret
->ai_addr
, ai
->ai_addr
, ai
->ai_addrlen
);
6749 static struct WS_addrinfoW
*addrinfo_list_AtoW(const struct WS_addrinfo
*info
)
6751 struct WS_addrinfoW
*ret
, *infoW
;
6753 if (!(ret
= infoW
= addrinfo_AtoW(info
))) return NULL
;
6754 while (info
->ai_next
)
6756 if (!(infoW
->ai_next
= addrinfo_AtoW(info
->ai_next
)))
6761 infoW
= infoW
->ai_next
;
6762 info
= info
->ai_next
;
6767 static struct WS_addrinfo
*addrinfo_WtoA(const struct WS_addrinfoW
*ai
)
6769 struct WS_addrinfo
*ret
;
6771 if (!(ret
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo
)))) return NULL
;
6772 ret
->ai_flags
= ai
->ai_flags
;
6773 ret
->ai_family
= ai
->ai_family
;
6774 ret
->ai_socktype
= ai
->ai_socktype
;
6775 ret
->ai_protocol
= ai
->ai_protocol
;
6776 ret
->ai_addrlen
= ai
->ai_addrlen
;
6777 ret
->ai_canonname
= NULL
;
6778 ret
->ai_addr
= NULL
;
6779 ret
->ai_next
= NULL
;
6780 if (ai
->ai_canonname
)
6782 int len
= WideCharToMultiByte(CP_ACP
, 0, ai
->ai_canonname
, -1, NULL
, 0, NULL
, NULL
);
6783 if (!(ret
->ai_canonname
= HeapAlloc(GetProcessHeap(), 0, len
)))
6785 HeapFree(GetProcessHeap(), 0, ret
);
6788 WideCharToMultiByte(CP_ACP
, 0, ai
->ai_canonname
, -1, ret
->ai_canonname
, len
, NULL
, NULL
);
6792 if (!(ret
->ai_addr
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr
))))
6794 HeapFree(GetProcessHeap(), 0, ret
->ai_canonname
);
6795 HeapFree(GetProcessHeap(), 0, ret
);
6798 memcpy(ret
->ai_addr
, ai
->ai_addr
, sizeof(struct WS_sockaddr
));
6803 /***********************************************************************
6804 * GetAddrInfoExW (WS2_32.@)
6806 int WINAPI
GetAddrInfoExW(const WCHAR
*name
, const WCHAR
*servname
, DWORD
namespace, GUID
*namespace_id
,
6807 const ADDRINFOEXW
*hints
, ADDRINFOEXW
**result
, struct timeval
*timeout
, OVERLAPPED
*overlapped
,
6808 LPLOOKUPSERVICE_COMPLETION_ROUTINE completion_routine
, HANDLE
*handle
)
6810 FIXME("(%s %s %x %s %p %p %p %p %p %p)\n", debugstr_w(name
), debugstr_w(servname
), namespace,
6811 debugstr_guid(namespace_id
), hints
, result
, timeout
, overlapped
, completion_routine
, handle
);
6812 return WSAHOST_NOT_FOUND
;
6815 /***********************************************************************
6816 * GetAddrInfoW (WS2_32.@)
6818 int WINAPI
GetAddrInfoW(LPCWSTR nodename
, LPCWSTR servname
, const ADDRINFOW
*hints
, PADDRINFOW
*res
)
6820 int ret
= EAI_MEMORY
, len
, i
;
6821 char *nodenameA
= NULL
, *servnameA
= NULL
;
6822 struct WS_addrinfo
*resA
, *hintsA
= NULL
;
6823 WCHAR
*local_nodenameW
= (WCHAR
*)nodename
;
6825 TRACE("nodename %s, servname %s, hints %p, result %p\n",
6826 debugstr_w(nodename
), debugstr_w(servname
), hints
, res
);
6831 /* Is this an IDN? Most likely if any char is above the Ascii table, this
6832 * is the simplest validation possible, further validation will be done by
6833 * the native getaddrinfo() */
6834 for (i
= 0; nodename
[i
]; i
++)
6836 if (nodename
[i
] > 'z')
6841 if (hints
&& (hints
->ai_flags
& WS_AI_DISABLE_IDN_ENCODING
))
6843 /* Name requires conversion but it was disabled */
6844 ret
= WSAHOST_NOT_FOUND
;
6845 WSASetLastError(ret
);
6849 len
= IdnToAscii(0, nodename
, -1, NULL
, 0);
6852 ERR("Failed to convert %s to punycode\n", debugstr_w(nodename
));
6856 if (!(local_nodenameW
= HeapAlloc(GetProcessHeap(), 0, len
* sizeof(WCHAR
)))) goto end
;
6857 IdnToAscii(0, nodename
, -1, local_nodenameW
, len
);
6860 if (local_nodenameW
)
6862 len
= WideCharToMultiByte(CP_ACP
, 0, local_nodenameW
, -1, NULL
, 0, NULL
, NULL
);
6863 if (!(nodenameA
= HeapAlloc(GetProcessHeap(), 0, len
))) goto end
;
6864 WideCharToMultiByte(CP_ACP
, 0, local_nodenameW
, -1, nodenameA
, len
, NULL
, NULL
);
6868 len
= WideCharToMultiByte(CP_ACP
, 0, servname
, -1, NULL
, 0, NULL
, NULL
);
6869 if (!(servnameA
= HeapAlloc(GetProcessHeap(), 0, len
))) goto end
;
6870 WideCharToMultiByte(CP_ACP
, 0, servname
, -1, servnameA
, len
, NULL
, NULL
);
6873 if (hints
) hintsA
= addrinfo_WtoA(hints
);
6874 ret
= WS_getaddrinfo(nodenameA
, servnameA
, hintsA
, &resA
);
6875 WS_freeaddrinfo(hintsA
);
6879 *res
= addrinfo_list_AtoW(resA
);
6880 WS_freeaddrinfo(resA
);
6884 if (local_nodenameW
!= nodename
)
6885 HeapFree(GetProcessHeap(), 0, local_nodenameW
);
6886 HeapFree(GetProcessHeap(), 0, nodenameA
);
6887 HeapFree(GetProcessHeap(), 0, servnameA
);
6891 /***********************************************************************
6892 * FreeAddrInfoW (WS2_32.@)
6894 void WINAPI
FreeAddrInfoW(PADDRINFOW ai
)
6899 HeapFree(GetProcessHeap(), 0, ai
->ai_canonname
);
6900 HeapFree(GetProcessHeap(), 0, ai
->ai_addr
);
6902 HeapFree(GetProcessHeap(), 0, ai
);
6907 /***********************************************************************
6908 * FreeAddrInfoExW (WS2_32.@)
6910 void WINAPI
FreeAddrInfoExW(ADDRINFOEXW
*ai
)
6915 int WINAPI
WS_getnameinfo(const SOCKADDR
*sa
, WS_socklen_t salen
, PCHAR host
,
6916 DWORD hostlen
, PCHAR serv
, DWORD servlen
, INT flags
)
6918 #ifdef HAVE_GETNAMEINFO
6920 union generic_unix_sockaddr sa_u
;
6923 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa
), salen
, host
, hostlen
,
6924 serv
, servlen
, flags
);
6926 size
= ws_sockaddr_ws2u(sa
, salen
, &sa_u
);
6929 SetLastError(WSAEFAULT
);
6930 return WSA_NOT_ENOUGH_MEMORY
;
6932 ret
= getnameinfo(&sa_u
.addr
, size
, host
, hostlen
, serv
, servlen
, convert_niflag_w2u(flags
));
6933 return convert_eai_u2w(ret
);
6935 FIXME("getnameinfo() failed, not found during buildtime.\n");
6940 int WINAPI
GetNameInfoW(const SOCKADDR
*sa
, WS_socklen_t salen
, PWCHAR host
,
6941 DWORD hostlen
, PWCHAR serv
, DWORD servlen
, INT flags
)
6944 char *hostA
= NULL
, *servA
= NULL
;
6946 if (host
&& (!(hostA
= HeapAlloc(GetProcessHeap(), 0, hostlen
)))) return EAI_MEMORY
;
6947 if (serv
&& (!(servA
= HeapAlloc(GetProcessHeap(), 0, servlen
))))
6949 HeapFree(GetProcessHeap(), 0, hostA
);
6953 ret
= WS_getnameinfo(sa
, salen
, hostA
, hostlen
, servA
, servlen
, flags
);
6956 if (host
) MultiByteToWideChar(CP_ACP
, 0, hostA
, -1, host
, hostlen
);
6957 if (serv
) MultiByteToWideChar(CP_ACP
, 0, servA
, -1, serv
, servlen
);
6960 HeapFree(GetProcessHeap(), 0, hostA
);
6961 HeapFree(GetProcessHeap(), 0, servA
);
6965 /***********************************************************************
6966 * getservbyport (WS2_32.56)
6968 struct WS_servent
* WINAPI
WS_getservbyport(int port
, const char *proto
)
6970 struct WS_servent
* retval
= NULL
;
6971 #ifdef HAVE_GETSERVBYPORT
6972 struct servent
* serv
;
6973 char *proto_str
= NULL
;
6975 if (proto
&& *proto
)
6977 if (!(proto_str
= strdup_lower(proto
))) return NULL
;
6979 EnterCriticalSection( &csWSgetXXXbyYYY
);
6980 if( (serv
= getservbyport(port
, proto_str
)) != NULL
) {
6981 retval
= WS_dup_se(serv
);
6983 else SetLastError(WSANO_DATA
);
6984 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6985 HeapFree( GetProcessHeap(), 0, proto_str
);
6987 TRACE("%d (i.e. port %d), %s ret %p\n", port
, (int)ntohl(port
), debugstr_a(proto
), retval
);
6992 /***********************************************************************
6993 * gethostname (WS2_32.57)
6995 int WINAPI
WS_gethostname(char *name
, int namelen
)
7000 TRACE("name %p, len %d\n", name
, namelen
);
7004 SetLastError(WSAEFAULT
);
7005 return SOCKET_ERROR
;
7008 if (gethostname(buf
, sizeof(buf
)) != 0)
7010 SetLastError(wsaErrno());
7011 return SOCKET_ERROR
;
7014 TRACE("<- '%s'\n", buf
);
7017 WARN("Windows supports NetBIOS name length up to 15 bytes!\n");
7020 SetLastError(WSAEFAULT
);
7021 WARN("<- not enough space for hostname, required %d, got %d!\n", len
+ 1, namelen
);
7022 return SOCKET_ERROR
;
7029 /* ------------------------------------- Windows sockets extensions -- *
7031 * ------------------------------------------------------------------- */
7033 /***********************************************************************
7034 * WSAEnumNetworkEvents (WS2_32.36)
7036 int WINAPI
WSAEnumNetworkEvents(SOCKET s
, WSAEVENT hEvent
, LPWSANETWORKEVENTS lpEvent
)
7040 int errors
[FD_MAX_EVENTS
];
7042 TRACE("%04lx, hEvent %p, lpEvent %p\n", s
, hEvent
, lpEvent
);
7044 SERVER_START_REQ( get_socket_event
)
7046 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
7047 req
->service
= TRUE
;
7048 req
->c_event
= wine_server_obj_handle( hEvent
);
7049 wine_server_set_reply( req
, errors
, sizeof(errors
) );
7050 if (!(ret
= wine_server_call(req
))) lpEvent
->lNetworkEvents
= reply
->pmask
& reply
->mask
;
7055 for (i
= 0; i
< FD_MAX_EVENTS
; i
++)
7056 lpEvent
->iErrorCode
[i
] = NtStatusToWSAError(errors
[i
]);
7059 SetLastError(WSAEINVAL
);
7060 return SOCKET_ERROR
;
7063 /***********************************************************************
7064 * WSAEventSelect (WS2_32.39)
7066 int WINAPI
WSAEventSelect(SOCKET s
, WSAEVENT hEvent
, LONG lEvent
)
7070 TRACE("%04lx, hEvent %p, event %08x\n", s
, hEvent
, lEvent
);
7072 SERVER_START_REQ( set_socket_event
)
7074 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
7076 req
->event
= wine_server_obj_handle( hEvent
);
7079 ret
= wine_server_call( req
);
7083 SetLastError(WSAEINVAL
);
7084 return SOCKET_ERROR
;
7087 /**********************************************************************
7088 * WSAGetOverlappedResult (WS2_32.40)
7090 BOOL WINAPI
WSAGetOverlappedResult( SOCKET s
, LPWSAOVERLAPPED lpOverlapped
,
7091 LPDWORD lpcbTransfer
, BOOL fWait
,
7096 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
7097 s
, lpOverlapped
, lpcbTransfer
, fWait
, lpdwFlags
);
7099 if ( lpOverlapped
== NULL
)
7101 ERR( "Invalid pointer\n" );
7102 SetLastError(WSA_INVALID_PARAMETER
);
7106 status
= lpOverlapped
->Internal
;
7107 if (status
== STATUS_PENDING
)
7111 SetLastError( WSA_IO_INCOMPLETE
);
7115 if (WaitForSingleObject( lpOverlapped
->hEvent
? lpOverlapped
->hEvent
: SOCKET2HANDLE(s
),
7116 INFINITE
) == WAIT_FAILED
)
7118 status
= lpOverlapped
->Internal
;
7122 *lpcbTransfer
= lpOverlapped
->InternalHigh
;
7125 *lpdwFlags
= lpOverlapped
->u
.s
.Offset
;
7127 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
7132 /***********************************************************************
7133 * WSAAsyncSelect (WS2_32.101)
7135 INT WINAPI
WSAAsyncSelect(SOCKET s
, HWND hWnd
, UINT uMsg
, LONG lEvent
)
7139 TRACE("%04lx, hWnd %p, uMsg %08x, event %08x\n", s
, hWnd
, uMsg
, lEvent
);
7141 SERVER_START_REQ( set_socket_event
)
7143 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
7146 req
->window
= wine_server_user_handle( hWnd
);
7148 ret
= wine_server_call( req
);
7152 SetLastError(WSAEINVAL
);
7153 return SOCKET_ERROR
;
7156 /***********************************************************************
7157 * WSACreateEvent (WS2_32.31)
7160 WSAEVENT WINAPI
WSACreateEvent(void)
7162 /* Create a manual-reset event, with initial state: unsignaled */
7165 return CreateEventW(NULL
, TRUE
, FALSE
, NULL
);
7168 /***********************************************************************
7169 * WSACloseEvent (WS2_32.29)
7172 BOOL WINAPI
WSACloseEvent(WSAEVENT event
)
7174 TRACE ("event=%p\n", event
);
7176 return CloseHandle(event
);
7179 /***********************************************************************
7180 * WSASocketA (WS2_32.78)
7183 SOCKET WINAPI
WSASocketA(int af
, int type
, int protocol
,
7184 LPWSAPROTOCOL_INFOA lpProtocolInfo
,
7185 GROUP g
, DWORD dwFlags
)
7188 WSAPROTOCOL_INFOW info
;
7190 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
7191 af
, type
, protocol
, lpProtocolInfo
, g
, dwFlags
);
7193 if (!lpProtocolInfo
) return WSASocketW(af
, type
, protocol
, NULL
, g
, dwFlags
);
7195 memcpy(&info
, lpProtocolInfo
, FIELD_OFFSET(WSAPROTOCOL_INFOW
, szProtocol
));
7196 len
= MultiByteToWideChar(CP_ACP
, 0, lpProtocolInfo
->szProtocol
, -1,
7197 info
.szProtocol
, WSAPROTOCOL_LEN
+ 1);
7201 SetLastError(WSAEINVAL
);
7202 return SOCKET_ERROR
;
7205 return WSASocketW(af
, type
, protocol
, &info
, g
, dwFlags
);
7208 /***********************************************************************
7209 * WSASocketW (WS2_32.79)
7212 SOCKET WINAPI
WSASocketW(int af
, int type
, int protocol
,
7213 LPWSAPROTOCOL_INFOW lpProtocolInfo
,
7214 GROUP g
, DWORD dwFlags
)
7218 int unixaf
, unixtype
, ipxptype
= -1;
7221 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
7222 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
7225 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
7226 af
, type
, protocol
, lpProtocolInfo
, g
, dwFlags
);
7230 err
= WSANOTINITIALISED
;
7234 /* hack for WSADuplicateSocket */
7235 if (lpProtocolInfo
&& lpProtocolInfo
->dwServiceFlags4
== 0xff00ff00) {
7236 ret
= lpProtocolInfo
->dwServiceFlags3
;
7237 TRACE("\tgot duplicate %04lx\n", ret
);
7243 if (af
== FROM_PROTOCOL_INFO
|| !af
)
7244 af
= lpProtocolInfo
->iAddressFamily
;
7245 if (type
== FROM_PROTOCOL_INFO
|| !type
)
7246 type
= lpProtocolInfo
->iSocketType
;
7247 if (protocol
== FROM_PROTOCOL_INFO
|| !protocol
)
7248 protocol
= lpProtocolInfo
->iProtocol
;
7251 if (!type
&& (af
|| protocol
))
7253 int autoproto
= protocol
;
7254 WSAPROTOCOL_INFOW infow
;
7256 /* default to the first valid protocol */
7258 autoproto
= valid_protocols
[0];
7259 else if(IS_IPX_PROTO(autoproto
))
7260 autoproto
= WS_NSPROTO_IPX
;
7262 if (WS_EnterSingleProtocolW(autoproto
, &infow
))
7264 type
= infow
.iSocketType
;
7266 /* after win2003 it's no longer possible to pass AF_UNSPEC
7267 using the protocol info struct */
7268 if (!lpProtocolInfo
&& af
== WS_AF_UNSPEC
)
7269 af
= infow
.iAddressFamily
;
7274 Windows has an extension to the IPX protocol that allows one to create sockets
7275 and set the IPX packet type at the same time, to do that a caller will use
7276 a protocol like NSPROTO_IPX + <PACKET TYPE>
7278 if (IS_IPX_PROTO(protocol
))
7279 ipxptype
= protocol
- WS_NSPROTO_IPX
;
7281 /* convert the socket family, type and protocol */
7282 unixaf
= convert_af_w2u(af
);
7283 unixtype
= convert_socktype_w2u(type
);
7284 protocol
= convert_proto_w2u(protocol
);
7285 if (unixaf
== AF_UNSPEC
) unixaf
= -1;
7287 /* filter invalid parameters */
7290 /* the type could not be converted */
7291 if (type
&& unixtype
< 0)
7293 err
= WSAESOCKTNOSUPPORT
;
7297 err
= WSAEPROTONOSUPPORT
;
7302 /* both family and protocol can't be invalid */
7309 /* family could not be converted and neither socket type */
7310 if (unixtype
< 0 && af
>= 0)
7313 err
= WSAESOCKTNOSUPPORT
;
7317 err
= WSAEAFNOSUPPORT
;
7321 SERVER_START_REQ( create_socket
)
7323 req
->family
= unixaf
;
7324 req
->type
= unixtype
;
7325 req
->protocol
= protocol
;
7326 req
->access
= GENERIC_READ
|GENERIC_WRITE
|SYNCHRONIZE
;
7327 req
->attributes
= (dwFlags
& WSA_FLAG_NO_HANDLE_INHERIT
) ? 0 : OBJ_INHERIT
;
7328 req
->flags
= dwFlags
& ~WSA_FLAG_NO_HANDLE_INHERIT
;
7329 set_error( wine_server_call( req
) );
7330 ret
= HANDLE2SOCKET( wine_server_ptr_handle( reply
->handle
));
7335 TRACE("\tcreated %04lx\n", ret
);
7337 set_ipx_packettype(ret
, ipxptype
);
7339 /* ensure IP_DONTFRAGMENT is disabled, in Linux the global default can be enabled */
7340 if (unixaf
== AF_INET
|| unixaf
== AF_INET6
)
7341 set_dont_fragment(ret
, unixaf
== AF_INET6
? IPPROTO_IPV6
: IPPROTO_IP
, FALSE
);
7344 if (unixaf
== AF_INET6
)
7346 int fd
= get_sock_fd(ret
, 0, NULL
);
7349 /* IPV6_V6ONLY is set by default on Windows */
7351 if (setsockopt(fd
, IPPROTO_IPV6
, IPV6_V6ONLY
, &enable
, sizeof(enable
)))
7352 WARN("\tsetting IPV6_V6ONLY failed - errno = %i\n", errno
);
7353 release_sock_fd(ret
, fd
);
7360 err
= GetLastError();
7361 if (err
== WSAEACCES
) /* raw socket denied */
7363 if (type
== SOCK_RAW
)
7364 ERR_(winediag
)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
7366 ERR_(winediag
)("Failed to create socket, this requires special permissions.\n");
7370 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
7371 if (err
== WSAEINVAL
)
7372 err
= WSAESOCKTNOSUPPORT
;
7373 else if (err
== WSAEOPNOTSUPP
)
7374 err
= WSAEPROTONOSUPPORT
;
7378 WARN("\t\tfailed, error %d!\n", err
);
7380 return INVALID_SOCKET
;
7383 /***********************************************************************
7384 * WSAJoinLeaf (WS2_32.58)
7387 SOCKET WINAPI
WSAJoinLeaf(
7389 const struct WS_sockaddr
*addr
,
7391 LPWSABUF lpCallerData
,
7392 LPWSABUF lpCalleeData
,
7398 return INVALID_SOCKET
;
7401 /***********************************************************************
7402 * __WSAFDIsSet (WS2_32.151)
7404 int WINAPI
__WSAFDIsSet(SOCKET s
, WS_fd_set
*set
)
7406 int i
= set
->fd_count
, ret
= 0;
7409 if (set
->fd_array
[i
] == s
)
7415 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s
, set
, set
->fd_count
, ret
);
7419 /***********************************************************************
7420 * WSAIsBlocking (WS2_32.114)
7422 BOOL WINAPI
WSAIsBlocking(void)
7424 /* By default WinSock should set all its sockets to non-blocking mode
7425 * and poll in PeekMessage loop when processing "blocking" ones. This
7426 * function is supposed to tell if the program is in this loop. Our
7427 * blocking calls are truly blocking so we always return FALSE.
7429 * Note: It is allowed to call this function without prior WSAStartup().
7436 /***********************************************************************
7437 * WSACancelBlockingCall (WS2_32.113)
7439 INT WINAPI
WSACancelBlockingCall(void)
7445 static INT WINAPI
WSA_DefaultBlockingHook( FARPROC x
)
7447 FIXME("How was this called?\n");
7452 /***********************************************************************
7453 * WSASetBlockingHook (WS2_32.109)
7455 FARPROC WINAPI
WSASetBlockingHook(FARPROC lpBlockFunc
)
7457 FARPROC prev
= blocking_hook
;
7458 blocking_hook
= lpBlockFunc
;
7459 TRACE("hook %p\n", lpBlockFunc
);
7464 /***********************************************************************
7465 * WSAUnhookBlockingHook (WS2_32.110)
7467 INT WINAPI
WSAUnhookBlockingHook(void)
7469 blocking_hook
= (FARPROC
)WSA_DefaultBlockingHook
;
7474 /* ----------------------------------- end of API stuff */
7476 /* ----------------------------------- helper functions -
7478 * TODO: Merge WS_dup_..() stuff into one function that
7479 * would operate with a generic structure containing internal
7480 * pointers (via a template of some kind).
7483 static int list_size(char** l
, int item_size
)
7488 j
+= (item_size
) ? item_size
: strlen(l
[i
]) + 1;
7489 j
+= (i
+ 1) * sizeof(char*); }
7493 static int list_dup(char** l_src
, char** l_to
, int item_size
)
7498 for (i
= 0; l_src
[i
]; i
++) ;
7499 p
= (char *)(l_to
+ i
+ 1);
7500 for (i
= 0; l_src
[i
]; i
++)
7502 int count
= ( item_size
) ? item_size
: strlen(l_src
[i
]) + 1;
7503 memcpy(p
, l_src
[i
], count
);
7508 return p
- (char *)l_to
;
7513 /* create a hostent entry
7515 * Creates the entry with enough memory for the name, aliases
7516 * addresses, and the address pointers. Also copies the name
7517 * and sets up all the pointers.
7519 * NOTE: The alias and address lists must be allocated with room
7520 * for the NULL item terminating the list. This is true even if
7521 * the list has no items ("aliases" and "addresses" must be
7522 * at least "1", a truly empty list is invalid).
7524 static struct WS_hostent
*WS_create_he(char *name
, int aliases
, int aliases_size
, int addresses
, int address_length
)
7526 struct WS_hostent
*p_to
;
7528 int size
= (sizeof(struct WS_hostent
) +
7530 sizeof(char *) * aliases
+
7532 sizeof(char *) * addresses
+
7533 address_length
* (addresses
- 1)), i
;
7535 if (!(p_to
= check_buffer_he(size
))) return NULL
;
7536 memset(p_to
, 0, size
);
7538 /* Use the memory in the same way winsock does.
7539 * First set the pointer for aliases, second set the pointers for addresses.
7540 * Third fill the addresses indexes, fourth jump aliases names size.
7541 * Fifth fill the hostname.
7542 * NOTE: This method is valid for OS version's >= XP.
7544 p
= (char *)(p_to
+ 1);
7545 p_to
->h_aliases
= (char **)p
;
7546 p
+= sizeof(char *)*aliases
;
7548 p_to
->h_addr_list
= (char **)p
;
7549 p
+= sizeof(char *)*addresses
;
7551 for (i
= 0, addresses
--; i
< addresses
; i
++, p
+= address_length
)
7552 p_to
->h_addr_list
[i
] = p
;
7554 /* NOTE: h_aliases must be filled in manually because we don't know each string
7555 * size, leave these pointers NULL (already set to NULL by memset earlier).
7565 /* duplicate hostent entry
7566 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
7567 * Ditto for protoent and servent.
7569 static struct WS_hostent
*WS_dup_he(const struct hostent
* p_he
)
7571 int i
, addresses
= 0, alias_size
= 0;
7572 struct WS_hostent
*p_to
;
7575 for( i
= 0; p_he
->h_aliases
[i
]; i
++) alias_size
+= strlen(p_he
->h_aliases
[i
]) + 1;
7576 while (p_he
->h_addr_list
[addresses
]) addresses
++;
7578 p_to
= WS_create_he(p_he
->h_name
, i
+ 1, alias_size
, addresses
+ 1, p_he
->h_length
);
7580 if (!p_to
) return NULL
;
7581 p_to
->h_addrtype
= convert_af_u2w(p_he
->h_addrtype
);
7582 p_to
->h_length
= p_he
->h_length
;
7584 for(i
= 0, p
= p_to
->h_addr_list
[0]; p_he
->h_addr_list
[i
]; i
++, p
+= p_to
->h_length
)
7585 memcpy(p
, p_he
->h_addr_list
[i
], p_to
->h_length
);
7587 /* Fill the aliases after the IP data */
7588 for(i
= 0; p_he
->h_aliases
[i
]; i
++)
7590 p_to
->h_aliases
[i
] = p
;
7591 strcpy(p
, p_he
->h_aliases
[i
]);
7598 /* ----- protoent */
7600 static struct WS_protoent
*WS_dup_pe(const struct protoent
* p_pe
)
7603 struct WS_protoent
*p_to
;
7605 int size
= (sizeof(*p_pe
) +
7606 strlen(p_pe
->p_name
) + 1 +
7607 list_size(p_pe
->p_aliases
, 0));
7609 if (!(p_to
= check_buffer_pe(size
))) return NULL
;
7610 p_to
->p_proto
= p_pe
->p_proto
;
7612 p
= (char *)(p_to
+ 1);
7614 strcpy(p
, p_pe
->p_name
);
7617 p_to
->p_aliases
= (char **)p
;
7618 list_dup(p_pe
->p_aliases
, p_to
->p_aliases
, 0);
7624 static struct WS_servent
*WS_dup_se(const struct servent
* p_se
)
7627 struct WS_servent
*p_to
;
7629 int size
= (sizeof(*p_se
) +
7630 strlen(p_se
->s_proto
) + 1 +
7631 strlen(p_se
->s_name
) + 1 +
7632 list_size(p_se
->s_aliases
, 0));
7634 if (!(p_to
= check_buffer_se(size
))) return NULL
;
7635 p_to
->s_port
= p_se
->s_port
;
7637 p
= (char *)(p_to
+ 1);
7639 strcpy(p
, p_se
->s_name
);
7643 strcpy(p
, p_se
->s_proto
);
7646 p_to
->s_aliases
= (char **)p
;
7647 list_dup(p_se
->s_aliases
, p_to
->s_aliases
, 0);
7652 /***********************************************************************
7653 * WSARecv (WS2_32.67)
7655 int WINAPI
WSARecv(SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
7656 LPDWORD NumberOfBytesReceived
, LPDWORD lpFlags
,
7657 LPWSAOVERLAPPED lpOverlapped
,
7658 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
7660 return WS2_recv_base(s
, lpBuffers
, dwBufferCount
, NumberOfBytesReceived
, lpFlags
,
7661 NULL
, NULL
, lpOverlapped
, lpCompletionRoutine
, NULL
);
7664 static int WS2_recv_base( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
7665 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
,
7666 struct WS_sockaddr
*lpFrom
,
7667 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
7668 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
,
7669 LPWSABUF lpControlBuffer
)
7671 unsigned int i
, options
;
7672 int n
, fd
, err
, overlapped
, flags
;
7673 struct ws2_async
*wsa
= NULL
, localwsa
;
7675 DWORD timeout_start
= GetTickCount();
7676 ULONG_PTR cvalue
= (lpOverlapped
&& ((ULONG_PTR
)lpOverlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)lpOverlapped
: 0;
7678 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
7679 s
, lpBuffers
, dwBufferCount
, *lpFlags
, lpFrom
,
7680 (lpFromlen
? *lpFromlen
: -1),
7681 lpOverlapped
, lpCompletionRoutine
);
7683 fd
= get_sock_fd( s
, FILE_READ_DATA
, &options
);
7684 TRACE( "fd=%d, options=%x\n", fd
, options
);
7686 if (fd
== -1) return SOCKET_ERROR
;
7688 if (*lpFlags
& WS_MSG_OOB
)
7690 /* It's invalid to receive OOB data from an OOBINLINED socket
7691 * as OOB data is turned into normal data. */
7693 if (!getsockopt(fd
, SOL_SOCKET
, SO_OOBINLINE
, (char*) &n
, &i
) && n
)
7700 overlapped
= (lpOverlapped
|| lpCompletionRoutine
) &&
7701 !(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
));
7702 if (overlapped
|| dwBufferCount
> 1)
7704 if (!(wsa
= (struct ws2_async
*)alloc_async_io( offsetof(struct ws2_async
, iovec
[dwBufferCount
]),
7714 wsa
->hSocket
= SOCKET2HANDLE(s
);
7715 wsa
->flags
= *lpFlags
;
7716 wsa
->lpFlags
= lpFlags
;
7718 wsa
->addrlen
.ptr
= lpFromlen
;
7719 wsa
->control
= lpControlBuffer
;
7720 wsa
->n_iovecs
= dwBufferCount
;
7721 wsa
->first_iovec
= 0;
7722 for (i
= 0; i
< dwBufferCount
; i
++)
7724 /* check buffer first to trigger write watches */
7725 if (IsBadWritePtr( lpBuffers
[i
].buf
, lpBuffers
[i
].len
))
7730 wsa
->iovec
[i
].iov_base
= lpBuffers
[i
].buf
;
7731 wsa
->iovec
[i
].iov_len
= lpBuffers
[i
].len
;
7734 flags
= convert_flags(wsa
->flags
);
7737 n
= WS2_recv( fd
, wsa
, flags
);
7740 /* Unix-like systems return EINVAL when attempting to read OOB data from
7741 * an empty socket buffer, convert that to a Windows expected return. */
7742 if ((flags
& MSG_OOB
) && errno
== EINVAL
)
7743 errno
= EWOULDBLOCK
;
7745 if (errno
!= EAGAIN
)
7747 int loc_errno
= errno
;
7749 if (cvalue
) WS_AddCompletion( s
, cvalue
, sock_get_ntstatus(loc_errno
), 0 );
7753 else if (lpNumberOfBytesRecvd
) *lpNumberOfBytesRecvd
= n
;
7757 IO_STATUS_BLOCK
*iosb
= lpOverlapped
? (IO_STATUS_BLOCK
*)lpOverlapped
: &wsa
->local_iosb
;
7759 wsa
->user_overlapped
= lpOverlapped
;
7760 wsa
->completion_func
= lpCompletionRoutine
;
7761 release_sock_fd( s
, fd
);
7765 iosb
->u
.Status
= STATUS_PENDING
;
7766 iosb
->Information
= 0;
7768 if (wsa
->completion_func
)
7769 err
= register_async( ASYNC_TYPE_READ
, wsa
->hSocket
, &wsa
->io
, NULL
,
7770 ws2_async_apc
, wsa
, iosb
);
7772 err
= register_async( ASYNC_TYPE_READ
, wsa
->hSocket
, &wsa
->io
, lpOverlapped
->hEvent
,
7773 NULL
, (void *)cvalue
, iosb
);
7775 if (err
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
7776 SetLastError(NtStatusToWSAError( err
));
7777 return SOCKET_ERROR
;
7780 iosb
->u
.Status
= STATUS_SUCCESS
;
7781 iosb
->Information
= n
;
7782 if (!wsa
->completion_func
)
7784 if (cvalue
) WS_AddCompletion( s
, cvalue
, STATUS_SUCCESS
, n
);
7785 if (lpOverlapped
->hEvent
) SetEvent( lpOverlapped
->hEvent
);
7786 HeapFree( GetProcessHeap(), 0, wsa
);
7788 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC
)ws2_async_apc
,
7789 (ULONG_PTR
)wsa
, (ULONG_PTR
)iosb
, 0 );
7790 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7796 if ((err
= _is_blocking( s
, &is_blocking
)))
7798 err
= NtStatusToWSAError( err
);
7805 int poll_timeout
= -1;
7806 INT64 timeout
= get_rcvsnd_timeo(fd
, TRUE
);
7810 timeout
-= GetTickCount() - timeout_start
;
7811 if (timeout
< 0) poll_timeout
= 0;
7812 else poll_timeout
= timeout
<= INT_MAX
? timeout
: INT_MAX
;
7816 pfd
.events
= POLLIN
;
7817 if (*lpFlags
& WS_MSG_OOB
) pfd
.events
|= POLLPRI
;
7819 if (!poll_timeout
|| !poll( &pfd
, 1, poll_timeout
))
7822 /* a timeout is not fatal */
7823 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7829 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7830 err
= WSAEWOULDBLOCK
;
7835 TRACE(" -> %i bytes\n", n
);
7836 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
7837 release_sock_fd( s
, fd
);
7838 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7839 SetLastError(ERROR_SUCCESS
);
7844 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
7845 release_sock_fd( s
, fd
);
7846 WARN(" -> ERROR %d\n", err
);
7847 SetLastError( err
);
7848 return SOCKET_ERROR
;
7851 /***********************************************************************
7852 * WSARecvFrom (WS2_32.69)
7854 INT WINAPI
WSARecvFrom( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
7855 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
, struct WS_sockaddr
*lpFrom
,
7856 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
7857 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
7860 return WS2_recv_base( s
, lpBuffers
, dwBufferCount
,
7861 lpNumberOfBytesRecvd
, lpFlags
,
7863 lpOverlapped
, lpCompletionRoutine
, NULL
);
7866 /***********************************************************************
7867 * WSCInstallProvider (WS2_32.88)
7869 INT WINAPI
WSCInstallProvider( const LPGUID lpProviderId
,
7870 LPCWSTR lpszProviderDllPath
,
7871 const LPWSAPROTOCOL_INFOW lpProtocolInfoList
,
7872 DWORD dwNumberOfEntries
,
7875 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId
),
7876 debugstr_w(lpszProviderDllPath
), lpProtocolInfoList
,
7877 dwNumberOfEntries
, lpErrno
);
7883 /***********************************************************************
7884 * WSCDeinstallProvider (WS2_32.83)
7886 INT WINAPI
WSCDeinstallProvider(LPGUID lpProviderId
, LPINT lpErrno
)
7888 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId
), lpErrno
);
7894 /***********************************************************************
7895 * WSAAccept (WS2_32.26)
7897 SOCKET WINAPI
WSAAccept( SOCKET s
, struct WS_sockaddr
*addr
, LPINT addrlen
,
7898 LPCONDITIONPROC lpfnCondition
, DWORD_PTR dwCallbackData
)
7902 WSABUF CallerId
, CallerData
, CalleeId
, CalleeData
;
7903 /* QOS SQOS, GQOS; */
7906 SOCKADDR src_addr
, dst_addr
;
7908 TRACE("socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
7909 s
, addr
, addrlen
, lpfnCondition
, dwCallbackData
);
7911 cs
= WS_accept(s
, addr
, addrlen
);
7912 if (cs
== SOCKET_ERROR
) return SOCKET_ERROR
;
7913 if (!lpfnCondition
) return cs
;
7915 if (addr
&& addrlen
)
7917 CallerId
.buf
= (char *)addr
;
7918 CallerId
.len
= *addrlen
;
7922 size
= sizeof(src_addr
);
7923 WS_getpeername(cs
, &src_addr
, &size
);
7924 CallerId
.buf
= (char *)&src_addr
;
7925 CallerId
.len
= size
;
7927 CallerData
.buf
= NULL
;
7930 size
= sizeof(dst_addr
);
7931 WS_getsockname(cs
, &dst_addr
, &size
);
7933 CalleeId
.buf
= (char *)&dst_addr
;
7934 CalleeId
.len
= sizeof(dst_addr
);
7936 ret
= (*lpfnCondition
)(&CallerId
, &CallerData
, NULL
, NULL
,
7937 &CalleeId
, &CalleeData
, &g
, dwCallbackData
);
7944 SERVER_START_REQ( set_socket_deferred
)
7946 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
7947 req
->deferred
= wine_server_obj_handle( SOCKET2HANDLE(cs
) );
7948 if ( !wine_server_call_err ( req
) )
7950 SetLastError( WSATRY_AGAIN
);
7951 WS_closesocket( cs
);
7955 return SOCKET_ERROR
;
7958 SetLastError(WSAECONNREFUSED
);
7959 return SOCKET_ERROR
;
7961 FIXME("Unknown return type from Condition function\n");
7962 SetLastError(WSAENOTSOCK
);
7963 return SOCKET_ERROR
;
7967 /***********************************************************************
7968 * WSADuplicateSocketA (WS2_32.32)
7970 int WINAPI
WSADuplicateSocketA( SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOA lpProtocolInfo
)
7972 return WS_DuplicateSocket(FALSE
, s
, dwProcessId
, (LPWSAPROTOCOL_INFOW
) lpProtocolInfo
);
7975 /***********************************************************************
7976 * WSADuplicateSocketW (WS2_32.33)
7978 int WINAPI
WSADuplicateSocketW( SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOW lpProtocolInfo
)
7980 return WS_DuplicateSocket(TRUE
, s
, dwProcessId
, lpProtocolInfo
);
7983 /***********************************************************************
7984 * WSAInstallServiceClassA (WS2_32.48)
7986 int WINAPI
WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info
)
7988 FIXME("Request to install service %s\n",debugstr_a(info
->lpszServiceClassName
));
7989 SetLastError(WSAEACCES
);
7990 return SOCKET_ERROR
;
7993 /***********************************************************************
7994 * WSAInstallServiceClassW (WS2_32.49)
7996 int WINAPI
WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info
)
7998 FIXME("Request to install service %s\n",debugstr_w(info
->lpszServiceClassName
));
7999 SetLastError(WSAEACCES
);
8000 return SOCKET_ERROR
;
8003 /***********************************************************************
8004 * WSARemoveServiceClass (WS2_32.70)
8006 int WINAPI
WSARemoveServiceClass(LPGUID info
)
8008 FIXME("Request to remove service %s\n", debugstr_guid(info
));
8009 SetLastError(WSATYPE_NOT_FOUND
);
8010 return SOCKET_ERROR
;
8013 /***********************************************************************
8014 * inet_ntop (WS2_32.@)
8016 PCSTR WINAPI
WS_inet_ntop( INT family
, PVOID addr
, PSTR buffer
, SIZE_T len
)
8018 #ifdef HAVE_INET_NTOP
8019 struct WS_in6_addr
*in6
;
8020 struct WS_in_addr
*in
;
8023 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family
, addr
, buffer
, len
);
8026 SetLastError( STATUS_INVALID_PARAMETER
);
8035 pdst
= inet_ntop( AF_INET
, &in
->WS_s_addr
, buffer
, len
);
8041 pdst
= inet_ntop( AF_INET6
, in6
->WS_s6_addr
, buffer
, len
);
8045 SetLastError( WSAEAFNOSUPPORT
);
8049 if (!pdst
) SetLastError( STATUS_INVALID_PARAMETER
);
8052 FIXME( "not supported on this platform\n" );
8053 SetLastError( WSAEAFNOSUPPORT
);
8058 /***********************************************************************
8059 * inet_pton (WS2_32.@)
8061 INT WINAPI
WS_inet_pton( INT family
, PCSTR addr
, PVOID buffer
)
8063 #ifdef HAVE_INET_PTON
8066 TRACE("family %d, addr %s, buffer (%p)\n", family
, debugstr_a(addr
), buffer
);
8068 if (!addr
|| !buffer
)
8070 SetLastError(WSAEFAULT
);
8071 return SOCKET_ERROR
;
8074 unixaf
= convert_af_w2u(family
);
8075 if (unixaf
!= AF_INET
&& unixaf
!= AF_INET6
)
8077 SetLastError(WSAEAFNOSUPPORT
);
8078 return SOCKET_ERROR
;
8081 ret
= inet_pton(unixaf
, addr
, buffer
);
8082 if (ret
== -1) SetLastError(wsaErrno());
8085 FIXME( "not supported on this platform\n" );
8086 SetLastError( WSAEAFNOSUPPORT
);
8087 return SOCKET_ERROR
;
8091 /***********************************************************************
8092 * InetPtonW (WS2_32.@)
8094 INT WINAPI
InetPtonW(INT family
, PCWSTR addr
, PVOID buffer
)
8100 TRACE("family %d, addr %s, buffer (%p)\n", family
, debugstr_w(addr
), buffer
);
8104 SetLastError(WSAEFAULT
);
8105 return SOCKET_ERROR
;
8108 len
= WideCharToMultiByte(CP_ACP
, 0, addr
, -1, NULL
, 0, NULL
, NULL
);
8109 if (!(addrA
= HeapAlloc(GetProcessHeap(), 0, len
)))
8111 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8112 return SOCKET_ERROR
;
8114 WideCharToMultiByte(CP_ACP
, 0, addr
, -1, addrA
, len
, NULL
, NULL
);
8116 ret
= WS_inet_pton(family
, addrA
, buffer
);
8118 HeapFree(GetProcessHeap(), 0, addrA
);
8122 /***********************************************************************
8123 * InetNtopW (WS2_32.@)
8125 PCWSTR WINAPI
InetNtopW(INT family
, PVOID addr
, PWSTR buffer
, SIZE_T len
)
8127 char bufferA
[WS_INET6_ADDRSTRLEN
];
8130 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family
, addr
, buffer
, len
);
8132 if (WS_inet_ntop(family
, addr
, bufferA
, sizeof(bufferA
)))
8134 if (MultiByteToWideChar(CP_ACP
, 0, bufferA
, -1, buffer
, len
))
8137 SetLastError(ERROR_INVALID_PARAMETER
);
8142 /***********************************************************************
8143 * WSAStringToAddressA (WS2_32.80)
8145 INT WINAPI
WSAStringToAddressA(LPSTR AddressString
,
8147 LPWSAPROTOCOL_INFOA lpProtocolInfo
,
8148 LPSOCKADDR lpAddress
,
8149 LPINT lpAddressLength
)
8152 LPSTR workBuffer
=NULL
,ptrPort
;
8154 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString
), AddressFamily
,
8155 lpProtocolInfo
, lpAddress
, lpAddressLength
);
8157 if (!lpAddressLength
|| !lpAddress
) return SOCKET_ERROR
;
8161 SetLastError(WSAEINVAL
);
8162 return SOCKET_ERROR
;
8166 FIXME("ProtocolInfo not implemented.\n");
8168 workBuffer
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
,
8169 strlen(AddressString
) + 1);
8172 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8173 return SOCKET_ERROR
;
8176 strcpy(workBuffer
, AddressString
);
8178 switch(AddressFamily
)
8182 struct in_addr inetaddr
;
8184 /* If lpAddressLength is too small, tell caller the size we need */
8185 if (*lpAddressLength
< sizeof(SOCKADDR_IN
))
8187 *lpAddressLength
= sizeof(SOCKADDR_IN
);
8191 *lpAddressLength
= sizeof(SOCKADDR_IN
);
8192 memset(lpAddress
, 0, sizeof(SOCKADDR_IN
));
8194 ((LPSOCKADDR_IN
)lpAddress
)->sin_family
= WS_AF_INET
;
8196 ptrPort
= strchr(workBuffer
, ':');
8199 /* User may have entered an IPv6 and asked to parse as IPv4 */
8200 if(strchr(ptrPort
+ 1, ':'))
8205 ((LPSOCKADDR_IN
)lpAddress
)->sin_port
= htons(atoi(ptrPort
+1));
8209 if(inet_aton(workBuffer
, &inetaddr
) > 0)
8211 ((LPSOCKADDR_IN
)lpAddress
)->sin_addr
.WS_s_addr
= inetaddr
.s_addr
;
8221 struct in6_addr inetaddr
;
8222 char *ptrAddr
= workBuffer
;
8224 /* If lpAddressLength is too small, tell caller the size we need */
8225 if (*lpAddressLength
< sizeof(SOCKADDR_IN6
))
8227 *lpAddressLength
= sizeof(SOCKADDR_IN6
);
8231 #ifdef HAVE_INET_PTON
8232 *lpAddressLength
= sizeof(SOCKADDR_IN6
);
8233 memset(lpAddress
, 0, sizeof(SOCKADDR_IN6
));
8235 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_family
= WS_AF_INET6
;
8237 /* Valid IPv6 addresses can also be surrounded by [ ], and in this case
8238 * a port number may follow after like in [fd12:3456:7890::1]:12345
8239 * We need to cut the brackets and find the port if any. */
8241 if(*workBuffer
== '[')
8243 ptrPort
= strchr(workBuffer
, ']');
8246 SetLastError(WSAEINVAL
);
8247 return SOCKET_ERROR
;
8250 if (ptrPort
[1] == ':')
8251 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_port
= htons(atoi(ptrPort
+ 2));
8254 ptrAddr
= workBuffer
+ 1;
8257 if(inet_pton(AF_INET6
, ptrAddr
, &inetaddr
) > 0)
8259 memcpy(&((LPSOCKADDR_IN6
)lpAddress
)->sin6_addr
, &inetaddr
,
8260 sizeof(struct in6_addr
));
8264 #endif /* HAVE_INET_PTON */
8270 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
8271 TRACE("Unsupported address family specified: %d.\n", AddressFamily
);
8275 HeapFree(GetProcessHeap(), 0, workBuffer
);
8279 return SOCKET_ERROR
;
8282 /***********************************************************************
8283 * WSAStringToAddressW (WS2_32.81)
8285 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
8286 * If this should be the case, it would be required to map these digits
8287 * to Unicode digits (0-9) using FoldString first.
8289 INT WINAPI
WSAStringToAddressW(LPWSTR AddressString
,
8291 LPWSAPROTOCOL_INFOW lpProtocolInfo
,
8292 LPSOCKADDR lpAddress
,
8293 LPINT lpAddressLength
)
8296 LPSTR workBuffer
=NULL
;
8297 WSAPROTOCOL_INFOA infoA
;
8298 LPWSAPROTOCOL_INFOA lpProtoInfoA
= NULL
;
8300 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString
), AddressFamily
, lpProtocolInfo
,
8301 lpAddress
, lpAddressLength
);
8303 if (!lpAddressLength
|| !lpAddress
) return SOCKET_ERROR
;
8305 /* if ProtocolInfo is available - convert to ANSI variant */
8308 lpProtoInfoA
= &infoA
;
8309 memcpy( lpProtoInfoA
, lpProtocolInfo
, FIELD_OFFSET( WSAPROTOCOL_INFOA
, szProtocol
) );
8311 if (!WideCharToMultiByte( CP_ACP
, 0, lpProtocolInfo
->szProtocol
, -1,
8312 lpProtoInfoA
->szProtocol
, WSAPROTOCOL_LEN
+1, NULL
, NULL
))
8314 SetLastError(WSAEINVAL
);
8315 return SOCKET_ERROR
;
8321 /* Translate AddressString to ANSI code page - assumes that only
8322 standard digits 0-9 are used with this API call */
8323 sBuffer
= WideCharToMultiByte( CP_ACP
, 0, AddressString
, -1, NULL
, 0, NULL
, NULL
);
8324 workBuffer
= HeapAlloc( GetProcessHeap(), 0, sBuffer
);
8328 WideCharToMultiByte( CP_ACP
, 0, AddressString
, -1, workBuffer
, sBuffer
, NULL
, NULL
);
8329 res
= WSAStringToAddressA(workBuffer
,AddressFamily
,lpProtoInfoA
,
8330 lpAddress
,lpAddressLength
);
8331 HeapFree( GetProcessHeap(), 0, workBuffer
);
8335 res
= WSA_NOT_ENOUGH_MEMORY
;
8341 return SOCKET_ERROR
;
8344 /***********************************************************************
8345 * WSAAddressToStringA (WS2_32.27)
8347 * See WSAAddressToStringW
8349 INT WINAPI
WSAAddressToStringA( LPSOCKADDR sockaddr
, DWORD len
,
8350 LPWSAPROTOCOL_INFOA info
, LPSTR string
,
8354 CHAR buffer
[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8357 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr
, len
, info
, string
, lenstr
);
8359 if (!sockaddr
) return SOCKET_ERROR
;
8360 if (!string
|| !lenstr
) return SOCKET_ERROR
;
8362 switch(sockaddr
->sa_family
)
8366 unsigned int long_ip
= ntohl(((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
);
8367 if (len
< sizeof(SOCKADDR_IN
)) return SOCKET_ERROR
;
8368 sprintf( buffer
, "%u.%u.%u.%u:%u",
8369 (long_ip
>> 24) & 0xff,
8370 (long_ip
>> 16) & 0xff,
8371 (long_ip
>> 8) & 0xff,
8373 ntohs( ((SOCKADDR_IN
*)sockaddr
)->sin_port
) );
8375 p
= strchr( buffer
, ':' );
8376 if (!((SOCKADDR_IN
*)sockaddr
)->sin_port
) *p
= 0;
8381 struct WS_sockaddr_in6
*sockaddr6
= (LPSOCKADDR_IN6
) sockaddr
;
8385 if (len
< sizeof(SOCKADDR_IN6
)) return SOCKET_ERROR
;
8386 if ((sockaddr6
->sin6_port
))
8387 strcpy(buffer
, "[");
8388 slen
= strlen(buffer
);
8389 if (!WS_inet_ntop(WS_AF_INET6
, &sockaddr6
->sin6_addr
, &buffer
[slen
], sizeof(buffer
) - slen
))
8391 SetLastError(WSAEINVAL
);
8392 return SOCKET_ERROR
;
8394 if ((sockaddr6
->sin6_scope_id
))
8395 sprintf(buffer
+strlen(buffer
), "%%%u", sockaddr6
->sin6_scope_id
);
8396 if ((sockaddr6
->sin6_port
))
8397 sprintf(buffer
+strlen(buffer
), "]:%u", ntohs(sockaddr6
->sin6_port
));
8402 SetLastError(WSAEINVAL
);
8403 return SOCKET_ERROR
;
8406 size
= strlen( buffer
) + 1;
8411 SetLastError(WSAEFAULT
);
8412 return SOCKET_ERROR
;
8415 TRACE("=> %s,%u bytes\n", debugstr_a(buffer
), size
);
8417 strcpy( string
, buffer
);
8421 /***********************************************************************
8422 * WSAAddressToStringW (WS2_32.28)
8424 * Convert a sockaddr address into a readable address string.
8427 * sockaddr [I] Pointer to a sockaddr structure.
8428 * len [I] Size of the sockaddr structure.
8429 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
8430 * string [I/O] Pointer to a buffer to receive the address string.
8431 * lenstr [I/O] Size of the receive buffer in WCHARs.
8435 * Failure: SOCKET_ERROR
8438 * The 'info' parameter is ignored.
8440 INT WINAPI
WSAAddressToStringW( LPSOCKADDR sockaddr
, DWORD len
,
8441 LPWSAPROTOCOL_INFOW info
, LPWSTR string
,
8446 WCHAR buffer
[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8449 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr
, len
, info
, string
, lenstr
);
8452 ret
= WSAAddressToStringA(sockaddr
, len
, NULL
, bufAddr
, &size
);
8454 if (ret
) return ret
;
8456 MultiByteToWideChar( CP_ACP
, 0, bufAddr
, size
, buffer
, sizeof( buffer
)/sizeof(WCHAR
));
8461 SetLastError(WSAEFAULT
);
8462 return SOCKET_ERROR
;
8465 TRACE("=> %s,%u bytes\n", debugstr_w(buffer
), size
);
8467 lstrcpyW( string
, buffer
);
8471 /***********************************************************************
8472 * WSAEnumNameSpaceProvidersA (WS2_32.34)
8474 INT WINAPI
WSAEnumNameSpaceProvidersA( LPDWORD len
, LPWSANAMESPACE_INFOA buffer
)
8476 FIXME( "(%p %p) Stub!\n", len
, buffer
);
8480 /***********************************************************************
8481 * WSAEnumNameSpaceProvidersW (WS2_32.35)
8483 INT WINAPI
WSAEnumNameSpaceProvidersW( LPDWORD len
, LPWSANAMESPACE_INFOW buffer
)
8485 FIXME( "(%p %p) Stub!\n", len
, buffer
);
8489 /***********************************************************************
8490 * WSAGetQOSByName (WS2_32.41)
8492 BOOL WINAPI
WSAGetQOSByName( SOCKET s
, LPWSABUF lpQOSName
, LPQOS lpQOS
)
8494 FIXME( "(0x%04lx %p %p) Stub!\n", s
, lpQOSName
, lpQOS
);
8498 /***********************************************************************
8499 * WSAGetServiceClassInfoA (WS2_32.42)
8501 INT WINAPI
WSAGetServiceClassInfoA( LPGUID provider
, LPGUID service
, LPDWORD len
,
8502 LPWSASERVICECLASSINFOA info
)
8504 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider
), debugstr_guid(service
),
8506 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8507 return SOCKET_ERROR
;
8510 /***********************************************************************
8511 * WSAGetServiceClassInfoW (WS2_32.43)
8513 INT WINAPI
WSAGetServiceClassInfoW( LPGUID provider
, LPGUID service
, LPDWORD len
,
8514 LPWSASERVICECLASSINFOW info
)
8516 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider
), debugstr_guid(service
),
8518 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8519 return SOCKET_ERROR
;
8522 /***********************************************************************
8523 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
8525 INT WINAPI
WSAGetServiceClassNameByClassIdA( LPGUID
class, LPSTR service
, LPDWORD len
)
8527 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service
, len
);
8528 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8529 return SOCKET_ERROR
;
8532 /***********************************************************************
8533 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
8535 INT WINAPI
WSAGetServiceClassNameByClassIdW( LPGUID
class, LPWSTR service
, LPDWORD len
)
8537 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service
, len
);
8538 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8539 return SOCKET_ERROR
;
8542 /***********************************************************************
8543 * WSALookupServiceBeginA (WS2_32.59)
8545 INT WINAPI
WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions
,
8546 DWORD dwControlFlags
,
8549 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions
, dwControlFlags
,
8551 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8552 return SOCKET_ERROR
;
8555 /***********************************************************************
8556 * WSALookupServiceBeginW (WS2_32.60)
8558 INT WINAPI
WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions
,
8559 DWORD dwControlFlags
,
8562 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions
, dwControlFlags
,
8564 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8565 return SOCKET_ERROR
;
8568 /***********************************************************************
8569 * WSALookupServiceEnd (WS2_32.61)
8571 INT WINAPI
WSALookupServiceEnd( HANDLE lookup
)
8573 FIXME("(%p) Stub!\n", lookup
);
8577 /***********************************************************************
8578 * WSALookupServiceNextA (WS2_32.62)
8580 INT WINAPI
WSALookupServiceNextA( HANDLE lookup
, DWORD flags
, LPDWORD len
, LPWSAQUERYSETA results
)
8582 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup
, flags
, len
, results
);
8583 SetLastError(WSA_E_NO_MORE
);
8584 return SOCKET_ERROR
;
8587 /***********************************************************************
8588 * WSALookupServiceNextW (WS2_32.63)
8590 INT WINAPI
WSALookupServiceNextW( HANDLE lookup
, DWORD flags
, LPDWORD len
, LPWSAQUERYSETW results
)
8592 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup
, flags
, len
, results
);
8593 SetLastError(WSA_E_NO_MORE
);
8594 return SOCKET_ERROR
;
8597 /***********************************************************************
8598 * WSANtohl (WS2_32.64)
8600 INT WINAPI
WSANtohl( SOCKET s
, WS_u_long netlong
, WS_u_long
* lphostlong
)
8602 TRACE( "(%04lx 0x%08x %p)\n", s
, netlong
, lphostlong
);
8604 if (!lphostlong
) return WSAEFAULT
;
8606 *lphostlong
= ntohl( netlong
);
8610 /***********************************************************************
8611 * WSANtohs (WS2_32.65)
8613 INT WINAPI
WSANtohs( SOCKET s
, WS_u_short netshort
, WS_u_short
* lphostshort
)
8615 TRACE( "(%04lx 0x%08x %p)\n", s
, netshort
, lphostshort
);
8617 if (!lphostshort
) return WSAEFAULT
;
8619 *lphostshort
= ntohs( netshort
);
8623 /***********************************************************************
8624 * WSAProviderConfigChange (WS2_32.66)
8626 INT WINAPI
WSAProviderConfigChange( LPHANDLE handle
, LPWSAOVERLAPPED overlapped
,
8627 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
8629 FIXME( "(%p %p %p) Stub!\n", handle
, overlapped
, completion
);
8630 return SOCKET_ERROR
;
8633 /***********************************************************************
8634 * WSARecvDisconnect (WS2_32.68)
8636 INT WINAPI
WSARecvDisconnect( SOCKET s
, LPWSABUF disconnectdata
)
8638 TRACE( "(%04lx %p)\n", s
, disconnectdata
);
8640 return WS_shutdown( s
, SD_RECEIVE
);
8643 /***********************************************************************
8644 * WSASetServiceA (WS2_32.76)
8646 INT WINAPI
WSASetServiceA( LPWSAQUERYSETA query
, WSAESETSERVICEOP operation
, DWORD flags
)
8648 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query
, operation
, flags
);
8652 /***********************************************************************
8653 * WSASetServiceW (WS2_32.77)
8655 INT WINAPI
WSASetServiceW( LPWSAQUERYSETW query
, WSAESETSERVICEOP operation
, DWORD flags
)
8657 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query
, operation
, flags
);
8661 /***********************************************************************
8662 * WSCEnableNSProvider (WS2_32.84)
8664 INT WINAPI
WSCEnableNSProvider( LPGUID provider
, BOOL enable
)
8666 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider
), enable
);
8670 /***********************************************************************
8671 * WSCGetProviderPath (WS2_32.86)
8673 INT WINAPI
WSCGetProviderPath( LPGUID provider
, LPWSTR path
, LPINT len
, LPINT errcode
)
8675 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider
), path
, len
, errcode
);
8677 if (!errcode
|| !provider
|| !len
) return WSAEFAULT
;
8679 *errcode
= WSAEINVAL
;
8680 return SOCKET_ERROR
;
8683 /***********************************************************************
8684 * WSCInstallNameSpace (WS2_32.87)
8686 INT WINAPI
WSCInstallNameSpace( LPWSTR identifier
, LPWSTR path
, DWORD
namespace,
8687 DWORD version
, LPGUID provider
)
8689 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier
), debugstr_w(path
),
8690 namespace, version
, debugstr_guid(provider
) );
8694 /***********************************************************************
8695 * WSCUnInstallNameSpace (WS2_32.89)
8697 INT WINAPI
WSCUnInstallNameSpace( LPGUID lpProviderId
)
8699 FIXME("(%s) Stub!\n", debugstr_guid(lpProviderId
));
8703 /***********************************************************************
8704 * WSCWriteProviderOrder (WS2_32.91)
8706 INT WINAPI
WSCWriteProviderOrder( LPDWORD entry
, DWORD number
)
8708 FIXME("(%p 0x%08x) Stub!\n", entry
, number
);
8712 /***********************************************************************
8713 * WSANSPIoctl (WS2_32.91)
8715 INT WINAPI
WSANSPIoctl( HANDLE hLookup
, DWORD dwControlCode
, LPVOID lpvInBuffer
,
8716 DWORD cbInBuffer
, LPVOID lpvOutBuffer
, DWORD cbOutBuffer
,
8717 LPDWORD lpcbBytesReturned
, LPWSACOMPLETION lpCompletion
)
8719 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup
, dwControlCode
,
8720 lpvInBuffer
, cbInBuffer
, lpvOutBuffer
, cbOutBuffer
, lpcbBytesReturned
, lpCompletion
);
8721 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8722 return SOCKET_ERROR
;
8725 /*****************************************************************************
8726 * WSAEnumProtocolsA [WS2_32.@]
8728 * see function WSAEnumProtocolsW
8730 INT WINAPI
WSAEnumProtocolsA( LPINT protocols
, LPWSAPROTOCOL_INFOA buffer
, LPDWORD len
)
8732 return WS_EnumProtocols( FALSE
, protocols
, (LPWSAPROTOCOL_INFOW
) buffer
, len
);
8735 /*****************************************************************************
8736 * WSAEnumProtocolsW [WS2_32.@]
8738 * Retrieves information about specified set of active network protocols.
8741 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
8742 * retrieves information on all available protocols.
8743 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
8745 * len [I/O] Pointer to a variable specifying buffer size. On output
8746 * the variable holds the number of bytes needed when the
8747 * specified size is too small.
8750 * Success: number of WSAPROTOCOL_INFO structures in buffer.
8751 * Failure: SOCKET_ERROR
8754 * NT4SP5 does not return SPX if protocols == NULL
8757 * - NT4SP5 returns in addition these list of NETBIOS protocols
8758 * (address family 17), each entry two times one for socket type 2 and 5
8760 * iProtocol szProtocol
8761 * 0x80000000 \Device\NwlnkNb
8762 * 0xfffffffa \Device\NetBT_CBENT7
8763 * 0xfffffffb \Device\Nbf_CBENT7
8764 * 0xfffffffc \Device\NetBT_NdisWan5
8765 * 0xfffffffd \Device\NetBT_El9202
8766 * 0xfffffffe \Device\Nbf_El9202
8767 * 0xffffffff \Device\Nbf_NdisWan4
8769 * - there is no check that the operating system supports the returned
8772 INT WINAPI
WSAEnumProtocolsW( LPINT protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
)
8774 return WS_EnumProtocols( TRUE
, protocols
, buffer
, len
);
8777 /*****************************************************************************
8778 * WSCEnumProtocols [WS2_32.@]
8781 * protocols [I] Null-terminated array of iProtocol values.
8782 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
8783 * len [I/O] Size of buffer on input/output.
8784 * errno [O] Error code.
8787 * Success: number of protocols to be reported on.
8788 * Failure: SOCKET_ERROR. error is in errno.
8791 * Doesn't supply info on layered protocols.
8794 INT WINAPI
WSCEnumProtocols( LPINT protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
, LPINT err
)
8796 INT ret
= WSAEnumProtocolsW( protocols
, buffer
, len
);
8798 if (ret
== SOCKET_ERROR
) *err
= WSAENOBUFS
;