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>
39 #ifdef HAVE_SYS_IOCTL_H
40 # include <sys/ioctl.h>
42 #ifdef HAVE_SYS_FILIO_H
43 # include <sys/filio.h>
45 #ifdef HAVE_SYS_SOCKIO_H
46 # include <sys/sockio.h>
50 # include <sys/so_ioctl.h>
53 #ifdef HAVE_SYS_PARAM_H
54 # include <sys/param.h>
60 #ifdef HAVE_SYS_WAIT_H
61 # include <sys/wait.h>
66 #ifdef HAVE_SYS_SOCKET_H
67 #include <sys/socket.h>
69 #ifdef HAVE_NETINET_IN_H
70 # include <netinet/in.h>
72 #ifdef HAVE_NETINET_TCP_H
73 # include <netinet/tcp.h>
75 #ifdef HAVE_ARPA_INET_H
76 # include <arpa/inet.h>
88 #ifdef HAVE_ARPA_NAMESER_H
89 # include <arpa/nameser.h>
97 #ifdef HAVE_LINUX_FILTER_H
98 # include <linux/filter.h>
101 #ifdef HAVE_NETIPX_IPX_H
102 # 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>
115 #ifdef HAVE_LINUX_IRDA_H
116 # ifdef HAVE_LINUX_TYPES_H
117 # include <linux/types.h>
119 # include <linux/irda.h>
126 #ifdef HAVE_SYS_POLL_H
127 # include <sys/poll.h>
129 #ifdef HAVE_SYS_TIME_H
130 # include <sys/time.h>
133 #define NONAMELESSUNION
134 #define NONAMELESSSTRUCT
135 #include "ntstatus.h"
136 #define WIN32_NO_STATUS
141 #include "winerror.h"
143 #include "winsock2.h"
145 #include "ws2tcpip.h"
148 #include "wshisotp.h"
152 #define USE_WC_PREFIX /* For CMSG_DATA */
153 #include "iphlpapi.h"
154 #include "wine/server.h"
155 #include "wine/debug.h"
156 #include "wine/exception.h"
157 #include "wine/unicode.h"
160 # include "wsnwlink.h"
163 #if defined(linux) && !defined(IP_UNICAST_IF)
164 #define IP_UNICAST_IF 50
167 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
168 # define sipx_network sipx_addr.x_net
169 # define sipx_node sipx_addr.x_host.c_host
170 #endif /* __FreeBSD__ */
173 #define INADDR_NONE ~0UL
176 WINE_DEFAULT_DEBUG_CHANNEL(winsock
);
177 WINE_DECLARE_DEBUG_CHANNEL(winediag
);
179 /* names of the protocols */
180 static const WCHAR NameIpxW
[] = {'I', 'P', 'X', '\0'};
181 static const WCHAR NameSpxW
[] = {'S', 'P', 'X', '\0'};
182 static const WCHAR NameSpxIIW
[] = {'S', 'P', 'X', ' ', 'I', 'I', '\0'};
183 static const WCHAR NameTcpW
[] = {'T', 'C', 'P', '/', 'I', 'P', '\0'};
184 static const WCHAR NameUdpW
[] = {'U', 'D', 'P', '/', 'I', 'P', '\0'};
186 /* Taken from Win2k */
187 static const GUID ProviderIdIP
= { 0xe70f1aa0, 0xab8b, 0x11cf,
188 { 0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
189 static const GUID ProviderIdIPX
= { 0x11058240, 0xbe47, 0x11cf,
190 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
191 static const GUID ProviderIdSPX
= { 0x11058241, 0xbe47, 0x11cf,
192 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
194 static const INT valid_protocols
[] =
204 #define IS_IPX_PROTO(X) ((X) >= WS_NSPROTO_IPX && (X) <= WS_NSPROTO_IPX + 255)
206 #if defined(IP_UNICAST_IF) && defined(SO_ATTACH_FILTER)
207 # define LINUX_BOUND_IF
208 struct interface_filter
{
209 struct sock_filter iface_memaddr
;
210 struct sock_filter iface_rule
;
211 struct sock_filter ip_memaddr
;
212 struct sock_filter ip_rule
;
213 struct sock_filter return_keep
;
214 struct sock_filter return_dump
;
216 # define FILTER_JUMP_DUMP(here) (u_char)(offsetof(struct interface_filter, return_dump) \
217 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
218 /sizeof(struct sock_filter)
219 # define FILTER_JUMP_KEEP(here) (u_char)(offsetof(struct interface_filter, return_keep) \
220 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
221 /sizeof(struct sock_filter)
222 # define FILTER_JUMP_NEXT() (u_char)(0)
223 # define SKF_NET_DESTIP 16 /* offset in the network header to the destination IP */
224 static struct interface_filter generic_interface_filter
= {
225 /* This filter rule allows incoming packets on the specified interface, which works for all
226 * remotely generated packets and for locally generated broadcast packets. */
227 BPF_STMT(BPF_LD
+BPF_W
+BPF_ABS
, SKF_AD_OFF
+SKF_AD_IFINDEX
),
228 BPF_JUMP(BPF_JMP
+BPF_JEQ
+BPF_K
, 0xdeadbeef, FILTER_JUMP_KEEP(iface_rule
), FILTER_JUMP_NEXT()),
229 /* This rule allows locally generated packets targeted at the specific IP address of the chosen
230 * adapter (local packets not destined for the broadcast address do not have IFINDEX set) */
231 BPF_STMT(BPF_LD
+BPF_W
+BPF_ABS
, SKF_NET_OFF
+SKF_NET_DESTIP
),
232 BPF_JUMP(BPF_JMP
+BPF_JEQ
+BPF_K
, 0xdeadbeef, FILTER_JUMP_KEEP(ip_rule
), FILTER_JUMP_DUMP(ip_rule
)),
233 BPF_STMT(BPF_RET
+BPF_K
, (u_int
)-1), /* keep packet */
234 BPF_STMT(BPF_RET
+BPF_K
, 0) /* dump packet */
236 #endif /* LINUX_BOUND_IF */
239 * The actual definition of WSASendTo, wrapped in a different function name
240 * so that internal calls from ws2_32 itself will not trigger programs like
241 * Garena, which hooks WSASendTo/WSARecvFrom calls.
243 static int WS2_sendto( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
244 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
245 const struct WS_sockaddr
*to
, int tolen
,
246 LPWSAOVERLAPPED lpOverlapped
,
247 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);
250 * Internal fundamental receive function, essentially WSARecvFrom with an
251 * additional parameter to support message control headers.
253 static int WS2_recv_base( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
254 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
,
255 struct WS_sockaddr
*lpFrom
,
256 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
257 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
,
258 LPWSABUF lpControlBuffer
);
260 /* critical section to protect some non-reentrant net function */
261 static CRITICAL_SECTION csWSgetXXXbyYYY
;
262 static CRITICAL_SECTION_DEBUG critsect_debug
=
264 0, 0, &csWSgetXXXbyYYY
,
265 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
266 0, 0, { (DWORD_PTR
)(__FILE__
": csWSgetXXXbyYYY") }
268 static CRITICAL_SECTION csWSgetXXXbyYYY
= { &critsect_debug
, -1, 0, 0, 0, 0 };
270 union generic_unix_sockaddr
272 struct sockaddr addr
;
273 char data
[128]; /* should be big enough for all families */
276 static inline const char *debugstr_sockaddr( const struct WS_sockaddr
*a
)
278 if (!a
) return "(nil)";
279 switch (a
->sa_family
)
282 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
283 inet_ntoa(((const struct sockaddr_in
*)a
)->sin_addr
),
284 ntohs(((const struct sockaddr_in
*)a
)->sin_port
));
289 struct WS_sockaddr_in6
*sin
= (struct WS_sockaddr_in6
*)a
;
291 p
= WS_inet_ntop( WS_AF_INET6
, &sin
->sin6_addr
, buf
, sizeof(buf
) );
293 p
= "(unknown IPv6 address)";
294 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
295 p
, ntohs(sin
->sin6_port
));
300 char netnum
[16], nodenum
[16];
301 struct WS_sockaddr_ipx
*sin
= (struct WS_sockaddr_ipx
*)a
;
303 for (i
= 0;i
< 4; i
++) sprintf(netnum
+ i
* 2, "%02X", (unsigned char) sin
->sa_netnum
[i
]);
304 for (i
= 0;i
< 6; i
++) sprintf(nodenum
+ i
* 2, "%02X", (unsigned char) sin
->sa_nodenum
[i
]);
306 return wine_dbg_sprintf("{ family AF_IPX, address %s.%s, ipx socket %d }",
307 netnum
, nodenum
, sin
->sa_socket
);
313 memcpy( &addr
, ((const SOCKADDR_IRDA
*)a
)->irdaDeviceID
, sizeof(addr
) );
314 addr
= ntohl( addr
);
315 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
317 ((const SOCKADDR_IRDA
*)a
)->irdaServiceName
);
320 return wine_dbg_sprintf("{ family %d }", a
->sa_family
);
324 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
325 #define SOCKET2HANDLE(s) ((HANDLE)(s))
326 #define HANDLE2SOCKET(h) ((SOCKET)(h))
328 /****************************************************************
329 * Async IO declarations
330 ****************************************************************/
332 typedef struct ws2_async
336 LPWSAOVERLAPPED user_overlapped
;
337 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func
;
338 IO_STATUS_BLOCK local_iosb
;
339 struct WS_sockaddr
*addr
;
342 int val
; /* for send operations */
343 int *ptr
; /* for recv operations */
348 unsigned int n_iovecs
;
349 unsigned int first_iovec
;
350 struct iovec iovec
[1];
353 typedef struct ws2_accept_async
355 HANDLE listen_socket
;
356 HANDLE accept_socket
;
357 LPOVERLAPPED user_overlapped
;
359 PVOID buf
; /* buffer to write data to */
363 struct ws2_async
*read
;
366 /****************************************************************/
368 /* ----------------------------------- internal data */
370 /* ws_... struct conversion flags */
372 typedef struct /* WSAAsyncSelect() control struct */
374 HANDLE service
, event
, sock
;
380 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
381 #define WS_MAX_UDP_DATAGRAM 1024
382 static INT WINAPI
WSA_DefaultBlockingHook( FARPROC x
);
384 /* hostent's, servent's and protent's are stored in one buffer per thread,
385 * as documented on MSDN for the functions that return any of the buffers */
386 struct per_thread_data
389 struct WS_hostent
*he_buffer
;
390 struct WS_servent
*se_buffer
;
391 struct WS_protoent
*pe_buffer
;
395 char ntoa_buffer
[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
398 /* internal: routing description information */
405 static INT num_startup
; /* reference counter */
406 static FARPROC blocking_hook
= (FARPROC
)WSA_DefaultBlockingHook
;
408 /* function prototypes */
409 static struct WS_hostent
*WS_create_he(char *name
, int aliases
, int aliases_size
, int addresses
, int address_length
);
410 static struct WS_hostent
*WS_dup_he(const struct hostent
* p_he
);
411 static struct WS_protoent
*WS_dup_pe(const struct protoent
* p_pe
);
412 static struct WS_servent
*WS_dup_se(const struct servent
* p_se
);
413 static int ws_protocol_info(SOCKET s
, int unicode
, WSAPROTOCOL_INFOW
*buffer
, int *size
);
415 int WSAIOCTL_GetInterfaceCount(void);
416 int WSAIOCTL_GetInterfaceName(int intNumber
, char *intName
);
418 static void WS_AddCompletion( SOCKET sock
, ULONG_PTR CompletionValue
, NTSTATUS CompletionStatus
, ULONG Information
);
420 #define MAP_OPTION(opt) { WS_##opt, opt }
422 static const int ws_sock_map
[][2] =
424 MAP_OPTION( SO_DEBUG
),
425 MAP_OPTION( SO_ACCEPTCONN
),
426 MAP_OPTION( SO_REUSEADDR
),
427 MAP_OPTION( SO_KEEPALIVE
),
428 MAP_OPTION( SO_DONTROUTE
),
429 MAP_OPTION( SO_BROADCAST
),
430 MAP_OPTION( SO_LINGER
),
431 MAP_OPTION( SO_OOBINLINE
),
432 MAP_OPTION( SO_SNDBUF
),
433 MAP_OPTION( SO_RCVBUF
),
434 MAP_OPTION( SO_ERROR
),
435 MAP_OPTION( SO_TYPE
),
437 MAP_OPTION( SO_RCVTIMEO
),
440 MAP_OPTION( SO_SNDTIMEO
),
444 static const int ws_tcp_map
[][2] =
447 MAP_OPTION( TCP_NODELAY
),
451 static const int ws_ip_map
[][2] =
453 MAP_OPTION( IP_MULTICAST_IF
),
454 MAP_OPTION( IP_MULTICAST_TTL
),
455 MAP_OPTION( IP_MULTICAST_LOOP
),
456 MAP_OPTION( IP_ADD_MEMBERSHIP
),
457 MAP_OPTION( IP_DROP_MEMBERSHIP
),
458 MAP_OPTION( IP_OPTIONS
),
460 MAP_OPTION( IP_HDRINCL
),
462 MAP_OPTION( IP_TOS
),
463 MAP_OPTION( IP_TTL
),
465 MAP_OPTION( IP_PKTINFO
),
468 MAP_OPTION( IP_UNICAST_IF
),
472 static const int ws_ipv6_map
[][2] =
474 #ifdef IPV6_ADD_MEMBERSHIP
475 MAP_OPTION( IPV6_ADD_MEMBERSHIP
),
477 #ifdef IPV6_DROP_MEMBERSHIP
478 MAP_OPTION( IPV6_DROP_MEMBERSHIP
),
480 MAP_OPTION( IPV6_MULTICAST_IF
),
481 MAP_OPTION( IPV6_MULTICAST_HOPS
),
482 MAP_OPTION( IPV6_MULTICAST_LOOP
),
483 MAP_OPTION( IPV6_UNICAST_HOPS
),
484 MAP_OPTION( IPV6_V6ONLY
),
485 #ifdef IPV6_UNICAST_IF
486 MAP_OPTION( IPV6_UNICAST_IF
),
490 static const int ws_af_map
[][2] =
492 MAP_OPTION( AF_UNSPEC
),
493 MAP_OPTION( AF_INET
),
494 MAP_OPTION( AF_INET6
),
496 MAP_OPTION( AF_IPX
),
499 MAP_OPTION( AF_IRDA
),
501 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
504 static const int ws_socktype_map
[][2] =
506 MAP_OPTION( SOCK_DGRAM
),
507 MAP_OPTION( SOCK_STREAM
),
508 MAP_OPTION( SOCK_RAW
),
509 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
512 static const int ws_proto_map
[][2] =
514 MAP_OPTION( IPPROTO_IP
),
515 MAP_OPTION( IPPROTO_TCP
),
516 MAP_OPTION( IPPROTO_UDP
),
517 MAP_OPTION( IPPROTO_ICMP
),
518 MAP_OPTION( IPPROTO_IGMP
),
519 MAP_OPTION( IPPROTO_RAW
),
520 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
523 static const int ws_aiflag_map
[][2] =
525 MAP_OPTION( AI_PASSIVE
),
526 MAP_OPTION( AI_CANONNAME
),
527 MAP_OPTION( AI_NUMERICHOST
),
528 #ifdef AI_NUMERICSERV
529 MAP_OPTION( AI_NUMERICSERV
),
531 MAP_OPTION( AI_V4MAPPED
),
532 MAP_OPTION( AI_ADDRCONFIG
),
535 static const int ws_niflag_map
[][2] =
537 MAP_OPTION( NI_NOFQDN
),
538 MAP_OPTION( NI_NUMERICHOST
),
539 MAP_OPTION( NI_NAMEREQD
),
540 MAP_OPTION( NI_NUMERICSERV
),
541 MAP_OPTION( NI_DGRAM
),
544 static const int ws_eai_map
[][2] =
546 MAP_OPTION( EAI_AGAIN
),
547 MAP_OPTION( EAI_BADFLAGS
),
548 MAP_OPTION( EAI_FAIL
),
549 MAP_OPTION( EAI_FAMILY
),
550 MAP_OPTION( EAI_MEMORY
),
551 /* Note: EAI_NODATA is deprecated, but still
552 * used by Windows and Linux... We map the newer
553 * EAI_NONAME to EAI_NODATA for now until Windows
557 MAP_OPTION( EAI_NODATA
),
560 { WS_EAI_NODATA
, EAI_NONAME
},
563 MAP_OPTION( EAI_SERVICE
),
564 MAP_OPTION( EAI_SOCKTYPE
),
568 static const char magic_loopback_addr
[] = {127, 12, 34, 56};
570 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
571 static inline WSACMSGHDR
*fill_control_message(int level
, int type
, WSACMSGHDR
*current
, ULONG
*maxsize
, void *data
, int len
)
573 ULONG msgsize
= sizeof(WSACMSGHDR
) + WSA_CMSG_ALIGN(len
);
574 char *ptr
= (char *) current
+ sizeof(WSACMSGHDR
);
576 /* Make sure there is at least enough room for this entry */
577 if (msgsize
> *maxsize
)
580 /* Fill in the entry */
581 current
->cmsg_len
= sizeof(WSACMSGHDR
) + len
;
582 current
->cmsg_level
= level
;
583 current
->cmsg_type
= type
;
584 memcpy(ptr
, data
, len
);
585 /* Return the pointer to where next entry should go */
586 return (WSACMSGHDR
*) (ptr
+ WSA_CMSG_ALIGN(len
));
589 static inline int convert_control_headers(struct msghdr
*hdr
, WSABUF
*control
)
592 WSACMSGHDR
*cmsg_win
= (WSACMSGHDR
*) control
->buf
, *ptr
;
593 ULONG ctlsize
= control
->len
;
594 struct cmsghdr
*cmsg_unix
;
597 /* Loop over all the headers, converting as appropriate */
598 for (cmsg_unix
= CMSG_FIRSTHDR(hdr
); cmsg_unix
!= NULL
; cmsg_unix
= CMSG_NXTHDR(hdr
, cmsg_unix
))
600 switch(cmsg_unix
->cmsg_level
)
603 switch(cmsg_unix
->cmsg_type
)
607 /* Convert the Unix IP_PKTINFO structure to the Windows version */
608 struct in_pktinfo
*data_unix
= (struct in_pktinfo
*) CMSG_DATA(cmsg_unix
);
609 struct WS_in_pktinfo data_win
;
611 memcpy(&data_win
.ipi_addr
,&data_unix
->ipi_addr
.s_addr
,4); /* 4 bytes = 32 address bits */
612 data_win
.ipi_ifindex
= data_unix
->ipi_ifindex
;
613 ptr
= fill_control_message(WS_IPPROTO_IP
, WS_IP_PKTINFO
, ptr
, &ctlsize
,
614 (void*)&data_win
, sizeof(data_win
));
615 if (!ptr
) goto error
;
618 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix
->cmsg_type
);
623 FIXME("Unhandled message header level %d\n", cmsg_unix
->cmsg_level
);
629 /* Set the length of the returned control headers */
630 control
->len
= (ptr
== NULL
? 0 : (char*)ptr
- (char*)cmsg_win
);
631 return (ptr
!= NULL
);
632 #else /* IP_PKTINFO */
635 #endif /* IP_PKTINFO */
637 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
639 /* ----------------------------------- error handling */
641 static NTSTATUS
sock_get_ntstatus( int err
)
645 case EBADF
: return STATUS_INVALID_HANDLE
;
646 case EBUSY
: return STATUS_DEVICE_BUSY
;
648 case EACCES
: return STATUS_ACCESS_DENIED
;
649 case EFAULT
: return STATUS_NO_MEMORY
;
650 case EINVAL
: return STATUS_INVALID_PARAMETER
;
652 case EMFILE
: return STATUS_TOO_MANY_OPENED_FILES
;
653 case EWOULDBLOCK
: return STATUS_CANT_WAIT
;
654 case EINPROGRESS
: return STATUS_PENDING
;
655 case EALREADY
: return STATUS_NETWORK_BUSY
;
656 case ENOTSOCK
: return STATUS_OBJECT_TYPE_MISMATCH
;
657 case EDESTADDRREQ
: return STATUS_INVALID_PARAMETER
;
658 case EMSGSIZE
: return STATUS_BUFFER_OVERFLOW
;
659 case EPROTONOSUPPORT
:
660 case ESOCKTNOSUPPORT
:
663 case EPROTOTYPE
: return STATUS_NOT_SUPPORTED
;
664 case ENOPROTOOPT
: return STATUS_INVALID_PARAMETER
;
665 case EOPNOTSUPP
: return STATUS_NOT_SUPPORTED
;
666 case EADDRINUSE
: return STATUS_ADDRESS_ALREADY_ASSOCIATED
;
667 case EADDRNOTAVAIL
: return STATUS_INVALID_PARAMETER
;
668 case ECONNREFUSED
: return STATUS_CONNECTION_REFUSED
;
669 case ESHUTDOWN
: return STATUS_PIPE_DISCONNECTED
;
670 case ENOTCONN
: return STATUS_CONNECTION_DISCONNECTED
;
671 case ETIMEDOUT
: return STATUS_IO_TIMEOUT
;
672 case ENETUNREACH
: return STATUS_NETWORK_UNREACHABLE
;
673 case ENETDOWN
: return STATUS_NETWORK_BUSY
;
675 case ECONNRESET
: return STATUS_CONNECTION_RESET
;
676 case ECONNABORTED
: return STATUS_CONNECTION_ABORTED
;
678 case 0: return STATUS_SUCCESS
;
680 WARN("Unknown errno %d!\n", err
);
681 return STATUS_UNSUCCESSFUL
;
685 static UINT
sock_get_error( int err
)
689 case EINTR
: return WSAEINTR
;
690 case EBADF
: return WSAEBADF
;
692 case EACCES
: return WSAEACCES
;
693 case EFAULT
: return WSAEFAULT
;
694 case EINVAL
: return WSAEINVAL
;
695 case EMFILE
: return WSAEMFILE
;
696 case EWOULDBLOCK
: return WSAEWOULDBLOCK
;
697 case EINPROGRESS
: return WSAEINPROGRESS
;
698 case EALREADY
: return WSAEALREADY
;
699 case ENOTSOCK
: return WSAENOTSOCK
;
700 case EDESTADDRREQ
: return WSAEDESTADDRREQ
;
701 case EMSGSIZE
: return WSAEMSGSIZE
;
702 case EPROTOTYPE
: return WSAEPROTOTYPE
;
703 case ENOPROTOOPT
: return WSAENOPROTOOPT
;
704 case EPROTONOSUPPORT
: return WSAEPROTONOSUPPORT
;
705 case ESOCKTNOSUPPORT
: return WSAESOCKTNOSUPPORT
;
706 case EOPNOTSUPP
: return WSAEOPNOTSUPP
;
707 case EPFNOSUPPORT
: return WSAEPFNOSUPPORT
;
708 case EAFNOSUPPORT
: return WSAEAFNOSUPPORT
;
709 case EADDRINUSE
: return WSAEADDRINUSE
;
710 case EADDRNOTAVAIL
: return WSAEADDRNOTAVAIL
;
711 case ENETDOWN
: return WSAENETDOWN
;
712 case ENETUNREACH
: return WSAENETUNREACH
;
713 case ENETRESET
: return WSAENETRESET
;
714 case ECONNABORTED
: return WSAECONNABORTED
;
716 case ECONNRESET
: return WSAECONNRESET
;
717 case ENOBUFS
: return WSAENOBUFS
;
718 case EISCONN
: return WSAEISCONN
;
719 case ENOTCONN
: return WSAENOTCONN
;
720 case ESHUTDOWN
: return WSAESHUTDOWN
;
721 case ETOOMANYREFS
: return WSAETOOMANYREFS
;
722 case ETIMEDOUT
: return WSAETIMEDOUT
;
723 case ECONNREFUSED
: return WSAECONNREFUSED
;
724 case ELOOP
: return WSAELOOP
;
725 case ENAMETOOLONG
: return WSAENAMETOOLONG
;
726 case EHOSTDOWN
: return WSAEHOSTDOWN
;
727 case EHOSTUNREACH
: return WSAEHOSTUNREACH
;
728 case ENOTEMPTY
: return WSAENOTEMPTY
;
730 case EPROCLIM
: return WSAEPROCLIM
;
733 case EUSERS
: return WSAEUSERS
;
736 case EDQUOT
: return WSAEDQUOT
;
739 case ESTALE
: return WSAESTALE
;
742 case EREMOTE
: return WSAEREMOTE
;
745 /* just in case we ever get here and there are no problems */
748 WARN("Unknown errno %d!\n", err
);
749 return WSAEOPNOTSUPP
;
753 static UINT
wsaErrno(void)
755 int loc_errno
= errno
;
756 WARN("errno %d, (%s).\n", loc_errno
, strerror(loc_errno
));
758 return sock_get_error( loc_errno
);
761 /* most ws2 overlapped functions return an ntstatus-based error code */
762 static NTSTATUS
wsaErrStatus(void)
764 int loc_errno
= errno
;
765 WARN("errno %d, (%s).\n", loc_errno
, strerror(loc_errno
));
767 return sock_get_ntstatus(loc_errno
);
770 static UINT
wsaHerrno(int loc_errno
)
772 WARN("h_errno %d.\n", loc_errno
);
776 case HOST_NOT_FOUND
: return WSAHOST_NOT_FOUND
;
777 case TRY_AGAIN
: return WSATRY_AGAIN
;
778 case NO_RECOVERY
: return WSANO_RECOVERY
;
779 case NO_DATA
: return WSANO_DATA
;
780 case ENOBUFS
: return WSAENOBUFS
;
784 WARN("Unknown h_errno %d!\n", loc_errno
);
785 return WSAEOPNOTSUPP
;
789 static inline DWORD
NtStatusToWSAError( const DWORD status
)
791 /* We only need to cover the status codes set by server async request handling */
795 case STATUS_SUCCESS
: wserr
= 0; break;
796 case STATUS_PENDING
: wserr
= WSA_IO_PENDING
; break;
797 case STATUS_OBJECT_TYPE_MISMATCH
: wserr
= WSAENOTSOCK
; break;
798 case STATUS_INVALID_HANDLE
: wserr
= WSAEBADF
; break;
799 case STATUS_INVALID_PARAMETER
: wserr
= WSAEINVAL
; break;
800 case STATUS_PIPE_DISCONNECTED
: wserr
= WSAESHUTDOWN
; break;
801 case STATUS_NETWORK_BUSY
: wserr
= WSAEALREADY
; break;
802 case STATUS_NETWORK_UNREACHABLE
: wserr
= WSAENETUNREACH
; break;
803 case STATUS_CONNECTION_REFUSED
: wserr
= WSAECONNREFUSED
; break;
804 case STATUS_CONNECTION_DISCONNECTED
: wserr
= WSAENOTCONN
; break;
805 case STATUS_CONNECTION_RESET
: wserr
= WSAECONNRESET
; break;
806 case STATUS_CONNECTION_ABORTED
: wserr
= WSAECONNABORTED
; break;
807 case STATUS_CANCELLED
: wserr
= WSA_OPERATION_ABORTED
; break;
808 case STATUS_ADDRESS_ALREADY_ASSOCIATED
: wserr
= WSAEADDRINUSE
; break;
809 case STATUS_IO_TIMEOUT
:
810 case STATUS_TIMEOUT
: wserr
= WSAETIMEDOUT
; break;
811 case STATUS_NO_MEMORY
: wserr
= WSAEFAULT
; break;
812 case STATUS_ACCESS_DENIED
: wserr
= WSAEACCES
; break;
813 case STATUS_TOO_MANY_OPENED_FILES
: wserr
= WSAEMFILE
; break;
814 case STATUS_CANT_WAIT
: wserr
= WSAEWOULDBLOCK
; break;
815 case STATUS_BUFFER_OVERFLOW
: wserr
= WSAEMSGSIZE
; break;
816 case STATUS_NOT_SUPPORTED
: wserr
= WSAEOPNOTSUPP
; break;
817 case STATUS_HOST_UNREACHABLE
: wserr
= WSAEHOSTUNREACH
; break;
820 wserr
= RtlNtStatusToDosError( status
);
821 FIXME( "Status code %08x converted to DOS error code %x\n", status
, wserr
);
826 /* set last error code from NT status without mapping WSA errors */
827 static inline unsigned int set_error( unsigned int err
)
831 err
= NtStatusToWSAError( err
);
837 static inline int get_sock_fd( SOCKET s
, DWORD access
, unsigned int *options
)
840 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s
), access
, &fd
, options
) ))
845 static inline void release_sock_fd( SOCKET s
, int fd
)
847 wine_server_release_fd( SOCKET2HANDLE(s
), fd
);
850 static void _enable_event( HANDLE s
, unsigned int event
,
851 unsigned int sstate
, unsigned int cstate
)
853 SERVER_START_REQ( enable_socket_event
)
855 req
->handle
= wine_server_obj_handle( s
);
857 req
->sstate
= sstate
;
858 req
->cstate
= cstate
;
859 wine_server_call( req
);
864 static NTSTATUS
_is_blocking(SOCKET s
, BOOL
*ret
)
867 SERVER_START_REQ( get_socket_event
)
869 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
870 req
->service
= FALSE
;
872 status
= wine_server_call( req
);
873 *ret
= (reply
->state
& FD_WINE_NONBLOCKING
) == 0;
879 static unsigned int _get_sock_mask(SOCKET s
)
882 SERVER_START_REQ( get_socket_event
)
884 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
885 req
->service
= FALSE
;
887 wine_server_call( req
);
894 static void _sync_sock_state(SOCKET s
)
897 /* do a dummy wineserver request in order to let
898 the wineserver run through its select loop once */
899 (void)_is_blocking(s
, &dummy
);
902 static int _get_sock_error(SOCKET s
, unsigned int bit
)
904 int events
[FD_MAX_EVENTS
];
906 SERVER_START_REQ( get_socket_event
)
908 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
909 req
->service
= FALSE
;
911 wine_server_set_reply( req
, events
, sizeof(events
) );
912 wine_server_call( req
);
918 static struct per_thread_data
*get_per_thread_data(void)
920 struct per_thread_data
* ptb
= NtCurrentTeb()->WinSockData
;
921 /* lazy initialization */
924 ptb
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(*ptb
) );
925 NtCurrentTeb()->WinSockData
= ptb
;
930 static void free_per_thread_data(void)
932 struct per_thread_data
* ptb
= NtCurrentTeb()->WinSockData
;
936 /* delete scratch buffers */
937 HeapFree( GetProcessHeap(), 0, ptb
->he_buffer
);
938 HeapFree( GetProcessHeap(), 0, ptb
->se_buffer
);
939 HeapFree( GetProcessHeap(), 0, ptb
->pe_buffer
);
940 ptb
->he_buffer
= NULL
;
941 ptb
->se_buffer
= NULL
;
942 ptb
->pe_buffer
= NULL
;
944 HeapFree( GetProcessHeap(), 0, ptb
);
945 NtCurrentTeb()->WinSockData
= NULL
;
948 /***********************************************************************
949 * DllMain (WS2_32.init)
951 BOOL WINAPI
DllMain(HINSTANCE hInstDLL
, DWORD fdwReason
, LPVOID fImpLoad
)
953 TRACE("%p 0x%x %p\n", hInstDLL
, fdwReason
, fImpLoad
);
955 case DLL_PROCESS_ATTACH
:
957 case DLL_PROCESS_DETACH
:
959 free_per_thread_data();
960 DeleteCriticalSection(&csWSgetXXXbyYYY
);
962 case DLL_THREAD_DETACH
:
963 free_per_thread_data();
969 /***********************************************************************
972 * Converts socket flags from Windows format.
973 * Return 1 if converted, 0 if not (error).
975 static int convert_sockopt(INT
*level
, INT
*optname
)
982 for(i
=0; i
<sizeof(ws_sock_map
)/sizeof(ws_sock_map
[0]); i
++) {
983 if( ws_sock_map
[i
][0] == *optname
)
985 *optname
= ws_sock_map
[i
][1];
989 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname
);
992 *level
= IPPROTO_TCP
;
993 for(i
=0; i
<sizeof(ws_tcp_map
)/sizeof(ws_tcp_map
[0]); i
++) {
994 if ( ws_tcp_map
[i
][0] == *optname
)
996 *optname
= ws_tcp_map
[i
][1];
1000 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname
);
1003 *level
= IPPROTO_IP
;
1004 for(i
=0; i
<sizeof(ws_ip_map
)/sizeof(ws_ip_map
[0]); i
++) {
1005 if (ws_ip_map
[i
][0] == *optname
)
1007 *optname
= ws_ip_map
[i
][1];
1011 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname
);
1013 case WS_IPPROTO_IPV6
:
1014 *level
= IPPROTO_IPV6
;
1015 for(i
=0; i
<sizeof(ws_ipv6_map
)/sizeof(ws_ipv6_map
[0]); i
++) {
1016 if (ws_ipv6_map
[i
][0] == *optname
)
1018 *optname
= ws_ipv6_map
[i
][1];
1022 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname
);
1024 default: FIXME("Unimplemented or unknown socket level\n");
1029 /* ----------------------------------- Per-thread info (or per-process?) */
1031 static char *strdup_lower(const char *str
)
1034 char *ret
= HeapAlloc( GetProcessHeap(), 0, strlen(str
) + 1 );
1038 for (i
= 0; str
[i
]; i
++) ret
[i
] = tolower(str
[i
]);
1041 else SetLastError(WSAENOBUFS
);
1045 static inline int sock_error_p(int s
)
1047 unsigned int optval
;
1048 socklen_t optlen
= sizeof(optval
);
1049 getsockopt(s
, SOL_SOCKET
, SO_ERROR
, (void *) &optval
, &optlen
);
1050 if (optval
) WARN("\t[%i] error: %d\n", s
, optval
);
1054 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1055 * from an fd and return the value converted to milli seconds
1056 * or -1 if there is an infinite time out */
1057 static inline int get_rcvsnd_timeo( int fd
, int optname
)
1060 socklen_t len
= sizeof(tv
);
1061 int ret
= getsockopt(fd
, SOL_SOCKET
, optname
, &tv
, &len
);
1063 ret
= tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000;
1064 if( ret
<= 0 ) /* tv == {0,0} means infinite time out */
1069 /* macro wrappers for portability */
1071 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
1073 #define GET_RCVTIMEO(fd) (-1)
1077 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
1079 #define GET_SNDTIMEO(fd) (-1)
1082 /* utility: given an fd, will block until one of the events occurs */
1083 static inline int do_block( int fd
, int events
, int timeout
)
1089 pfd
.events
= events
;
1091 while ((ret
= poll(&pfd
, 1, timeout
)) < 0)
1102 convert_af_w2u(int windowsaf
) {
1105 for (i
=0;i
<sizeof(ws_af_map
)/sizeof(ws_af_map
[0]);i
++)
1106 if (ws_af_map
[i
][0] == windowsaf
)
1107 return ws_af_map
[i
][1];
1108 FIXME("unhandled Windows address family %d\n", windowsaf
);
1113 convert_af_u2w(int unixaf
) {
1116 for (i
=0;i
<sizeof(ws_af_map
)/sizeof(ws_af_map
[0]);i
++)
1117 if (ws_af_map
[i
][1] == unixaf
)
1118 return ws_af_map
[i
][0];
1119 FIXME("unhandled UNIX address family %d\n", unixaf
);
1124 convert_proto_w2u(int windowsproto
) {
1127 for (i
=0;i
<sizeof(ws_proto_map
)/sizeof(ws_proto_map
[0]);i
++)
1128 if (ws_proto_map
[i
][0] == windowsproto
)
1129 return ws_proto_map
[i
][1];
1131 /* check for extended IPX */
1132 if (IS_IPX_PROTO(windowsproto
))
1133 return windowsproto
;
1135 FIXME("unhandled Windows socket protocol %d\n", windowsproto
);
1140 convert_proto_u2w(int unixproto
) {
1143 for (i
=0;i
<sizeof(ws_proto_map
)/sizeof(ws_proto_map
[0]);i
++)
1144 if (ws_proto_map
[i
][1] == unixproto
)
1145 return ws_proto_map
[i
][0];
1147 /* if value is inside IPX range just return it - the kernel simply
1148 * echoes the value used in the socket() function */
1149 if (IS_IPX_PROTO(unixproto
))
1152 FIXME("unhandled UNIX socket protocol %d\n", unixproto
);
1157 convert_socktype_w2u(int windowssocktype
) {
1160 for (i
=0;i
<sizeof(ws_socktype_map
)/sizeof(ws_socktype_map
[0]);i
++)
1161 if (ws_socktype_map
[i
][0] == windowssocktype
)
1162 return ws_socktype_map
[i
][1];
1163 FIXME("unhandled Windows socket type %d\n", windowssocktype
);
1168 convert_socktype_u2w(int unixsocktype
) {
1171 for (i
=0;i
<sizeof(ws_socktype_map
)/sizeof(ws_socktype_map
[0]);i
++)
1172 if (ws_socktype_map
[i
][1] == unixsocktype
)
1173 return ws_socktype_map
[i
][0];
1174 FIXME("unhandled UNIX socket type %d\n", unixsocktype
);
1178 static int set_ipx_packettype(int sock
, int ptype
)
1181 int fd
= get_sock_fd( sock
, 0, NULL
), ret
= 0;
1182 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype
, fd
);
1184 if (fd
== -1) return SOCKET_ERROR
;
1186 /* We try to set the ipx type on ipx socket level. */
1188 if(setsockopt(fd
, SOL_IPX
, IPX_TYPE
, &ptype
, sizeof(ptype
)) == -1)
1190 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1196 /* Should we retrieve val using a getsockopt call and then
1197 * set the modified one? */
1199 setsockopt(fd
, 0, SO_DEFAULT_HEADERS
, &val
, sizeof(struct ipx
));
1202 release_sock_fd( sock
, fd
);
1205 WARN("IPX support is not enabled, can't set packet type\n");
1206 return SOCKET_ERROR
;
1210 /* ----------------------------------- API -----
1212 * Init / cleanup / error checking.
1215 /***********************************************************************
1216 * WSAStartup (WS2_32.115)
1218 int WINAPI
WSAStartup(WORD wVersionRequested
, LPWSADATA lpWSAData
)
1220 TRACE("verReq=%x\n", wVersionRequested
);
1222 if (LOBYTE(wVersionRequested
) < 1)
1223 return WSAVERNOTSUPPORTED
;
1225 if (!lpWSAData
) return WSAEINVAL
;
1229 /* that's the whole of the negotiation for now */
1230 lpWSAData
->wVersion
= wVersionRequested
;
1231 /* return winsock information */
1232 lpWSAData
->wHighVersion
= 0x0202;
1233 strcpy(lpWSAData
->szDescription
, "WinSock 2.0" );
1234 strcpy(lpWSAData
->szSystemStatus
, "Running" );
1235 lpWSAData
->iMaxSockets
= WS_MAX_SOCKETS_PER_PROCESS
;
1236 lpWSAData
->iMaxUdpDg
= WS_MAX_UDP_DATAGRAM
;
1237 /* don't do anything with lpWSAData->lpVendorInfo */
1238 /* (some apps don't allocate the space for this field) */
1240 TRACE("succeeded\n");
1245 /***********************************************************************
1246 * WSACleanup (WS2_32.116)
1248 INT WINAPI
WSACleanup(void)
1254 SetLastError(WSANOTINITIALISED
);
1255 return SOCKET_ERROR
;
1259 /***********************************************************************
1260 * WSAGetLastError (WS2_32.111)
1262 INT WINAPI
WSAGetLastError(void)
1264 return GetLastError();
1267 /***********************************************************************
1268 * WSASetLastError (WS2_32.112)
1270 void WINAPI
WSASetLastError(INT iError
) {
1271 SetLastError(iError
);
1274 static struct WS_hostent
*check_buffer_he(int size
)
1276 struct per_thread_data
* ptb
= get_per_thread_data();
1279 if (ptb
->he_len
>= size
) return ptb
->he_buffer
;
1280 HeapFree( GetProcessHeap(), 0, ptb
->he_buffer
);
1282 ptb
->he_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->he_len
= size
) );
1283 if (!ptb
->he_buffer
) SetLastError(WSAENOBUFS
);
1284 return ptb
->he_buffer
;
1287 static struct WS_servent
*check_buffer_se(int size
)
1289 struct per_thread_data
* ptb
= get_per_thread_data();
1292 if (ptb
->se_len
>= size
) return ptb
->se_buffer
;
1293 HeapFree( GetProcessHeap(), 0, ptb
->se_buffer
);
1295 ptb
->se_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->se_len
= size
) );
1296 if (!ptb
->se_buffer
) SetLastError(WSAENOBUFS
);
1297 return ptb
->se_buffer
;
1300 static struct WS_protoent
*check_buffer_pe(int size
)
1302 struct per_thread_data
* ptb
= get_per_thread_data();
1305 if (ptb
->pe_len
>= size
) return ptb
->pe_buffer
;
1306 HeapFree( GetProcessHeap(), 0, ptb
->pe_buffer
);
1308 ptb
->pe_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->pe_len
= size
) );
1309 if (!ptb
->pe_buffer
) SetLastError(WSAENOBUFS
);
1310 return ptb
->pe_buffer
;
1313 /* ----------------------------------- i/o APIs */
1315 static inline BOOL
supported_pf(int pf
)
1335 static inline BOOL
supported_protocol(int protocol
)
1338 for (i
= 0; i
< sizeof(valid_protocols
) / sizeof(valid_protocols
[0]); i
++)
1339 if (protocol
== valid_protocols
[i
])
1344 /**********************************************************************/
1346 /* Returns the length of the converted address if successful, 0 if it was too small to
1349 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr
* wsaddr
, int wsaddrlen
,
1350 union generic_unix_sockaddr
*uaddr
)
1352 unsigned int uaddrlen
= 0;
1354 switch (wsaddr
->sa_family
)
1359 const struct WS_sockaddr_ipx
* wsipx
=(const struct WS_sockaddr_ipx
*)wsaddr
;
1360 struct sockaddr_ipx
* uipx
= (struct sockaddr_ipx
*)uaddr
;
1362 if (wsaddrlen
<sizeof(struct WS_sockaddr_ipx
))
1365 uaddrlen
= sizeof(struct sockaddr_ipx
);
1366 memset( uaddr
, 0, uaddrlen
);
1367 uipx
->sipx_family
=AF_IPX
;
1368 uipx
->sipx_port
=wsipx
->sa_socket
;
1369 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1372 memcpy(&uipx
->sipx_network
,wsipx
->sa_netnum
,sizeof(uipx
->sipx_network
)+sizeof(uipx
->sipx_node
));
1373 #ifdef IPX_FRAME_NONE
1374 uipx
->sipx_type
=IPX_FRAME_NONE
;
1380 struct sockaddr_in6
* uin6
= (struct sockaddr_in6
*)uaddr
;
1381 const struct WS_sockaddr_in6
* win6
= (const struct WS_sockaddr_in6
*)wsaddr
;
1383 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1384 * scope_id, one without.
1386 if (wsaddrlen
>= sizeof(struct WS_sockaddr_in6_old
)) {
1387 uaddrlen
= sizeof(struct sockaddr_in6
);
1388 memset( uaddr
, 0, uaddrlen
);
1389 uin6
->sin6_family
= AF_INET6
;
1390 uin6
->sin6_port
= win6
->sin6_port
;
1391 uin6
->sin6_flowinfo
= win6
->sin6_flowinfo
;
1392 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1393 if (wsaddrlen
>= sizeof(struct WS_sockaddr_in6
)) uin6
->sin6_scope_id
= win6
->sin6_scope_id
;
1395 memcpy(&uin6
->sin6_addr
,&win6
->sin6_addr
,16); /* 16 bytes = 128 address bits */
1398 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen
);
1402 struct sockaddr_in
* uin
= (struct sockaddr_in
*)uaddr
;
1403 const struct WS_sockaddr_in
* win
= (const struct WS_sockaddr_in
*)wsaddr
;
1405 if (wsaddrlen
<sizeof(struct WS_sockaddr_in
))
1407 uaddrlen
= sizeof(struct sockaddr_in
);
1408 memset( uaddr
, 0, uaddrlen
);
1409 uin
->sin_family
= AF_INET
;
1410 uin
->sin_port
= win
->sin_port
;
1411 memcpy(&uin
->sin_addr
,&win
->sin_addr
,4); /* 4 bytes = 32 address bits */
1416 struct sockaddr_irda
*uin
= (struct sockaddr_irda
*)uaddr
;
1417 const SOCKADDR_IRDA
*win
= (const SOCKADDR_IRDA
*)wsaddr
;
1419 if (wsaddrlen
< sizeof(SOCKADDR_IRDA
))
1421 uaddrlen
= sizeof(struct sockaddr_irda
);
1422 memset( uaddr
, 0, uaddrlen
);
1423 uin
->sir_family
= AF_IRDA
;
1424 if (!strncmp( win
->irdaServiceName
, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1426 unsigned int lsap_sel
= 0;
1428 sscanf( win
->irdaServiceName
, "LSAP-SEL%u", &lsap_sel
);
1429 uin
->sir_lsap_sel
= lsap_sel
;
1433 uin
->sir_lsap_sel
= LSAP_ANY
;
1434 memcpy( uin
->sir_name
, win
->irdaServiceName
, 25 );
1436 memcpy( &uin
->sir_addr
, win
->irdaDeviceID
, sizeof(uin
->sir_addr
) );
1440 case WS_AF_UNSPEC
: {
1441 /* Try to determine the needed space by the passed windows sockaddr space */
1442 switch (wsaddrlen
) {
1443 default: /* likely an ipv4 address */
1444 case sizeof(struct WS_sockaddr_in
):
1445 uaddrlen
= sizeof(struct sockaddr_in
);
1448 case sizeof(struct WS_sockaddr_ipx
):
1449 uaddrlen
= sizeof(struct sockaddr_ipx
);
1453 case sizeof(SOCKADDR_IRDA
):
1454 uaddrlen
= sizeof(struct sockaddr_irda
);
1457 case sizeof(struct WS_sockaddr_in6
):
1458 case sizeof(struct WS_sockaddr_in6_old
):
1459 uaddrlen
= sizeof(struct sockaddr_in6
);
1462 memset( uaddr
, 0, uaddrlen
);
1466 FIXME("Unknown address family %d, return NULL.\n", wsaddr
->sa_family
);
1472 static BOOL
is_sockaddr_bound(const struct sockaddr
*uaddr
, int uaddrlen
)
1474 switch (uaddr
->sa_family
)
1479 static const struct sockaddr_ipx emptyAddr
;
1480 struct sockaddr_ipx
*ipx
= (struct sockaddr_ipx
*) uaddr
;
1481 return ipx
->sipx_port
1482 || memcmp(&ipx
->sipx_network
, &emptyAddr
.sipx_network
, sizeof(emptyAddr
.sipx_network
))
1483 || memcmp(&ipx
->sipx_node
, &emptyAddr
.sipx_node
, sizeof(emptyAddr
.sipx_node
));
1488 static const struct sockaddr_in6 emptyAddr
;
1489 const struct sockaddr_in6
*in6
= (const struct sockaddr_in6
*) uaddr
;
1490 return in6
->sin6_port
|| memcmp(&in6
->sin6_addr
, &emptyAddr
.sin6_addr
, sizeof(struct in6_addr
));
1494 static const struct sockaddr_in emptyAddr
;
1495 const struct sockaddr_in
*in
= (const struct sockaddr_in
*) uaddr
;
1496 return in
->sin_port
|| memcmp(&in
->sin_addr
, &emptyAddr
.sin_addr
, sizeof(struct in_addr
));
1501 FIXME("unknown address family %d\n", uaddr
->sa_family
);
1506 /* Returns 0 if successful, -1 if the buffer is too small */
1507 static int ws_sockaddr_u2ws(const struct sockaddr
* uaddr
, struct WS_sockaddr
* wsaddr
, int* wsaddrlen
)
1511 switch(uaddr
->sa_family
)
1516 const struct sockaddr_ipx
* uipx
=(const struct sockaddr_ipx
*)uaddr
;
1517 struct WS_sockaddr_ipx
* wsipx
=(struct WS_sockaddr_ipx
*)wsaddr
;
1520 switch (*wsaddrlen
) /* how much can we copy? */
1524 *wsaddrlen
= sizeof(*wsipx
);
1525 wsipx
->sa_socket
=uipx
->sipx_port
;
1529 memcpy(wsipx
->sa_nodenum
,uipx
->sipx_node
,sizeof(wsipx
->sa_nodenum
));
1537 memcpy(wsipx
->sa_netnum
,&uipx
->sipx_network
,sizeof(wsipx
->sa_netnum
));
1543 wsipx
->sa_family
=WS_AF_IPX
;
1555 const struct sockaddr_irda
*uin
= (const struct sockaddr_irda
*)uaddr
;
1556 SOCKADDR_IRDA
*win
= (SOCKADDR_IRDA
*)wsaddr
;
1558 if (*wsaddrlen
< sizeof(SOCKADDR_IRDA
))
1560 win
->irdaAddressFamily
= WS_AF_IRDA
;
1561 memcpy( win
->irdaDeviceID
, &uin
->sir_addr
, sizeof(win
->irdaDeviceID
) );
1562 if (uin
->sir_lsap_sel
!= LSAP_ANY
)
1563 sprintf( win
->irdaServiceName
, "LSAP-SEL%u", uin
->sir_lsap_sel
);
1565 memcpy( win
->irdaServiceName
, uin
->sir_name
,
1566 sizeof(win
->irdaServiceName
) );
1571 const struct sockaddr_in6
* uin6
= (const struct sockaddr_in6
*)uaddr
;
1572 struct WS_sockaddr_in6_old
* win6old
= (struct WS_sockaddr_in6_old
*)wsaddr
;
1574 if (*wsaddrlen
< sizeof(struct WS_sockaddr_in6_old
))
1576 win6old
->sin6_family
= WS_AF_INET6
;
1577 win6old
->sin6_port
= uin6
->sin6_port
;
1578 win6old
->sin6_flowinfo
= uin6
->sin6_flowinfo
;
1579 memcpy(&win6old
->sin6_addr
,&uin6
->sin6_addr
,16); /* 16 bytes = 128 address bits */
1580 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1581 if (*wsaddrlen
>= sizeof(struct WS_sockaddr_in6
)) {
1582 struct WS_sockaddr_in6
* win6
= (struct WS_sockaddr_in6
*)wsaddr
;
1583 win6
->sin6_scope_id
= uin6
->sin6_scope_id
;
1584 *wsaddrlen
= sizeof(struct WS_sockaddr_in6
);
1587 *wsaddrlen
= sizeof(struct WS_sockaddr_in6_old
);
1589 *wsaddrlen
= sizeof(struct WS_sockaddr_in6_old
);
1594 const struct sockaddr_in
* uin
= (const struct sockaddr_in
*)uaddr
;
1595 struct WS_sockaddr_in
* win
= (struct WS_sockaddr_in
*)wsaddr
;
1597 if (*wsaddrlen
< sizeof(struct WS_sockaddr_in
))
1599 win
->sin_family
= WS_AF_INET
;
1600 win
->sin_port
= uin
->sin_port
;
1601 memcpy(&win
->sin_addr
,&uin
->sin_addr
,4); /* 4 bytes = 32 address bits */
1602 memset(win
->sin_zero
, 0, 8); /* Make sure the null padding is null */
1603 *wsaddrlen
= sizeof(struct WS_sockaddr_in
);
1607 memset(wsaddr
,0,*wsaddrlen
);
1611 FIXME("Unknown address family %d\n", uaddr
->sa_family
);
1617 static INT
WS_DuplicateSocket(BOOL unicode
, SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOW lpProtocolInfo
)
1621 WSAPROTOCOL_INFOW infow
;
1623 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
1624 unicode
, s
, dwProcessId
, lpProtocolInfo
);
1626 if (!ws_protocol_info(s
, unicode
, &infow
, &size
))
1627 return SOCKET_ERROR
;
1629 if (!(hProcess
= OpenProcess(PROCESS_DUP_HANDLE
, FALSE
, dwProcessId
)))
1631 SetLastError(WSAEINVAL
);
1632 return SOCKET_ERROR
;
1635 if (!lpProtocolInfo
)
1637 CloseHandle(hProcess
);
1638 SetLastError(WSAEFAULT
);
1639 return SOCKET_ERROR
;
1642 /* I don't know what the real Windoze does next, this is a hack */
1643 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
1644 * the target use the global duplicate, or we could copy a reference to us to the structure
1645 * and let the target duplicate it from us, but let's do it as simple as possible */
1646 memcpy(lpProtocolInfo
, &infow
, size
);
1647 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s
),
1648 hProcess
, (LPHANDLE
)&lpProtocolInfo
->dwServiceFlags3
,
1649 0, FALSE
, DUPLICATE_SAME_ACCESS
);
1650 CloseHandle(hProcess
);
1651 lpProtocolInfo
->dwServiceFlags4
= 0xff00ff00; /* magic */
1655 /*****************************************************************************
1656 * WS_EnterSingleProtocolW [internal]
1658 * enters the protocol information of one given protocol into the given
1662 * TRUE if a protocol was entered into the buffer.
1665 * - only implemented for IPX, SPX, SPXII, TCP, UDP
1666 * - there is no check that the operating system supports the returned
1669 static BOOL
WS_EnterSingleProtocolW( INT protocol
, WSAPROTOCOL_INFOW
* info
)
1671 memset( info
, 0, sizeof(WSAPROTOCOL_INFOW
) );
1672 info
->iProtocol
= protocol
;
1676 case WS_IPPROTO_TCP
:
1677 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_EXPEDITED_DATA
|
1678 XP1_GRACEFUL_CLOSE
| XP1_GUARANTEED_ORDER
|
1679 XP1_GUARANTEED_DELIVERY
;
1680 info
->ProviderId
= ProviderIdIP
;
1681 info
->dwCatalogEntryId
= 0x3e9;
1682 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1683 info
->ProtocolChain
.ChainLen
= 1;
1685 info
->iAddressFamily
= WS_AF_INET
;
1686 info
->iMaxSockAddr
= 0x10;
1687 info
->iMinSockAddr
= 0x10;
1688 info
->iSocketType
= WS_SOCK_STREAM
;
1689 strcpyW( info
->szProtocol
, NameTcpW
);
1692 case WS_IPPROTO_UDP
:
1693 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_SUPPORT_BROADCAST
|
1694 XP1_SUPPORT_MULTIPOINT
| XP1_MESSAGE_ORIENTED
|
1696 info
->ProviderId
= ProviderIdIP
;
1697 info
->dwCatalogEntryId
= 0x3ea;
1698 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1699 info
->ProtocolChain
.ChainLen
= 1;
1701 info
->iAddressFamily
= WS_AF_INET
;
1702 info
->iMaxSockAddr
= 0x10;
1703 info
->iMinSockAddr
= 0x10;
1704 info
->iSocketType
= WS_SOCK_DGRAM
;
1705 info
->dwMessageSize
= 0xffbb;
1706 strcpyW( info
->szProtocol
, NameUdpW
);
1709 case WS_NSPROTO_IPX
:
1710 info
->dwServiceFlags1
= XP1_PARTIAL_MESSAGE
| XP1_SUPPORT_BROADCAST
|
1711 XP1_SUPPORT_MULTIPOINT
| XP1_MESSAGE_ORIENTED
|
1713 info
->ProviderId
= ProviderIdIPX
;
1714 info
->dwCatalogEntryId
= 0x406;
1715 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1716 info
->ProtocolChain
.ChainLen
= 1;
1718 info
->iAddressFamily
= WS_AF_IPX
;
1719 info
->iMaxSockAddr
= 0x10;
1720 info
->iMinSockAddr
= 0x0e;
1721 info
->iSocketType
= WS_SOCK_DGRAM
;
1722 info
->iProtocolMaxOffset
= 0xff;
1723 info
->dwMessageSize
= 0x240;
1724 strcpyW( info
->szProtocol
, NameIpxW
);
1727 case WS_NSPROTO_SPX
:
1728 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_PSEUDO_STREAM
|
1729 XP1_MESSAGE_ORIENTED
| XP1_GUARANTEED_ORDER
|
1730 XP1_GUARANTEED_DELIVERY
;
1731 info
->ProviderId
= ProviderIdSPX
;
1732 info
->dwCatalogEntryId
= 0x407;
1733 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1734 info
->ProtocolChain
.ChainLen
= 1;
1736 info
->iAddressFamily
= WS_AF_IPX
;
1737 info
->iMaxSockAddr
= 0x10;
1738 info
->iMinSockAddr
= 0x0e;
1739 info
->iSocketType
= WS_SOCK_SEQPACKET
;
1740 info
->dwMessageSize
= 0xffffffff;
1741 strcpyW( info
->szProtocol
, NameSpxW
);
1744 case WS_NSPROTO_SPXII
:
1745 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_GRACEFUL_CLOSE
|
1746 XP1_PSEUDO_STREAM
| XP1_MESSAGE_ORIENTED
|
1747 XP1_GUARANTEED_ORDER
| XP1_GUARANTEED_DELIVERY
;
1748 info
->ProviderId
= ProviderIdSPX
;
1749 info
->dwCatalogEntryId
= 0x409;
1750 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1751 info
->ProtocolChain
.ChainLen
= 1;
1753 info
->iAddressFamily
= WS_AF_IPX
;
1754 info
->iMaxSockAddr
= 0x10;
1755 info
->iMinSockAddr
= 0x0e;
1756 info
->iSocketType
= WS_SOCK_SEQPACKET
;
1757 info
->dwMessageSize
= 0xffffffff;
1758 strcpyW( info
->szProtocol
, NameSpxIIW
);
1762 FIXME("unknown Protocol <0x%08x>\n", protocol
);
1768 /*****************************************************************************
1769 * WS_EnterSingleProtocolA [internal]
1771 * see function WS_EnterSingleProtocolW
1774 static BOOL
WS_EnterSingleProtocolA( INT protocol
, WSAPROTOCOL_INFOA
* info
)
1776 WSAPROTOCOL_INFOW infow
;
1778 memset( info
, 0, sizeof(WSAPROTOCOL_INFOA
) );
1780 ret
= WS_EnterSingleProtocolW( protocol
, &infow
);
1783 /* convert the structure from W to A */
1784 memcpy( info
, &infow
, FIELD_OFFSET( WSAPROTOCOL_INFOA
, szProtocol
) );
1785 WideCharToMultiByte( CP_ACP
, 0, infow
.szProtocol
, -1,
1786 info
->szProtocol
, WSAPROTOCOL_LEN
+1, NULL
, NULL
);
1792 static INT
WS_EnumProtocols( BOOL unicode
, const INT
*protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
)
1794 INT i
= 0, items
= 0;
1798 LPWSAPROTOCOL_INFOA a
;
1799 LPWSAPROTOCOL_INFOW w
;
1803 if (!protocols
) protocols
= valid_protocols
;
1805 while (protocols
[i
])
1807 if(supported_protocol(protocols
[i
++]))
1811 size
= items
* (unicode
? sizeof(WSAPROTOCOL_INFOW
) : sizeof(WSAPROTOCOL_INFOA
));
1813 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
1814 unicode
, protocols
, buffer
, len
, len
? *len
: 0, items
, size
);
1816 if (*len
< size
|| !buffer
)
1819 WSASetLastError(WSAENOBUFS
);
1820 return SOCKET_ERROR
;
1823 for (i
= items
= 0; protocols
[i
]; i
++)
1827 if (WS_EnterSingleProtocolW( protocols
[i
], &info
.w
[items
] ))
1832 if (WS_EnterSingleProtocolA( protocols
[i
], &info
.a
[items
] ))
1839 static BOOL
ws_protocol_info(SOCKET s
, int unicode
, WSAPROTOCOL_INFOW
*buffer
, int *size
)
1843 *size
= unicode
? sizeof(WSAPROTOCOL_INFOW
) : sizeof(WSAPROTOCOL_INFOA
);
1844 memset(buffer
, 0, *size
);
1846 SERVER_START_REQ( get_socket_info
)
1848 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1849 status
= wine_server_call( req
);
1852 buffer
->iAddressFamily
= convert_af_u2w(reply
->family
);
1853 buffer
->iSocketType
= convert_socktype_u2w(reply
->type
);
1854 buffer
->iProtocol
= convert_proto_u2w(reply
->protocol
);
1861 unsigned int err
= NtStatusToWSAError( status
);
1862 SetLastError( err
== WSAEBADF
? WSAENOTSOCK
: err
);
1867 WS_EnterSingleProtocolW( buffer
->iProtocol
, buffer
);
1869 WS_EnterSingleProtocolA( buffer
->iProtocol
, (WSAPROTOCOL_INFOA
*)buffer
);
1874 /**************************************************************************
1875 * Functions for handling overlapped I/O
1876 **************************************************************************/
1878 /* user APC called upon async completion */
1879 static void WINAPI
ws2_async_apc( void *arg
, IO_STATUS_BLOCK
*iosb
, ULONG reserved
)
1881 ws2_async
*wsa
= arg
;
1883 if (wsa
->completion_func
) wsa
->completion_func( NtStatusToWSAError(iosb
->u
.Status
),
1884 iosb
->Information
, wsa
->user_overlapped
,
1886 HeapFree( GetProcessHeap(), 0, wsa
);
1889 /***********************************************************************
1890 * WS2_recv (INTERNAL)
1892 * Workhorse for both synchronous and asynchronous recv() operations.
1894 static int WS2_recv( int fd
, struct ws2_async
*wsa
)
1896 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1900 union generic_unix_sockaddr unix_sockaddr
;
1903 hdr
.msg_name
= NULL
;
1907 hdr
.msg_namelen
= sizeof(unix_sockaddr
);
1908 hdr
.msg_name
= &unix_sockaddr
;
1911 hdr
.msg_namelen
= 0;
1913 hdr
.msg_iov
= wsa
->iovec
+ wsa
->first_iovec
;
1914 hdr
.msg_iovlen
= wsa
->n_iovecs
- wsa
->first_iovec
;
1915 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1916 hdr
.msg_accrights
= NULL
;
1917 hdr
.msg_accrightslen
= 0;
1919 hdr
.msg_control
= pktbuf
;
1920 hdr
.msg_controllen
= sizeof(pktbuf
);
1924 if ( (n
= recvmsg(fd
, &hdr
, wsa
->flags
)) == -1 )
1927 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1930 ERR("Message control headers cannot be properly supported on this system.\n");
1931 wsa
->control
->len
= 0;
1934 if (wsa
->control
&& !convert_control_headers(&hdr
, wsa
->control
))
1936 WARN("Application passed insufficient room for control headers.\n");
1937 *wsa
->lpFlags
|= WS_MSG_CTRUNC
;
1943 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1944 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1946 * quoting linux 2.6 net/ipv4/tcp.c:
1947 * "According to UNIX98, msg_name/msg_namelen are ignored
1948 * on connected socket. I was just happy when found this 8) --ANK"
1950 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1951 * connection-oriented sockets, so don't try to update lpFrom.
1953 if (wsa
->addr
&& hdr
.msg_namelen
)
1954 ws_sockaddr_u2ws( &unix_sockaddr
.addr
, wsa
->addr
, wsa
->addrlen
.ptr
);
1959 /***********************************************************************
1960 * WS2_async_recv (INTERNAL)
1962 * Handler for overlapped recv() operations.
1964 static NTSTATUS
WS2_async_recv( void* user
, IO_STATUS_BLOCK
* iosb
, NTSTATUS status
, void **apc
)
1966 ws2_async
* wsa
= user
;
1971 case STATUS_ALERTED
:
1972 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, FILE_READ_DATA
, &fd
, NULL
) ))
1975 result
= WS2_recv( fd
, wsa
);
1976 wine_server_release_fd( wsa
->hSocket
, fd
);
1979 status
= STATUS_SUCCESS
;
1980 _enable_event( wsa
->hSocket
, FD_READ
, 0, 0 );
1984 if (errno
== EINTR
|| errno
== EAGAIN
)
1986 status
= STATUS_PENDING
;
1987 _enable_event( wsa
->hSocket
, FD_READ
, 0, 0 );
1992 status
= wsaErrStatus();
1997 if (status
!= STATUS_PENDING
)
1999 iosb
->u
.Status
= status
;
2000 iosb
->Information
= result
;
2001 *apc
= ws2_async_apc
;
2006 /* user APC called upon async accept completion */
2007 static void WINAPI
ws2_async_accept_apc( void *arg
, IO_STATUS_BLOCK
*iosb
, ULONG reserved
)
2009 struct ws2_accept_async
*wsa
= arg
;
2011 HeapFree( GetProcessHeap(), 0, wsa
->read
);
2012 HeapFree( GetProcessHeap(), 0, wsa
);
2015 /***********************************************************************
2016 * WS2_async_accept_recv (INTERNAL)
2018 * This function is used to finish the read part of an accept request. It is
2019 * needed to place the completion on the correct socket (listener).
2021 static NTSTATUS
WS2_async_accept_recv( void *arg
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
, void **apc
)
2024 struct ws2_accept_async
*wsa
= arg
;
2026 status
= WS2_async_recv( wsa
->read
, iosb
, status
, &junk
);
2027 if (status
== STATUS_PENDING
)
2030 if (wsa
->user_overlapped
->hEvent
)
2031 SetEvent(wsa
->user_overlapped
->hEvent
);
2033 WS_AddCompletion( HANDLE2SOCKET(wsa
->listen_socket
), wsa
->cvalue
, iosb
->u
.Status
, iosb
->Information
);
2035 *apc
= ws2_async_accept_apc
;
2039 /***********************************************************************
2040 * WS2_async_accept (INTERNAL)
2042 * This is the function called to satisfy the AcceptEx callback
2044 static NTSTATUS
WS2_async_accept( void *arg
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
, void **apc
)
2046 struct ws2_accept_async
*wsa
= arg
;
2050 TRACE("status: 0x%x listen: %p, accept: %p\n", status
, wsa
->listen_socket
, wsa
->accept_socket
);
2052 if (status
== STATUS_ALERTED
)
2054 SERVER_START_REQ( accept_into_socket
)
2056 req
->lhandle
= wine_server_obj_handle( wsa
->listen_socket
);
2057 req
->ahandle
= wine_server_obj_handle( wsa
->accept_socket
);
2058 status
= wine_server_call( req
);
2062 if (status
== STATUS_CANT_WAIT
)
2063 return STATUS_PENDING
;
2065 if (status
== STATUS_INVALID_HANDLE
)
2067 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2068 status
= STATUS_CANCELLED
;
2071 else if (status
== STATUS_HANDLES_CLOSED
)
2072 status
= STATUS_CANCELLED
; /* strange windows behavior */
2074 if (status
!= STATUS_SUCCESS
)
2077 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2078 addr
= ((char *)wsa
->buf
) + wsa
->data_len
;
2079 len
= wsa
->local_len
- sizeof(int);
2080 WS_getsockname(HANDLE2SOCKET(wsa
->accept_socket
),
2081 (struct WS_sockaddr
*)(addr
+ sizeof(int)), &len
);
2084 addr
+= wsa
->local_len
;
2085 len
= wsa
->remote_len
- sizeof(int);
2086 WS_getpeername(HANDLE2SOCKET(wsa
->accept_socket
),
2087 (struct WS_sockaddr
*)(addr
+ sizeof(int)), &len
);
2093 SERVER_START_REQ( register_async
)
2095 req
->type
= ASYNC_TYPE_READ
;
2096 req
->async
.handle
= wine_server_obj_handle( wsa
->accept_socket
);
2097 req
->async
.callback
= wine_server_client_ptr( WS2_async_accept_recv
);
2098 req
->async
.iosb
= wine_server_client_ptr( iosb
);
2099 req
->async
.arg
= wine_server_client_ptr( wsa
);
2100 status
= wine_server_call( req
);
2104 if (status
!= STATUS_PENDING
)
2107 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2108 * needs to be performed by WS2_async_accept_recv() first. */
2109 return STATUS_MORE_PROCESSING_REQUIRED
;
2112 iosb
->u
.Status
= status
;
2113 iosb
->Information
= 0;
2115 if (wsa
->user_overlapped
->hEvent
)
2116 SetEvent(wsa
->user_overlapped
->hEvent
);
2118 *apc
= ws2_async_accept_apc
;
2122 /***********************************************************************
2123 * WS2_send (INTERNAL)
2125 * Workhorse for both synchronous and asynchronous send() operations.
2127 static int WS2_send( int fd
, struct ws2_async
*wsa
)
2130 union generic_unix_sockaddr unix_addr
;
2133 hdr
.msg_name
= NULL
;
2134 hdr
.msg_namelen
= 0;
2138 hdr
.msg_name
= &unix_addr
;
2139 hdr
.msg_namelen
= ws_sockaddr_ws2u( wsa
->addr
, wsa
->addrlen
.val
, &unix_addr
);
2140 if ( !hdr
.msg_namelen
)
2146 #if defined(HAS_IPX) && defined(SOL_IPX)
2147 if(wsa
->addr
->sa_family
== WS_AF_IPX
)
2149 struct sockaddr_ipx
* uipx
= (struct sockaddr_ipx
*)hdr
.msg_name
;
2151 socklen_t len
= sizeof(int);
2153 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2154 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2155 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2156 * ipx type in the sockaddr_opx structure with the stored value.
2158 if(getsockopt(fd
, SOL_IPX
, IPX_TYPE
, &val
, &len
) != -1)
2159 uipx
->sipx_type
= val
;
2164 hdr
.msg_iov
= wsa
->iovec
+ wsa
->first_iovec
;
2165 hdr
.msg_iovlen
= wsa
->n_iovecs
- wsa
->first_iovec
;
2166 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2167 hdr
.msg_accrights
= NULL
;
2168 hdr
.msg_accrightslen
= 0;
2170 hdr
.msg_control
= NULL
;
2171 hdr
.msg_controllen
= 0;
2175 ret
= sendmsg(fd
, &hdr
, wsa
->flags
);
2179 while (wsa
->first_iovec
< wsa
->n_iovecs
&& wsa
->iovec
[wsa
->first_iovec
].iov_len
<= n
)
2180 n
-= wsa
->iovec
[wsa
->first_iovec
++].iov_len
;
2181 if (wsa
->first_iovec
< wsa
->n_iovecs
)
2183 wsa
->iovec
[wsa
->first_iovec
].iov_base
= (char*)wsa
->iovec
[wsa
->first_iovec
].iov_base
+ n
;
2184 wsa
->iovec
[wsa
->first_iovec
].iov_len
-= n
;
2190 /***********************************************************************
2191 * WS2_async_send (INTERNAL)
2193 * Handler for overlapped send() operations.
2195 static NTSTATUS
WS2_async_send(void* user
, IO_STATUS_BLOCK
* iosb
, NTSTATUS status
, void **apc
)
2197 ws2_async
* wsa
= user
;
2202 case STATUS_ALERTED
:
2203 if ( wsa
->n_iovecs
<= wsa
->first_iovec
)
2206 status
= STATUS_SUCCESS
;
2209 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, FILE_WRITE_DATA
, &fd
, NULL
) ))
2212 /* check to see if the data is ready (non-blocking) */
2213 result
= WS2_send( fd
, wsa
);
2214 wine_server_release_fd( wsa
->hSocket
, fd
);
2218 if (wsa
->first_iovec
< wsa
->n_iovecs
)
2219 status
= STATUS_PENDING
;
2221 status
= STATUS_SUCCESS
;
2223 iosb
->Information
+= result
;
2225 else if (errno
== EINTR
|| errno
== EAGAIN
)
2227 status
= STATUS_PENDING
;
2231 status
= wsaErrStatus();
2235 if (status
!= STATUS_PENDING
)
2237 iosb
->u
.Status
= status
;
2238 *apc
= ws2_async_apc
;
2243 /***********************************************************************
2244 * WS2_async_shutdown (INTERNAL)
2246 * Handler for shutdown() operations on overlapped sockets.
2248 static NTSTATUS
WS2_async_shutdown( void* user
, PIO_STATUS_BLOCK iosb
, NTSTATUS status
, void **apc
)
2250 ws2_async
* wsa
= user
;
2255 case STATUS_ALERTED
:
2256 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, 0, &fd
, NULL
) ))
2259 switch ( wsa
->type
)
2261 case ASYNC_TYPE_READ
: err
= shutdown( fd
, 0 ); break;
2262 case ASYNC_TYPE_WRITE
: err
= shutdown( fd
, 1 ); break;
2264 status
= err
? wsaErrStatus() : STATUS_SUCCESS
;
2265 wine_server_release_fd( wsa
->hSocket
, fd
);
2268 iosb
->u
.Status
= status
;
2269 iosb
->Information
= 0;
2270 *apc
= ws2_async_apc
;
2274 /***********************************************************************
2275 * WS2_register_async_shutdown (INTERNAL)
2277 * Helper function for WS_shutdown() on overlapped sockets.
2279 static int WS2_register_async_shutdown( SOCKET s
, int type
)
2281 struct ws2_async
*wsa
;
2284 TRACE("s %ld type %d\n", s
, type
);
2286 wsa
= HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async
, iovec
[1] ));
2290 wsa
->hSocket
= SOCKET2HANDLE(s
);
2292 wsa
->completion_func
= NULL
;
2294 SERVER_START_REQ( register_async
)
2297 req
->async
.handle
= wine_server_obj_handle( wsa
->hSocket
);
2298 req
->async
.callback
= wine_server_client_ptr( WS2_async_shutdown
);
2299 req
->async
.iosb
= wine_server_client_ptr( &wsa
->local_iosb
);
2300 req
->async
.arg
= wine_server_client_ptr( wsa
);
2301 req
->async
.cvalue
= 0;
2302 status
= wine_server_call( req
);
2306 if (status
!= STATUS_PENDING
)
2308 HeapFree( GetProcessHeap(), 0, wsa
);
2309 return NtStatusToWSAError( status
);
2314 /***********************************************************************
2317 SOCKET WINAPI
WS_accept(SOCKET s
, struct WS_sockaddr
*addr
, int *addrlen32
)
2323 TRACE("socket %04lx\n", s
);
2324 status
= _is_blocking(s
, &is_blocking
);
2328 return INVALID_SOCKET
;
2332 /* try accepting first (if there is a deferred connection) */
2333 SERVER_START_REQ( accept_socket
)
2335 req
->lhandle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
2336 req
->access
= GENERIC_READ
|GENERIC_WRITE
|SYNCHRONIZE
;
2337 req
->attributes
= OBJ_INHERIT
;
2338 status
= wine_server_call( req
);
2339 as
= HANDLE2SOCKET( wine_server_ptr_handle( reply
->handle
));
2344 if (addr
&& WS_getpeername(as
, addr
, addrlen32
))
2347 return SOCKET_ERROR
;
2351 if (is_blocking
&& status
== STATUS_CANT_WAIT
)
2353 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
2355 do_block(fd
, POLLIN
, -1);
2356 _sync_sock_state(s
); /* let wineserver notice connection */
2357 release_sock_fd( s
, fd
);
2359 } while (is_blocking
&& status
== STATUS_CANT_WAIT
);
2362 return INVALID_SOCKET
;
2365 /***********************************************************************
2368 static BOOL WINAPI
WS2_AcceptEx(SOCKET listener
, SOCKET acceptor
, PVOID dest
, DWORD dest_len
,
2369 DWORD local_addr_len
, DWORD rem_addr_len
, LPDWORD received
,
2370 LPOVERLAPPED overlapped
)
2373 struct ws2_accept_async
*wsa
;
2375 ULONG_PTR cvalue
= (overlapped
&& ((ULONG_PTR
)overlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)overlapped
: 0;
2377 TRACE("(%lx, %lx, %p, %d, %d, %d, %p, %p)\n", listener
, acceptor
, dest
, dest_len
, local_addr_len
,
2378 rem_addr_len
, received
, overlapped
);
2382 SetLastError(WSAEINVAL
);
2388 SetLastError(WSA_INVALID_PARAMETER
);
2394 SetLastError(WSAEFAULT
);
2398 fd
= get_sock_fd( listener
, FILE_READ_DATA
, NULL
);
2401 SetLastError(WSAENOTSOCK
);
2404 release_sock_fd( listener
, fd
);
2406 fd
= get_sock_fd( acceptor
, FILE_READ_DATA
, NULL
);
2409 SetLastError(WSAENOTSOCK
);
2412 release_sock_fd( acceptor
, fd
);
2414 wsa
= HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa
) );
2417 SetLastError(WSAEFAULT
);
2421 wsa
->listen_socket
= SOCKET2HANDLE(listener
);
2422 wsa
->accept_socket
= SOCKET2HANDLE(acceptor
);
2423 wsa
->user_overlapped
= overlapped
;
2424 wsa
->cvalue
= cvalue
;
2426 wsa
->data_len
= dest_len
;
2427 wsa
->local_len
= local_addr_len
;
2428 wsa
->remote_len
= rem_addr_len
;
2433 /* set up a read request if we need it */
2434 wsa
->read
= HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async
, iovec
[1]) );
2437 HeapFree( GetProcessHeap(), 0, wsa
);
2438 SetLastError(WSAEFAULT
);
2442 wsa
->read
->hSocket
= wsa
->accept_socket
;
2443 wsa
->read
->flags
= 0;
2444 wsa
->read
->lpFlags
= &wsa
->read
->flags
;
2445 wsa
->read
->addr
= NULL
;
2446 wsa
->read
->addrlen
.ptr
= NULL
;
2447 wsa
->read
->control
= NULL
;
2448 wsa
->read
->n_iovecs
= 1;
2449 wsa
->read
->first_iovec
= 0;
2450 wsa
->read
->iovec
[0].iov_base
= wsa
->buf
;
2451 wsa
->read
->iovec
[0].iov_len
= wsa
->data_len
;
2454 SERVER_START_REQ( register_async
)
2456 req
->type
= ASYNC_TYPE_READ
;
2457 req
->async
.handle
= wine_server_obj_handle( SOCKET2HANDLE(listener
) );
2458 req
->async
.callback
= wine_server_client_ptr( WS2_async_accept
);
2459 req
->async
.iosb
= wine_server_client_ptr( overlapped
);
2460 req
->async
.arg
= wine_server_client_ptr( wsa
);
2461 req
->async
.cvalue
= cvalue
;
2462 /* We don't set event since we may also have to read */
2463 status
= wine_server_call( req
);
2467 if(status
!= STATUS_PENDING
)
2469 HeapFree( GetProcessHeap(), 0, wsa
->read
);
2470 HeapFree( GetProcessHeap(), 0, wsa
);
2473 SetLastError( NtStatusToWSAError(status
) );
2477 /***********************************************************************
2478 * GetAcceptExSockaddrs
2480 static void WINAPI
WS2_GetAcceptExSockaddrs(PVOID buffer
, DWORD data_size
, DWORD local_size
, DWORD remote_size
,
2481 struct WS_sockaddr
**local_addr
, LPINT local_addr_len
,
2482 struct WS_sockaddr
**remote_addr
, LPINT remote_addr_len
)
2484 char *cbuf
= buffer
;
2485 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer
, data_size
, local_size
, remote_size
, local_addr
,
2486 local_addr_len
, remote_addr
, remote_addr_len
);
2489 *local_addr_len
= *(int *) cbuf
;
2490 *local_addr
= (struct WS_sockaddr
*)(cbuf
+ sizeof(int));
2494 *remote_addr_len
= *(int *) cbuf
;
2495 *remote_addr
= (struct WS_sockaddr
*)(cbuf
+ sizeof(int));
2498 /***********************************************************************
2501 int WINAPI
WSASendMsg( SOCKET s
, LPWSAMSG msg
, DWORD dwFlags
, LPDWORD lpNumberOfBytesSent
,
2502 LPWSAOVERLAPPED lpOverlapped
,
2503 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
2507 SetLastError( WSAEFAULT
);
2508 return SOCKET_ERROR
;
2511 return WS2_sendto( s
, msg
->lpBuffers
, msg
->dwBufferCount
, lpNumberOfBytesSent
,
2512 dwFlags
, msg
->name
, msg
->namelen
,
2513 lpOverlapped
, lpCompletionRoutine
);
2516 /***********************************************************************
2519 * Perform a receive operation that is capable of returning message
2520 * control headers. It is important to note that the WSAMSG parameter
2521 * must remain valid throughout the operation, even when an overlapped
2522 * receive is performed.
2524 static int WINAPI
WS2_WSARecvMsg( SOCKET s
, LPWSAMSG msg
, LPDWORD lpNumberOfBytesRecvd
,
2525 LPWSAOVERLAPPED lpOverlapped
,
2526 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
2530 SetLastError( WSAEFAULT
);
2531 return SOCKET_ERROR
;
2534 return WS2_recv_base( s
, msg
->lpBuffers
, msg
->dwBufferCount
, lpNumberOfBytesRecvd
,
2535 &msg
->dwFlags
, msg
->name
, &msg
->namelen
,
2536 lpOverlapped
, lpCompletionRoutine
, &msg
->Control
);
2539 /***********************************************************************
2540 * interface_bind (INTERNAL)
2542 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
2543 * operating only on the specified interface. This restriction consists of two components:
2544 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
2545 * 2) An incoming packet restriction dropping packets not meant for the interface.
2546 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
2547 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
2548 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
2549 * to receive broadcast packets on a socket that is bound to a specific network interface.
2551 static BOOL
interface_bind( SOCKET s
, int fd
, struct sockaddr
*addr
)
2553 struct sockaddr_in
*in_sock
= (struct sockaddr_in
*) addr
;
2554 unsigned int sock_type
= 0;
2555 socklen_t optlen
= sizeof(sock_type
);
2556 in_addr_t bind_addr
= in_sock
->sin_addr
.s_addr
;
2557 PIP_ADAPTER_INFO adapters
= NULL
, adapter
;
2562 if (bind_addr
== htonl(INADDR_ANY
) || bind_addr
== htonl(INADDR_LOOPBACK
))
2563 return FALSE
; /* Not binding to a network adapter, special interface binding unnecessary. */
2564 if (getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, &sock_type
, &optlen
) == -1 || sock_type
!= SOCK_DGRAM
)
2565 return FALSE
; /* Special interface binding is only necessary for UDP datagrams. */
2566 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
2568 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
2569 if (adapters
== NULL
|| GetAdaptersInfo(adapters
, &adap_size
) != NO_ERROR
)
2571 /* Search the IPv4 adapter list for the appropriate binding interface */
2572 for (adapter
= adapters
; adapter
!= NULL
; adapter
= adapter
->Next
)
2574 in_addr_t adapter_addr
= (in_addr_t
) inet_addr(adapter
->IpAddressList
.IpAddress
.String
);
2576 if (bind_addr
== adapter_addr
)
2578 #if defined(IP_BOUND_IF)
2579 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
2580 if (setsockopt(fd
, IPPROTO_IP
, IP_BOUND_IF
, &adapter
->Index
, sizeof(adapter
->Index
)) != 0)
2583 #elif defined(LINUX_BOUND_IF)
2584 in_addr_t ifindex
= (in_addr_t
) htonl(adapter
->Index
);
2585 struct interface_filter specific_interface_filter
;
2586 struct sock_fprog filter_prog
;
2588 if (setsockopt(fd
, IPPROTO_IP
, IP_UNICAST_IF
, &ifindex
, sizeof(ifindex
)) != 0)
2589 goto cleanup
; /* Failed to suggest egress interface */
2590 specific_interface_filter
= generic_interface_filter
;
2591 specific_interface_filter
.iface_rule
.k
= adapter
->Index
;
2592 specific_interface_filter
.ip_rule
.k
= htonl(adapter_addr
);
2593 filter_prog
.len
= sizeof(generic_interface_filter
)/sizeof(struct sock_filter
);
2594 filter_prog
.filter
= (struct sock_filter
*) &specific_interface_filter
;
2595 if (setsockopt(fd
, SOL_SOCKET
, SO_ATTACH_FILTER
, &filter_prog
, sizeof(filter_prog
)) != 0)
2596 goto cleanup
; /* Failed to specify incoming packet filter */
2599 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
2600 "receiving broadcast packets will not work on socket %04lx.\n", s
);
2605 /* Will soon be switching to INADDR_ANY: permit address reuse */
2606 if (ret
&& setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &enable
, sizeof(enable
)) == 0)
2607 TRACE("Socket %04lx bound to interface index %d\n", s
, adapter
->Index
);
2613 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s
);
2614 HeapFree(GetProcessHeap(), 0, adapters
);
2618 /***********************************************************************
2621 int WINAPI
WS_bind(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
)
2623 int fd
= get_sock_fd( s
, 0, NULL
);
2624 int res
= SOCKET_ERROR
;
2626 TRACE("socket %04lx, ptr %p %s, length %d\n", s
, name
, debugstr_sockaddr(name
), namelen
);
2630 if (!name
|| (name
->sa_family
&& !supported_pf(name
->sa_family
)))
2632 SetLastError(WSAEAFNOSUPPORT
);
2636 union generic_unix_sockaddr uaddr
;
2637 unsigned int uaddrlen
= ws_sockaddr_ws2u(name
, namelen
, &uaddr
);
2640 SetLastError(WSAEFAULT
);
2645 const struct sockaddr_in6
*in6
= (const struct sockaddr_in6
*) &uaddr
;
2646 if (name
->sa_family
== WS_AF_INET6
&&
2647 !memcmp(&in6
->sin6_addr
, &in6addr_any
, sizeof(struct in6_addr
)))
2650 if (setsockopt(fd
, IPPROTO_IPV6
, IPV6_V6ONLY
, &enable
, sizeof(enable
)) == -1)
2652 release_sock_fd( s
, fd
);
2653 SetLastError(WSAEAFNOSUPPORT
);
2654 return SOCKET_ERROR
;
2658 if (name
->sa_family
== WS_AF_INET
)
2660 struct sockaddr_in
*in4
= (struct sockaddr_in
*) &uaddr
;
2661 if (memcmp(&in4
->sin_addr
, magic_loopback_addr
, 4) == 0)
2663 /* Trying to bind to the default host interface, using
2664 * INADDR_ANY instead*/
2665 WARN("Trying to bind to magic IP address, using "
2666 "INADDR_ANY instead.\n");
2667 in4
->sin_addr
.s_addr
= htonl(INADDR_ANY
);
2669 else if (interface_bind(s
, fd
, &uaddr
.addr
))
2670 in4
->sin_addr
.s_addr
= htonl(INADDR_ANY
);
2672 if (bind(fd
, &uaddr
.addr
, uaddrlen
) < 0)
2674 int loc_errno
= errno
;
2675 WARN("\tfailure - errno = %i\n", errno
);
2680 SetLastError(WSAENOTSOCK
);
2683 SetLastError(WSAEINVAL
);
2688 socklen_t optlen
= sizeof(optval
);
2689 /* Windows >= 2003 will return different results depending on
2690 * SO_REUSEADDR, WSAEACCES may be returned representing that
2691 * the socket hijacking protection prevented the bind */
2692 if (!getsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&optval
, &optlen
) && optval
)
2694 SetLastError(WSAEACCES
);
2700 SetLastError(wsaErrno());
2706 res
=0; /* success */
2710 release_sock_fd( s
, fd
);
2715 /***********************************************************************
2716 * closesocket (WS2_32.3)
2718 int WINAPI
WS_closesocket(SOCKET s
)
2720 TRACE("socket %04lx\n", s
);
2721 if (CloseHandle(SOCKET2HANDLE(s
))) return 0;
2722 return SOCKET_ERROR
;
2725 static int do_connect(int fd
, const struct WS_sockaddr
* name
, int namelen
)
2727 union generic_unix_sockaddr uaddr
;
2728 unsigned int uaddrlen
= ws_sockaddr_ws2u(name
, namelen
, &uaddr
);
2733 if (name
->sa_family
== WS_AF_INET
)
2735 struct sockaddr_in
*in4
= (struct sockaddr_in
*) &uaddr
;
2736 if (memcmp(&in4
->sin_addr
, magic_loopback_addr
, 4) == 0)
2738 /* Trying to connect to magic replace-loopback address,
2739 * assuming we really want to connect to localhost */
2740 TRACE("Trying to connect to magic IP address, using "
2741 "INADDR_LOOPBACK instead.\n");
2742 in4
->sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
2746 if (connect(fd
, &uaddr
.addr
, uaddrlen
) == 0)
2752 /***********************************************************************
2753 * connect (WS2_32.4)
2755 int WINAPI
WS_connect(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
)
2757 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
2759 TRACE("socket %04lx, ptr %p %s, length %d\n", s
, name
, debugstr_sockaddr(name
), namelen
);
2765 int ret
= do_connect(fd
, name
, namelen
);
2767 goto connect_success
;
2769 if (ret
== WSAEINPROGRESS
)
2771 /* tell wineserver that a connection is in progress */
2772 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
2774 FD_WINE_CONNECTED
|FD_WINE_LISTENING
);
2775 status
= _is_blocking( s
, &is_blocking
);
2778 release_sock_fd( s
, fd
);
2779 set_error( status
);
2780 return SOCKET_ERROR
;
2786 do_block(fd
, POLLIN
| POLLOUT
, -1);
2787 _sync_sock_state(s
); /* let wineserver notice connection */
2788 /* retrieve any error codes from it */
2789 result
= _get_sock_error(s
, FD_CONNECT_BIT
);
2791 SetLastError(NtStatusToWSAError(result
));
2794 goto connect_success
;
2799 SetLastError(WSAEWOULDBLOCK
);
2806 release_sock_fd( s
, fd
);
2808 return SOCKET_ERROR
;
2811 release_sock_fd( s
, fd
);
2812 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
2813 FD_WINE_CONNECTED
|FD_READ
|FD_WRITE
,
2814 FD_CONNECT
|FD_WINE_LISTENING
);
2818 /***********************************************************************
2819 * WSAConnect (WS2_32.30)
2821 int WINAPI
WSAConnect( SOCKET s
, const struct WS_sockaddr
* name
, int namelen
,
2822 LPWSABUF lpCallerData
, LPWSABUF lpCalleeData
,
2823 LPQOS lpSQOS
, LPQOS lpGQOS
)
2825 if ( lpCallerData
|| lpCalleeData
|| lpSQOS
|| lpGQOS
)
2826 FIXME("unsupported parameters!\n");
2827 return WS_connect( s
, name
, namelen
);
2830 /***********************************************************************
2833 static BOOL WINAPI
WS2_ConnectEx(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
,
2834 PVOID sendBuf
, DWORD sendBufLen
, LPDWORD sent
, LPOVERLAPPED ov
)
2836 int fd
, ret
, status
;
2837 union generic_unix_sockaddr uaddr
;
2838 socklen_t uaddrlen
= sizeof(uaddr
);
2842 SetLastError( ERROR_INVALID_PARAMETER
);
2846 fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
2849 SetLastError( WSAENOTSOCK
);
2853 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
2854 s
, name
, debugstr_sockaddr(name
), namelen
, sendBuf
, sendBufLen
, ov
);
2856 if (getsockname(fd
, &uaddr
.addr
, &uaddrlen
) != 0)
2858 SetLastError(wsaErrno());
2861 else if (!is_sockaddr_bound(&uaddr
.addr
, uaddrlen
))
2863 SetLastError(WSAEINVAL
);
2867 ret
= do_connect(fd
, name
, namelen
);
2872 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
2873 FD_WINE_CONNECTED
|FD_READ
|FD_WRITE
,
2874 FD_CONNECT
|FD_WINE_LISTENING
);
2876 wsabuf
.len
= sendBufLen
;
2877 wsabuf
.buf
= (char*) sendBuf
;
2879 /* WSASend takes care of completion if need be */
2880 if (WSASend(s
, &wsabuf
, sendBuf
? 1 : 0, sent
, 0, ov
, NULL
) != SOCKET_ERROR
)
2881 goto connection_success
;
2883 else if (ret
== WSAEINPROGRESS
)
2885 struct ws2_async
*wsa
;
2886 ULONG_PTR cvalue
= (((ULONG_PTR
)ov
->hEvent
& 1) == 0) ? (ULONG_PTR
)ov
: 0;
2888 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
2890 FD_WINE_CONNECTED
|FD_WINE_LISTENING
);
2892 /* Indirectly call WSASend */
2893 if (!(wsa
= HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async
, iovec
[1] ))))
2895 SetLastError(WSAEFAULT
);
2899 IO_STATUS_BLOCK
*iosb
= (IO_STATUS_BLOCK
*)ov
;
2900 iosb
->u
.Status
= STATUS_PENDING
;
2901 iosb
->Information
= 0;
2903 wsa
->hSocket
= SOCKET2HANDLE(s
);
2905 wsa
->addrlen
.val
= 0;
2907 wsa
->lpFlags
= &wsa
->flags
;
2908 wsa
->control
= NULL
;
2909 wsa
->n_iovecs
= sendBuf
? 1 : 0;
2910 wsa
->first_iovec
= 0;
2911 wsa
->completion_func
= NULL
;
2912 wsa
->iovec
[0].iov_base
= sendBuf
;
2913 wsa
->iovec
[0].iov_len
= sendBufLen
;
2915 SERVER_START_REQ( register_async
)
2917 req
->type
= ASYNC_TYPE_WRITE
;
2918 req
->async
.handle
= wine_server_obj_handle( wsa
->hSocket
);
2919 req
->async
.callback
= wine_server_client_ptr( WS2_async_send
);
2920 req
->async
.iosb
= wine_server_client_ptr( iosb
);
2921 req
->async
.arg
= wine_server_client_ptr( wsa
);
2922 req
->async
.event
= wine_server_obj_handle( ov
->hEvent
);
2923 req
->async
.cvalue
= cvalue
;
2924 status
= wine_server_call( req
);
2928 if (status
!= STATUS_PENDING
) HeapFree(GetProcessHeap(), 0, wsa
);
2930 /* If the connect already failed */
2931 if (status
== STATUS_PIPE_DISCONNECTED
)
2932 status
= _get_sock_error(s
, FD_CONNECT_BIT
);
2933 SetLastError( NtStatusToWSAError(status
) );
2941 release_sock_fd( s
, fd
);
2945 release_sock_fd( s
, fd
);
2950 /***********************************************************************
2951 * getpeername (WS2_32.5)
2953 int WINAPI
WS_getpeername(SOCKET s
, struct WS_sockaddr
*name
, int *namelen
)
2958 TRACE("socket: %04lx, ptr %p, len %08x\n", s
, name
, namelen
? *namelen
: 0);
2960 fd
= get_sock_fd( s
, 0, NULL
);
2965 union generic_unix_sockaddr uaddr
;
2966 socklen_t uaddrlen
= sizeof(uaddr
);
2968 if (getpeername(fd
, &uaddr
.addr
, &uaddrlen
) == 0)
2970 if (!name
|| !namelen
)
2971 SetLastError(WSAEFAULT
);
2972 else if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
2973 /* The buffer was too small */
2974 SetLastError(WSAEFAULT
);
2979 SetLastError(wsaErrno());
2980 release_sock_fd( s
, fd
);
2985 /***********************************************************************
2986 * getsockname (WS2_32.6)
2988 int WINAPI
WS_getsockname(SOCKET s
, struct WS_sockaddr
*name
, int *namelen
)
2993 TRACE("socket: %04lx, ptr %p, len %08x\n", s
, name
, namelen
? *namelen
: 0);
2995 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
2996 if( (name
== NULL
) || (namelen
== NULL
) )
2998 SetLastError( WSAEFAULT
);
2999 return SOCKET_ERROR
;
3002 fd
= get_sock_fd( s
, 0, NULL
);
3007 union generic_unix_sockaddr uaddr
;
3008 socklen_t uaddrlen
= sizeof(uaddr
);
3010 if (getsockname(fd
, &uaddr
.addr
, &uaddrlen
) != 0)
3012 SetLastError(wsaErrno());
3014 else if (!is_sockaddr_bound(&uaddr
.addr
, uaddrlen
))
3016 SetLastError(WSAEINVAL
);
3018 else if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
3020 /* The buffer was too small */
3021 SetLastError(WSAEFAULT
);
3026 TRACE("=> %s\n", debugstr_sockaddr(name
));
3028 release_sock_fd( s
, fd
);
3033 /***********************************************************************
3034 * getsockopt (WS2_32.7)
3036 INT WINAPI
WS_getsockopt(SOCKET s
, INT level
,
3037 INT optname
, char *optval
, INT
*optlen
)
3042 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
3043 s
, level
, optname
, optval
, optlen
? *optlen
: 0);
3051 /* Handle common cases. The special cases are below, sorted
3053 case WS_SO_BROADCAST
:
3056 case WS_SO_KEEPALIVE
:
3057 case WS_SO_OOBINLINE
:
3059 case WS_SO_REUSEADDR
:
3061 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3062 return SOCKET_ERROR
;
3063 convert_sockopt(&level
, &optname
);
3064 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3066 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3069 release_sock_fd( s
, fd
);
3071 case WS_SO_ACCEPTCONN
:
3072 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3073 return SOCKET_ERROR
;
3074 if (getsockopt(fd
, SOL_SOCKET
, SO_ACCEPTCONN
, optval
, (socklen_t
*)optlen
) != 0 )
3076 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3081 /* BSD returns != 0 while Windows return exact == 1 */
3082 if (*(int *)optval
) *(int *)optval
= 1;
3084 release_sock_fd( s
, fd
);
3086 case WS_SO_DONTLINGER
:
3088 struct linger lingval
;
3089 socklen_t len
= sizeof(struct linger
);
3091 if (!optlen
|| *optlen
< sizeof(BOOL
)|| !optval
)
3093 SetLastError(WSAEFAULT
);
3094 return SOCKET_ERROR
;
3096 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3097 return SOCKET_ERROR
;
3099 if (getsockopt(fd
, SOL_SOCKET
, SO_LINGER
, &lingval
, &len
) != 0 )
3101 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3106 *(BOOL
*)optval
= !lingval
.l_onoff
;
3107 *optlen
= sizeof(BOOL
);
3110 release_sock_fd( s
, fd
);
3114 case WS_SO_CONNECT_TIME
:
3116 static int pretendtime
= 0;
3117 struct WS_sockaddr addr
;
3118 int len
= sizeof(addr
);
3120 if (!optlen
|| *optlen
< sizeof(DWORD
) || !optval
)
3122 SetLastError(WSAEFAULT
);
3123 return SOCKET_ERROR
;
3125 if (WS_getpeername(s
, &addr
, &len
) == SOCKET_ERROR
)
3126 *(DWORD
*)optval
= ~0u;
3129 if (!pretendtime
) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3130 *(DWORD
*)optval
= pretendtime
++;
3132 *optlen
= sizeof(DWORD
);
3135 /* As mentioned in setsockopt, Windows ignores this, so we
3136 * always return true here */
3137 case WS_SO_DONTROUTE
:
3138 if (!optlen
|| *optlen
< sizeof(BOOL
) || !optval
)
3140 SetLastError(WSAEFAULT
);
3141 return SOCKET_ERROR
;
3143 *(BOOL
*)optval
= TRUE
;
3144 *optlen
= sizeof(BOOL
);
3149 struct linger lingval
;
3151 socklen_t len
= sizeof(struct linger
), slen
= sizeof(int);
3153 /* struct linger and LINGER have different sizes */
3154 if (!optlen
|| *optlen
< sizeof(LINGER
) || !optval
)
3156 SetLastError(WSAEFAULT
);
3157 return SOCKET_ERROR
;
3159 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3160 return SOCKET_ERROR
;
3162 if ((getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, &so_type
, &slen
) == 0 && so_type
== SOCK_DGRAM
))
3164 SetLastError(WSAENOPROTOOPT
);
3167 else if (getsockopt(fd
, SOL_SOCKET
, SO_LINGER
, &lingval
, &len
) != 0)
3169 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3174 ((LINGER
*)optval
)->l_onoff
= lingval
.l_onoff
;
3175 ((LINGER
*)optval
)->l_linger
= lingval
.l_linger
;
3176 *optlen
= sizeof(struct linger
);
3179 release_sock_fd( s
, fd
);
3183 case WS_SO_MAX_MSG_SIZE
:
3184 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
3186 SetLastError(WSAEFAULT
);
3187 return SOCKET_ERROR
;
3189 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3190 *(int *)optval
= 65507;
3191 *optlen
= sizeof(int);
3194 /* SO_OPENTYPE does not require a valid socket handle. */
3195 case WS_SO_OPENTYPE
:
3196 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
3198 SetLastError(WSAEFAULT
);
3199 return SOCKET_ERROR
;
3201 *(int *)optval
= get_per_thread_data()->opentype
;
3202 *optlen
= sizeof(int);
3203 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval
) );
3205 case WS_SO_PROTOCOL_INFOA
:
3206 case WS_SO_PROTOCOL_INFOW
:
3209 WSAPROTOCOL_INFOW infow
;
3211 ret
= ws_protocol_info(s
, optname
== WS_SO_PROTOCOL_INFOW
, &infow
, &size
);
3214 if (!optlen
|| !optval
|| *optlen
< size
)
3216 if(optlen
) *optlen
= size
;
3218 SetLastError(WSAEFAULT
);
3221 memcpy(optval
, &infow
, size
);
3223 return ret
? 0 : SOCKET_ERROR
;
3226 case WS_SO_RCVTIMEO
:
3229 case WS_SO_SNDTIMEO
:
3231 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3234 socklen_t len
= sizeof(struct timeval
);
3236 if (!optlen
|| *optlen
< sizeof(int)|| !optval
)
3238 SetLastError(WSAEFAULT
);
3239 return SOCKET_ERROR
;
3241 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3242 return SOCKET_ERROR
;
3244 convert_sockopt(&level
, &optname
);
3245 if (getsockopt(fd
, level
, optname
, &tv
, &len
) != 0 )
3247 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3252 *(int *)optval
= tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000;
3253 *optlen
= sizeof(int);
3256 release_sock_fd( s
, fd
);
3262 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
3264 SetLastError(WSAEFAULT
);
3265 return SOCKET_ERROR
;
3267 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3268 return SOCKET_ERROR
;
3270 if (getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, optval
, (socklen_t
*)optlen
) != 0 )
3272 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3276 (*(int *)optval
) = convert_socktype_u2w(*(int *)optval
);
3278 release_sock_fd( s
, fd
);
3282 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname
);
3283 SetLastError(WSAENOPROTOOPT
);
3284 return SOCKET_ERROR
;
3285 } /* end switch(optname) */
3286 }/* end case WS_SOL_SOCKET */
3288 case WS_NSPROTO_IPX
:
3290 struct WS_sockaddr_ipx addr
;
3291 IPX_ADDRESS_DATA
*data
;
3296 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
3298 if(getsockopt(fd
, SOL_IPX
, IPX_TYPE
, optval
, (socklen_t
*)optlen
) == -1)
3305 socklen_t len
=sizeof(struct ipx
);
3306 if(getsockopt(fd
, 0, SO_DEFAULT_HEADERS
, &val
, &len
) == -1 )
3309 *optval
= (int)val
.ipx_pt
;
3312 TRACE("ptype: %d (fd: %d)\n", *(int*)optval
, fd
);
3313 release_sock_fd( s
, fd
);
3318 * On a Win2000 system with one network card there are usually
3319 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
3320 * Using this call you can then retrieve info about this all.
3321 * In case of Linux it is a bit different. Usually you have
3322 * only "one" device active and further it is not possible to
3323 * query things like the linkspeed.
3325 FIXME("IPX_ADDRESS\n");
3326 namelen
= sizeof(struct WS_sockaddr_ipx
);
3327 memset(&addr
, 0, sizeof(struct WS_sockaddr_ipx
));
3328 WS_getsockname(s
, (struct WS_sockaddr
*)&addr
, &namelen
);
3330 data
= (IPX_ADDRESS_DATA
*)optval
;
3331 memcpy(data
->nodenum
,addr
.sa_nodenum
,sizeof(data
->nodenum
));
3332 memcpy(data
->netnum
,addr
.sa_netnum
,sizeof(data
->netnum
));
3333 data
->adapternum
= 0;
3334 data
->wan
= FALSE
; /* We are not on a wan for now .. */
3335 data
->status
= FALSE
; /* Since we are not on a wan, the wan link isn't up */
3336 data
->maxpkt
= 1467; /* This value is the default one, at least on Win2k/WinXP */
3337 data
->linkspeed
= 100000; /* Set the line speed in 100bit/s to 10 Mbit;
3338 * note 1MB = 1000kB in this case */
3341 case IPX_MAX_ADAPTER_NUM
:
3342 FIXME("IPX_MAX_ADAPTER_NUM\n");
3343 *(int*)optval
= 1; /* As noted under IPX_ADDRESS we have just one card. */
3347 FIXME("IPX optname:%x\n", optname
);
3348 return SOCKET_ERROR
;
3349 }/* end switch(optname) */
3350 } /* end case WS_NSPROTO_IPX */
3354 #define MAX_IRDA_DEVICES 10
3359 case WS_IRLMP_ENUMDEVICES
:
3361 char buf
[sizeof(struct irda_device_list
) +
3362 (MAX_IRDA_DEVICES
- 1) * sizeof(struct irda_device_info
)];
3364 socklen_t len
= sizeof(buf
);
3366 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3367 return SOCKET_ERROR
;
3368 res
= getsockopt( fd
, SOL_IRLMP
, IRLMP_ENUMDEVICES
, buf
, &len
);
3369 release_sock_fd( s
, fd
);
3372 SetLastError(wsaErrno());
3373 return SOCKET_ERROR
;
3377 struct irda_device_list
*src
= (struct irda_device_list
*)buf
;
3378 DEVICELIST
*dst
= (DEVICELIST
*)optval
;
3379 INT needed
= sizeof(DEVICELIST
);
3383 needed
+= (src
->len
- 1) * sizeof(IRDA_DEVICE_INFO
);
3384 if (*optlen
< needed
)
3386 SetLastError(WSAEFAULT
);
3387 return SOCKET_ERROR
;
3390 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src
->len
);
3391 dst
->numDevice
= src
->len
;
3392 for (i
= 0; i
< src
->len
; i
++)
3394 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
3395 src
->dev
[i
].saddr
, src
->dev
[i
].daddr
,
3396 src
->dev
[i
].info
, src
->dev
[i
].hints
[0],
3397 src
->dev
[i
].hints
[1]);
3398 memcpy( dst
->Device
[i
].irdaDeviceID
,
3400 sizeof(dst
->Device
[i
].irdaDeviceID
) ) ;
3401 memcpy( dst
->Device
[i
].irdaDeviceName
,
3403 sizeof(dst
->Device
[i
].irdaDeviceName
) ) ;
3404 memcpy( &dst
->Device
[i
].irdaDeviceHints1
,
3405 &src
->dev
[i
].hints
[0],
3406 sizeof(dst
->Device
[i
].irdaDeviceHints1
) ) ;
3407 memcpy( &dst
->Device
[i
].irdaDeviceHints2
,
3408 &src
->dev
[i
].hints
[1],
3409 sizeof(dst
->Device
[i
].irdaDeviceHints2
) ) ;
3410 dst
->Device
[i
].irdaCharSet
= src
->dev
[i
].charset
;
3416 FIXME("IrDA optname:0x%x\n", optname
);
3417 return SOCKET_ERROR
;
3419 break; /* case WS_SOL_IRLMP */
3420 #undef MAX_IRDA_DEVICES
3423 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3424 case WS_IPPROTO_TCP
:
3427 case WS_TCP_NODELAY
:
3428 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3429 return SOCKET_ERROR
;
3430 convert_sockopt(&level
, &optname
);
3431 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3433 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3436 release_sock_fd( s
, fd
);
3439 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname
);
3440 return SOCKET_ERROR
;
3445 case WS_IP_ADD_MEMBERSHIP
:
3446 case WS_IP_DROP_MEMBERSHIP
:
3450 case WS_IP_MULTICAST_IF
:
3451 case WS_IP_MULTICAST_LOOP
:
3452 case WS_IP_MULTICAST_TTL
:
3459 #ifdef IP_UNICAST_IF
3460 case WS_IP_UNICAST_IF
:
3462 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3463 return SOCKET_ERROR
;
3464 convert_sockopt(&level
, &optname
);
3465 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3467 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3470 release_sock_fd( s
, fd
);
3472 case WS_IP_DONTFRAGMENT
:
3473 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
3474 *(BOOL
*)optval
= FALSE
;
3477 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname
);
3478 return SOCKET_ERROR
;
3480 case WS_IPPROTO_IPV6
:
3483 #ifdef IPV6_ADD_MEMBERSHIP
3484 case WS_IPV6_ADD_MEMBERSHIP
:
3486 #ifdef IPV6_DROP_MEMBERSHIP
3487 case WS_IPV6_DROP_MEMBERSHIP
:
3489 case WS_IPV6_MULTICAST_IF
:
3490 case WS_IPV6_MULTICAST_HOPS
:
3491 case WS_IPV6_MULTICAST_LOOP
:
3492 case WS_IPV6_UNICAST_HOPS
:
3493 case WS_IPV6_V6ONLY
:
3494 #ifdef IPV6_UNICAST_IF
3495 case WS_IPV6_UNICAST_IF
:
3497 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3498 return SOCKET_ERROR
;
3499 convert_sockopt(&level
, &optname
);
3500 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3502 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3505 release_sock_fd( s
, fd
);
3507 case WS_IPV6_DONTFRAG
:
3508 FIXME("WS_IPV6_DONTFRAG is always false!\n");
3509 *(BOOL
*)optval
= FALSE
;
3512 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname
);
3513 return SOCKET_ERROR
;
3516 WARN("Unknown level: 0x%08x\n", level
);
3517 SetLastError(WSAEINVAL
);
3518 return SOCKET_ERROR
;
3519 } /* end switch(level) */
3522 /***********************************************************************
3525 WS_u_long WINAPI
WS_htonl(WS_u_long hostlong
)
3527 return htonl(hostlong
);
3531 /***********************************************************************
3534 WS_u_short WINAPI
WS_htons(WS_u_short hostshort
)
3536 return htons(hostshort
);
3539 /***********************************************************************
3540 * WSAHtonl (WS2_32.46)
3541 * From MSDN description of error codes, this function should also
3542 * check if WinSock has been initialized and the socket is a valid
3543 * socket. But why? This function only translates a host byte order
3544 * u_long into a network byte order u_long...
3546 int WINAPI
WSAHtonl(SOCKET s
, WS_u_long hostlong
, WS_u_long
*lpnetlong
)
3550 *lpnetlong
= htonl(hostlong
);
3553 WSASetLastError(WSAEFAULT
);
3554 return SOCKET_ERROR
;
3557 /***********************************************************************
3558 * WSAHtons (WS2_32.47)
3559 * From MSDN description of error codes, this function should also
3560 * check if WinSock has been initialized and the socket is a valid
3561 * socket. But why? This function only translates a host byte order
3562 * u_short into a network byte order u_short...
3564 int WINAPI
WSAHtons(SOCKET s
, WS_u_short hostshort
, WS_u_short
*lpnetshort
)
3569 *lpnetshort
= htons(hostshort
);
3572 WSASetLastError(WSAEFAULT
);
3573 return SOCKET_ERROR
;
3577 /***********************************************************************
3578 * inet_addr (WS2_32.11)
3580 WS_u_long WINAPI
WS_inet_addr(const char *cp
)
3582 if (!cp
) return INADDR_NONE
;
3583 return inet_addr(cp
);
3587 /***********************************************************************
3590 WS_u_long WINAPI
WS_ntohl(WS_u_long netlong
)
3592 return ntohl(netlong
);
3596 /***********************************************************************
3599 WS_u_short WINAPI
WS_ntohs(WS_u_short netshort
)
3601 return ntohs(netshort
);
3605 /***********************************************************************
3606 * inet_ntoa (WS2_32.12)
3608 char* WINAPI
WS_inet_ntoa(struct WS_in_addr in
)
3610 char* s
= inet_ntoa(*((struct in_addr
*)&in
));
3613 struct per_thread_data
*data
= get_per_thread_data();
3614 strcpy(data
->ntoa_buffer
, s
);
3615 return data
->ntoa_buffer
;
3617 SetLastError(wsaErrno());
3621 static const char *debugstr_wsaioctl(DWORD ioctl
)
3623 const char *buf_type
, *family
;
3625 switch(ioctl
& 0x18000000)
3630 case WS_IOC_PROTOCOL
:
3631 family
= "IOC_PROTOCOL";
3634 family
= "IOC_VENDOR";
3636 default: /* WS_IOC_UNIX */
3638 BYTE size
= (ioctl
>> 16) & WS_IOCPARM_MASK
;
3639 char x
= (ioctl
& 0xff00) >> 8;
3640 BYTE y
= ioctl
& 0xff;
3643 switch (ioctl
& (WS_IOC_VOID
|WS_IOC_INOUT
))
3647 sprintf(args
, "%d, %d", x
, y
);
3651 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
3655 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
3659 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
3662 return wine_dbg_sprintf("%s(%s)", buf_type
, args
);
3666 /* We are different from WS_IOC_UNIX. */
3667 switch (ioctl
& (WS_IOC_VOID
|WS_IOC_INOUT
))
3670 buf_type
= "_WSAIO";
3673 buf_type
= "_WSAIORW";
3676 buf_type
= "_WSAIOW";
3679 buf_type
= "_WSAIOR";
3686 return wine_dbg_sprintf("%s(%s, %d)", buf_type
, family
,
3687 (USHORT
)(ioctl
& 0xffff));
3690 /* do an ioctl call through the server */
3691 static DWORD
server_ioctl_sock( SOCKET s
, DWORD code
, LPVOID in_buff
, DWORD in_size
,
3692 LPVOID out_buff
, DWORD out_size
, LPDWORD ret_size
,
3693 LPWSAOVERLAPPED overlapped
,
3694 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
3696 HANDLE event
= overlapped
? overlapped
->hEvent
: 0;
3697 HANDLE handle
= SOCKET2HANDLE( s
);
3698 struct ws2_async
*wsa
;
3700 PIO_STATUS_BLOCK io
;
3702 if (!(wsa
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wsa
) )))
3703 return WSA_NOT_ENOUGH_MEMORY
;
3704 wsa
->hSocket
= handle
;
3705 wsa
->user_overlapped
= overlapped
;
3706 wsa
->completion_func
= completion
;
3707 io
= (overlapped
? (PIO_STATUS_BLOCK
)overlapped
: &wsa
->local_iosb
);
3709 status
= NtDeviceIoControlFile( handle
, event
, (PIO_APC_ROUTINE
)ws2_async_apc
, wsa
, io
, code
,
3710 in_buff
, in_size
, out_buff
, out_size
);
3711 if (status
== STATUS_NOT_SUPPORTED
)
3713 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
3714 code
, code
>> 16, (code
>> 14) & 3, (code
>> 2) & 0xfff, code
& 3);
3716 else if (status
== STATUS_SUCCESS
)
3717 *ret_size
= io
->Information
; /* "Information" is the size written to the output buffer */
3719 if (status
!= STATUS_PENDING
) RtlFreeHeap( GetProcessHeap(), 0, wsa
);
3721 return NtStatusToWSAError( status
);
3724 /**********************************************************************
3725 * WSAIoctl (WS2_32.50)
3728 INT WINAPI
WSAIoctl(SOCKET s
, DWORD code
, LPVOID in_buff
, DWORD in_size
, LPVOID out_buff
,
3729 DWORD out_size
, LPDWORD ret_size
, LPWSAOVERLAPPED overlapped
,
3730 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
3733 DWORD status
= 0, total
= 0;
3735 TRACE("%ld, %s, %p, %d, %p, %d, %p, %p, %p\n",
3736 s
, debugstr_wsaioctl(code
), in_buff
, in_size
, out_buff
, out_size
, ret_size
, overlapped
, completion
);
3741 if (in_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(in_buff
))
3743 WSASetLastError(WSAEFAULT
);
3744 return SOCKET_ERROR
;
3746 TRACE("-> FIONBIO (%x)\n", *(WS_u_long
*)in_buff
);
3747 if (_get_sock_mask(s
))
3749 /* AsyncSelect()'ed sockets are always nonblocking */
3750 if (!*(WS_u_long
*)in_buff
) status
= WSAEINVAL
;
3753 if (*(WS_u_long
*)in_buff
)
3754 _enable_event(SOCKET2HANDLE(s
), 0, FD_WINE_NONBLOCKING
, 0);
3756 _enable_event(SOCKET2HANDLE(s
), 0, 0, FD_WINE_NONBLOCKING
);
3761 if (out_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(out_buff
))
3763 WSASetLastError(WSAEFAULT
);
3764 return SOCKET_ERROR
;
3766 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
3767 if (ioctl(fd
, FIONREAD
, out_buff
) == -1)
3768 status
= (errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno();
3769 release_sock_fd( s
, fd
);
3775 unsigned int oob
= 0, atmark
= 0;
3776 socklen_t oobsize
= sizeof(int);
3777 if (out_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(out_buff
))
3779 WSASetLastError(WSAEFAULT
);
3780 return SOCKET_ERROR
;
3782 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
3783 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
3784 if ((getsockopt(fd
, SOL_SOCKET
, SO_OOBINLINE
, &oob
, &oobsize
) == -1)
3785 || (!oob
&& ioctl(fd
, SIOCATMARK
, &atmark
) == -1))
3786 status
= (errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno();
3789 /* The SIOCATMARK value read from ioctl() is reversed
3790 * because BSD returns TRUE if it's in the OOB mark
3791 * while Windows returns TRUE if there are NO OOB bytes.
3793 (*(WS_u_long
*) out_buff
) = oob
| !atmark
;
3796 release_sock_fd( s
, fd
);
3801 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
3802 SetLastError(WSAEINVAL
);
3803 return SOCKET_ERROR
;
3805 case WS_SIO_GET_INTERFACE_LIST
:
3807 INTERFACE_INFO
* intArray
= out_buff
;
3808 DWORD size
, numInt
= 0, apiReturn
;
3810 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
3812 if (!out_buff
|| !ret_size
)
3814 WSASetLastError(WSAEFAULT
);
3815 return SOCKET_ERROR
;
3818 fd
= get_sock_fd( s
, 0, NULL
);
3819 if (fd
== -1) return SOCKET_ERROR
;
3821 apiReturn
= GetAdaptersInfo(NULL
, &size
);
3822 if (apiReturn
== ERROR_BUFFER_OVERFLOW
)
3824 PIP_ADAPTER_INFO table
= HeapAlloc(GetProcessHeap(),0,size
);
3828 if (GetAdaptersInfo(table
, &size
) == NO_ERROR
)
3830 PIP_ADAPTER_INFO ptr
;
3832 for (ptr
= table
, numInt
= 0; ptr
; ptr
= ptr
->Next
)
3834 unsigned int addr
, mask
, bcast
;
3835 struct ifreq ifInfo
;
3837 /* Skip interfaces without an IPv4 address. */
3838 if (ptr
->IpAddressList
.IpAddress
.String
[0] == '\0')
3841 if ((numInt
+ 1)*sizeof(INTERFACE_INFO
)/sizeof(IP_ADAPTER_INFO
) > out_size
)
3843 WARN("Buffer too small = %u, out_size = %u\n", numInt
+ 1, out_size
);
3848 /* Socket Status Flags */
3849 lstrcpynA(ifInfo
.ifr_name
, ptr
->AdapterName
, IFNAMSIZ
);
3850 if (ioctl(fd
, SIOCGIFFLAGS
, &ifInfo
) < 0)
3852 ERR("Error obtaining status flags for socket!\n");
3858 /* set flags; the values of IFF_* are not the same
3859 under Linux and Windows, therefore must generate
3861 intArray
->iiFlags
= 0;
3862 if (ifInfo
.ifr_flags
& IFF_BROADCAST
)
3863 intArray
->iiFlags
|= WS_IFF_BROADCAST
;
3864 #ifdef IFF_POINTOPOINT
3865 if (ifInfo
.ifr_flags
& IFF_POINTOPOINT
)
3866 intArray
->iiFlags
|= WS_IFF_POINTTOPOINT
;
3868 if (ifInfo
.ifr_flags
& IFF_LOOPBACK
)
3869 intArray
->iiFlags
|= WS_IFF_LOOPBACK
;
3870 if (ifInfo
.ifr_flags
& IFF_UP
)
3871 intArray
->iiFlags
|= WS_IFF_UP
;
3872 if (ifInfo
.ifr_flags
& IFF_MULTICAST
)
3873 intArray
->iiFlags
|= WS_IFF_MULTICAST
;
3876 addr
= inet_addr(ptr
->IpAddressList
.IpAddress
.String
);
3877 mask
= inet_addr(ptr
->IpAddressList
.IpMask
.String
);
3878 bcast
= addr
| ~mask
;
3879 intArray
->iiAddress
.AddressIn
.sin_family
= AF_INET
;
3880 intArray
->iiAddress
.AddressIn
.sin_port
= 0;
3881 intArray
->iiAddress
.AddressIn
.sin_addr
.WS_s_addr
=
3883 intArray
->iiNetmask
.AddressIn
.sin_family
= AF_INET
;
3884 intArray
->iiNetmask
.AddressIn
.sin_port
= 0;
3885 intArray
->iiNetmask
.AddressIn
.sin_addr
.WS_s_addr
=
3887 intArray
->iiBroadcastAddress
.AddressIn
.sin_family
=
3889 intArray
->iiBroadcastAddress
.AddressIn
.sin_port
= 0;
3890 intArray
->iiBroadcastAddress
.AddressIn
.sin_addr
.
3898 ERR("Unable to get interface table!\n");
3901 HeapFree(GetProcessHeap(),0,table
);
3903 else status
= WSAEINVAL
;
3905 else if (apiReturn
!= ERROR_NO_DATA
)
3907 ERR("Unable to get interface table!\n");
3910 /* Calculate the size of the array being returned */
3911 total
= sizeof(INTERFACE_INFO
) * numInt
;
3912 release_sock_fd( s
, fd
);
3916 case WS_SIO_ADDRESS_LIST_QUERY
:
3920 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
3924 WSASetLastError(WSAEFAULT
);
3925 return SOCKET_ERROR
;
3928 if (GetAdaptersInfo(NULL
, &size
) == ERROR_BUFFER_OVERFLOW
)
3930 IP_ADAPTER_INFO
*p
, *table
= HeapAlloc(GetProcessHeap(), 0, size
);
3933 if (!table
|| GetAdaptersInfo(table
, &size
))
3935 HeapFree(GetProcessHeap(), 0, table
);
3940 for (p
= table
, num
= 0; p
; p
= p
->Next
)
3941 if (p
->IpAddressList
.IpAddress
.String
[0]) num
++;
3943 total
= sizeof(SOCKET_ADDRESS_LIST
) + sizeof(SOCKET_ADDRESS
) * (num
- 1);
3944 total
+= sizeof(SOCKADDR
) * num
;
3946 if (total
> out_size
)
3948 HeapFree(GetProcessHeap(), 0, table
);
3957 SOCKET_ADDRESS_LIST
*sa_list
= out_buff
;
3958 SOCKADDR_IN
*sockaddr
;
3960 sa
= sa_list
->Address
;
3961 sockaddr
= (SOCKADDR_IN
*)((char *)sa
+ num
* sizeof(SOCKET_ADDRESS
));
3962 sa_list
->iAddressCount
= num
;
3964 for (p
= table
, i
= 0; p
; p
= p
->Next
)
3966 if (!p
->IpAddressList
.IpAddress
.String
[0]) continue;
3968 sa
[i
].lpSockaddr
= (SOCKADDR
*)&sockaddr
[i
];
3969 sa
[i
].iSockaddrLength
= sizeof(SOCKADDR
);
3971 sockaddr
[i
].sin_family
= AF_INET
;
3972 sockaddr
[i
].sin_port
= 0;
3973 sockaddr
[i
].sin_addr
.WS_s_addr
= inet_addr(p
->IpAddressList
.IpAddress
.String
);
3978 HeapFree(GetProcessHeap(), 0, table
);
3982 WARN("unable to get IP address list\n");
3989 FIXME("SIO_FLUSH: stub.\n");
3992 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER
:
3994 static const GUID connectex_guid
= WSAID_CONNECTEX
;
3995 static const GUID disconnectex_guid
= WSAID_DISCONNECTEX
;
3996 static const GUID acceptex_guid
= WSAID_ACCEPTEX
;
3997 static const GUID getaccepexsockaddrs_guid
= WSAID_GETACCEPTEXSOCKADDRS
;
3998 static const GUID transmitfile_guid
= WSAID_TRANSMITFILE
;
3999 static const GUID transmitpackets_guid
= WSAID_TRANSMITPACKETS
;
4000 static const GUID wsarecvmsg_guid
= WSAID_WSARECVMSG
;
4001 static const GUID wsasendmsg_guid
= WSAID_WSASENDMSG
;
4003 if ( IsEqualGUID(&connectex_guid
, in_buff
) )
4005 *(LPFN_CONNECTEX
*)out_buff
= WS2_ConnectEx
;
4008 else if ( IsEqualGUID(&disconnectex_guid
, in_buff
) )
4010 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
4012 else if ( IsEqualGUID(&acceptex_guid
, in_buff
) )
4014 *(LPFN_ACCEPTEX
*)out_buff
= WS2_AcceptEx
;
4017 else if ( IsEqualGUID(&getaccepexsockaddrs_guid
, in_buff
) )
4019 *(LPFN_GETACCEPTEXSOCKADDRS
*)out_buff
= WS2_GetAcceptExSockaddrs
;
4022 else if ( IsEqualGUID(&transmitfile_guid
, in_buff
) )
4024 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
4026 else if ( IsEqualGUID(&transmitpackets_guid
, in_buff
) )
4028 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
4030 else if ( IsEqualGUID(&wsarecvmsg_guid
, in_buff
) )
4032 *(LPFN_WSARECVMSG
*)out_buff
= WS2_WSARecvMsg
;
4035 else if ( IsEqualGUID(&wsasendmsg_guid
, in_buff
) )
4037 *(LPFN_WSASENDMSG
*)out_buff
= WSASendMsg
;
4041 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff
));
4043 status
= WSAEOPNOTSUPP
;
4046 case WS_SIO_KEEPALIVE_VALS
:
4048 struct tcp_keepalive
*k
;
4049 int keepalive
, keepidle
, keepintvl
;
4051 if (!in_buff
|| in_size
< sizeof(struct tcp_keepalive
))
4053 WSASetLastError(WSAEFAULT
);
4054 return SOCKET_ERROR
;
4058 keepalive
= k
->onoff
? 1 : 0;
4059 keepidle
= max( 1, (k
->keepalivetime
+ 500) / 1000 );
4060 keepintvl
= max( 1, (k
->keepaliveinterval
+ 500) / 1000 );
4062 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive
, keepidle
, keepintvl
);
4064 fd
= get_sock_fd(s
, 0, NULL
);
4065 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&keepalive
, sizeof(int)) == -1)
4067 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
4068 /* these values need to be set only if SO_KEEPALIVE is enabled */
4071 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPIDLE
, (void *)&keepidle
, sizeof(int)) == -1)
4073 else if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPINTVL
, (void *)&keepintvl
, sizeof(int)) == -1)
4078 FIXME("ignoring keepalive interval and timeout\n");
4080 release_sock_fd(s
, fd
);
4083 case WS_SIO_ROUTING_INTERFACE_QUERY
:
4085 struct WS_sockaddr
*daddr
= (struct WS_sockaddr
*)in_buff
;
4086 struct WS_sockaddr_in
*daddr_in
= (struct WS_sockaddr_in
*)daddr
;
4087 struct WS_sockaddr_in
*saddr_in
= out_buff
;
4088 MIB_IPFORWARDROW row
;
4089 PMIB_IPADDRTABLE ipAddrTable
= NULL
;
4090 DWORD size
, i
, found_index
;
4092 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4094 if (!in_buff
|| in_size
< sizeof(struct WS_sockaddr
) ||
4095 !out_buff
|| out_size
< sizeof(struct WS_sockaddr_in
) || !ret_size
)
4097 WSASetLastError(WSAEFAULT
);
4098 return SOCKET_ERROR
;
4100 if (daddr
->sa_family
!= AF_INET
)
4102 FIXME("unsupported address family %d\n", daddr
->sa_family
);
4103 status
= WSAEAFNOSUPPORT
;
4106 if (GetBestRoute(daddr_in
->sin_addr
.S_un
.S_addr
, 0, &row
) != NOERROR
||
4107 GetIpAddrTable(NULL
, &size
, FALSE
) != ERROR_INSUFFICIENT_BUFFER
)
4112 ipAddrTable
= HeapAlloc(GetProcessHeap(), 0, size
);
4113 if (GetIpAddrTable(ipAddrTable
, &size
, FALSE
))
4115 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
4119 for (i
= 0, found_index
= ipAddrTable
->dwNumEntries
;
4120 i
< ipAddrTable
->dwNumEntries
; i
++)
4122 if (ipAddrTable
->table
[i
].dwIndex
== row
.dwForwardIfIndex
)
4125 if (found_index
== ipAddrTable
->dwNumEntries
)
4127 ERR("no matching IP address for interface %d\n",
4128 row
.dwForwardIfIndex
);
4129 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
4133 saddr_in
->sin_family
= AF_INET
;
4134 saddr_in
->sin_addr
.S_un
.S_addr
= ipAddrTable
->table
[found_index
].dwAddr
;
4135 saddr_in
->sin_port
= 0;
4136 total
= sizeof(struct WS_sockaddr_in
);
4137 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
4140 case WS_SIO_SET_COMPATIBILITY_MODE
:
4141 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4142 status
= WSAEOPNOTSUPP
;
4144 case WS_SIO_UDP_CONNRESET
:
4145 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4147 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4148 WSASetLastError(WSAEOPNOTSUPP
);
4149 return SOCKET_ERROR
;
4151 status
= WSAEOPNOTSUPP
;
4155 if (status
== WSAEOPNOTSUPP
)
4157 status
= server_ioctl_sock(s
, code
, in_buff
, in_size
, out_buff
, out_size
, &total
,
4158 overlapped
, completion
);
4159 if (status
!= WSAEOPNOTSUPP
)
4161 if (status
== 0 || status
== WSA_IO_PENDING
)
4162 TRACE("-> %s request\n", debugstr_wsaioctl(code
));
4164 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code
), status
);
4166 /* overlapped and completion operations will be handled by the server */
4171 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code
));
4176 FIXME( "completion routine %p not supported\n", completion
);
4178 else if (overlapped
)
4180 ULONG_PTR cvalue
= (overlapped
&& ((ULONG_PTR
)overlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)overlapped
: 0;
4181 overlapped
->Internal
= status
;
4182 overlapped
->InternalHigh
= total
;
4183 if (overlapped
->hEvent
) NtSetEvent( overlapped
->hEvent
, NULL
);
4184 if (cvalue
) WS_AddCompletion( HANDLE2SOCKET(s
), cvalue
, status
, total
);
4189 if (ret_size
) *ret_size
= total
;
4192 SetLastError( status
);
4193 return SOCKET_ERROR
;
4197 /***********************************************************************
4198 * ioctlsocket (WS2_32.10)
4200 int WINAPI
WS_ioctlsocket(SOCKET s
, LONG cmd
, WS_u_long
*argp
)
4203 return WSAIoctl( s
, cmd
, argp
, sizeof(WS_u_long
), argp
, sizeof(WS_u_long
), &ret_size
, NULL
, NULL
);
4206 /***********************************************************************
4207 * listen (WS2_32.13)
4209 int WINAPI
WS_listen(SOCKET s
, int backlog
)
4211 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
), ret
= SOCKET_ERROR
;
4213 TRACE("socket %04lx, backlog %d\n", s
, backlog
);
4216 union generic_unix_sockaddr uaddr
;
4217 socklen_t uaddrlen
= sizeof(uaddr
);
4219 if (getsockname(fd
, &uaddr
.addr
, &uaddrlen
) != 0)
4221 SetLastError(wsaErrno());
4223 else if (!is_sockaddr_bound(&uaddr
.addr
, uaddrlen
))
4225 SetLastError(WSAEINVAL
);
4227 else if (listen(fd
, backlog
) == 0)
4229 _enable_event(SOCKET2HANDLE(s
), FD_ACCEPT
,
4231 FD_CONNECT
|FD_WINE_CONNECTED
);
4235 SetLastError(wsaErrno());
4236 release_sock_fd( s
, fd
);
4239 SetLastError(WSAENOTSOCK
);
4243 /***********************************************************************
4246 int WINAPI
WS_recv(SOCKET s
, char *buf
, int len
, int flags
)
4248 DWORD n
, dwFlags
= flags
;
4254 if ( WS2_recv_base(s
, &wsabuf
, 1, &n
, &dwFlags
, NULL
, NULL
, NULL
, NULL
, NULL
) == SOCKET_ERROR
)
4255 return SOCKET_ERROR
;
4260 /***********************************************************************
4261 * recvfrom (WS2_32.17)
4263 int WINAPI
WS_recvfrom(SOCKET s
, char *buf
, INT len
, int flags
,
4264 struct WS_sockaddr
*from
, int *fromlen
)
4266 DWORD n
, dwFlags
= flags
;
4272 if ( WS2_recv_base(s
, &wsabuf
, 1, &n
, &dwFlags
, from
, fromlen
, NULL
, NULL
, NULL
) == SOCKET_ERROR
)
4273 return SOCKET_ERROR
;
4278 /* allocate a poll array for the corresponding fd sets */
4279 static struct pollfd
*fd_sets_to_poll( const WS_fd_set
*readfds
, const WS_fd_set
*writefds
,
4280 const WS_fd_set
*exceptfds
, int *count_ptr
)
4282 unsigned int i
, j
= 0, count
= 0;
4285 if (readfds
) count
+= readfds
->fd_count
;
4286 if (writefds
) count
+= writefds
->fd_count
;
4287 if (exceptfds
) count
+= exceptfds
->fd_count
;
4291 SetLastError(WSAEINVAL
);
4294 if (!(fds
= HeapAlloc( GetProcessHeap(), 0, count
* sizeof(fds
[0]))))
4296 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
4300 for (i
= 0; i
< readfds
->fd_count
; i
++, j
++)
4302 fds
[j
].fd
= get_sock_fd( readfds
->fd_array
[i
], FILE_READ_DATA
, NULL
);
4303 if (fds
[j
].fd
== -1) goto failed
;
4304 fds
[j
].events
= POLLIN
;
4308 for (i
= 0; i
< writefds
->fd_count
; i
++, j
++)
4310 fds
[j
].fd
= get_sock_fd( writefds
->fd_array
[i
], FILE_WRITE_DATA
, NULL
);
4311 if (fds
[j
].fd
== -1) goto failed
;
4312 fds
[j
].events
= POLLOUT
;
4316 for (i
= 0; i
< exceptfds
->fd_count
; i
++, j
++)
4318 fds
[j
].fd
= get_sock_fd( exceptfds
->fd_array
[i
], 0, NULL
);
4319 if (fds
[j
].fd
== -1) goto failed
;
4320 fds
[j
].events
= POLLHUP
;
4329 for (i
= 0; i
< readfds
->fd_count
&& j
< count
; i
++, j
++)
4330 release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
4332 for (i
= 0; i
< writefds
->fd_count
&& j
< count
; i
++, j
++)
4333 release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
4335 for (i
= 0; i
< exceptfds
->fd_count
&& j
< count
; i
++, j
++)
4336 release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
4337 HeapFree( GetProcessHeap(), 0, fds
);
4341 /* release the file descriptor obtained in fd_sets_to_poll */
4342 /* must be called with the original fd_set arrays, before calling get_poll_results */
4343 static void release_poll_fds( const WS_fd_set
*readfds
, const WS_fd_set
*writefds
,
4344 const WS_fd_set
*exceptfds
, struct pollfd
*fds
)
4346 unsigned int i
, j
= 0;
4350 for (i
= 0; i
< readfds
->fd_count
; i
++, j
++)
4351 if (fds
[j
].fd
!= -1) release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
4355 for (i
= 0; i
< writefds
->fd_count
; i
++, j
++)
4356 if (fds
[j
].fd
!= -1) release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
4360 for (i
= 0; i
< exceptfds
->fd_count
; i
++, j
++)
4361 if (fds
[j
].fd
!= -1)
4363 /* make sure we have a real error before releasing the fd */
4364 if (!sock_error_p( fds
[j
].fd
)) fds
[j
].revents
= 0;
4365 release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
4370 /* map the poll results back into the Windows fd sets */
4371 static int get_poll_results( WS_fd_set
*readfds
, WS_fd_set
*writefds
, WS_fd_set
*exceptfds
,
4372 const struct pollfd
*fds
)
4374 unsigned int i
, j
= 0, k
, total
= 0;
4378 for (i
= k
= 0; i
< readfds
->fd_count
; i
++, j
++)
4379 if (fds
[j
].revents
) readfds
->fd_array
[k
++] = readfds
->fd_array
[i
];
4380 readfds
->fd_count
= k
;
4385 for (i
= k
= 0; i
< writefds
->fd_count
; i
++, j
++)
4386 if ((fds
[j
].revents
& POLLOUT
) && !(fds
[j
].revents
& POLLHUP
))
4387 writefds
->fd_array
[k
++] = writefds
->fd_array
[i
];
4388 writefds
->fd_count
= k
;
4393 for (i
= k
= 0; i
< exceptfds
->fd_count
; i
++, j
++)
4394 if (fds
[j
].revents
) exceptfds
->fd_array
[k
++] = exceptfds
->fd_array
[i
];
4395 exceptfds
->fd_count
= k
;
4402 /***********************************************************************
4403 * select (WS2_32.18)
4405 int WINAPI
WS_select(int nfds
, WS_fd_set
*ws_readfds
,
4406 WS_fd_set
*ws_writefds
, WS_fd_set
*ws_exceptfds
,
4407 const struct WS_timeval
* ws_timeout
)
4409 struct pollfd
*pollfds
;
4410 struct timeval tv1
, tv2
;
4412 int count
, ret
, timeout
= -1;
4414 TRACE("read %p, write %p, excp %p timeout %p\n",
4415 ws_readfds
, ws_writefds
, ws_exceptfds
, ws_timeout
);
4417 if (!(pollfds
= fd_sets_to_poll( ws_readfds
, ws_writefds
, ws_exceptfds
, &count
)))
4418 return SOCKET_ERROR
;
4422 torig
= (ws_timeout
->tv_sec
* 1000) + (ws_timeout
->tv_usec
+ 999) / 1000;
4424 gettimeofday( &tv1
, 0 );
4427 while ((ret
= poll( pollfds
, count
, timeout
)) < 0)
4431 if (!ws_timeout
) continue;
4432 gettimeofday( &tv2
, 0 );
4434 tv2
.tv_sec
-= tv1
.tv_sec
;
4435 tv2
.tv_usec
-= tv1
.tv_usec
;
4436 if (tv2
.tv_usec
< 0)
4438 tv2
.tv_usec
+= 1000000;
4442 timeout
= torig
- (tv2
.tv_sec
* 1000) - (tv2
.tv_usec
+ 999) / 1000;
4443 if (timeout
<= 0) break;
4446 release_poll_fds( ws_readfds
, ws_writefds
, ws_exceptfds
, pollfds
);
4448 if (ret
== -1) SetLastError(wsaErrno());
4449 else ret
= get_poll_results( ws_readfds
, ws_writefds
, ws_exceptfds
, pollfds
);
4450 HeapFree( GetProcessHeap(), 0, pollfds
);
4454 /* helper to send completion messages for client-only i/o operation case */
4455 static void WS_AddCompletion( SOCKET sock
, ULONG_PTR CompletionValue
, NTSTATUS CompletionStatus
,
4458 SERVER_START_REQ( add_fd_completion
)
4460 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(sock
) );
4461 req
->cvalue
= CompletionValue
;
4462 req
->status
= CompletionStatus
;
4463 req
->information
= Information
;
4464 wine_server_call( req
);
4470 /***********************************************************************
4473 int WINAPI
WS_send(SOCKET s
, const char *buf
, int len
, int flags
)
4479 wsabuf
.buf
= (char*) buf
;
4481 if ( WS2_sendto( s
, &wsabuf
, 1, &n
, flags
, NULL
, 0, NULL
, NULL
) == SOCKET_ERROR
)
4482 return SOCKET_ERROR
;
4487 /***********************************************************************
4488 * WSASend (WS2_32.72)
4490 INT WINAPI
WSASend( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
4491 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
4492 LPWSAOVERLAPPED lpOverlapped
,
4493 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
4495 return WS2_sendto( s
, lpBuffers
, dwBufferCount
, lpNumberOfBytesSent
, dwFlags
,
4496 NULL
, 0, lpOverlapped
, lpCompletionRoutine
);
4499 /***********************************************************************
4500 * WSASendDisconnect (WS2_32.73)
4502 INT WINAPI
WSASendDisconnect( SOCKET s
, LPWSABUF lpBuffers
)
4504 return WS_shutdown( s
, SD_SEND
);
4508 static int WS2_sendto( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
4509 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
4510 const struct WS_sockaddr
*to
, int tolen
,
4511 LPWSAOVERLAPPED lpOverlapped
,
4512 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
4514 unsigned int i
, options
;
4516 struct ws2_async
*wsa
= NULL
;
4517 int totalLength
= 0;
4518 ULONG_PTR cvalue
= (lpOverlapped
&& ((ULONG_PTR
)lpOverlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)lpOverlapped
: 0;
4522 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
4523 s
, lpBuffers
, dwBufferCount
, dwFlags
,
4524 to
, tolen
, lpOverlapped
, lpCompletionRoutine
);
4526 fd
= get_sock_fd( s
, FILE_WRITE_DATA
, &options
);
4527 TRACE( "fd=%d, options=%x\n", fd
, options
);
4529 if ( fd
== -1 ) return SOCKET_ERROR
;
4531 if (!lpOverlapped
&& !lpNumberOfBytesSent
)
4536 if (!(wsa
= HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async
, iovec
[dwBufferCount
]) )))
4542 wsa
->hSocket
= SOCKET2HANDLE(s
);
4543 wsa
->addr
= (struct WS_sockaddr
*)to
;
4544 wsa
->addrlen
.val
= tolen
;
4545 wsa
->flags
= dwFlags
;
4546 wsa
->lpFlags
= &wsa
->flags
;
4547 wsa
->control
= NULL
;
4548 wsa
->n_iovecs
= dwBufferCount
;
4549 wsa
->first_iovec
= 0;
4550 for ( i
= 0; i
< dwBufferCount
; i
++ )
4552 wsa
->iovec
[i
].iov_base
= lpBuffers
[i
].buf
;
4553 wsa
->iovec
[i
].iov_len
= lpBuffers
[i
].len
;
4554 totalLength
+= lpBuffers
[i
].len
;
4559 n
= WS2_send( fd
, wsa
);
4560 if (n
!= -1 || errno
!= EINTR
) break;
4562 if (n
== -1 && errno
!= EAGAIN
)
4568 if ((lpOverlapped
|| lpCompletionRoutine
) &&
4569 !(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
)))
4571 IO_STATUS_BLOCK
*iosb
= lpOverlapped
? (IO_STATUS_BLOCK
*)lpOverlapped
: &wsa
->local_iosb
;
4573 wsa
->user_overlapped
= lpOverlapped
;
4574 wsa
->completion_func
= lpCompletionRoutine
;
4575 release_sock_fd( s
, fd
);
4577 if (n
== -1 || n
< totalLength
)
4579 iosb
->u
.Status
= STATUS_PENDING
;
4580 iosb
->Information
= n
== -1 ? 0 : n
;
4582 SERVER_START_REQ( register_async
)
4584 req
->type
= ASYNC_TYPE_WRITE
;
4585 req
->async
.handle
= wine_server_obj_handle( wsa
->hSocket
);
4586 req
->async
.callback
= wine_server_client_ptr( WS2_async_send
);
4587 req
->async
.iosb
= wine_server_client_ptr( iosb
);
4588 req
->async
.arg
= wine_server_client_ptr( wsa
);
4589 req
->async
.event
= wine_server_obj_handle( lpCompletionRoutine
? 0 : lpOverlapped
->hEvent
);
4590 req
->async
.cvalue
= cvalue
;
4591 err
= wine_server_call( req
);
4595 /* Enable the event only after starting the async. The server will deliver it as soon as
4596 the async is done. */
4597 _enable_event(SOCKET2HANDLE(s
), FD_WRITE
, 0, 0);
4599 if (err
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
4600 WSASetLastError( NtStatusToWSAError( err
));
4601 return SOCKET_ERROR
;
4604 iosb
->u
.Status
= STATUS_SUCCESS
;
4605 iosb
->Information
= n
;
4606 if (lpNumberOfBytesSent
) *lpNumberOfBytesSent
= n
;
4607 if (!wsa
->completion_func
)
4609 if (cvalue
) WS_AddCompletion( s
, cvalue
, STATUS_SUCCESS
, n
);
4610 if (lpOverlapped
->hEvent
) SetEvent( lpOverlapped
->hEvent
);
4611 HeapFree( GetProcessHeap(), 0, wsa
);
4613 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC
)ws2_async_apc
,
4614 (ULONG_PTR
)wsa
, (ULONG_PTR
)iosb
, 0 );
4619 if ((err
= _is_blocking( s
, &is_blocking
)))
4621 err
= NtStatusToWSAError( err
);
4627 /* On a blocking non-overlapped stream socket,
4628 * sending blocks until the entire buffer is sent. */
4629 DWORD timeout_start
= GetTickCount();
4631 bytes_sent
= n
== -1 ? 0 : n
;
4633 while (wsa
->first_iovec
< wsa
->n_iovecs
)
4636 int timeout
= GET_SNDTIMEO(fd
);
4640 timeout
-= GetTickCount() - timeout_start
;
4641 if (timeout
< 0) timeout
= 0;
4645 pfd
.events
= POLLOUT
;
4647 if (!timeout
|| !poll( &pfd
, 1, timeout
))
4650 goto error
; /* msdn says a timeout in send is fatal */
4653 n
= WS2_send( fd
, wsa
);
4654 if (n
== -1 && errno
!= EAGAIN
&& errno
!= EINTR
)
4664 else /* non-blocking */
4666 if (n
< totalLength
)
4667 _enable_event(SOCKET2HANDLE(s
), FD_WRITE
, 0, 0);
4670 err
= WSAEWOULDBLOCK
;
4676 TRACE(" -> %i bytes\n", bytes_sent
);
4678 if (lpNumberOfBytesSent
) *lpNumberOfBytesSent
= bytes_sent
;
4679 HeapFree( GetProcessHeap(), 0, wsa
);
4680 release_sock_fd( s
, fd
);
4685 HeapFree( GetProcessHeap(), 0, wsa
);
4686 release_sock_fd( s
, fd
);
4687 WARN(" -> ERROR %d\n", err
);
4688 WSASetLastError(err
);
4689 return SOCKET_ERROR
;
4692 /***********************************************************************
4693 * WSASendTo (WS2_32.74)
4695 INT WINAPI
WSASendTo( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
4696 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
4697 const struct WS_sockaddr
*to
, int tolen
,
4698 LPWSAOVERLAPPED lpOverlapped
,
4699 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
4701 return WS2_sendto( s
, lpBuffers
, dwBufferCount
,
4702 lpNumberOfBytesSent
, dwFlags
,
4704 lpOverlapped
, lpCompletionRoutine
);
4707 /***********************************************************************
4708 * sendto (WS2_32.20)
4710 int WINAPI
WS_sendto(SOCKET s
, const char *buf
, int len
, int flags
,
4711 const struct WS_sockaddr
*to
, int tolen
)
4717 wsabuf
.buf
= (char*) buf
;
4719 if ( WS2_sendto(s
, &wsabuf
, 1, &n
, flags
, to
, tolen
, NULL
, NULL
) == SOCKET_ERROR
)
4720 return SOCKET_ERROR
;
4725 /***********************************************************************
4726 * setsockopt (WS2_32.21)
4728 int WINAPI
WS_setsockopt(SOCKET s
, int level
, int optname
,
4729 const char *optval
, int optlen
)
4733 struct linger linger
;
4734 struct timeval tval
;
4736 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
4737 s
, level
, optname
, optval
, optlen
);
4739 /* some broken apps pass the value directly instead of a pointer to it */
4740 if(optlen
&& IS_INTRESOURCE(optval
))
4742 SetLastError(WSAEFAULT
);
4743 return SOCKET_ERROR
;
4751 /* Some options need some conversion before they can be sent to
4752 * setsockopt. The conversions are done here, then they will fall though
4753 * to the general case. Special options that are not passed to
4754 * setsockopt follow below that.*/
4756 case WS_SO_DONTLINGER
:
4759 SetLastError(WSAEFAULT
);
4760 return SOCKET_ERROR
;
4762 linger
.l_onoff
= *(const int*)optval
== 0;
4763 linger
.l_linger
= 0;
4765 optname
= SO_LINGER
;
4766 optval
= (char*)&linger
;
4767 optlen
= sizeof(struct linger
);
4773 SetLastError(WSAEFAULT
);
4774 return SOCKET_ERROR
;
4776 linger
.l_onoff
= ((LINGER
*)optval
)->l_onoff
;
4777 linger
.l_linger
= ((LINGER
*)optval
)->l_linger
;
4779 optname
= SO_LINGER
;
4780 optval
= (char*)&linger
;
4781 optlen
= sizeof(struct linger
);
4785 if (*(const int*)optval
< 2048)
4787 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval
);
4792 /* The options listed here don't need any special handling. Thanks to
4793 * the conversion happening above, options from there will fall through
4795 case WS_SO_ACCEPTCONN
:
4796 case WS_SO_BROADCAST
:
4798 case WS_SO_KEEPALIVE
:
4799 case WS_SO_OOBINLINE
:
4800 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
4801 * however, using it the BSD way fixes bug 8513 and seems to be what
4802 * most programmers assume, anyway */
4803 case WS_SO_REUSEADDR
:
4806 convert_sockopt(&level
, &optname
);
4809 /* SO_DEBUG is a privileged operation, ignore it. */
4811 TRACE("Ignoring SO_DEBUG\n");
4814 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
4815 * socket. According to MSDN, this option is silently ignored.*/
4816 case WS_SO_DONTROUTE
:
4817 TRACE("Ignoring SO_DONTROUTE\n");
4820 /* Stops two sockets from being bound to the same port. Always happens
4821 * on unix systems, so just drop it. */
4822 case WS_SO_EXCLUSIVEADDRUSE
:
4823 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
4826 /* After a ConnectEx call succeeds, the socket can't be used with half of the
4827 * normal winsock functions on windows. We don't have that problem. */
4828 case WS_SO_UPDATE_CONNECT_CONTEXT
:
4829 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
4832 /* After a AcceptEx call succeeds, the socket can't be used with half of the
4833 * normal winsock functions on windows. We don't have that problem. */
4834 case WS_SO_UPDATE_ACCEPT_CONTEXT
:
4835 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
4838 /* SO_OPENTYPE does not require a valid socket handle. */
4839 case WS_SO_OPENTYPE
:
4840 if (!optlen
|| optlen
< sizeof(int) || !optval
)
4842 SetLastError(WSAEFAULT
);
4843 return SOCKET_ERROR
;
4845 get_per_thread_data()->opentype
= *(const int *)optval
;
4846 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval
) );
4850 case WS_SO_RCVTIMEO
:
4853 case WS_SO_SNDTIMEO
:
4855 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
4856 if (optval
&& optlen
== sizeof(UINT32
)) {
4857 /* WinSock passes milliseconds instead of struct timeval */
4858 tval
.tv_usec
= (*(const UINT32
*)optval
% 1000) * 1000;
4859 tval
.tv_sec
= *(const UINT32
*)optval
/ 1000;
4860 /* min of 500 milliseconds */
4861 if (tval
.tv_sec
== 0 && tval
.tv_usec
&& tval
.tv_usec
< 500000)
4862 tval
.tv_usec
= 500000;
4863 optlen
= sizeof(struct timeval
);
4864 optval
= (char*)&tval
;
4865 } else if (optlen
== sizeof(struct timeval
)) {
4866 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen
);
4868 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen
);
4871 convert_sockopt(&level
, &optname
);
4876 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname
);
4877 SetLastError(WSAENOPROTOOPT
);
4878 return SOCKET_ERROR
;
4880 break; /* case WS_SOL_SOCKET */
4883 case WS_NSPROTO_IPX
:
4887 return set_ipx_packettype(s
, *(int*)optval
);
4889 case IPX_FILTERPTYPE
:
4890 /* Sets the receive filter packet type, at the moment we don't support it */
4891 FIXME("IPX_FILTERPTYPE: %x\n", *optval
);
4892 /* Returning 0 is better for now than returning a SOCKET_ERROR */
4896 FIXME("opt_name:%x\n", optname
);
4897 return SOCKET_ERROR
;
4899 break; /* case WS_NSPROTO_IPX */
4902 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4903 case WS_IPPROTO_TCP
:
4906 case WS_TCP_NODELAY
:
4907 convert_sockopt(&level
, &optname
);
4910 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname
);
4911 return SOCKET_ERROR
;
4918 case WS_IP_ADD_MEMBERSHIP
:
4919 case WS_IP_DROP_MEMBERSHIP
:
4923 case WS_IP_MULTICAST_IF
:
4924 case WS_IP_MULTICAST_LOOP
:
4925 case WS_IP_MULTICAST_TTL
:
4932 #ifdef IP_UNICAST_IF
4933 case WS_IP_UNICAST_IF
:
4935 convert_sockopt(&level
, &optname
);
4937 case WS_IP_DONTFRAGMENT
:
4938 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
4941 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname
);
4942 return SOCKET_ERROR
;
4946 case WS_IPPROTO_IPV6
:
4949 #ifdef IPV6_ADD_MEMBERSHIP
4950 case WS_IPV6_ADD_MEMBERSHIP
:
4952 #ifdef IPV6_DROP_MEMBERSHIP
4953 case WS_IPV6_DROP_MEMBERSHIP
:
4955 case WS_IPV6_MULTICAST_IF
:
4956 case WS_IPV6_MULTICAST_HOPS
:
4957 case WS_IPV6_MULTICAST_LOOP
:
4958 case WS_IPV6_UNICAST_HOPS
:
4959 case WS_IPV6_V6ONLY
:
4960 #ifdef IPV6_UNICAST_IF
4961 case WS_IPV6_UNICAST_IF
:
4963 convert_sockopt(&level
, &optname
);
4965 case WS_IPV6_DONTFRAG
:
4966 FIXME("IPV6_DONTFRAG is silently ignored!\n");
4968 case WS_IPV6_PROTECTION_LEVEL
:
4969 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
4972 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname
);
4973 return SOCKET_ERROR
;
4978 WARN("Unknown level: 0x%08x\n", level
);
4979 SetLastError(WSAEINVAL
);
4980 return SOCKET_ERROR
;
4981 } /* end switch(level) */
4983 /* avoid endianness issues if argument is a 16-bit int */
4984 if (optval
&& optlen
< sizeof(int))
4986 woptval
= *((const INT16
*) optval
);
4987 optval
= (char*) &woptval
;
4990 fd
= get_sock_fd( s
, 0, NULL
);
4991 if (fd
== -1) return SOCKET_ERROR
;
4993 if (setsockopt(fd
, level
, optname
, optval
, optlen
) == 0)
4996 if (level
== SOL_SOCKET
&& optname
== SO_REUSEADDR
&&
4997 setsockopt(fd
, level
, SO_REUSEPORT
, optval
, optlen
) != 0)
4999 SetLastError(wsaErrno());
5000 release_sock_fd( s
, fd
);
5001 return SOCKET_ERROR
;
5004 release_sock_fd( s
, fd
);
5007 TRACE("Setting socket error, %d\n", wsaErrno());
5008 SetLastError(wsaErrno());
5009 release_sock_fd( s
, fd
);
5011 return SOCKET_ERROR
;
5014 /***********************************************************************
5015 * shutdown (WS2_32.22)
5017 int WINAPI
WS_shutdown(SOCKET s
, int how
)
5019 int fd
, err
= WSAENOTSOCK
;
5020 unsigned int options
, clear_flags
= 0;
5022 fd
= get_sock_fd( s
, 0, &options
);
5023 TRACE("socket %04lx, how %i %x\n", s
, how
, options
);
5026 return SOCKET_ERROR
;
5030 case 0: /* drop receives */
5031 clear_flags
|= FD_READ
;
5033 case 1: /* drop sends */
5034 clear_flags
|= FD_WRITE
;
5036 case 2: /* drop all */
5037 clear_flags
|= FD_READ
|FD_WRITE
;
5040 clear_flags
|= FD_WINE_LISTENING
;
5043 if (!(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
)))
5048 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_READ
);
5051 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_WRITE
);
5055 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_READ
);
5056 if (!err
) err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_WRITE
);
5059 if (err
) goto error
;
5061 else /* non-overlapped mode */
5063 if ( shutdown( fd
, how
) )
5070 release_sock_fd( s
, fd
);
5071 _enable_event( SOCKET2HANDLE(s
), 0, 0, clear_flags
);
5072 if ( how
> 1) WSAAsyncSelect( s
, 0, 0, 0 );
5076 release_sock_fd( s
, fd
);
5077 _enable_event( SOCKET2HANDLE(s
), 0, 0, clear_flags
);
5078 WSASetLastError( err
);
5079 return SOCKET_ERROR
;
5082 /***********************************************************************
5083 * socket (WS2_32.23)
5085 SOCKET WINAPI
WS_socket(int af
, int type
, int protocol
)
5087 TRACE("af=%d type=%d protocol=%d\n", af
, type
, protocol
);
5089 return WSASocketA( af
, type
, protocol
, NULL
, 0,
5090 get_per_thread_data()->opentype
? 0 : WSA_FLAG_OVERLAPPED
);
5094 /***********************************************************************
5095 * gethostbyaddr (WS2_32.51)
5097 struct WS_hostent
* WINAPI
WS_gethostbyaddr(const char *addr
, int len
, int type
)
5099 struct WS_hostent
*retval
= NULL
;
5100 struct hostent
* host
;
5101 int unixtype
= convert_af_w2u(type
);
5102 const char *paddr
= addr
;
5103 unsigned long loopback
;
5104 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5106 int ebufsize
= 1024;
5107 struct hostent hostentry
;
5108 int locerr
= ENOBUFS
;
5111 /* convert back the magic loopback address if necessary */
5112 if (unixtype
== AF_INET
&& len
== 4 && !memcmp(addr
, magic_loopback_addr
, 4))
5114 loopback
= htonl(INADDR_LOOPBACK
);
5115 paddr
= (char*) &loopback
;
5118 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5120 extrabuf
=HeapAlloc(GetProcessHeap(),0,ebufsize
) ;
5122 int res
= gethostbyaddr_r(paddr
, len
, unixtype
,
5123 &hostentry
, extrabuf
, ebufsize
, &host
, &locerr
);
5124 if (res
!= ERANGE
) break;
5126 extrabuf
=HeapReAlloc(GetProcessHeap(),0,extrabuf
,ebufsize
) ;
5128 if (host
) retval
= WS_dup_he(host
);
5129 else SetLastError((locerr
< 0) ? wsaErrno() : wsaHerrno(locerr
));
5130 HeapFree(GetProcessHeap(),0,extrabuf
);
5132 EnterCriticalSection( &csWSgetXXXbyYYY
);
5133 host
= gethostbyaddr(paddr
, len
, unixtype
);
5134 if (host
) retval
= WS_dup_he(host
);
5135 else SetLastError((h_errno
< 0) ? wsaErrno() : wsaHerrno(h_errno
));
5136 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5138 TRACE("ptr %p, len %d, type %d ret %p\n", addr
, len
, type
, retval
);
5142 /***********************************************************************
5143 * WS_get_local_ips (INTERNAL)
5145 * Returns the list of local IP addresses by going through the network
5146 * adapters and using the local routing table to sort the addresses
5147 * from highest routing priority to lowest routing priority. This
5148 * functionality is inferred from the description for obtaining local
5149 * IP addresses given in the Knowledge Base Article Q160215.
5151 * Please note that the returned hostent is only freed when the thread
5152 * closes and is replaced if another hostent is requested.
5154 static struct WS_hostent
* WS_get_local_ips( char *hostname
)
5156 int last_metric
, numroutes
= 0, i
, j
;
5158 PIP_ADAPTER_INFO adapters
= NULL
, k
;
5159 struct WS_hostent
*hostlist
= NULL
;
5160 PMIB_IPFORWARDTABLE routes
= NULL
;
5161 struct route
*route_addrs
= NULL
;
5162 DWORD adap_size
, route_size
;
5164 /* Obtain the size of the adapter list and routing table, also allocate memory */
5165 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
5167 if (GetIpForwardTable(NULL
, &route_size
, FALSE
) != ERROR_INSUFFICIENT_BUFFER
)
5169 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
5170 routes
= HeapAlloc(GetProcessHeap(), 0, route_size
);
5171 route_addrs
= HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
5172 if (adapters
== NULL
|| routes
== NULL
|| route_addrs
== NULL
)
5174 /* Obtain the adapter list and the full routing table */
5175 if (GetAdaptersInfo(adapters
, &adap_size
) != NO_ERROR
)
5177 if (GetIpForwardTable(routes
, &route_size
, FALSE
) != NO_ERROR
)
5179 /* Store the interface associated with each route */
5180 for (n
= 0; n
< routes
->dwNumEntries
; n
++)
5184 BOOL exists
= FALSE
;
5186 if (routes
->table
[n
].u1
.ForwardType
!= MIB_IPROUTE_TYPE_DIRECT
)
5188 ifindex
= routes
->table
[n
].dwForwardIfIndex
;
5189 ifmetric
= routes
->table
[n
].dwForwardMetric1
;
5190 /* Only store the lowest valued metric for an interface */
5191 for (j
= 0; j
< numroutes
; j
++)
5193 if (route_addrs
[j
].interface
== ifindex
)
5195 if (route_addrs
[j
].metric
> ifmetric
)
5196 route_addrs
[j
].metric
= ifmetric
;
5202 route_addrs
= HeapReAlloc(GetProcessHeap(), 0, route_addrs
, (numroutes
+1)*sizeof(struct route
));
5203 if (route_addrs
== NULL
)
5204 goto cleanup
; /* Memory allocation error, fail gracefully */
5205 route_addrs
[numroutes
].interface
= ifindex
;
5206 route_addrs
[numroutes
].metric
= ifmetric
;
5207 /* If no IP is found in the next step (for whatever reason)
5208 * then fall back to the magic loopback address.
5210 memcpy(&(route_addrs
[numroutes
].addr
.s_addr
), magic_loopback_addr
, 4);
5214 goto cleanup
; /* No routes, fall back to the Magic IP */
5215 /* Find the IP address associated with each found interface */
5216 for (i
= 0; i
< numroutes
; i
++)
5218 for (k
= adapters
; k
!= NULL
; k
= k
->Next
)
5220 char *ip
= k
->IpAddressList
.IpAddress
.String
;
5222 if (route_addrs
[i
].interface
== k
->Index
)
5223 route_addrs
[i
].addr
.s_addr
= (in_addr_t
) inet_addr(ip
);
5226 /* Allocate a hostent and enough memory for all the IPs,
5227 * including the NULL at the end of the list.
5229 hostlist
= WS_create_he(hostname
, 1, 0, numroutes
+1, sizeof(struct in_addr
));
5230 if (hostlist
== NULL
)
5231 goto cleanup
; /* Failed to allocate a hostent for the list of IPs */
5232 hostlist
->h_addr_list
[numroutes
] = NULL
; /* NULL-terminate the address list */
5233 hostlist
->h_aliases
[0] = NULL
; /* NULL-terminate the alias list */
5234 hostlist
->h_addrtype
= AF_INET
;
5235 hostlist
->h_length
= sizeof(struct in_addr
); /* = 4 */
5236 /* Reorder the entries when placing them in the host list, Windows expects
5237 * the IP list in order from highest priority to lowest (the critical thing
5238 * is that most applications expect the first IP to be the default route).
5241 for (i
= 0; i
< numroutes
; i
++)
5243 struct in_addr addr
;
5244 int metric
= 0xFFFF;
5246 memcpy(&addr
, magic_loopback_addr
, 4);
5247 for (j
= 0; j
< numroutes
; j
++)
5249 int this_metric
= route_addrs
[j
].metric
;
5251 if (this_metric
> last_metric
&& this_metric
< metric
)
5253 addr
= route_addrs
[j
].addr
;
5254 metric
= this_metric
;
5257 last_metric
= metric
;
5258 (*(struct in_addr
*) hostlist
->h_addr_list
[i
]) = addr
;
5261 /* Cleanup all allocated memory except the address list,
5262 * the address list is used by the calling app.
5265 HeapFree(GetProcessHeap(), 0, route_addrs
);
5266 HeapFree(GetProcessHeap(), 0, adapters
);
5267 HeapFree(GetProcessHeap(), 0, routes
);
5271 /***********************************************************************
5272 * gethostbyname (WS2_32.52)
5274 struct WS_hostent
* WINAPI
WS_gethostbyname(const char* name
)
5276 struct WS_hostent
*retval
= NULL
;
5277 struct hostent
* host
;
5278 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5281 struct hostent hostentry
;
5282 int locerr
= ENOBUFS
;
5286 SetLastError(WSANOTINITIALISED
);
5289 if( gethostname( hostname
, 100) == -1) {
5290 SetLastError( WSAENOBUFS
); /* appropriate ? */
5293 if( !name
|| !name
[0]) {
5296 /* If the hostname of the local machine is requested then return the
5297 * complete list of local IP addresses */
5298 if(strcmp(name
, hostname
) == 0)
5299 retval
= WS_get_local_ips(hostname
);
5300 /* If any other hostname was requested (or the routing table lookup failed)
5301 * then return the IP found by the host OS */
5304 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5306 extrabuf
=HeapAlloc(GetProcessHeap(),0,ebufsize
) ;
5308 int res
= gethostbyname_r(name
, &hostentry
, extrabuf
, ebufsize
, &host
, &locerr
);
5309 if( res
!= ERANGE
) break;
5311 extrabuf
=HeapReAlloc(GetProcessHeap(),0,extrabuf
,ebufsize
) ;
5313 if (!host
) SetLastError((locerr
< 0) ? wsaErrno() : wsaHerrno(locerr
));
5315 EnterCriticalSection( &csWSgetXXXbyYYY
);
5316 host
= gethostbyname(name
);
5317 if (!host
) SetLastError((h_errno
< 0) ? wsaErrno() : wsaHerrno(h_errno
));
5319 if (host
) retval
= WS_dup_he(host
);
5320 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5321 HeapFree(GetProcessHeap(),0,extrabuf
);
5323 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5326 if (retval
&& retval
->h_addr_list
[0][0] == 127 &&
5327 strcmp(name
, "localhost") != 0)
5329 /* hostname != "localhost" but has loopback address. replace by our
5330 * special address.*/
5331 memcpy(retval
->h_addr_list
[0], magic_loopback_addr
, 4);
5333 TRACE( "%s ret %p\n", debugstr_a(name
), retval
);
5338 /***********************************************************************
5339 * getprotobyname (WS2_32.53)
5341 struct WS_protoent
* WINAPI
WS_getprotobyname(const char* name
)
5343 struct WS_protoent
* retval
= NULL
;
5344 #ifdef HAVE_GETPROTOBYNAME
5345 struct protoent
* proto
;
5346 EnterCriticalSection( &csWSgetXXXbyYYY
);
5347 if( (proto
= getprotobyname(name
)) != NULL
)
5349 retval
= WS_dup_pe(proto
);
5352 MESSAGE("protocol %s not found; You might want to add "
5353 "this to /etc/protocols\n", debugstr_a(name
) );
5354 SetLastError(WSANO_DATA
);
5356 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5358 TRACE( "%s ret %p\n", debugstr_a(name
), retval
);
5363 /***********************************************************************
5364 * getprotobynumber (WS2_32.54)
5366 struct WS_protoent
* WINAPI
WS_getprotobynumber(int number
)
5368 struct WS_protoent
* retval
= NULL
;
5369 #ifdef HAVE_GETPROTOBYNUMBER
5370 struct protoent
* proto
;
5371 EnterCriticalSection( &csWSgetXXXbyYYY
);
5372 if( (proto
= getprotobynumber(number
)) != NULL
)
5374 retval
= WS_dup_pe(proto
);
5377 MESSAGE("protocol number %d not found; You might want to add "
5378 "this to /etc/protocols\n", number
);
5379 SetLastError(WSANO_DATA
);
5381 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5383 TRACE("%i ret %p\n", number
, retval
);
5388 /***********************************************************************
5389 * getservbyname (WS2_32.55)
5391 struct WS_servent
* WINAPI
WS_getservbyname(const char *name
, const char *proto
)
5393 struct WS_servent
* retval
= NULL
;
5394 struct servent
* serv
;
5396 char *proto_str
= NULL
;
5398 if (!(name_str
= strdup_lower(name
))) return NULL
;
5400 if (proto
&& *proto
)
5402 if (!(proto_str
= strdup_lower(proto
)))
5404 HeapFree( GetProcessHeap(), 0, name_str
);
5409 EnterCriticalSection( &csWSgetXXXbyYYY
);
5410 serv
= getservbyname(name_str
, proto_str
);
5413 retval
= WS_dup_se(serv
);
5415 else SetLastError(WSANO_DATA
);
5416 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5417 HeapFree( GetProcessHeap(), 0, proto_str
);
5418 HeapFree( GetProcessHeap(), 0, name_str
);
5419 TRACE( "%s, %s ret %p\n", debugstr_a(name
), debugstr_a(proto
), retval
);
5423 /***********************************************************************
5424 * freeaddrinfo (WS2_32.@)
5426 void WINAPI
WS_freeaddrinfo(struct WS_addrinfo
*res
)
5429 struct WS_addrinfo
*next
;
5431 HeapFree(GetProcessHeap(),0,res
->ai_canonname
);
5432 HeapFree(GetProcessHeap(),0,res
->ai_addr
);
5433 next
= res
->ai_next
;
5434 HeapFree(GetProcessHeap(),0,res
);
5439 /* helper functions for getaddrinfo()/getnameinfo() */
5440 static int convert_aiflag_w2u(int winflags
) {
5444 for (i
=0;i
<sizeof(ws_aiflag_map
)/sizeof(ws_aiflag_map
[0]);i
++)
5445 if (ws_aiflag_map
[i
][0] & winflags
) {
5446 unixflags
|= ws_aiflag_map
[i
][1];
5447 winflags
&= ~ws_aiflag_map
[i
][0];
5450 FIXME("Unhandled windows AI_xxx flags %x\n", winflags
);
5454 static int convert_niflag_w2u(int winflags
) {
5458 for (i
=0;i
<sizeof(ws_niflag_map
)/sizeof(ws_niflag_map
[0]);i
++)
5459 if (ws_niflag_map
[i
][0] & winflags
) {
5460 unixflags
|= ws_niflag_map
[i
][1];
5461 winflags
&= ~ws_niflag_map
[i
][0];
5464 FIXME("Unhandled windows NI_xxx flags %x\n", winflags
);
5468 static int convert_aiflag_u2w(int unixflags
) {
5472 for (i
=0;i
<sizeof(ws_aiflag_map
)/sizeof(ws_aiflag_map
[0]);i
++)
5473 if (ws_aiflag_map
[i
][1] & unixflags
) {
5474 winflags
|= ws_aiflag_map
[i
][0];
5475 unixflags
&= ~ws_aiflag_map
[i
][1];
5477 if (unixflags
) /* will warn usually */
5478 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags
);
5482 static int convert_eai_u2w(int unixret
) {
5485 if (!unixret
) return 0;
5487 for (i
=0;ws_eai_map
[i
][0];i
++)
5488 if (ws_eai_map
[i
][1] == unixret
)
5489 return ws_eai_map
[i
][0];
5491 if (unixret
== EAI_SYSTEM
)
5492 /* There are broken versions of glibc which return EAI_SYSTEM
5493 * and set errno to 0 instead of returning EAI_NONAME.
5495 return errno
? sock_get_error( errno
) : WS_EAI_NONAME
;
5497 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret
);
5501 static char *get_hostname(void)
5506 GetComputerNameExA( ComputerNamePhysicalDnsHostname
, NULL
, &size
);
5507 if (GetLastError() != ERROR_MORE_DATA
) return NULL
;
5508 if (!(ret
= HeapAlloc( GetProcessHeap(), 0, size
))) return NULL
;
5509 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname
, ret
, &size
))
5511 HeapFree( GetProcessHeap(), 0, ret
);
5517 /***********************************************************************
5518 * getaddrinfo (WS2_32.@)
5520 int WINAPI
WS_getaddrinfo(LPCSTR nodename
, LPCSTR servname
, const struct WS_addrinfo
*hints
, struct WS_addrinfo
**res
)
5522 #ifdef HAVE_GETADDRINFO
5523 struct addrinfo
*unixaires
= NULL
;
5525 struct addrinfo unixhints
, *punixhints
= NULL
;
5526 char *hostname
= NULL
;
5530 if (!nodename
&& !servname
) return WSAHOST_NOT_FOUND
;
5534 else if (!nodename
[0])
5536 node
= hostname
= get_hostname();
5537 if (!node
) return WSA_NOT_ENOUGH_MEMORY
;
5542 /* servname tweak required by OSX and BSD kernels */
5543 if (servname
&& !servname
[0]) servname
= "0";
5546 punixhints
= &unixhints
;
5548 memset(&unixhints
, 0, sizeof(unixhints
));
5549 punixhints
->ai_flags
= convert_aiflag_w2u(hints
->ai_flags
);
5551 /* zero is a wildcard, no need to convert */
5552 if (hints
->ai_family
)
5553 punixhints
->ai_family
= convert_af_w2u(hints
->ai_family
);
5554 if (hints
->ai_socktype
)
5555 punixhints
->ai_socktype
= convert_socktype_w2u(hints
->ai_socktype
);
5556 if (hints
->ai_protocol
)
5557 punixhints
->ai_protocol
= max(convert_proto_w2u(hints
->ai_protocol
), 0);
5559 if (punixhints
->ai_socktype
< 0)
5561 WSASetLastError(WSAESOCKTNOSUPPORT
);
5562 HeapFree(GetProcessHeap(), 0, hostname
);
5563 return SOCKET_ERROR
;
5566 /* windows allows invalid combinations of socket type and protocol, unix does not.
5567 * fix the parameters here to make getaddrinfo call always work */
5568 if (punixhints
->ai_protocol
== IPPROTO_TCP
&&
5569 punixhints
->ai_socktype
!= SOCK_STREAM
&& punixhints
->ai_socktype
!= SOCK_SEQPACKET
)
5570 punixhints
->ai_socktype
= 0;
5572 else if (punixhints
->ai_protocol
== IPPROTO_UDP
&& punixhints
->ai_socktype
!= SOCK_DGRAM
)
5573 punixhints
->ai_socktype
= 0;
5575 else if (IS_IPX_PROTO(punixhints
->ai_protocol
) && punixhints
->ai_socktype
!= SOCK_DGRAM
)
5576 punixhints
->ai_socktype
= 0;
5579 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
5580 result
= getaddrinfo(node
, servname
, punixhints
, &unixaires
);
5582 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename
), debugstr_a(servname
), hints
, res
, result
);
5583 HeapFree(GetProcessHeap(), 0, hostname
);
5586 struct addrinfo
*xuai
= unixaires
;
5587 struct WS_addrinfo
**xai
= res
;
5591 struct WS_addrinfo
*ai
= HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY
, sizeof(struct WS_addrinfo
));
5597 *xai
= ai
;xai
= &ai
->ai_next
;
5598 ai
->ai_flags
= convert_aiflag_u2w(xuai
->ai_flags
);
5599 ai
->ai_family
= convert_af_u2w(xuai
->ai_family
);
5600 /* copy whatever was sent in the hints */
5602 ai
->ai_socktype
= hints
->ai_socktype
;
5603 ai
->ai_protocol
= hints
->ai_protocol
;
5605 ai
->ai_socktype
= convert_socktype_u2w(xuai
->ai_socktype
);
5606 ai
->ai_protocol
= convert_proto_u2w(xuai
->ai_protocol
);
5608 if (xuai
->ai_canonname
) {
5609 TRACE("canon name - %s\n",debugstr_a(xuai
->ai_canonname
));
5610 ai
->ai_canonname
= HeapAlloc(GetProcessHeap(),0,strlen(xuai
->ai_canonname
)+1);
5611 if (!ai
->ai_canonname
)
5613 strcpy(ai
->ai_canonname
,xuai
->ai_canonname
);
5615 len
= xuai
->ai_addrlen
;
5616 ai
->ai_addr
= HeapAlloc(GetProcessHeap(),0,len
);
5619 ai
->ai_addrlen
= len
;
5621 int winlen
= ai
->ai_addrlen
;
5623 if (!ws_sockaddr_u2ws(xuai
->ai_addr
, ai
->ai_addr
, &winlen
)) {
5624 ai
->ai_addrlen
= winlen
;
5628 ai
->ai_addr
= HeapReAlloc(GetProcessHeap(),0,ai
->ai_addr
,len
);
5631 ai
->ai_addrlen
= len
;
5633 xuai
= xuai
->ai_next
;
5635 freeaddrinfo(unixaires
);
5637 if (TRACE_ON(winsock
))
5639 struct WS_addrinfo
*ai
= *res
;
5642 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
5643 ai
, ai
->ai_flags
, ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
, ai
->ai_addrlen
,
5644 ai
->ai_canonname
, debugstr_sockaddr(ai
->ai_addr
));
5649 result
= convert_eai_u2w(result
);
5654 if (*res
) WS_freeaddrinfo(*res
);
5655 if (unixaires
) freeaddrinfo(unixaires
);
5656 return WSA_NOT_ENOUGH_MEMORY
;
5658 FIXME("getaddrinfo() failed, not found during buildtime.\n");
5663 static struct WS_addrinfoW
*addrinfo_AtoW(const struct WS_addrinfo
*ai
)
5665 struct WS_addrinfoW
*ret
;
5667 if (!(ret
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW
)))) return NULL
;
5668 ret
->ai_flags
= ai
->ai_flags
;
5669 ret
->ai_family
= ai
->ai_family
;
5670 ret
->ai_socktype
= ai
->ai_socktype
;
5671 ret
->ai_protocol
= ai
->ai_protocol
;
5672 ret
->ai_addrlen
= ai
->ai_addrlen
;
5673 ret
->ai_canonname
= NULL
;
5674 ret
->ai_addr
= NULL
;
5675 ret
->ai_next
= NULL
;
5676 if (ai
->ai_canonname
)
5678 int len
= MultiByteToWideChar(CP_ACP
, 0, ai
->ai_canonname
, -1, NULL
, 0);
5679 if (!(ret
->ai_canonname
= HeapAlloc(GetProcessHeap(), 0, len
)))
5681 HeapFree(GetProcessHeap(), 0, ret
);
5684 MultiByteToWideChar(CP_ACP
, 0, ai
->ai_canonname
, -1, ret
->ai_canonname
, len
);
5688 if (!(ret
->ai_addr
= HeapAlloc(GetProcessHeap(), 0, ai
->ai_addrlen
)))
5690 HeapFree(GetProcessHeap(), 0, ret
->ai_canonname
);
5691 HeapFree(GetProcessHeap(), 0, ret
);
5694 memcpy(ret
->ai_addr
, ai
->ai_addr
, ai
->ai_addrlen
);
5699 static struct WS_addrinfoW
*addrinfo_list_AtoW(const struct WS_addrinfo
*info
)
5701 struct WS_addrinfoW
*ret
, *infoW
;
5703 if (!(ret
= infoW
= addrinfo_AtoW(info
))) return NULL
;
5704 while (info
->ai_next
)
5706 if (!(infoW
->ai_next
= addrinfo_AtoW(info
->ai_next
)))
5711 infoW
= infoW
->ai_next
;
5712 info
= info
->ai_next
;
5717 static struct WS_addrinfo
*addrinfo_WtoA(const struct WS_addrinfoW
*ai
)
5719 struct WS_addrinfo
*ret
;
5721 if (!(ret
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo
)))) return NULL
;
5722 ret
->ai_flags
= ai
->ai_flags
;
5723 ret
->ai_family
= ai
->ai_family
;
5724 ret
->ai_socktype
= ai
->ai_socktype
;
5725 ret
->ai_protocol
= ai
->ai_protocol
;
5726 ret
->ai_addrlen
= ai
->ai_addrlen
;
5727 ret
->ai_canonname
= NULL
;
5728 ret
->ai_addr
= NULL
;
5729 ret
->ai_next
= NULL
;
5730 if (ai
->ai_canonname
)
5732 int len
= WideCharToMultiByte(CP_ACP
, 0, ai
->ai_canonname
, -1, NULL
, 0, NULL
, NULL
);
5733 if (!(ret
->ai_canonname
= HeapAlloc(GetProcessHeap(), 0, len
)))
5735 HeapFree(GetProcessHeap(), 0, ret
);
5738 WideCharToMultiByte(CP_ACP
, 0, ai
->ai_canonname
, -1, ret
->ai_canonname
, len
, NULL
, NULL
);
5742 if (!(ret
->ai_addr
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr
))))
5744 HeapFree(GetProcessHeap(), 0, ret
->ai_canonname
);
5745 HeapFree(GetProcessHeap(), 0, ret
);
5748 memcpy(ret
->ai_addr
, ai
->ai_addr
, sizeof(struct WS_sockaddr
));
5753 /***********************************************************************
5754 * GetAddrInfoW (WS2_32.@)
5756 int WINAPI
GetAddrInfoW(LPCWSTR nodename
, LPCWSTR servname
, const ADDRINFOW
*hints
, PADDRINFOW
*res
)
5759 char *nodenameA
= NULL
, *servnameA
= NULL
;
5760 struct WS_addrinfo
*resA
, *hintsA
= NULL
;
5765 len
= WideCharToMultiByte(CP_ACP
, 0, nodename
, -1, NULL
, 0, NULL
, NULL
);
5766 if (!(nodenameA
= HeapAlloc(GetProcessHeap(), 0, len
))) return EAI_MEMORY
;
5767 WideCharToMultiByte(CP_ACP
, 0, nodename
, -1, nodenameA
, len
, NULL
, NULL
);
5771 len
= WideCharToMultiByte(CP_ACP
, 0, servname
, -1, NULL
, 0, NULL
, NULL
);
5772 if (!(servnameA
= HeapAlloc(GetProcessHeap(), 0, len
)))
5774 HeapFree(GetProcessHeap(), 0, nodenameA
);
5777 WideCharToMultiByte(CP_ACP
, 0, servname
, -1, servnameA
, len
, NULL
, NULL
);
5780 if (hints
) hintsA
= addrinfo_WtoA(hints
);
5781 ret
= WS_getaddrinfo(nodenameA
, servnameA
, hintsA
, &resA
);
5782 WS_freeaddrinfo(hintsA
);
5786 *res
= addrinfo_list_AtoW(resA
);
5787 WS_freeaddrinfo(resA
);
5790 HeapFree(GetProcessHeap(), 0, nodenameA
);
5791 HeapFree(GetProcessHeap(), 0, servnameA
);
5795 /***********************************************************************
5796 * FreeAddrInfoW (WS2_32.@)
5798 void WINAPI
FreeAddrInfoW(PADDRINFOW ai
)
5803 HeapFree(GetProcessHeap(), 0, ai
->ai_canonname
);
5804 HeapFree(GetProcessHeap(), 0, ai
->ai_addr
);
5806 HeapFree(GetProcessHeap(), 0, ai
);
5811 int WINAPI
WS_getnameinfo(const SOCKADDR
*sa
, WS_socklen_t salen
, PCHAR host
,
5812 DWORD hostlen
, PCHAR serv
, DWORD servlen
, INT flags
)
5814 #ifdef HAVE_GETNAMEINFO
5816 union generic_unix_sockaddr sa_u
;
5819 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa
), salen
, host
, hostlen
,
5820 serv
, servlen
, flags
);
5822 size
= ws_sockaddr_ws2u(sa
, salen
, &sa_u
);
5825 WSASetLastError(WSAEFAULT
);
5826 return WSA_NOT_ENOUGH_MEMORY
;
5828 ret
= getnameinfo(&sa_u
.addr
, size
, host
, hostlen
, serv
, servlen
, convert_niflag_w2u(flags
));
5829 return convert_eai_u2w(ret
);
5831 FIXME("getnameinfo() failed, not found during buildtime.\n");
5836 int WINAPI
GetNameInfoW(const SOCKADDR
*sa
, WS_socklen_t salen
, PWCHAR host
,
5837 DWORD hostlen
, PWCHAR serv
, DWORD servlen
, INT flags
)
5840 char *hostA
= NULL
, *servA
= NULL
;
5842 if (host
&& (!(hostA
= HeapAlloc(GetProcessHeap(), 0, hostlen
)))) return EAI_MEMORY
;
5843 if (serv
&& (!(servA
= HeapAlloc(GetProcessHeap(), 0, servlen
))))
5845 HeapFree(GetProcessHeap(), 0, hostA
);
5849 ret
= WS_getnameinfo(sa
, salen
, hostA
, hostlen
, servA
, servlen
, flags
);
5852 if (host
) MultiByteToWideChar(CP_ACP
, 0, hostA
, -1, host
, hostlen
);
5853 if (serv
) MultiByteToWideChar(CP_ACP
, 0, servA
, -1, serv
, servlen
);
5856 HeapFree(GetProcessHeap(), 0, hostA
);
5857 HeapFree(GetProcessHeap(), 0, servA
);
5861 /***********************************************************************
5862 * getservbyport (WS2_32.56)
5864 struct WS_servent
* WINAPI
WS_getservbyport(int port
, const char *proto
)
5866 struct WS_servent
* retval
= NULL
;
5867 #ifdef HAVE_GETSERVBYPORT
5868 struct servent
* serv
;
5869 char *proto_str
= NULL
;
5871 if (proto
&& *proto
)
5873 if (!(proto_str
= strdup_lower(proto
))) return NULL
;
5875 EnterCriticalSection( &csWSgetXXXbyYYY
);
5876 if( (serv
= getservbyport(port
, proto_str
)) != NULL
) {
5877 retval
= WS_dup_se(serv
);
5879 else SetLastError(WSANO_DATA
);
5880 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5881 HeapFree( GetProcessHeap(), 0, proto_str
);
5883 TRACE("%d (i.e. port %d), %s ret %p\n", port
, (int)ntohl(port
), debugstr_a(proto
), retval
);
5888 /***********************************************************************
5889 * gethostname (WS2_32.57)
5891 int WINAPI
WS_gethostname(char *name
, int namelen
)
5893 TRACE("name %p, len %d\n", name
, namelen
);
5895 if (gethostname(name
, namelen
) == 0)
5897 TRACE("<- '%s'\n", name
);
5900 SetLastError((errno
== EINVAL
) ? WSAEFAULT
: wsaErrno());
5901 TRACE("<- ERROR !\n");
5902 return SOCKET_ERROR
;
5906 /* ------------------------------------- Windows sockets extensions -- *
5908 * ------------------------------------------------------------------- */
5910 /***********************************************************************
5911 * WSAEnumNetworkEvents (WS2_32.36)
5913 int WINAPI
WSAEnumNetworkEvents(SOCKET s
, WSAEVENT hEvent
, LPWSANETWORKEVENTS lpEvent
)
5917 int errors
[FD_MAX_EVENTS
];
5919 TRACE("%08lx, hEvent %p, lpEvent %p\n", s
, hEvent
, lpEvent
);
5921 SERVER_START_REQ( get_socket_event
)
5923 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
5924 req
->service
= TRUE
;
5925 req
->c_event
= wine_server_obj_handle( hEvent
);
5926 wine_server_set_reply( req
, errors
, sizeof(errors
) );
5927 if (!(ret
= wine_server_call(req
))) lpEvent
->lNetworkEvents
= reply
->pmask
& reply
->mask
;
5932 for (i
= 0; i
< FD_MAX_EVENTS
; i
++)
5933 lpEvent
->iErrorCode
[i
] = NtStatusToWSAError(errors
[i
]);
5936 SetLastError(WSAEINVAL
);
5937 return SOCKET_ERROR
;
5940 /***********************************************************************
5941 * WSAEventSelect (WS2_32.39)
5943 int WINAPI
WSAEventSelect(SOCKET s
, WSAEVENT hEvent
, LONG lEvent
)
5947 TRACE("%08lx, hEvent %p, event %08x\n", s
, hEvent
, lEvent
);
5949 SERVER_START_REQ( set_socket_event
)
5951 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
5953 req
->event
= wine_server_obj_handle( hEvent
);
5956 ret
= wine_server_call( req
);
5960 SetLastError(WSAEINVAL
);
5961 return SOCKET_ERROR
;
5964 /**********************************************************************
5965 * WSAGetOverlappedResult (WS2_32.40)
5967 BOOL WINAPI
WSAGetOverlappedResult( SOCKET s
, LPWSAOVERLAPPED lpOverlapped
,
5968 LPDWORD lpcbTransfer
, BOOL fWait
,
5973 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
5974 s
, lpOverlapped
, lpcbTransfer
, fWait
, lpdwFlags
);
5976 if ( lpOverlapped
== NULL
)
5978 ERR( "Invalid pointer\n" );
5979 WSASetLastError(WSA_INVALID_PARAMETER
);
5983 status
= lpOverlapped
->Internal
;
5984 if (status
== STATUS_PENDING
)
5988 SetLastError( WSA_IO_INCOMPLETE
);
5992 if (WaitForSingleObject( lpOverlapped
->hEvent
? lpOverlapped
->hEvent
: SOCKET2HANDLE(s
),
5993 INFINITE
) == WAIT_FAILED
)
5995 status
= lpOverlapped
->Internal
;
5999 *lpcbTransfer
= lpOverlapped
->InternalHigh
;
6002 *lpdwFlags
= lpOverlapped
->u
.s
.Offset
;
6004 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
6009 /***********************************************************************
6010 * WSAAsyncSelect (WS2_32.101)
6012 INT WINAPI
WSAAsyncSelect(SOCKET s
, HWND hWnd
, UINT uMsg
, LONG lEvent
)
6016 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s
, hWnd
, uMsg
, lEvent
);
6018 SERVER_START_REQ( set_socket_event
)
6020 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
6023 req
->window
= wine_server_user_handle( hWnd
);
6025 ret
= wine_server_call( req
);
6029 SetLastError(WSAEINVAL
);
6030 return SOCKET_ERROR
;
6033 /***********************************************************************
6034 * WSACreateEvent (WS2_32.31)
6037 WSAEVENT WINAPI
WSACreateEvent(void)
6039 /* Create a manual-reset event, with initial state: unsignaled */
6042 return CreateEventW(NULL
, TRUE
, FALSE
, NULL
);
6045 /***********************************************************************
6046 * WSACloseEvent (WS2_32.29)
6049 BOOL WINAPI
WSACloseEvent(WSAEVENT event
)
6051 TRACE ("event=%p\n", event
);
6053 return CloseHandle(event
);
6056 /***********************************************************************
6057 * WSASocketA (WS2_32.78)
6060 SOCKET WINAPI
WSASocketA(int af
, int type
, int protocol
,
6061 LPWSAPROTOCOL_INFOA lpProtocolInfo
,
6062 GROUP g
, DWORD dwFlags
)
6065 WSAPROTOCOL_INFOW info
;
6067 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6068 af
, type
, protocol
, lpProtocolInfo
, g
, dwFlags
);
6070 if (!lpProtocolInfo
) return WSASocketW(af
, type
, protocol
, NULL
, g
, dwFlags
);
6072 memcpy(&info
, lpProtocolInfo
, FIELD_OFFSET(WSAPROTOCOL_INFOW
, szProtocol
));
6073 len
= MultiByteToWideChar(CP_ACP
, 0, lpProtocolInfo
->szProtocol
, -1,
6074 info
.szProtocol
, WSAPROTOCOL_LEN
+ 1);
6078 WSASetLastError( WSAEINVAL
);
6079 return SOCKET_ERROR
;
6082 return WSASocketW(af
, type
, protocol
, &info
, g
, dwFlags
);
6085 /***********************************************************************
6086 * WSASocketW (WS2_32.79)
6089 SOCKET WINAPI
WSASocketW(int af
, int type
, int protocol
,
6090 LPWSAPROTOCOL_INFOW lpProtocolInfo
,
6091 GROUP g
, DWORD dwFlags
)
6095 int unixaf
, unixtype
, ipxptype
= -1;
6098 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
6099 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
6102 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6103 af
, type
, protocol
, lpProtocolInfo
, g
, dwFlags
);
6107 err
= WSANOTINITIALISED
;
6111 /* hack for WSADuplicateSocket */
6112 if (lpProtocolInfo
&& lpProtocolInfo
->dwServiceFlags4
== 0xff00ff00) {
6113 ret
= lpProtocolInfo
->dwServiceFlags3
;
6114 TRACE("\tgot duplicate %04lx\n", ret
);
6120 if (af
== FROM_PROTOCOL_INFO
|| !af
)
6121 af
= lpProtocolInfo
->iAddressFamily
;
6122 if (type
== FROM_PROTOCOL_INFO
|| !type
)
6123 type
= lpProtocolInfo
->iSocketType
;
6124 if (protocol
== FROM_PROTOCOL_INFO
|| !protocol
)
6125 protocol
= lpProtocolInfo
->iProtocol
;
6128 if (!type
&& (af
|| protocol
))
6130 int autoproto
= protocol
;
6131 WSAPROTOCOL_INFOW infow
;
6133 /* default to the first valid protocol */
6135 autoproto
= valid_protocols
[0];
6136 else if(IS_IPX_PROTO(autoproto
))
6137 autoproto
= WS_NSPROTO_IPX
;
6139 if (WS_EnterSingleProtocolW(autoproto
, &infow
))
6141 type
= infow
.iSocketType
;
6143 /* after win2003 it's no longer possible to pass AF_UNSPEC
6144 using the protocol info struct */
6145 if (!lpProtocolInfo
&& af
== WS_AF_UNSPEC
)
6146 af
= infow
.iAddressFamily
;
6151 Windows has an extension to the IPX protocol that allows one to create sockets
6152 and set the IPX packet type at the same time, to do that a caller will use
6153 a protocol like NSPROTO_IPX + <PACKET TYPE>
6155 if (IS_IPX_PROTO(protocol
))
6156 ipxptype
= protocol
- WS_NSPROTO_IPX
;
6158 /* convert the socket family, type and protocol */
6159 unixaf
= convert_af_w2u(af
);
6160 unixtype
= convert_socktype_w2u(type
);
6161 protocol
= convert_proto_w2u(protocol
);
6162 if (unixaf
== AF_UNSPEC
) unixaf
= -1;
6164 /* filter invalid parameters */
6167 /* the type could not be converted */
6168 if (type
&& unixtype
< 0)
6170 err
= WSAESOCKTNOSUPPORT
;
6174 err
= WSAEPROTONOSUPPORT
;
6179 /* both family and protocol can't be invalid */
6186 /* family could not be converted and neither socket type */
6187 if (unixtype
< 0 && af
>= 0)
6190 err
= WSAESOCKTNOSUPPORT
;
6194 err
= WSAEAFNOSUPPORT
;
6198 SERVER_START_REQ( create_socket
)
6200 req
->family
= unixaf
;
6201 req
->type
= unixtype
;
6202 req
->protocol
= protocol
;
6203 req
->access
= GENERIC_READ
|GENERIC_WRITE
|SYNCHRONIZE
;
6204 req
->attributes
= OBJ_INHERIT
;
6205 req
->flags
= dwFlags
;
6206 set_error( wine_server_call( req
) );
6207 ret
= HANDLE2SOCKET( wine_server_ptr_handle( reply
->handle
));
6212 TRACE("\tcreated %04lx\n", ret
);
6214 set_ipx_packettype(ret
, ipxptype
);
6218 err
= GetLastError();
6219 if (err
== WSAEACCES
) /* raw socket denied */
6221 if (type
== SOCK_RAW
)
6222 ERR_(winediag
)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
6224 ERR_(winediag
)("Failed to create socket, this requires special permissions.\n");
6228 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
6229 if (err
== WSAEINVAL
)
6230 err
= WSAESOCKTNOSUPPORT
;
6231 else if (err
== WSAEOPNOTSUPP
)
6232 err
= WSAEPROTONOSUPPORT
;
6236 WARN("\t\tfailed, error %d!\n", err
);
6238 return INVALID_SOCKET
;
6241 /***********************************************************************
6242 * WSAJoinLeaf (WS2_32.58)
6245 SOCKET WINAPI
WSAJoinLeaf(
6247 const struct WS_sockaddr
*addr
,
6249 LPWSABUF lpCallerData
,
6250 LPWSABUF lpCalleeData
,
6256 return INVALID_SOCKET
;
6259 /***********************************************************************
6260 * __WSAFDIsSet (WS2_32.151)
6262 int WINAPI
__WSAFDIsSet(SOCKET s
, WS_fd_set
*set
)
6264 int i
= set
->fd_count
;
6266 TRACE("(%ld,%p(%i))\n", s
, set
, i
);
6269 if (set
->fd_array
[i
] == s
) return 1;
6273 /***********************************************************************
6274 * WSAIsBlocking (WS2_32.114)
6276 BOOL WINAPI
WSAIsBlocking(void)
6278 /* By default WinSock should set all its sockets to non-blocking mode
6279 * and poll in PeekMessage loop when processing "blocking" ones. This
6280 * function is supposed to tell if the program is in this loop. Our
6281 * blocking calls are truly blocking so we always return FALSE.
6283 * Note: It is allowed to call this function without prior WSAStartup().
6290 /***********************************************************************
6291 * WSACancelBlockingCall (WS2_32.113)
6293 INT WINAPI
WSACancelBlockingCall(void)
6299 static INT WINAPI
WSA_DefaultBlockingHook( FARPROC x
)
6301 FIXME("How was this called?\n");
6306 /***********************************************************************
6307 * WSASetBlockingHook (WS2_32.109)
6309 FARPROC WINAPI
WSASetBlockingHook(FARPROC lpBlockFunc
)
6311 FARPROC prev
= blocking_hook
;
6312 blocking_hook
= lpBlockFunc
;
6313 TRACE("hook %p\n", lpBlockFunc
);
6318 /***********************************************************************
6319 * WSAUnhookBlockingHook (WS2_32.110)
6321 INT WINAPI
WSAUnhookBlockingHook(void)
6323 blocking_hook
= (FARPROC
)WSA_DefaultBlockingHook
;
6328 /* ----------------------------------- end of API stuff */
6330 /* ----------------------------------- helper functions -
6332 * TODO: Merge WS_dup_..() stuff into one function that
6333 * would operate with a generic structure containing internal
6334 * pointers (via a template of some kind).
6337 static int list_size(char** l
, int item_size
)
6342 j
+= (item_size
) ? item_size
: strlen(l
[i
]) + 1;
6343 j
+= (i
+ 1) * sizeof(char*); }
6347 static int list_dup(char** l_src
, char** l_to
, int item_size
)
6352 for (i
= 0; l_src
[i
]; i
++) ;
6353 p
= (char *)(l_to
+ i
+ 1);
6354 for (i
= 0; l_src
[i
]; i
++)
6356 int count
= ( item_size
) ? item_size
: strlen(l_src
[i
]) + 1;
6357 memcpy(p
, l_src
[i
], count
);
6362 return p
- (char *)l_to
;
6367 /* create a hostent entry
6369 * Creates the entry with enough memory for the name, aliases
6370 * addresses, and the address pointers. Also copies the name
6371 * and sets up all the pointers.
6373 * NOTE: The alias and address lists must be allocated with room
6374 * for the NULL item terminating the list. This is true even if
6375 * the list has no items ("aliases" and "addresses" must be
6376 * at least "1", a truly empty list is invalid).
6378 static struct WS_hostent
*WS_create_he(char *name
, int aliases
, int aliases_size
, int addresses
, int address_length
)
6380 struct WS_hostent
*p_to
;
6382 int size
= (sizeof(struct WS_hostent
) +
6384 sizeof(char *) * aliases
+
6386 sizeof(char *) * addresses
+
6387 address_length
* (addresses
- 1)), i
;
6389 if (!(p_to
= check_buffer_he(size
))) return NULL
;
6390 memset(p_to
, 0, size
);
6392 /* Use the memory in the same way winsock does.
6393 * First set the pointer for aliases, second set the pointers for addresses.
6394 * Third fill the addresses indexes, fourth jump aliases names size.
6395 * Fifth fill the hostname.
6396 * NOTE: This method is valid for OS version's >= XP.
6398 p
= (char *)(p_to
+ 1);
6399 p_to
->h_aliases
= (char **)p
;
6400 p
+= sizeof(char *)*aliases
;
6402 p_to
->h_addr_list
= (char **)p
;
6403 p
+= sizeof(char *)*addresses
;
6405 for (i
= 0, addresses
--; i
< addresses
; i
++, p
+= address_length
)
6406 p_to
->h_addr_list
[i
] = p
;
6408 /* NOTE: h_aliases must be filled in manually because we don't know each string
6409 * size, leave these pointers NULL (already set to NULL by memset earlier).
6419 /* duplicate hostent entry
6420 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
6421 * Ditto for protoent and servent.
6423 static struct WS_hostent
*WS_dup_he(const struct hostent
* p_he
)
6425 int i
, addresses
= 0, alias_size
= 0;
6426 struct WS_hostent
*p_to
;
6429 for( i
= 0; p_he
->h_aliases
[i
]; i
++) alias_size
+= strlen(p_he
->h_aliases
[i
]) + 1;
6430 while (p_he
->h_addr_list
[addresses
]) addresses
++;
6432 p_to
= WS_create_he(p_he
->h_name
, i
+ 1, alias_size
, addresses
+ 1, p_he
->h_length
);
6434 if (!p_to
) return NULL
;
6435 p_to
->h_addrtype
= convert_af_u2w(p_he
->h_addrtype
);
6436 p_to
->h_length
= p_he
->h_length
;
6438 for(i
= 0, p
= p_to
->h_addr_list
[0]; p_he
->h_addr_list
[i
]; i
++, p
+= p_to
->h_length
)
6439 memcpy(p
, p_he
->h_addr_list
[i
], p_to
->h_length
);
6441 /* Fill the aliases after the IP data */
6442 for(i
= 0; p_he
->h_aliases
[i
]; i
++)
6444 p_to
->h_aliases
[i
] = p
;
6445 strcpy(p
, p_he
->h_aliases
[i
]);
6452 /* ----- protoent */
6454 static struct WS_protoent
*WS_dup_pe(const struct protoent
* p_pe
)
6457 struct WS_protoent
*p_to
;
6459 int size
= (sizeof(*p_pe
) +
6460 strlen(p_pe
->p_name
) + 1 +
6461 list_size(p_pe
->p_aliases
, 0));
6463 if (!(p_to
= check_buffer_pe(size
))) return NULL
;
6464 p_to
->p_proto
= p_pe
->p_proto
;
6466 p
= (char *)(p_to
+ 1);
6468 strcpy(p
, p_pe
->p_name
);
6471 p_to
->p_aliases
= (char **)p
;
6472 list_dup(p_pe
->p_aliases
, p_to
->p_aliases
, 0);
6478 static struct WS_servent
*WS_dup_se(const struct servent
* p_se
)
6481 struct WS_servent
*p_to
;
6483 int size
= (sizeof(*p_se
) +
6484 strlen(p_se
->s_proto
) + 1 +
6485 strlen(p_se
->s_name
) + 1 +
6486 list_size(p_se
->s_aliases
, 0));
6488 if (!(p_to
= check_buffer_se(size
))) return NULL
;
6489 p_to
->s_port
= p_se
->s_port
;
6491 p
= (char *)(p_to
+ 1);
6493 strcpy(p
, p_se
->s_name
);
6497 strcpy(p
, p_se
->s_proto
);
6500 p_to
->s_aliases
= (char **)p
;
6501 list_dup(p_se
->s_aliases
, p_to
->s_aliases
, 0);
6506 /***********************************************************************
6507 * WSARecv (WS2_32.67)
6509 int WINAPI
WSARecv(SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
6510 LPDWORD NumberOfBytesReceived
, LPDWORD lpFlags
,
6511 LPWSAOVERLAPPED lpOverlapped
,
6512 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
6514 return WS2_recv_base(s
, lpBuffers
, dwBufferCount
, NumberOfBytesReceived
, lpFlags
,
6515 NULL
, NULL
, lpOverlapped
, lpCompletionRoutine
, NULL
);
6518 static int WS2_recv_base( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
6519 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
,
6520 struct WS_sockaddr
*lpFrom
,
6521 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
6522 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
,
6523 LPWSABUF lpControlBuffer
)
6525 unsigned int i
, options
;
6527 struct ws2_async
*wsa
;
6529 DWORD timeout_start
= GetTickCount();
6530 ULONG_PTR cvalue
= (lpOverlapped
&& ((ULONG_PTR
)lpOverlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)lpOverlapped
: 0;
6532 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
6533 s
, lpBuffers
, dwBufferCount
, *lpFlags
, lpFrom
,
6534 (lpFromlen
? *lpFromlen
: -1),
6535 lpOverlapped
, lpCompletionRoutine
);
6537 fd
= get_sock_fd( s
, FILE_READ_DATA
, &options
);
6538 TRACE( "fd=%d, options=%x\n", fd
, options
);
6540 if (fd
== -1) return SOCKET_ERROR
;
6542 if (!(wsa
= HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async
, iovec
[dwBufferCount
]) )))
6548 wsa
->hSocket
= SOCKET2HANDLE(s
);
6549 wsa
->flags
= *lpFlags
;
6550 wsa
->lpFlags
= lpFlags
;
6552 wsa
->addrlen
.ptr
= lpFromlen
;
6553 wsa
->control
= lpControlBuffer
;
6554 wsa
->n_iovecs
= dwBufferCount
;
6555 wsa
->first_iovec
= 0;
6556 for (i
= 0; i
< dwBufferCount
; i
++)
6558 /* check buffer first to trigger write watches */
6559 if (IsBadWritePtr( lpBuffers
[i
].buf
, lpBuffers
[i
].len
))
6564 wsa
->iovec
[i
].iov_base
= lpBuffers
[i
].buf
;
6565 wsa
->iovec
[i
].iov_len
= lpBuffers
[i
].len
;
6570 n
= WS2_recv( fd
, wsa
);
6573 if (errno
== EINTR
) continue;
6574 if (errno
!= EAGAIN
)
6576 int loc_errno
= errno
;
6578 if (cvalue
) WS_AddCompletion( s
, cvalue
, sock_get_ntstatus(loc_errno
), 0 );
6582 else if (lpNumberOfBytesRecvd
) *lpNumberOfBytesRecvd
= n
;
6584 if ((lpOverlapped
|| lpCompletionRoutine
) &&
6585 !(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
)))
6587 IO_STATUS_BLOCK
*iosb
= lpOverlapped
? (IO_STATUS_BLOCK
*)lpOverlapped
: &wsa
->local_iosb
;
6589 wsa
->user_overlapped
= lpOverlapped
;
6590 wsa
->completion_func
= lpCompletionRoutine
;
6591 release_sock_fd( s
, fd
);
6595 iosb
->u
.Status
= STATUS_PENDING
;
6596 iosb
->Information
= 0;
6598 SERVER_START_REQ( register_async
)
6600 req
->type
= ASYNC_TYPE_READ
;
6601 req
->async
.handle
= wine_server_obj_handle( wsa
->hSocket
);
6602 req
->async
.callback
= wine_server_client_ptr( WS2_async_recv
);
6603 req
->async
.iosb
= wine_server_client_ptr( iosb
);
6604 req
->async
.arg
= wine_server_client_ptr( wsa
);
6605 req
->async
.event
= wine_server_obj_handle( lpCompletionRoutine
? 0 : lpOverlapped
->hEvent
);
6606 req
->async
.cvalue
= cvalue
;
6607 err
= wine_server_call( req
);
6611 if (err
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
6612 WSASetLastError( NtStatusToWSAError( err
));
6613 return SOCKET_ERROR
;
6616 iosb
->u
.Status
= STATUS_SUCCESS
;
6617 iosb
->Information
= n
;
6618 if (!wsa
->completion_func
)
6620 if (cvalue
) WS_AddCompletion( s
, cvalue
, STATUS_SUCCESS
, n
);
6621 if (lpOverlapped
->hEvent
) SetEvent( lpOverlapped
->hEvent
);
6622 HeapFree( GetProcessHeap(), 0, wsa
);
6624 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC
)ws2_async_apc
,
6625 (ULONG_PTR
)wsa
, (ULONG_PTR
)iosb
, 0 );
6626 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
6632 if ((err
= _is_blocking( s
, &is_blocking
)))
6634 err
= NtStatusToWSAError( err
);
6641 int timeout
= GET_RCVTIMEO(fd
);
6644 timeout
-= GetTickCount() - timeout_start
;
6645 if (timeout
< 0) timeout
= 0;
6649 pfd
.events
= POLLIN
;
6650 if (*lpFlags
& WS_MSG_OOB
) pfd
.events
|= POLLPRI
;
6652 if (!timeout
|| !poll( &pfd
, 1, timeout
))
6655 /* a timeout is not fatal */
6656 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
6662 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
6663 err
= WSAEWOULDBLOCK
;
6668 TRACE(" -> %i bytes\n", n
);
6669 HeapFree( GetProcessHeap(), 0, wsa
);
6670 release_sock_fd( s
, fd
);
6671 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
6676 HeapFree( GetProcessHeap(), 0, wsa
);
6677 release_sock_fd( s
, fd
);
6678 WARN(" -> ERROR %d\n", err
);
6679 WSASetLastError( err
);
6680 return SOCKET_ERROR
;
6683 /***********************************************************************
6684 * WSARecvFrom (WS2_32.69)
6686 INT WINAPI
WSARecvFrom( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
6687 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
, struct WS_sockaddr
*lpFrom
,
6688 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
6689 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
6692 return WS2_recv_base( s
, lpBuffers
, dwBufferCount
,
6693 lpNumberOfBytesRecvd
, lpFlags
,
6695 lpOverlapped
, lpCompletionRoutine
, NULL
);
6698 /***********************************************************************
6699 * WSCInstallProvider (WS2_32.88)
6701 INT WINAPI
WSCInstallProvider( const LPGUID lpProviderId
,
6702 LPCWSTR lpszProviderDllPath
,
6703 const LPWSAPROTOCOL_INFOW lpProtocolInfoList
,
6704 DWORD dwNumberOfEntries
,
6707 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId
),
6708 debugstr_w(lpszProviderDllPath
), lpProtocolInfoList
,
6709 dwNumberOfEntries
, lpErrno
);
6715 /***********************************************************************
6716 * WSCDeinstallProvider (WS2_32.83)
6718 INT WINAPI
WSCDeinstallProvider(LPGUID lpProviderId
, LPINT lpErrno
)
6720 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId
), lpErrno
);
6726 /***********************************************************************
6727 * WSAAccept (WS2_32.26)
6729 SOCKET WINAPI
WSAAccept( SOCKET s
, struct WS_sockaddr
*addr
, LPINT addrlen
,
6730 LPCONDITIONPROC lpfnCondition
, DWORD_PTR dwCallbackData
)
6734 WSABUF CallerId
, CallerData
, CalleeId
, CalleeData
;
6735 /* QOS SQOS, GQOS; */
6738 SOCKADDR src_addr
, dst_addr
;
6740 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
6741 s
, addr
, addrlen
, lpfnCondition
, dwCallbackData
);
6743 cs
= WS_accept(s
, addr
, addrlen
);
6744 if (cs
== SOCKET_ERROR
) return SOCKET_ERROR
;
6745 if (!lpfnCondition
) return cs
;
6747 if (addr
&& addrlen
)
6749 CallerId
.buf
= (char *)addr
;
6750 CallerId
.len
= *addrlen
;
6754 size
= sizeof(src_addr
);
6755 WS_getpeername(cs
, &src_addr
, &size
);
6756 CallerId
.buf
= (char *)&src_addr
;
6757 CallerId
.len
= size
;
6759 CallerData
.buf
= NULL
;
6762 size
= sizeof(dst_addr
);
6763 WS_getsockname(cs
, &dst_addr
, &size
);
6765 CalleeId
.buf
= (char *)&dst_addr
;
6766 CalleeId
.len
= sizeof(dst_addr
);
6768 ret
= (*lpfnCondition
)(&CallerId
, &CallerData
, NULL
, NULL
,
6769 &CalleeId
, &CalleeData
, &g
, dwCallbackData
);
6776 SERVER_START_REQ( set_socket_deferred
)
6778 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
6779 req
->deferred
= wine_server_obj_handle( SOCKET2HANDLE(cs
) );
6780 if ( !wine_server_call_err ( req
) )
6782 SetLastError( WSATRY_AGAIN
);
6783 WS_closesocket( cs
);
6787 return SOCKET_ERROR
;
6790 SetLastError(WSAECONNREFUSED
);
6791 return SOCKET_ERROR
;
6793 FIXME("Unknown return type from Condition function\n");
6794 SetLastError(WSAENOTSOCK
);
6795 return SOCKET_ERROR
;
6799 /***********************************************************************
6800 * WSADuplicateSocketA (WS2_32.32)
6802 int WINAPI
WSADuplicateSocketA( SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOA lpProtocolInfo
)
6804 return WS_DuplicateSocket(FALSE
, s
, dwProcessId
, (LPWSAPROTOCOL_INFOW
) lpProtocolInfo
);
6807 /***********************************************************************
6808 * WSADuplicateSocketW (WS2_32.33)
6810 int WINAPI
WSADuplicateSocketW( SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOW lpProtocolInfo
)
6812 return WS_DuplicateSocket(TRUE
, s
, dwProcessId
, lpProtocolInfo
);
6815 /***********************************************************************
6816 * WSAInstallServiceClassA (WS2_32.48)
6818 int WINAPI
WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info
)
6820 FIXME("Request to install service %s\n",debugstr_a(info
->lpszServiceClassName
));
6821 WSASetLastError(WSAEACCES
);
6822 return SOCKET_ERROR
;
6825 /***********************************************************************
6826 * WSAInstallServiceClassW (WS2_32.49)
6828 int WINAPI
WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info
)
6830 FIXME("Request to install service %s\n",debugstr_w(info
->lpszServiceClassName
));
6831 WSASetLastError(WSAEACCES
);
6832 return SOCKET_ERROR
;
6835 /***********************************************************************
6836 * WSARemoveServiceClass (WS2_32.70)
6838 int WINAPI
WSARemoveServiceClass(LPGUID info
)
6840 FIXME("Request to remove service %p\n",info
);
6841 WSASetLastError(WSATYPE_NOT_FOUND
);
6842 return SOCKET_ERROR
;
6845 /***********************************************************************
6846 * inet_ntop (WS2_32.@)
6848 PCSTR WINAPI
WS_inet_ntop( INT family
, PVOID addr
, PSTR buffer
, SIZE_T len
)
6850 #ifdef HAVE_INET_NTOP
6851 struct WS_in6_addr
*in6
;
6852 struct WS_in_addr
*in
;
6855 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family
, addr
, buffer
, len
);
6858 WSASetLastError( STATUS_INVALID_PARAMETER
);
6867 pdst
= inet_ntop( AF_INET
, &in
->WS_s_addr
, buffer
, len
);
6873 pdst
= inet_ntop( AF_INET6
, in6
->WS_s6_addr
, buffer
, len
);
6877 WSASetLastError( WSAEAFNOSUPPORT
);
6881 if (!pdst
) WSASetLastError( STATUS_INVALID_PARAMETER
);
6884 FIXME( "not supported on this platform\n" );
6885 WSASetLastError( WSAEAFNOSUPPORT
);
6890 /***********************************************************************
6891 * WSAStringToAddressA (WS2_32.80)
6893 INT WINAPI
WSAStringToAddressA(LPSTR AddressString
,
6895 LPWSAPROTOCOL_INFOA lpProtocolInfo
,
6896 LPSOCKADDR lpAddress
,
6897 LPINT lpAddressLength
)
6900 LPSTR workBuffer
=NULL
,ptrPort
;
6902 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString
), AddressFamily
,
6903 lpProtocolInfo
, lpAddress
, lpAddressLength
);
6905 if (!lpAddressLength
|| !lpAddress
) return SOCKET_ERROR
;
6909 WSASetLastError(WSAEINVAL
);
6910 return SOCKET_ERROR
;
6914 FIXME("ProtocolInfo not implemented.\n");
6916 workBuffer
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
,
6917 strlen(AddressString
) + 1);
6920 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
6921 return SOCKET_ERROR
;
6924 strcpy(workBuffer
, AddressString
);
6926 switch(AddressFamily
)
6930 struct in_addr inetaddr
;
6932 /* If lpAddressLength is too small, tell caller the size we need */
6933 if (*lpAddressLength
< sizeof(SOCKADDR_IN
))
6935 *lpAddressLength
= sizeof(SOCKADDR_IN
);
6939 *lpAddressLength
= sizeof(SOCKADDR_IN
);
6940 memset(lpAddress
, 0, sizeof(SOCKADDR_IN
));
6942 ((LPSOCKADDR_IN
)lpAddress
)->sin_family
= WS_AF_INET
;
6944 ptrPort
= strchr(workBuffer
, ':');
6947 ((LPSOCKADDR_IN
)lpAddress
)->sin_port
= htons(atoi(ptrPort
+1));
6952 ((LPSOCKADDR_IN
)lpAddress
)->sin_port
= 0;
6955 if(inet_aton(workBuffer
, &inetaddr
) > 0)
6957 ((LPSOCKADDR_IN
)lpAddress
)->sin_addr
.WS_s_addr
= inetaddr
.s_addr
;
6968 struct in6_addr inetaddr
;
6969 /* If lpAddressLength is too small, tell caller the size we need */
6970 if (*lpAddressLength
< sizeof(SOCKADDR_IN6
))
6972 *lpAddressLength
= sizeof(SOCKADDR_IN6
);
6976 #ifdef HAVE_INET_PTON
6977 *lpAddressLength
= sizeof(SOCKADDR_IN6
);
6978 memset(lpAddress
, 0, sizeof(SOCKADDR_IN6
));
6980 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_family
= WS_AF_INET6
;
6982 /* This one is a bit tricky. An IPv6 address contains colons, so the
6983 * check from IPv4 doesn't work like that. However, IPv6 addresses that
6984 * contain a port are written with braces like [fd12:3456:7890::1]:12345
6985 * so what we will do is to look for ']', check if the next char is a
6986 * colon, and if it is, parse the port as in IPv4. */
6988 ptrPort
= strchr(workBuffer
, ']');
6989 if(ptrPort
&& *(++ptrPort
) == ':')
6991 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_port
= htons(atoi(ptrPort
+1));
6996 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_port
= 0;
6999 if(inet_pton(AF_INET6
, workBuffer
, &inetaddr
) > 0)
7001 memcpy(&((LPSOCKADDR_IN6
)lpAddress
)->sin6_addr
, &inetaddr
,
7002 sizeof(struct in6_addr
));
7006 #endif /* HAVE_INET_PTON */
7012 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
7013 TRACE("Unsupported address family specified: %d.\n", AddressFamily
);
7017 HeapFree(GetProcessHeap(), 0, workBuffer
);
7020 WSASetLastError(res
);
7021 return SOCKET_ERROR
;
7024 /***********************************************************************
7025 * WSAStringToAddressW (WS2_32.81)
7027 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
7028 * If this should be the case, it would be required to map these digits
7029 * to Unicode digits (0-9) using FoldString first.
7031 INT WINAPI
WSAStringToAddressW(LPWSTR AddressString
,
7033 LPWSAPROTOCOL_INFOW lpProtocolInfo
,
7034 LPSOCKADDR lpAddress
,
7035 LPINT lpAddressLength
)
7038 LPSTR workBuffer
=NULL
;
7039 WSAPROTOCOL_INFOA infoA
;
7040 LPWSAPROTOCOL_INFOA lpProtoInfoA
= NULL
;
7042 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString
), AddressFamily
, lpProtocolInfo
,
7043 lpAddress
, lpAddressLength
);
7045 if (!lpAddressLength
|| !lpAddress
) return SOCKET_ERROR
;
7047 /* if ProtocolInfo is available - convert to ANSI variant */
7050 lpProtoInfoA
= &infoA
;
7051 memcpy( lpProtoInfoA
, lpProtocolInfo
, FIELD_OFFSET( WSAPROTOCOL_INFOA
, szProtocol
) );
7053 if (!WideCharToMultiByte( CP_ACP
, 0, lpProtocolInfo
->szProtocol
, -1,
7054 lpProtoInfoA
->szProtocol
, WSAPROTOCOL_LEN
+1, NULL
, NULL
))
7056 WSASetLastError( WSAEINVAL
);
7057 return SOCKET_ERROR
;
7063 /* Translate AddressString to ANSI code page - assumes that only
7064 standard digits 0-9 are used with this API call */
7065 sBuffer
= WideCharToMultiByte( CP_ACP
, 0, AddressString
, -1, NULL
, 0, NULL
, NULL
);
7066 workBuffer
= HeapAlloc( GetProcessHeap(), 0, sBuffer
);
7070 WideCharToMultiByte( CP_ACP
, 0, AddressString
, -1, workBuffer
, sBuffer
, NULL
, NULL
);
7071 res
= WSAStringToAddressA(workBuffer
,AddressFamily
,lpProtoInfoA
,
7072 lpAddress
,lpAddressLength
);
7073 HeapFree( GetProcessHeap(), 0, workBuffer
);
7077 res
= WSA_NOT_ENOUGH_MEMORY
;
7082 WSASetLastError(res
);
7083 return SOCKET_ERROR
;
7086 /***********************************************************************
7087 * WSAAddressToStringA (WS2_32.27)
7089 * See WSAAddressToStringW
7091 INT WINAPI
WSAAddressToStringA( LPSOCKADDR sockaddr
, DWORD len
,
7092 LPWSAPROTOCOL_INFOA info
, LPSTR string
,
7096 CHAR buffer
[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7099 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr
, len
, info
, string
, lenstr
);
7101 if (!sockaddr
) return SOCKET_ERROR
;
7102 if (!string
|| !lenstr
) return SOCKET_ERROR
;
7104 switch(sockaddr
->sa_family
)
7107 if (len
< sizeof(SOCKADDR_IN
)) return SOCKET_ERROR
;
7108 sprintf( buffer
, "%u.%u.%u.%u:%u",
7109 (unsigned int)(ntohl( ((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
) >> 24 & 0xff),
7110 (unsigned int)(ntohl( ((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
) >> 16 & 0xff),
7111 (unsigned int)(ntohl( ((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
) >> 8 & 0xff),
7112 (unsigned int)(ntohl( ((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
) & 0xff),
7113 ntohs( ((SOCKADDR_IN
*)sockaddr
)->sin_port
) );
7115 p
= strchr( buffer
, ':' );
7116 if (!((SOCKADDR_IN
*)sockaddr
)->sin_port
) *p
= 0;
7121 struct WS_sockaddr_in6
*sockaddr6
= (LPSOCKADDR_IN6
) sockaddr
;
7124 if (len
< sizeof(SOCKADDR_IN6
)) return SOCKET_ERROR
;
7125 if ((sockaddr6
->sin6_port
))
7126 strcpy(buffer
, "[");
7127 if (!WS_inet_ntop(WS_AF_INET6
, &sockaddr6
->sin6_addr
, buffer
+strlen(buffer
), sizeof(buffer
)))
7129 WSASetLastError(WSAEINVAL
);
7130 return SOCKET_ERROR
;
7132 if ((sockaddr6
->sin6_scope_id
))
7133 sprintf(buffer
+strlen(buffer
), "%%%u", sockaddr6
->sin6_scope_id
);
7134 if ((sockaddr6
->sin6_port
))
7135 sprintf(buffer
+strlen(buffer
), "]:%u", ntohs(sockaddr6
->sin6_port
));
7140 WSASetLastError(WSAEINVAL
);
7141 return SOCKET_ERROR
;
7144 size
= strlen( buffer
) + 1;
7149 WSASetLastError(WSAEFAULT
);
7150 return SOCKET_ERROR
;
7153 TRACE("=> %s,%u bytes\n", debugstr_a(buffer
), size
);
7155 strcpy( string
, buffer
);
7159 /***********************************************************************
7160 * WSAAddressToStringW (WS2_32.28)
7162 * Convert a sockaddr address into a readable address string.
7165 * sockaddr [I] Pointer to a sockaddr structure.
7166 * len [I] Size of the sockaddr structure.
7167 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
7168 * string [I/O] Pointer to a buffer to receive the address string.
7169 * lenstr [I/O] Size of the receive buffer in WCHARs.
7173 * Failure: SOCKET_ERROR
7176 * The 'info' parameter is ignored.
7178 INT WINAPI
WSAAddressToStringW( LPSOCKADDR sockaddr
, DWORD len
,
7179 LPWSAPROTOCOL_INFOW info
, LPWSTR string
,
7184 WCHAR buffer
[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7187 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr
, len
, info
, string
, lenstr
);
7190 ret
= WSAAddressToStringA(sockaddr
, len
, NULL
, bufAddr
, &size
);
7192 if (ret
) return ret
;
7194 MultiByteToWideChar( CP_ACP
, 0, bufAddr
, size
, buffer
, sizeof( buffer
)/sizeof(WCHAR
));
7199 WSASetLastError(WSAEFAULT
);
7200 return SOCKET_ERROR
;
7203 TRACE("=> %s,%u bytes\n", debugstr_w(buffer
), size
);
7205 lstrcpyW( string
, buffer
);
7209 /***********************************************************************
7210 * WSAEnumNameSpaceProvidersA (WS2_32.34)
7212 INT WINAPI
WSAEnumNameSpaceProvidersA( LPDWORD len
, LPWSANAMESPACE_INFOA buffer
)
7214 FIXME( "(%p %p) Stub!\n", len
, buffer
);
7218 /***********************************************************************
7219 * WSAEnumNameSpaceProvidersW (WS2_32.35)
7221 INT WINAPI
WSAEnumNameSpaceProvidersW( LPDWORD len
, LPWSANAMESPACE_INFOW buffer
)
7223 FIXME( "(%p %p) Stub!\n", len
, buffer
);
7227 /***********************************************************************
7228 * WSAGetQOSByName (WS2_32.41)
7230 BOOL WINAPI
WSAGetQOSByName( SOCKET s
, LPWSABUF lpQOSName
, LPQOS lpQOS
)
7232 FIXME( "(0x%04lx %p %p) Stub!\n", s
, lpQOSName
, lpQOS
);
7236 /***********************************************************************
7237 * WSAGetServiceClassInfoA (WS2_32.42)
7239 INT WINAPI
WSAGetServiceClassInfoA( LPGUID provider
, LPGUID service
, LPDWORD len
,
7240 LPWSASERVICECLASSINFOA info
)
7242 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider
), debugstr_guid(service
),
7244 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
7245 return SOCKET_ERROR
;
7248 /***********************************************************************
7249 * WSAGetServiceClassInfoW (WS2_32.43)
7251 INT WINAPI
WSAGetServiceClassInfoW( LPGUID provider
, LPGUID service
, LPDWORD len
,
7252 LPWSASERVICECLASSINFOW info
)
7254 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider
), debugstr_guid(service
),
7256 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
7257 return SOCKET_ERROR
;
7260 /***********************************************************************
7261 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
7263 INT WINAPI
WSAGetServiceClassNameByClassIdA( LPGUID
class, LPSTR service
, LPDWORD len
)
7265 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service
, len
);
7266 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
7267 return SOCKET_ERROR
;
7270 /***********************************************************************
7271 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
7273 INT WINAPI
WSAGetServiceClassNameByClassIdW( LPGUID
class, LPWSTR service
, LPDWORD len
)
7275 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service
, len
);
7276 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
7277 return SOCKET_ERROR
;
7280 /***********************************************************************
7281 * WSALookupServiceBeginA (WS2_32.59)
7283 INT WINAPI
WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions
,
7284 DWORD dwControlFlags
,
7287 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions
, dwControlFlags
,
7289 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
7290 return SOCKET_ERROR
;
7293 /***********************************************************************
7294 * WSALookupServiceBeginW (WS2_32.60)
7296 INT WINAPI
WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions
,
7297 DWORD dwControlFlags
,
7300 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions
, dwControlFlags
,
7302 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
7303 return SOCKET_ERROR
;
7306 /***********************************************************************
7307 * WSALookupServiceEnd (WS2_32.61)
7309 INT WINAPI
WSALookupServiceEnd( HANDLE lookup
)
7311 FIXME("(%p) Stub!\n", lookup
);
7315 /***********************************************************************
7316 * WSALookupServiceNextA (WS2_32.62)
7318 INT WINAPI
WSALookupServiceNextA( HANDLE lookup
, DWORD flags
, LPDWORD len
, LPWSAQUERYSETA results
)
7320 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup
, flags
, len
, results
);
7321 WSASetLastError(WSA_E_NO_MORE
);
7322 return SOCKET_ERROR
;
7325 /***********************************************************************
7326 * WSALookupServiceNextW (WS2_32.63)
7328 INT WINAPI
WSALookupServiceNextW( HANDLE lookup
, DWORD flags
, LPDWORD len
, LPWSAQUERYSETW results
)
7330 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup
, flags
, len
, results
);
7331 WSASetLastError(WSA_E_NO_MORE
);
7332 return SOCKET_ERROR
;
7335 /***********************************************************************
7336 * WSANtohl (WS2_32.64)
7338 INT WINAPI
WSANtohl( SOCKET s
, WS_u_long netlong
, WS_u_long
* lphostlong
)
7340 TRACE( "(0x%04lx 0x%08x %p)\n", s
, netlong
, lphostlong
);
7342 if (!lphostlong
) return WSAEFAULT
;
7344 *lphostlong
= ntohl( netlong
);
7348 /***********************************************************************
7349 * WSANtohs (WS2_32.65)
7351 INT WINAPI
WSANtohs( SOCKET s
, WS_u_short netshort
, WS_u_short
* lphostshort
)
7353 TRACE( "(0x%04lx 0x%08x %p)\n", s
, netshort
, lphostshort
);
7355 if (!lphostshort
) return WSAEFAULT
;
7357 *lphostshort
= ntohs( netshort
);
7361 /***********************************************************************
7362 * WSAProviderConfigChange (WS2_32.66)
7364 INT WINAPI
WSAProviderConfigChange( LPHANDLE handle
, LPWSAOVERLAPPED overlapped
,
7365 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
7367 FIXME( "(%p %p %p) Stub!\n", handle
, overlapped
, completion
);
7368 return SOCKET_ERROR
;
7371 /***********************************************************************
7372 * WSARecvDisconnect (WS2_32.68)
7374 INT WINAPI
WSARecvDisconnect( SOCKET s
, LPWSABUF disconnectdata
)
7376 TRACE( "(0x%04lx %p)\n", s
, disconnectdata
);
7378 return WS_shutdown( s
, 0 );
7381 /***********************************************************************
7382 * WSASetServiceA (WS2_32.76)
7384 INT WINAPI
WSASetServiceA( LPWSAQUERYSETA query
, WSAESETSERVICEOP operation
, DWORD flags
)
7386 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query
, operation
, flags
);
7390 /***********************************************************************
7391 * WSASetServiceW (WS2_32.77)
7393 INT WINAPI
WSASetServiceW( LPWSAQUERYSETW query
, WSAESETSERVICEOP operation
, DWORD flags
)
7395 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query
, operation
, flags
);
7399 /***********************************************************************
7400 * WSCEnableNSProvider (WS2_32.84)
7402 INT WINAPI
WSCEnableNSProvider( LPGUID provider
, BOOL enable
)
7404 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider
), enable
);
7408 /***********************************************************************
7409 * WSCGetProviderPath (WS2_32.86)
7411 INT WINAPI
WSCGetProviderPath( LPGUID provider
, LPWSTR path
, LPINT len
, LPINT errcode
)
7413 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider
), path
, len
, errcode
);
7415 if (!errcode
|| !provider
|| !len
) return WSAEFAULT
;
7417 *errcode
= WSAEINVAL
;
7418 return SOCKET_ERROR
;
7421 /***********************************************************************
7422 * WSCInstallNameSpace (WS2_32.87)
7424 INT WINAPI
WSCInstallNameSpace( LPWSTR identifier
, LPWSTR path
, DWORD
namespace,
7425 DWORD version
, LPGUID provider
)
7427 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier
), debugstr_w(path
),
7428 namespace, version
, debugstr_guid(provider
) );
7432 /***********************************************************************
7433 * WSCUnInstallNameSpace (WS2_32.89)
7435 INT WINAPI
WSCUnInstallNameSpace( LPGUID lpProviderId
)
7437 FIXME("(%p) Stub!\n", lpProviderId
);
7441 /***********************************************************************
7442 * WSCWriteProviderOrder (WS2_32.91)
7444 INT WINAPI
WSCWriteProviderOrder( LPDWORD entry
, DWORD number
)
7446 FIXME("(%p 0x%08x) Stub!\n", entry
, number
);
7450 /***********************************************************************
7451 * WSANSPIoctl (WS2_32.91)
7453 INT WINAPI
WSANSPIoctl( HANDLE hLookup
, DWORD dwControlCode
, LPVOID lpvInBuffer
,
7454 DWORD cbInBuffer
, LPVOID lpvOutBuffer
, DWORD cbOutBuffer
,
7455 LPDWORD lpcbBytesReturned
, LPWSACOMPLETION lpCompletion
)
7457 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup
, dwControlCode
,
7458 lpvInBuffer
, cbInBuffer
, lpvOutBuffer
, cbOutBuffer
, lpcbBytesReturned
, lpCompletion
);
7459 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
7460 return SOCKET_ERROR
;
7463 /*****************************************************************************
7464 * WSAEnumProtocolsA [WS2_32.@]
7466 * see function WSAEnumProtocolsW
7468 INT WINAPI
WSAEnumProtocolsA( LPINT protocols
, LPWSAPROTOCOL_INFOA buffer
, LPDWORD len
)
7470 return WS_EnumProtocols( FALSE
, protocols
, (LPWSAPROTOCOL_INFOW
) buffer
, len
);
7473 /*****************************************************************************
7474 * WSAEnumProtocolsW [WS2_32.@]
7476 * Retrieves information about specified set of active network protocols.
7479 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
7480 * retrieves information on all available protocols.
7481 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
7483 * len [I/O] Pointer to a variable specifying buffer size. On output
7484 * the variable holds the number of bytes needed when the
7485 * specified size is too small.
7488 * Success: number of WSAPROTOCOL_INFO structures in buffer.
7489 * Failure: SOCKET_ERROR
7492 * NT4SP5 does not return SPX if protocols == NULL
7495 * - NT4SP5 returns in addition these list of NETBIOS protocols
7496 * (address family 17), each entry two times one for socket type 2 and 5
7498 * iProtocol szProtocol
7499 * 0x80000000 \Device\NwlnkNb
7500 * 0xfffffffa \Device\NetBT_CBENT7
7501 * 0xfffffffb \Device\Nbf_CBENT7
7502 * 0xfffffffc \Device\NetBT_NdisWan5
7503 * 0xfffffffd \Device\NetBT_El9202
7504 * 0xfffffffe \Device\Nbf_El9202
7505 * 0xffffffff \Device\Nbf_NdisWan4
7507 * - there is no check that the operating system supports the returned
7510 INT WINAPI
WSAEnumProtocolsW( LPINT protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
)
7512 return WS_EnumProtocols( TRUE
, protocols
, buffer
, len
);
7515 /*****************************************************************************
7516 * WSCEnumProtocols [WS2_32.@]
7519 * protocols [I] Null-terminated array of iProtocol values.
7520 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
7521 * len [I/O] Size of buffer on input/output.
7522 * errno [O] Error code.
7525 * Success: number of protocols to be reported on.
7526 * Failure: SOCKET_ERROR. error is in errno.
7529 * Doesn't supply info on layered protocols.
7532 INT WINAPI
WSCEnumProtocols( LPINT protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
, LPINT err
)
7534 INT ret
= WSAEnumProtocolsW( protocols
, buffer
, len
);
7536 if (ret
== SOCKET_ERROR
) *err
= WSAENOBUFS
;