2 * based on Windows Sockets 1.1 specs
4 * Copyright (C) 1993,1994,1996,1997 John Brezak, Erik Bos, Alex Korobka.
5 * Copyright (C) 2001 Stefan Leichter
6 * Copyright (C) 2004 Hans Leidekker
7 * Copyright (C) 2005 Marcus Meissner
8 * Copyright (C) 2006-2008 Kai Blin
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 * NOTE: If you make any changes to fix a particular app, make sure
25 * they don't break something else like Netscape or telnet and ftp
26 * clients and servers (www.winsite.com got a lot of those).
30 #include "wine/port.h"
35 #include <sys/types.h>
40 #ifdef HAVE_SYS_IOCTL_H
41 # include <sys/ioctl.h>
43 #ifdef HAVE_SYS_FILIO_H
44 # include <sys/filio.h>
46 #ifdef HAVE_SYS_SOCKIO_H
47 # include <sys/sockio.h>
51 # include <sys/so_ioctl.h>
54 #ifdef HAVE_SYS_PARAM_H
55 # include <sys/param.h>
61 #ifdef HAVE_SYS_WAIT_H
62 # include <sys/wait.h>
67 #ifdef HAVE_SYS_SOCKET_H
68 #include <sys/socket.h>
70 #ifdef HAVE_NETINET_IN_H
71 # include <netinet/in.h>
73 #ifdef HAVE_NETINET_TCP_H
74 # include <netinet/tcp.h>
76 #ifdef HAVE_ARPA_INET_H
77 # include <arpa/inet.h>
89 #ifdef HAVE_ARPA_NAMESER_H
90 # include <arpa/nameser.h>
98 #ifdef HAVE_LINUX_FILTER_H
99 # include <linux/filter.h>
102 #ifdef HAVE_NETIPX_IPX_H
103 # include <netipx/ipx.h>
104 #elif defined(HAVE_LINUX_IPX_H)
105 # ifdef HAVE_ASM_TYPES_H
106 # include <asm/types.h>
108 # ifdef HAVE_LINUX_TYPES_H
109 # include <linux/types.h>
111 # include <linux/ipx.h>
113 #if defined(SOL_IPX) || defined(SO_DEFAULT_HEADERS)
117 #ifdef HAVE_LINUX_IRDA_H
118 # ifdef HAVE_LINUX_TYPES_H
119 # include <linux/types.h>
121 # include <linux/irda.h>
128 #ifdef HAVE_SYS_POLL_H
129 # include <sys/poll.h>
131 #ifdef HAVE_SYS_TIME_H
132 # include <sys/time.h>
135 #define NONAMELESSUNION
136 #define NONAMELESSSTRUCT
137 #include "ntstatus.h"
138 #define WIN32_NO_STATUS
143 #include "winerror.h"
145 #include "winsock2.h"
147 #include "ws2tcpip.h"
150 #include "wsnwlink.h"
151 #include "wshisotp.h"
155 #define USE_WC_PREFIX /* For CMSG_DATA */
156 #include "iphlpapi.h"
157 #include "wine/server.h"
158 #include "wine/debug.h"
159 #include "wine/exception.h"
160 #include "wine/unicode.h"
162 #if defined(linux) && !defined(IP_UNICAST_IF)
163 #define IP_UNICAST_IF 50
166 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
167 # define sipx_network sipx_addr.x_net
168 # define sipx_node sipx_addr.x_host.c_host
169 #endif /* __FreeBSD__ */
172 #define INADDR_NONE ~0UL
175 #if !defined(TCP_KEEPIDLE) && defined(TCP_KEEPALIVE)
176 /* TCP_KEEPALIVE is the Mac OS name for TCP_KEEPIDLE */
177 #define TCP_KEEPIDLE TCP_KEEPALIVE
180 #define FILE_USE_FILE_POINTER_POSITION ((LONGLONG)-2)
182 WINE_DEFAULT_DEBUG_CHANNEL(winsock
);
183 WINE_DECLARE_DEBUG_CHANNEL(winediag
);
185 /* names of the protocols */
186 static const WCHAR NameIpxW
[] = {'I', 'P', 'X', '\0'};
187 static const WCHAR NameSpxW
[] = {'S', 'P', 'X', '\0'};
188 static const WCHAR NameSpxIIW
[] = {'S', 'P', 'X', ' ', 'I', 'I', '\0'};
189 static const WCHAR NameTcpW
[] = {'T', 'C', 'P', '/', 'I', 'P', '\0'};
190 static const WCHAR NameUdpW
[] = {'U', 'D', 'P', '/', 'I', 'P', '\0'};
192 /* Taken from Win2k */
193 static const GUID ProviderIdIP
= { 0xe70f1aa0, 0xab8b, 0x11cf,
194 { 0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
195 static const GUID ProviderIdIPX
= { 0x11058240, 0xbe47, 0x11cf,
196 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
197 static const GUID ProviderIdSPX
= { 0x11058241, 0xbe47, 0x11cf,
198 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
200 static const INT valid_protocols
[] =
210 #define IS_IPX_PROTO(X) ((X) >= WS_NSPROTO_IPX && (X) <= WS_NSPROTO_IPX + 255)
212 #if defined(IP_UNICAST_IF) && defined(SO_ATTACH_FILTER)
213 # define LINUX_BOUND_IF
214 struct interface_filter
{
215 struct sock_filter iface_memaddr
;
216 struct sock_filter iface_rule
;
217 struct sock_filter ip_memaddr
;
218 struct sock_filter ip_rule
;
219 struct sock_filter return_keep
;
220 struct sock_filter return_dump
;
222 # define FILTER_JUMP_DUMP(here) (u_char)(offsetof(struct interface_filter, return_dump) \
223 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
224 /sizeof(struct sock_filter)
225 # define FILTER_JUMP_KEEP(here) (u_char)(offsetof(struct interface_filter, return_keep) \
226 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
227 /sizeof(struct sock_filter)
228 # define FILTER_JUMP_NEXT() (u_char)(0)
229 # define SKF_NET_DESTIP 16 /* offset in the network header to the destination IP */
230 static struct interface_filter generic_interface_filter
= {
231 /* This filter rule allows incoming packets on the specified interface, which works for all
232 * remotely generated packets and for locally generated broadcast packets. */
233 BPF_STMT(BPF_LD
+BPF_W
+BPF_ABS
, SKF_AD_OFF
+SKF_AD_IFINDEX
),
234 BPF_JUMP(BPF_JMP
+BPF_JEQ
+BPF_K
, 0xdeadbeef, FILTER_JUMP_KEEP(iface_rule
), FILTER_JUMP_NEXT()),
235 /* This rule allows locally generated packets targeted at the specific IP address of the chosen
236 * adapter (local packets not destined for the broadcast address do not have IFINDEX set) */
237 BPF_STMT(BPF_LD
+BPF_W
+BPF_ABS
, SKF_NET_OFF
+SKF_NET_DESTIP
),
238 BPF_JUMP(BPF_JMP
+BPF_JEQ
+BPF_K
, 0xdeadbeef, FILTER_JUMP_KEEP(ip_rule
), FILTER_JUMP_DUMP(ip_rule
)),
239 BPF_STMT(BPF_RET
+BPF_K
, (u_int
)-1), /* keep packet */
240 BPF_STMT(BPF_RET
+BPF_K
, 0) /* dump packet */
242 #endif /* LINUX_BOUND_IF */
245 * The actual definition of WSASendTo, wrapped in a different function name
246 * so that internal calls from ws2_32 itself will not trigger programs like
247 * Garena, which hooks WSASendTo/WSARecvFrom calls.
249 static int WS2_sendto( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
250 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
251 const struct WS_sockaddr
*to
, int tolen
,
252 LPWSAOVERLAPPED lpOverlapped
,
253 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);
256 * Internal fundamental receive function, essentially WSARecvFrom with an
257 * additional parameter to support message control headers.
259 static int WS2_recv_base( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
260 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
,
261 struct WS_sockaddr
*lpFrom
,
262 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
263 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
,
264 LPWSABUF lpControlBuffer
);
266 /* critical section to protect some non-reentrant net function */
267 static CRITICAL_SECTION csWSgetXXXbyYYY
;
268 static CRITICAL_SECTION_DEBUG critsect_debug
=
270 0, 0, &csWSgetXXXbyYYY
,
271 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
272 0, 0, { (DWORD_PTR
)(__FILE__
": csWSgetXXXbyYYY") }
274 static CRITICAL_SECTION csWSgetXXXbyYYY
= { &critsect_debug
, -1, 0, 0, 0, 0 };
276 union generic_unix_sockaddr
278 struct sockaddr addr
;
279 char data
[128]; /* should be big enough for all families */
282 static inline const char *debugstr_sockaddr( const struct WS_sockaddr
*a
)
284 if (!a
) return "(nil)";
285 switch (a
->sa_family
)
291 struct WS_sockaddr_in
*sin
= (struct WS_sockaddr_in
*)a
;
293 p
= WS_inet_ntop( WS_AF_INET
, &sin
->sin_addr
, buf
, sizeof(buf
) );
295 p
= "(unknown IPv4 address)";
297 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
298 p
, ntohs(sin
->sin_port
));
304 struct WS_sockaddr_in6
*sin
= (struct WS_sockaddr_in6
*)a
;
306 p
= WS_inet_ntop( WS_AF_INET6
, &sin
->sin6_addr
, buf
, sizeof(buf
) );
308 p
= "(unknown IPv6 address)";
309 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
310 p
, ntohs(sin
->sin6_port
));
315 char netnum
[16], nodenum
[16];
316 struct WS_sockaddr_ipx
*sin
= (struct WS_sockaddr_ipx
*)a
;
318 for (i
= 0;i
< 4; i
++) sprintf(netnum
+ i
* 2, "%02X", (unsigned char) sin
->sa_netnum
[i
]);
319 for (i
= 0;i
< 6; i
++) sprintf(nodenum
+ i
* 2, "%02X", (unsigned char) sin
->sa_nodenum
[i
]);
321 return wine_dbg_sprintf("{ family AF_IPX, address %s.%s, ipx socket %d }",
322 netnum
, nodenum
, sin
->sa_socket
);
328 memcpy( &addr
, ((const SOCKADDR_IRDA
*)a
)->irdaDeviceID
, sizeof(addr
) );
329 addr
= ntohl( addr
);
330 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
332 ((const SOCKADDR_IRDA
*)a
)->irdaServiceName
);
335 return wine_dbg_sprintf("{ family %d }", a
->sa_family
);
339 static inline const char *debugstr_sockopt(int level
, int optname
)
341 const char *stropt
= NULL
, *strlevel
= NULL
;
343 #define DEBUG_SOCKLEVEL(x) case (x): strlevel = #x
344 #define DEBUG_SOCKOPT(x) case (x): stropt = #x; break
348 DEBUG_SOCKLEVEL(WS_SOL_SOCKET
);
351 DEBUG_SOCKOPT(WS_SO_ACCEPTCONN
);
352 DEBUG_SOCKOPT(WS_SO_BROADCAST
);
353 DEBUG_SOCKOPT(WS_SO_BSP_STATE
);
354 DEBUG_SOCKOPT(WS_SO_CONDITIONAL_ACCEPT
);
355 DEBUG_SOCKOPT(WS_SO_CONNECT_TIME
);
356 DEBUG_SOCKOPT(WS_SO_DEBUG
);
357 DEBUG_SOCKOPT(WS_SO_DONTLINGER
);
358 DEBUG_SOCKOPT(WS_SO_DONTROUTE
);
359 DEBUG_SOCKOPT(WS_SO_ERROR
);
360 DEBUG_SOCKOPT(WS_SO_EXCLUSIVEADDRUSE
);
361 DEBUG_SOCKOPT(WS_SO_GROUP_ID
);
362 DEBUG_SOCKOPT(WS_SO_GROUP_PRIORITY
);
363 DEBUG_SOCKOPT(WS_SO_KEEPALIVE
);
364 DEBUG_SOCKOPT(WS_SO_LINGER
);
365 DEBUG_SOCKOPT(WS_SO_MAX_MSG_SIZE
);
366 DEBUG_SOCKOPT(WS_SO_OOBINLINE
);
367 DEBUG_SOCKOPT(WS_SO_OPENTYPE
);
368 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOA
);
369 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOW
);
370 DEBUG_SOCKOPT(WS_SO_RCVBUF
);
371 DEBUG_SOCKOPT(WS_SO_RCVTIMEO
);
372 DEBUG_SOCKOPT(WS_SO_REUSEADDR
);
373 DEBUG_SOCKOPT(WS_SO_SNDBUF
);
374 DEBUG_SOCKOPT(WS_SO_SNDTIMEO
);
375 DEBUG_SOCKOPT(WS_SO_TYPE
);
376 DEBUG_SOCKOPT(WS_SO_UPDATE_CONNECT_CONTEXT
);
380 DEBUG_SOCKLEVEL(WS_NSPROTO_IPX
);
383 DEBUG_SOCKOPT(WS_IPX_PTYPE
);
384 DEBUG_SOCKOPT(WS_IPX_FILTERPTYPE
);
385 DEBUG_SOCKOPT(WS_IPX_DSTYPE
);
386 DEBUG_SOCKOPT(WS_IPX_RECVHDR
);
387 DEBUG_SOCKOPT(WS_IPX_MAXSIZE
);
388 DEBUG_SOCKOPT(WS_IPX_ADDRESS
);
389 DEBUG_SOCKOPT(WS_IPX_MAX_ADAPTER_NUM
);
393 DEBUG_SOCKLEVEL(WS_SOL_IRLMP
);
396 DEBUG_SOCKOPT(WS_IRLMP_ENUMDEVICES
);
400 DEBUG_SOCKLEVEL(WS_IPPROTO_TCP
);
403 DEBUG_SOCKOPT(WS_TCP_BSDURGENT
);
404 DEBUG_SOCKOPT(WS_TCP_EXPEDITED_1122
);
405 DEBUG_SOCKOPT(WS_TCP_NODELAY
);
409 DEBUG_SOCKLEVEL(WS_IPPROTO_IP
);
412 DEBUG_SOCKOPT(WS_IP_ADD_MEMBERSHIP
);
413 DEBUG_SOCKOPT(WS_IP_DONTFRAGMENT
);
414 DEBUG_SOCKOPT(WS_IP_DROP_MEMBERSHIP
);
415 DEBUG_SOCKOPT(WS_IP_HDRINCL
);
416 DEBUG_SOCKOPT(WS_IP_MULTICAST_IF
);
417 DEBUG_SOCKOPT(WS_IP_MULTICAST_LOOP
);
418 DEBUG_SOCKOPT(WS_IP_MULTICAST_TTL
);
419 DEBUG_SOCKOPT(WS_IP_OPTIONS
);
420 DEBUG_SOCKOPT(WS_IP_PKTINFO
);
421 DEBUG_SOCKOPT(WS_IP_RECEIVE_BROADCAST
);
422 DEBUG_SOCKOPT(WS_IP_TOS
);
423 DEBUG_SOCKOPT(WS_IP_TTL
);
424 DEBUG_SOCKOPT(WS_IP_UNICAST_IF
);
428 DEBUG_SOCKLEVEL(WS_IPPROTO_IPV6
);
431 DEBUG_SOCKOPT(WS_IPV6_ADD_MEMBERSHIP
);
432 DEBUG_SOCKOPT(WS_IPV6_DROP_MEMBERSHIP
);
433 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_IF
);
434 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_HOPS
);
435 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_LOOP
);
436 DEBUG_SOCKOPT(WS_IPV6_UNICAST_HOPS
);
437 DEBUG_SOCKOPT(WS_IPV6_V6ONLY
);
438 DEBUG_SOCKOPT(WS_IPV6_UNICAST_IF
);
439 DEBUG_SOCKOPT(WS_IPV6_DONTFRAG
);
443 #undef DEBUG_SOCKLEVEL
447 strlevel
= wine_dbg_sprintf("WS_0x%x", level
);
449 stropt
= wine_dbg_sprintf("WS_0x%x", optname
);
451 return wine_dbg_sprintf("level %s, name %s", strlevel
+ 3, stropt
+ 3);
454 static inline const char *debugstr_optval(const char *optval
, int optlenval
)
456 if (optval
&& !IS_INTRESOURCE(optval
) && optlenval
>= 1 && optlenval
<= sizeof(DWORD
))
459 memcpy(&value
, optval
, optlenval
);
460 return wine_dbg_sprintf("%p (%u)", optval
, value
);
462 return wine_dbg_sprintf("%p", optval
);
465 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
466 #define SOCKET2HANDLE(s) ((HANDLE)(s))
467 #define HANDLE2SOCKET(h) ((SOCKET)(h))
469 /****************************************************************
470 * Async IO declarations
471 ****************************************************************/
473 typedef NTSTATUS
async_callback_t( void *user
, IO_STATUS_BLOCK
*io
, NTSTATUS status
);
477 async_callback_t
*callback
; /* must be the first field */
478 struct ws2_async_io
*next
;
481 struct ws2_async_shutdown
483 struct ws2_async_io io
;
485 IO_STATUS_BLOCK iosb
;
491 struct ws2_async_io io
;
493 LPWSAOVERLAPPED user_overlapped
;
494 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func
;
495 IO_STATUS_BLOCK local_iosb
;
496 struct WS_sockaddr
*addr
;
499 int val
; /* for send operations */
500 int *ptr
; /* for recv operations */
505 unsigned int n_iovecs
;
506 unsigned int first_iovec
;
507 struct iovec iovec
[1];
510 struct ws2_accept_async
512 struct ws2_async_io io
;
513 HANDLE listen_socket
;
514 HANDLE accept_socket
;
515 LPOVERLAPPED user_overlapped
;
517 PVOID buf
; /* buffer to write data to */
521 struct ws2_async
*read
;
524 struct ws2_transmitfile_async
526 struct ws2_async_io io
;
531 DWORD bytes_per_send
;
532 TRANSMIT_FILE_BUFFERS buffers
;
534 LARGE_INTEGER offset
;
535 struct ws2_async write
;
538 static struct ws2_async_io
*async_io_freelist
;
540 static void release_async_io( struct ws2_async_io
*io
)
544 struct ws2_async_io
*next
= async_io_freelist
;
546 if (InterlockedCompareExchangePointer( (void **)&async_io_freelist
, io
, next
) == next
) return;
550 static struct ws2_async_io
*alloc_async_io( DWORD size
, async_callback_t callback
)
552 /* first free remaining previous fileinfos */
554 struct ws2_async_io
*io
= InterlockedExchangePointer( (void **)&async_io_freelist
, NULL
);
558 struct ws2_async_io
*next
= io
->next
;
559 HeapFree( GetProcessHeap(), 0, io
);
563 io
= HeapAlloc( GetProcessHeap(), 0, size
);
564 if (io
) io
->callback
= callback
;
568 static NTSTATUS
register_async( int type
, HANDLE handle
, struct ws2_async_io
*async
, HANDLE event
,
569 PIO_APC_ROUTINE apc
, void *apc_context
, IO_STATUS_BLOCK
*io
)
573 SERVER_START_REQ( register_async
)
576 req
->async
.handle
= wine_server_obj_handle( handle
);
577 req
->async
.user
= wine_server_client_ptr( async
);
578 req
->async
.iosb
= wine_server_client_ptr( io
);
579 req
->async
.event
= wine_server_obj_handle( event
);
580 req
->async
.apc
= wine_server_client_ptr( apc
);
581 req
->async
.apc_context
= wine_server_client_ptr( apc_context
);
582 status
= wine_server_call( req
);
589 /****************************************************************/
591 /* ----------------------------------- internal data */
593 /* ws_... struct conversion flags */
595 typedef struct /* WSAAsyncSelect() control struct */
597 HANDLE service
, event
, sock
;
603 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
604 #define WS_MAX_UDP_DATAGRAM 1024
605 static INT WINAPI
WSA_DefaultBlockingHook( FARPROC x
);
607 /* hostent's, servent's and protent's are stored in one buffer per thread,
608 * as documented on MSDN for the functions that return any of the buffers */
609 struct per_thread_data
612 struct WS_hostent
*he_buffer
;
613 struct WS_servent
*se_buffer
;
614 struct WS_protoent
*pe_buffer
;
615 struct pollfd
*fd_cache
;
616 unsigned int fd_count
;
620 char ntoa_buffer
[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
623 /* internal: routing description information */
627 DWORD metric
, default_route
;
630 static INT num_startup
; /* reference counter */
631 static FARPROC blocking_hook
= (FARPROC
)WSA_DefaultBlockingHook
;
633 /* function prototypes */
634 static struct WS_hostent
*WS_create_he(char *name
, int aliases
, int aliases_size
, int addresses
, int address_length
);
635 static struct WS_hostent
*WS_dup_he(const struct hostent
* p_he
);
636 static struct WS_protoent
*WS_dup_pe(const struct protoent
* p_pe
);
637 static struct WS_servent
*WS_dup_se(const struct servent
* p_se
);
638 static int ws_protocol_info(SOCKET s
, int unicode
, WSAPROTOCOL_INFOW
*buffer
, int *size
);
640 int WSAIOCTL_GetInterfaceCount(void);
641 int WSAIOCTL_GetInterfaceName(int intNumber
, char *intName
);
643 static void WS_AddCompletion( SOCKET sock
, ULONG_PTR CompletionValue
, NTSTATUS CompletionStatus
, ULONG Information
);
645 #define MAP_OPTION(opt) { WS_##opt, opt }
647 static const int ws_flags_map
[][2] =
649 MAP_OPTION( MSG_OOB
),
650 MAP_OPTION( MSG_PEEK
),
651 MAP_OPTION( MSG_DONTROUTE
),
652 MAP_OPTION( MSG_WAITALL
),
653 { WS_MSG_PARTIAL
, 0 },
656 static const int ws_sock_map
[][2] =
658 MAP_OPTION( SO_DEBUG
),
659 MAP_OPTION( SO_ACCEPTCONN
),
660 MAP_OPTION( SO_REUSEADDR
),
661 MAP_OPTION( SO_KEEPALIVE
),
662 MAP_OPTION( SO_DONTROUTE
),
663 MAP_OPTION( SO_BROADCAST
),
664 MAP_OPTION( SO_LINGER
),
665 MAP_OPTION( SO_OOBINLINE
),
666 MAP_OPTION( SO_SNDBUF
),
667 MAP_OPTION( SO_RCVBUF
),
668 MAP_OPTION( SO_ERROR
),
669 MAP_OPTION( SO_TYPE
),
671 MAP_OPTION( SO_RCVTIMEO
),
674 MAP_OPTION( SO_SNDTIMEO
),
678 static const int ws_tcp_map
[][2] =
681 MAP_OPTION( TCP_NODELAY
),
685 static const int ws_ip_map
[][2] =
687 MAP_OPTION( IP_MULTICAST_IF
),
688 MAP_OPTION( IP_MULTICAST_TTL
),
689 MAP_OPTION( IP_MULTICAST_LOOP
),
690 MAP_OPTION( IP_ADD_MEMBERSHIP
),
691 MAP_OPTION( IP_DROP_MEMBERSHIP
),
692 MAP_OPTION( IP_OPTIONS
),
694 MAP_OPTION( IP_HDRINCL
),
696 MAP_OPTION( IP_TOS
),
697 MAP_OPTION( IP_TTL
),
699 MAP_OPTION( IP_PKTINFO
),
702 MAP_OPTION( IP_UNICAST_IF
),
706 static const int ws_ipv6_map
[][2] =
708 #ifdef IPV6_ADD_MEMBERSHIP
709 MAP_OPTION( IPV6_ADD_MEMBERSHIP
),
711 #ifdef IPV6_DROP_MEMBERSHIP
712 MAP_OPTION( IPV6_DROP_MEMBERSHIP
),
714 MAP_OPTION( IPV6_MULTICAST_IF
),
715 MAP_OPTION( IPV6_MULTICAST_HOPS
),
716 MAP_OPTION( IPV6_MULTICAST_LOOP
),
717 MAP_OPTION( IPV6_UNICAST_HOPS
),
718 MAP_OPTION( IPV6_V6ONLY
),
719 #ifdef IPV6_UNICAST_IF
720 MAP_OPTION( IPV6_UNICAST_IF
),
724 static const int ws_af_map
[][2] =
726 MAP_OPTION( AF_UNSPEC
),
727 MAP_OPTION( AF_INET
),
728 MAP_OPTION( AF_INET6
),
730 MAP_OPTION( AF_IPX
),
733 MAP_OPTION( AF_IRDA
),
735 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
738 static const int ws_socktype_map
[][2] =
740 MAP_OPTION( SOCK_DGRAM
),
741 MAP_OPTION( SOCK_STREAM
),
742 MAP_OPTION( SOCK_RAW
),
743 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
746 static const int ws_proto_map
[][2] =
748 MAP_OPTION( IPPROTO_IP
),
749 MAP_OPTION( IPPROTO_TCP
),
750 MAP_OPTION( IPPROTO_UDP
),
751 MAP_OPTION( IPPROTO_IPV6
),
752 MAP_OPTION( IPPROTO_ICMP
),
753 MAP_OPTION( IPPROTO_IGMP
),
754 MAP_OPTION( IPPROTO_RAW
),
755 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
758 static const int ws_aiflag_map
[][2] =
760 MAP_OPTION( AI_PASSIVE
),
761 MAP_OPTION( AI_CANONNAME
),
762 MAP_OPTION( AI_NUMERICHOST
),
763 #ifdef AI_NUMERICSERV
764 MAP_OPTION( AI_NUMERICSERV
),
767 MAP_OPTION( AI_V4MAPPED
),
769 MAP_OPTION( AI_ADDRCONFIG
),
772 static const int ws_niflag_map
[][2] =
774 MAP_OPTION( NI_NOFQDN
),
775 MAP_OPTION( NI_NUMERICHOST
),
776 MAP_OPTION( NI_NAMEREQD
),
777 MAP_OPTION( NI_NUMERICSERV
),
778 MAP_OPTION( NI_DGRAM
),
781 static const int ws_eai_map
[][2] =
783 MAP_OPTION( EAI_AGAIN
),
784 MAP_OPTION( EAI_BADFLAGS
),
785 MAP_OPTION( EAI_FAIL
),
786 MAP_OPTION( EAI_FAMILY
),
787 MAP_OPTION( EAI_MEMORY
),
788 /* Note: EAI_NODATA is deprecated, but still
789 * used by Windows and Linux... We map the newer
790 * EAI_NONAME to EAI_NODATA for now until Windows
794 MAP_OPTION( EAI_NODATA
),
797 { WS_EAI_NODATA
, EAI_NONAME
},
800 MAP_OPTION( EAI_SERVICE
),
801 MAP_OPTION( EAI_SOCKTYPE
),
805 static const int ws_poll_map
[][2] =
807 MAP_OPTION( POLLERR
),
808 MAP_OPTION( POLLHUP
),
809 MAP_OPTION( POLLNVAL
),
810 MAP_OPTION( POLLWRNORM
),
811 MAP_OPTION( POLLWRBAND
),
812 MAP_OPTION( POLLRDNORM
),
813 { WS_POLLRDBAND
, POLLPRI
}
816 static const char magic_loopback_addr
[] = {127, 12, 34, 56};
818 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
820 static inline WSACMSGHDR
*fill_control_message(int level
, int type
, WSACMSGHDR
*current
, ULONG
*maxsize
, void *data
, int len
)
822 ULONG msgsize
= sizeof(WSACMSGHDR
) + WSA_CMSG_ALIGN(len
);
823 char *ptr
= (char *) current
+ sizeof(WSACMSGHDR
);
825 /* Make sure there is at least enough room for this entry */
826 if (msgsize
> *maxsize
)
829 /* Fill in the entry */
830 current
->cmsg_len
= sizeof(WSACMSGHDR
) + len
;
831 current
->cmsg_level
= level
;
832 current
->cmsg_type
= type
;
833 memcpy(ptr
, data
, len
);
834 /* Return the pointer to where next entry should go */
835 return (WSACMSGHDR
*) (ptr
+ WSA_CMSG_ALIGN(len
));
837 #endif /* IP_PKTINFO */
839 static inline int convert_control_headers(struct msghdr
*hdr
, WSABUF
*control
)
842 WSACMSGHDR
*cmsg_win
= (WSACMSGHDR
*) control
->buf
, *ptr
;
843 ULONG ctlsize
= control
->len
;
844 struct cmsghdr
*cmsg_unix
;
847 /* Loop over all the headers, converting as appropriate */
848 for (cmsg_unix
= CMSG_FIRSTHDR(hdr
); cmsg_unix
!= NULL
; cmsg_unix
= CMSG_NXTHDR(hdr
, cmsg_unix
))
850 switch(cmsg_unix
->cmsg_level
)
853 switch(cmsg_unix
->cmsg_type
)
857 /* Convert the Unix IP_PKTINFO structure to the Windows version */
858 struct in_pktinfo
*data_unix
= (struct in_pktinfo
*) CMSG_DATA(cmsg_unix
);
859 struct WS_in_pktinfo data_win
;
861 memcpy(&data_win
.ipi_addr
,&data_unix
->ipi_addr
.s_addr
,4); /* 4 bytes = 32 address bits */
862 data_win
.ipi_ifindex
= data_unix
->ipi_ifindex
;
863 ptr
= fill_control_message(WS_IPPROTO_IP
, WS_IP_PKTINFO
, ptr
, &ctlsize
,
864 (void*)&data_win
, sizeof(data_win
));
865 if (!ptr
) goto error
;
868 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix
->cmsg_type
);
873 FIXME("Unhandled message header level %d\n", cmsg_unix
->cmsg_level
);
879 /* Set the length of the returned control headers */
880 control
->len
= (ptr
== NULL
? 0 : (char*)ptr
- (char*)cmsg_win
);
881 return (ptr
!= NULL
);
882 #else /* IP_PKTINFO */
885 #endif /* IP_PKTINFO */
887 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
889 /* ----------------------------------- error handling */
891 static NTSTATUS
sock_get_ntstatus( int err
)
895 case EBADF
: return STATUS_INVALID_HANDLE
;
896 case EBUSY
: return STATUS_DEVICE_BUSY
;
898 case EACCES
: return STATUS_ACCESS_DENIED
;
899 case EFAULT
: return STATUS_NO_MEMORY
;
900 case EINVAL
: return STATUS_INVALID_PARAMETER
;
902 case EMFILE
: return STATUS_TOO_MANY_OPENED_FILES
;
903 case EWOULDBLOCK
: return STATUS_CANT_WAIT
;
904 case EINPROGRESS
: return STATUS_PENDING
;
905 case EALREADY
: return STATUS_NETWORK_BUSY
;
906 case ENOTSOCK
: return STATUS_OBJECT_TYPE_MISMATCH
;
907 case EDESTADDRREQ
: return STATUS_INVALID_PARAMETER
;
908 case EMSGSIZE
: return STATUS_BUFFER_OVERFLOW
;
909 case EPROTONOSUPPORT
:
910 case ESOCKTNOSUPPORT
:
913 case EPROTOTYPE
: return STATUS_NOT_SUPPORTED
;
914 case ENOPROTOOPT
: return STATUS_INVALID_PARAMETER
;
915 case EOPNOTSUPP
: return STATUS_NOT_SUPPORTED
;
916 case EADDRINUSE
: return STATUS_ADDRESS_ALREADY_ASSOCIATED
;
917 case EADDRNOTAVAIL
: return STATUS_INVALID_PARAMETER
;
918 case ECONNREFUSED
: return STATUS_CONNECTION_REFUSED
;
919 case ESHUTDOWN
: return STATUS_PIPE_DISCONNECTED
;
920 case ENOTCONN
: return STATUS_CONNECTION_DISCONNECTED
;
921 case ETIMEDOUT
: return STATUS_IO_TIMEOUT
;
922 case ENETUNREACH
: return STATUS_NETWORK_UNREACHABLE
;
923 case ENETDOWN
: return STATUS_NETWORK_BUSY
;
925 case ECONNRESET
: return STATUS_CONNECTION_RESET
;
926 case ECONNABORTED
: return STATUS_CONNECTION_ABORTED
;
928 case 0: return STATUS_SUCCESS
;
930 WARN("Unknown errno %d!\n", err
);
931 return STATUS_UNSUCCESSFUL
;
935 static UINT
sock_get_error( int err
)
939 case EINTR
: return WSAEINTR
;
941 case EACCES
: return WSAEACCES
;
942 case EFAULT
: return WSAEFAULT
;
943 case EINVAL
: return WSAEINVAL
;
944 case EMFILE
: return WSAEMFILE
;
945 case EWOULDBLOCK
: return WSAEWOULDBLOCK
;
946 case EINPROGRESS
: return WSAEINPROGRESS
;
947 case EALREADY
: return WSAEALREADY
;
949 case ENOTSOCK
: return WSAENOTSOCK
;
950 case EDESTADDRREQ
: return WSAEDESTADDRREQ
;
951 case EMSGSIZE
: return WSAEMSGSIZE
;
952 case EPROTOTYPE
: return WSAEPROTOTYPE
;
953 case ENOPROTOOPT
: return WSAENOPROTOOPT
;
954 case EPROTONOSUPPORT
: return WSAEPROTONOSUPPORT
;
955 case ESOCKTNOSUPPORT
: return WSAESOCKTNOSUPPORT
;
956 case EOPNOTSUPP
: return WSAEOPNOTSUPP
;
957 case EPFNOSUPPORT
: return WSAEPFNOSUPPORT
;
958 case EAFNOSUPPORT
: return WSAEAFNOSUPPORT
;
959 case EADDRINUSE
: return WSAEADDRINUSE
;
960 case EADDRNOTAVAIL
: return WSAEADDRNOTAVAIL
;
961 case ENETDOWN
: return WSAENETDOWN
;
962 case ENETUNREACH
: return WSAENETUNREACH
;
963 case ENETRESET
: return WSAENETRESET
;
964 case ECONNABORTED
: return WSAECONNABORTED
;
966 case ECONNRESET
: return WSAECONNRESET
;
967 case ENOBUFS
: return WSAENOBUFS
;
968 case EISCONN
: return WSAEISCONN
;
969 case ENOTCONN
: return WSAENOTCONN
;
970 case ESHUTDOWN
: return WSAESHUTDOWN
;
971 case ETOOMANYREFS
: return WSAETOOMANYREFS
;
972 case ETIMEDOUT
: return WSAETIMEDOUT
;
973 case ECONNREFUSED
: return WSAECONNREFUSED
;
974 case ELOOP
: return WSAELOOP
;
975 case ENAMETOOLONG
: return WSAENAMETOOLONG
;
976 case EHOSTDOWN
: return WSAEHOSTDOWN
;
977 case EHOSTUNREACH
: return WSAEHOSTUNREACH
;
978 case ENOTEMPTY
: return WSAENOTEMPTY
;
980 case EPROCLIM
: return WSAEPROCLIM
;
983 case EUSERS
: return WSAEUSERS
;
986 case EDQUOT
: return WSAEDQUOT
;
989 case ESTALE
: return WSAESTALE
;
992 case EREMOTE
: return WSAEREMOTE
;
995 /* just in case we ever get here and there are no problems */
998 WARN("Unknown errno %d!\n", err
);
999 return WSAEOPNOTSUPP
;
1003 static UINT
wsaErrno(void)
1005 int loc_errno
= errno
;
1006 WARN("errno %d, (%s).\n", loc_errno
, strerror(loc_errno
));
1008 return sock_get_error( loc_errno
);
1011 /* most ws2 overlapped functions return an ntstatus-based error code */
1012 static NTSTATUS
wsaErrStatus(void)
1014 int loc_errno
= errno
;
1015 WARN("errno %d, (%s).\n", loc_errno
, strerror(loc_errno
));
1017 return sock_get_ntstatus(loc_errno
);
1020 static UINT
wsaHerrno(int loc_errno
)
1022 WARN("h_errno %d.\n", loc_errno
);
1026 case HOST_NOT_FOUND
: return WSAHOST_NOT_FOUND
;
1027 case TRY_AGAIN
: return WSATRY_AGAIN
;
1028 case NO_RECOVERY
: return WSANO_RECOVERY
;
1029 case NO_DATA
: return WSANO_DATA
;
1030 case ENOBUFS
: return WSAENOBUFS
;
1034 WARN("Unknown h_errno %d!\n", loc_errno
);
1035 return WSAEOPNOTSUPP
;
1039 static inline DWORD
NtStatusToWSAError( const DWORD status
)
1041 /* We only need to cover the status codes set by server async request handling */
1045 case STATUS_SUCCESS
: wserr
= 0; break;
1046 case STATUS_PENDING
: wserr
= WSA_IO_PENDING
; break;
1047 case STATUS_OBJECT_TYPE_MISMATCH
: wserr
= WSAENOTSOCK
; break;
1048 case STATUS_INVALID_HANDLE
: wserr
= WSAEBADF
; break;
1049 case STATUS_INVALID_PARAMETER
: wserr
= WSAEINVAL
; break;
1050 case STATUS_PIPE_DISCONNECTED
: wserr
= WSAESHUTDOWN
; break;
1051 case STATUS_NETWORK_BUSY
: wserr
= WSAEALREADY
; break;
1052 case STATUS_NETWORK_UNREACHABLE
: wserr
= WSAENETUNREACH
; break;
1053 case STATUS_CONNECTION_REFUSED
: wserr
= WSAECONNREFUSED
; break;
1054 case STATUS_CONNECTION_DISCONNECTED
: wserr
= WSAENOTCONN
; break;
1055 case STATUS_CONNECTION_RESET
: wserr
= WSAECONNRESET
; break;
1056 case STATUS_CONNECTION_ABORTED
: wserr
= WSAECONNABORTED
; break;
1057 case STATUS_CANCELLED
: wserr
= WSA_OPERATION_ABORTED
; break;
1058 case STATUS_ADDRESS_ALREADY_ASSOCIATED
: wserr
= WSAEADDRINUSE
; break;
1059 case STATUS_IO_TIMEOUT
:
1060 case STATUS_TIMEOUT
: wserr
= WSAETIMEDOUT
; break;
1061 case STATUS_NO_MEMORY
: wserr
= WSAEFAULT
; break;
1062 case STATUS_ACCESS_DENIED
: wserr
= WSAEACCES
; break;
1063 case STATUS_TOO_MANY_OPENED_FILES
: wserr
= WSAEMFILE
; break;
1064 case STATUS_CANT_WAIT
: wserr
= WSAEWOULDBLOCK
; break;
1065 case STATUS_BUFFER_OVERFLOW
: wserr
= WSAEMSGSIZE
; break;
1066 case STATUS_NOT_SUPPORTED
: wserr
= WSAEOPNOTSUPP
; break;
1067 case STATUS_HOST_UNREACHABLE
: wserr
= WSAEHOSTUNREACH
; break;
1070 wserr
= RtlNtStatusToDosError( status
);
1071 FIXME( "Status code %08x converted to DOS error code %x\n", status
, wserr
);
1076 /* set last error code from NT status without mapping WSA errors */
1077 static inline unsigned int set_error( unsigned int err
)
1081 err
= NtStatusToWSAError( err
);
1082 SetLastError( err
);
1087 static inline int get_sock_fd( SOCKET s
, DWORD access
, unsigned int *options
)
1090 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s
), access
, &fd
, options
) ))
1095 static inline void release_sock_fd( SOCKET s
, int fd
)
1097 wine_server_release_fd( SOCKET2HANDLE(s
), fd
);
1100 static void _enable_event( HANDLE s
, unsigned int event
,
1101 unsigned int sstate
, unsigned int cstate
)
1103 SERVER_START_REQ( enable_socket_event
)
1105 req
->handle
= wine_server_obj_handle( s
);
1107 req
->sstate
= sstate
;
1108 req
->cstate
= cstate
;
1109 wine_server_call( req
);
1114 static NTSTATUS
_is_blocking(SOCKET s
, BOOL
*ret
)
1117 SERVER_START_REQ( get_socket_event
)
1119 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1120 req
->service
= FALSE
;
1122 status
= wine_server_call( req
);
1123 *ret
= (reply
->state
& FD_WINE_NONBLOCKING
) == 0;
1129 static unsigned int _get_sock_mask(SOCKET s
)
1132 SERVER_START_REQ( get_socket_event
)
1134 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1135 req
->service
= FALSE
;
1137 wine_server_call( req
);
1144 static void _sync_sock_state(SOCKET s
)
1147 /* do a dummy wineserver request in order to let
1148 the wineserver run through its select loop once */
1149 (void)_is_blocking(s
, &dummy
);
1152 static void _get_sock_errors(SOCKET s
, int *events
)
1154 SERVER_START_REQ( get_socket_event
)
1156 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1157 req
->service
= FALSE
;
1159 wine_server_set_reply( req
, events
, sizeof(int) * FD_MAX_EVENTS
);
1160 wine_server_call( req
);
1165 static int _get_sock_error(SOCKET s
, unsigned int bit
)
1167 int events
[FD_MAX_EVENTS
];
1168 _get_sock_errors(s
, events
);
1172 static int _get_fd_type(int fd
)
1175 socklen_t optlen
= sizeof(sock_type
);
1176 getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char*) &sock_type
, &optlen
);
1180 static BOOL
set_dont_fragment(SOCKET s
, int level
, BOOL value
)
1184 if (level
== IPPROTO_IP
)
1187 optname
= IP_DONTFRAG
;
1188 #elif defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO) && defined(IP_PMTUDISC_DONT)
1189 optname
= IP_MTU_DISCOVER
;
1190 value
= value
? IP_PMTUDISC_DO
: IP_PMTUDISC_DONT
;
1194 FIXME("IP_DONTFRAGMENT for IPv4 not supported in this platform\n");
1195 return TRUE
; /* fake success */
1200 #ifdef IPV6_DONTFRAG
1201 optname
= IPV6_DONTFRAG
;
1202 #elif defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO) && defined(IPV6_PMTUDISC_DONT)
1203 optname
= IPV6_MTU_DISCOVER
;
1204 value
= value
? IPV6_PMTUDISC_DO
: IPV6_PMTUDISC_DONT
;
1208 FIXME("IP_DONTFRAGMENT for IPv6 not supported in this platform\n");
1209 return TRUE
; /* fake success */
1213 fd
= get_sock_fd(s
, 0, NULL
);
1214 if (fd
== -1) return FALSE
;
1216 if (!setsockopt(fd
, level
, optname
, &value
, sizeof(value
)))
1220 WSASetLastError(wsaErrno());
1224 release_sock_fd(s
, fd
);
1228 static BOOL
get_dont_fragment(SOCKET s
, int level
, BOOL
*out
)
1230 int fd
, optname
, value
, not_expected
;
1231 socklen_t optlen
= sizeof(value
);
1233 if (level
== IPPROTO_IP
)
1236 optname
= IP_DONTFRAG
;
1238 #elif defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
1239 optname
= IP_MTU_DISCOVER
;
1240 not_expected
= IP_PMTUDISC_DONT
;
1244 FIXME("IP_DONTFRAGMENT for IPv4 not supported in this platform\n");
1245 return TRUE
; /* fake success */
1250 #ifdef IPV6_DONTFRAG
1251 optname
= IPV6_DONTFRAG
;
1253 #elif defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DONT)
1254 optname
= IPV6_MTU_DISCOVER
;
1255 not_expected
= IPV6_PMTUDISC_DONT
;
1259 FIXME("IP_DONTFRAGMENT for IPv6 not supported in this platform\n");
1260 return TRUE
; /* fake success */
1264 fd
= get_sock_fd(s
, 0, NULL
);
1265 if (fd
== -1) return FALSE
;
1267 if (!getsockopt(fd
, level
, optname
, &value
, &optlen
))
1269 *out
= value
!= not_expected
;
1274 WSASetLastError(wsaErrno());
1278 release_sock_fd(s
, fd
);
1282 static struct per_thread_data
*get_per_thread_data(void)
1284 struct per_thread_data
* ptb
= NtCurrentTeb()->WinSockData
;
1285 /* lazy initialization */
1288 ptb
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(*ptb
) );
1289 NtCurrentTeb()->WinSockData
= ptb
;
1294 static void free_per_thread_data(void)
1296 struct per_thread_data
* ptb
= NtCurrentTeb()->WinSockData
;
1300 /* delete scratch buffers */
1301 HeapFree( GetProcessHeap(), 0, ptb
->he_buffer
);
1302 HeapFree( GetProcessHeap(), 0, ptb
->se_buffer
);
1303 HeapFree( GetProcessHeap(), 0, ptb
->pe_buffer
);
1304 HeapFree( GetProcessHeap(), 0, ptb
->fd_cache
);
1306 HeapFree( GetProcessHeap(), 0, ptb
);
1307 NtCurrentTeb()->WinSockData
= NULL
;
1310 /***********************************************************************
1311 * DllMain (WS2_32.init)
1313 BOOL WINAPI
DllMain(HINSTANCE hInstDLL
, DWORD fdwReason
, LPVOID fImpLoad
)
1315 TRACE("%p 0x%x %p\n", hInstDLL
, fdwReason
, fImpLoad
);
1316 switch (fdwReason
) {
1317 case DLL_PROCESS_ATTACH
:
1319 case DLL_PROCESS_DETACH
:
1320 if (fImpLoad
) break;
1321 free_per_thread_data();
1322 DeleteCriticalSection(&csWSgetXXXbyYYY
);
1324 case DLL_THREAD_DETACH
:
1325 free_per_thread_data();
1331 /***********************************************************************
1334 * Converts send/recv flags from Windows format.
1335 * Return the converted flag bits, unsupported flags remain unchanged.
1337 static int convert_flags(int flags
)
1340 if (!flags
) return 0;
1342 for (out
= i
= 0; flags
&& i
< sizeof(ws_flags_map
) / sizeof(ws_flags_map
[0]); i
++)
1344 if (ws_flags_map
[i
][0] & flags
)
1346 out
|= ws_flags_map
[i
][1];
1347 flags
&= ~ws_flags_map
[i
][0];
1352 FIXME("Unknown send/recv flags 0x%x, using anyway...\n", flags
);
1358 /***********************************************************************
1361 * Converts socket flags from Windows format.
1362 * Return 1 if converted, 0 if not (error).
1364 static int convert_sockopt(INT
*level
, INT
*optname
)
1370 *level
= SOL_SOCKET
;
1371 for(i
=0; i
<sizeof(ws_sock_map
)/sizeof(ws_sock_map
[0]); i
++) {
1372 if( ws_sock_map
[i
][0] == *optname
)
1374 *optname
= ws_sock_map
[i
][1];
1378 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname
);
1380 case WS_IPPROTO_TCP
:
1381 *level
= IPPROTO_TCP
;
1382 for(i
=0; i
<sizeof(ws_tcp_map
)/sizeof(ws_tcp_map
[0]); i
++) {
1383 if ( ws_tcp_map
[i
][0] == *optname
)
1385 *optname
= ws_tcp_map
[i
][1];
1389 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname
);
1392 *level
= IPPROTO_IP
;
1393 for(i
=0; i
<sizeof(ws_ip_map
)/sizeof(ws_ip_map
[0]); i
++) {
1394 if (ws_ip_map
[i
][0] == *optname
)
1396 *optname
= ws_ip_map
[i
][1];
1400 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname
);
1402 case WS_IPPROTO_IPV6
:
1403 *level
= IPPROTO_IPV6
;
1404 for(i
=0; i
<sizeof(ws_ipv6_map
)/sizeof(ws_ipv6_map
[0]); i
++) {
1405 if (ws_ipv6_map
[i
][0] == *optname
)
1407 *optname
= ws_ipv6_map
[i
][1];
1411 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname
);
1413 default: FIXME("Unimplemented or unknown socket level\n");
1418 /* ----------------------------------- Per-thread info (or per-process?) */
1420 static char *strdup_lower(const char *str
)
1423 char *ret
= HeapAlloc( GetProcessHeap(), 0, strlen(str
) + 1 );
1427 for (i
= 0; str
[i
]; i
++) ret
[i
] = tolower(str
[i
]);
1430 else SetLastError(WSAENOBUFS
);
1434 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1435 * from an fd and return the value converted to milli seconds
1436 * or 0 if there is an infinite time out */
1437 static inline INT64
get_rcvsnd_timeo( int fd
, BOOL is_recv
)
1440 socklen_t len
= sizeof(tv
);
1445 optname
= SO_RCVTIMEO
;
1451 optname
= SO_SNDTIMEO
;
1456 res
= getsockopt(fd
, SOL_SOCKET
, optname
, &tv
, &len
);
1459 return (UINT64
)tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000;
1462 /* utility: given an fd, will block until one of the events occurs */
1463 static inline int do_block( int fd
, int events
, int timeout
)
1469 pfd
.events
= events
;
1471 while ((ret
= poll(&pfd
, 1, timeout
)) < 0)
1482 convert_af_w2u(int windowsaf
) {
1485 for (i
=0;i
<sizeof(ws_af_map
)/sizeof(ws_af_map
[0]);i
++)
1486 if (ws_af_map
[i
][0] == windowsaf
)
1487 return ws_af_map
[i
][1];
1488 FIXME("unhandled Windows address family %d\n", windowsaf
);
1493 convert_af_u2w(int unixaf
) {
1496 for (i
=0;i
<sizeof(ws_af_map
)/sizeof(ws_af_map
[0]);i
++)
1497 if (ws_af_map
[i
][1] == unixaf
)
1498 return ws_af_map
[i
][0];
1499 FIXME("unhandled UNIX address family %d\n", unixaf
);
1504 convert_proto_w2u(int windowsproto
) {
1507 for (i
=0;i
<sizeof(ws_proto_map
)/sizeof(ws_proto_map
[0]);i
++)
1508 if (ws_proto_map
[i
][0] == windowsproto
)
1509 return ws_proto_map
[i
][1];
1511 /* check for extended IPX */
1512 if (IS_IPX_PROTO(windowsproto
))
1513 return windowsproto
;
1515 FIXME("unhandled Windows socket protocol %d\n", windowsproto
);
1520 convert_proto_u2w(int unixproto
) {
1523 for (i
=0;i
<sizeof(ws_proto_map
)/sizeof(ws_proto_map
[0]);i
++)
1524 if (ws_proto_map
[i
][1] == unixproto
)
1525 return ws_proto_map
[i
][0];
1527 /* if value is inside IPX range just return it - the kernel simply
1528 * echoes the value used in the socket() function */
1529 if (IS_IPX_PROTO(unixproto
))
1532 FIXME("unhandled UNIX socket protocol %d\n", unixproto
);
1537 convert_socktype_w2u(int windowssocktype
) {
1540 for (i
=0;i
<sizeof(ws_socktype_map
)/sizeof(ws_socktype_map
[0]);i
++)
1541 if (ws_socktype_map
[i
][0] == windowssocktype
)
1542 return ws_socktype_map
[i
][1];
1543 FIXME("unhandled Windows socket type %d\n", windowssocktype
);
1548 convert_socktype_u2w(int unixsocktype
) {
1551 for (i
=0;i
<sizeof(ws_socktype_map
)/sizeof(ws_socktype_map
[0]);i
++)
1552 if (ws_socktype_map
[i
][1] == unixsocktype
)
1553 return ws_socktype_map
[i
][0];
1554 FIXME("unhandled UNIX socket type %d\n", unixsocktype
);
1558 static int convert_poll_w2u(int events
)
1561 for (i
= ret
= 0; events
&& i
< sizeof(ws_poll_map
) / sizeof(ws_poll_map
[0]); i
++)
1563 if (ws_poll_map
[i
][0] & events
)
1565 ret
|= ws_poll_map
[i
][1];
1566 events
&= ~ws_poll_map
[i
][0];
1571 FIXME("Unsupported WSAPoll() flags 0x%x\n", events
);
1575 static int convert_poll_u2w(int events
)
1578 for (i
= ret
= 0; events
&& i
< sizeof(ws_poll_map
) / sizeof(ws_poll_map
[0]); i
++)
1580 if (ws_poll_map
[i
][1] & events
)
1582 ret
|= ws_poll_map
[i
][0];
1583 events
&= ~ws_poll_map
[i
][1];
1588 FIXME("Unsupported poll() flags 0x%x\n", events
);
1592 static int set_ipx_packettype(int sock
, int ptype
)
1595 int fd
= get_sock_fd( sock
, 0, NULL
), ret
= 0;
1596 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype
, fd
);
1598 if (fd
== -1) return SOCKET_ERROR
;
1600 /* We try to set the ipx type on ipx socket level. */
1602 if(setsockopt(fd
, SOL_IPX
, IPX_TYPE
, &ptype
, sizeof(ptype
)) == -1)
1604 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1610 /* Should we retrieve val using a getsockopt call and then
1611 * set the modified one? */
1613 setsockopt(fd
, 0, SO_DEFAULT_HEADERS
, &val
, sizeof(struct ipx
));
1616 release_sock_fd( sock
, fd
);
1619 WARN("IPX support is not enabled, can't set packet type\n");
1620 return SOCKET_ERROR
;
1624 /* ----------------------------------- API -----
1626 * Init / cleanup / error checking.
1629 /***********************************************************************
1630 * WSAStartup (WS2_32.115)
1632 int WINAPI
WSAStartup(WORD wVersionRequested
, LPWSADATA lpWSAData
)
1634 TRACE("verReq=%x\n", wVersionRequested
);
1636 if (LOBYTE(wVersionRequested
) < 1)
1637 return WSAVERNOTSUPPORTED
;
1639 if (!lpWSAData
) return WSAEINVAL
;
1643 /* that's the whole of the negotiation for now */
1644 lpWSAData
->wVersion
= wVersionRequested
;
1645 /* return winsock information */
1646 lpWSAData
->wHighVersion
= 0x0202;
1647 strcpy(lpWSAData
->szDescription
, "WinSock 2.0" );
1648 strcpy(lpWSAData
->szSystemStatus
, "Running" );
1649 lpWSAData
->iMaxSockets
= WS_MAX_SOCKETS_PER_PROCESS
;
1650 lpWSAData
->iMaxUdpDg
= WS_MAX_UDP_DATAGRAM
;
1651 /* don't do anything with lpWSAData->lpVendorInfo */
1652 /* (some apps don't allocate the space for this field) */
1654 TRACE("succeeded starts: %d\n", num_startup
);
1659 /***********************************************************************
1660 * WSACleanup (WS2_32.116)
1662 INT WINAPI
WSACleanup(void)
1666 TRACE("pending cleanups: %d\n", num_startup
);
1669 SetLastError(WSANOTINITIALISED
);
1670 return SOCKET_ERROR
;
1674 /***********************************************************************
1675 * WSAGetLastError (WS2_32.111)
1677 INT WINAPI
WSAGetLastError(void)
1679 return GetLastError();
1682 /***********************************************************************
1683 * WSASetLastError (WS2_32.112)
1685 void WINAPI
WSASetLastError(INT iError
) {
1686 SetLastError(iError
);
1689 static struct WS_hostent
*check_buffer_he(int size
)
1691 struct per_thread_data
* ptb
= get_per_thread_data();
1694 if (ptb
->he_len
>= size
) return ptb
->he_buffer
;
1695 HeapFree( GetProcessHeap(), 0, ptb
->he_buffer
);
1697 ptb
->he_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->he_len
= size
) );
1698 if (!ptb
->he_buffer
) SetLastError(WSAENOBUFS
);
1699 return ptb
->he_buffer
;
1702 static struct WS_servent
*check_buffer_se(int size
)
1704 struct per_thread_data
* ptb
= get_per_thread_data();
1707 if (ptb
->se_len
>= size
) return ptb
->se_buffer
;
1708 HeapFree( GetProcessHeap(), 0, ptb
->se_buffer
);
1710 ptb
->se_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->se_len
= size
) );
1711 if (!ptb
->se_buffer
) SetLastError(WSAENOBUFS
);
1712 return ptb
->se_buffer
;
1715 static struct WS_protoent
*check_buffer_pe(int size
)
1717 struct per_thread_data
* ptb
= get_per_thread_data();
1720 if (ptb
->pe_len
>= size
) return ptb
->pe_buffer
;
1721 HeapFree( GetProcessHeap(), 0, ptb
->pe_buffer
);
1723 ptb
->pe_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->pe_len
= size
) );
1724 if (!ptb
->pe_buffer
) SetLastError(WSAENOBUFS
);
1725 return ptb
->pe_buffer
;
1728 /* ----------------------------------- i/o APIs */
1730 static inline BOOL
supported_pf(int pf
)
1750 static inline BOOL
supported_protocol(int protocol
)
1753 for (i
= 0; i
< sizeof(valid_protocols
) / sizeof(valid_protocols
[0]); i
++)
1754 if (protocol
== valid_protocols
[i
])
1759 /**********************************************************************/
1761 /* Returns the length of the converted address if successful, 0 if it was too
1762 * small to start with or unknown family or invalid address buffer.
1764 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr
* wsaddr
, int wsaddrlen
,
1765 union generic_unix_sockaddr
*uaddr
)
1767 unsigned int uaddrlen
= 0;
1772 switch (wsaddr
->sa_family
)
1777 const struct WS_sockaddr_ipx
* wsipx
=(const struct WS_sockaddr_ipx
*)wsaddr
;
1778 struct sockaddr_ipx
* uipx
= (struct sockaddr_ipx
*)uaddr
;
1780 if (wsaddrlen
<sizeof(struct WS_sockaddr_ipx
))
1783 uaddrlen
= sizeof(struct sockaddr_ipx
);
1784 memset( uaddr
, 0, uaddrlen
);
1785 uipx
->sipx_family
=AF_IPX
;
1786 uipx
->sipx_port
=wsipx
->sa_socket
;
1787 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1790 memcpy(&uipx
->sipx_network
,wsipx
->sa_netnum
,sizeof(uipx
->sipx_network
)+sizeof(uipx
->sipx_node
));
1791 #ifdef IPX_FRAME_NONE
1792 uipx
->sipx_type
=IPX_FRAME_NONE
;
1798 struct sockaddr_in6
* uin6
= (struct sockaddr_in6
*)uaddr
;
1799 const struct WS_sockaddr_in6
* win6
= (const struct WS_sockaddr_in6
*)wsaddr
;
1801 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1802 * scope_id, one without.
1804 if (wsaddrlen
>= sizeof(struct WS_sockaddr_in6_old
)) {
1805 uaddrlen
= sizeof(struct sockaddr_in6
);
1806 memset( uaddr
, 0, uaddrlen
);
1807 uin6
->sin6_family
= AF_INET6
;
1808 uin6
->sin6_port
= win6
->sin6_port
;
1809 uin6
->sin6_flowinfo
= win6
->sin6_flowinfo
;
1810 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1811 if (wsaddrlen
>= sizeof(struct WS_sockaddr_in6
)) uin6
->sin6_scope_id
= win6
->sin6_scope_id
;
1813 memcpy(&uin6
->sin6_addr
,&win6
->sin6_addr
,16); /* 16 bytes = 128 address bits */
1816 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen
);
1820 struct sockaddr_in
* uin
= (struct sockaddr_in
*)uaddr
;
1821 const struct WS_sockaddr_in
* win
= (const struct WS_sockaddr_in
*)wsaddr
;
1823 if (wsaddrlen
<sizeof(struct WS_sockaddr_in
))
1825 uaddrlen
= sizeof(struct sockaddr_in
);
1826 memset( uaddr
, 0, uaddrlen
);
1827 uin
->sin_family
= AF_INET
;
1828 uin
->sin_port
= win
->sin_port
;
1829 memcpy(&uin
->sin_addr
,&win
->sin_addr
,4); /* 4 bytes = 32 address bits */
1834 struct sockaddr_irda
*uin
= (struct sockaddr_irda
*)uaddr
;
1835 const SOCKADDR_IRDA
*win
= (const SOCKADDR_IRDA
*)wsaddr
;
1837 if (wsaddrlen
< sizeof(SOCKADDR_IRDA
))
1839 uaddrlen
= sizeof(struct sockaddr_irda
);
1840 memset( uaddr
, 0, uaddrlen
);
1841 uin
->sir_family
= AF_IRDA
;
1842 if (!strncmp( win
->irdaServiceName
, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1844 unsigned int lsap_sel
= 0;
1846 sscanf( win
->irdaServiceName
, "LSAP-SEL%u", &lsap_sel
);
1847 uin
->sir_lsap_sel
= lsap_sel
;
1851 uin
->sir_lsap_sel
= LSAP_ANY
;
1852 memcpy( uin
->sir_name
, win
->irdaServiceName
, 25 );
1854 memcpy( &uin
->sir_addr
, win
->irdaDeviceID
, sizeof(uin
->sir_addr
) );
1858 case WS_AF_UNSPEC
: {
1859 /* Try to determine the needed space by the passed windows sockaddr space */
1860 switch (wsaddrlen
) {
1861 default: /* likely an ipv4 address */
1862 case sizeof(struct WS_sockaddr_in
):
1863 uaddrlen
= sizeof(struct sockaddr_in
);
1866 case sizeof(struct WS_sockaddr_ipx
):
1867 uaddrlen
= sizeof(struct sockaddr_ipx
);
1871 case sizeof(SOCKADDR_IRDA
):
1872 uaddrlen
= sizeof(struct sockaddr_irda
);
1875 case sizeof(struct WS_sockaddr_in6
):
1876 case sizeof(struct WS_sockaddr_in6_old
):
1877 uaddrlen
= sizeof(struct sockaddr_in6
);
1880 memset( uaddr
, 0, uaddrlen
);
1884 FIXME("Unknown address family %d, return NULL.\n", wsaddr
->sa_family
);
1890 static BOOL
is_sockaddr_bound(const struct sockaddr
*uaddr
, int uaddrlen
)
1892 switch (uaddr
->sa_family
)
1897 static const struct sockaddr_ipx emptyAddr
;
1898 struct sockaddr_ipx
*ipx
= (struct sockaddr_ipx
*) uaddr
;
1899 return ipx
->sipx_port
1900 || memcmp(&ipx
->sipx_network
, &emptyAddr
.sipx_network
, sizeof(emptyAddr
.sipx_network
))
1901 || memcmp(&ipx
->sipx_node
, &emptyAddr
.sipx_node
, sizeof(emptyAddr
.sipx_node
));
1906 static const struct sockaddr_in6 emptyAddr
;
1907 const struct sockaddr_in6
*in6
= (const struct sockaddr_in6
*) uaddr
;
1908 return in6
->sin6_port
|| memcmp(&in6
->sin6_addr
, &emptyAddr
.sin6_addr
, sizeof(struct in6_addr
));
1912 static const struct sockaddr_in emptyAddr
;
1913 const struct sockaddr_in
*in
= (const struct sockaddr_in
*) uaddr
;
1914 return in
->sin_port
|| memcmp(&in
->sin_addr
, &emptyAddr
.sin_addr
, sizeof(struct in_addr
));
1919 FIXME("unknown address family %d\n", uaddr
->sa_family
);
1924 /* Returns -1 if getsockname fails, 0 if not bound, 1 otherwise */
1925 static int is_fd_bound(int fd
, union generic_unix_sockaddr
*uaddr
, socklen_t
*uaddrlen
)
1927 union generic_unix_sockaddr inaddr
;
1931 if (!uaddr
) uaddr
= &inaddr
;
1932 if (!uaddrlen
) uaddrlen
= &inlen
;
1934 *uaddrlen
= sizeof(inaddr
);
1935 res
= getsockname(fd
, &uaddr
->addr
, uaddrlen
);
1936 if (!res
) res
= is_sockaddr_bound(&uaddr
->addr
, *uaddrlen
);
1940 /* Returns 0 if successful, -1 if the buffer is too small */
1941 static int ws_sockaddr_u2ws(const struct sockaddr
* uaddr
, struct WS_sockaddr
* wsaddr
, int* wsaddrlen
)
1945 switch(uaddr
->sa_family
)
1950 const struct sockaddr_ipx
* uipx
=(const struct sockaddr_ipx
*)uaddr
;
1951 struct WS_sockaddr_ipx
* wsipx
=(struct WS_sockaddr_ipx
*)wsaddr
;
1954 switch (*wsaddrlen
) /* how much can we copy? */
1958 *wsaddrlen
= sizeof(*wsipx
);
1959 wsipx
->sa_socket
=uipx
->sipx_port
;
1963 memcpy(wsipx
->sa_nodenum
,uipx
->sipx_node
,sizeof(wsipx
->sa_nodenum
));
1971 memcpy(wsipx
->sa_netnum
,&uipx
->sipx_network
,sizeof(wsipx
->sa_netnum
));
1977 wsipx
->sa_family
=WS_AF_IPX
;
1989 const struct sockaddr_irda
*uin
= (const struct sockaddr_irda
*)uaddr
;
1990 SOCKADDR_IRDA
*win
= (SOCKADDR_IRDA
*)wsaddr
;
1992 if (*wsaddrlen
< sizeof(SOCKADDR_IRDA
))
1994 win
->irdaAddressFamily
= WS_AF_IRDA
;
1995 memcpy( win
->irdaDeviceID
, &uin
->sir_addr
, sizeof(win
->irdaDeviceID
) );
1996 if (uin
->sir_lsap_sel
!= LSAP_ANY
)
1997 sprintf( win
->irdaServiceName
, "LSAP-SEL%u", uin
->sir_lsap_sel
);
1999 memcpy( win
->irdaServiceName
, uin
->sir_name
,
2000 sizeof(win
->irdaServiceName
) );
2005 const struct sockaddr_in6
* uin6
= (const struct sockaddr_in6
*)uaddr
;
2006 struct WS_sockaddr_in6_old
* win6old
= (struct WS_sockaddr_in6_old
*)wsaddr
;
2008 if (*wsaddrlen
< sizeof(struct WS_sockaddr_in6_old
))
2010 win6old
->sin6_family
= WS_AF_INET6
;
2011 win6old
->sin6_port
= uin6
->sin6_port
;
2012 win6old
->sin6_flowinfo
= uin6
->sin6_flowinfo
;
2013 memcpy(&win6old
->sin6_addr
,&uin6
->sin6_addr
,16); /* 16 bytes = 128 address bits */
2014 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
2015 if (*wsaddrlen
>= sizeof(struct WS_sockaddr_in6
)) {
2016 struct WS_sockaddr_in6
* win6
= (struct WS_sockaddr_in6
*)wsaddr
;
2017 win6
->sin6_scope_id
= uin6
->sin6_scope_id
;
2018 *wsaddrlen
= sizeof(struct WS_sockaddr_in6
);
2021 *wsaddrlen
= sizeof(struct WS_sockaddr_in6_old
);
2023 *wsaddrlen
= sizeof(struct WS_sockaddr_in6_old
);
2028 const struct sockaddr_in
* uin
= (const struct sockaddr_in
*)uaddr
;
2029 struct WS_sockaddr_in
* win
= (struct WS_sockaddr_in
*)wsaddr
;
2031 if (*wsaddrlen
< sizeof(struct WS_sockaddr_in
))
2033 win
->sin_family
= WS_AF_INET
;
2034 win
->sin_port
= uin
->sin_port
;
2035 memcpy(&win
->sin_addr
,&uin
->sin_addr
,4); /* 4 bytes = 32 address bits */
2036 memset(win
->sin_zero
, 0, 8); /* Make sure the null padding is null */
2037 *wsaddrlen
= sizeof(struct WS_sockaddr_in
);
2041 memset(wsaddr
,0,*wsaddrlen
);
2045 FIXME("Unknown address family %d\n", uaddr
->sa_family
);
2051 static INT
WS_DuplicateSocket(BOOL unicode
, SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOW lpProtocolInfo
)
2055 WSAPROTOCOL_INFOW infow
;
2057 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
2058 unicode
, s
, dwProcessId
, lpProtocolInfo
);
2060 if (!ws_protocol_info(s
, unicode
, &infow
, &size
))
2061 return SOCKET_ERROR
;
2063 if (!(hProcess
= OpenProcess(PROCESS_DUP_HANDLE
, FALSE
, dwProcessId
)))
2065 SetLastError(WSAEINVAL
);
2066 return SOCKET_ERROR
;
2069 if (!lpProtocolInfo
)
2071 CloseHandle(hProcess
);
2072 SetLastError(WSAEFAULT
);
2073 return SOCKET_ERROR
;
2076 /* I don't know what the real Windoze does next, this is a hack */
2077 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
2078 * the target use the global duplicate, or we could copy a reference to us to the structure
2079 * and let the target duplicate it from us, but let's do it as simple as possible */
2080 memcpy(lpProtocolInfo
, &infow
, size
);
2081 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s
),
2082 hProcess
, (LPHANDLE
)&lpProtocolInfo
->dwServiceFlags3
,
2083 0, FALSE
, DUPLICATE_SAME_ACCESS
);
2084 CloseHandle(hProcess
);
2085 lpProtocolInfo
->dwServiceFlags4
= 0xff00ff00; /* magic */
2089 /*****************************************************************************
2090 * WS_EnterSingleProtocolW [internal]
2092 * enters the protocol information of one given protocol into the given
2096 * TRUE if a protocol was entered into the buffer.
2099 * - only implemented for IPX, SPX, SPXII, TCP, UDP
2100 * - there is no check that the operating system supports the returned
2103 static BOOL
WS_EnterSingleProtocolW( INT protocol
, WSAPROTOCOL_INFOW
* info
)
2105 memset( info
, 0, sizeof(WSAPROTOCOL_INFOW
) );
2106 info
->iProtocol
= protocol
;
2110 case WS_IPPROTO_TCP
:
2111 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_EXPEDITED_DATA
|
2112 XP1_GRACEFUL_CLOSE
| XP1_GUARANTEED_ORDER
|
2113 XP1_GUARANTEED_DELIVERY
;
2114 info
->ProviderId
= ProviderIdIP
;
2115 info
->dwCatalogEntryId
= 0x3e9;
2116 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2117 info
->ProtocolChain
.ChainLen
= 1;
2119 info
->iAddressFamily
= WS_AF_INET
;
2120 info
->iMaxSockAddr
= 0x10;
2121 info
->iMinSockAddr
= 0x10;
2122 info
->iSocketType
= WS_SOCK_STREAM
;
2123 strcpyW( info
->szProtocol
, NameTcpW
);
2126 case WS_IPPROTO_UDP
:
2127 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_SUPPORT_BROADCAST
|
2128 XP1_SUPPORT_MULTIPOINT
| XP1_MESSAGE_ORIENTED
|
2130 info
->ProviderId
= ProviderIdIP
;
2131 info
->dwCatalogEntryId
= 0x3ea;
2132 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2133 info
->ProtocolChain
.ChainLen
= 1;
2135 info
->iAddressFamily
= WS_AF_INET
;
2136 info
->iMaxSockAddr
= 0x10;
2137 info
->iMinSockAddr
= 0x10;
2138 info
->iSocketType
= WS_SOCK_DGRAM
;
2139 info
->dwMessageSize
= 0xffbb;
2140 strcpyW( info
->szProtocol
, NameUdpW
);
2143 case WS_NSPROTO_IPX
:
2144 info
->dwServiceFlags1
= XP1_PARTIAL_MESSAGE
| XP1_SUPPORT_BROADCAST
|
2145 XP1_SUPPORT_MULTIPOINT
| XP1_MESSAGE_ORIENTED
|
2147 info
->ProviderId
= ProviderIdIPX
;
2148 info
->dwCatalogEntryId
= 0x406;
2149 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2150 info
->ProtocolChain
.ChainLen
= 1;
2152 info
->iAddressFamily
= WS_AF_IPX
;
2153 info
->iMaxSockAddr
= 0x10;
2154 info
->iMinSockAddr
= 0x0e;
2155 info
->iSocketType
= WS_SOCK_DGRAM
;
2156 info
->iProtocolMaxOffset
= 0xff;
2157 info
->dwMessageSize
= 0x240;
2158 strcpyW( info
->szProtocol
, NameIpxW
);
2161 case WS_NSPROTO_SPX
:
2162 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_PSEUDO_STREAM
|
2163 XP1_MESSAGE_ORIENTED
| XP1_GUARANTEED_ORDER
|
2164 XP1_GUARANTEED_DELIVERY
;
2165 info
->ProviderId
= ProviderIdSPX
;
2166 info
->dwCatalogEntryId
= 0x407;
2167 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2168 info
->ProtocolChain
.ChainLen
= 1;
2170 info
->iAddressFamily
= WS_AF_IPX
;
2171 info
->iMaxSockAddr
= 0x10;
2172 info
->iMinSockAddr
= 0x0e;
2173 info
->iSocketType
= WS_SOCK_SEQPACKET
;
2174 info
->dwMessageSize
= 0xffffffff;
2175 strcpyW( info
->szProtocol
, NameSpxW
);
2178 case WS_NSPROTO_SPXII
:
2179 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_GRACEFUL_CLOSE
|
2180 XP1_PSEUDO_STREAM
| XP1_MESSAGE_ORIENTED
|
2181 XP1_GUARANTEED_ORDER
| XP1_GUARANTEED_DELIVERY
;
2182 info
->ProviderId
= ProviderIdSPX
;
2183 info
->dwCatalogEntryId
= 0x409;
2184 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
2185 info
->ProtocolChain
.ChainLen
= 1;
2187 info
->iAddressFamily
= WS_AF_IPX
;
2188 info
->iMaxSockAddr
= 0x10;
2189 info
->iMinSockAddr
= 0x0e;
2190 info
->iSocketType
= WS_SOCK_SEQPACKET
;
2191 info
->dwMessageSize
= 0xffffffff;
2192 strcpyW( info
->szProtocol
, NameSpxIIW
);
2196 FIXME("unknown Protocol <0x%08x>\n", protocol
);
2202 /*****************************************************************************
2203 * WS_EnterSingleProtocolA [internal]
2205 * see function WS_EnterSingleProtocolW
2208 static BOOL
WS_EnterSingleProtocolA( INT protocol
, WSAPROTOCOL_INFOA
* info
)
2210 WSAPROTOCOL_INFOW infow
;
2212 memset( info
, 0, sizeof(WSAPROTOCOL_INFOA
) );
2214 ret
= WS_EnterSingleProtocolW( protocol
, &infow
);
2217 /* convert the structure from W to A */
2218 memcpy( info
, &infow
, FIELD_OFFSET( WSAPROTOCOL_INFOA
, szProtocol
) );
2219 WideCharToMultiByte( CP_ACP
, 0, infow
.szProtocol
, -1,
2220 info
->szProtocol
, WSAPROTOCOL_LEN
+1, NULL
, NULL
);
2226 static INT
WS_EnumProtocols( BOOL unicode
, const INT
*protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
)
2228 INT i
= 0, items
= 0;
2232 LPWSAPROTOCOL_INFOA a
;
2233 LPWSAPROTOCOL_INFOW w
;
2237 if (!protocols
) protocols
= valid_protocols
;
2239 while (protocols
[i
])
2241 if(supported_protocol(protocols
[i
++]))
2245 size
= items
* (unicode
? sizeof(WSAPROTOCOL_INFOW
) : sizeof(WSAPROTOCOL_INFOA
));
2247 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
2248 unicode
, protocols
, buffer
, len
, len
? *len
: 0, items
, size
);
2250 if (*len
< size
|| !buffer
)
2253 SetLastError(WSAENOBUFS
);
2254 return SOCKET_ERROR
;
2257 for (i
= items
= 0; protocols
[i
]; i
++)
2259 if (!supported_protocol(protocols
[i
])) continue;
2262 if (WS_EnterSingleProtocolW( protocols
[i
], &info
.w
[items
] ))
2267 if (WS_EnterSingleProtocolA( protocols
[i
], &info
.a
[items
] ))
2274 static BOOL
ws_protocol_info(SOCKET s
, int unicode
, WSAPROTOCOL_INFOW
*buffer
, int *size
)
2278 *size
= unicode
? sizeof(WSAPROTOCOL_INFOW
) : sizeof(WSAPROTOCOL_INFOA
);
2279 memset(buffer
, 0, *size
);
2281 SERVER_START_REQ( get_socket_info
)
2283 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
2284 status
= wine_server_call( req
);
2287 buffer
->iAddressFamily
= convert_af_u2w(reply
->family
);
2288 buffer
->iSocketType
= convert_socktype_u2w(reply
->type
);
2289 buffer
->iProtocol
= convert_proto_u2w(reply
->protocol
);
2296 unsigned int err
= NtStatusToWSAError( status
);
2297 SetLastError( err
== WSAEBADF
? WSAENOTSOCK
: err
);
2302 WS_EnterSingleProtocolW( buffer
->iProtocol
, buffer
);
2304 WS_EnterSingleProtocolA( buffer
->iProtocol
, (WSAPROTOCOL_INFOA
*)buffer
);
2309 /**************************************************************************
2310 * Functions for handling overlapped I/O
2311 **************************************************************************/
2313 /* user APC called upon async completion */
2314 static void WINAPI
ws2_async_apc( void *arg
, IO_STATUS_BLOCK
*iosb
, ULONG reserved
)
2316 struct ws2_async
*wsa
= arg
;
2318 if (wsa
->completion_func
) wsa
->completion_func( NtStatusToWSAError(iosb
->u
.Status
),
2319 iosb
->Information
, wsa
->user_overlapped
,
2321 release_async_io( &wsa
->io
);
2324 /***********************************************************************
2325 * WS2_recv (INTERNAL)
2327 * Workhorse for both synchronous and asynchronous recv() operations.
2329 static int WS2_recv( int fd
, struct ws2_async
*wsa
, int flags
)
2331 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2335 union generic_unix_sockaddr unix_sockaddr
;
2338 hdr
.msg_name
= NULL
;
2342 hdr
.msg_namelen
= sizeof(unix_sockaddr
);
2343 hdr
.msg_name
= &unix_sockaddr
;
2346 hdr
.msg_namelen
= 0;
2348 hdr
.msg_iov
= wsa
->iovec
+ wsa
->first_iovec
;
2349 hdr
.msg_iovlen
= wsa
->n_iovecs
- wsa
->first_iovec
;
2350 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2351 hdr
.msg_accrights
= NULL
;
2352 hdr
.msg_accrightslen
= 0;
2354 hdr
.msg_control
= pktbuf
;
2355 hdr
.msg_controllen
= sizeof(pktbuf
);
2359 while ((n
= recvmsg(fd
, &hdr
, flags
)) == -1)
2365 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2368 ERR("Message control headers cannot be properly supported on this system.\n");
2369 wsa
->control
->len
= 0;
2372 if (wsa
->control
&& !convert_control_headers(&hdr
, wsa
->control
))
2374 WARN("Application passed insufficient room for control headers.\n");
2375 *wsa
->lpFlags
|= WS_MSG_CTRUNC
;
2381 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
2382 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
2384 * quoting linux 2.6 net/ipv4/tcp.c:
2385 * "According to UNIX98, msg_name/msg_namelen are ignored
2386 * on connected socket. I was just happy when found this 8) --ANK"
2388 * likewise MSDN says that lpFrom and lpFromlen are ignored for
2389 * connection-oriented sockets, so don't try to update lpFrom.
2391 if (wsa
->addr
&& hdr
.msg_namelen
)
2392 ws_sockaddr_u2ws( &unix_sockaddr
.addr
, wsa
->addr
, wsa
->addrlen
.ptr
);
2397 /***********************************************************************
2398 * WS2_async_recv (INTERNAL)
2400 * Handler for overlapped recv() operations.
2402 static NTSTATUS
WS2_async_recv( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
2404 struct ws2_async
*wsa
= user
;
2409 case STATUS_ALERTED
:
2410 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, FILE_READ_DATA
, &fd
, NULL
) ))
2413 result
= WS2_recv( fd
, wsa
, convert_flags(wsa
->flags
) );
2414 wine_server_release_fd( wsa
->hSocket
, fd
);
2417 status
= STATUS_SUCCESS
;
2418 _enable_event( wsa
->hSocket
, FD_READ
, 0, 0 );
2422 if (errno
== EAGAIN
)
2424 status
= STATUS_PENDING
;
2425 _enable_event( wsa
->hSocket
, FD_READ
, 0, 0 );
2430 status
= wsaErrStatus();
2435 if (status
!= STATUS_PENDING
)
2437 iosb
->u
.Status
= status
;
2438 iosb
->Information
= result
;
2439 if (!wsa
->completion_func
)
2440 release_async_io( &wsa
->io
);
2445 /***********************************************************************
2446 * WS2_async_accept_recv (INTERNAL)
2448 * This function is used to finish the read part of an accept request. It is
2449 * needed to place the completion on the correct socket (listener).
2451 static NTSTATUS
WS2_async_accept_recv( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
2453 struct ws2_accept_async
*wsa
= user
;
2455 status
= WS2_async_recv( wsa
->read
, iosb
, status
);
2456 if (status
== STATUS_PENDING
)
2460 WS_AddCompletion( HANDLE2SOCKET(wsa
->listen_socket
), wsa
->cvalue
, iosb
->u
.Status
, iosb
->Information
);
2462 release_async_io( &wsa
->io
);
2466 /***********************************************************************
2467 * WS2_async_accept (INTERNAL)
2469 * This is the function called to satisfy the AcceptEx callback
2471 static NTSTATUS
WS2_async_accept( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
2473 struct ws2_accept_async
*wsa
= user
;
2477 TRACE("status: 0x%x listen: %p, accept: %p\n", status
, wsa
->listen_socket
, wsa
->accept_socket
);
2479 if (status
== STATUS_ALERTED
)
2481 SERVER_START_REQ( accept_into_socket
)
2483 req
->lhandle
= wine_server_obj_handle( wsa
->listen_socket
);
2484 req
->ahandle
= wine_server_obj_handle( wsa
->accept_socket
);
2485 status
= wine_server_call( req
);
2489 if (status
== STATUS_CANT_WAIT
)
2490 return STATUS_PENDING
;
2492 if (status
== STATUS_INVALID_HANDLE
)
2494 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2495 status
= STATUS_CANCELLED
;
2498 else if (status
== STATUS_HANDLES_CLOSED
)
2499 status
= STATUS_CANCELLED
; /* strange windows behavior */
2501 if (status
!= STATUS_SUCCESS
)
2504 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2505 addr
= ((char *)wsa
->buf
) + wsa
->data_len
;
2506 len
= wsa
->local_len
- sizeof(int);
2507 WS_getsockname(HANDLE2SOCKET(wsa
->accept_socket
),
2508 (struct WS_sockaddr
*)(addr
+ sizeof(int)), &len
);
2511 addr
+= wsa
->local_len
;
2512 len
= wsa
->remote_len
- sizeof(int);
2513 WS_getpeername(HANDLE2SOCKET(wsa
->accept_socket
),
2514 (struct WS_sockaddr
*)(addr
+ sizeof(int)), &len
);
2520 wsa
->io
.callback
= WS2_async_accept_recv
;
2521 status
= register_async( ASYNC_TYPE_READ
, wsa
->accept_socket
, &wsa
->io
,
2522 wsa
->user_overlapped
->hEvent
, NULL
, NULL
, iosb
);
2524 if (status
!= STATUS_PENDING
)
2527 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2528 * needs to be performed by WS2_async_accept_recv() first. */
2529 return STATUS_MORE_PROCESSING_REQUIRED
;
2532 iosb
->u
.Status
= status
;
2533 iosb
->Information
= 0;
2535 if (wsa
->read
) release_async_io( &wsa
->read
->io
);
2536 release_async_io( &wsa
->io
);
2540 /***********************************************************************
2541 * WS2_send (INTERNAL)
2543 * Workhorse for both synchronous and asynchronous send() operations.
2545 static int WS2_send( int fd
, struct ws2_async
*wsa
, int flags
)
2548 union generic_unix_sockaddr unix_addr
;
2551 hdr
.msg_name
= NULL
;
2552 hdr
.msg_namelen
= 0;
2556 hdr
.msg_name
= &unix_addr
;
2557 hdr
.msg_namelen
= ws_sockaddr_ws2u( wsa
->addr
, wsa
->addrlen
.val
, &unix_addr
);
2558 if ( !hdr
.msg_namelen
)
2564 #if defined(HAS_IPX) && defined(SOL_IPX)
2565 if(wsa
->addr
->sa_family
== WS_AF_IPX
)
2567 struct sockaddr_ipx
* uipx
= (struct sockaddr_ipx
*)hdr
.msg_name
;
2569 socklen_t len
= sizeof(int);
2571 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2572 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2573 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2574 * ipx type in the sockaddr_opx structure with the stored value.
2576 if(getsockopt(fd
, SOL_IPX
, IPX_TYPE
, &val
, &len
) != -1)
2577 uipx
->sipx_type
= val
;
2582 hdr
.msg_iov
= wsa
->iovec
+ wsa
->first_iovec
;
2583 hdr
.msg_iovlen
= wsa
->n_iovecs
- wsa
->first_iovec
;
2584 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2585 hdr
.msg_accrights
= NULL
;
2586 hdr
.msg_accrightslen
= 0;
2588 hdr
.msg_control
= NULL
;
2589 hdr
.msg_controllen
= 0;
2593 while ((ret
= sendmsg(fd
, &hdr
, flags
)) == -1)
2600 while (wsa
->first_iovec
< wsa
->n_iovecs
&& wsa
->iovec
[wsa
->first_iovec
].iov_len
<= n
)
2601 n
-= wsa
->iovec
[wsa
->first_iovec
++].iov_len
;
2602 if (wsa
->first_iovec
< wsa
->n_iovecs
)
2604 wsa
->iovec
[wsa
->first_iovec
].iov_base
= (char*)wsa
->iovec
[wsa
->first_iovec
].iov_base
+ n
;
2605 wsa
->iovec
[wsa
->first_iovec
].iov_len
-= n
;
2610 /***********************************************************************
2611 * WS2_async_send (INTERNAL)
2613 * Handler for overlapped send() operations.
2615 static NTSTATUS
WS2_async_send( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
2617 struct ws2_async
*wsa
= user
;
2622 case STATUS_ALERTED
:
2623 if ( wsa
->n_iovecs
<= wsa
->first_iovec
)
2626 status
= STATUS_SUCCESS
;
2629 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, FILE_WRITE_DATA
, &fd
, NULL
) ))
2632 /* check to see if the data is ready (non-blocking) */
2633 result
= WS2_send( fd
, wsa
, convert_flags(wsa
->flags
) );
2634 wine_server_release_fd( wsa
->hSocket
, fd
);
2638 if (wsa
->first_iovec
< wsa
->n_iovecs
)
2639 status
= STATUS_PENDING
;
2641 status
= STATUS_SUCCESS
;
2643 iosb
->Information
+= result
;
2645 else if (errno
== EAGAIN
)
2647 status
= STATUS_PENDING
;
2651 status
= wsaErrStatus();
2655 if (status
!= STATUS_PENDING
)
2657 iosb
->u
.Status
= status
;
2658 if (!wsa
->completion_func
)
2659 release_async_io( &wsa
->io
);
2664 /***********************************************************************
2665 * WS2_async_shutdown (INTERNAL)
2667 * Handler for shutdown() operations on overlapped sockets.
2669 static NTSTATUS
WS2_async_shutdown( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
2671 struct ws2_async_shutdown
*wsa
= user
;
2676 case STATUS_ALERTED
:
2677 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, 0, &fd
, NULL
) ))
2680 switch ( wsa
->type
)
2682 case ASYNC_TYPE_READ
: err
= shutdown( fd
, 0 ); break;
2683 case ASYNC_TYPE_WRITE
: err
= shutdown( fd
, 1 ); break;
2685 status
= err
? wsaErrStatus() : STATUS_SUCCESS
;
2686 wine_server_release_fd( wsa
->hSocket
, fd
);
2689 iosb
->u
.Status
= status
;
2690 iosb
->Information
= 0;
2691 release_async_io( &wsa
->io
);
2695 /***********************************************************************
2696 * WS2_register_async_shutdown (INTERNAL)
2698 * Helper function for WS_shutdown() on overlapped sockets.
2700 static int WS2_register_async_shutdown( SOCKET s
, int type
)
2702 struct ws2_async_shutdown
*wsa
;
2705 TRACE("socket %04lx type %d\n", s
, type
);
2707 wsa
= (struct ws2_async_shutdown
*)alloc_async_io( sizeof(*wsa
), WS2_async_shutdown
);
2711 wsa
->hSocket
= SOCKET2HANDLE(s
);
2714 status
= register_async( type
, wsa
->hSocket
, &wsa
->io
, 0, NULL
, NULL
, &wsa
->iosb
);
2715 if (status
!= STATUS_PENDING
)
2717 HeapFree( GetProcessHeap(), 0, wsa
);
2718 return NtStatusToWSAError( status
);
2723 /***********************************************************************
2726 SOCKET WINAPI
WS_accept(SOCKET s
, struct WS_sockaddr
*addr
, int *addrlen32
)
2732 TRACE("socket %04lx\n", s
);
2733 status
= _is_blocking(s
, &is_blocking
);
2738 /* try accepting first (if there is a deferred connection) */
2739 SERVER_START_REQ( accept_socket
)
2741 req
->lhandle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
2742 req
->access
= GENERIC_READ
|GENERIC_WRITE
|SYNCHRONIZE
;
2743 req
->attributes
= OBJ_INHERIT
;
2744 status
= wine_server_call( req
);
2745 as
= HANDLE2SOCKET( wine_server_ptr_handle( reply
->handle
));
2750 if (addr
&& addrlen32
&& WS_getpeername(as
, addr
, addrlen32
))
2753 return SOCKET_ERROR
;
2755 TRACE("\taccepted %04lx\n", as
);
2758 if (is_blocking
&& status
== STATUS_CANT_WAIT
)
2760 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
2762 do_block(fd
, POLLIN
, -1);
2763 _sync_sock_state(s
); /* let wineserver notice connection */
2764 release_sock_fd( s
, fd
);
2766 } while (is_blocking
&& status
== STATUS_CANT_WAIT
);
2770 WARN(" -> ERROR %d\n", GetLastError());
2771 return INVALID_SOCKET
;
2774 /***********************************************************************
2777 static BOOL WINAPI
WS2_AcceptEx(SOCKET listener
, SOCKET acceptor
, PVOID dest
, DWORD dest_len
,
2778 DWORD local_addr_len
, DWORD rem_addr_len
, LPDWORD received
,
2779 LPOVERLAPPED overlapped
)
2782 struct ws2_accept_async
*wsa
;
2785 TRACE("(%04lx, %04lx, %p, %d, %d, %d, %p, %p)\n", listener
, acceptor
, dest
, dest_len
, local_addr_len
,
2786 rem_addr_len
, received
, overlapped
);
2790 SetLastError(WSAEINVAL
);
2796 SetLastError(WSA_INVALID_PARAMETER
);
2802 SetLastError(WSAEFAULT
);
2806 fd
= get_sock_fd( listener
, FILE_READ_DATA
, NULL
);
2809 SetLastError(WSAENOTSOCK
);
2812 release_sock_fd( listener
, fd
);
2814 fd
= get_sock_fd( acceptor
, FILE_READ_DATA
, NULL
);
2817 SetLastError(WSAENOTSOCK
);
2820 release_sock_fd( acceptor
, fd
);
2822 wsa
= (struct ws2_accept_async
*)alloc_async_io( sizeof(*wsa
), WS2_async_accept
);
2825 SetLastError(WSAEFAULT
);
2829 wsa
->listen_socket
= SOCKET2HANDLE(listener
);
2830 wsa
->accept_socket
= SOCKET2HANDLE(acceptor
);
2831 wsa
->user_overlapped
= overlapped
;
2832 wsa
->cvalue
= !((ULONG_PTR
)overlapped
->hEvent
& 1) ? (ULONG_PTR
)overlapped
: 0;
2834 wsa
->data_len
= dest_len
;
2835 wsa
->local_len
= local_addr_len
;
2836 wsa
->remote_len
= rem_addr_len
;
2841 /* set up a read request if we need it */
2842 wsa
->read
= (struct ws2_async
*)alloc_async_io( offsetof(struct ws2_async
, iovec
[1]), WS2_async_accept_recv
);
2845 HeapFree( GetProcessHeap(), 0, wsa
);
2846 SetLastError(WSAEFAULT
);
2850 wsa
->read
->hSocket
= wsa
->accept_socket
;
2851 wsa
->read
->flags
= 0;
2852 wsa
->read
->lpFlags
= &wsa
->read
->flags
;
2853 wsa
->read
->addr
= NULL
;
2854 wsa
->read
->addrlen
.ptr
= NULL
;
2855 wsa
->read
->control
= NULL
;
2856 wsa
->read
->n_iovecs
= 1;
2857 wsa
->read
->first_iovec
= 0;
2858 wsa
->read
->completion_func
= NULL
;
2859 wsa
->read
->iovec
[0].iov_base
= wsa
->buf
;
2860 wsa
->read
->iovec
[0].iov_len
= wsa
->data_len
;
2863 status
= register_async( ASYNC_TYPE_READ
, SOCKET2HANDLE(listener
), &wsa
->io
,
2864 overlapped
->hEvent
, NULL
, (void *)wsa
->cvalue
, (IO_STATUS_BLOCK
*)overlapped
);
2866 if(status
!= STATUS_PENDING
)
2868 HeapFree( GetProcessHeap(), 0, wsa
->read
);
2869 HeapFree( GetProcessHeap(), 0, wsa
);
2872 SetLastError( NtStatusToWSAError(status
) );
2876 /***********************************************************************
2877 * WS2_ReadFile (INTERNAL)
2879 * Perform an APC-safe ReadFile operation
2881 static NTSTATUS
WS2_ReadFile(HANDLE hFile
, PIO_STATUS_BLOCK io_status
, char* buffer
, ULONG length
,
2882 PLARGE_INTEGER offset
)
2884 int result
= -1, unix_handle
;
2885 unsigned int options
;
2888 TRACE( "(%p,%p,0x%08x)\n", hFile
, buffer
,length
);
2890 status
= wine_server_handle_to_fd( hFile
, FILE_READ_DATA
, &unix_handle
, &options
);
2891 if (status
) return status
;
2893 while (result
== -1)
2895 if (offset
->QuadPart
!= FILE_USE_FILE_POINTER_POSITION
)
2896 result
= pread( unix_handle
, buffer
, length
, offset
->QuadPart
);
2898 result
= read( unix_handle
, buffer
, length
);
2904 status
= (length
? STATUS_END_OF_FILE
: STATUS_SUCCESS
);
2905 else if (result
!= -1)
2906 status
= STATUS_SUCCESS
;
2907 else if (errno
!= EAGAIN
)
2908 status
= wsaErrStatus();
2910 status
= STATUS_PENDING
;
2912 wine_server_release_fd( hFile
, unix_handle
);
2913 TRACE("= 0x%08x (%d)\n", status
, result
);
2914 if (status
== STATUS_SUCCESS
|| status
== STATUS_END_OF_FILE
)
2916 io_status
->u
.Status
= status
;
2917 io_status
->Information
= result
;
2923 /***********************************************************************
2924 * WS2_transmitfile_getbuffer (INTERNAL)
2926 * Pick the appropriate buffer for a TransmitFile send operation.
2928 static NTSTATUS
WS2_transmitfile_getbuffer( int fd
, struct ws2_transmitfile_async
*wsa
)
2930 /* send any incomplete writes from a previous iteration */
2931 if (wsa
->write
.first_iovec
< wsa
->write
.n_iovecs
)
2932 return STATUS_PENDING
;
2934 /* process the header (if applicable) */
2935 if (wsa
->buffers
.Head
)
2937 wsa
->write
.first_iovec
= 0;
2938 wsa
->write
.n_iovecs
= 1;
2939 wsa
->write
.iovec
[0].iov_base
= wsa
->buffers
.Head
;
2940 wsa
->write
.iovec
[0].iov_len
= wsa
->buffers
.HeadLength
;
2941 wsa
->buffers
.Head
= NULL
;
2942 return STATUS_PENDING
;
2945 /* process the main file */
2948 DWORD bytes_per_send
= wsa
->bytes_per_send
;
2949 IO_STATUS_BLOCK iosb
;
2952 iosb
.Information
= 0;
2953 /* when the size of the transfer is limited ensure that we don't go past that limit */
2954 if (wsa
->file_bytes
!= 0)
2955 bytes_per_send
= min(bytes_per_send
, wsa
->file_bytes
- wsa
->file_read
);
2956 status
= WS2_ReadFile( wsa
->file
, &iosb
, wsa
->buffer
, bytes_per_send
, &wsa
->offset
);
2957 if (wsa
->offset
.QuadPart
!= FILE_USE_FILE_POINTER_POSITION
)
2958 wsa
->offset
.QuadPart
+= iosb
.Information
;
2959 if (status
== STATUS_END_OF_FILE
)
2960 wsa
->file
= NULL
; /* continue on to the footer */
2961 else if (status
!= STATUS_SUCCESS
)
2965 if (iosb
.Information
)
2967 wsa
->write
.first_iovec
= 0;
2968 wsa
->write
.n_iovecs
= 1;
2969 wsa
->write
.iovec
[0].iov_base
= wsa
->buffer
;
2970 wsa
->write
.iovec
[0].iov_len
= iosb
.Information
;
2971 wsa
->file_read
+= iosb
.Information
;
2974 if (wsa
->file_bytes
!= 0 && wsa
->file_read
>= wsa
->file_bytes
)
2977 return STATUS_PENDING
;
2981 /* send the footer (if applicable) */
2982 if (wsa
->buffers
.Tail
)
2984 wsa
->write
.first_iovec
= 0;
2985 wsa
->write
.n_iovecs
= 1;
2986 wsa
->write
.iovec
[0].iov_base
= wsa
->buffers
.Tail
;
2987 wsa
->write
.iovec
[0].iov_len
= wsa
->buffers
.TailLength
;
2988 wsa
->buffers
.Tail
= NULL
;
2989 return STATUS_PENDING
;
2992 return STATUS_SUCCESS
;
2995 /***********************************************************************
2996 * WS2_transmitfile_base (INTERNAL)
2998 * Shared implementation for both synchronous and asynchronous TransmitFile.
3000 static NTSTATUS
WS2_transmitfile_base( int fd
, struct ws2_transmitfile_async
*wsa
)
3004 status
= WS2_transmitfile_getbuffer( fd
, wsa
);
3005 if (status
== STATUS_PENDING
)
3007 IO_STATUS_BLOCK
*iosb
= (IO_STATUS_BLOCK
*)wsa
->write
.user_overlapped
;
3010 n
= WS2_send( fd
, &wsa
->write
, convert_flags(wsa
->write
.flags
) );
3013 if (iosb
) iosb
->Information
+= n
;
3015 else if (errno
!= EAGAIN
)
3016 return wsaErrStatus();
3022 /***********************************************************************
3023 * WS2_async_transmitfile (INTERNAL)
3025 * Asynchronous callback for overlapped TransmitFile operations.
3027 static NTSTATUS
WS2_async_transmitfile( void *user
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
)
3029 struct ws2_transmitfile_async
*wsa
= user
;
3032 if (status
== STATUS_ALERTED
)
3034 if (!(status
= wine_server_handle_to_fd( wsa
->write
.hSocket
, FILE_WRITE_DATA
, &fd
, NULL
)))
3036 status
= WS2_transmitfile_base( fd
, wsa
);
3037 wine_server_release_fd( wsa
->write
.hSocket
, fd
);
3039 if (status
== STATUS_PENDING
)
3043 iosb
->u
.Status
= status
;
3044 release_async_io( &wsa
->io
);
3048 /***********************************************************************
3051 static BOOL WINAPI
WS2_TransmitFile( SOCKET s
, HANDLE h
, DWORD file_bytes
, DWORD bytes_per_send
,
3052 LPOVERLAPPED overlapped
, LPTRANSMIT_FILE_BUFFERS buffers
,
3055 union generic_unix_sockaddr uaddr
;
3056 socklen_t uaddrlen
= sizeof(uaddr
);
3057 struct ws2_transmitfile_async
*wsa
;
3061 TRACE("(%lx, %p, %d, %d, %p, %p, %d)\n", s
, h
, file_bytes
, bytes_per_send
, overlapped
,
3064 fd
= get_sock_fd( s
, FILE_WRITE_DATA
, NULL
);
3067 WSASetLastError( WSAENOTSOCK
);
3070 if (getpeername( fd
, &uaddr
.addr
, &uaddrlen
) != 0)
3072 release_sock_fd( s
, fd
);
3073 WSASetLastError( WSAENOTCONN
);
3077 FIXME("Flags are not currently supported (0x%x).\n", flags
);
3079 if (h
&& GetFileType( h
) != FILE_TYPE_DISK
)
3081 FIXME("Non-disk file handles are not currently supported.\n");
3082 release_sock_fd( s
, fd
);
3083 WSASetLastError( WSAEOPNOTSUPP
);
3087 /* set reasonable defaults when requested */
3088 if (!bytes_per_send
)
3089 bytes_per_send
= (1 << 16); /* Depends on OS version: PAGE_SIZE, 2*PAGE_SIZE, or 2^16 */
3091 if (!(wsa
= (struct ws2_transmitfile_async
*)alloc_async_io( sizeof(*wsa
) + bytes_per_send
,
3092 WS2_async_transmitfile
)))
3094 release_sock_fd( s
, fd
);
3095 WSASetLastError( WSAEFAULT
);
3099 wsa
->buffers
= *buffers
;
3101 memset(&wsa
->buffers
, 0x0, sizeof(wsa
->buffers
));
3102 wsa
->buffer
= (char *)(wsa
+ 1);
3105 wsa
->file_bytes
= file_bytes
;
3106 wsa
->bytes_per_send
= bytes_per_send
;
3108 wsa
->offset
.QuadPart
= FILE_USE_FILE_POINTER_POSITION
;
3109 wsa
->write
.hSocket
= SOCKET2HANDLE(s
);
3110 wsa
->write
.addr
= NULL
;
3111 wsa
->write
.addrlen
.val
= 0;
3112 wsa
->write
.flags
= 0;
3113 wsa
->write
.lpFlags
= &wsa
->flags
;
3114 wsa
->write
.control
= NULL
;
3115 wsa
->write
.n_iovecs
= 0;
3116 wsa
->write
.first_iovec
= 0;
3117 wsa
->write
.user_overlapped
= overlapped
;
3120 IO_STATUS_BLOCK
*iosb
= (IO_STATUS_BLOCK
*)overlapped
;
3123 wsa
->offset
.u
.LowPart
= overlapped
->u
.s
.Offset
;
3124 wsa
->offset
.u
.HighPart
= overlapped
->u
.s
.OffsetHigh
;
3125 iosb
->u
.Status
= STATUS_PENDING
;
3126 iosb
->Information
= 0;
3127 status
= register_async( ASYNC_TYPE_WRITE
, SOCKET2HANDLE(s
), &wsa
->io
,
3128 overlapped
->hEvent
, NULL
, NULL
, iosb
);
3129 if(status
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
3130 release_sock_fd( s
, fd
);
3131 WSASetLastError( NtStatusToWSAError(status
) );
3137 status
= WS2_transmitfile_base( fd
, wsa
);
3138 if (status
== STATUS_PENDING
)
3141 do_block(fd
, POLLOUT
, -1);
3142 _sync_sock_state(s
); /* let wineserver notice connection */
3145 while (status
== STATUS_PENDING
);
3146 release_sock_fd( s
, fd
);
3148 if (status
!= STATUS_SUCCESS
)
3149 WSASetLastError( NtStatusToWSAError(status
) );
3150 HeapFree( GetProcessHeap(), 0, wsa
);
3151 return (status
== STATUS_SUCCESS
);
3154 /***********************************************************************
3155 * GetAcceptExSockaddrs
3157 static void WINAPI
WS2_GetAcceptExSockaddrs(PVOID buffer
, DWORD data_size
, DWORD local_size
, DWORD remote_size
,
3158 struct WS_sockaddr
**local_addr
, LPINT local_addr_len
,
3159 struct WS_sockaddr
**remote_addr
, LPINT remote_addr_len
)
3161 char *cbuf
= buffer
;
3162 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer
, data_size
, local_size
, remote_size
, local_addr
,
3163 local_addr_len
, remote_addr
, remote_addr_len
);
3166 *local_addr_len
= *(int *) cbuf
;
3167 *local_addr
= (struct WS_sockaddr
*)(cbuf
+ sizeof(int));
3171 *remote_addr_len
= *(int *) cbuf
;
3172 *remote_addr
= (struct WS_sockaddr
*)(cbuf
+ sizeof(int));
3175 /***********************************************************************
3178 int WINAPI
WSASendMsg( SOCKET s
, LPWSAMSG msg
, DWORD dwFlags
, LPDWORD lpNumberOfBytesSent
,
3179 LPWSAOVERLAPPED lpOverlapped
,
3180 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
3184 SetLastError( WSAEFAULT
);
3185 return SOCKET_ERROR
;
3188 return WS2_sendto( s
, msg
->lpBuffers
, msg
->dwBufferCount
, lpNumberOfBytesSent
,
3189 dwFlags
, msg
->name
, msg
->namelen
,
3190 lpOverlapped
, lpCompletionRoutine
);
3193 /***********************************************************************
3196 * Perform a receive operation that is capable of returning message
3197 * control headers. It is important to note that the WSAMSG parameter
3198 * must remain valid throughout the operation, even when an overlapped
3199 * receive is performed.
3201 static int WINAPI
WS2_WSARecvMsg( SOCKET s
, LPWSAMSG msg
, LPDWORD lpNumberOfBytesRecvd
,
3202 LPWSAOVERLAPPED lpOverlapped
,
3203 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
3207 SetLastError( WSAEFAULT
);
3208 return SOCKET_ERROR
;
3211 return WS2_recv_base( s
, msg
->lpBuffers
, msg
->dwBufferCount
, lpNumberOfBytesRecvd
,
3212 &msg
->dwFlags
, msg
->name
, &msg
->namelen
,
3213 lpOverlapped
, lpCompletionRoutine
, &msg
->Control
);
3216 /***********************************************************************
3217 * interface_bind (INTERNAL)
3219 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
3220 * operating only on the specified interface. This restriction consists of two components:
3221 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
3222 * 2) An incoming packet restriction dropping packets not meant for the interface.
3223 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
3224 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
3225 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
3226 * to receive broadcast packets on a socket that is bound to a specific network interface.
3228 static BOOL
interface_bind( SOCKET s
, int fd
, struct sockaddr
*addr
)
3230 struct sockaddr_in
*in_sock
= (struct sockaddr_in
*) addr
;
3231 in_addr_t bind_addr
= in_sock
->sin_addr
.s_addr
;
3232 PIP_ADAPTER_INFO adapters
= NULL
, adapter
;
3237 if (bind_addr
== htonl(INADDR_ANY
) || bind_addr
== htonl(INADDR_LOOPBACK
))
3238 return FALSE
; /* Not binding to a network adapter, special interface binding unnecessary. */
3239 if (_get_fd_type(fd
) != SOCK_DGRAM
)
3240 return FALSE
; /* Special interface binding is only necessary for UDP datagrams. */
3241 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
3243 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
3244 if (adapters
== NULL
|| GetAdaptersInfo(adapters
, &adap_size
) != NO_ERROR
)
3246 /* Search the IPv4 adapter list for the appropriate binding interface */
3247 for (adapter
= adapters
; adapter
!= NULL
; adapter
= adapter
->Next
)
3249 in_addr_t adapter_addr
= (in_addr_t
) inet_addr(adapter
->IpAddressList
.IpAddress
.String
);
3251 if (bind_addr
== adapter_addr
)
3253 #if defined(IP_BOUND_IF)
3254 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
3255 if (setsockopt(fd
, IPPROTO_IP
, IP_BOUND_IF
, &adapter
->Index
, sizeof(adapter
->Index
)) != 0)
3258 #elif defined(LINUX_BOUND_IF)
3259 in_addr_t ifindex
= (in_addr_t
) htonl(adapter
->Index
);
3260 struct interface_filter specific_interface_filter
;
3261 struct sock_fprog filter_prog
;
3263 if (setsockopt(fd
, IPPROTO_IP
, IP_UNICAST_IF
, &ifindex
, sizeof(ifindex
)) != 0)
3264 goto cleanup
; /* Failed to suggest egress interface */
3265 specific_interface_filter
= generic_interface_filter
;
3266 specific_interface_filter
.iface_rule
.k
= adapter
->Index
;
3267 specific_interface_filter
.ip_rule
.k
= htonl(adapter_addr
);
3268 filter_prog
.len
= sizeof(generic_interface_filter
)/sizeof(struct sock_filter
);
3269 filter_prog
.filter
= (struct sock_filter
*) &specific_interface_filter
;
3270 if (setsockopt(fd
, SOL_SOCKET
, SO_ATTACH_FILTER
, &filter_prog
, sizeof(filter_prog
)) != 0)
3271 goto cleanup
; /* Failed to specify incoming packet filter */
3274 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
3275 "receiving broadcast packets will not work on socket %04lx.\n", s
);
3280 /* Will soon be switching to INADDR_ANY: permit address reuse */
3281 if (ret
&& setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &enable
, sizeof(enable
)) == 0)
3282 TRACE("Socket %04lx bound to interface index %d\n", s
, adapter
->Index
);
3288 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s
);
3289 HeapFree(GetProcessHeap(), 0, adapters
);
3293 /***********************************************************************
3296 int WINAPI
WS_bind(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
)
3298 int fd
= get_sock_fd( s
, 0, NULL
);
3299 int res
= SOCKET_ERROR
;
3301 TRACE("socket %04lx, ptr %p %s, length %d\n", s
, name
, debugstr_sockaddr(name
), namelen
);
3305 if (!name
|| (name
->sa_family
&& !supported_pf(name
->sa_family
)))
3307 SetLastError(WSAEAFNOSUPPORT
);
3311 union generic_unix_sockaddr uaddr
;
3312 unsigned int uaddrlen
= ws_sockaddr_ws2u(name
, namelen
, &uaddr
);
3315 SetLastError(WSAEFAULT
);
3319 if (name
->sa_family
== WS_AF_INET
)
3321 struct sockaddr_in
*in4
= (struct sockaddr_in
*) &uaddr
;
3322 if (memcmp(&in4
->sin_addr
, magic_loopback_addr
, 4) == 0)
3324 /* Trying to bind to the default host interface, using
3325 * INADDR_ANY instead*/
3326 WARN("Trying to bind to magic IP address, using "
3327 "INADDR_ANY instead.\n");
3328 in4
->sin_addr
.s_addr
= htonl(INADDR_ANY
);
3330 else if (interface_bind(s
, fd
, &uaddr
.addr
))
3331 in4
->sin_addr
.s_addr
= htonl(INADDR_ANY
);
3333 if (bind(fd
, &uaddr
.addr
, uaddrlen
) < 0)
3335 int loc_errno
= errno
;
3336 WARN("\tfailure - errno = %i\n", errno
);
3341 SetLastError(WSAEINVAL
);
3346 socklen_t optlen
= sizeof(optval
);
3347 /* Windows >= 2003 will return different results depending on
3348 * SO_REUSEADDR, WSAEACCES may be returned representing that
3349 * the socket hijacking protection prevented the bind */
3350 if (!getsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&optval
, &optlen
) && optval
)
3352 SetLastError(WSAEACCES
);
3358 SetLastError(wsaErrno());
3364 res
=0; /* success */
3368 release_sock_fd( s
, fd
);
3373 /***********************************************************************
3374 * closesocket (WS2_32.3)
3376 int WINAPI
WS_closesocket(SOCKET s
)
3378 int res
= SOCKET_ERROR
, fd
;
3381 fd
= get_sock_fd(s
, FILE_READ_DATA
, NULL
);
3384 release_sock_fd(s
, fd
);
3385 if (CloseHandle(SOCKET2HANDLE(s
)))
3389 SetLastError(WSAENOTSOCK
);
3392 SetLastError(WSANOTINITIALISED
);
3393 TRACE("(socket %04lx) -> %d\n", s
, res
);
3397 static int do_connect(int fd
, const struct WS_sockaddr
* name
, int namelen
)
3399 union generic_unix_sockaddr uaddr
;
3400 unsigned int uaddrlen
= ws_sockaddr_ws2u(name
, namelen
, &uaddr
);
3405 if (name
->sa_family
== WS_AF_INET
)
3407 struct sockaddr_in
*in4
= (struct sockaddr_in
*) &uaddr
;
3408 if (memcmp(&in4
->sin_addr
, magic_loopback_addr
, 4) == 0)
3410 /* Trying to connect to magic replace-loopback address,
3411 * assuming we really want to connect to localhost */
3412 TRACE("Trying to connect to magic IP address, using "
3413 "INADDR_LOOPBACK instead.\n");
3414 in4
->sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
3418 if (connect(fd
, &uaddr
.addr
, uaddrlen
) == 0)
3424 /***********************************************************************
3425 * connect (WS2_32.4)
3427 int WINAPI
WS_connect(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
)
3429 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
3431 TRACE("socket %04lx, ptr %p %s, length %d\n", s
, name
, debugstr_sockaddr(name
), namelen
);
3437 int ret
= do_connect(fd
, name
, namelen
);
3439 goto connect_success
;
3441 if (ret
== WSAEINPROGRESS
)
3443 /* tell wineserver that a connection is in progress */
3444 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3446 FD_WINE_CONNECTED
|FD_WINE_LISTENING
);
3447 status
= _is_blocking( s
, &is_blocking
);
3450 release_sock_fd( s
, fd
);
3451 set_error( status
);
3452 return SOCKET_ERROR
;
3458 do_block(fd
, POLLIN
| POLLOUT
, -1);
3459 _sync_sock_state(s
); /* let wineserver notice connection */
3460 /* retrieve any error codes from it */
3461 result
= _get_sock_error(s
, FD_CONNECT_BIT
);
3463 SetLastError(NtStatusToWSAError(result
));
3466 goto connect_success
;
3471 SetLastError(WSAEWOULDBLOCK
);
3478 release_sock_fd( s
, fd
);
3480 return SOCKET_ERROR
;
3483 release_sock_fd( s
, fd
);
3484 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3485 FD_WINE_CONNECTED
|FD_READ
|FD_WRITE
,
3486 FD_CONNECT
|FD_WINE_LISTENING
);
3487 TRACE("\tconnected %04lx\n", s
);
3491 /***********************************************************************
3492 * WSAConnect (WS2_32.30)
3494 int WINAPI
WSAConnect( SOCKET s
, const struct WS_sockaddr
* name
, int namelen
,
3495 LPWSABUF lpCallerData
, LPWSABUF lpCalleeData
,
3496 LPQOS lpSQOS
, LPQOS lpGQOS
)
3498 if ( lpCallerData
|| lpCalleeData
|| lpSQOS
|| lpGQOS
)
3499 FIXME("unsupported parameters!\n");
3500 return WS_connect( s
, name
, namelen
);
3503 /***********************************************************************
3506 static BOOL WINAPI
WS2_ConnectEx(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
,
3507 PVOID sendBuf
, DWORD sendBufLen
, LPDWORD sent
, LPOVERLAPPED ov
)
3509 int fd
, ret
, status
;
3513 SetLastError( ERROR_INVALID_PARAMETER
);
3517 fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
3520 SetLastError( WSAENOTSOCK
);
3524 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
3525 s
, name
, debugstr_sockaddr(name
), namelen
, sendBuf
, sendBufLen
, ov
);
3527 ret
= is_fd_bound(fd
, NULL
, NULL
);
3530 SetLastError(ret
== -1 ? wsaErrno() : WSAEINVAL
);
3531 release_sock_fd( s
, fd
);
3535 ret
= do_connect(fd
, name
, namelen
);
3540 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3541 FD_WINE_CONNECTED
|FD_READ
|FD_WRITE
,
3542 FD_CONNECT
|FD_WINE_LISTENING
);
3544 wsabuf
.len
= sendBufLen
;
3545 wsabuf
.buf
= (char*) sendBuf
;
3547 /* WSASend takes care of completion if need be */
3548 if (WSASend(s
, &wsabuf
, sendBuf
? 1 : 0, sent
, 0, ov
, NULL
) != SOCKET_ERROR
)
3549 goto connection_success
;
3551 else if (ret
== WSAEINPROGRESS
)
3553 struct ws2_async
*wsa
;
3554 ULONG_PTR cvalue
= (((ULONG_PTR
)ov
->hEvent
& 1) == 0) ? (ULONG_PTR
)ov
: 0;
3556 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
3558 FD_WINE_CONNECTED
|FD_WINE_LISTENING
);
3560 /* Indirectly call WSASend */
3561 if (!(wsa
= (struct ws2_async
*)alloc_async_io( offsetof( struct ws2_async
, iovec
[1] ), WS2_async_send
)))
3563 SetLastError(WSAEFAULT
);
3567 IO_STATUS_BLOCK
*iosb
= (IO_STATUS_BLOCK
*)ov
;
3568 iosb
->u
.Status
= STATUS_PENDING
;
3569 iosb
->Information
= 0;
3571 wsa
->hSocket
= SOCKET2HANDLE(s
);
3573 wsa
->addrlen
.val
= 0;
3575 wsa
->lpFlags
= &wsa
->flags
;
3576 wsa
->control
= NULL
;
3577 wsa
->n_iovecs
= sendBuf
? 1 : 0;
3578 wsa
->first_iovec
= 0;
3579 wsa
->completion_func
= NULL
;
3580 wsa
->iovec
[0].iov_base
= sendBuf
;
3581 wsa
->iovec
[0].iov_len
= sendBufLen
;
3583 status
= register_async( ASYNC_TYPE_WRITE
, wsa
->hSocket
, &wsa
->io
, ov
->hEvent
,
3584 NULL
, (void *)cvalue
, iosb
);
3585 if (status
!= STATUS_PENDING
) HeapFree(GetProcessHeap(), 0, wsa
);
3587 /* If the connect already failed */
3588 if (status
== STATUS_PIPE_DISCONNECTED
)
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)
3674 unsigned int ifindex
;
3678 /* Check for IPv4, address 0.0.0.0 and UDP socket */
3679 if (addr
->sin_family
!= AF_INET
|| addr
->sin_addr
.s_addr
!= 0)
3681 if (_get_fd_type(fd
) != SOCK_DGRAM
)
3684 len
= sizeof(ifindex
);
3685 #if defined(IP_BOUND_IF)
3686 ret
= getsockopt(fd
, IPPROTO_IP
, IP_BOUND_IF
, &ifindex
, &len
);
3687 #elif defined(LINUX_BOUND_IF)
3688 ret
= getsockopt(fd
, IPPROTO_IP
, IP_UNICAST_IF
, &ifindex
, &len
);
3689 if (!ret
) 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
;
4910 total
= sizeof(void *);
4914 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff
));
4915 status
= WSAEOPNOTSUPP
;
4918 case WS_SIO_KEEPALIVE_VALS
:
4920 struct tcp_keepalive
*k
;
4921 int keepalive
, keepidle
, keepintvl
;
4923 if (!in_buff
|| in_size
< sizeof(struct tcp_keepalive
))
4925 SetLastError(WSAEFAULT
);
4926 return SOCKET_ERROR
;
4930 keepalive
= k
->onoff
? 1 : 0;
4931 keepidle
= max( 1, (k
->keepalivetime
+ 500) / 1000 );
4932 keepintvl
= max( 1, (k
->keepaliveinterval
+ 500) / 1000 );
4934 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive
, keepidle
, keepintvl
);
4936 fd
= get_sock_fd(s
, 0, NULL
);
4937 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&keepalive
, sizeof(int)) == -1)
4939 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPINTVL)
4940 /* these values need to be set only if SO_KEEPALIVE is enabled */
4943 #ifndef TCP_KEEPIDLE
4944 FIXME("ignoring keepalive timeout\n");
4946 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPIDLE
, (void *)&keepidle
, sizeof(int)) == -1)
4950 #ifdef TCP_KEEPINTVL
4951 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPINTVL
, (void *)&keepintvl
, sizeof(int)) == -1)
4954 FIXME("ignoring keepalive interval\n");
4959 FIXME("ignoring keepalive interval and timeout\n");
4961 release_sock_fd(s
, fd
);
4964 case WS_SIO_ROUTING_INTERFACE_QUERY
:
4966 struct WS_sockaddr
*daddr
= (struct WS_sockaddr
*)in_buff
;
4967 struct WS_sockaddr_in
*daddr_in
= (struct WS_sockaddr_in
*)daddr
;
4968 struct WS_sockaddr_in
*saddr_in
= out_buff
;
4969 MIB_IPFORWARDROW row
;
4970 PMIB_IPADDRTABLE ipAddrTable
= NULL
;
4971 DWORD size
, i
, found_index
;
4973 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4975 if (!in_buff
|| in_size
< sizeof(struct WS_sockaddr
) ||
4976 !out_buff
|| out_size
< sizeof(struct WS_sockaddr_in
) || !ret_size
)
4978 SetLastError(WSAEFAULT
);
4979 return SOCKET_ERROR
;
4981 if (daddr
->sa_family
!= WS_AF_INET
)
4983 FIXME("unsupported address family %d\n", daddr
->sa_family
);
4984 status
= WSAEAFNOSUPPORT
;
4987 if (GetBestRoute(daddr_in
->sin_addr
.S_un
.S_addr
, 0, &row
) != NOERROR
||
4988 GetIpAddrTable(NULL
, &size
, FALSE
) != ERROR_INSUFFICIENT_BUFFER
)
4993 ipAddrTable
= HeapAlloc(GetProcessHeap(), 0, size
);
4994 if (GetIpAddrTable(ipAddrTable
, &size
, FALSE
))
4996 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
5000 for (i
= 0, found_index
= ipAddrTable
->dwNumEntries
;
5001 i
< ipAddrTable
->dwNumEntries
; i
++)
5003 if (ipAddrTable
->table
[i
].dwIndex
== row
.dwForwardIfIndex
)
5006 if (found_index
== ipAddrTable
->dwNumEntries
)
5008 ERR("no matching IP address for interface %d\n",
5009 row
.dwForwardIfIndex
);
5010 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
5014 saddr_in
->sin_family
= WS_AF_INET
;
5015 saddr_in
->sin_addr
.S_un
.S_addr
= ipAddrTable
->table
[found_index
].dwAddr
;
5016 saddr_in
->sin_port
= 0;
5017 total
= sizeof(struct WS_sockaddr_in
);
5018 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
5021 case WS_SIO_SET_COMPATIBILITY_MODE
:
5022 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
5023 status
= WSAEOPNOTSUPP
;
5025 case WS_SIO_UDP_CONNRESET
:
5026 FIXME("WS_SIO_UDP_CONNRESET stub\n");
5028 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
5029 SetLastError(WSAEOPNOTSUPP
);
5030 return SOCKET_ERROR
;
5032 status
= WSAEOPNOTSUPP
;
5036 if (status
== WSAEOPNOTSUPP
)
5038 status
= server_ioctl_sock(s
, code
, in_buff
, in_size
, out_buff
, out_size
, &total
,
5039 overlapped
, completion
);
5040 if (status
!= WSAEOPNOTSUPP
)
5042 if (status
== 0 || status
== WSA_IO_PENDING
)
5043 TRACE("-> %s request\n", debugstr_wsaioctl(code
));
5045 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code
), status
);
5047 /* overlapped and completion operations will be handled by the server */
5052 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code
));
5057 FIXME( "completion routine %p not supported\n", completion
);
5059 else if (overlapped
)
5061 ULONG_PTR cvalue
= (overlapped
&& ((ULONG_PTR
)overlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)overlapped
: 0;
5062 overlapped
->Internal
= status
;
5063 overlapped
->InternalHigh
= total
;
5064 if (overlapped
->hEvent
) NtSetEvent( overlapped
->hEvent
, NULL
);
5065 if (cvalue
) WS_AddCompletion( HANDLE2SOCKET(s
), cvalue
, status
, total
);
5070 if (ret_size
) *ret_size
= total
;
5073 SetLastError( status
);
5074 return SOCKET_ERROR
;
5078 /***********************************************************************
5079 * ioctlsocket (WS2_32.10)
5081 int WINAPI
WS_ioctlsocket(SOCKET s
, LONG cmd
, WS_u_long
*argp
)
5084 return WSAIoctl( s
, cmd
, argp
, sizeof(WS_u_long
), argp
, sizeof(WS_u_long
), &ret_size
, NULL
, NULL
);
5087 /***********************************************************************
5088 * listen (WS2_32.13)
5090 int WINAPI
WS_listen(SOCKET s
, int backlog
)
5092 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
), ret
= SOCKET_ERROR
;
5094 TRACE("socket %04lx, backlog %d\n", s
, backlog
);
5097 int bound
= is_fd_bound(fd
, NULL
, NULL
);
5101 SetLastError(bound
== -1 ? wsaErrno() : WSAEINVAL
);
5103 else if (listen(fd
, backlog
) == 0)
5105 _enable_event(SOCKET2HANDLE(s
), FD_ACCEPT
,
5107 FD_CONNECT
|FD_WINE_CONNECTED
);
5111 SetLastError(wsaErrno());
5112 release_sock_fd( s
, fd
);
5115 SetLastError(WSAENOTSOCK
);
5119 /***********************************************************************
5122 int WINAPI
WS_recv(SOCKET s
, char *buf
, int len
, int flags
)
5124 DWORD n
, dwFlags
= flags
;
5130 if ( WS2_recv_base(s
, &wsabuf
, 1, &n
, &dwFlags
, NULL
, NULL
, NULL
, NULL
, NULL
) == SOCKET_ERROR
)
5131 return SOCKET_ERROR
;
5136 /***********************************************************************
5137 * recvfrom (WS2_32.17)
5139 int WINAPI
WS_recvfrom(SOCKET s
, char *buf
, INT len
, int flags
,
5140 struct WS_sockaddr
*from
, int *fromlen
)
5142 DWORD n
, dwFlags
= flags
;
5148 if ( WS2_recv_base(s
, &wsabuf
, 1, &n
, &dwFlags
, from
, fromlen
, NULL
, NULL
, NULL
) == SOCKET_ERROR
)
5149 return SOCKET_ERROR
;
5154 /* allocate a poll array for the corresponding fd sets */
5155 static struct pollfd
*fd_sets_to_poll( const WS_fd_set
*readfds
, const WS_fd_set
*writefds
,
5156 const WS_fd_set
*exceptfds
, int *count_ptr
)
5158 unsigned int i
, j
= 0, count
= 0;
5160 struct per_thread_data
*ptb
= get_per_thread_data();
5162 if (readfds
) count
+= readfds
->fd_count
;
5163 if (writefds
) count
+= writefds
->fd_count
;
5164 if (exceptfds
) count
+= exceptfds
->fd_count
;
5168 SetLastError(WSAEINVAL
);
5172 /* check if the cache can hold all descriptors, if not do the resizing */
5173 if (ptb
->fd_count
< count
)
5175 if (!(fds
= HeapAlloc(GetProcessHeap(), 0, count
* sizeof(fds
[0]))))
5177 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
5180 HeapFree(GetProcessHeap(), 0, ptb
->fd_cache
);
5181 ptb
->fd_cache
= fds
;
5182 ptb
->fd_count
= count
;
5185 fds
= ptb
->fd_cache
;
5188 for (i
= 0; i
< readfds
->fd_count
; i
++, j
++)
5190 fds
[j
].fd
= get_sock_fd( readfds
->fd_array
[i
], FILE_READ_DATA
, NULL
);
5191 if (fds
[j
].fd
== -1) goto failed
;
5193 if (is_fd_bound(fds
[j
].fd
, NULL
, NULL
) == 1)
5195 fds
[j
].events
= POLLIN
;
5199 release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
5205 for (i
= 0; i
< writefds
->fd_count
; i
++, j
++)
5207 fds
[j
].fd
= get_sock_fd( writefds
->fd_array
[i
], FILE_WRITE_DATA
, NULL
);
5208 if (fds
[j
].fd
== -1) goto failed
;
5210 if (is_fd_bound(fds
[j
].fd
, NULL
, NULL
) == 1 ||
5211 _get_fd_type(fds
[j
].fd
) == SOCK_DGRAM
)
5213 fds
[j
].events
= POLLOUT
;
5217 release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
5223 for (i
= 0; i
< exceptfds
->fd_count
; i
++, j
++)
5225 fds
[j
].fd
= get_sock_fd( exceptfds
->fd_array
[i
], 0, NULL
);
5226 if (fds
[j
].fd
== -1) goto failed
;
5228 if (is_fd_bound(fds
[j
].fd
, NULL
, NULL
) == 1)
5230 int oob_inlined
= 0;
5231 socklen_t olen
= sizeof(oob_inlined
);
5233 fds
[j
].events
= POLLHUP
;
5235 /* Check if we need to test for urgent data or not */
5236 getsockopt(fds
[j
].fd
, SOL_SOCKET
, SO_OOBINLINE
, (char*) &oob_inlined
, &olen
);
5238 fds
[j
].events
|= POLLPRI
;
5242 release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
5253 for (i
= 0; i
< readfds
->fd_count
&& j
< count
; i
++, j
++)
5254 if (fds
[j
].fd
!= -1) release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
5256 for (i
= 0; i
< writefds
->fd_count
&& j
< count
; i
++, j
++)
5257 if (fds
[j
].fd
!= -1) release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
5259 for (i
= 0; i
< exceptfds
->fd_count
&& j
< count
; i
++, j
++)
5260 if (fds
[j
].fd
!= -1) release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
5264 /* release the file descriptor obtained in fd_sets_to_poll */
5265 /* must be called with the original fd_set arrays, before calling get_poll_results */
5266 static void release_poll_fds( const WS_fd_set
*readfds
, const WS_fd_set
*writefds
,
5267 const WS_fd_set
*exceptfds
, struct pollfd
*fds
)
5269 unsigned int i
, j
= 0;
5273 for (i
= 0; i
< readfds
->fd_count
; i
++, j
++)
5274 if (fds
[j
].fd
!= -1) release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
5278 for (i
= 0; i
< writefds
->fd_count
; i
++, j
++)
5279 if (fds
[j
].fd
!= -1) release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
5283 for (i
= 0; i
< exceptfds
->fd_count
; i
++, j
++)
5285 if (fds
[j
].fd
== -1) continue;
5286 release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
5287 if (fds
[j
].revents
& POLLHUP
)
5289 int fd
= get_sock_fd( exceptfds
->fd_array
[i
], 0, NULL
);
5291 release_sock_fd( exceptfds
->fd_array
[i
], fd
);
5299 static int do_poll(struct pollfd
*pollfds
, int count
, int timeout
)
5301 struct timeval tv1
, tv2
;
5302 int ret
, torig
= timeout
;
5304 if (timeout
> 0) gettimeofday( &tv1
, 0 );
5306 while ((ret
= poll( pollfds
, count
, timeout
)) < 0)
5308 if (errno
!= EINTR
) break;
5309 if (timeout
< 0) continue;
5310 if (timeout
== 0) return 0;
5312 gettimeofday( &tv2
, 0 );
5314 tv2
.tv_sec
-= tv1
.tv_sec
;
5315 tv2
.tv_usec
-= tv1
.tv_usec
;
5316 if (tv2
.tv_usec
< 0)
5318 tv2
.tv_usec
+= 1000000;
5322 timeout
= torig
- (tv2
.tv_sec
* 1000) - (tv2
.tv_usec
+ 999) / 1000;
5323 if (timeout
<= 0) return 0;
5328 /* map the poll results back into the Windows fd sets */
5329 static int get_poll_results( WS_fd_set
*readfds
, WS_fd_set
*writefds
, WS_fd_set
*exceptfds
,
5330 const struct pollfd
*fds
)
5332 const struct pollfd
*poll_writefds
= fds
+ (readfds
? readfds
->fd_count
: 0);
5333 const struct pollfd
*poll_exceptfds
= poll_writefds
+ (writefds
? writefds
->fd_count
: 0);
5334 unsigned int i
, k
, total
= 0;
5338 for (i
= k
= 0; i
< readfds
->fd_count
; i
++)
5340 if (fds
[i
].revents
||
5341 (readfds
== writefds
&& (poll_writefds
[i
].revents
& POLLOUT
) && !(poll_writefds
[i
].revents
& POLLHUP
)) ||
5342 (readfds
== exceptfds
&& poll_exceptfds
[i
].revents
))
5343 readfds
->fd_array
[k
++] = readfds
->fd_array
[i
];
5345 readfds
->fd_count
= k
;
5348 if (writefds
&& writefds
!= readfds
)
5350 for (i
= k
= 0; i
< writefds
->fd_count
; i
++)
5352 if (((poll_writefds
[i
].revents
& POLLOUT
) && !(poll_writefds
[i
].revents
& POLLHUP
)) ||
5353 (writefds
== exceptfds
&& poll_exceptfds
[i
].revents
))
5354 writefds
->fd_array
[k
++] = writefds
->fd_array
[i
];
5356 writefds
->fd_count
= k
;
5359 if (exceptfds
&& exceptfds
!= readfds
&& exceptfds
!= writefds
)
5361 for (i
= k
= 0; i
< exceptfds
->fd_count
; i
++)
5362 if (poll_exceptfds
[i
].revents
) exceptfds
->fd_array
[k
++] = exceptfds
->fd_array
[i
];
5363 exceptfds
->fd_count
= k
;
5369 /***********************************************************************
5370 * select (WS2_32.18)
5372 int WINAPI
WS_select(int nfds
, WS_fd_set
*ws_readfds
,
5373 WS_fd_set
*ws_writefds
, WS_fd_set
*ws_exceptfds
,
5374 const struct WS_timeval
* ws_timeout
)
5376 struct pollfd
*pollfds
;
5377 int count
, ret
, timeout
= -1;
5379 TRACE("read %p, write %p, excp %p timeout %p\n",
5380 ws_readfds
, ws_writefds
, ws_exceptfds
, ws_timeout
);
5382 if (!(pollfds
= fd_sets_to_poll( ws_readfds
, ws_writefds
, ws_exceptfds
, &count
)))
5383 return SOCKET_ERROR
;
5386 timeout
= (ws_timeout
->tv_sec
* 1000) + (ws_timeout
->tv_usec
+ 999) / 1000;
5388 ret
= do_poll(pollfds
, count
, timeout
);
5389 release_poll_fds( ws_readfds
, ws_writefds
, ws_exceptfds
, pollfds
);
5391 if (ret
== -1) SetLastError(wsaErrno());
5392 else ret
= get_poll_results( ws_readfds
, ws_writefds
, ws_exceptfds
, pollfds
);
5396 /***********************************************************************
5399 int WINAPI
WSAPoll(WSAPOLLFD
*wfds
, ULONG count
, int timeout
)
5402 struct pollfd
*ufds
;
5406 SetLastError(WSAEINVAL
);
5407 return SOCKET_ERROR
;
5411 SetLastError(WSAEFAULT
);
5412 return SOCKET_ERROR
;
5415 if (!(ufds
= HeapAlloc(GetProcessHeap(), 0, count
* sizeof(ufds
[0]))))
5417 SetLastError(WSAENOBUFS
);
5418 return SOCKET_ERROR
;
5421 for (i
= 0; i
< count
; i
++)
5423 ufds
[i
].fd
= get_sock_fd(wfds
[i
].fd
, 0, NULL
);
5424 ufds
[i
].events
= convert_poll_w2u(wfds
[i
].events
);
5425 ufds
[i
].revents
= 0;
5428 ret
= do_poll(ufds
, count
, timeout
);
5430 for (i
= 0; i
< count
; i
++)
5432 if (ufds
[i
].fd
!= -1)
5434 release_sock_fd(wfds
[i
].fd
, ufds
[i
].fd
);
5435 if (ufds
[i
].revents
& POLLHUP
)
5437 /* Check if the socket still exists */
5438 int fd
= get_sock_fd(wfds
[i
].fd
, 0, NULL
);
5441 wfds
[i
].revents
= WS_POLLHUP
;
5442 release_sock_fd(wfds
[i
].fd
, fd
);
5445 wfds
[i
].revents
= WS_POLLNVAL
;
5448 wfds
[i
].revents
= convert_poll_u2w(ufds
[i
].revents
);
5451 wfds
[i
].revents
= WS_POLLNVAL
;
5454 HeapFree(GetProcessHeap(), 0, ufds
);
5458 /* helper to send completion messages for client-only i/o operation case */
5459 static void WS_AddCompletion( SOCKET sock
, ULONG_PTR CompletionValue
, NTSTATUS CompletionStatus
,
5462 SERVER_START_REQ( add_fd_completion
)
5464 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(sock
) );
5465 req
->cvalue
= CompletionValue
;
5466 req
->status
= CompletionStatus
;
5467 req
->information
= Information
;
5468 wine_server_call( req
);
5474 /***********************************************************************
5477 int WINAPI
WS_send(SOCKET s
, const char *buf
, int len
, int flags
)
5483 wsabuf
.buf
= (char*) buf
;
5485 if ( WS2_sendto( s
, &wsabuf
, 1, &n
, flags
, NULL
, 0, NULL
, NULL
) == SOCKET_ERROR
)
5486 return SOCKET_ERROR
;
5491 /***********************************************************************
5492 * WSASend (WS2_32.72)
5494 INT WINAPI
WSASend( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
5495 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
5496 LPWSAOVERLAPPED lpOverlapped
,
5497 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
5499 return WS2_sendto( s
, lpBuffers
, dwBufferCount
, lpNumberOfBytesSent
, dwFlags
,
5500 NULL
, 0, lpOverlapped
, lpCompletionRoutine
);
5503 /***********************************************************************
5504 * WSASendDisconnect (WS2_32.73)
5506 INT WINAPI
WSASendDisconnect( SOCKET s
, LPWSABUF lpBuffers
)
5508 return WS_shutdown( s
, SD_SEND
);
5512 static int WS2_sendto( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
5513 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
5514 const struct WS_sockaddr
*to
, int tolen
,
5515 LPWSAOVERLAPPED lpOverlapped
,
5516 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
5518 unsigned int i
, options
;
5519 int n
, fd
, err
, overlapped
, flags
;
5520 struct ws2_async
*wsa
= NULL
, localwsa
;
5521 int totalLength
= 0;
5525 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
5526 s
, lpBuffers
, dwBufferCount
, dwFlags
,
5527 to
, tolen
, lpOverlapped
, lpCompletionRoutine
);
5529 fd
= get_sock_fd( s
, FILE_WRITE_DATA
, &options
);
5530 TRACE( "fd=%d, options=%x\n", fd
, options
);
5532 if ( fd
== -1 ) return SOCKET_ERROR
;
5534 if (!lpOverlapped
&& !lpNumberOfBytesSent
)
5540 overlapped
= (lpOverlapped
|| lpCompletionRoutine
) &&
5541 !(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
));
5542 if (overlapped
|| dwBufferCount
> 1)
5544 if (!(wsa
= (struct ws2_async
*)alloc_async_io( offsetof(struct ws2_async
, iovec
[dwBufferCount
]),
5554 wsa
->hSocket
= SOCKET2HANDLE(s
);
5555 wsa
->addr
= (struct WS_sockaddr
*)to
;
5556 wsa
->addrlen
.val
= tolen
;
5557 wsa
->flags
= dwFlags
;
5558 wsa
->lpFlags
= &wsa
->flags
;
5559 wsa
->control
= NULL
;
5560 wsa
->n_iovecs
= dwBufferCount
;
5561 wsa
->first_iovec
= 0;
5562 for ( i
= 0; i
< dwBufferCount
; i
++ )
5564 wsa
->iovec
[i
].iov_base
= lpBuffers
[i
].buf
;
5565 wsa
->iovec
[i
].iov_len
= lpBuffers
[i
].len
;
5566 totalLength
+= lpBuffers
[i
].len
;
5569 flags
= convert_flags(dwFlags
);
5570 n
= WS2_send( fd
, wsa
, flags
);
5571 if (n
== -1 && errno
!= EAGAIN
)
5579 IO_STATUS_BLOCK
*iosb
= lpOverlapped
? (IO_STATUS_BLOCK
*)lpOverlapped
: &wsa
->local_iosb
;
5580 ULONG_PTR cvalue
= (lpOverlapped
&& ((ULONG_PTR
)lpOverlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)lpOverlapped
: 0;
5582 wsa
->user_overlapped
= lpOverlapped
;
5583 wsa
->completion_func
= lpCompletionRoutine
;
5584 release_sock_fd( s
, fd
);
5586 if (n
== -1 || n
< totalLength
)
5588 iosb
->u
.Status
= STATUS_PENDING
;
5589 iosb
->Information
= n
== -1 ? 0 : n
;
5591 if (wsa
->completion_func
)
5592 err
= register_async( ASYNC_TYPE_WRITE
, wsa
->hSocket
, &wsa
->io
, NULL
,
5593 ws2_async_apc
, wsa
, iosb
);
5595 err
= register_async( ASYNC_TYPE_WRITE
, wsa
->hSocket
, &wsa
->io
, lpOverlapped
->hEvent
,
5596 NULL
, (void *)cvalue
, iosb
);
5598 /* Enable the event only after starting the async. The server will deliver it as soon as
5599 the async is done. */
5600 _enable_event(SOCKET2HANDLE(s
), FD_WRITE
, 0, 0);
5602 if (err
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
5603 SetLastError(NtStatusToWSAError( err
));
5604 return SOCKET_ERROR
;
5607 iosb
->u
.Status
= STATUS_SUCCESS
;
5608 iosb
->Information
= n
;
5609 if (lpNumberOfBytesSent
) *lpNumberOfBytesSent
= n
;
5610 if (!wsa
->completion_func
)
5612 if (cvalue
) WS_AddCompletion( s
, cvalue
, STATUS_SUCCESS
, n
);
5613 if (lpOverlapped
->hEvent
) SetEvent( lpOverlapped
->hEvent
);
5614 HeapFree( GetProcessHeap(), 0, wsa
);
5616 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC
)ws2_async_apc
,
5617 (ULONG_PTR
)wsa
, (ULONG_PTR
)iosb
, 0 );
5618 SetLastError(ERROR_SUCCESS
);
5622 if ((err
= _is_blocking( s
, &is_blocking
)))
5624 err
= NtStatusToWSAError( err
);
5630 /* On a blocking non-overlapped stream socket,
5631 * sending blocks until the entire buffer is sent. */
5632 DWORD timeout_start
= GetTickCount();
5634 bytes_sent
= n
== -1 ? 0 : n
;
5636 while (wsa
->first_iovec
< wsa
->n_iovecs
)
5639 int poll_timeout
= -1;
5640 INT64 timeout
= get_rcvsnd_timeo(fd
, FALSE
);
5644 timeout
-= GetTickCount() - timeout_start
;
5645 if (timeout
< 0) poll_timeout
= 0;
5646 else poll_timeout
= timeout
<= INT_MAX
? timeout
: INT_MAX
;
5650 pfd
.events
= POLLOUT
;
5652 if (!poll_timeout
|| !poll( &pfd
, 1, poll_timeout
))
5655 goto error
; /* msdn says a timeout in send is fatal */
5658 n
= WS2_send( fd
, wsa
, flags
);
5659 if (n
== -1 && errno
!= EAGAIN
)
5669 else /* non-blocking */
5671 if (n
< totalLength
)
5672 _enable_event(SOCKET2HANDLE(s
), FD_WRITE
, 0, 0);
5675 err
= WSAEWOULDBLOCK
;
5681 TRACE(" -> %i bytes\n", bytes_sent
);
5683 if (lpNumberOfBytesSent
) *lpNumberOfBytesSent
= bytes_sent
;
5684 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
5685 release_sock_fd( s
, fd
);
5686 SetLastError(ERROR_SUCCESS
);
5690 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
5691 release_sock_fd( s
, fd
);
5692 WARN(" -> ERROR %d\n", err
);
5694 return SOCKET_ERROR
;
5697 /***********************************************************************
5698 * WSASendTo (WS2_32.74)
5700 INT WINAPI
WSASendTo( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
5701 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
5702 const struct WS_sockaddr
*to
, int tolen
,
5703 LPWSAOVERLAPPED lpOverlapped
,
5704 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
5706 return WS2_sendto( s
, lpBuffers
, dwBufferCount
,
5707 lpNumberOfBytesSent
, dwFlags
,
5709 lpOverlapped
, lpCompletionRoutine
);
5712 /***********************************************************************
5713 * sendto (WS2_32.20)
5715 int WINAPI
WS_sendto(SOCKET s
, const char *buf
, int len
, int flags
,
5716 const struct WS_sockaddr
*to
, int tolen
)
5722 wsabuf
.buf
= (char*) buf
;
5724 if ( WS2_sendto(s
, &wsabuf
, 1, &n
, flags
, to
, tolen
, NULL
, NULL
) == SOCKET_ERROR
)
5725 return SOCKET_ERROR
;
5730 /***********************************************************************
5731 * setsockopt (WS2_32.21)
5733 int WINAPI
WS_setsockopt(SOCKET s
, int level
, int optname
,
5734 const char *optval
, int optlen
)
5738 struct linger linger
;
5739 struct timeval tval
;
5741 TRACE("(socket %04lx, %s, optval %s, optlen %d)\n", s
,
5742 debugstr_sockopt(level
, optname
), debugstr_optval(optval
, optlen
),
5745 /* some broken apps pass the value directly instead of a pointer to it */
5746 if(optlen
&& IS_INTRESOURCE(optval
))
5748 SetLastError(WSAEFAULT
);
5749 return SOCKET_ERROR
;
5757 /* Some options need some conversion before they can be sent to
5758 * setsockopt. The conversions are done here, then they will fall through
5759 * to the general case. Special options that are not passed to
5760 * setsockopt follow below that.*/
5762 case WS_SO_DONTLINGER
:
5765 SetLastError(WSAEFAULT
);
5766 return SOCKET_ERROR
;
5768 linger
.l_onoff
= *(const int*)optval
== 0;
5769 linger
.l_linger
= 0;
5771 optname
= SO_LINGER
;
5772 optval
= (char*)&linger
;
5773 optlen
= sizeof(struct linger
);
5779 SetLastError(WSAEFAULT
);
5780 return SOCKET_ERROR
;
5782 linger
.l_onoff
= ((LINGER
*)optval
)->l_onoff
;
5783 linger
.l_linger
= ((LINGER
*)optval
)->l_linger
;
5785 optname
= SO_LINGER
;
5786 optval
= (char*)&linger
;
5787 optlen
= sizeof(struct linger
);
5791 if (*(const int*)optval
< 2048)
5793 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval
);
5798 /* The options listed here don't need any special handling. Thanks to
5799 * the conversion happening above, options from there will fall through
5801 case WS_SO_ACCEPTCONN
:
5802 case WS_SO_BROADCAST
:
5804 case WS_SO_KEEPALIVE
:
5805 case WS_SO_OOBINLINE
:
5806 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
5807 * however, using it the BSD way fixes bug 8513 and seems to be what
5808 * most programmers assume, anyway */
5809 case WS_SO_REUSEADDR
:
5812 convert_sockopt(&level
, &optname
);
5815 /* SO_DEBUG is a privileged operation, ignore it. */
5817 TRACE("Ignoring SO_DEBUG\n");
5820 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
5821 * socket. According to MSDN, this option is silently ignored.*/
5822 case WS_SO_DONTROUTE
:
5823 TRACE("Ignoring SO_DONTROUTE\n");
5826 /* Stops two sockets from being bound to the same port. Always happens
5827 * on unix systems, so just drop it. */
5828 case WS_SO_EXCLUSIVEADDRUSE
:
5829 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
5832 /* After a ConnectEx call succeeds, the socket can't be used with half of the
5833 * normal winsock functions on windows. We don't have that problem. */
5834 case WS_SO_UPDATE_CONNECT_CONTEXT
:
5835 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
5838 /* After a AcceptEx call succeeds, the socket can't be used with half of the
5839 * normal winsock functions on windows. We don't have that problem. */
5840 case WS_SO_UPDATE_ACCEPT_CONTEXT
:
5841 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
5844 /* SO_OPENTYPE does not require a valid socket handle. */
5845 case WS_SO_OPENTYPE
:
5846 if (!optlen
|| optlen
< sizeof(int) || !optval
)
5848 SetLastError(WSAEFAULT
);
5849 return SOCKET_ERROR
;
5851 get_per_thread_data()->opentype
= *(const int *)optval
;
5852 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval
) );
5856 case WS_SO_RCVTIMEO
:
5859 case WS_SO_SNDTIMEO
:
5861 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
5862 if (optval
&& optlen
== sizeof(UINT32
)) {
5863 /* WinSock passes milliseconds instead of struct timeval */
5864 tval
.tv_usec
= (*(const UINT32
*)optval
% 1000) * 1000;
5865 tval
.tv_sec
= *(const UINT32
*)optval
/ 1000;
5866 /* min of 500 milliseconds */
5867 if (tval
.tv_sec
== 0 && tval
.tv_usec
&& tval
.tv_usec
< 500000)
5868 tval
.tv_usec
= 500000;
5869 optlen
= sizeof(struct timeval
);
5870 optval
= (char*)&tval
;
5871 } else if (optlen
== sizeof(struct timeval
)) {
5872 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen
);
5874 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen
);
5877 convert_sockopt(&level
, &optname
);
5882 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname
);
5883 SetLastError(WSAENOPROTOOPT
);
5884 return SOCKET_ERROR
;
5886 break; /* case WS_SOL_SOCKET */
5889 case WS_NSPROTO_IPX
:
5893 return set_ipx_packettype(s
, *(int*)optval
);
5895 case WS_IPX_FILTERPTYPE
:
5896 /* Sets the receive filter packet type, at the moment we don't support it */
5897 FIXME("IPX_FILTERPTYPE: %x\n", *optval
);
5898 /* Returning 0 is better for now than returning a SOCKET_ERROR */
5902 FIXME("opt_name:%x\n", optname
);
5903 return SOCKET_ERROR
;
5905 break; /* case WS_NSPROTO_IPX */
5908 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
5909 case WS_IPPROTO_TCP
:
5912 case WS_TCP_NODELAY
:
5913 convert_sockopt(&level
, &optname
);
5916 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname
);
5917 return SOCKET_ERROR
;
5924 case WS_IP_ADD_MEMBERSHIP
:
5925 case WS_IP_DROP_MEMBERSHIP
:
5929 case WS_IP_MULTICAST_IF
:
5930 case WS_IP_MULTICAST_LOOP
:
5931 case WS_IP_MULTICAST_TTL
:
5938 #ifdef IP_UNICAST_IF
5939 case WS_IP_UNICAST_IF
:
5941 convert_sockopt(&level
, &optname
);
5943 case WS_IP_DONTFRAGMENT
:
5944 return set_dont_fragment(s
, IPPROTO_IP
, *(BOOL
*)optval
) ? 0 : SOCKET_ERROR
;
5946 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname
);
5947 return SOCKET_ERROR
;
5951 case WS_IPPROTO_IPV6
:
5954 #ifdef IPV6_ADD_MEMBERSHIP
5955 case WS_IPV6_ADD_MEMBERSHIP
:
5957 #ifdef IPV6_DROP_MEMBERSHIP
5958 case WS_IPV6_DROP_MEMBERSHIP
:
5960 case WS_IPV6_MULTICAST_IF
:
5961 case WS_IPV6_MULTICAST_HOPS
:
5962 case WS_IPV6_MULTICAST_LOOP
:
5963 case WS_IPV6_UNICAST_HOPS
:
5964 #ifdef IPV6_UNICAST_IF
5965 case WS_IPV6_UNICAST_IF
:
5967 convert_sockopt(&level
, &optname
);
5969 case WS_IPV6_DONTFRAG
:
5970 return set_dont_fragment(s
, IPPROTO_IPV6
, *(BOOL
*)optval
) ? 0 : SOCKET_ERROR
;
5971 case WS_IPV6_PROTECTION_LEVEL
:
5972 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
5974 case WS_IPV6_V6ONLY
:
5976 union generic_unix_sockaddr uaddr
;
5980 fd
= get_sock_fd( s
, 0, NULL
);
5981 if (fd
== -1) return SOCKET_ERROR
;
5983 bound
= is_fd_bound(fd
, &uaddr
, &uaddrlen
);
5984 release_sock_fd( s
, fd
);
5985 if (bound
== 0 && uaddr
.addr
.sa_family
== AF_INET
)
5987 /* Changing IPV6_V6ONLY succeeds on AF_INET (IPv4) socket
5988 * on Windows (with IPv6 support) if the socket is unbound.
5989 * It is essentially a noop, though Windows does store the value
5991 WARN("Silently ignoring IPPROTO_IPV6+IPV6_V6ONLY on AF_INET socket\n");
5994 level
= IPPROTO_IPV6
;
5995 optname
= IPV6_V6ONLY
;
5999 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname
);
6000 return SOCKET_ERROR
;
6005 WARN("Unknown level: 0x%08x\n", level
);
6006 SetLastError(WSAEINVAL
);
6007 return SOCKET_ERROR
;
6008 } /* end switch(level) */
6010 /* avoid endianness issues if argument is a 16-bit int */
6011 if (optval
&& optlen
< sizeof(int))
6013 woptval
= *((const INT16
*) optval
);
6014 optval
= (char*) &woptval
;
6015 woptval
&= (1 << optlen
* 8) - 1;
6018 fd
= get_sock_fd( s
, 0, NULL
);
6019 if (fd
== -1) return SOCKET_ERROR
;
6021 if (setsockopt(fd
, level
, optname
, optval
, optlen
) == 0)
6024 if (level
== SOL_SOCKET
&& optname
== SO_REUSEADDR
&&
6025 setsockopt(fd
, level
, SO_REUSEPORT
, optval
, optlen
) != 0)
6027 SetLastError(wsaErrno());
6028 release_sock_fd( s
, fd
);
6029 return SOCKET_ERROR
;
6032 release_sock_fd( s
, fd
);
6035 TRACE("Setting socket error, %d\n", wsaErrno());
6036 SetLastError(wsaErrno());
6037 release_sock_fd( s
, fd
);
6039 return SOCKET_ERROR
;
6042 /***********************************************************************
6043 * shutdown (WS2_32.22)
6045 int WINAPI
WS_shutdown(SOCKET s
, int how
)
6047 int fd
, err
= WSAENOTSOCK
;
6048 unsigned int options
= 0, clear_flags
= 0;
6050 fd
= get_sock_fd( s
, 0, &options
);
6051 TRACE("socket %04lx, how 0x%x, options 0x%x\n", s
, how
, options
);
6054 return SOCKET_ERROR
;
6058 case SD_RECEIVE
: /* drop receives */
6059 clear_flags
|= FD_READ
;
6061 case SD_SEND
: /* drop sends */
6062 clear_flags
|= FD_WRITE
;
6064 case SD_BOTH
: /* drop all */
6065 clear_flags
|= FD_READ
|FD_WRITE
;
6068 clear_flags
|= FD_WINE_LISTENING
;
6071 if (!(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
)))
6076 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_READ
);
6079 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_WRITE
);
6083 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_READ
);
6084 if (!err
) err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_WRITE
);
6087 if (err
) goto error
;
6089 else /* non-overlapped mode */
6091 if ( shutdown( fd
, how
) )
6098 release_sock_fd( s
, fd
);
6099 _enable_event( SOCKET2HANDLE(s
), 0, 0, clear_flags
);
6100 if ( how
> 1) WSAAsyncSelect( s
, 0, 0, 0 );
6104 release_sock_fd( s
, fd
);
6105 _enable_event( SOCKET2HANDLE(s
), 0, 0, clear_flags
);
6106 SetLastError( err
);
6107 return SOCKET_ERROR
;
6110 /***********************************************************************
6111 * socket (WS2_32.23)
6113 SOCKET WINAPI
WS_socket(int af
, int type
, int protocol
)
6115 TRACE("af=%d type=%d protocol=%d\n", af
, type
, protocol
);
6117 return WSASocketW( af
, type
, protocol
, NULL
, 0,
6118 get_per_thread_data()->opentype
? 0 : WSA_FLAG_OVERLAPPED
);
6122 /***********************************************************************
6123 * gethostbyaddr (WS2_32.51)
6125 struct WS_hostent
* WINAPI
WS_gethostbyaddr(const char *addr
, int len
, int type
)
6127 struct WS_hostent
*retval
= NULL
;
6128 struct hostent
* host
;
6129 int unixtype
= convert_af_w2u(type
);
6130 const char *paddr
= addr
;
6131 unsigned long loopback
;
6132 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6134 int ebufsize
= 1024;
6135 struct hostent hostentry
;
6136 int locerr
= ENOBUFS
;
6139 /* convert back the magic loopback address if necessary */
6140 if (unixtype
== AF_INET
&& len
== 4 && !memcmp(addr
, magic_loopback_addr
, 4))
6142 loopback
= htonl(INADDR_LOOPBACK
);
6143 paddr
= (char*) &loopback
;
6146 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6148 extrabuf
=HeapAlloc(GetProcessHeap(),0,ebufsize
) ;
6150 int res
= gethostbyaddr_r(paddr
, len
, unixtype
,
6151 &hostentry
, extrabuf
, ebufsize
, &host
, &locerr
);
6152 if (res
!= ERANGE
) break;
6154 extrabuf
=HeapReAlloc(GetProcessHeap(),0,extrabuf
,ebufsize
) ;
6156 if (host
) retval
= WS_dup_he(host
);
6157 else SetLastError((locerr
< 0) ? wsaErrno() : wsaHerrno(locerr
));
6158 HeapFree(GetProcessHeap(),0,extrabuf
);
6160 EnterCriticalSection( &csWSgetXXXbyYYY
);
6161 host
= gethostbyaddr(paddr
, len
, unixtype
);
6162 if (host
) retval
= WS_dup_he(host
);
6163 else SetLastError((h_errno
< 0) ? wsaErrno() : wsaHerrno(h_errno
));
6164 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6166 TRACE("ptr %p, len %d, type %d ret %p\n", addr
, len
, type
, retval
);
6170 /***********************************************************************
6171 * WS_compare_routes_by_metric_asc (INTERNAL)
6173 * Comparison function for qsort(), for sorting two routes (struct route)
6174 * by metric in ascending order.
6176 static int WS_compare_routes_by_metric_asc(const void *left
, const void *right
)
6178 const struct route
*a
= left
, *b
= right
;
6179 if (a
->default_route
&& b
->default_route
)
6180 return a
->default_route
- b
->default_route
;
6181 if (a
->default_route
&& !b
->default_route
)
6183 if (b
->default_route
&& !a
->default_route
)
6185 return a
->metric
- b
->metric
;
6188 /***********************************************************************
6189 * WS_get_local_ips (INTERNAL)
6191 * Returns the list of local IP addresses by going through the network
6192 * adapters and using the local routing table to sort the addresses
6193 * from highest routing priority to lowest routing priority. This
6194 * functionality is inferred from the description for obtaining local
6195 * IP addresses given in the Knowledge Base Article Q160215.
6197 * Please note that the returned hostent is only freed when the thread
6198 * closes and is replaced if another hostent is requested.
6200 static struct WS_hostent
* WS_get_local_ips( char *hostname
)
6202 int numroutes
= 0, i
, j
, default_routes
= 0;
6204 PIP_ADAPTER_INFO adapters
= NULL
, k
;
6205 struct WS_hostent
*hostlist
= NULL
;
6206 PMIB_IPFORWARDTABLE routes
= NULL
;
6207 struct route
*route_addrs
= NULL
;
6208 DWORD adap_size
, route_size
;
6210 /* Obtain the size of the adapter list and routing table, also allocate memory */
6211 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
6213 if (GetIpForwardTable(NULL
, &route_size
, FALSE
) != ERROR_INSUFFICIENT_BUFFER
)
6215 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
6216 routes
= HeapAlloc(GetProcessHeap(), 0, route_size
);
6217 route_addrs
= HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
6218 if (adapters
== NULL
|| routes
== NULL
|| route_addrs
== NULL
)
6220 /* Obtain the adapter list and the full routing table */
6221 if (GetAdaptersInfo(adapters
, &adap_size
) != NO_ERROR
)
6223 if (GetIpForwardTable(routes
, &route_size
, FALSE
) != NO_ERROR
)
6225 /* Store the interface associated with each route */
6226 for (n
= 0; n
< routes
->dwNumEntries
; n
++)
6229 DWORD ifmetric
, ifdefault
= 0;
6230 BOOL exists
= FALSE
;
6232 /* Check if this is a default route (there may be more than one) */
6233 if (!routes
->table
[n
].dwForwardDest
)
6234 ifdefault
= ++default_routes
;
6235 else if (routes
->table
[n
].u1
.ForwardType
!= MIB_IPROUTE_TYPE_DIRECT
)
6237 ifindex
= routes
->table
[n
].dwForwardIfIndex
;
6238 ifmetric
= routes
->table
[n
].dwForwardMetric1
;
6239 /* Only store the lowest valued metric for an interface */
6240 for (j
= 0; j
< numroutes
; j
++)
6242 if (route_addrs
[j
].interface
== ifindex
)
6244 if (route_addrs
[j
].metric
> ifmetric
)
6245 route_addrs
[j
].metric
= ifmetric
;
6251 route_addrs
= HeapReAlloc(GetProcessHeap(), 0, route_addrs
, (numroutes
+1)*sizeof(struct route
));
6252 if (route_addrs
== NULL
)
6253 goto cleanup
; /* Memory allocation error, fail gracefully */
6254 route_addrs
[numroutes
].interface
= ifindex
;
6255 route_addrs
[numroutes
].metric
= ifmetric
;
6256 route_addrs
[numroutes
].default_route
= ifdefault
;
6257 /* If no IP is found in the next step (for whatever reason)
6258 * then fall back to the magic loopback address.
6260 memcpy(&(route_addrs
[numroutes
].addr
.s_addr
), magic_loopback_addr
, 4);
6264 goto cleanup
; /* No routes, fall back to the Magic IP */
6265 /* Find the IP address associated with each found interface */
6266 for (i
= 0; i
< numroutes
; i
++)
6268 for (k
= adapters
; k
!= NULL
; k
= k
->Next
)
6270 char *ip
= k
->IpAddressList
.IpAddress
.String
;
6272 if (route_addrs
[i
].interface
== k
->Index
)
6273 route_addrs
[i
].addr
.s_addr
= (in_addr_t
) inet_addr(ip
);
6276 /* Allocate a hostent and enough memory for all the IPs,
6277 * including the NULL at the end of the list.
6279 hostlist
= WS_create_he(hostname
, 1, 0, numroutes
+1, sizeof(struct in_addr
));
6280 if (hostlist
== NULL
)
6281 goto cleanup
; /* Failed to allocate a hostent for the list of IPs */
6282 hostlist
->h_addr_list
[numroutes
] = NULL
; /* NULL-terminate the address list */
6283 hostlist
->h_aliases
[0] = NULL
; /* NULL-terminate the alias list */
6284 hostlist
->h_addrtype
= AF_INET
;
6285 hostlist
->h_length
= sizeof(struct in_addr
); /* = 4 */
6286 /* Reorder the entries before placing them in the host list. Windows expects
6287 * the IP list in order from highest priority to lowest (the critical thing
6288 * is that most applications expect the first IP to be the default route).
6291 qsort(route_addrs
, numroutes
, sizeof(struct route
), WS_compare_routes_by_metric_asc
);
6293 for (i
= 0; i
< numroutes
; i
++)
6294 (*(struct in_addr
*) hostlist
->h_addr_list
[i
]) = route_addrs
[i
].addr
;
6296 /* Cleanup all allocated memory except the address list,
6297 * the address list is used by the calling app.
6300 HeapFree(GetProcessHeap(), 0, route_addrs
);
6301 HeapFree(GetProcessHeap(), 0, adapters
);
6302 HeapFree(GetProcessHeap(), 0, routes
);
6306 /***********************************************************************
6307 * gethostbyname (WS2_32.52)
6309 struct WS_hostent
* WINAPI
WS_gethostbyname(const char* name
)
6311 struct WS_hostent
*retval
= NULL
;
6312 struct hostent
* host
;
6313 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6316 struct hostent hostentry
;
6317 int locerr
= ENOBUFS
;
6321 SetLastError(WSANOTINITIALISED
);
6324 if( gethostname( hostname
, 100) == -1) {
6325 SetLastError(WSAENOBUFS
); /* appropriate ? */
6328 if( !name
|| !name
[0]) {
6331 /* If the hostname of the local machine is requested then return the
6332 * complete list of local IP addresses */
6333 if(strcmp(name
, hostname
) == 0)
6334 retval
= WS_get_local_ips(hostname
);
6335 /* If any other hostname was requested (or the routing table lookup failed)
6336 * then return the IP found by the host OS */
6339 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6341 extrabuf
=HeapAlloc(GetProcessHeap(),0,ebufsize
) ;
6343 int res
= gethostbyname_r(name
, &hostentry
, extrabuf
, ebufsize
, &host
, &locerr
);
6344 if( res
!= ERANGE
) break;
6346 extrabuf
=HeapReAlloc(GetProcessHeap(),0,extrabuf
,ebufsize
) ;
6348 if (!host
) SetLastError((locerr
< 0) ? wsaErrno() : wsaHerrno(locerr
));
6350 EnterCriticalSection( &csWSgetXXXbyYYY
);
6351 host
= gethostbyname(name
);
6352 if (!host
) SetLastError((h_errno
< 0) ? wsaErrno() : wsaHerrno(h_errno
));
6354 if (host
) retval
= WS_dup_he(host
);
6355 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6356 HeapFree(GetProcessHeap(),0,extrabuf
);
6358 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6361 if (retval
&& retval
->h_addr_list
[0][0] == 127 &&
6362 strcmp(name
, "localhost") != 0)
6364 /* hostname != "localhost" but has loopback address. replace by our
6365 * special address.*/
6366 memcpy(retval
->h_addr_list
[0], magic_loopback_addr
, 4);
6368 TRACE( "%s ret %p\n", debugstr_a(name
), retval
);
6373 /***********************************************************************
6374 * getprotobyname (WS2_32.53)
6376 struct WS_protoent
* WINAPI
WS_getprotobyname(const char* name
)
6378 struct WS_protoent
* retval
= NULL
;
6379 #ifdef HAVE_GETPROTOBYNAME
6380 struct protoent
* proto
;
6381 EnterCriticalSection( &csWSgetXXXbyYYY
);
6382 if( (proto
= getprotobyname(name
)) != NULL
)
6384 retval
= WS_dup_pe(proto
);
6387 MESSAGE("protocol %s not found; You might want to add "
6388 "this to /etc/protocols\n", debugstr_a(name
) );
6389 SetLastError(WSANO_DATA
);
6391 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6393 TRACE( "%s ret %p\n", debugstr_a(name
), retval
);
6398 /***********************************************************************
6399 * getprotobynumber (WS2_32.54)
6401 struct WS_protoent
* WINAPI
WS_getprotobynumber(int number
)
6403 struct WS_protoent
* retval
= NULL
;
6404 #ifdef HAVE_GETPROTOBYNUMBER
6405 struct protoent
* proto
;
6406 EnterCriticalSection( &csWSgetXXXbyYYY
);
6407 if( (proto
= getprotobynumber(number
)) != NULL
)
6409 retval
= WS_dup_pe(proto
);
6412 MESSAGE("protocol number %d not found; You might want to add "
6413 "this to /etc/protocols\n", number
);
6414 SetLastError(WSANO_DATA
);
6416 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6418 TRACE("%i ret %p\n", number
, retval
);
6423 /***********************************************************************
6424 * getservbyname (WS2_32.55)
6426 struct WS_servent
* WINAPI
WS_getservbyname(const char *name
, const char *proto
)
6428 struct WS_servent
* retval
= NULL
;
6429 struct servent
* serv
;
6431 char *proto_str
= NULL
;
6433 if (!(name_str
= strdup_lower(name
))) return NULL
;
6435 if (proto
&& *proto
)
6437 if (!(proto_str
= strdup_lower(proto
)))
6439 HeapFree( GetProcessHeap(), 0, name_str
);
6444 EnterCriticalSection( &csWSgetXXXbyYYY
);
6445 serv
= getservbyname(name_str
, proto_str
);
6448 retval
= WS_dup_se(serv
);
6450 else SetLastError(WSANO_DATA
);
6451 LeaveCriticalSection( &csWSgetXXXbyYYY
);
6452 HeapFree( GetProcessHeap(), 0, proto_str
);
6453 HeapFree( GetProcessHeap(), 0, name_str
);
6454 TRACE( "%s, %s ret %p\n", debugstr_a(name
), debugstr_a(proto
), retval
);
6458 /***********************************************************************
6459 * freeaddrinfo (WS2_32.@)
6461 void WINAPI
WS_freeaddrinfo(struct WS_addrinfo
*res
)
6464 struct WS_addrinfo
*next
;
6466 HeapFree(GetProcessHeap(),0,res
->ai_canonname
);
6467 HeapFree(GetProcessHeap(),0,res
->ai_addr
);
6468 next
= res
->ai_next
;
6469 HeapFree(GetProcessHeap(),0,res
);
6474 /* helper functions for getaddrinfo()/getnameinfo() */
6475 static int convert_aiflag_w2u(int winflags
) {
6479 for (i
=0;i
<sizeof(ws_aiflag_map
)/sizeof(ws_aiflag_map
[0]);i
++)
6480 if (ws_aiflag_map
[i
][0] & winflags
) {
6481 unixflags
|= ws_aiflag_map
[i
][1];
6482 winflags
&= ~ws_aiflag_map
[i
][0];
6485 FIXME("Unhandled windows AI_xxx flags 0x%x\n", winflags
);
6489 static int convert_niflag_w2u(int winflags
) {
6493 for (i
=0;i
<sizeof(ws_niflag_map
)/sizeof(ws_niflag_map
[0]);i
++)
6494 if (ws_niflag_map
[i
][0] & winflags
) {
6495 unixflags
|= ws_niflag_map
[i
][1];
6496 winflags
&= ~ws_niflag_map
[i
][0];
6499 FIXME("Unhandled windows NI_xxx flags 0x%x\n", winflags
);
6503 static int convert_aiflag_u2w(int unixflags
) {
6507 for (i
=0;i
<sizeof(ws_aiflag_map
)/sizeof(ws_aiflag_map
[0]);i
++)
6508 if (ws_aiflag_map
[i
][1] & unixflags
) {
6509 winflags
|= ws_aiflag_map
[i
][0];
6510 unixflags
&= ~ws_aiflag_map
[i
][1];
6513 WARN("Unhandled UNIX AI_xxx flags 0x%x\n", unixflags
);
6517 static int convert_eai_u2w(int unixret
) {
6520 if (!unixret
) return 0;
6522 for (i
=0;ws_eai_map
[i
][0];i
++)
6523 if (ws_eai_map
[i
][1] == unixret
)
6524 return ws_eai_map
[i
][0];
6526 if (unixret
== EAI_SYSTEM
)
6527 /* There are broken versions of glibc which return EAI_SYSTEM
6528 * and set errno to 0 instead of returning EAI_NONAME.
6530 return errno
? sock_get_error( errno
) : WS_EAI_NONAME
;
6532 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret
);
6536 static char *get_hostname(void)
6541 GetComputerNameExA( ComputerNamePhysicalDnsHostname
, NULL
, &size
);
6542 if (GetLastError() != ERROR_MORE_DATA
) return NULL
;
6543 if (!(ret
= HeapAlloc( GetProcessHeap(), 0, size
))) return NULL
;
6544 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname
, ret
, &size
))
6546 HeapFree( GetProcessHeap(), 0, ret
);
6552 /***********************************************************************
6553 * getaddrinfo (WS2_32.@)
6555 int WINAPI
WS_getaddrinfo(LPCSTR nodename
, LPCSTR servname
, const struct WS_addrinfo
*hints
, struct WS_addrinfo
**res
)
6557 #ifdef HAVE_GETADDRINFO
6558 struct addrinfo
*unixaires
= NULL
;
6560 struct addrinfo unixhints
, *punixhints
= NULL
;
6561 char *hostname
, *nodeV6
= NULL
;
6565 if (!nodename
&& !servname
)
6567 SetLastError(WSAHOST_NOT_FOUND
);
6568 return WSAHOST_NOT_FOUND
;
6571 hostname
= get_hostname();
6572 if (!hostname
) return WSA_NOT_ENOUGH_MEMORY
;
6576 else if (!nodename
[0])
6582 /* Check for [ipv6] or [ipv6]:portnumber, which are supported by Windows */
6583 if (!hints
|| hints
->ai_family
== WS_AF_UNSPEC
|| hints
->ai_family
== WS_AF_INET6
)
6585 char *close_bracket
;
6587 if (node
[0] == '[' && (close_bracket
= strchr(node
+ 1, ']')))
6589 nodeV6
= HeapAlloc(GetProcessHeap(), 0, close_bracket
- node
);
6592 HeapFree(GetProcessHeap(), 0, hostname
);
6593 return WSA_NOT_ENOUGH_MEMORY
;
6595 lstrcpynA(nodeV6
, node
+ 1, close_bracket
- node
);
6601 /* servname tweak required by OSX and BSD kernels */
6602 if (servname
&& !servname
[0]) servname
= "0";
6605 punixhints
= &unixhints
;
6607 memset(&unixhints
, 0, sizeof(unixhints
));
6608 punixhints
->ai_flags
= convert_aiflag_w2u(hints
->ai_flags
);
6610 /* zero is a wildcard, no need to convert */
6611 if (hints
->ai_family
)
6612 punixhints
->ai_family
= convert_af_w2u(hints
->ai_family
);
6613 if (hints
->ai_socktype
)
6614 punixhints
->ai_socktype
= convert_socktype_w2u(hints
->ai_socktype
);
6615 if (hints
->ai_protocol
)
6616 punixhints
->ai_protocol
= max(convert_proto_w2u(hints
->ai_protocol
), 0);
6618 if (punixhints
->ai_socktype
< 0)
6620 SetLastError(WSAESOCKTNOSUPPORT
);
6621 HeapFree(GetProcessHeap(), 0, hostname
);
6622 HeapFree(GetProcessHeap(), 0, nodeV6
);
6623 return SOCKET_ERROR
;
6626 /* windows allows invalid combinations of socket type and protocol, unix does not.
6627 * fix the parameters here to make getaddrinfo call always work */
6628 if (punixhints
->ai_protocol
== IPPROTO_TCP
&&
6629 punixhints
->ai_socktype
!= SOCK_STREAM
&& punixhints
->ai_socktype
!= SOCK_SEQPACKET
)
6630 punixhints
->ai_socktype
= 0;
6632 else if (punixhints
->ai_protocol
== IPPROTO_UDP
&& punixhints
->ai_socktype
!= SOCK_DGRAM
)
6633 punixhints
->ai_socktype
= 0;
6635 else if (IS_IPX_PROTO(punixhints
->ai_protocol
) && punixhints
->ai_socktype
!= SOCK_DGRAM
)
6636 punixhints
->ai_socktype
= 0;
6638 else if (punixhints
->ai_protocol
== IPPROTO_IPV6
)
6639 punixhints
->ai_protocol
= 0;
6642 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
6643 result
= getaddrinfo(node
, servname
, punixhints
, &unixaires
);
6645 if (result
&& (!hints
|| !(hints
->ai_flags
& WS_AI_NUMERICHOST
)) && !strcmp(hostname
, node
))
6647 /* If it didn't work it means the host name IP is not in /etc/hosts, try again
6648 * by sending a NULL host and avoid sending a NULL servname too because that
6650 ERR_(winediag
)("Failed to resolve your host name IP\n");
6651 result
= getaddrinfo(NULL
, servname
? servname
: "0", punixhints
, &unixaires
);
6653 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename
), debugstr_a(servname
), hints
, res
, result
);
6654 HeapFree(GetProcessHeap(), 0, hostname
);
6655 HeapFree(GetProcessHeap(), 0, nodeV6
);
6658 struct addrinfo
*xuai
= unixaires
;
6659 struct WS_addrinfo
**xai
= res
;
6663 struct WS_addrinfo
*ai
= HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY
, sizeof(struct WS_addrinfo
));
6669 *xai
= ai
;xai
= &ai
->ai_next
;
6670 ai
->ai_flags
= convert_aiflag_u2w(xuai
->ai_flags
);
6671 ai
->ai_family
= convert_af_u2w(xuai
->ai_family
);
6672 /* copy whatever was sent in the hints */
6674 ai
->ai_socktype
= hints
->ai_socktype
;
6675 ai
->ai_protocol
= hints
->ai_protocol
;
6677 ai
->ai_socktype
= convert_socktype_u2w(xuai
->ai_socktype
);
6678 ai
->ai_protocol
= convert_proto_u2w(xuai
->ai_protocol
);
6680 if (xuai
->ai_canonname
) {
6681 TRACE("canon name - %s\n",debugstr_a(xuai
->ai_canonname
));
6682 ai
->ai_canonname
= HeapAlloc(GetProcessHeap(),0,strlen(xuai
->ai_canonname
)+1);
6683 if (!ai
->ai_canonname
)
6685 strcpy(ai
->ai_canonname
,xuai
->ai_canonname
);
6687 len
= xuai
->ai_addrlen
;
6688 ai
->ai_addr
= HeapAlloc(GetProcessHeap(),0,len
);
6691 ai
->ai_addrlen
= len
;
6693 int winlen
= ai
->ai_addrlen
;
6695 if (!ws_sockaddr_u2ws(xuai
->ai_addr
, ai
->ai_addr
, &winlen
)) {
6696 ai
->ai_addrlen
= winlen
;
6700 ai
->ai_addr
= HeapReAlloc(GetProcessHeap(),0,ai
->ai_addr
,len
);
6703 ai
->ai_addrlen
= len
;
6705 xuai
= xuai
->ai_next
;
6707 freeaddrinfo(unixaires
);
6709 if (TRACE_ON(winsock
))
6711 struct WS_addrinfo
*ai
= *res
;
6714 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
6715 ai
, ai
->ai_flags
, ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
, ai
->ai_addrlen
,
6716 ai
->ai_canonname
, debugstr_sockaddr(ai
->ai_addr
));
6721 result
= convert_eai_u2w(result
);
6723 SetLastError(result
);
6727 if (*res
) WS_freeaddrinfo(*res
);
6728 if (unixaires
) freeaddrinfo(unixaires
);
6729 return WSA_NOT_ENOUGH_MEMORY
;
6731 FIXME("getaddrinfo() failed, not found during buildtime.\n");
6736 static struct WS_addrinfoW
*addrinfo_AtoW(const struct WS_addrinfo
*ai
)
6738 struct WS_addrinfoW
*ret
;
6740 if (!(ret
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW
)))) return NULL
;
6741 ret
->ai_flags
= ai
->ai_flags
;
6742 ret
->ai_family
= ai
->ai_family
;
6743 ret
->ai_socktype
= ai
->ai_socktype
;
6744 ret
->ai_protocol
= ai
->ai_protocol
;
6745 ret
->ai_addrlen
= ai
->ai_addrlen
;
6746 ret
->ai_canonname
= NULL
;
6747 ret
->ai_addr
= NULL
;
6748 ret
->ai_next
= NULL
;
6749 if (ai
->ai_canonname
)
6751 int len
= MultiByteToWideChar(CP_ACP
, 0, ai
->ai_canonname
, -1, NULL
, 0);
6752 if (!(ret
->ai_canonname
= HeapAlloc(GetProcessHeap(), 0, len
*sizeof(WCHAR
))))
6754 HeapFree(GetProcessHeap(), 0, ret
);
6757 MultiByteToWideChar(CP_ACP
, 0, ai
->ai_canonname
, -1, ret
->ai_canonname
, len
);
6761 if (!(ret
->ai_addr
= HeapAlloc(GetProcessHeap(), 0, ai
->ai_addrlen
)))
6763 HeapFree(GetProcessHeap(), 0, ret
->ai_canonname
);
6764 HeapFree(GetProcessHeap(), 0, ret
);
6767 memcpy(ret
->ai_addr
, ai
->ai_addr
, ai
->ai_addrlen
);
6772 static struct WS_addrinfoW
*addrinfo_list_AtoW(const struct WS_addrinfo
*info
)
6774 struct WS_addrinfoW
*ret
, *infoW
;
6776 if (!(ret
= infoW
= addrinfo_AtoW(info
))) return NULL
;
6777 while (info
->ai_next
)
6779 if (!(infoW
->ai_next
= addrinfo_AtoW(info
->ai_next
)))
6784 infoW
= infoW
->ai_next
;
6785 info
= info
->ai_next
;
6790 static struct WS_addrinfo
*addrinfo_WtoA(const struct WS_addrinfoW
*ai
)
6792 struct WS_addrinfo
*ret
;
6794 if (!(ret
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo
)))) return NULL
;
6795 ret
->ai_flags
= ai
->ai_flags
;
6796 ret
->ai_family
= ai
->ai_family
;
6797 ret
->ai_socktype
= ai
->ai_socktype
;
6798 ret
->ai_protocol
= ai
->ai_protocol
;
6799 ret
->ai_addrlen
= ai
->ai_addrlen
;
6800 ret
->ai_canonname
= NULL
;
6801 ret
->ai_addr
= NULL
;
6802 ret
->ai_next
= NULL
;
6803 if (ai
->ai_canonname
)
6805 int len
= WideCharToMultiByte(CP_ACP
, 0, ai
->ai_canonname
, -1, NULL
, 0, NULL
, NULL
);
6806 if (!(ret
->ai_canonname
= HeapAlloc(GetProcessHeap(), 0, len
)))
6808 HeapFree(GetProcessHeap(), 0, ret
);
6811 WideCharToMultiByte(CP_ACP
, 0, ai
->ai_canonname
, -1, ret
->ai_canonname
, len
, NULL
, NULL
);
6815 if (!(ret
->ai_addr
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr
))))
6817 HeapFree(GetProcessHeap(), 0, ret
->ai_canonname
);
6818 HeapFree(GetProcessHeap(), 0, ret
);
6821 memcpy(ret
->ai_addr
, ai
->ai_addr
, sizeof(struct WS_sockaddr
));
6826 /***********************************************************************
6827 * GetAddrInfoExW (WS2_32.@)
6829 int WINAPI
GetAddrInfoExW(const WCHAR
*name
, const WCHAR
*servname
, DWORD
namespace, GUID
*namespace_id
,
6830 const ADDRINFOEXW
*hints
, ADDRINFOEXW
**result
, struct timeval
*timeout
, OVERLAPPED
*overlapped
,
6831 LPLOOKUPSERVICE_COMPLETION_ROUTINE completion_routine
, HANDLE
*handle
)
6833 FIXME("(%s %s %x %s %p %p %p %p %p %p)\n", debugstr_w(name
), debugstr_w(servname
), namespace,
6834 debugstr_guid(namespace_id
), hints
, result
, timeout
, overlapped
, completion_routine
, handle
);
6835 return WSAHOST_NOT_FOUND
;
6838 /***********************************************************************
6839 * GetAddrInfoExCancel (WS2_32.@)
6841 int WINAPI
GetAddrInfoExCancel(HANDLE
*handle
)
6843 FIXME("(%p)\n", handle
);
6844 return WSA_INVALID_HANDLE
;
6847 /***********************************************************************
6848 * GetAddrInfoW (WS2_32.@)
6850 int WINAPI
GetAddrInfoW(LPCWSTR nodename
, LPCWSTR servname
, const ADDRINFOW
*hints
, PADDRINFOW
*res
)
6852 int ret
= EAI_MEMORY
, len
, i
;
6853 char *nodenameA
= NULL
, *servnameA
= NULL
;
6854 struct WS_addrinfo
*resA
, *hintsA
= NULL
;
6855 WCHAR
*local_nodenameW
= (WCHAR
*)nodename
;
6857 TRACE("nodename %s, servname %s, hints %p, result %p\n",
6858 debugstr_w(nodename
), debugstr_w(servname
), hints
, res
);
6863 /* Is this an IDN? Most likely if any char is above the Ascii table, this
6864 * is the simplest validation possible, further validation will be done by
6865 * the native getaddrinfo() */
6866 for (i
= 0; nodename
[i
]; i
++)
6868 if (nodename
[i
] > 'z')
6873 if (hints
&& (hints
->ai_flags
& WS_AI_DISABLE_IDN_ENCODING
))
6875 /* Name requires conversion but it was disabled */
6876 ret
= WSAHOST_NOT_FOUND
;
6877 WSASetLastError(ret
);
6881 len
= IdnToAscii(0, nodename
, -1, NULL
, 0);
6884 ERR("Failed to convert %s to punycode\n", debugstr_w(nodename
));
6888 if (!(local_nodenameW
= HeapAlloc(GetProcessHeap(), 0, len
* sizeof(WCHAR
)))) goto end
;
6889 IdnToAscii(0, nodename
, -1, local_nodenameW
, len
);
6892 if (local_nodenameW
)
6894 len
= WideCharToMultiByte(CP_ACP
, 0, local_nodenameW
, -1, NULL
, 0, NULL
, NULL
);
6895 if (!(nodenameA
= HeapAlloc(GetProcessHeap(), 0, len
))) goto end
;
6896 WideCharToMultiByte(CP_ACP
, 0, local_nodenameW
, -1, nodenameA
, len
, NULL
, NULL
);
6900 len
= WideCharToMultiByte(CP_ACP
, 0, servname
, -1, NULL
, 0, NULL
, NULL
);
6901 if (!(servnameA
= HeapAlloc(GetProcessHeap(), 0, len
))) goto end
;
6902 WideCharToMultiByte(CP_ACP
, 0, servname
, -1, servnameA
, len
, NULL
, NULL
);
6905 if (hints
) hintsA
= addrinfo_WtoA(hints
);
6906 ret
= WS_getaddrinfo(nodenameA
, servnameA
, hintsA
, &resA
);
6907 WS_freeaddrinfo(hintsA
);
6911 *res
= addrinfo_list_AtoW(resA
);
6912 WS_freeaddrinfo(resA
);
6916 if (local_nodenameW
!= nodename
)
6917 HeapFree(GetProcessHeap(), 0, local_nodenameW
);
6918 HeapFree(GetProcessHeap(), 0, nodenameA
);
6919 HeapFree(GetProcessHeap(), 0, servnameA
);
6923 /***********************************************************************
6924 * FreeAddrInfoW (WS2_32.@)
6926 void WINAPI
FreeAddrInfoW(PADDRINFOW ai
)
6931 HeapFree(GetProcessHeap(), 0, ai
->ai_canonname
);
6932 HeapFree(GetProcessHeap(), 0, ai
->ai_addr
);
6934 HeapFree(GetProcessHeap(), 0, ai
);
6939 /***********************************************************************
6940 * FreeAddrInfoExW (WS2_32.@)
6942 void WINAPI
FreeAddrInfoExW(ADDRINFOEXW
*ai
)
6947 int WINAPI
WS_getnameinfo(const SOCKADDR
*sa
, WS_socklen_t salen
, PCHAR host
,
6948 DWORD hostlen
, PCHAR serv
, DWORD servlen
, INT flags
)
6950 #ifdef HAVE_GETNAMEINFO
6952 union generic_unix_sockaddr sa_u
;
6955 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa
), salen
, host
, hostlen
,
6956 serv
, servlen
, flags
);
6958 size
= ws_sockaddr_ws2u(sa
, salen
, &sa_u
);
6961 SetLastError(WSAEFAULT
);
6962 return WSA_NOT_ENOUGH_MEMORY
;
6964 ret
= getnameinfo(&sa_u
.addr
, size
, host
, hostlen
, serv
, servlen
, convert_niflag_w2u(flags
));
6965 return convert_eai_u2w(ret
);
6967 FIXME("getnameinfo() failed, not found during buildtime.\n");
6972 int WINAPI
GetNameInfoW(const SOCKADDR
*sa
, WS_socklen_t salen
, PWCHAR host
,
6973 DWORD hostlen
, PWCHAR serv
, DWORD servlen
, INT flags
)
6976 char *hostA
= NULL
, *servA
= NULL
;
6978 if (host
&& (!(hostA
= HeapAlloc(GetProcessHeap(), 0, hostlen
)))) return EAI_MEMORY
;
6979 if (serv
&& (!(servA
= HeapAlloc(GetProcessHeap(), 0, servlen
))))
6981 HeapFree(GetProcessHeap(), 0, hostA
);
6985 ret
= WS_getnameinfo(sa
, salen
, hostA
, hostlen
, servA
, servlen
, flags
);
6988 if (host
) MultiByteToWideChar(CP_ACP
, 0, hostA
, -1, host
, hostlen
);
6989 if (serv
) MultiByteToWideChar(CP_ACP
, 0, servA
, -1, serv
, servlen
);
6992 HeapFree(GetProcessHeap(), 0, hostA
);
6993 HeapFree(GetProcessHeap(), 0, servA
);
6997 /***********************************************************************
6998 * getservbyport (WS2_32.56)
7000 struct WS_servent
* WINAPI
WS_getservbyport(int port
, const char *proto
)
7002 struct WS_servent
* retval
= NULL
;
7003 #ifdef HAVE_GETSERVBYPORT
7004 struct servent
* serv
;
7005 char *proto_str
= NULL
;
7007 if (proto
&& *proto
)
7009 if (!(proto_str
= strdup_lower(proto
))) return NULL
;
7011 EnterCriticalSection( &csWSgetXXXbyYYY
);
7012 if( (serv
= getservbyport(port
, proto_str
)) != NULL
) {
7013 retval
= WS_dup_se(serv
);
7015 else SetLastError(WSANO_DATA
);
7016 LeaveCriticalSection( &csWSgetXXXbyYYY
);
7017 HeapFree( GetProcessHeap(), 0, proto_str
);
7019 TRACE("%d (i.e. port %d), %s ret %p\n", port
, (int)ntohl(port
), debugstr_a(proto
), retval
);
7024 /***********************************************************************
7025 * gethostname (WS2_32.57)
7027 int WINAPI
WS_gethostname(char *name
, int namelen
)
7032 TRACE("name %p, len %d\n", name
, namelen
);
7036 SetLastError(WSAEFAULT
);
7037 return SOCKET_ERROR
;
7040 if (gethostname(buf
, sizeof(buf
)) != 0)
7042 SetLastError(wsaErrno());
7043 return SOCKET_ERROR
;
7046 TRACE("<- '%s'\n", buf
);
7049 WARN("Windows supports NetBIOS name length up to 15 bytes!\n");
7052 SetLastError(WSAEFAULT
);
7053 WARN("<- not enough space for hostname, required %d, got %d!\n", len
+ 1, namelen
);
7054 return SOCKET_ERROR
;
7061 /* ------------------------------------- Windows sockets extensions -- *
7063 * ------------------------------------------------------------------- */
7065 /***********************************************************************
7066 * WSAEnumNetworkEvents (WS2_32.36)
7068 int WINAPI
WSAEnumNetworkEvents(SOCKET s
, WSAEVENT hEvent
, LPWSANETWORKEVENTS lpEvent
)
7072 int errors
[FD_MAX_EVENTS
];
7074 TRACE("%04lx, hEvent %p, lpEvent %p\n", s
, hEvent
, lpEvent
);
7076 SERVER_START_REQ( get_socket_event
)
7078 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
7079 req
->service
= TRUE
;
7080 req
->c_event
= wine_server_obj_handle( hEvent
);
7081 wine_server_set_reply( req
, errors
, sizeof(errors
) );
7082 if (!(ret
= wine_server_call(req
))) lpEvent
->lNetworkEvents
= reply
->pmask
& reply
->mask
;
7087 for (i
= 0; i
< FD_MAX_EVENTS
; i
++)
7088 lpEvent
->iErrorCode
[i
] = NtStatusToWSAError(errors
[i
]);
7091 SetLastError(WSAEINVAL
);
7092 return SOCKET_ERROR
;
7095 /***********************************************************************
7096 * WSAEventSelect (WS2_32.39)
7098 int WINAPI
WSAEventSelect(SOCKET s
, WSAEVENT hEvent
, LONG lEvent
)
7102 TRACE("%04lx, hEvent %p, event %08x\n", s
, hEvent
, lEvent
);
7104 SERVER_START_REQ( set_socket_event
)
7106 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
7108 req
->event
= wine_server_obj_handle( hEvent
);
7111 ret
= wine_server_call( req
);
7115 SetLastError(WSAEINVAL
);
7116 return SOCKET_ERROR
;
7119 /**********************************************************************
7120 * WSAGetOverlappedResult (WS2_32.40)
7122 BOOL WINAPI
WSAGetOverlappedResult( SOCKET s
, LPWSAOVERLAPPED lpOverlapped
,
7123 LPDWORD lpcbTransfer
, BOOL fWait
,
7128 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
7129 s
, lpOverlapped
, lpcbTransfer
, fWait
, lpdwFlags
);
7131 if ( lpOverlapped
== NULL
)
7133 ERR( "Invalid pointer\n" );
7134 SetLastError(WSA_INVALID_PARAMETER
);
7138 status
= lpOverlapped
->Internal
;
7139 if (status
== STATUS_PENDING
)
7143 SetLastError( WSA_IO_INCOMPLETE
);
7147 if (WaitForSingleObject( lpOverlapped
->hEvent
? lpOverlapped
->hEvent
: SOCKET2HANDLE(s
),
7148 INFINITE
) == WAIT_FAILED
)
7150 status
= lpOverlapped
->Internal
;
7154 *lpcbTransfer
= lpOverlapped
->InternalHigh
;
7157 *lpdwFlags
= lpOverlapped
->u
.s
.Offset
;
7159 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
7164 /***********************************************************************
7165 * WSAAsyncSelect (WS2_32.101)
7167 INT WINAPI
WSAAsyncSelect(SOCKET s
, HWND hWnd
, UINT uMsg
, LONG lEvent
)
7171 TRACE("%04lx, hWnd %p, uMsg %08x, event %08x\n", s
, hWnd
, uMsg
, lEvent
);
7173 SERVER_START_REQ( set_socket_event
)
7175 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
7178 req
->window
= wine_server_user_handle( hWnd
);
7180 ret
= wine_server_call( req
);
7184 SetLastError(WSAEINVAL
);
7185 return SOCKET_ERROR
;
7188 /***********************************************************************
7189 * WSACreateEvent (WS2_32.31)
7192 WSAEVENT WINAPI
WSACreateEvent(void)
7194 /* Create a manual-reset event, with initial state: unsignaled */
7197 return CreateEventW(NULL
, TRUE
, FALSE
, NULL
);
7200 /***********************************************************************
7201 * WSACloseEvent (WS2_32.29)
7204 BOOL WINAPI
WSACloseEvent(WSAEVENT event
)
7206 TRACE ("event=%p\n", event
);
7208 return CloseHandle(event
);
7211 /***********************************************************************
7212 * WSASocketA (WS2_32.78)
7215 SOCKET WINAPI
WSASocketA(int af
, int type
, int protocol
,
7216 LPWSAPROTOCOL_INFOA lpProtocolInfo
,
7217 GROUP g
, DWORD dwFlags
)
7220 WSAPROTOCOL_INFOW info
;
7222 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
7223 af
, type
, protocol
, lpProtocolInfo
, g
, dwFlags
);
7225 if (!lpProtocolInfo
) return WSASocketW(af
, type
, protocol
, NULL
, g
, dwFlags
);
7227 memcpy(&info
, lpProtocolInfo
, FIELD_OFFSET(WSAPROTOCOL_INFOW
, szProtocol
));
7228 len
= MultiByteToWideChar(CP_ACP
, 0, lpProtocolInfo
->szProtocol
, -1,
7229 info
.szProtocol
, WSAPROTOCOL_LEN
+ 1);
7233 SetLastError(WSAEINVAL
);
7234 return SOCKET_ERROR
;
7237 return WSASocketW(af
, type
, protocol
, &info
, g
, dwFlags
);
7240 /***********************************************************************
7241 * WSASocketW (WS2_32.79)
7244 SOCKET WINAPI
WSASocketW(int af
, int type
, int protocol
,
7245 LPWSAPROTOCOL_INFOW lpProtocolInfo
,
7246 GROUP g
, DWORD dwFlags
)
7250 int unixaf
, unixtype
, ipxptype
= -1;
7253 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
7254 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
7257 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
7258 af
, type
, protocol
, lpProtocolInfo
, g
, dwFlags
);
7262 err
= WSANOTINITIALISED
;
7266 /* hack for WSADuplicateSocket */
7267 if (lpProtocolInfo
&& lpProtocolInfo
->dwServiceFlags4
== 0xff00ff00) {
7268 ret
= lpProtocolInfo
->dwServiceFlags3
;
7269 TRACE("\tgot duplicate %04lx\n", ret
);
7275 if (af
== FROM_PROTOCOL_INFO
|| !af
)
7276 af
= lpProtocolInfo
->iAddressFamily
;
7277 if (type
== FROM_PROTOCOL_INFO
|| !type
)
7278 type
= lpProtocolInfo
->iSocketType
;
7279 if (protocol
== FROM_PROTOCOL_INFO
|| !protocol
)
7280 protocol
= lpProtocolInfo
->iProtocol
;
7283 if (!type
&& (af
|| protocol
))
7285 int autoproto
= protocol
;
7286 WSAPROTOCOL_INFOW infow
;
7288 /* default to the first valid protocol */
7290 autoproto
= valid_protocols
[0];
7291 else if(IS_IPX_PROTO(autoproto
))
7292 autoproto
= WS_NSPROTO_IPX
;
7294 if (WS_EnterSingleProtocolW(autoproto
, &infow
))
7296 type
= infow
.iSocketType
;
7298 /* after win2003 it's no longer possible to pass AF_UNSPEC
7299 using the protocol info struct */
7300 if (!lpProtocolInfo
&& af
== WS_AF_UNSPEC
)
7301 af
= infow
.iAddressFamily
;
7306 Windows has an extension to the IPX protocol that allows one to create sockets
7307 and set the IPX packet type at the same time, to do that a caller will use
7308 a protocol like NSPROTO_IPX + <PACKET TYPE>
7310 if (IS_IPX_PROTO(protocol
))
7311 ipxptype
= protocol
- WS_NSPROTO_IPX
;
7313 /* convert the socket family, type and protocol */
7314 unixaf
= convert_af_w2u(af
);
7315 unixtype
= convert_socktype_w2u(type
);
7316 protocol
= convert_proto_w2u(protocol
);
7317 if (unixaf
== AF_UNSPEC
) unixaf
= -1;
7319 /* filter invalid parameters */
7322 /* the type could not be converted */
7323 if (type
&& unixtype
< 0)
7325 err
= WSAESOCKTNOSUPPORT
;
7329 err
= WSAEPROTONOSUPPORT
;
7334 /* both family and protocol can't be invalid */
7341 /* family could not be converted and neither socket type */
7342 if (unixtype
< 0 && af
>= 0)
7345 err
= WSAESOCKTNOSUPPORT
;
7349 err
= WSAEAFNOSUPPORT
;
7353 SERVER_START_REQ( create_socket
)
7355 req
->family
= unixaf
;
7356 req
->type
= unixtype
;
7357 req
->protocol
= protocol
;
7358 req
->access
= GENERIC_READ
|GENERIC_WRITE
|SYNCHRONIZE
;
7359 req
->attributes
= (dwFlags
& WSA_FLAG_NO_HANDLE_INHERIT
) ? 0 : OBJ_INHERIT
;
7360 req
->flags
= dwFlags
& ~WSA_FLAG_NO_HANDLE_INHERIT
;
7361 set_error( wine_server_call( req
) );
7362 ret
= HANDLE2SOCKET( wine_server_ptr_handle( reply
->handle
));
7367 TRACE("\tcreated %04lx\n", ret
);
7369 set_ipx_packettype(ret
, ipxptype
);
7371 /* ensure IP_DONTFRAGMENT is disabled, in Linux the global default can be enabled */
7372 if (unixaf
== AF_INET
|| unixaf
== AF_INET6
)
7373 set_dont_fragment(ret
, unixaf
== AF_INET6
? IPPROTO_IPV6
: IPPROTO_IP
, FALSE
);
7376 if (unixaf
== AF_INET6
)
7378 int fd
= get_sock_fd(ret
, 0, NULL
);
7381 /* IPV6_V6ONLY is set by default on Windows */
7383 if (setsockopt(fd
, IPPROTO_IPV6
, IPV6_V6ONLY
, &enable
, sizeof(enable
)))
7384 WARN("\tsetting IPV6_V6ONLY failed - errno = %i\n", errno
);
7385 release_sock_fd(ret
, fd
);
7392 err
= GetLastError();
7393 if (err
== WSAEACCES
) /* raw socket denied */
7395 if (type
== SOCK_RAW
)
7396 ERR_(winediag
)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
7398 ERR_(winediag
)("Failed to create socket, this requires special permissions.\n");
7402 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
7403 if (err
== WSAEINVAL
)
7404 err
= WSAESOCKTNOSUPPORT
;
7405 else if (err
== WSAEOPNOTSUPP
)
7406 err
= WSAEPROTONOSUPPORT
;
7410 WARN("\t\tfailed, error %d!\n", err
);
7412 return INVALID_SOCKET
;
7415 /***********************************************************************
7416 * WSAJoinLeaf (WS2_32.58)
7419 SOCKET WINAPI
WSAJoinLeaf(
7421 const struct WS_sockaddr
*addr
,
7423 LPWSABUF lpCallerData
,
7424 LPWSABUF lpCalleeData
,
7430 return INVALID_SOCKET
;
7433 /***********************************************************************
7434 * __WSAFDIsSet (WS2_32.151)
7436 int WINAPI
__WSAFDIsSet(SOCKET s
, WS_fd_set
*set
)
7438 int i
= set
->fd_count
, ret
= 0;
7441 if (set
->fd_array
[i
] == s
)
7447 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s
, set
, set
->fd_count
, ret
);
7451 /***********************************************************************
7452 * WSAIsBlocking (WS2_32.114)
7454 BOOL WINAPI
WSAIsBlocking(void)
7456 /* By default WinSock should set all its sockets to non-blocking mode
7457 * and poll in PeekMessage loop when processing "blocking" ones. This
7458 * function is supposed to tell if the program is in this loop. Our
7459 * blocking calls are truly blocking so we always return FALSE.
7461 * Note: It is allowed to call this function without prior WSAStartup().
7468 /***********************************************************************
7469 * WSACancelBlockingCall (WS2_32.113)
7471 INT WINAPI
WSACancelBlockingCall(void)
7477 static INT WINAPI
WSA_DefaultBlockingHook( FARPROC x
)
7479 FIXME("How was this called?\n");
7484 /***********************************************************************
7485 * WSASetBlockingHook (WS2_32.109)
7487 FARPROC WINAPI
WSASetBlockingHook(FARPROC lpBlockFunc
)
7489 FARPROC prev
= blocking_hook
;
7490 blocking_hook
= lpBlockFunc
;
7491 TRACE("hook %p\n", lpBlockFunc
);
7496 /***********************************************************************
7497 * WSAUnhookBlockingHook (WS2_32.110)
7499 INT WINAPI
WSAUnhookBlockingHook(void)
7501 blocking_hook
= (FARPROC
)WSA_DefaultBlockingHook
;
7506 /* ----------------------------------- end of API stuff */
7508 /* ----------------------------------- helper functions -
7510 * TODO: Merge WS_dup_..() stuff into one function that
7511 * would operate with a generic structure containing internal
7512 * pointers (via a template of some kind).
7515 static int list_size(char** l
, int item_size
)
7520 j
+= (item_size
) ? item_size
: strlen(l
[i
]) + 1;
7521 j
+= (i
+ 1) * sizeof(char*); }
7525 static int list_dup(char** l_src
, char** l_to
, int item_size
)
7530 for (i
= 0; l_src
[i
]; i
++) ;
7531 p
= (char *)(l_to
+ i
+ 1);
7532 for (i
= 0; l_src
[i
]; i
++)
7534 int count
= ( item_size
) ? item_size
: strlen(l_src
[i
]) + 1;
7535 memcpy(p
, l_src
[i
], count
);
7540 return p
- (char *)l_to
;
7545 /* create a hostent entry
7547 * Creates the entry with enough memory for the name, aliases
7548 * addresses, and the address pointers. Also copies the name
7549 * and sets up all the pointers.
7551 * NOTE: The alias and address lists must be allocated with room
7552 * for the NULL item terminating the list. This is true even if
7553 * the list has no items ("aliases" and "addresses" must be
7554 * at least "1", a truly empty list is invalid).
7556 static struct WS_hostent
*WS_create_he(char *name
, int aliases
, int aliases_size
, int addresses
, int address_length
)
7558 struct WS_hostent
*p_to
;
7560 int size
= (sizeof(struct WS_hostent
) +
7562 sizeof(char *) * aliases
+
7564 sizeof(char *) * addresses
+
7565 address_length
* (addresses
- 1)), i
;
7567 if (!(p_to
= check_buffer_he(size
))) return NULL
;
7568 memset(p_to
, 0, size
);
7570 /* Use the memory in the same way winsock does.
7571 * First set the pointer for aliases, second set the pointers for addresses.
7572 * Third fill the addresses indexes, fourth jump aliases names size.
7573 * Fifth fill the hostname.
7574 * NOTE: This method is valid for OS version's >= XP.
7576 p
= (char *)(p_to
+ 1);
7577 p_to
->h_aliases
= (char **)p
;
7578 p
+= sizeof(char *)*aliases
;
7580 p_to
->h_addr_list
= (char **)p
;
7581 p
+= sizeof(char *)*addresses
;
7583 for (i
= 0, addresses
--; i
< addresses
; i
++, p
+= address_length
)
7584 p_to
->h_addr_list
[i
] = p
;
7586 /* NOTE: h_aliases must be filled in manually because we don't know each string
7587 * size, leave these pointers NULL (already set to NULL by memset earlier).
7597 /* duplicate hostent entry
7598 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
7599 * Ditto for protoent and servent.
7601 static struct WS_hostent
*WS_dup_he(const struct hostent
* p_he
)
7603 int i
, addresses
= 0, alias_size
= 0;
7604 struct WS_hostent
*p_to
;
7607 for( i
= 0; p_he
->h_aliases
[i
]; i
++) alias_size
+= strlen(p_he
->h_aliases
[i
]) + 1;
7608 while (p_he
->h_addr_list
[addresses
]) addresses
++;
7610 p_to
= WS_create_he(p_he
->h_name
, i
+ 1, alias_size
, addresses
+ 1, p_he
->h_length
);
7612 if (!p_to
) return NULL
;
7613 p_to
->h_addrtype
= convert_af_u2w(p_he
->h_addrtype
);
7614 p_to
->h_length
= p_he
->h_length
;
7616 for(i
= 0, p
= p_to
->h_addr_list
[0]; p_he
->h_addr_list
[i
]; i
++, p
+= p_to
->h_length
)
7617 memcpy(p
, p_he
->h_addr_list
[i
], p_to
->h_length
);
7619 /* Fill the aliases after the IP data */
7620 for(i
= 0; p_he
->h_aliases
[i
]; i
++)
7622 p_to
->h_aliases
[i
] = p
;
7623 strcpy(p
, p_he
->h_aliases
[i
]);
7630 /* ----- protoent */
7632 static struct WS_protoent
*WS_dup_pe(const struct protoent
* p_pe
)
7635 struct WS_protoent
*p_to
;
7637 int size
= (sizeof(*p_pe
) +
7638 strlen(p_pe
->p_name
) + 1 +
7639 list_size(p_pe
->p_aliases
, 0));
7641 if (!(p_to
= check_buffer_pe(size
))) return NULL
;
7642 p_to
->p_proto
= p_pe
->p_proto
;
7644 p
= (char *)(p_to
+ 1);
7646 strcpy(p
, p_pe
->p_name
);
7649 p_to
->p_aliases
= (char **)p
;
7650 list_dup(p_pe
->p_aliases
, p_to
->p_aliases
, 0);
7656 static struct WS_servent
*WS_dup_se(const struct servent
* p_se
)
7659 struct WS_servent
*p_to
;
7661 int size
= (sizeof(*p_se
) +
7662 strlen(p_se
->s_proto
) + 1 +
7663 strlen(p_se
->s_name
) + 1 +
7664 list_size(p_se
->s_aliases
, 0));
7666 if (!(p_to
= check_buffer_se(size
))) return NULL
;
7667 p_to
->s_port
= p_se
->s_port
;
7669 p
= (char *)(p_to
+ 1);
7671 strcpy(p
, p_se
->s_name
);
7675 strcpy(p
, p_se
->s_proto
);
7678 p_to
->s_aliases
= (char **)p
;
7679 list_dup(p_se
->s_aliases
, p_to
->s_aliases
, 0);
7684 /***********************************************************************
7685 * WSARecv (WS2_32.67)
7687 int WINAPI
WSARecv(SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
7688 LPDWORD NumberOfBytesReceived
, LPDWORD lpFlags
,
7689 LPWSAOVERLAPPED lpOverlapped
,
7690 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
7692 return WS2_recv_base(s
, lpBuffers
, dwBufferCount
, NumberOfBytesReceived
, lpFlags
,
7693 NULL
, NULL
, lpOverlapped
, lpCompletionRoutine
, NULL
);
7696 static int WS2_recv_base( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
7697 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
,
7698 struct WS_sockaddr
*lpFrom
,
7699 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
7700 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
,
7701 LPWSABUF lpControlBuffer
)
7703 unsigned int i
, options
;
7704 int n
, fd
, err
, overlapped
, flags
;
7705 struct ws2_async
*wsa
= NULL
, localwsa
;
7707 DWORD timeout_start
= GetTickCount();
7708 ULONG_PTR cvalue
= (lpOverlapped
&& ((ULONG_PTR
)lpOverlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)lpOverlapped
: 0;
7710 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
7711 s
, lpBuffers
, dwBufferCount
, *lpFlags
, lpFrom
,
7712 (lpFromlen
? *lpFromlen
: -1),
7713 lpOverlapped
, lpCompletionRoutine
);
7715 fd
= get_sock_fd( s
, FILE_READ_DATA
, &options
);
7716 TRACE( "fd=%d, options=%x\n", fd
, options
);
7718 if (fd
== -1) return SOCKET_ERROR
;
7720 if (*lpFlags
& WS_MSG_OOB
)
7722 /* It's invalid to receive OOB data from an OOBINLINED socket
7723 * as OOB data is turned into normal data. */
7724 socklen_t len
= sizeof(n
);
7725 if (!getsockopt(fd
, SOL_SOCKET
, SO_OOBINLINE
, (char*) &n
, &len
) && n
)
7732 overlapped
= (lpOverlapped
|| lpCompletionRoutine
) &&
7733 !(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
));
7734 if (overlapped
|| dwBufferCount
> 1)
7736 if (!(wsa
= (struct ws2_async
*)alloc_async_io( offsetof(struct ws2_async
, iovec
[dwBufferCount
]),
7746 wsa
->hSocket
= SOCKET2HANDLE(s
);
7747 wsa
->flags
= *lpFlags
;
7748 wsa
->lpFlags
= lpFlags
;
7750 wsa
->addrlen
.ptr
= lpFromlen
;
7751 wsa
->control
= lpControlBuffer
;
7752 wsa
->n_iovecs
= dwBufferCount
;
7753 wsa
->first_iovec
= 0;
7754 for (i
= 0; i
< dwBufferCount
; i
++)
7756 /* check buffer first to trigger write watches */
7757 if (IsBadWritePtr( lpBuffers
[i
].buf
, lpBuffers
[i
].len
))
7762 wsa
->iovec
[i
].iov_base
= lpBuffers
[i
].buf
;
7763 wsa
->iovec
[i
].iov_len
= lpBuffers
[i
].len
;
7766 flags
= convert_flags(wsa
->flags
);
7769 n
= WS2_recv( fd
, wsa
, flags
);
7772 /* Unix-like systems return EINVAL when attempting to read OOB data from
7773 * an empty socket buffer, convert that to a Windows expected return. */
7774 if ((flags
& MSG_OOB
) && errno
== EINVAL
)
7775 errno
= EWOULDBLOCK
;
7777 if (errno
!= EAGAIN
)
7783 else if (lpNumberOfBytesRecvd
) *lpNumberOfBytesRecvd
= n
;
7787 IO_STATUS_BLOCK
*iosb
= lpOverlapped
? (IO_STATUS_BLOCK
*)lpOverlapped
: &wsa
->local_iosb
;
7789 wsa
->user_overlapped
= lpOverlapped
;
7790 wsa
->completion_func
= lpCompletionRoutine
;
7791 release_sock_fd( s
, fd
);
7795 iosb
->u
.Status
= STATUS_PENDING
;
7796 iosb
->Information
= 0;
7798 if (wsa
->completion_func
)
7799 err
= register_async( ASYNC_TYPE_READ
, wsa
->hSocket
, &wsa
->io
, NULL
,
7800 ws2_async_apc
, wsa
, iosb
);
7802 err
= register_async( ASYNC_TYPE_READ
, wsa
->hSocket
, &wsa
->io
, lpOverlapped
->hEvent
,
7803 NULL
, (void *)cvalue
, iosb
);
7805 if (err
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
7806 SetLastError(NtStatusToWSAError( err
));
7807 return SOCKET_ERROR
;
7810 iosb
->u
.Status
= STATUS_SUCCESS
;
7811 iosb
->Information
= n
;
7812 if (!wsa
->completion_func
)
7814 if (cvalue
) WS_AddCompletion( s
, cvalue
, STATUS_SUCCESS
, n
);
7815 if (lpOverlapped
->hEvent
) SetEvent( lpOverlapped
->hEvent
);
7816 HeapFree( GetProcessHeap(), 0, wsa
);
7818 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC
)ws2_async_apc
,
7819 (ULONG_PTR
)wsa
, (ULONG_PTR
)iosb
, 0 );
7820 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7826 if ((err
= _is_blocking( s
, &is_blocking
)))
7828 err
= NtStatusToWSAError( err
);
7835 int poll_timeout
= -1;
7836 INT64 timeout
= get_rcvsnd_timeo(fd
, TRUE
);
7840 timeout
-= GetTickCount() - timeout_start
;
7841 if (timeout
< 0) poll_timeout
= 0;
7842 else poll_timeout
= timeout
<= INT_MAX
? timeout
: INT_MAX
;
7846 pfd
.events
= POLLIN
;
7847 if (*lpFlags
& WS_MSG_OOB
) pfd
.events
|= POLLPRI
;
7849 if (!poll_timeout
|| !poll( &pfd
, 1, poll_timeout
))
7852 /* a timeout is not fatal */
7853 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7859 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7860 err
= WSAEWOULDBLOCK
;
7865 TRACE(" -> %i bytes\n", n
);
7866 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
7867 release_sock_fd( s
, fd
);
7868 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
7869 SetLastError(ERROR_SUCCESS
);
7874 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
7875 release_sock_fd( s
, fd
);
7876 WARN(" -> ERROR %d\n", err
);
7877 SetLastError( err
);
7878 return SOCKET_ERROR
;
7881 /***********************************************************************
7882 * WSARecvFrom (WS2_32.69)
7884 INT WINAPI
WSARecvFrom( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
7885 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
, struct WS_sockaddr
*lpFrom
,
7886 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
7887 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
7890 return WS2_recv_base( s
, lpBuffers
, dwBufferCount
,
7891 lpNumberOfBytesRecvd
, lpFlags
,
7893 lpOverlapped
, lpCompletionRoutine
, NULL
);
7896 /***********************************************************************
7897 * WSCInstallProvider (WS2_32.88)
7899 INT WINAPI
WSCInstallProvider( const LPGUID lpProviderId
,
7900 LPCWSTR lpszProviderDllPath
,
7901 const LPWSAPROTOCOL_INFOW lpProtocolInfoList
,
7902 DWORD dwNumberOfEntries
,
7905 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId
),
7906 debugstr_w(lpszProviderDllPath
), lpProtocolInfoList
,
7907 dwNumberOfEntries
, lpErrno
);
7913 /***********************************************************************
7914 * WSCDeinstallProvider (WS2_32.83)
7916 INT WINAPI
WSCDeinstallProvider(LPGUID lpProviderId
, LPINT lpErrno
)
7918 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId
), lpErrno
);
7924 /***********************************************************************
7925 * WSAAccept (WS2_32.26)
7927 SOCKET WINAPI
WSAAccept( SOCKET s
, struct WS_sockaddr
*addr
, LPINT addrlen
,
7928 LPCONDITIONPROC lpfnCondition
, DWORD_PTR dwCallbackData
)
7932 WSABUF CallerId
, CallerData
, CalleeId
, CalleeData
;
7933 /* QOS SQOS, GQOS; */
7936 SOCKADDR src_addr
, dst_addr
;
7938 TRACE("socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
7939 s
, addr
, addrlen
, lpfnCondition
, dwCallbackData
);
7941 cs
= WS_accept(s
, addr
, addrlen
);
7942 if (cs
== SOCKET_ERROR
) return SOCKET_ERROR
;
7943 if (!lpfnCondition
) return cs
;
7945 if (addr
&& addrlen
)
7947 CallerId
.buf
= (char *)addr
;
7948 CallerId
.len
= *addrlen
;
7952 size
= sizeof(src_addr
);
7953 WS_getpeername(cs
, &src_addr
, &size
);
7954 CallerId
.buf
= (char *)&src_addr
;
7955 CallerId
.len
= size
;
7957 CallerData
.buf
= NULL
;
7960 size
= sizeof(dst_addr
);
7961 WS_getsockname(cs
, &dst_addr
, &size
);
7963 CalleeId
.buf
= (char *)&dst_addr
;
7964 CalleeId
.len
= sizeof(dst_addr
);
7966 ret
= (*lpfnCondition
)(&CallerId
, &CallerData
, NULL
, NULL
,
7967 &CalleeId
, &CalleeData
, &g
, dwCallbackData
);
7974 SERVER_START_REQ( set_socket_deferred
)
7976 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
7977 req
->deferred
= wine_server_obj_handle( SOCKET2HANDLE(cs
) );
7978 if ( !wine_server_call_err ( req
) )
7980 SetLastError( WSATRY_AGAIN
);
7981 WS_closesocket( cs
);
7985 return SOCKET_ERROR
;
7988 SetLastError(WSAECONNREFUSED
);
7989 return SOCKET_ERROR
;
7991 FIXME("Unknown return type from Condition function\n");
7992 SetLastError(WSAENOTSOCK
);
7993 return SOCKET_ERROR
;
7997 /***********************************************************************
7998 * WSADuplicateSocketA (WS2_32.32)
8000 int WINAPI
WSADuplicateSocketA( SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOA lpProtocolInfo
)
8002 return WS_DuplicateSocket(FALSE
, s
, dwProcessId
, (LPWSAPROTOCOL_INFOW
) lpProtocolInfo
);
8005 /***********************************************************************
8006 * WSADuplicateSocketW (WS2_32.33)
8008 int WINAPI
WSADuplicateSocketW( SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOW lpProtocolInfo
)
8010 return WS_DuplicateSocket(TRUE
, s
, dwProcessId
, lpProtocolInfo
);
8013 /***********************************************************************
8014 * WSAInstallServiceClassA (WS2_32.48)
8016 int WINAPI
WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info
)
8018 FIXME("Request to install service %s\n",debugstr_a(info
->lpszServiceClassName
));
8019 SetLastError(WSAEACCES
);
8020 return SOCKET_ERROR
;
8023 /***********************************************************************
8024 * WSAInstallServiceClassW (WS2_32.49)
8026 int WINAPI
WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info
)
8028 FIXME("Request to install service %s\n",debugstr_w(info
->lpszServiceClassName
));
8029 SetLastError(WSAEACCES
);
8030 return SOCKET_ERROR
;
8033 /***********************************************************************
8034 * WSARemoveServiceClass (WS2_32.70)
8036 int WINAPI
WSARemoveServiceClass(LPGUID info
)
8038 FIXME("Request to remove service %s\n", debugstr_guid(info
));
8039 SetLastError(WSATYPE_NOT_FOUND
);
8040 return SOCKET_ERROR
;
8043 /***********************************************************************
8044 * inet_ntop (WS2_32.@)
8046 PCSTR WINAPI
WS_inet_ntop( INT family
, PVOID addr
, PSTR buffer
, SIZE_T len
)
8048 #ifdef HAVE_INET_NTOP
8049 struct WS_in6_addr
*in6
;
8050 struct WS_in_addr
*in
;
8053 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family
, addr
, buffer
, len
);
8056 SetLastError( STATUS_INVALID_PARAMETER
);
8065 pdst
= inet_ntop( AF_INET
, &in
->WS_s_addr
, buffer
, len
);
8071 pdst
= inet_ntop( AF_INET6
, in6
->WS_s6_addr
, buffer
, len
);
8075 SetLastError( WSAEAFNOSUPPORT
);
8079 if (!pdst
) SetLastError( STATUS_INVALID_PARAMETER
);
8082 FIXME( "not supported on this platform\n" );
8083 SetLastError( WSAEAFNOSUPPORT
);
8088 /***********************************************************************
8089 * inet_pton (WS2_32.@)
8091 INT WINAPI
WS_inet_pton( INT family
, PCSTR addr
, PVOID buffer
)
8093 #ifdef HAVE_INET_PTON
8096 TRACE("family %d, addr %s, buffer (%p)\n", family
, debugstr_a(addr
), buffer
);
8098 if (!addr
|| !buffer
)
8100 SetLastError(WSAEFAULT
);
8101 return SOCKET_ERROR
;
8104 unixaf
= convert_af_w2u(family
);
8105 if (unixaf
!= AF_INET
&& unixaf
!= AF_INET6
)
8107 SetLastError(WSAEAFNOSUPPORT
);
8108 return SOCKET_ERROR
;
8111 ret
= inet_pton(unixaf
, addr
, buffer
);
8112 if (ret
== -1) SetLastError(wsaErrno());
8115 FIXME( "not supported on this platform\n" );
8116 SetLastError( WSAEAFNOSUPPORT
);
8117 return SOCKET_ERROR
;
8121 /***********************************************************************
8122 * InetPtonW (WS2_32.@)
8124 INT WINAPI
InetPtonW(INT family
, PCWSTR addr
, PVOID buffer
)
8130 TRACE("family %d, addr %s, buffer (%p)\n", family
, debugstr_w(addr
), buffer
);
8134 SetLastError(WSAEFAULT
);
8135 return SOCKET_ERROR
;
8138 len
= WideCharToMultiByte(CP_ACP
, 0, addr
, -1, NULL
, 0, NULL
, NULL
);
8139 if (!(addrA
= HeapAlloc(GetProcessHeap(), 0, len
)))
8141 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8142 return SOCKET_ERROR
;
8144 WideCharToMultiByte(CP_ACP
, 0, addr
, -1, addrA
, len
, NULL
, NULL
);
8146 ret
= WS_inet_pton(family
, addrA
, buffer
);
8148 HeapFree(GetProcessHeap(), 0, addrA
);
8152 /***********************************************************************
8153 * InetNtopW (WS2_32.@)
8155 PCWSTR WINAPI
InetNtopW(INT family
, PVOID addr
, PWSTR buffer
, SIZE_T len
)
8157 char bufferA
[WS_INET6_ADDRSTRLEN
];
8160 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family
, addr
, buffer
, len
);
8162 if (WS_inet_ntop(family
, addr
, bufferA
, sizeof(bufferA
)))
8164 if (MultiByteToWideChar(CP_ACP
, 0, bufferA
, -1, buffer
, len
))
8167 SetLastError(ERROR_INVALID_PARAMETER
);
8172 /***********************************************************************
8173 * WSAStringToAddressA (WS2_32.80)
8175 INT WINAPI
WSAStringToAddressA(LPSTR AddressString
,
8177 LPWSAPROTOCOL_INFOA lpProtocolInfo
,
8178 LPSOCKADDR lpAddress
,
8179 LPINT lpAddressLength
)
8182 LPSTR workBuffer
=NULL
,ptrPort
;
8184 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString
), AddressFamily
,
8185 lpProtocolInfo
, lpAddress
, lpAddressLength
);
8187 if (!lpAddressLength
|| !lpAddress
) return SOCKET_ERROR
;
8191 SetLastError(WSAEINVAL
);
8192 return SOCKET_ERROR
;
8196 FIXME("ProtocolInfo not implemented.\n");
8198 workBuffer
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
,
8199 strlen(AddressString
) + 1);
8202 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8203 return SOCKET_ERROR
;
8206 strcpy(workBuffer
, AddressString
);
8208 switch(AddressFamily
)
8212 struct in_addr inetaddr
;
8214 /* If lpAddressLength is too small, tell caller the size we need */
8215 if (*lpAddressLength
< sizeof(SOCKADDR_IN
))
8217 *lpAddressLength
= sizeof(SOCKADDR_IN
);
8221 *lpAddressLength
= sizeof(SOCKADDR_IN
);
8222 memset(lpAddress
, 0, sizeof(SOCKADDR_IN
));
8224 ((LPSOCKADDR_IN
)lpAddress
)->sin_family
= WS_AF_INET
;
8226 ptrPort
= strchr(workBuffer
, ':');
8229 /* User may have entered an IPv6 and asked to parse as IPv4 */
8230 if(strchr(ptrPort
+ 1, ':'))
8235 ((LPSOCKADDR_IN
)lpAddress
)->sin_port
= htons(atoi(ptrPort
+1));
8239 if(inet_aton(workBuffer
, &inetaddr
) > 0)
8241 ((LPSOCKADDR_IN
)lpAddress
)->sin_addr
.WS_s_addr
= inetaddr
.s_addr
;
8251 struct in6_addr inetaddr
;
8252 char *ptrAddr
= workBuffer
;
8254 /* If lpAddressLength is too small, tell caller the size we need */
8255 if (*lpAddressLength
< sizeof(SOCKADDR_IN6
))
8257 *lpAddressLength
= sizeof(SOCKADDR_IN6
);
8261 #ifdef HAVE_INET_PTON
8262 *lpAddressLength
= sizeof(SOCKADDR_IN6
);
8263 memset(lpAddress
, 0, sizeof(SOCKADDR_IN6
));
8265 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_family
= WS_AF_INET6
;
8267 /* Valid IPv6 addresses can also be surrounded by [ ], and in this case
8268 * a port number may follow after like in [fd12:3456:7890::1]:12345
8269 * We need to cut the brackets and find the port if any. */
8271 if(*workBuffer
== '[')
8273 ptrPort
= strchr(workBuffer
, ']');
8276 SetLastError(WSAEINVAL
);
8277 return SOCKET_ERROR
;
8280 if (ptrPort
[1] == ':')
8281 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_port
= htons(atoi(ptrPort
+ 2));
8284 ptrAddr
= workBuffer
+ 1;
8287 if(inet_pton(AF_INET6
, ptrAddr
, &inetaddr
) > 0)
8289 memcpy(&((LPSOCKADDR_IN6
)lpAddress
)->sin6_addr
, &inetaddr
,
8290 sizeof(struct in6_addr
));
8294 #endif /* HAVE_INET_PTON */
8300 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
8301 TRACE("Unsupported address family specified: %d.\n", AddressFamily
);
8305 HeapFree(GetProcessHeap(), 0, workBuffer
);
8309 return SOCKET_ERROR
;
8312 /***********************************************************************
8313 * WSAStringToAddressW (WS2_32.81)
8315 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
8316 * If this should be the case, it would be required to map these digits
8317 * to Unicode digits (0-9) using FoldString first.
8319 INT WINAPI
WSAStringToAddressW(LPWSTR AddressString
,
8321 LPWSAPROTOCOL_INFOW lpProtocolInfo
,
8322 LPSOCKADDR lpAddress
,
8323 LPINT lpAddressLength
)
8326 LPSTR workBuffer
=NULL
;
8327 WSAPROTOCOL_INFOA infoA
;
8328 LPWSAPROTOCOL_INFOA lpProtoInfoA
= NULL
;
8330 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString
), AddressFamily
, lpProtocolInfo
,
8331 lpAddress
, lpAddressLength
);
8333 if (!lpAddressLength
|| !lpAddress
) return SOCKET_ERROR
;
8335 /* if ProtocolInfo is available - convert to ANSI variant */
8338 lpProtoInfoA
= &infoA
;
8339 memcpy( lpProtoInfoA
, lpProtocolInfo
, FIELD_OFFSET( WSAPROTOCOL_INFOA
, szProtocol
) );
8341 if (!WideCharToMultiByte( CP_ACP
, 0, lpProtocolInfo
->szProtocol
, -1,
8342 lpProtoInfoA
->szProtocol
, WSAPROTOCOL_LEN
+1, NULL
, NULL
))
8344 SetLastError(WSAEINVAL
);
8345 return SOCKET_ERROR
;
8351 /* Translate AddressString to ANSI code page - assumes that only
8352 standard digits 0-9 are used with this API call */
8353 sBuffer
= WideCharToMultiByte( CP_ACP
, 0, AddressString
, -1, NULL
, 0, NULL
, NULL
);
8354 workBuffer
= HeapAlloc( GetProcessHeap(), 0, sBuffer
);
8358 WideCharToMultiByte( CP_ACP
, 0, AddressString
, -1, workBuffer
, sBuffer
, NULL
, NULL
);
8359 res
= WSAStringToAddressA(workBuffer
,AddressFamily
,lpProtoInfoA
,
8360 lpAddress
,lpAddressLength
);
8361 HeapFree( GetProcessHeap(), 0, workBuffer
);
8365 res
= WSA_NOT_ENOUGH_MEMORY
;
8371 return SOCKET_ERROR
;
8374 /***********************************************************************
8375 * WSAAddressToStringA (WS2_32.27)
8377 * See WSAAddressToStringW
8379 INT WINAPI
WSAAddressToStringA( LPSOCKADDR sockaddr
, DWORD len
,
8380 LPWSAPROTOCOL_INFOA info
, LPSTR string
,
8384 CHAR buffer
[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8387 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr
, len
, info
, string
, lenstr
);
8389 if (!sockaddr
) return SOCKET_ERROR
;
8390 if (!string
|| !lenstr
) return SOCKET_ERROR
;
8392 switch(sockaddr
->sa_family
)
8396 unsigned int long_ip
= ntohl(((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
);
8397 if (len
< sizeof(SOCKADDR_IN
)) return SOCKET_ERROR
;
8398 sprintf( buffer
, "%u.%u.%u.%u:%u",
8399 (long_ip
>> 24) & 0xff,
8400 (long_ip
>> 16) & 0xff,
8401 (long_ip
>> 8) & 0xff,
8403 ntohs( ((SOCKADDR_IN
*)sockaddr
)->sin_port
) );
8405 p
= strchr( buffer
, ':' );
8406 if (!((SOCKADDR_IN
*)sockaddr
)->sin_port
) *p
= 0;
8411 struct WS_sockaddr_in6
*sockaddr6
= (LPSOCKADDR_IN6
) sockaddr
;
8415 if (len
< sizeof(SOCKADDR_IN6
)) return SOCKET_ERROR
;
8416 if ((sockaddr6
->sin6_port
))
8417 strcpy(buffer
, "[");
8418 slen
= strlen(buffer
);
8419 if (!WS_inet_ntop(WS_AF_INET6
, &sockaddr6
->sin6_addr
, &buffer
[slen
], sizeof(buffer
) - slen
))
8421 SetLastError(WSAEINVAL
);
8422 return SOCKET_ERROR
;
8424 if ((sockaddr6
->sin6_scope_id
))
8425 sprintf(buffer
+strlen(buffer
), "%%%u", sockaddr6
->sin6_scope_id
);
8426 if ((sockaddr6
->sin6_port
))
8427 sprintf(buffer
+strlen(buffer
), "]:%u", ntohs(sockaddr6
->sin6_port
));
8432 SetLastError(WSAEINVAL
);
8433 return SOCKET_ERROR
;
8436 size
= strlen( buffer
) + 1;
8441 SetLastError(WSAEFAULT
);
8442 return SOCKET_ERROR
;
8445 TRACE("=> %s,%u bytes\n", debugstr_a(buffer
), size
);
8447 strcpy( string
, buffer
);
8451 /***********************************************************************
8452 * WSAAddressToStringW (WS2_32.28)
8454 * Convert a sockaddr address into a readable address string.
8457 * sockaddr [I] Pointer to a sockaddr structure.
8458 * len [I] Size of the sockaddr structure.
8459 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
8460 * string [I/O] Pointer to a buffer to receive the address string.
8461 * lenstr [I/O] Size of the receive buffer in WCHARs.
8465 * Failure: SOCKET_ERROR
8468 * The 'info' parameter is ignored.
8470 INT WINAPI
WSAAddressToStringW( LPSOCKADDR sockaddr
, DWORD len
,
8471 LPWSAPROTOCOL_INFOW info
, LPWSTR string
,
8476 WCHAR buffer
[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8479 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr
, len
, info
, string
, lenstr
);
8482 ret
= WSAAddressToStringA(sockaddr
, len
, NULL
, bufAddr
, &size
);
8484 if (ret
) return ret
;
8486 MultiByteToWideChar( CP_ACP
, 0, bufAddr
, size
, buffer
, sizeof( buffer
)/sizeof(WCHAR
));
8491 SetLastError(WSAEFAULT
);
8492 return SOCKET_ERROR
;
8495 TRACE("=> %s,%u bytes\n", debugstr_w(buffer
), size
);
8497 lstrcpyW( string
, buffer
);
8501 /***********************************************************************
8502 * WSAEnumNameSpaceProvidersA (WS2_32.34)
8504 INT WINAPI
WSAEnumNameSpaceProvidersA( LPDWORD len
, LPWSANAMESPACE_INFOA buffer
)
8506 FIXME( "(%p %p) Stub!\n", len
, buffer
);
8510 /***********************************************************************
8511 * WSAEnumNameSpaceProvidersW (WS2_32.35)
8513 INT WINAPI
WSAEnumNameSpaceProvidersW( LPDWORD len
, LPWSANAMESPACE_INFOW buffer
)
8515 FIXME( "(%p %p) Stub!\n", len
, buffer
);
8519 /***********************************************************************
8520 * WSAGetQOSByName (WS2_32.41)
8522 BOOL WINAPI
WSAGetQOSByName( SOCKET s
, LPWSABUF lpQOSName
, LPQOS lpQOS
)
8524 FIXME( "(0x%04lx %p %p) Stub!\n", s
, lpQOSName
, lpQOS
);
8528 /***********************************************************************
8529 * WSAGetServiceClassInfoA (WS2_32.42)
8531 INT WINAPI
WSAGetServiceClassInfoA( LPGUID provider
, LPGUID service
, LPDWORD len
,
8532 LPWSASERVICECLASSINFOA info
)
8534 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider
), debugstr_guid(service
),
8536 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8537 return SOCKET_ERROR
;
8540 /***********************************************************************
8541 * WSAGetServiceClassInfoW (WS2_32.43)
8543 INT WINAPI
WSAGetServiceClassInfoW( LPGUID provider
, LPGUID service
, LPDWORD len
,
8544 LPWSASERVICECLASSINFOW info
)
8546 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider
), debugstr_guid(service
),
8548 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8549 return SOCKET_ERROR
;
8552 /***********************************************************************
8553 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
8555 INT WINAPI
WSAGetServiceClassNameByClassIdA( LPGUID
class, LPSTR service
, LPDWORD len
)
8557 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service
, len
);
8558 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8559 return SOCKET_ERROR
;
8562 /***********************************************************************
8563 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
8565 INT WINAPI
WSAGetServiceClassNameByClassIdW( LPGUID
class, LPWSTR service
, LPDWORD len
)
8567 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service
, len
);
8568 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8569 return SOCKET_ERROR
;
8572 /***********************************************************************
8573 * WSALookupServiceBeginA (WS2_32.59)
8575 INT WINAPI
WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions
,
8576 DWORD dwControlFlags
,
8579 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions
, dwControlFlags
,
8581 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8582 return SOCKET_ERROR
;
8585 /***********************************************************************
8586 * WSALookupServiceBeginW (WS2_32.60)
8588 INT WINAPI
WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions
,
8589 DWORD dwControlFlags
,
8592 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions
, dwControlFlags
,
8594 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8595 return SOCKET_ERROR
;
8598 /***********************************************************************
8599 * WSALookupServiceEnd (WS2_32.61)
8601 INT WINAPI
WSALookupServiceEnd( HANDLE lookup
)
8603 FIXME("(%p) Stub!\n", lookup
);
8607 /***********************************************************************
8608 * WSALookupServiceNextA (WS2_32.62)
8610 INT WINAPI
WSALookupServiceNextA( HANDLE lookup
, DWORD flags
, LPDWORD len
, LPWSAQUERYSETA results
)
8612 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup
, flags
, len
, results
);
8613 SetLastError(WSA_E_NO_MORE
);
8614 return SOCKET_ERROR
;
8617 /***********************************************************************
8618 * WSALookupServiceNextW (WS2_32.63)
8620 INT WINAPI
WSALookupServiceNextW( HANDLE lookup
, DWORD flags
, LPDWORD len
, LPWSAQUERYSETW results
)
8622 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup
, flags
, len
, results
);
8623 SetLastError(WSA_E_NO_MORE
);
8624 return SOCKET_ERROR
;
8627 /***********************************************************************
8628 * WSANtohl (WS2_32.64)
8630 INT WINAPI
WSANtohl( SOCKET s
, WS_u_long netlong
, WS_u_long
* lphostlong
)
8632 TRACE( "(%04lx 0x%08x %p)\n", s
, netlong
, lphostlong
);
8634 if (!lphostlong
) return WSAEFAULT
;
8636 *lphostlong
= ntohl( netlong
);
8640 /***********************************************************************
8641 * WSANtohs (WS2_32.65)
8643 INT WINAPI
WSANtohs( SOCKET s
, WS_u_short netshort
, WS_u_short
* lphostshort
)
8645 TRACE( "(%04lx 0x%08x %p)\n", s
, netshort
, lphostshort
);
8647 if (!lphostshort
) return WSAEFAULT
;
8649 *lphostshort
= ntohs( netshort
);
8653 /***********************************************************************
8654 * WSAProviderConfigChange (WS2_32.66)
8656 INT WINAPI
WSAProviderConfigChange( LPHANDLE handle
, LPWSAOVERLAPPED overlapped
,
8657 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
8659 FIXME( "(%p %p %p) Stub!\n", handle
, overlapped
, completion
);
8660 return SOCKET_ERROR
;
8663 /***********************************************************************
8664 * WSARecvDisconnect (WS2_32.68)
8666 INT WINAPI
WSARecvDisconnect( SOCKET s
, LPWSABUF disconnectdata
)
8668 TRACE( "(%04lx %p)\n", s
, disconnectdata
);
8670 return WS_shutdown( s
, SD_RECEIVE
);
8673 /***********************************************************************
8674 * WSASetServiceA (WS2_32.76)
8676 INT WINAPI
WSASetServiceA( LPWSAQUERYSETA query
, WSAESETSERVICEOP operation
, DWORD flags
)
8678 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query
, operation
, flags
);
8682 /***********************************************************************
8683 * WSASetServiceW (WS2_32.77)
8685 INT WINAPI
WSASetServiceW( LPWSAQUERYSETW query
, WSAESETSERVICEOP operation
, DWORD flags
)
8687 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query
, operation
, flags
);
8691 /***********************************************************************
8692 * WSCEnableNSProvider (WS2_32.84)
8694 INT WINAPI
WSCEnableNSProvider( LPGUID provider
, BOOL enable
)
8696 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider
), enable
);
8700 /***********************************************************************
8701 * WSCGetProviderPath (WS2_32.86)
8703 INT WINAPI
WSCGetProviderPath( LPGUID provider
, LPWSTR path
, LPINT len
, LPINT errcode
)
8705 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider
), path
, len
, errcode
);
8707 if (!errcode
|| !provider
|| !len
) return WSAEFAULT
;
8709 *errcode
= WSAEINVAL
;
8710 return SOCKET_ERROR
;
8713 /***********************************************************************
8714 * WSCInstallNameSpace (WS2_32.87)
8716 INT WINAPI
WSCInstallNameSpace( LPWSTR identifier
, LPWSTR path
, DWORD
namespace,
8717 DWORD version
, LPGUID provider
)
8719 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier
), debugstr_w(path
),
8720 namespace, version
, debugstr_guid(provider
) );
8724 /***********************************************************************
8725 * WSCUnInstallNameSpace (WS2_32.89)
8727 INT WINAPI
WSCUnInstallNameSpace( LPGUID lpProviderId
)
8729 FIXME("(%s) Stub!\n", debugstr_guid(lpProviderId
));
8733 /***********************************************************************
8734 * WSCWriteProviderOrder (WS2_32.91)
8736 INT WINAPI
WSCWriteProviderOrder( LPDWORD entry
, DWORD number
)
8738 FIXME("(%p 0x%08x) Stub!\n", entry
, number
);
8742 /***********************************************************************
8743 * WSANSPIoctl (WS2_32.91)
8745 INT WINAPI
WSANSPIoctl( HANDLE hLookup
, DWORD dwControlCode
, LPVOID lpvInBuffer
,
8746 DWORD cbInBuffer
, LPVOID lpvOutBuffer
, DWORD cbOutBuffer
,
8747 LPDWORD lpcbBytesReturned
, LPWSACOMPLETION lpCompletion
)
8749 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup
, dwControlCode
,
8750 lpvInBuffer
, cbInBuffer
, lpvOutBuffer
, cbOutBuffer
, lpcbBytesReturned
, lpCompletion
);
8751 SetLastError(WSA_NOT_ENOUGH_MEMORY
);
8752 return SOCKET_ERROR
;
8755 /*****************************************************************************
8756 * WSAEnumProtocolsA [WS2_32.@]
8758 * see function WSAEnumProtocolsW
8760 INT WINAPI
WSAEnumProtocolsA( LPINT protocols
, LPWSAPROTOCOL_INFOA buffer
, LPDWORD len
)
8762 return WS_EnumProtocols( FALSE
, protocols
, (LPWSAPROTOCOL_INFOW
) buffer
, len
);
8765 /*****************************************************************************
8766 * WSAEnumProtocolsW [WS2_32.@]
8768 * Retrieves information about specified set of active network protocols.
8771 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
8772 * retrieves information on all available protocols.
8773 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
8775 * len [I/O] Pointer to a variable specifying buffer size. On output
8776 * the variable holds the number of bytes needed when the
8777 * specified size is too small.
8780 * Success: number of WSAPROTOCOL_INFO structures in buffer.
8781 * Failure: SOCKET_ERROR
8784 * NT4SP5 does not return SPX if protocols == NULL
8787 * - NT4SP5 returns in addition these list of NETBIOS protocols
8788 * (address family 17), each entry two times one for socket type 2 and 5
8790 * iProtocol szProtocol
8791 * 0x80000000 \Device\NwlnkNb
8792 * 0xfffffffa \Device\NetBT_CBENT7
8793 * 0xfffffffb \Device\Nbf_CBENT7
8794 * 0xfffffffc \Device\NetBT_NdisWan5
8795 * 0xfffffffd \Device\NetBT_El9202
8796 * 0xfffffffe \Device\Nbf_El9202
8797 * 0xffffffff \Device\Nbf_NdisWan4
8799 * - there is no check that the operating system supports the returned
8802 INT WINAPI
WSAEnumProtocolsW( LPINT protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
)
8804 return WS_EnumProtocols( TRUE
, protocols
, buffer
, len
);
8807 /*****************************************************************************
8808 * WSCEnumProtocols [WS2_32.@]
8811 * protocols [I] Null-terminated array of iProtocol values.
8812 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
8813 * len [I/O] Size of buffer on input/output.
8814 * errno [O] Error code.
8817 * Success: number of protocols to be reported on.
8818 * Failure: SOCKET_ERROR. error is in errno.
8821 * Doesn't supply info on layered protocols.
8824 INT WINAPI
WSCEnumProtocols( LPINT protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
, LPINT err
)
8826 INT ret
= WSAEnumProtocolsW( protocols
, buffer
, len
);
8828 if (ret
== SOCKET_ERROR
) *err
= WSAENOBUFS
;