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>
103 #elif defined(HAVE_LINUX_IPX_H)
104 # ifdef HAVE_ASM_TYPES_H
105 # include <asm/types.h>
107 # ifdef HAVE_LINUX_TYPES_H
108 # include <linux/types.h>
110 # include <linux/ipx.h>
112 #if defined(SOL_IPX) || defined(SO_DEFAULT_HEADERS)
116 #ifdef HAVE_LINUX_IRDA_H
117 # ifdef HAVE_LINUX_TYPES_H
118 # include <linux/types.h>
120 # include <linux/irda.h>
127 #ifdef HAVE_SYS_POLL_H
128 # include <sys/poll.h>
130 #ifdef HAVE_SYS_TIME_H
131 # include <sys/time.h>
134 #define NONAMELESSUNION
135 #define NONAMELESSSTRUCT
136 #include "ntstatus.h"
137 #define WIN32_NO_STATUS
142 #include "winerror.h"
144 #include "winsock2.h"
146 #include "ws2tcpip.h"
149 #include "wshisotp.h"
153 #define USE_WC_PREFIX /* For CMSG_DATA */
154 #include "iphlpapi.h"
155 #include "wine/server.h"
156 #include "wine/debug.h"
157 #include "wine/exception.h"
158 #include "wine/unicode.h"
161 # include "wsnwlink.h"
164 #if defined(linux) && !defined(IP_UNICAST_IF)
165 #define IP_UNICAST_IF 50
168 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
169 # define sipx_network sipx_addr.x_net
170 # define sipx_node sipx_addr.x_host.c_host
171 #endif /* __FreeBSD__ */
174 #define INADDR_NONE ~0UL
177 WINE_DEFAULT_DEBUG_CHANNEL(winsock
);
178 WINE_DECLARE_DEBUG_CHANNEL(winediag
);
180 /* names of the protocols */
181 static const WCHAR NameIpxW
[] = {'I', 'P', 'X', '\0'};
182 static const WCHAR NameSpxW
[] = {'S', 'P', 'X', '\0'};
183 static const WCHAR NameSpxIIW
[] = {'S', 'P', 'X', ' ', 'I', 'I', '\0'};
184 static const WCHAR NameTcpW
[] = {'T', 'C', 'P', '/', 'I', 'P', '\0'};
185 static const WCHAR NameUdpW
[] = {'U', 'D', 'P', '/', 'I', 'P', '\0'};
187 /* Taken from Win2k */
188 static const GUID ProviderIdIP
= { 0xe70f1aa0, 0xab8b, 0x11cf,
189 { 0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
190 static const GUID ProviderIdIPX
= { 0x11058240, 0xbe47, 0x11cf,
191 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
192 static const GUID ProviderIdSPX
= { 0x11058241, 0xbe47, 0x11cf,
193 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
195 static const INT valid_protocols
[] =
205 #define IS_IPX_PROTO(X) ((X) >= WS_NSPROTO_IPX && (X) <= WS_NSPROTO_IPX + 255)
207 #if defined(IP_UNICAST_IF) && defined(SO_ATTACH_FILTER)
208 # define LINUX_BOUND_IF
209 struct interface_filter
{
210 struct sock_filter iface_memaddr
;
211 struct sock_filter iface_rule
;
212 struct sock_filter ip_memaddr
;
213 struct sock_filter ip_rule
;
214 struct sock_filter return_keep
;
215 struct sock_filter return_dump
;
217 # define FILTER_JUMP_DUMP(here) (u_char)(offsetof(struct interface_filter, return_dump) \
218 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
219 /sizeof(struct sock_filter)
220 # define FILTER_JUMP_KEEP(here) (u_char)(offsetof(struct interface_filter, return_keep) \
221 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
222 /sizeof(struct sock_filter)
223 # define FILTER_JUMP_NEXT() (u_char)(0)
224 # define SKF_NET_DESTIP 16 /* offset in the network header to the destination IP */
225 static struct interface_filter generic_interface_filter
= {
226 /* This filter rule allows incoming packets on the specified interface, which works for all
227 * remotely generated packets and for locally generated broadcast packets. */
228 BPF_STMT(BPF_LD
+BPF_W
+BPF_ABS
, SKF_AD_OFF
+SKF_AD_IFINDEX
),
229 BPF_JUMP(BPF_JMP
+BPF_JEQ
+BPF_K
, 0xdeadbeef, FILTER_JUMP_KEEP(iface_rule
), FILTER_JUMP_NEXT()),
230 /* This rule allows locally generated packets targeted at the specific IP address of the chosen
231 * adapter (local packets not destined for the broadcast address do not have IFINDEX set) */
232 BPF_STMT(BPF_LD
+BPF_W
+BPF_ABS
, SKF_NET_OFF
+SKF_NET_DESTIP
),
233 BPF_JUMP(BPF_JMP
+BPF_JEQ
+BPF_K
, 0xdeadbeef, FILTER_JUMP_KEEP(ip_rule
), FILTER_JUMP_DUMP(ip_rule
)),
234 BPF_STMT(BPF_RET
+BPF_K
, (u_int
)-1), /* keep packet */
235 BPF_STMT(BPF_RET
+BPF_K
, 0) /* dump packet */
237 #endif /* LINUX_BOUND_IF */
240 * The actual definition of WSASendTo, wrapped in a different function name
241 * so that internal calls from ws2_32 itself will not trigger programs like
242 * Garena, which hooks WSASendTo/WSARecvFrom calls.
244 static int WS2_sendto( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
245 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
246 const struct WS_sockaddr
*to
, int tolen
,
247 LPWSAOVERLAPPED lpOverlapped
,
248 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);
251 * Internal fundamental receive function, essentially WSARecvFrom with an
252 * additional parameter to support message control headers.
254 static int WS2_recv_base( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
255 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
,
256 struct WS_sockaddr
*lpFrom
,
257 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
258 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
,
259 LPWSABUF lpControlBuffer
);
261 /* critical section to protect some non-reentrant net function */
262 static CRITICAL_SECTION csWSgetXXXbyYYY
;
263 static CRITICAL_SECTION_DEBUG critsect_debug
=
265 0, 0, &csWSgetXXXbyYYY
,
266 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
267 0, 0, { (DWORD_PTR
)(__FILE__
": csWSgetXXXbyYYY") }
269 static CRITICAL_SECTION csWSgetXXXbyYYY
= { &critsect_debug
, -1, 0, 0, 0, 0 };
271 union generic_unix_sockaddr
273 struct sockaddr addr
;
274 char data
[128]; /* should be big enough for all families */
277 static inline const char *debugstr_sockaddr( const struct WS_sockaddr
*a
)
279 if (!a
) return "(nil)";
280 switch (a
->sa_family
)
283 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
284 inet_ntoa(((const struct sockaddr_in
*)a
)->sin_addr
),
285 ntohs(((const struct sockaddr_in
*)a
)->sin_port
));
290 struct WS_sockaddr_in6
*sin
= (struct WS_sockaddr_in6
*)a
;
292 p
= WS_inet_ntop( WS_AF_INET6
, &sin
->sin6_addr
, buf
, sizeof(buf
) );
294 p
= "(unknown IPv6 address)";
295 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
296 p
, ntohs(sin
->sin6_port
));
301 char netnum
[16], nodenum
[16];
302 struct WS_sockaddr_ipx
*sin
= (struct WS_sockaddr_ipx
*)a
;
304 for (i
= 0;i
< 4; i
++) sprintf(netnum
+ i
* 2, "%02X", (unsigned char) sin
->sa_netnum
[i
]);
305 for (i
= 0;i
< 6; i
++) sprintf(nodenum
+ i
* 2, "%02X", (unsigned char) sin
->sa_nodenum
[i
]);
307 return wine_dbg_sprintf("{ family AF_IPX, address %s.%s, ipx socket %d }",
308 netnum
, nodenum
, sin
->sa_socket
);
314 memcpy( &addr
, ((const SOCKADDR_IRDA
*)a
)->irdaDeviceID
, sizeof(addr
) );
315 addr
= ntohl( addr
);
316 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
318 ((const SOCKADDR_IRDA
*)a
)->irdaServiceName
);
321 return wine_dbg_sprintf("{ family %d }", a
->sa_family
);
325 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
326 #define SOCKET2HANDLE(s) ((HANDLE)(s))
327 #define HANDLE2SOCKET(h) ((SOCKET)(h))
329 /****************************************************************
330 * Async IO declarations
331 ****************************************************************/
333 typedef struct ws2_async
337 LPWSAOVERLAPPED user_overlapped
;
338 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func
;
339 IO_STATUS_BLOCK local_iosb
;
340 struct WS_sockaddr
*addr
;
343 int val
; /* for send operations */
344 int *ptr
; /* for recv operations */
349 unsigned int n_iovecs
;
350 unsigned int first_iovec
;
351 struct iovec iovec
[1];
354 typedef struct ws2_accept_async
356 HANDLE listen_socket
;
357 HANDLE accept_socket
;
358 LPOVERLAPPED user_overlapped
;
360 PVOID buf
; /* buffer to write data to */
364 struct ws2_async
*read
;
367 /****************************************************************/
369 /* ----------------------------------- internal data */
371 /* ws_... struct conversion flags */
373 typedef struct /* WSAAsyncSelect() control struct */
375 HANDLE service
, event
, sock
;
381 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
382 #define WS_MAX_UDP_DATAGRAM 1024
383 static INT WINAPI
WSA_DefaultBlockingHook( FARPROC x
);
385 /* hostent's, servent's and protent's are stored in one buffer per thread,
386 * as documented on MSDN for the functions that return any of the buffers */
387 struct per_thread_data
390 struct WS_hostent
*he_buffer
;
391 struct WS_servent
*se_buffer
;
392 struct WS_protoent
*pe_buffer
;
396 char ntoa_buffer
[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
399 /* internal: routing description information */
406 static INT num_startup
; /* reference counter */
407 static FARPROC blocking_hook
= (FARPROC
)WSA_DefaultBlockingHook
;
409 /* function prototypes */
410 static struct WS_hostent
*WS_create_he(char *name
, int aliases
, int aliases_size
, int addresses
, int address_length
);
411 static struct WS_hostent
*WS_dup_he(const struct hostent
* p_he
);
412 static struct WS_protoent
*WS_dup_pe(const struct protoent
* p_pe
);
413 static struct WS_servent
*WS_dup_se(const struct servent
* p_se
);
414 static int ws_protocol_info(SOCKET s
, int unicode
, WSAPROTOCOL_INFOW
*buffer
, int *size
);
416 int WSAIOCTL_GetInterfaceCount(void);
417 int WSAIOCTL_GetInterfaceName(int intNumber
, char *intName
);
419 static void WS_AddCompletion( SOCKET sock
, ULONG_PTR CompletionValue
, NTSTATUS CompletionStatus
, ULONG Information
);
421 #define MAP_OPTION(opt) { WS_##opt, opt }
423 static const int ws_sock_map
[][2] =
425 MAP_OPTION( SO_DEBUG
),
426 MAP_OPTION( SO_ACCEPTCONN
),
427 MAP_OPTION( SO_REUSEADDR
),
428 MAP_OPTION( SO_KEEPALIVE
),
429 MAP_OPTION( SO_DONTROUTE
),
430 MAP_OPTION( SO_BROADCAST
),
431 MAP_OPTION( SO_LINGER
),
432 MAP_OPTION( SO_OOBINLINE
),
433 MAP_OPTION( SO_SNDBUF
),
434 MAP_OPTION( SO_RCVBUF
),
435 MAP_OPTION( SO_ERROR
),
436 MAP_OPTION( SO_TYPE
),
438 MAP_OPTION( SO_RCVTIMEO
),
441 MAP_OPTION( SO_SNDTIMEO
),
445 static const int ws_tcp_map
[][2] =
448 MAP_OPTION( TCP_NODELAY
),
452 static const int ws_ip_map
[][2] =
454 MAP_OPTION( IP_MULTICAST_IF
),
455 MAP_OPTION( IP_MULTICAST_TTL
),
456 MAP_OPTION( IP_MULTICAST_LOOP
),
457 MAP_OPTION( IP_ADD_MEMBERSHIP
),
458 MAP_OPTION( IP_DROP_MEMBERSHIP
),
459 MAP_OPTION( IP_OPTIONS
),
461 MAP_OPTION( IP_HDRINCL
),
463 MAP_OPTION( IP_TOS
),
464 MAP_OPTION( IP_TTL
),
466 MAP_OPTION( IP_PKTINFO
),
469 MAP_OPTION( IP_UNICAST_IF
),
473 static const int ws_ipv6_map
[][2] =
475 #ifdef IPV6_ADD_MEMBERSHIP
476 MAP_OPTION( IPV6_ADD_MEMBERSHIP
),
478 #ifdef IPV6_DROP_MEMBERSHIP
479 MAP_OPTION( IPV6_DROP_MEMBERSHIP
),
481 MAP_OPTION( IPV6_MULTICAST_IF
),
482 MAP_OPTION( IPV6_MULTICAST_HOPS
),
483 MAP_OPTION( IPV6_MULTICAST_LOOP
),
484 MAP_OPTION( IPV6_UNICAST_HOPS
),
485 MAP_OPTION( IPV6_V6ONLY
),
486 #ifdef IPV6_UNICAST_IF
487 MAP_OPTION( IPV6_UNICAST_IF
),
491 static const int ws_af_map
[][2] =
493 MAP_OPTION( AF_UNSPEC
),
494 MAP_OPTION( AF_INET
),
495 MAP_OPTION( AF_INET6
),
497 MAP_OPTION( AF_IPX
),
500 MAP_OPTION( AF_IRDA
),
502 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
505 static const int ws_socktype_map
[][2] =
507 MAP_OPTION( SOCK_DGRAM
),
508 MAP_OPTION( SOCK_STREAM
),
509 MAP_OPTION( SOCK_RAW
),
510 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
513 static const int ws_proto_map
[][2] =
515 MAP_OPTION( IPPROTO_IP
),
516 MAP_OPTION( IPPROTO_TCP
),
517 MAP_OPTION( IPPROTO_UDP
),
518 MAP_OPTION( IPPROTO_ICMP
),
519 MAP_OPTION( IPPROTO_IGMP
),
520 MAP_OPTION( IPPROTO_RAW
),
521 {FROM_PROTOCOL_INFO
, FROM_PROTOCOL_INFO
},
524 static const int ws_aiflag_map
[][2] =
526 MAP_OPTION( AI_PASSIVE
),
527 MAP_OPTION( AI_CANONNAME
),
528 MAP_OPTION( AI_NUMERICHOST
),
529 #ifdef AI_NUMERICSERV
530 MAP_OPTION( AI_NUMERICSERV
),
532 MAP_OPTION( AI_V4MAPPED
),
533 MAP_OPTION( AI_ADDRCONFIG
),
536 static const int ws_niflag_map
[][2] =
538 MAP_OPTION( NI_NOFQDN
),
539 MAP_OPTION( NI_NUMERICHOST
),
540 MAP_OPTION( NI_NAMEREQD
),
541 MAP_OPTION( NI_NUMERICSERV
),
542 MAP_OPTION( NI_DGRAM
),
545 static const int ws_eai_map
[][2] =
547 MAP_OPTION( EAI_AGAIN
),
548 MAP_OPTION( EAI_BADFLAGS
),
549 MAP_OPTION( EAI_FAIL
),
550 MAP_OPTION( EAI_FAMILY
),
551 MAP_OPTION( EAI_MEMORY
),
552 /* Note: EAI_NODATA is deprecated, but still
553 * used by Windows and Linux... We map the newer
554 * EAI_NONAME to EAI_NODATA for now until Windows
558 MAP_OPTION( EAI_NODATA
),
561 { WS_EAI_NODATA
, EAI_NONAME
},
564 MAP_OPTION( EAI_SERVICE
),
565 MAP_OPTION( EAI_SOCKTYPE
),
569 static const char magic_loopback_addr
[] = {127, 12, 34, 56};
571 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
573 static inline WSACMSGHDR
*fill_control_message(int level
, int type
, WSACMSGHDR
*current
, ULONG
*maxsize
, void *data
, int len
)
575 ULONG msgsize
= sizeof(WSACMSGHDR
) + WSA_CMSG_ALIGN(len
);
576 char *ptr
= (char *) current
+ sizeof(WSACMSGHDR
);
578 /* Make sure there is at least enough room for this entry */
579 if (msgsize
> *maxsize
)
582 /* Fill in the entry */
583 current
->cmsg_len
= sizeof(WSACMSGHDR
) + len
;
584 current
->cmsg_level
= level
;
585 current
->cmsg_type
= type
;
586 memcpy(ptr
, data
, len
);
587 /* Return the pointer to where next entry should go */
588 return (WSACMSGHDR
*) (ptr
+ WSA_CMSG_ALIGN(len
));
590 #endif /* IP_PKTINFO */
592 static inline int convert_control_headers(struct msghdr
*hdr
, WSABUF
*control
)
595 WSACMSGHDR
*cmsg_win
= (WSACMSGHDR
*) control
->buf
, *ptr
;
596 ULONG ctlsize
= control
->len
;
597 struct cmsghdr
*cmsg_unix
;
600 /* Loop over all the headers, converting as appropriate */
601 for (cmsg_unix
= CMSG_FIRSTHDR(hdr
); cmsg_unix
!= NULL
; cmsg_unix
= CMSG_NXTHDR(hdr
, cmsg_unix
))
603 switch(cmsg_unix
->cmsg_level
)
606 switch(cmsg_unix
->cmsg_type
)
610 /* Convert the Unix IP_PKTINFO structure to the Windows version */
611 struct in_pktinfo
*data_unix
= (struct in_pktinfo
*) CMSG_DATA(cmsg_unix
);
612 struct WS_in_pktinfo data_win
;
614 memcpy(&data_win
.ipi_addr
,&data_unix
->ipi_addr
.s_addr
,4); /* 4 bytes = 32 address bits */
615 data_win
.ipi_ifindex
= data_unix
->ipi_ifindex
;
616 ptr
= fill_control_message(WS_IPPROTO_IP
, WS_IP_PKTINFO
, ptr
, &ctlsize
,
617 (void*)&data_win
, sizeof(data_win
));
618 if (!ptr
) goto error
;
621 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix
->cmsg_type
);
626 FIXME("Unhandled message header level %d\n", cmsg_unix
->cmsg_level
);
632 /* Set the length of the returned control headers */
633 control
->len
= (ptr
== NULL
? 0 : (char*)ptr
- (char*)cmsg_win
);
634 return (ptr
!= NULL
);
635 #else /* IP_PKTINFO */
638 #endif /* IP_PKTINFO */
640 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
642 /* ----------------------------------- error handling */
644 static NTSTATUS
sock_get_ntstatus( int err
)
648 case EBADF
: return STATUS_INVALID_HANDLE
;
649 case EBUSY
: return STATUS_DEVICE_BUSY
;
651 case EACCES
: return STATUS_ACCESS_DENIED
;
652 case EFAULT
: return STATUS_NO_MEMORY
;
653 case EINVAL
: return STATUS_INVALID_PARAMETER
;
655 case EMFILE
: return STATUS_TOO_MANY_OPENED_FILES
;
656 case EWOULDBLOCK
: return STATUS_CANT_WAIT
;
657 case EINPROGRESS
: return STATUS_PENDING
;
658 case EALREADY
: return STATUS_NETWORK_BUSY
;
659 case ENOTSOCK
: return STATUS_OBJECT_TYPE_MISMATCH
;
660 case EDESTADDRREQ
: return STATUS_INVALID_PARAMETER
;
661 case EMSGSIZE
: return STATUS_BUFFER_OVERFLOW
;
662 case EPROTONOSUPPORT
:
663 case ESOCKTNOSUPPORT
:
666 case EPROTOTYPE
: return STATUS_NOT_SUPPORTED
;
667 case ENOPROTOOPT
: return STATUS_INVALID_PARAMETER
;
668 case EOPNOTSUPP
: return STATUS_NOT_SUPPORTED
;
669 case EADDRINUSE
: return STATUS_ADDRESS_ALREADY_ASSOCIATED
;
670 case EADDRNOTAVAIL
: return STATUS_INVALID_PARAMETER
;
671 case ECONNREFUSED
: return STATUS_CONNECTION_REFUSED
;
672 case ESHUTDOWN
: return STATUS_PIPE_DISCONNECTED
;
673 case ENOTCONN
: return STATUS_CONNECTION_DISCONNECTED
;
674 case ETIMEDOUT
: return STATUS_IO_TIMEOUT
;
675 case ENETUNREACH
: return STATUS_NETWORK_UNREACHABLE
;
676 case ENETDOWN
: return STATUS_NETWORK_BUSY
;
678 case ECONNRESET
: return STATUS_CONNECTION_RESET
;
679 case ECONNABORTED
: return STATUS_CONNECTION_ABORTED
;
681 case 0: return STATUS_SUCCESS
;
683 WARN("Unknown errno %d!\n", err
);
684 return STATUS_UNSUCCESSFUL
;
688 static UINT
sock_get_error( int err
)
692 case EINTR
: return WSAEINTR
;
693 case EBADF
: return WSAEBADF
;
695 case EACCES
: return WSAEACCES
;
696 case EFAULT
: return WSAEFAULT
;
697 case EINVAL
: return WSAEINVAL
;
698 case EMFILE
: return WSAEMFILE
;
699 case EWOULDBLOCK
: return WSAEWOULDBLOCK
;
700 case EINPROGRESS
: return WSAEINPROGRESS
;
701 case EALREADY
: return WSAEALREADY
;
702 case ENOTSOCK
: return WSAENOTSOCK
;
703 case EDESTADDRREQ
: return WSAEDESTADDRREQ
;
704 case EMSGSIZE
: return WSAEMSGSIZE
;
705 case EPROTOTYPE
: return WSAEPROTOTYPE
;
706 case ENOPROTOOPT
: return WSAENOPROTOOPT
;
707 case EPROTONOSUPPORT
: return WSAEPROTONOSUPPORT
;
708 case ESOCKTNOSUPPORT
: return WSAESOCKTNOSUPPORT
;
709 case EOPNOTSUPP
: return WSAEOPNOTSUPP
;
710 case EPFNOSUPPORT
: return WSAEPFNOSUPPORT
;
711 case EAFNOSUPPORT
: return WSAEAFNOSUPPORT
;
712 case EADDRINUSE
: return WSAEADDRINUSE
;
713 case EADDRNOTAVAIL
: return WSAEADDRNOTAVAIL
;
714 case ENETDOWN
: return WSAENETDOWN
;
715 case ENETUNREACH
: return WSAENETUNREACH
;
716 case ENETRESET
: return WSAENETRESET
;
717 case ECONNABORTED
: return WSAECONNABORTED
;
719 case ECONNRESET
: return WSAECONNRESET
;
720 case ENOBUFS
: return WSAENOBUFS
;
721 case EISCONN
: return WSAEISCONN
;
722 case ENOTCONN
: return WSAENOTCONN
;
723 case ESHUTDOWN
: return WSAESHUTDOWN
;
724 case ETOOMANYREFS
: return WSAETOOMANYREFS
;
725 case ETIMEDOUT
: return WSAETIMEDOUT
;
726 case ECONNREFUSED
: return WSAECONNREFUSED
;
727 case ELOOP
: return WSAELOOP
;
728 case ENAMETOOLONG
: return WSAENAMETOOLONG
;
729 case EHOSTDOWN
: return WSAEHOSTDOWN
;
730 case EHOSTUNREACH
: return WSAEHOSTUNREACH
;
731 case ENOTEMPTY
: return WSAENOTEMPTY
;
733 case EPROCLIM
: return WSAEPROCLIM
;
736 case EUSERS
: return WSAEUSERS
;
739 case EDQUOT
: return WSAEDQUOT
;
742 case ESTALE
: return WSAESTALE
;
745 case EREMOTE
: return WSAEREMOTE
;
748 /* just in case we ever get here and there are no problems */
751 WARN("Unknown errno %d!\n", err
);
752 return WSAEOPNOTSUPP
;
756 static UINT
wsaErrno(void)
758 int loc_errno
= errno
;
759 WARN("errno %d, (%s).\n", loc_errno
, strerror(loc_errno
));
761 return sock_get_error( loc_errno
);
764 /* most ws2 overlapped functions return an ntstatus-based error code */
765 static NTSTATUS
wsaErrStatus(void)
767 int loc_errno
= errno
;
768 WARN("errno %d, (%s).\n", loc_errno
, strerror(loc_errno
));
770 return sock_get_ntstatus(loc_errno
);
773 static UINT
wsaHerrno(int loc_errno
)
775 WARN("h_errno %d.\n", loc_errno
);
779 case HOST_NOT_FOUND
: return WSAHOST_NOT_FOUND
;
780 case TRY_AGAIN
: return WSATRY_AGAIN
;
781 case NO_RECOVERY
: return WSANO_RECOVERY
;
782 case NO_DATA
: return WSANO_DATA
;
783 case ENOBUFS
: return WSAENOBUFS
;
787 WARN("Unknown h_errno %d!\n", loc_errno
);
788 return WSAEOPNOTSUPP
;
792 static inline DWORD
NtStatusToWSAError( const DWORD status
)
794 /* We only need to cover the status codes set by server async request handling */
798 case STATUS_SUCCESS
: wserr
= 0; break;
799 case STATUS_PENDING
: wserr
= WSA_IO_PENDING
; break;
800 case STATUS_OBJECT_TYPE_MISMATCH
: wserr
= WSAENOTSOCK
; break;
801 case STATUS_INVALID_HANDLE
: wserr
= WSAEBADF
; break;
802 case STATUS_INVALID_PARAMETER
: wserr
= WSAEINVAL
; break;
803 case STATUS_PIPE_DISCONNECTED
: wserr
= WSAESHUTDOWN
; break;
804 case STATUS_NETWORK_BUSY
: wserr
= WSAEALREADY
; break;
805 case STATUS_NETWORK_UNREACHABLE
: wserr
= WSAENETUNREACH
; break;
806 case STATUS_CONNECTION_REFUSED
: wserr
= WSAECONNREFUSED
; break;
807 case STATUS_CONNECTION_DISCONNECTED
: wserr
= WSAENOTCONN
; break;
808 case STATUS_CONNECTION_RESET
: wserr
= WSAECONNRESET
; break;
809 case STATUS_CONNECTION_ABORTED
: wserr
= WSAECONNABORTED
; break;
810 case STATUS_CANCELLED
: wserr
= WSA_OPERATION_ABORTED
; break;
811 case STATUS_ADDRESS_ALREADY_ASSOCIATED
: wserr
= WSAEADDRINUSE
; break;
812 case STATUS_IO_TIMEOUT
:
813 case STATUS_TIMEOUT
: wserr
= WSAETIMEDOUT
; break;
814 case STATUS_NO_MEMORY
: wserr
= WSAEFAULT
; break;
815 case STATUS_ACCESS_DENIED
: wserr
= WSAEACCES
; break;
816 case STATUS_TOO_MANY_OPENED_FILES
: wserr
= WSAEMFILE
; break;
817 case STATUS_CANT_WAIT
: wserr
= WSAEWOULDBLOCK
; break;
818 case STATUS_BUFFER_OVERFLOW
: wserr
= WSAEMSGSIZE
; break;
819 case STATUS_NOT_SUPPORTED
: wserr
= WSAEOPNOTSUPP
; break;
820 case STATUS_HOST_UNREACHABLE
: wserr
= WSAEHOSTUNREACH
; break;
823 wserr
= RtlNtStatusToDosError( status
);
824 FIXME( "Status code %08x converted to DOS error code %x\n", status
, wserr
);
829 /* set last error code from NT status without mapping WSA errors */
830 static inline unsigned int set_error( unsigned int err
)
834 err
= NtStatusToWSAError( err
);
840 static inline int get_sock_fd( SOCKET s
, DWORD access
, unsigned int *options
)
843 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s
), access
, &fd
, options
) ))
848 static inline void release_sock_fd( SOCKET s
, int fd
)
850 wine_server_release_fd( SOCKET2HANDLE(s
), fd
);
853 static void _enable_event( HANDLE s
, unsigned int event
,
854 unsigned int sstate
, unsigned int cstate
)
856 SERVER_START_REQ( enable_socket_event
)
858 req
->handle
= wine_server_obj_handle( s
);
860 req
->sstate
= sstate
;
861 req
->cstate
= cstate
;
862 wine_server_call( req
);
867 static NTSTATUS
_is_blocking(SOCKET s
, BOOL
*ret
)
870 SERVER_START_REQ( get_socket_event
)
872 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
873 req
->service
= FALSE
;
875 status
= wine_server_call( req
);
876 *ret
= (reply
->state
& FD_WINE_NONBLOCKING
) == 0;
882 static unsigned int _get_sock_mask(SOCKET s
)
885 SERVER_START_REQ( get_socket_event
)
887 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
888 req
->service
= FALSE
;
890 wine_server_call( req
);
897 static void _sync_sock_state(SOCKET s
)
900 /* do a dummy wineserver request in order to let
901 the wineserver run through its select loop once */
902 (void)_is_blocking(s
, &dummy
);
905 static int _get_sock_error(SOCKET s
, unsigned int bit
)
907 int events
[FD_MAX_EVENTS
];
909 SERVER_START_REQ( get_socket_event
)
911 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
912 req
->service
= FALSE
;
914 wine_server_set_reply( req
, events
, sizeof(events
) );
915 wine_server_call( req
);
921 static struct per_thread_data
*get_per_thread_data(void)
923 struct per_thread_data
* ptb
= NtCurrentTeb()->WinSockData
;
924 /* lazy initialization */
927 ptb
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(*ptb
) );
928 NtCurrentTeb()->WinSockData
= ptb
;
933 static void free_per_thread_data(void)
935 struct per_thread_data
* ptb
= NtCurrentTeb()->WinSockData
;
939 /* delete scratch buffers */
940 HeapFree( GetProcessHeap(), 0, ptb
->he_buffer
);
941 HeapFree( GetProcessHeap(), 0, ptb
->se_buffer
);
942 HeapFree( GetProcessHeap(), 0, ptb
->pe_buffer
);
943 ptb
->he_buffer
= NULL
;
944 ptb
->se_buffer
= NULL
;
945 ptb
->pe_buffer
= NULL
;
947 HeapFree( GetProcessHeap(), 0, ptb
);
948 NtCurrentTeb()->WinSockData
= NULL
;
951 /***********************************************************************
952 * DllMain (WS2_32.init)
954 BOOL WINAPI
DllMain(HINSTANCE hInstDLL
, DWORD fdwReason
, LPVOID fImpLoad
)
956 TRACE("%p 0x%x %p\n", hInstDLL
, fdwReason
, fImpLoad
);
958 case DLL_PROCESS_ATTACH
:
960 case DLL_PROCESS_DETACH
:
962 free_per_thread_data();
963 DeleteCriticalSection(&csWSgetXXXbyYYY
);
965 case DLL_THREAD_DETACH
:
966 free_per_thread_data();
972 /***********************************************************************
975 * Converts socket flags from Windows format.
976 * Return 1 if converted, 0 if not (error).
978 static int convert_sockopt(INT
*level
, INT
*optname
)
985 for(i
=0; i
<sizeof(ws_sock_map
)/sizeof(ws_sock_map
[0]); i
++) {
986 if( ws_sock_map
[i
][0] == *optname
)
988 *optname
= ws_sock_map
[i
][1];
992 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname
);
995 *level
= IPPROTO_TCP
;
996 for(i
=0; i
<sizeof(ws_tcp_map
)/sizeof(ws_tcp_map
[0]); i
++) {
997 if ( ws_tcp_map
[i
][0] == *optname
)
999 *optname
= ws_tcp_map
[i
][1];
1003 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname
);
1006 *level
= IPPROTO_IP
;
1007 for(i
=0; i
<sizeof(ws_ip_map
)/sizeof(ws_ip_map
[0]); i
++) {
1008 if (ws_ip_map
[i
][0] == *optname
)
1010 *optname
= ws_ip_map
[i
][1];
1014 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname
);
1016 case WS_IPPROTO_IPV6
:
1017 *level
= IPPROTO_IPV6
;
1018 for(i
=0; i
<sizeof(ws_ipv6_map
)/sizeof(ws_ipv6_map
[0]); i
++) {
1019 if (ws_ipv6_map
[i
][0] == *optname
)
1021 *optname
= ws_ipv6_map
[i
][1];
1025 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname
);
1027 default: FIXME("Unimplemented or unknown socket level\n");
1032 /* ----------------------------------- Per-thread info (or per-process?) */
1034 static char *strdup_lower(const char *str
)
1037 char *ret
= HeapAlloc( GetProcessHeap(), 0, strlen(str
) + 1 );
1041 for (i
= 0; str
[i
]; i
++) ret
[i
] = tolower(str
[i
]);
1044 else SetLastError(WSAENOBUFS
);
1048 static inline int sock_error_p(int s
)
1050 unsigned int optval
;
1051 socklen_t optlen
= sizeof(optval
);
1052 getsockopt(s
, SOL_SOCKET
, SO_ERROR
, (void *) &optval
, &optlen
);
1053 if (optval
) WARN("\t[%i] error: %d\n", s
, optval
);
1057 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1058 * from an fd and return the value converted to milli seconds
1059 * or -1 if there is an infinite time out */
1060 static inline int get_rcvsnd_timeo( int fd
, int optname
)
1063 socklen_t len
= sizeof(tv
);
1064 int ret
= getsockopt(fd
, SOL_SOCKET
, optname
, &tv
, &len
);
1066 ret
= tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000;
1067 if( ret
<= 0 ) /* tv == {0,0} means infinite time out */
1072 /* macro wrappers for portability */
1074 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
1076 #define GET_RCVTIMEO(fd) (-1)
1080 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
1082 #define GET_SNDTIMEO(fd) (-1)
1085 /* utility: given an fd, will block until one of the events occurs */
1086 static inline int do_block( int fd
, int events
, int timeout
)
1092 pfd
.events
= events
;
1094 while ((ret
= poll(&pfd
, 1, timeout
)) < 0)
1105 convert_af_w2u(int windowsaf
) {
1108 for (i
=0;i
<sizeof(ws_af_map
)/sizeof(ws_af_map
[0]);i
++)
1109 if (ws_af_map
[i
][0] == windowsaf
)
1110 return ws_af_map
[i
][1];
1111 FIXME("unhandled Windows address family %d\n", windowsaf
);
1116 convert_af_u2w(int unixaf
) {
1119 for (i
=0;i
<sizeof(ws_af_map
)/sizeof(ws_af_map
[0]);i
++)
1120 if (ws_af_map
[i
][1] == unixaf
)
1121 return ws_af_map
[i
][0];
1122 FIXME("unhandled UNIX address family %d\n", unixaf
);
1127 convert_proto_w2u(int windowsproto
) {
1130 for (i
=0;i
<sizeof(ws_proto_map
)/sizeof(ws_proto_map
[0]);i
++)
1131 if (ws_proto_map
[i
][0] == windowsproto
)
1132 return ws_proto_map
[i
][1];
1134 /* check for extended IPX */
1135 if (IS_IPX_PROTO(windowsproto
))
1136 return windowsproto
;
1138 FIXME("unhandled Windows socket protocol %d\n", windowsproto
);
1143 convert_proto_u2w(int unixproto
) {
1146 for (i
=0;i
<sizeof(ws_proto_map
)/sizeof(ws_proto_map
[0]);i
++)
1147 if (ws_proto_map
[i
][1] == unixproto
)
1148 return ws_proto_map
[i
][0];
1150 /* if value is inside IPX range just return it - the kernel simply
1151 * echoes the value used in the socket() function */
1152 if (IS_IPX_PROTO(unixproto
))
1155 FIXME("unhandled UNIX socket protocol %d\n", unixproto
);
1160 convert_socktype_w2u(int windowssocktype
) {
1163 for (i
=0;i
<sizeof(ws_socktype_map
)/sizeof(ws_socktype_map
[0]);i
++)
1164 if (ws_socktype_map
[i
][0] == windowssocktype
)
1165 return ws_socktype_map
[i
][1];
1166 FIXME("unhandled Windows socket type %d\n", windowssocktype
);
1171 convert_socktype_u2w(int unixsocktype
) {
1174 for (i
=0;i
<sizeof(ws_socktype_map
)/sizeof(ws_socktype_map
[0]);i
++)
1175 if (ws_socktype_map
[i
][1] == unixsocktype
)
1176 return ws_socktype_map
[i
][0];
1177 FIXME("unhandled UNIX socket type %d\n", unixsocktype
);
1181 static int set_ipx_packettype(int sock
, int ptype
)
1184 int fd
= get_sock_fd( sock
, 0, NULL
), ret
= 0;
1185 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype
, fd
);
1187 if (fd
== -1) return SOCKET_ERROR
;
1189 /* We try to set the ipx type on ipx socket level. */
1191 if(setsockopt(fd
, SOL_IPX
, IPX_TYPE
, &ptype
, sizeof(ptype
)) == -1)
1193 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1199 /* Should we retrieve val using a getsockopt call and then
1200 * set the modified one? */
1202 setsockopt(fd
, 0, SO_DEFAULT_HEADERS
, &val
, sizeof(struct ipx
));
1205 release_sock_fd( sock
, fd
);
1208 WARN("IPX support is not enabled, can't set packet type\n");
1209 return SOCKET_ERROR
;
1213 /* ----------------------------------- API -----
1215 * Init / cleanup / error checking.
1218 /***********************************************************************
1219 * WSAStartup (WS2_32.115)
1221 int WINAPI
WSAStartup(WORD wVersionRequested
, LPWSADATA lpWSAData
)
1223 TRACE("verReq=%x\n", wVersionRequested
);
1225 if (LOBYTE(wVersionRequested
) < 1)
1226 return WSAVERNOTSUPPORTED
;
1228 if (!lpWSAData
) return WSAEINVAL
;
1232 /* that's the whole of the negotiation for now */
1233 lpWSAData
->wVersion
= wVersionRequested
;
1234 /* return winsock information */
1235 lpWSAData
->wHighVersion
= 0x0202;
1236 strcpy(lpWSAData
->szDescription
, "WinSock 2.0" );
1237 strcpy(lpWSAData
->szSystemStatus
, "Running" );
1238 lpWSAData
->iMaxSockets
= WS_MAX_SOCKETS_PER_PROCESS
;
1239 lpWSAData
->iMaxUdpDg
= WS_MAX_UDP_DATAGRAM
;
1240 /* don't do anything with lpWSAData->lpVendorInfo */
1241 /* (some apps don't allocate the space for this field) */
1243 TRACE("succeeded starts: %d\n", num_startup
);
1248 /***********************************************************************
1249 * WSACleanup (WS2_32.116)
1251 INT WINAPI
WSACleanup(void)
1255 TRACE("pending cleanups: %d\n", num_startup
);
1258 SetLastError(WSANOTINITIALISED
);
1259 return SOCKET_ERROR
;
1263 /***********************************************************************
1264 * WSAGetLastError (WS2_32.111)
1266 INT WINAPI
WSAGetLastError(void)
1268 return GetLastError();
1271 /***********************************************************************
1272 * WSASetLastError (WS2_32.112)
1274 void WINAPI
WSASetLastError(INT iError
) {
1275 SetLastError(iError
);
1278 static struct WS_hostent
*check_buffer_he(int size
)
1280 struct per_thread_data
* ptb
= get_per_thread_data();
1283 if (ptb
->he_len
>= size
) return ptb
->he_buffer
;
1284 HeapFree( GetProcessHeap(), 0, ptb
->he_buffer
);
1286 ptb
->he_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->he_len
= size
) );
1287 if (!ptb
->he_buffer
) SetLastError(WSAENOBUFS
);
1288 return ptb
->he_buffer
;
1291 static struct WS_servent
*check_buffer_se(int size
)
1293 struct per_thread_data
* ptb
= get_per_thread_data();
1296 if (ptb
->se_len
>= size
) return ptb
->se_buffer
;
1297 HeapFree( GetProcessHeap(), 0, ptb
->se_buffer
);
1299 ptb
->se_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->se_len
= size
) );
1300 if (!ptb
->se_buffer
) SetLastError(WSAENOBUFS
);
1301 return ptb
->se_buffer
;
1304 static struct WS_protoent
*check_buffer_pe(int size
)
1306 struct per_thread_data
* ptb
= get_per_thread_data();
1309 if (ptb
->pe_len
>= size
) return ptb
->pe_buffer
;
1310 HeapFree( GetProcessHeap(), 0, ptb
->pe_buffer
);
1312 ptb
->pe_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->pe_len
= size
) );
1313 if (!ptb
->pe_buffer
) SetLastError(WSAENOBUFS
);
1314 return ptb
->pe_buffer
;
1317 /* ----------------------------------- i/o APIs */
1319 static inline BOOL
supported_pf(int pf
)
1339 static inline BOOL
supported_protocol(int protocol
)
1342 for (i
= 0; i
< sizeof(valid_protocols
) / sizeof(valid_protocols
[0]); i
++)
1343 if (protocol
== valid_protocols
[i
])
1348 /**********************************************************************/
1350 /* Returns the length of the converted address if successful, 0 if it was too small to
1353 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr
* wsaddr
, int wsaddrlen
,
1354 union generic_unix_sockaddr
*uaddr
)
1356 unsigned int uaddrlen
= 0;
1358 switch (wsaddr
->sa_family
)
1363 const struct WS_sockaddr_ipx
* wsipx
=(const struct WS_sockaddr_ipx
*)wsaddr
;
1364 struct sockaddr_ipx
* uipx
= (struct sockaddr_ipx
*)uaddr
;
1366 if (wsaddrlen
<sizeof(struct WS_sockaddr_ipx
))
1369 uaddrlen
= sizeof(struct sockaddr_ipx
);
1370 memset( uaddr
, 0, uaddrlen
);
1371 uipx
->sipx_family
=AF_IPX
;
1372 uipx
->sipx_port
=wsipx
->sa_socket
;
1373 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1376 memcpy(&uipx
->sipx_network
,wsipx
->sa_netnum
,sizeof(uipx
->sipx_network
)+sizeof(uipx
->sipx_node
));
1377 #ifdef IPX_FRAME_NONE
1378 uipx
->sipx_type
=IPX_FRAME_NONE
;
1384 struct sockaddr_in6
* uin6
= (struct sockaddr_in6
*)uaddr
;
1385 const struct WS_sockaddr_in6
* win6
= (const struct WS_sockaddr_in6
*)wsaddr
;
1387 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1388 * scope_id, one without.
1390 if (wsaddrlen
>= sizeof(struct WS_sockaddr_in6_old
)) {
1391 uaddrlen
= sizeof(struct sockaddr_in6
);
1392 memset( uaddr
, 0, uaddrlen
);
1393 uin6
->sin6_family
= AF_INET6
;
1394 uin6
->sin6_port
= win6
->sin6_port
;
1395 uin6
->sin6_flowinfo
= win6
->sin6_flowinfo
;
1396 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1397 if (wsaddrlen
>= sizeof(struct WS_sockaddr_in6
)) uin6
->sin6_scope_id
= win6
->sin6_scope_id
;
1399 memcpy(&uin6
->sin6_addr
,&win6
->sin6_addr
,16); /* 16 bytes = 128 address bits */
1402 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen
);
1406 struct sockaddr_in
* uin
= (struct sockaddr_in
*)uaddr
;
1407 const struct WS_sockaddr_in
* win
= (const struct WS_sockaddr_in
*)wsaddr
;
1409 if (wsaddrlen
<sizeof(struct WS_sockaddr_in
))
1411 uaddrlen
= sizeof(struct sockaddr_in
);
1412 memset( uaddr
, 0, uaddrlen
);
1413 uin
->sin_family
= AF_INET
;
1414 uin
->sin_port
= win
->sin_port
;
1415 memcpy(&uin
->sin_addr
,&win
->sin_addr
,4); /* 4 bytes = 32 address bits */
1420 struct sockaddr_irda
*uin
= (struct sockaddr_irda
*)uaddr
;
1421 const SOCKADDR_IRDA
*win
= (const SOCKADDR_IRDA
*)wsaddr
;
1423 if (wsaddrlen
< sizeof(SOCKADDR_IRDA
))
1425 uaddrlen
= sizeof(struct sockaddr_irda
);
1426 memset( uaddr
, 0, uaddrlen
);
1427 uin
->sir_family
= AF_IRDA
;
1428 if (!strncmp( win
->irdaServiceName
, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1430 unsigned int lsap_sel
= 0;
1432 sscanf( win
->irdaServiceName
, "LSAP-SEL%u", &lsap_sel
);
1433 uin
->sir_lsap_sel
= lsap_sel
;
1437 uin
->sir_lsap_sel
= LSAP_ANY
;
1438 memcpy( uin
->sir_name
, win
->irdaServiceName
, 25 );
1440 memcpy( &uin
->sir_addr
, win
->irdaDeviceID
, sizeof(uin
->sir_addr
) );
1444 case WS_AF_UNSPEC
: {
1445 /* Try to determine the needed space by the passed windows sockaddr space */
1446 switch (wsaddrlen
) {
1447 default: /* likely an ipv4 address */
1448 case sizeof(struct WS_sockaddr_in
):
1449 uaddrlen
= sizeof(struct sockaddr_in
);
1452 case sizeof(struct WS_sockaddr_ipx
):
1453 uaddrlen
= sizeof(struct sockaddr_ipx
);
1457 case sizeof(SOCKADDR_IRDA
):
1458 uaddrlen
= sizeof(struct sockaddr_irda
);
1461 case sizeof(struct WS_sockaddr_in6
):
1462 case sizeof(struct WS_sockaddr_in6_old
):
1463 uaddrlen
= sizeof(struct sockaddr_in6
);
1466 memset( uaddr
, 0, uaddrlen
);
1470 FIXME("Unknown address family %d, return NULL.\n", wsaddr
->sa_family
);
1476 static BOOL
is_sockaddr_bound(const struct sockaddr
*uaddr
, int uaddrlen
)
1478 switch (uaddr
->sa_family
)
1483 static const struct sockaddr_ipx emptyAddr
;
1484 struct sockaddr_ipx
*ipx
= (struct sockaddr_ipx
*) uaddr
;
1485 return ipx
->sipx_port
1486 || memcmp(&ipx
->sipx_network
, &emptyAddr
.sipx_network
, sizeof(emptyAddr
.sipx_network
))
1487 || memcmp(&ipx
->sipx_node
, &emptyAddr
.sipx_node
, sizeof(emptyAddr
.sipx_node
));
1492 static const struct sockaddr_in6 emptyAddr
;
1493 const struct sockaddr_in6
*in6
= (const struct sockaddr_in6
*) uaddr
;
1494 return in6
->sin6_port
|| memcmp(&in6
->sin6_addr
, &emptyAddr
.sin6_addr
, sizeof(struct in6_addr
));
1498 static const struct sockaddr_in emptyAddr
;
1499 const struct sockaddr_in
*in
= (const struct sockaddr_in
*) uaddr
;
1500 return in
->sin_port
|| memcmp(&in
->sin_addr
, &emptyAddr
.sin_addr
, sizeof(struct in_addr
));
1505 FIXME("unknown address family %d\n", uaddr
->sa_family
);
1510 /* Returns 0 if successful, -1 if the buffer is too small */
1511 static int ws_sockaddr_u2ws(const struct sockaddr
* uaddr
, struct WS_sockaddr
* wsaddr
, int* wsaddrlen
)
1515 switch(uaddr
->sa_family
)
1520 const struct sockaddr_ipx
* uipx
=(const struct sockaddr_ipx
*)uaddr
;
1521 struct WS_sockaddr_ipx
* wsipx
=(struct WS_sockaddr_ipx
*)wsaddr
;
1524 switch (*wsaddrlen
) /* how much can we copy? */
1528 *wsaddrlen
= sizeof(*wsipx
);
1529 wsipx
->sa_socket
=uipx
->sipx_port
;
1533 memcpy(wsipx
->sa_nodenum
,uipx
->sipx_node
,sizeof(wsipx
->sa_nodenum
));
1541 memcpy(wsipx
->sa_netnum
,&uipx
->sipx_network
,sizeof(wsipx
->sa_netnum
));
1547 wsipx
->sa_family
=WS_AF_IPX
;
1559 const struct sockaddr_irda
*uin
= (const struct sockaddr_irda
*)uaddr
;
1560 SOCKADDR_IRDA
*win
= (SOCKADDR_IRDA
*)wsaddr
;
1562 if (*wsaddrlen
< sizeof(SOCKADDR_IRDA
))
1564 win
->irdaAddressFamily
= WS_AF_IRDA
;
1565 memcpy( win
->irdaDeviceID
, &uin
->sir_addr
, sizeof(win
->irdaDeviceID
) );
1566 if (uin
->sir_lsap_sel
!= LSAP_ANY
)
1567 sprintf( win
->irdaServiceName
, "LSAP-SEL%u", uin
->sir_lsap_sel
);
1569 memcpy( win
->irdaServiceName
, uin
->sir_name
,
1570 sizeof(win
->irdaServiceName
) );
1575 const struct sockaddr_in6
* uin6
= (const struct sockaddr_in6
*)uaddr
;
1576 struct WS_sockaddr_in6_old
* win6old
= (struct WS_sockaddr_in6_old
*)wsaddr
;
1578 if (*wsaddrlen
< sizeof(struct WS_sockaddr_in6_old
))
1580 win6old
->sin6_family
= WS_AF_INET6
;
1581 win6old
->sin6_port
= uin6
->sin6_port
;
1582 win6old
->sin6_flowinfo
= uin6
->sin6_flowinfo
;
1583 memcpy(&win6old
->sin6_addr
,&uin6
->sin6_addr
,16); /* 16 bytes = 128 address bits */
1584 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1585 if (*wsaddrlen
>= sizeof(struct WS_sockaddr_in6
)) {
1586 struct WS_sockaddr_in6
* win6
= (struct WS_sockaddr_in6
*)wsaddr
;
1587 win6
->sin6_scope_id
= uin6
->sin6_scope_id
;
1588 *wsaddrlen
= sizeof(struct WS_sockaddr_in6
);
1591 *wsaddrlen
= sizeof(struct WS_sockaddr_in6_old
);
1593 *wsaddrlen
= sizeof(struct WS_sockaddr_in6_old
);
1598 const struct sockaddr_in
* uin
= (const struct sockaddr_in
*)uaddr
;
1599 struct WS_sockaddr_in
* win
= (struct WS_sockaddr_in
*)wsaddr
;
1601 if (*wsaddrlen
< sizeof(struct WS_sockaddr_in
))
1603 win
->sin_family
= WS_AF_INET
;
1604 win
->sin_port
= uin
->sin_port
;
1605 memcpy(&win
->sin_addr
,&uin
->sin_addr
,4); /* 4 bytes = 32 address bits */
1606 memset(win
->sin_zero
, 0, 8); /* Make sure the null padding is null */
1607 *wsaddrlen
= sizeof(struct WS_sockaddr_in
);
1611 memset(wsaddr
,0,*wsaddrlen
);
1615 FIXME("Unknown address family %d\n", uaddr
->sa_family
);
1621 static INT
WS_DuplicateSocket(BOOL unicode
, SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOW lpProtocolInfo
)
1625 WSAPROTOCOL_INFOW infow
;
1627 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
1628 unicode
, s
, dwProcessId
, lpProtocolInfo
);
1630 if (!ws_protocol_info(s
, unicode
, &infow
, &size
))
1631 return SOCKET_ERROR
;
1633 if (!(hProcess
= OpenProcess(PROCESS_DUP_HANDLE
, FALSE
, dwProcessId
)))
1635 SetLastError(WSAEINVAL
);
1636 return SOCKET_ERROR
;
1639 if (!lpProtocolInfo
)
1641 CloseHandle(hProcess
);
1642 SetLastError(WSAEFAULT
);
1643 return SOCKET_ERROR
;
1646 /* I don't know what the real Windoze does next, this is a hack */
1647 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
1648 * the target use the global duplicate, or we could copy a reference to us to the structure
1649 * and let the target duplicate it from us, but let's do it as simple as possible */
1650 memcpy(lpProtocolInfo
, &infow
, size
);
1651 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s
),
1652 hProcess
, (LPHANDLE
)&lpProtocolInfo
->dwServiceFlags3
,
1653 0, FALSE
, DUPLICATE_SAME_ACCESS
);
1654 CloseHandle(hProcess
);
1655 lpProtocolInfo
->dwServiceFlags4
= 0xff00ff00; /* magic */
1659 /*****************************************************************************
1660 * WS_EnterSingleProtocolW [internal]
1662 * enters the protocol information of one given protocol into the given
1666 * TRUE if a protocol was entered into the buffer.
1669 * - only implemented for IPX, SPX, SPXII, TCP, UDP
1670 * - there is no check that the operating system supports the returned
1673 static BOOL
WS_EnterSingleProtocolW( INT protocol
, WSAPROTOCOL_INFOW
* info
)
1675 memset( info
, 0, sizeof(WSAPROTOCOL_INFOW
) );
1676 info
->iProtocol
= protocol
;
1680 case WS_IPPROTO_TCP
:
1681 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_EXPEDITED_DATA
|
1682 XP1_GRACEFUL_CLOSE
| XP1_GUARANTEED_ORDER
|
1683 XP1_GUARANTEED_DELIVERY
;
1684 info
->ProviderId
= ProviderIdIP
;
1685 info
->dwCatalogEntryId
= 0x3e9;
1686 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1687 info
->ProtocolChain
.ChainLen
= 1;
1689 info
->iAddressFamily
= WS_AF_INET
;
1690 info
->iMaxSockAddr
= 0x10;
1691 info
->iMinSockAddr
= 0x10;
1692 info
->iSocketType
= WS_SOCK_STREAM
;
1693 strcpyW( info
->szProtocol
, NameTcpW
);
1696 case WS_IPPROTO_UDP
:
1697 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_SUPPORT_BROADCAST
|
1698 XP1_SUPPORT_MULTIPOINT
| XP1_MESSAGE_ORIENTED
|
1700 info
->ProviderId
= ProviderIdIP
;
1701 info
->dwCatalogEntryId
= 0x3ea;
1702 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1703 info
->ProtocolChain
.ChainLen
= 1;
1705 info
->iAddressFamily
= WS_AF_INET
;
1706 info
->iMaxSockAddr
= 0x10;
1707 info
->iMinSockAddr
= 0x10;
1708 info
->iSocketType
= WS_SOCK_DGRAM
;
1709 info
->dwMessageSize
= 0xffbb;
1710 strcpyW( info
->szProtocol
, NameUdpW
);
1713 case WS_NSPROTO_IPX
:
1714 info
->dwServiceFlags1
= XP1_PARTIAL_MESSAGE
| XP1_SUPPORT_BROADCAST
|
1715 XP1_SUPPORT_MULTIPOINT
| XP1_MESSAGE_ORIENTED
|
1717 info
->ProviderId
= ProviderIdIPX
;
1718 info
->dwCatalogEntryId
= 0x406;
1719 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1720 info
->ProtocolChain
.ChainLen
= 1;
1722 info
->iAddressFamily
= WS_AF_IPX
;
1723 info
->iMaxSockAddr
= 0x10;
1724 info
->iMinSockAddr
= 0x0e;
1725 info
->iSocketType
= WS_SOCK_DGRAM
;
1726 info
->iProtocolMaxOffset
= 0xff;
1727 info
->dwMessageSize
= 0x240;
1728 strcpyW( info
->szProtocol
, NameIpxW
);
1731 case WS_NSPROTO_SPX
:
1732 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_PSEUDO_STREAM
|
1733 XP1_MESSAGE_ORIENTED
| XP1_GUARANTEED_ORDER
|
1734 XP1_GUARANTEED_DELIVERY
;
1735 info
->ProviderId
= ProviderIdSPX
;
1736 info
->dwCatalogEntryId
= 0x407;
1737 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1738 info
->ProtocolChain
.ChainLen
= 1;
1740 info
->iAddressFamily
= WS_AF_IPX
;
1741 info
->iMaxSockAddr
= 0x10;
1742 info
->iMinSockAddr
= 0x0e;
1743 info
->iSocketType
= WS_SOCK_SEQPACKET
;
1744 info
->dwMessageSize
= 0xffffffff;
1745 strcpyW( info
->szProtocol
, NameSpxW
);
1748 case WS_NSPROTO_SPXII
:
1749 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_GRACEFUL_CLOSE
|
1750 XP1_PSEUDO_STREAM
| XP1_MESSAGE_ORIENTED
|
1751 XP1_GUARANTEED_ORDER
| XP1_GUARANTEED_DELIVERY
;
1752 info
->ProviderId
= ProviderIdSPX
;
1753 info
->dwCatalogEntryId
= 0x409;
1754 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1755 info
->ProtocolChain
.ChainLen
= 1;
1757 info
->iAddressFamily
= WS_AF_IPX
;
1758 info
->iMaxSockAddr
= 0x10;
1759 info
->iMinSockAddr
= 0x0e;
1760 info
->iSocketType
= WS_SOCK_SEQPACKET
;
1761 info
->dwMessageSize
= 0xffffffff;
1762 strcpyW( info
->szProtocol
, NameSpxIIW
);
1766 FIXME("unknown Protocol <0x%08x>\n", protocol
);
1772 /*****************************************************************************
1773 * WS_EnterSingleProtocolA [internal]
1775 * see function WS_EnterSingleProtocolW
1778 static BOOL
WS_EnterSingleProtocolA( INT protocol
, WSAPROTOCOL_INFOA
* info
)
1780 WSAPROTOCOL_INFOW infow
;
1782 memset( info
, 0, sizeof(WSAPROTOCOL_INFOA
) );
1784 ret
= WS_EnterSingleProtocolW( protocol
, &infow
);
1787 /* convert the structure from W to A */
1788 memcpy( info
, &infow
, FIELD_OFFSET( WSAPROTOCOL_INFOA
, szProtocol
) );
1789 WideCharToMultiByte( CP_ACP
, 0, infow
.szProtocol
, -1,
1790 info
->szProtocol
, WSAPROTOCOL_LEN
+1, NULL
, NULL
);
1796 static INT
WS_EnumProtocols( BOOL unicode
, const INT
*protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
)
1798 INT i
= 0, items
= 0;
1802 LPWSAPROTOCOL_INFOA a
;
1803 LPWSAPROTOCOL_INFOW w
;
1807 if (!protocols
) protocols
= valid_protocols
;
1809 while (protocols
[i
])
1811 if(supported_protocol(protocols
[i
++]))
1815 size
= items
* (unicode
? sizeof(WSAPROTOCOL_INFOW
) : sizeof(WSAPROTOCOL_INFOA
));
1817 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
1818 unicode
, protocols
, buffer
, len
, len
? *len
: 0, items
, size
);
1820 if (*len
< size
|| !buffer
)
1823 WSASetLastError(WSAENOBUFS
);
1824 return SOCKET_ERROR
;
1827 for (i
= items
= 0; protocols
[i
]; i
++)
1829 if (!supported_protocol(protocols
[i
])) continue;
1832 if (WS_EnterSingleProtocolW( protocols
[i
], &info
.w
[items
] ))
1837 if (WS_EnterSingleProtocolA( protocols
[i
], &info
.a
[items
] ))
1844 static BOOL
ws_protocol_info(SOCKET s
, int unicode
, WSAPROTOCOL_INFOW
*buffer
, int *size
)
1848 *size
= unicode
? sizeof(WSAPROTOCOL_INFOW
) : sizeof(WSAPROTOCOL_INFOA
);
1849 memset(buffer
, 0, *size
);
1851 SERVER_START_REQ( get_socket_info
)
1853 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1854 status
= wine_server_call( req
);
1857 buffer
->iAddressFamily
= convert_af_u2w(reply
->family
);
1858 buffer
->iSocketType
= convert_socktype_u2w(reply
->type
);
1859 buffer
->iProtocol
= convert_proto_u2w(reply
->protocol
);
1866 unsigned int err
= NtStatusToWSAError( status
);
1867 SetLastError( err
== WSAEBADF
? WSAENOTSOCK
: err
);
1872 WS_EnterSingleProtocolW( buffer
->iProtocol
, buffer
);
1874 WS_EnterSingleProtocolA( buffer
->iProtocol
, (WSAPROTOCOL_INFOA
*)buffer
);
1879 /**************************************************************************
1880 * Functions for handling overlapped I/O
1881 **************************************************************************/
1883 /* user APC called upon async completion */
1884 static void WINAPI
ws2_async_apc( void *arg
, IO_STATUS_BLOCK
*iosb
, ULONG reserved
)
1886 ws2_async
*wsa
= arg
;
1888 if (wsa
->completion_func
) wsa
->completion_func( NtStatusToWSAError(iosb
->u
.Status
),
1889 iosb
->Information
, wsa
->user_overlapped
,
1891 HeapFree( GetProcessHeap(), 0, wsa
);
1894 /***********************************************************************
1895 * WS2_recv (INTERNAL)
1897 * Workhorse for both synchronous and asynchronous recv() operations.
1899 static int WS2_recv( int fd
, struct ws2_async
*wsa
)
1901 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1905 union generic_unix_sockaddr unix_sockaddr
;
1908 hdr
.msg_name
= NULL
;
1912 hdr
.msg_namelen
= sizeof(unix_sockaddr
);
1913 hdr
.msg_name
= &unix_sockaddr
;
1916 hdr
.msg_namelen
= 0;
1918 hdr
.msg_iov
= wsa
->iovec
+ wsa
->first_iovec
;
1919 hdr
.msg_iovlen
= wsa
->n_iovecs
- wsa
->first_iovec
;
1920 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1921 hdr
.msg_accrights
= NULL
;
1922 hdr
.msg_accrightslen
= 0;
1924 hdr
.msg_control
= pktbuf
;
1925 hdr
.msg_controllen
= sizeof(pktbuf
);
1929 while ((n
= recvmsg(fd
, &hdr
, wsa
->flags
)) == -1)
1935 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1938 ERR("Message control headers cannot be properly supported on this system.\n");
1939 wsa
->control
->len
= 0;
1942 if (wsa
->control
&& !convert_control_headers(&hdr
, wsa
->control
))
1944 WARN("Application passed insufficient room for control headers.\n");
1945 *wsa
->lpFlags
|= WS_MSG_CTRUNC
;
1951 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1952 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1954 * quoting linux 2.6 net/ipv4/tcp.c:
1955 * "According to UNIX98, msg_name/msg_namelen are ignored
1956 * on connected socket. I was just happy when found this 8) --ANK"
1958 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1959 * connection-oriented sockets, so don't try to update lpFrom.
1961 if (wsa
->addr
&& hdr
.msg_namelen
)
1962 ws_sockaddr_u2ws( &unix_sockaddr
.addr
, wsa
->addr
, wsa
->addrlen
.ptr
);
1967 /***********************************************************************
1968 * WS2_async_recv (INTERNAL)
1970 * Handler for overlapped recv() operations.
1972 static NTSTATUS
WS2_async_recv( void* user
, IO_STATUS_BLOCK
* iosb
, NTSTATUS status
, void **apc
)
1974 ws2_async
* wsa
= user
;
1979 case STATUS_ALERTED
:
1980 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, FILE_READ_DATA
, &fd
, NULL
) ))
1983 result
= WS2_recv( fd
, wsa
);
1984 wine_server_release_fd( wsa
->hSocket
, fd
);
1987 status
= STATUS_SUCCESS
;
1988 _enable_event( wsa
->hSocket
, FD_READ
, 0, 0 );
1992 if (errno
== EAGAIN
)
1994 status
= STATUS_PENDING
;
1995 _enable_event( wsa
->hSocket
, FD_READ
, 0, 0 );
2000 status
= wsaErrStatus();
2005 if (status
!= STATUS_PENDING
)
2007 iosb
->u
.Status
= status
;
2008 iosb
->Information
= result
;
2009 *apc
= ws2_async_apc
;
2014 /* user APC called upon async accept completion */
2015 static void WINAPI
ws2_async_accept_apc( void *arg
, IO_STATUS_BLOCK
*iosb
, ULONG reserved
)
2017 struct ws2_accept_async
*wsa
= arg
;
2019 HeapFree( GetProcessHeap(), 0, wsa
->read
);
2020 HeapFree( GetProcessHeap(), 0, wsa
);
2023 /***********************************************************************
2024 * WS2_async_accept_recv (INTERNAL)
2026 * This function is used to finish the read part of an accept request. It is
2027 * needed to place the completion on the correct socket (listener).
2029 static NTSTATUS
WS2_async_accept_recv( void *arg
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
, void **apc
)
2032 struct ws2_accept_async
*wsa
= arg
;
2034 status
= WS2_async_recv( wsa
->read
, iosb
, status
, &junk
);
2035 if (status
== STATUS_PENDING
)
2038 if (wsa
->user_overlapped
->hEvent
)
2039 SetEvent(wsa
->user_overlapped
->hEvent
);
2041 WS_AddCompletion( HANDLE2SOCKET(wsa
->listen_socket
), wsa
->cvalue
, iosb
->u
.Status
, iosb
->Information
);
2043 *apc
= ws2_async_accept_apc
;
2047 /***********************************************************************
2048 * WS2_async_accept (INTERNAL)
2050 * This is the function called to satisfy the AcceptEx callback
2052 static NTSTATUS
WS2_async_accept( void *arg
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
, void **apc
)
2054 struct ws2_accept_async
*wsa
= arg
;
2058 TRACE("status: 0x%x listen: %p, accept: %p\n", status
, wsa
->listen_socket
, wsa
->accept_socket
);
2060 if (status
== STATUS_ALERTED
)
2062 SERVER_START_REQ( accept_into_socket
)
2064 req
->lhandle
= wine_server_obj_handle( wsa
->listen_socket
);
2065 req
->ahandle
= wine_server_obj_handle( wsa
->accept_socket
);
2066 status
= wine_server_call( req
);
2070 if (status
== STATUS_CANT_WAIT
)
2071 return STATUS_PENDING
;
2073 if (status
== STATUS_INVALID_HANDLE
)
2075 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2076 status
= STATUS_CANCELLED
;
2079 else if (status
== STATUS_HANDLES_CLOSED
)
2080 status
= STATUS_CANCELLED
; /* strange windows behavior */
2082 if (status
!= STATUS_SUCCESS
)
2085 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2086 addr
= ((char *)wsa
->buf
) + wsa
->data_len
;
2087 len
= wsa
->local_len
- sizeof(int);
2088 WS_getsockname(HANDLE2SOCKET(wsa
->accept_socket
),
2089 (struct WS_sockaddr
*)(addr
+ sizeof(int)), &len
);
2092 addr
+= wsa
->local_len
;
2093 len
= wsa
->remote_len
- sizeof(int);
2094 WS_getpeername(HANDLE2SOCKET(wsa
->accept_socket
),
2095 (struct WS_sockaddr
*)(addr
+ sizeof(int)), &len
);
2101 SERVER_START_REQ( register_async
)
2103 req
->type
= ASYNC_TYPE_READ
;
2104 req
->async
.handle
= wine_server_obj_handle( wsa
->accept_socket
);
2105 req
->async
.callback
= wine_server_client_ptr( WS2_async_accept_recv
);
2106 req
->async
.iosb
= wine_server_client_ptr( iosb
);
2107 req
->async
.arg
= wine_server_client_ptr( wsa
);
2108 status
= wine_server_call( req
);
2112 if (status
!= STATUS_PENDING
)
2115 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2116 * needs to be performed by WS2_async_accept_recv() first. */
2117 return STATUS_MORE_PROCESSING_REQUIRED
;
2120 iosb
->u
.Status
= status
;
2121 iosb
->Information
= 0;
2123 if (wsa
->user_overlapped
->hEvent
)
2124 SetEvent(wsa
->user_overlapped
->hEvent
);
2126 *apc
= ws2_async_accept_apc
;
2130 /***********************************************************************
2131 * WS2_send (INTERNAL)
2133 * Workhorse for both synchronous and asynchronous send() operations.
2135 static int WS2_send( int fd
, struct ws2_async
*wsa
)
2138 union generic_unix_sockaddr unix_addr
;
2141 hdr
.msg_name
= NULL
;
2142 hdr
.msg_namelen
= 0;
2146 hdr
.msg_name
= &unix_addr
;
2147 hdr
.msg_namelen
= ws_sockaddr_ws2u( wsa
->addr
, wsa
->addrlen
.val
, &unix_addr
);
2148 if ( !hdr
.msg_namelen
)
2154 #if defined(HAS_IPX) && defined(SOL_IPX)
2155 if(wsa
->addr
->sa_family
== WS_AF_IPX
)
2157 struct sockaddr_ipx
* uipx
= (struct sockaddr_ipx
*)hdr
.msg_name
;
2159 socklen_t len
= sizeof(int);
2161 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2162 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2163 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2164 * ipx type in the sockaddr_opx structure with the stored value.
2166 if(getsockopt(fd
, SOL_IPX
, IPX_TYPE
, &val
, &len
) != -1)
2167 uipx
->sipx_type
= val
;
2172 hdr
.msg_iov
= wsa
->iovec
+ wsa
->first_iovec
;
2173 hdr
.msg_iovlen
= wsa
->n_iovecs
- wsa
->first_iovec
;
2174 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2175 hdr
.msg_accrights
= NULL
;
2176 hdr
.msg_accrightslen
= 0;
2178 hdr
.msg_control
= NULL
;
2179 hdr
.msg_controllen
= 0;
2183 while ((ret
= sendmsg(fd
, &hdr
, wsa
->flags
)) == -1)
2190 while (wsa
->first_iovec
< wsa
->n_iovecs
&& wsa
->iovec
[wsa
->first_iovec
].iov_len
<= n
)
2191 n
-= wsa
->iovec
[wsa
->first_iovec
++].iov_len
;
2192 if (wsa
->first_iovec
< wsa
->n_iovecs
)
2194 wsa
->iovec
[wsa
->first_iovec
].iov_base
= (char*)wsa
->iovec
[wsa
->first_iovec
].iov_base
+ n
;
2195 wsa
->iovec
[wsa
->first_iovec
].iov_len
-= n
;
2200 /***********************************************************************
2201 * WS2_async_send (INTERNAL)
2203 * Handler for overlapped send() operations.
2205 static NTSTATUS
WS2_async_send(void* user
, IO_STATUS_BLOCK
* iosb
, NTSTATUS status
, void **apc
)
2207 ws2_async
* wsa
= user
;
2212 case STATUS_ALERTED
:
2213 if ( wsa
->n_iovecs
<= wsa
->first_iovec
)
2216 status
= STATUS_SUCCESS
;
2219 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, FILE_WRITE_DATA
, &fd
, NULL
) ))
2222 /* check to see if the data is ready (non-blocking) */
2223 result
= WS2_send( fd
, wsa
);
2224 wine_server_release_fd( wsa
->hSocket
, fd
);
2228 if (wsa
->first_iovec
< wsa
->n_iovecs
)
2229 status
= STATUS_PENDING
;
2231 status
= STATUS_SUCCESS
;
2233 iosb
->Information
+= result
;
2235 else if (errno
== EAGAIN
)
2237 status
= STATUS_PENDING
;
2241 status
= wsaErrStatus();
2245 if (status
!= STATUS_PENDING
)
2247 iosb
->u
.Status
= status
;
2248 *apc
= ws2_async_apc
;
2253 /***********************************************************************
2254 * WS2_async_shutdown (INTERNAL)
2256 * Handler for shutdown() operations on overlapped sockets.
2258 static NTSTATUS
WS2_async_shutdown( void* user
, PIO_STATUS_BLOCK iosb
, NTSTATUS status
, void **apc
)
2260 ws2_async
* wsa
= user
;
2265 case STATUS_ALERTED
:
2266 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, 0, &fd
, NULL
) ))
2269 switch ( wsa
->type
)
2271 case ASYNC_TYPE_READ
: err
= shutdown( fd
, 0 ); break;
2272 case ASYNC_TYPE_WRITE
: err
= shutdown( fd
, 1 ); break;
2274 status
= err
? wsaErrStatus() : STATUS_SUCCESS
;
2275 wine_server_release_fd( wsa
->hSocket
, fd
);
2278 iosb
->u
.Status
= status
;
2279 iosb
->Information
= 0;
2280 *apc
= ws2_async_apc
;
2284 /***********************************************************************
2285 * WS2_register_async_shutdown (INTERNAL)
2287 * Helper function for WS_shutdown() on overlapped sockets.
2289 static int WS2_register_async_shutdown( SOCKET s
, int type
)
2291 struct ws2_async
*wsa
;
2294 TRACE("s %ld type %d\n", s
, type
);
2296 wsa
= HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async
, iovec
[1] ));
2300 wsa
->hSocket
= SOCKET2HANDLE(s
);
2302 wsa
->completion_func
= NULL
;
2304 SERVER_START_REQ( register_async
)
2307 req
->async
.handle
= wine_server_obj_handle( wsa
->hSocket
);
2308 req
->async
.callback
= wine_server_client_ptr( WS2_async_shutdown
);
2309 req
->async
.iosb
= wine_server_client_ptr( &wsa
->local_iosb
);
2310 req
->async
.arg
= wine_server_client_ptr( wsa
);
2311 req
->async
.cvalue
= 0;
2312 status
= wine_server_call( req
);
2316 if (status
!= STATUS_PENDING
)
2318 HeapFree( GetProcessHeap(), 0, wsa
);
2319 return NtStatusToWSAError( status
);
2324 /***********************************************************************
2327 SOCKET WINAPI
WS_accept(SOCKET s
, struct WS_sockaddr
*addr
, int *addrlen32
)
2333 TRACE("socket %04lx\n", s
);
2334 status
= _is_blocking(s
, &is_blocking
);
2338 return INVALID_SOCKET
;
2342 /* try accepting first (if there is a deferred connection) */
2343 SERVER_START_REQ( accept_socket
)
2345 req
->lhandle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
2346 req
->access
= GENERIC_READ
|GENERIC_WRITE
|SYNCHRONIZE
;
2347 req
->attributes
= OBJ_INHERIT
;
2348 status
= wine_server_call( req
);
2349 as
= HANDLE2SOCKET( wine_server_ptr_handle( reply
->handle
));
2354 if (addr
&& WS_getpeername(as
, addr
, addrlen32
))
2357 return SOCKET_ERROR
;
2361 if (is_blocking
&& status
== STATUS_CANT_WAIT
)
2363 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
2365 do_block(fd
, POLLIN
, -1);
2366 _sync_sock_state(s
); /* let wineserver notice connection */
2367 release_sock_fd( s
, fd
);
2369 } while (is_blocking
&& status
== STATUS_CANT_WAIT
);
2372 return INVALID_SOCKET
;
2375 /***********************************************************************
2378 static BOOL WINAPI
WS2_AcceptEx(SOCKET listener
, SOCKET acceptor
, PVOID dest
, DWORD dest_len
,
2379 DWORD local_addr_len
, DWORD rem_addr_len
, LPDWORD received
,
2380 LPOVERLAPPED overlapped
)
2383 struct ws2_accept_async
*wsa
;
2385 ULONG_PTR cvalue
= (overlapped
&& ((ULONG_PTR
)overlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)overlapped
: 0;
2387 TRACE("(%lx, %lx, %p, %d, %d, %d, %p, %p)\n", listener
, acceptor
, dest
, dest_len
, local_addr_len
,
2388 rem_addr_len
, received
, overlapped
);
2392 SetLastError(WSAEINVAL
);
2398 SetLastError(WSA_INVALID_PARAMETER
);
2404 SetLastError(WSAEFAULT
);
2408 fd
= get_sock_fd( listener
, FILE_READ_DATA
, NULL
);
2411 SetLastError(WSAENOTSOCK
);
2414 release_sock_fd( listener
, fd
);
2416 fd
= get_sock_fd( acceptor
, FILE_READ_DATA
, NULL
);
2419 SetLastError(WSAENOTSOCK
);
2422 release_sock_fd( acceptor
, fd
);
2424 wsa
= HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa
) );
2427 SetLastError(WSAEFAULT
);
2431 wsa
->listen_socket
= SOCKET2HANDLE(listener
);
2432 wsa
->accept_socket
= SOCKET2HANDLE(acceptor
);
2433 wsa
->user_overlapped
= overlapped
;
2434 wsa
->cvalue
= cvalue
;
2436 wsa
->data_len
= dest_len
;
2437 wsa
->local_len
= local_addr_len
;
2438 wsa
->remote_len
= rem_addr_len
;
2443 /* set up a read request if we need it */
2444 wsa
->read
= HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async
, iovec
[1]) );
2447 HeapFree( GetProcessHeap(), 0, wsa
);
2448 SetLastError(WSAEFAULT
);
2452 wsa
->read
->hSocket
= wsa
->accept_socket
;
2453 wsa
->read
->flags
= 0;
2454 wsa
->read
->lpFlags
= &wsa
->read
->flags
;
2455 wsa
->read
->addr
= NULL
;
2456 wsa
->read
->addrlen
.ptr
= NULL
;
2457 wsa
->read
->control
= NULL
;
2458 wsa
->read
->n_iovecs
= 1;
2459 wsa
->read
->first_iovec
= 0;
2460 wsa
->read
->iovec
[0].iov_base
= wsa
->buf
;
2461 wsa
->read
->iovec
[0].iov_len
= wsa
->data_len
;
2464 SERVER_START_REQ( register_async
)
2466 req
->type
= ASYNC_TYPE_READ
;
2467 req
->async
.handle
= wine_server_obj_handle( SOCKET2HANDLE(listener
) );
2468 req
->async
.callback
= wine_server_client_ptr( WS2_async_accept
);
2469 req
->async
.iosb
= wine_server_client_ptr( overlapped
);
2470 req
->async
.arg
= wine_server_client_ptr( wsa
);
2471 req
->async
.cvalue
= cvalue
;
2472 /* We don't set event since we may also have to read */
2473 status
= wine_server_call( req
);
2477 if(status
!= STATUS_PENDING
)
2479 HeapFree( GetProcessHeap(), 0, wsa
->read
);
2480 HeapFree( GetProcessHeap(), 0, wsa
);
2483 SetLastError( NtStatusToWSAError(status
) );
2487 /***********************************************************************
2488 * GetAcceptExSockaddrs
2490 static void WINAPI
WS2_GetAcceptExSockaddrs(PVOID buffer
, DWORD data_size
, DWORD local_size
, DWORD remote_size
,
2491 struct WS_sockaddr
**local_addr
, LPINT local_addr_len
,
2492 struct WS_sockaddr
**remote_addr
, LPINT remote_addr_len
)
2494 char *cbuf
= buffer
;
2495 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer
, data_size
, local_size
, remote_size
, local_addr
,
2496 local_addr_len
, remote_addr
, remote_addr_len
);
2499 *local_addr_len
= *(int *) cbuf
;
2500 *local_addr
= (struct WS_sockaddr
*)(cbuf
+ sizeof(int));
2504 *remote_addr_len
= *(int *) cbuf
;
2505 *remote_addr
= (struct WS_sockaddr
*)(cbuf
+ sizeof(int));
2508 /***********************************************************************
2511 int WINAPI
WSASendMsg( SOCKET s
, LPWSAMSG msg
, DWORD dwFlags
, LPDWORD lpNumberOfBytesSent
,
2512 LPWSAOVERLAPPED lpOverlapped
,
2513 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
2517 SetLastError( WSAEFAULT
);
2518 return SOCKET_ERROR
;
2521 return WS2_sendto( s
, msg
->lpBuffers
, msg
->dwBufferCount
, lpNumberOfBytesSent
,
2522 dwFlags
, msg
->name
, msg
->namelen
,
2523 lpOverlapped
, lpCompletionRoutine
);
2526 /***********************************************************************
2529 * Perform a receive operation that is capable of returning message
2530 * control headers. It is important to note that the WSAMSG parameter
2531 * must remain valid throughout the operation, even when an overlapped
2532 * receive is performed.
2534 static int WINAPI
WS2_WSARecvMsg( SOCKET s
, LPWSAMSG msg
, LPDWORD lpNumberOfBytesRecvd
,
2535 LPWSAOVERLAPPED lpOverlapped
,
2536 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
2540 SetLastError( WSAEFAULT
);
2541 return SOCKET_ERROR
;
2544 return WS2_recv_base( s
, msg
->lpBuffers
, msg
->dwBufferCount
, lpNumberOfBytesRecvd
,
2545 &msg
->dwFlags
, msg
->name
, &msg
->namelen
,
2546 lpOverlapped
, lpCompletionRoutine
, &msg
->Control
);
2549 /***********************************************************************
2550 * interface_bind (INTERNAL)
2552 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
2553 * operating only on the specified interface. This restriction consists of two components:
2554 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
2555 * 2) An incoming packet restriction dropping packets not meant for the interface.
2556 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
2557 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
2558 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
2559 * to receive broadcast packets on a socket that is bound to a specific network interface.
2561 static BOOL
interface_bind( SOCKET s
, int fd
, struct sockaddr
*addr
)
2563 struct sockaddr_in
*in_sock
= (struct sockaddr_in
*) addr
;
2564 unsigned int sock_type
= 0;
2565 socklen_t optlen
= sizeof(sock_type
);
2566 in_addr_t bind_addr
= in_sock
->sin_addr
.s_addr
;
2567 PIP_ADAPTER_INFO adapters
= NULL
, adapter
;
2572 if (bind_addr
== htonl(INADDR_ANY
) || bind_addr
== htonl(INADDR_LOOPBACK
))
2573 return FALSE
; /* Not binding to a network adapter, special interface binding unnecessary. */
2574 if (getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, &sock_type
, &optlen
) == -1 || sock_type
!= SOCK_DGRAM
)
2575 return FALSE
; /* Special interface binding is only necessary for UDP datagrams. */
2576 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
2578 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
2579 if (adapters
== NULL
|| GetAdaptersInfo(adapters
, &adap_size
) != NO_ERROR
)
2581 /* Search the IPv4 adapter list for the appropriate binding interface */
2582 for (adapter
= adapters
; adapter
!= NULL
; adapter
= adapter
->Next
)
2584 in_addr_t adapter_addr
= (in_addr_t
) inet_addr(adapter
->IpAddressList
.IpAddress
.String
);
2586 if (bind_addr
== adapter_addr
)
2588 #if defined(IP_BOUND_IF)
2589 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
2590 if (setsockopt(fd
, IPPROTO_IP
, IP_BOUND_IF
, &adapter
->Index
, sizeof(adapter
->Index
)) != 0)
2593 #elif defined(LINUX_BOUND_IF)
2594 in_addr_t ifindex
= (in_addr_t
) htonl(adapter
->Index
);
2595 struct interface_filter specific_interface_filter
;
2596 struct sock_fprog filter_prog
;
2598 if (setsockopt(fd
, IPPROTO_IP
, IP_UNICAST_IF
, &ifindex
, sizeof(ifindex
)) != 0)
2599 goto cleanup
; /* Failed to suggest egress interface */
2600 specific_interface_filter
= generic_interface_filter
;
2601 specific_interface_filter
.iface_rule
.k
= adapter
->Index
;
2602 specific_interface_filter
.ip_rule
.k
= htonl(adapter_addr
);
2603 filter_prog
.len
= sizeof(generic_interface_filter
)/sizeof(struct sock_filter
);
2604 filter_prog
.filter
= (struct sock_filter
*) &specific_interface_filter
;
2605 if (setsockopt(fd
, SOL_SOCKET
, SO_ATTACH_FILTER
, &filter_prog
, sizeof(filter_prog
)) != 0)
2606 goto cleanup
; /* Failed to specify incoming packet filter */
2609 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
2610 "receiving broadcast packets will not work on socket %04lx.\n", s
);
2615 /* Will soon be switching to INADDR_ANY: permit address reuse */
2616 if (ret
&& setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &enable
, sizeof(enable
)) == 0)
2617 TRACE("Socket %04lx bound to interface index %d\n", s
, adapter
->Index
);
2623 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s
);
2624 HeapFree(GetProcessHeap(), 0, adapters
);
2628 /***********************************************************************
2631 int WINAPI
WS_bind(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
)
2633 int fd
= get_sock_fd( s
, 0, NULL
);
2634 int res
= SOCKET_ERROR
;
2636 TRACE("socket %04lx, ptr %p %s, length %d\n", s
, name
, debugstr_sockaddr(name
), namelen
);
2640 if (!name
|| (name
->sa_family
&& !supported_pf(name
->sa_family
)))
2642 SetLastError(WSAEAFNOSUPPORT
);
2646 union generic_unix_sockaddr uaddr
;
2647 unsigned int uaddrlen
= ws_sockaddr_ws2u(name
, namelen
, &uaddr
);
2650 SetLastError(WSAEFAULT
);
2655 const struct sockaddr_in6
*in6
= (const struct sockaddr_in6
*) &uaddr
;
2656 if (name
->sa_family
== WS_AF_INET6
&&
2657 !memcmp(&in6
->sin6_addr
, &in6addr_any
, sizeof(struct in6_addr
)))
2660 if (setsockopt(fd
, IPPROTO_IPV6
, IPV6_V6ONLY
, &enable
, sizeof(enable
)) == -1)
2662 release_sock_fd( s
, fd
);
2663 SetLastError(WSAEAFNOSUPPORT
);
2664 return SOCKET_ERROR
;
2668 if (name
->sa_family
== WS_AF_INET
)
2670 struct sockaddr_in
*in4
= (struct sockaddr_in
*) &uaddr
;
2671 if (memcmp(&in4
->sin_addr
, magic_loopback_addr
, 4) == 0)
2673 /* Trying to bind to the default host interface, using
2674 * INADDR_ANY instead*/
2675 WARN("Trying to bind to magic IP address, using "
2676 "INADDR_ANY instead.\n");
2677 in4
->sin_addr
.s_addr
= htonl(INADDR_ANY
);
2679 else if (interface_bind(s
, fd
, &uaddr
.addr
))
2680 in4
->sin_addr
.s_addr
= htonl(INADDR_ANY
);
2682 if (bind(fd
, &uaddr
.addr
, uaddrlen
) < 0)
2684 int loc_errno
= errno
;
2685 WARN("\tfailure - errno = %i\n", errno
);
2690 SetLastError(WSAENOTSOCK
);
2693 SetLastError(WSAEINVAL
);
2698 socklen_t optlen
= sizeof(optval
);
2699 /* Windows >= 2003 will return different results depending on
2700 * SO_REUSEADDR, WSAEACCES may be returned representing that
2701 * the socket hijacking protection prevented the bind */
2702 if (!getsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&optval
, &optlen
) && optval
)
2704 SetLastError(WSAEACCES
);
2710 SetLastError(wsaErrno());
2716 res
=0; /* success */
2720 release_sock_fd( s
, fd
);
2725 /***********************************************************************
2726 * closesocket (WS2_32.3)
2728 int WINAPI
WS_closesocket(SOCKET s
)
2730 TRACE("socket %04lx\n", s
);
2731 if (CloseHandle(SOCKET2HANDLE(s
))) return 0;
2732 return SOCKET_ERROR
;
2735 static int do_connect(int fd
, const struct WS_sockaddr
* name
, int namelen
)
2737 union generic_unix_sockaddr uaddr
;
2738 unsigned int uaddrlen
= ws_sockaddr_ws2u(name
, namelen
, &uaddr
);
2743 if (name
->sa_family
== WS_AF_INET
)
2745 struct sockaddr_in
*in4
= (struct sockaddr_in
*) &uaddr
;
2746 if (memcmp(&in4
->sin_addr
, magic_loopback_addr
, 4) == 0)
2748 /* Trying to connect to magic replace-loopback address,
2749 * assuming we really want to connect to localhost */
2750 TRACE("Trying to connect to magic IP address, using "
2751 "INADDR_LOOPBACK instead.\n");
2752 in4
->sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
2756 if (connect(fd
, &uaddr
.addr
, uaddrlen
) == 0)
2762 /***********************************************************************
2763 * connect (WS2_32.4)
2765 int WINAPI
WS_connect(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
)
2767 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
2769 TRACE("socket %04lx, ptr %p %s, length %d\n", s
, name
, debugstr_sockaddr(name
), namelen
);
2775 int ret
= do_connect(fd
, name
, namelen
);
2777 goto connect_success
;
2779 if (ret
== WSAEINPROGRESS
)
2781 /* tell wineserver that a connection is in progress */
2782 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
2784 FD_WINE_CONNECTED
|FD_WINE_LISTENING
);
2785 status
= _is_blocking( s
, &is_blocking
);
2788 release_sock_fd( s
, fd
);
2789 set_error( status
);
2790 return SOCKET_ERROR
;
2796 do_block(fd
, POLLIN
| POLLOUT
, -1);
2797 _sync_sock_state(s
); /* let wineserver notice connection */
2798 /* retrieve any error codes from it */
2799 result
= _get_sock_error(s
, FD_CONNECT_BIT
);
2801 SetLastError(NtStatusToWSAError(result
));
2804 goto connect_success
;
2809 SetLastError(WSAEWOULDBLOCK
);
2816 release_sock_fd( s
, fd
);
2818 return SOCKET_ERROR
;
2821 release_sock_fd( s
, fd
);
2822 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
2823 FD_WINE_CONNECTED
|FD_READ
|FD_WRITE
,
2824 FD_CONNECT
|FD_WINE_LISTENING
);
2828 /***********************************************************************
2829 * WSAConnect (WS2_32.30)
2831 int WINAPI
WSAConnect( SOCKET s
, const struct WS_sockaddr
* name
, int namelen
,
2832 LPWSABUF lpCallerData
, LPWSABUF lpCalleeData
,
2833 LPQOS lpSQOS
, LPQOS lpGQOS
)
2835 if ( lpCallerData
|| lpCalleeData
|| lpSQOS
|| lpGQOS
)
2836 FIXME("unsupported parameters!\n");
2837 return WS_connect( s
, name
, namelen
);
2840 /***********************************************************************
2843 static BOOL WINAPI
WS2_ConnectEx(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
,
2844 PVOID sendBuf
, DWORD sendBufLen
, LPDWORD sent
, LPOVERLAPPED ov
)
2846 int fd
, ret
, status
;
2847 union generic_unix_sockaddr uaddr
;
2848 socklen_t uaddrlen
= sizeof(uaddr
);
2852 SetLastError( ERROR_INVALID_PARAMETER
);
2856 fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
2859 SetLastError( WSAENOTSOCK
);
2863 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
2864 s
, name
, debugstr_sockaddr(name
), namelen
, sendBuf
, sendBufLen
, ov
);
2866 if (getsockname(fd
, &uaddr
.addr
, &uaddrlen
) != 0)
2868 SetLastError(wsaErrno());
2871 else if (!is_sockaddr_bound(&uaddr
.addr
, uaddrlen
))
2873 SetLastError(WSAEINVAL
);
2877 ret
= do_connect(fd
, name
, namelen
);
2882 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
2883 FD_WINE_CONNECTED
|FD_READ
|FD_WRITE
,
2884 FD_CONNECT
|FD_WINE_LISTENING
);
2886 wsabuf
.len
= sendBufLen
;
2887 wsabuf
.buf
= (char*) sendBuf
;
2889 /* WSASend takes care of completion if need be */
2890 if (WSASend(s
, &wsabuf
, sendBuf
? 1 : 0, sent
, 0, ov
, NULL
) != SOCKET_ERROR
)
2891 goto connection_success
;
2893 else if (ret
== WSAEINPROGRESS
)
2895 struct ws2_async
*wsa
;
2896 ULONG_PTR cvalue
= (((ULONG_PTR
)ov
->hEvent
& 1) == 0) ? (ULONG_PTR
)ov
: 0;
2898 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
2900 FD_WINE_CONNECTED
|FD_WINE_LISTENING
);
2902 /* Indirectly call WSASend */
2903 if (!(wsa
= HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async
, iovec
[1] ))))
2905 SetLastError(WSAEFAULT
);
2909 IO_STATUS_BLOCK
*iosb
= (IO_STATUS_BLOCK
*)ov
;
2910 iosb
->u
.Status
= STATUS_PENDING
;
2911 iosb
->Information
= 0;
2913 wsa
->hSocket
= SOCKET2HANDLE(s
);
2915 wsa
->addrlen
.val
= 0;
2917 wsa
->lpFlags
= &wsa
->flags
;
2918 wsa
->control
= NULL
;
2919 wsa
->n_iovecs
= sendBuf
? 1 : 0;
2920 wsa
->first_iovec
= 0;
2921 wsa
->completion_func
= NULL
;
2922 wsa
->iovec
[0].iov_base
= sendBuf
;
2923 wsa
->iovec
[0].iov_len
= sendBufLen
;
2925 SERVER_START_REQ( register_async
)
2927 req
->type
= ASYNC_TYPE_WRITE
;
2928 req
->async
.handle
= wine_server_obj_handle( wsa
->hSocket
);
2929 req
->async
.callback
= wine_server_client_ptr( WS2_async_send
);
2930 req
->async
.iosb
= wine_server_client_ptr( iosb
);
2931 req
->async
.arg
= wine_server_client_ptr( wsa
);
2932 req
->async
.event
= wine_server_obj_handle( ov
->hEvent
);
2933 req
->async
.cvalue
= cvalue
;
2934 status
= wine_server_call( req
);
2938 if (status
!= STATUS_PENDING
) HeapFree(GetProcessHeap(), 0, wsa
);
2940 /* If the connect already failed */
2941 if (status
== STATUS_PIPE_DISCONNECTED
)
2942 status
= _get_sock_error(s
, FD_CONNECT_BIT
);
2943 SetLastError( NtStatusToWSAError(status
) );
2951 release_sock_fd( s
, fd
);
2955 release_sock_fd( s
, fd
);
2960 /***********************************************************************
2961 * getpeername (WS2_32.5)
2963 int WINAPI
WS_getpeername(SOCKET s
, struct WS_sockaddr
*name
, int *namelen
)
2968 TRACE("socket: %04lx, ptr %p, len %08x\n", s
, name
, namelen
? *namelen
: 0);
2970 fd
= get_sock_fd( s
, 0, NULL
);
2975 union generic_unix_sockaddr uaddr
;
2976 socklen_t uaddrlen
= sizeof(uaddr
);
2978 if (getpeername(fd
, &uaddr
.addr
, &uaddrlen
) == 0)
2980 if (!name
|| !namelen
)
2981 SetLastError(WSAEFAULT
);
2982 else if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
2983 /* The buffer was too small */
2984 SetLastError(WSAEFAULT
);
2989 SetLastError(wsaErrno());
2990 release_sock_fd( s
, fd
);
2995 /***********************************************************************
2996 * getsockname (WS2_32.6)
2998 int WINAPI
WS_getsockname(SOCKET s
, struct WS_sockaddr
*name
, int *namelen
)
3003 TRACE("socket: %04lx, ptr %p, len %08x\n", s
, name
, namelen
? *namelen
: 0);
3005 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3006 if( (name
== NULL
) || (namelen
== NULL
) )
3008 SetLastError( WSAEFAULT
);
3009 return SOCKET_ERROR
;
3012 fd
= get_sock_fd( s
, 0, NULL
);
3017 union generic_unix_sockaddr uaddr
;
3018 socklen_t uaddrlen
= sizeof(uaddr
);
3020 if (getsockname(fd
, &uaddr
.addr
, &uaddrlen
) != 0)
3022 SetLastError(wsaErrno());
3024 else if (!is_sockaddr_bound(&uaddr
.addr
, uaddrlen
))
3026 SetLastError(WSAEINVAL
);
3028 else if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
3030 /* The buffer was too small */
3031 SetLastError(WSAEFAULT
);
3036 TRACE("=> %s\n", debugstr_sockaddr(name
));
3038 release_sock_fd( s
, fd
);
3043 /***********************************************************************
3044 * getsockopt (WS2_32.7)
3046 INT WINAPI
WS_getsockopt(SOCKET s
, INT level
,
3047 INT optname
, char *optval
, INT
*optlen
)
3052 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
3053 s
, level
, optname
, optval
, optlen
? *optlen
: 0);
3061 /* Handle common cases. The special cases are below, sorted
3063 case WS_SO_BROADCAST
:
3066 case WS_SO_KEEPALIVE
:
3067 case WS_SO_OOBINLINE
:
3069 case WS_SO_REUSEADDR
:
3071 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3072 return SOCKET_ERROR
;
3073 convert_sockopt(&level
, &optname
);
3074 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3076 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3079 release_sock_fd( s
, fd
);
3081 case WS_SO_ACCEPTCONN
:
3082 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3083 return SOCKET_ERROR
;
3084 if (getsockopt(fd
, SOL_SOCKET
, SO_ACCEPTCONN
, optval
, (socklen_t
*)optlen
) != 0 )
3086 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3091 /* BSD returns != 0 while Windows return exact == 1 */
3092 if (*(int *)optval
) *(int *)optval
= 1;
3094 release_sock_fd( s
, fd
);
3096 case WS_SO_DONTLINGER
:
3098 struct linger lingval
;
3099 socklen_t len
= sizeof(struct linger
);
3101 if (!optlen
|| *optlen
< sizeof(BOOL
)|| !optval
)
3103 SetLastError(WSAEFAULT
);
3104 return SOCKET_ERROR
;
3106 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3107 return SOCKET_ERROR
;
3109 if (getsockopt(fd
, SOL_SOCKET
, SO_LINGER
, &lingval
, &len
) != 0 )
3111 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3116 *(BOOL
*)optval
= !lingval
.l_onoff
;
3117 *optlen
= sizeof(BOOL
);
3120 release_sock_fd( s
, fd
);
3124 case WS_SO_CONNECT_TIME
:
3126 static int pretendtime
= 0;
3127 struct WS_sockaddr addr
;
3128 int len
= sizeof(addr
);
3130 if (!optlen
|| *optlen
< sizeof(DWORD
) || !optval
)
3132 SetLastError(WSAEFAULT
);
3133 return SOCKET_ERROR
;
3135 if (WS_getpeername(s
, &addr
, &len
) == SOCKET_ERROR
)
3136 *(DWORD
*)optval
= ~0u;
3139 if (!pretendtime
) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3140 *(DWORD
*)optval
= pretendtime
++;
3142 *optlen
= sizeof(DWORD
);
3145 /* As mentioned in setsockopt, Windows ignores this, so we
3146 * always return true here */
3147 case WS_SO_DONTROUTE
:
3148 if (!optlen
|| *optlen
< sizeof(BOOL
) || !optval
)
3150 SetLastError(WSAEFAULT
);
3151 return SOCKET_ERROR
;
3153 *(BOOL
*)optval
= TRUE
;
3154 *optlen
= sizeof(BOOL
);
3159 struct linger lingval
;
3161 socklen_t len
= sizeof(struct linger
), slen
= sizeof(int);
3163 /* struct linger and LINGER have different sizes */
3164 if (!optlen
|| *optlen
< sizeof(LINGER
) || !optval
)
3166 SetLastError(WSAEFAULT
);
3167 return SOCKET_ERROR
;
3169 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3170 return SOCKET_ERROR
;
3172 if ((getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, &so_type
, &slen
) == 0 && so_type
== SOCK_DGRAM
))
3174 SetLastError(WSAENOPROTOOPT
);
3177 else if (getsockopt(fd
, SOL_SOCKET
, SO_LINGER
, &lingval
, &len
) != 0)
3179 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3184 ((LINGER
*)optval
)->l_onoff
= lingval
.l_onoff
;
3185 ((LINGER
*)optval
)->l_linger
= lingval
.l_linger
;
3186 *optlen
= sizeof(struct linger
);
3189 release_sock_fd( s
, fd
);
3193 case WS_SO_MAX_MSG_SIZE
:
3194 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
3196 SetLastError(WSAEFAULT
);
3197 return SOCKET_ERROR
;
3199 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3200 *(int *)optval
= 65507;
3201 *optlen
= sizeof(int);
3204 /* SO_OPENTYPE does not require a valid socket handle. */
3205 case WS_SO_OPENTYPE
:
3206 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
3208 SetLastError(WSAEFAULT
);
3209 return SOCKET_ERROR
;
3211 *(int *)optval
= get_per_thread_data()->opentype
;
3212 *optlen
= sizeof(int);
3213 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval
) );
3215 case WS_SO_PROTOCOL_INFOA
:
3216 case WS_SO_PROTOCOL_INFOW
:
3219 WSAPROTOCOL_INFOW infow
;
3221 ret
= ws_protocol_info(s
, optname
== WS_SO_PROTOCOL_INFOW
, &infow
, &size
);
3224 if (!optlen
|| !optval
|| *optlen
< size
)
3226 if(optlen
) *optlen
= size
;
3228 SetLastError(WSAEFAULT
);
3231 memcpy(optval
, &infow
, size
);
3233 return ret
? 0 : SOCKET_ERROR
;
3236 case WS_SO_RCVTIMEO
:
3239 case WS_SO_SNDTIMEO
:
3241 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3244 socklen_t len
= sizeof(struct timeval
);
3246 if (!optlen
|| *optlen
< sizeof(int)|| !optval
)
3248 SetLastError(WSAEFAULT
);
3249 return SOCKET_ERROR
;
3251 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3252 return SOCKET_ERROR
;
3254 convert_sockopt(&level
, &optname
);
3255 if (getsockopt(fd
, level
, optname
, &tv
, &len
) != 0 )
3257 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3262 *(int *)optval
= tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000;
3263 *optlen
= sizeof(int);
3266 release_sock_fd( s
, fd
);
3272 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
3274 SetLastError(WSAEFAULT
);
3275 return SOCKET_ERROR
;
3277 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3278 return SOCKET_ERROR
;
3280 if (getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, optval
, (socklen_t
*)optlen
) != 0 )
3282 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3286 (*(int *)optval
) = convert_socktype_u2w(*(int *)optval
);
3288 release_sock_fd( s
, fd
);
3292 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname
);
3293 SetLastError(WSAENOPROTOOPT
);
3294 return SOCKET_ERROR
;
3295 } /* end switch(optname) */
3296 }/* end case WS_SOL_SOCKET */
3298 case WS_NSPROTO_IPX
:
3300 struct WS_sockaddr_ipx addr
;
3301 IPX_ADDRESS_DATA
*data
;
3306 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
3308 if(getsockopt(fd
, SOL_IPX
, IPX_TYPE
, optval
, (socklen_t
*)optlen
) == -1)
3315 socklen_t len
=sizeof(struct ipx
);
3316 if(getsockopt(fd
, 0, SO_DEFAULT_HEADERS
, &val
, &len
) == -1 )
3319 *optval
= (int)val
.ipx_pt
;
3322 TRACE("ptype: %d (fd: %d)\n", *(int*)optval
, fd
);
3323 release_sock_fd( s
, fd
);
3328 * On a Win2000 system with one network card there are usually
3329 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
3330 * Using this call you can then retrieve info about this all.
3331 * In case of Linux it is a bit different. Usually you have
3332 * only "one" device active and further it is not possible to
3333 * query things like the linkspeed.
3335 FIXME("IPX_ADDRESS\n");
3336 namelen
= sizeof(struct WS_sockaddr_ipx
);
3337 memset(&addr
, 0, sizeof(struct WS_sockaddr_ipx
));
3338 WS_getsockname(s
, (struct WS_sockaddr
*)&addr
, &namelen
);
3340 data
= (IPX_ADDRESS_DATA
*)optval
;
3341 memcpy(data
->nodenum
,addr
.sa_nodenum
,sizeof(data
->nodenum
));
3342 memcpy(data
->netnum
,addr
.sa_netnum
,sizeof(data
->netnum
));
3343 data
->adapternum
= 0;
3344 data
->wan
= FALSE
; /* We are not on a wan for now .. */
3345 data
->status
= FALSE
; /* Since we are not on a wan, the wan link isn't up */
3346 data
->maxpkt
= 1467; /* This value is the default one, at least on Win2k/WinXP */
3347 data
->linkspeed
= 100000; /* Set the line speed in 100bit/s to 10 Mbit;
3348 * note 1MB = 1000kB in this case */
3351 case IPX_MAX_ADAPTER_NUM
:
3352 FIXME("IPX_MAX_ADAPTER_NUM\n");
3353 *(int*)optval
= 1; /* As noted under IPX_ADDRESS we have just one card. */
3357 FIXME("IPX optname:%x\n", optname
);
3358 return SOCKET_ERROR
;
3359 }/* end switch(optname) */
3360 } /* end case WS_NSPROTO_IPX */
3364 #define MAX_IRDA_DEVICES 10
3369 case WS_IRLMP_ENUMDEVICES
:
3371 char buf
[sizeof(struct irda_device_list
) +
3372 (MAX_IRDA_DEVICES
- 1) * sizeof(struct irda_device_info
)];
3374 socklen_t len
= sizeof(buf
);
3376 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3377 return SOCKET_ERROR
;
3378 res
= getsockopt( fd
, SOL_IRLMP
, IRLMP_ENUMDEVICES
, buf
, &len
);
3379 release_sock_fd( s
, fd
);
3382 SetLastError(wsaErrno());
3383 return SOCKET_ERROR
;
3387 struct irda_device_list
*src
= (struct irda_device_list
*)buf
;
3388 DEVICELIST
*dst
= (DEVICELIST
*)optval
;
3389 INT needed
= sizeof(DEVICELIST
);
3393 needed
+= (src
->len
- 1) * sizeof(IRDA_DEVICE_INFO
);
3394 if (*optlen
< needed
)
3396 SetLastError(WSAEFAULT
);
3397 return SOCKET_ERROR
;
3400 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src
->len
);
3401 dst
->numDevice
= src
->len
;
3402 for (i
= 0; i
< src
->len
; i
++)
3404 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
3405 src
->dev
[i
].saddr
, src
->dev
[i
].daddr
,
3406 src
->dev
[i
].info
, src
->dev
[i
].hints
[0],
3407 src
->dev
[i
].hints
[1]);
3408 memcpy( dst
->Device
[i
].irdaDeviceID
,
3410 sizeof(dst
->Device
[i
].irdaDeviceID
) ) ;
3411 memcpy( dst
->Device
[i
].irdaDeviceName
,
3413 sizeof(dst
->Device
[i
].irdaDeviceName
) ) ;
3414 memcpy( &dst
->Device
[i
].irdaDeviceHints1
,
3415 &src
->dev
[i
].hints
[0],
3416 sizeof(dst
->Device
[i
].irdaDeviceHints1
) ) ;
3417 memcpy( &dst
->Device
[i
].irdaDeviceHints2
,
3418 &src
->dev
[i
].hints
[1],
3419 sizeof(dst
->Device
[i
].irdaDeviceHints2
) ) ;
3420 dst
->Device
[i
].irdaCharSet
= src
->dev
[i
].charset
;
3426 FIXME("IrDA optname:0x%x\n", optname
);
3427 return SOCKET_ERROR
;
3429 break; /* case WS_SOL_IRLMP */
3430 #undef MAX_IRDA_DEVICES
3433 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3434 case WS_IPPROTO_TCP
:
3437 case WS_TCP_NODELAY
:
3438 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3439 return SOCKET_ERROR
;
3440 convert_sockopt(&level
, &optname
);
3441 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3443 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3446 release_sock_fd( s
, fd
);
3449 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname
);
3450 return SOCKET_ERROR
;
3455 case WS_IP_ADD_MEMBERSHIP
:
3456 case WS_IP_DROP_MEMBERSHIP
:
3460 case WS_IP_MULTICAST_IF
:
3461 case WS_IP_MULTICAST_LOOP
:
3462 case WS_IP_MULTICAST_TTL
:
3469 #ifdef IP_UNICAST_IF
3470 case WS_IP_UNICAST_IF
:
3472 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3473 return SOCKET_ERROR
;
3474 convert_sockopt(&level
, &optname
);
3475 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3477 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3480 release_sock_fd( s
, fd
);
3482 case WS_IP_DONTFRAGMENT
:
3483 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
3484 *(BOOL
*)optval
= FALSE
;
3487 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname
);
3488 return SOCKET_ERROR
;
3490 case WS_IPPROTO_IPV6
:
3493 #ifdef IPV6_ADD_MEMBERSHIP
3494 case WS_IPV6_ADD_MEMBERSHIP
:
3496 #ifdef IPV6_DROP_MEMBERSHIP
3497 case WS_IPV6_DROP_MEMBERSHIP
:
3499 case WS_IPV6_MULTICAST_IF
:
3500 case WS_IPV6_MULTICAST_HOPS
:
3501 case WS_IPV6_MULTICAST_LOOP
:
3502 case WS_IPV6_UNICAST_HOPS
:
3503 case WS_IPV6_V6ONLY
:
3504 #ifdef IPV6_UNICAST_IF
3505 case WS_IPV6_UNICAST_IF
:
3507 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3508 return SOCKET_ERROR
;
3509 convert_sockopt(&level
, &optname
);
3510 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3512 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3515 release_sock_fd( s
, fd
);
3517 case WS_IPV6_DONTFRAG
:
3518 FIXME("WS_IPV6_DONTFRAG is always false!\n");
3519 *(BOOL
*)optval
= FALSE
;
3522 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname
);
3523 return SOCKET_ERROR
;
3526 WARN("Unknown level: 0x%08x\n", level
);
3527 SetLastError(WSAEINVAL
);
3528 return SOCKET_ERROR
;
3529 } /* end switch(level) */
3532 /***********************************************************************
3535 WS_u_long WINAPI
WS_htonl(WS_u_long hostlong
)
3537 return htonl(hostlong
);
3541 /***********************************************************************
3544 WS_u_short WINAPI
WS_htons(WS_u_short hostshort
)
3546 return htons(hostshort
);
3549 /***********************************************************************
3550 * WSAHtonl (WS2_32.46)
3551 * From MSDN description of error codes, this function should also
3552 * check if WinSock has been initialized and the socket is a valid
3553 * socket. But why? This function only translates a host byte order
3554 * u_long into a network byte order u_long...
3556 int WINAPI
WSAHtonl(SOCKET s
, WS_u_long hostlong
, WS_u_long
*lpnetlong
)
3560 *lpnetlong
= htonl(hostlong
);
3563 WSASetLastError(WSAEFAULT
);
3564 return SOCKET_ERROR
;
3567 /***********************************************************************
3568 * WSAHtons (WS2_32.47)
3569 * From MSDN description of error codes, this function should also
3570 * check if WinSock has been initialized and the socket is a valid
3571 * socket. But why? This function only translates a host byte order
3572 * u_short into a network byte order u_short...
3574 int WINAPI
WSAHtons(SOCKET s
, WS_u_short hostshort
, WS_u_short
*lpnetshort
)
3579 *lpnetshort
= htons(hostshort
);
3582 WSASetLastError(WSAEFAULT
);
3583 return SOCKET_ERROR
;
3587 /***********************************************************************
3588 * inet_addr (WS2_32.11)
3590 WS_u_long WINAPI
WS_inet_addr(const char *cp
)
3592 if (!cp
) return INADDR_NONE
;
3593 return inet_addr(cp
);
3597 /***********************************************************************
3600 WS_u_long WINAPI
WS_ntohl(WS_u_long netlong
)
3602 return ntohl(netlong
);
3606 /***********************************************************************
3609 WS_u_short WINAPI
WS_ntohs(WS_u_short netshort
)
3611 return ntohs(netshort
);
3615 /***********************************************************************
3616 * inet_ntoa (WS2_32.12)
3618 char* WINAPI
WS_inet_ntoa(struct WS_in_addr in
)
3620 char* s
= inet_ntoa(*((struct in_addr
*)&in
));
3623 struct per_thread_data
*data
= get_per_thread_data();
3624 strcpy(data
->ntoa_buffer
, s
);
3625 return data
->ntoa_buffer
;
3627 SetLastError(wsaErrno());
3631 static const char *debugstr_wsaioctl(DWORD ioctl
)
3633 const char *buf_type
, *family
;
3635 switch(ioctl
& 0x18000000)
3640 case WS_IOC_PROTOCOL
:
3641 family
= "IOC_PROTOCOL";
3644 family
= "IOC_VENDOR";
3646 default: /* WS_IOC_UNIX */
3648 BYTE size
= (ioctl
>> 16) & WS_IOCPARM_MASK
;
3649 char x
= (ioctl
& 0xff00) >> 8;
3650 BYTE y
= ioctl
& 0xff;
3653 switch (ioctl
& (WS_IOC_VOID
|WS_IOC_INOUT
))
3657 sprintf(args
, "%d, %d", x
, y
);
3661 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
3665 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
3669 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
3672 return wine_dbg_sprintf("%s(%s)", buf_type
, args
);
3676 /* We are different from WS_IOC_UNIX. */
3677 switch (ioctl
& (WS_IOC_VOID
|WS_IOC_INOUT
))
3680 buf_type
= "_WSAIO";
3683 buf_type
= "_WSAIORW";
3686 buf_type
= "_WSAIOW";
3689 buf_type
= "_WSAIOR";
3696 return wine_dbg_sprintf("%s(%s, %d)", buf_type
, family
,
3697 (USHORT
)(ioctl
& 0xffff));
3700 /* do an ioctl call through the server */
3701 static DWORD
server_ioctl_sock( SOCKET s
, DWORD code
, LPVOID in_buff
, DWORD in_size
,
3702 LPVOID out_buff
, DWORD out_size
, LPDWORD ret_size
,
3703 LPWSAOVERLAPPED overlapped
,
3704 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
3706 HANDLE event
= overlapped
? overlapped
->hEvent
: 0;
3707 HANDLE handle
= SOCKET2HANDLE( s
);
3708 struct ws2_async
*wsa
;
3710 PIO_STATUS_BLOCK io
;
3712 if (!(wsa
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wsa
) )))
3713 return WSA_NOT_ENOUGH_MEMORY
;
3714 wsa
->hSocket
= handle
;
3715 wsa
->user_overlapped
= overlapped
;
3716 wsa
->completion_func
= completion
;
3717 io
= (overlapped
? (PIO_STATUS_BLOCK
)overlapped
: &wsa
->local_iosb
);
3719 status
= NtDeviceIoControlFile( handle
, event
, (PIO_APC_ROUTINE
)ws2_async_apc
, wsa
, io
, code
,
3720 in_buff
, in_size
, out_buff
, out_size
);
3721 if (status
== STATUS_NOT_SUPPORTED
)
3723 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
3724 code
, code
>> 16, (code
>> 14) & 3, (code
>> 2) & 0xfff, code
& 3);
3726 else if (status
== STATUS_SUCCESS
)
3727 *ret_size
= io
->Information
; /* "Information" is the size written to the output buffer */
3729 if (status
!= STATUS_PENDING
) RtlFreeHeap( GetProcessHeap(), 0, wsa
);
3731 return NtStatusToWSAError( status
);
3734 /**********************************************************************
3735 * WSAIoctl (WS2_32.50)
3738 INT WINAPI
WSAIoctl(SOCKET s
, DWORD code
, LPVOID in_buff
, DWORD in_size
, LPVOID out_buff
,
3739 DWORD out_size
, LPDWORD ret_size
, LPWSAOVERLAPPED overlapped
,
3740 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
3743 DWORD status
= 0, total
= 0;
3745 TRACE("%ld, %s, %p, %d, %p, %d, %p, %p, %p\n",
3746 s
, debugstr_wsaioctl(code
), in_buff
, in_size
, out_buff
, out_size
, ret_size
, overlapped
, completion
);
3751 if (in_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(in_buff
))
3753 WSASetLastError(WSAEFAULT
);
3754 return SOCKET_ERROR
;
3756 TRACE("-> FIONBIO (%x)\n", *(WS_u_long
*)in_buff
);
3757 if (_get_sock_mask(s
))
3759 /* AsyncSelect()'ed sockets are always nonblocking */
3760 if (!*(WS_u_long
*)in_buff
) status
= WSAEINVAL
;
3763 if (*(WS_u_long
*)in_buff
)
3764 _enable_event(SOCKET2HANDLE(s
), 0, FD_WINE_NONBLOCKING
, 0);
3766 _enable_event(SOCKET2HANDLE(s
), 0, 0, FD_WINE_NONBLOCKING
);
3771 if (out_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(out_buff
))
3773 WSASetLastError(WSAEFAULT
);
3774 return SOCKET_ERROR
;
3776 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
3777 if (ioctl(fd
, FIONREAD
, out_buff
) == -1)
3778 status
= (errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno();
3779 release_sock_fd( s
, fd
);
3785 unsigned int oob
= 0, atmark
= 0;
3786 socklen_t oobsize
= sizeof(int);
3787 if (out_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(out_buff
))
3789 WSASetLastError(WSAEFAULT
);
3790 return SOCKET_ERROR
;
3792 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
3793 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
3794 if ((getsockopt(fd
, SOL_SOCKET
, SO_OOBINLINE
, &oob
, &oobsize
) == -1)
3795 || (!oob
&& ioctl(fd
, SIOCATMARK
, &atmark
) == -1))
3796 status
= (errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno();
3799 /* The SIOCATMARK value read from ioctl() is reversed
3800 * because BSD returns TRUE if it's in the OOB mark
3801 * while Windows returns TRUE if there are NO OOB bytes.
3803 (*(WS_u_long
*) out_buff
) = oob
| !atmark
;
3806 release_sock_fd( s
, fd
);
3811 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
3812 SetLastError(WSAEINVAL
);
3813 return SOCKET_ERROR
;
3815 case WS_SIO_GET_INTERFACE_LIST
:
3817 INTERFACE_INFO
* intArray
= out_buff
;
3818 DWORD size
, numInt
= 0, apiReturn
;
3820 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
3822 if (!out_buff
|| !ret_size
)
3824 WSASetLastError(WSAEFAULT
);
3825 return SOCKET_ERROR
;
3828 fd
= get_sock_fd( s
, 0, NULL
);
3829 if (fd
== -1) return SOCKET_ERROR
;
3831 apiReturn
= GetAdaptersInfo(NULL
, &size
);
3832 if (apiReturn
== ERROR_BUFFER_OVERFLOW
)
3834 PIP_ADAPTER_INFO table
= HeapAlloc(GetProcessHeap(),0,size
);
3838 if (GetAdaptersInfo(table
, &size
) == NO_ERROR
)
3840 PIP_ADAPTER_INFO ptr
;
3842 for (ptr
= table
, numInt
= 0; ptr
; ptr
= ptr
->Next
)
3844 unsigned int addr
, mask
, bcast
;
3845 struct ifreq ifInfo
;
3847 /* Skip interfaces without an IPv4 address. */
3848 if (ptr
->IpAddressList
.IpAddress
.String
[0] == '\0')
3851 if ((numInt
+ 1)*sizeof(INTERFACE_INFO
)/sizeof(IP_ADAPTER_INFO
) > out_size
)
3853 WARN("Buffer too small = %u, out_size = %u\n", numInt
+ 1, out_size
);
3858 /* Socket Status Flags */
3859 lstrcpynA(ifInfo
.ifr_name
, ptr
->AdapterName
, IFNAMSIZ
);
3860 if (ioctl(fd
, SIOCGIFFLAGS
, &ifInfo
) < 0)
3862 ERR("Error obtaining status flags for socket!\n");
3868 /* set flags; the values of IFF_* are not the same
3869 under Linux and Windows, therefore must generate
3871 intArray
->iiFlags
= 0;
3872 if (ifInfo
.ifr_flags
& IFF_BROADCAST
)
3873 intArray
->iiFlags
|= WS_IFF_BROADCAST
;
3874 #ifdef IFF_POINTOPOINT
3875 if (ifInfo
.ifr_flags
& IFF_POINTOPOINT
)
3876 intArray
->iiFlags
|= WS_IFF_POINTTOPOINT
;
3878 if (ifInfo
.ifr_flags
& IFF_LOOPBACK
)
3879 intArray
->iiFlags
|= WS_IFF_LOOPBACK
;
3880 if (ifInfo
.ifr_flags
& IFF_UP
)
3881 intArray
->iiFlags
|= WS_IFF_UP
;
3882 if (ifInfo
.ifr_flags
& IFF_MULTICAST
)
3883 intArray
->iiFlags
|= WS_IFF_MULTICAST
;
3886 addr
= inet_addr(ptr
->IpAddressList
.IpAddress
.String
);
3887 mask
= inet_addr(ptr
->IpAddressList
.IpMask
.String
);
3888 bcast
= addr
| ~mask
;
3889 intArray
->iiAddress
.AddressIn
.sin_family
= AF_INET
;
3890 intArray
->iiAddress
.AddressIn
.sin_port
= 0;
3891 intArray
->iiAddress
.AddressIn
.sin_addr
.WS_s_addr
=
3893 intArray
->iiNetmask
.AddressIn
.sin_family
= AF_INET
;
3894 intArray
->iiNetmask
.AddressIn
.sin_port
= 0;
3895 intArray
->iiNetmask
.AddressIn
.sin_addr
.WS_s_addr
=
3897 intArray
->iiBroadcastAddress
.AddressIn
.sin_family
=
3899 intArray
->iiBroadcastAddress
.AddressIn
.sin_port
= 0;
3900 intArray
->iiBroadcastAddress
.AddressIn
.sin_addr
.
3908 ERR("Unable to get interface table!\n");
3911 HeapFree(GetProcessHeap(),0,table
);
3913 else status
= WSAEINVAL
;
3915 else if (apiReturn
!= ERROR_NO_DATA
)
3917 ERR("Unable to get interface table!\n");
3920 /* Calculate the size of the array being returned */
3921 total
= sizeof(INTERFACE_INFO
) * numInt
;
3922 release_sock_fd( s
, fd
);
3926 case WS_SIO_ADDRESS_LIST_QUERY
:
3930 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
3934 WSASetLastError(WSAEFAULT
);
3935 return SOCKET_ERROR
;
3938 if (GetAdaptersInfo(NULL
, &size
) == ERROR_BUFFER_OVERFLOW
)
3940 IP_ADAPTER_INFO
*p
, *table
= HeapAlloc(GetProcessHeap(), 0, size
);
3943 if (!table
|| GetAdaptersInfo(table
, &size
))
3945 HeapFree(GetProcessHeap(), 0, table
);
3950 for (p
= table
, num
= 0; p
; p
= p
->Next
)
3951 if (p
->IpAddressList
.IpAddress
.String
[0]) num
++;
3953 total
= sizeof(SOCKET_ADDRESS_LIST
) + sizeof(SOCKET_ADDRESS
) * (num
- 1);
3954 total
+= sizeof(SOCKADDR
) * num
;
3956 if (total
> out_size
)
3958 HeapFree(GetProcessHeap(), 0, table
);
3967 SOCKET_ADDRESS_LIST
*sa_list
= out_buff
;
3968 SOCKADDR_IN
*sockaddr
;
3970 sa
= sa_list
->Address
;
3971 sockaddr
= (SOCKADDR_IN
*)((char *)sa
+ num
* sizeof(SOCKET_ADDRESS
));
3972 sa_list
->iAddressCount
= num
;
3974 for (p
= table
, i
= 0; p
; p
= p
->Next
)
3976 if (!p
->IpAddressList
.IpAddress
.String
[0]) continue;
3978 sa
[i
].lpSockaddr
= (SOCKADDR
*)&sockaddr
[i
];
3979 sa
[i
].iSockaddrLength
= sizeof(SOCKADDR
);
3981 sockaddr
[i
].sin_family
= AF_INET
;
3982 sockaddr
[i
].sin_port
= 0;
3983 sockaddr
[i
].sin_addr
.WS_s_addr
= inet_addr(p
->IpAddressList
.IpAddress
.String
);
3988 HeapFree(GetProcessHeap(), 0, table
);
3992 WARN("unable to get IP address list\n");
3999 FIXME("SIO_FLUSH: stub.\n");
4002 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER
:
4004 static const GUID connectex_guid
= WSAID_CONNECTEX
;
4005 static const GUID disconnectex_guid
= WSAID_DISCONNECTEX
;
4006 static const GUID acceptex_guid
= WSAID_ACCEPTEX
;
4007 static const GUID getaccepexsockaddrs_guid
= WSAID_GETACCEPTEXSOCKADDRS
;
4008 static const GUID transmitfile_guid
= WSAID_TRANSMITFILE
;
4009 static const GUID transmitpackets_guid
= WSAID_TRANSMITPACKETS
;
4010 static const GUID wsarecvmsg_guid
= WSAID_WSARECVMSG
;
4011 static const GUID wsasendmsg_guid
= WSAID_WSASENDMSG
;
4013 if ( IsEqualGUID(&connectex_guid
, in_buff
) )
4015 *(LPFN_CONNECTEX
*)out_buff
= WS2_ConnectEx
;
4018 else if ( IsEqualGUID(&disconnectex_guid
, in_buff
) )
4020 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
4022 else if ( IsEqualGUID(&acceptex_guid
, in_buff
) )
4024 *(LPFN_ACCEPTEX
*)out_buff
= WS2_AcceptEx
;
4027 else if ( IsEqualGUID(&getaccepexsockaddrs_guid
, in_buff
) )
4029 *(LPFN_GETACCEPTEXSOCKADDRS
*)out_buff
= WS2_GetAcceptExSockaddrs
;
4032 else if ( IsEqualGUID(&transmitfile_guid
, in_buff
) )
4034 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
4036 else if ( IsEqualGUID(&transmitpackets_guid
, in_buff
) )
4038 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
4040 else if ( IsEqualGUID(&wsarecvmsg_guid
, in_buff
) )
4042 *(LPFN_WSARECVMSG
*)out_buff
= WS2_WSARecvMsg
;
4045 else if ( IsEqualGUID(&wsasendmsg_guid
, in_buff
) )
4047 *(LPFN_WSASENDMSG
*)out_buff
= WSASendMsg
;
4051 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff
));
4053 status
= WSAEOPNOTSUPP
;
4056 case WS_SIO_KEEPALIVE_VALS
:
4058 struct tcp_keepalive
*k
;
4059 int keepalive
, keepidle
, keepintvl
;
4061 if (!in_buff
|| in_size
< sizeof(struct tcp_keepalive
))
4063 WSASetLastError(WSAEFAULT
);
4064 return SOCKET_ERROR
;
4068 keepalive
= k
->onoff
? 1 : 0;
4069 keepidle
= max( 1, (k
->keepalivetime
+ 500) / 1000 );
4070 keepintvl
= max( 1, (k
->keepaliveinterval
+ 500) / 1000 );
4072 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive
, keepidle
, keepintvl
);
4074 fd
= get_sock_fd(s
, 0, NULL
);
4075 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&keepalive
, sizeof(int)) == -1)
4077 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
4078 /* these values need to be set only if SO_KEEPALIVE is enabled */
4081 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPIDLE
, (void *)&keepidle
, sizeof(int)) == -1)
4083 else if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPINTVL
, (void *)&keepintvl
, sizeof(int)) == -1)
4088 FIXME("ignoring keepalive interval and timeout\n");
4090 release_sock_fd(s
, fd
);
4093 case WS_SIO_ROUTING_INTERFACE_QUERY
:
4095 struct WS_sockaddr
*daddr
= (struct WS_sockaddr
*)in_buff
;
4096 struct WS_sockaddr_in
*daddr_in
= (struct WS_sockaddr_in
*)daddr
;
4097 struct WS_sockaddr_in
*saddr_in
= out_buff
;
4098 MIB_IPFORWARDROW row
;
4099 PMIB_IPADDRTABLE ipAddrTable
= NULL
;
4100 DWORD size
, i
, found_index
;
4102 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4104 if (!in_buff
|| in_size
< sizeof(struct WS_sockaddr
) ||
4105 !out_buff
|| out_size
< sizeof(struct WS_sockaddr_in
) || !ret_size
)
4107 WSASetLastError(WSAEFAULT
);
4108 return SOCKET_ERROR
;
4110 if (daddr
->sa_family
!= AF_INET
)
4112 FIXME("unsupported address family %d\n", daddr
->sa_family
);
4113 status
= WSAEAFNOSUPPORT
;
4116 if (GetBestRoute(daddr_in
->sin_addr
.S_un
.S_addr
, 0, &row
) != NOERROR
||
4117 GetIpAddrTable(NULL
, &size
, FALSE
) != ERROR_INSUFFICIENT_BUFFER
)
4122 ipAddrTable
= HeapAlloc(GetProcessHeap(), 0, size
);
4123 if (GetIpAddrTable(ipAddrTable
, &size
, FALSE
))
4125 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
4129 for (i
= 0, found_index
= ipAddrTable
->dwNumEntries
;
4130 i
< ipAddrTable
->dwNumEntries
; i
++)
4132 if (ipAddrTable
->table
[i
].dwIndex
== row
.dwForwardIfIndex
)
4135 if (found_index
== ipAddrTable
->dwNumEntries
)
4137 ERR("no matching IP address for interface %d\n",
4138 row
.dwForwardIfIndex
);
4139 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
4143 saddr_in
->sin_family
= AF_INET
;
4144 saddr_in
->sin_addr
.S_un
.S_addr
= ipAddrTable
->table
[found_index
].dwAddr
;
4145 saddr_in
->sin_port
= 0;
4146 total
= sizeof(struct WS_sockaddr_in
);
4147 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
4150 case WS_SIO_SET_COMPATIBILITY_MODE
:
4151 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4152 status
= WSAEOPNOTSUPP
;
4154 case WS_SIO_UDP_CONNRESET
:
4155 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4157 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4158 WSASetLastError(WSAEOPNOTSUPP
);
4159 return SOCKET_ERROR
;
4161 status
= WSAEOPNOTSUPP
;
4165 if (status
== WSAEOPNOTSUPP
)
4167 status
= server_ioctl_sock(s
, code
, in_buff
, in_size
, out_buff
, out_size
, &total
,
4168 overlapped
, completion
);
4169 if (status
!= WSAEOPNOTSUPP
)
4171 if (status
== 0 || status
== WSA_IO_PENDING
)
4172 TRACE("-> %s request\n", debugstr_wsaioctl(code
));
4174 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code
), status
);
4176 /* overlapped and completion operations will be handled by the server */
4181 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code
));
4186 FIXME( "completion routine %p not supported\n", completion
);
4188 else if (overlapped
)
4190 ULONG_PTR cvalue
= (overlapped
&& ((ULONG_PTR
)overlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)overlapped
: 0;
4191 overlapped
->Internal
= status
;
4192 overlapped
->InternalHigh
= total
;
4193 if (overlapped
->hEvent
) NtSetEvent( overlapped
->hEvent
, NULL
);
4194 if (cvalue
) WS_AddCompletion( HANDLE2SOCKET(s
), cvalue
, status
, total
);
4199 if (ret_size
) *ret_size
= total
;
4202 SetLastError( status
);
4203 return SOCKET_ERROR
;
4207 /***********************************************************************
4208 * ioctlsocket (WS2_32.10)
4210 int WINAPI
WS_ioctlsocket(SOCKET s
, LONG cmd
, WS_u_long
*argp
)
4213 return WSAIoctl( s
, cmd
, argp
, sizeof(WS_u_long
), argp
, sizeof(WS_u_long
), &ret_size
, NULL
, NULL
);
4216 /***********************************************************************
4217 * listen (WS2_32.13)
4219 int WINAPI
WS_listen(SOCKET s
, int backlog
)
4221 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
), ret
= SOCKET_ERROR
;
4223 TRACE("socket %04lx, backlog %d\n", s
, backlog
);
4226 union generic_unix_sockaddr uaddr
;
4227 socklen_t uaddrlen
= sizeof(uaddr
);
4229 if (getsockname(fd
, &uaddr
.addr
, &uaddrlen
) != 0)
4231 SetLastError(wsaErrno());
4233 else if (!is_sockaddr_bound(&uaddr
.addr
, uaddrlen
))
4235 SetLastError(WSAEINVAL
);
4237 else if (listen(fd
, backlog
) == 0)
4239 _enable_event(SOCKET2HANDLE(s
), FD_ACCEPT
,
4241 FD_CONNECT
|FD_WINE_CONNECTED
);
4245 SetLastError(wsaErrno());
4246 release_sock_fd( s
, fd
);
4249 SetLastError(WSAENOTSOCK
);
4253 /***********************************************************************
4256 int WINAPI
WS_recv(SOCKET s
, char *buf
, int len
, int flags
)
4258 DWORD n
, dwFlags
= flags
;
4264 if ( WS2_recv_base(s
, &wsabuf
, 1, &n
, &dwFlags
, NULL
, NULL
, NULL
, NULL
, NULL
) == SOCKET_ERROR
)
4265 return SOCKET_ERROR
;
4270 /***********************************************************************
4271 * recvfrom (WS2_32.17)
4273 int WINAPI
WS_recvfrom(SOCKET s
, char *buf
, INT len
, int flags
,
4274 struct WS_sockaddr
*from
, int *fromlen
)
4276 DWORD n
, dwFlags
= flags
;
4282 if ( WS2_recv_base(s
, &wsabuf
, 1, &n
, &dwFlags
, from
, fromlen
, NULL
, NULL
, NULL
) == SOCKET_ERROR
)
4283 return SOCKET_ERROR
;
4288 /* allocate a poll array for the corresponding fd sets */
4289 static struct pollfd
*fd_sets_to_poll( const WS_fd_set
*readfds
, const WS_fd_set
*writefds
,
4290 const WS_fd_set
*exceptfds
, int *count_ptr
)
4292 unsigned int i
, j
= 0, count
= 0;
4295 if (readfds
) count
+= readfds
->fd_count
;
4296 if (writefds
) count
+= writefds
->fd_count
;
4297 if (exceptfds
) count
+= exceptfds
->fd_count
;
4301 SetLastError(WSAEINVAL
);
4304 if (!(fds
= HeapAlloc( GetProcessHeap(), 0, count
* sizeof(fds
[0]))))
4306 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
4310 for (i
= 0; i
< readfds
->fd_count
; i
++, j
++)
4312 fds
[j
].fd
= get_sock_fd( readfds
->fd_array
[i
], FILE_READ_DATA
, NULL
);
4313 if (fds
[j
].fd
== -1) goto failed
;
4314 fds
[j
].events
= POLLIN
;
4318 for (i
= 0; i
< writefds
->fd_count
; i
++, j
++)
4320 fds
[j
].fd
= get_sock_fd( writefds
->fd_array
[i
], FILE_WRITE_DATA
, NULL
);
4321 if (fds
[j
].fd
== -1) goto failed
;
4322 fds
[j
].events
= POLLOUT
;
4326 for (i
= 0; i
< exceptfds
->fd_count
; i
++, j
++)
4328 fds
[j
].fd
= get_sock_fd( exceptfds
->fd_array
[i
], 0, NULL
);
4329 if (fds
[j
].fd
== -1) goto failed
;
4330 fds
[j
].events
= POLLHUP
;
4339 for (i
= 0; i
< readfds
->fd_count
&& j
< count
; i
++, j
++)
4340 release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
4342 for (i
= 0; i
< writefds
->fd_count
&& j
< count
; i
++, j
++)
4343 release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
4345 for (i
= 0; i
< exceptfds
->fd_count
&& j
< count
; i
++, j
++)
4346 release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
4347 HeapFree( GetProcessHeap(), 0, fds
);
4351 /* release the file descriptor obtained in fd_sets_to_poll */
4352 /* must be called with the original fd_set arrays, before calling get_poll_results */
4353 static void release_poll_fds( const WS_fd_set
*readfds
, const WS_fd_set
*writefds
,
4354 const WS_fd_set
*exceptfds
, struct pollfd
*fds
)
4356 unsigned int i
, j
= 0;
4360 for (i
= 0; i
< readfds
->fd_count
; i
++, j
++)
4361 if (fds
[j
].fd
!= -1) release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
4365 for (i
= 0; i
< writefds
->fd_count
; i
++, j
++)
4366 if (fds
[j
].fd
!= -1) release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
4370 for (i
= 0; i
< exceptfds
->fd_count
; i
++, j
++)
4371 if (fds
[j
].fd
!= -1)
4373 /* make sure we have a real error before releasing the fd */
4374 if (!sock_error_p( fds
[j
].fd
)) fds
[j
].revents
= 0;
4375 release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
4380 /* map the poll results back into the Windows fd sets */
4381 static int get_poll_results( WS_fd_set
*readfds
, WS_fd_set
*writefds
, WS_fd_set
*exceptfds
,
4382 const struct pollfd
*fds
)
4384 unsigned int i
, j
= 0, k
, total
= 0;
4388 for (i
= k
= 0; i
< readfds
->fd_count
; i
++, j
++)
4389 if (fds
[j
].revents
) readfds
->fd_array
[k
++] = readfds
->fd_array
[i
];
4390 readfds
->fd_count
= k
;
4395 for (i
= k
= 0; i
< writefds
->fd_count
; i
++, j
++)
4396 if ((fds
[j
].revents
& POLLOUT
) && !(fds
[j
].revents
& POLLHUP
))
4397 writefds
->fd_array
[k
++] = writefds
->fd_array
[i
];
4398 writefds
->fd_count
= k
;
4403 for (i
= k
= 0; i
< exceptfds
->fd_count
; i
++, j
++)
4404 if (fds
[j
].revents
) exceptfds
->fd_array
[k
++] = exceptfds
->fd_array
[i
];
4405 exceptfds
->fd_count
= k
;
4412 /***********************************************************************
4413 * select (WS2_32.18)
4415 int WINAPI
WS_select(int nfds
, WS_fd_set
*ws_readfds
,
4416 WS_fd_set
*ws_writefds
, WS_fd_set
*ws_exceptfds
,
4417 const struct WS_timeval
* ws_timeout
)
4419 struct pollfd
*pollfds
;
4420 struct timeval tv1
, tv2
;
4422 int count
, ret
, timeout
= -1;
4424 TRACE("read %p, write %p, excp %p timeout %p\n",
4425 ws_readfds
, ws_writefds
, ws_exceptfds
, ws_timeout
);
4427 if (!(pollfds
= fd_sets_to_poll( ws_readfds
, ws_writefds
, ws_exceptfds
, &count
)))
4428 return SOCKET_ERROR
;
4432 torig
= (ws_timeout
->tv_sec
* 1000) + (ws_timeout
->tv_usec
+ 999) / 1000;
4434 gettimeofday( &tv1
, 0 );
4437 while ((ret
= poll( pollfds
, count
, timeout
)) < 0)
4441 if (!ws_timeout
) continue;
4442 gettimeofday( &tv2
, 0 );
4444 tv2
.tv_sec
-= tv1
.tv_sec
;
4445 tv2
.tv_usec
-= tv1
.tv_usec
;
4446 if (tv2
.tv_usec
< 0)
4448 tv2
.tv_usec
+= 1000000;
4452 timeout
= torig
- (tv2
.tv_sec
* 1000) - (tv2
.tv_usec
+ 999) / 1000;
4453 if (timeout
<= 0) break;
4456 release_poll_fds( ws_readfds
, ws_writefds
, ws_exceptfds
, pollfds
);
4458 if (ret
== -1) SetLastError(wsaErrno());
4459 else ret
= get_poll_results( ws_readfds
, ws_writefds
, ws_exceptfds
, pollfds
);
4460 HeapFree( GetProcessHeap(), 0, pollfds
);
4464 /* helper to send completion messages for client-only i/o operation case */
4465 static void WS_AddCompletion( SOCKET sock
, ULONG_PTR CompletionValue
, NTSTATUS CompletionStatus
,
4468 SERVER_START_REQ( add_fd_completion
)
4470 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(sock
) );
4471 req
->cvalue
= CompletionValue
;
4472 req
->status
= CompletionStatus
;
4473 req
->information
= Information
;
4474 wine_server_call( req
);
4480 /***********************************************************************
4483 int WINAPI
WS_send(SOCKET s
, const char *buf
, int len
, int flags
)
4489 wsabuf
.buf
= (char*) buf
;
4491 if ( WS2_sendto( s
, &wsabuf
, 1, &n
, flags
, NULL
, 0, NULL
, NULL
) == SOCKET_ERROR
)
4492 return SOCKET_ERROR
;
4497 /***********************************************************************
4498 * WSASend (WS2_32.72)
4500 INT WINAPI
WSASend( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
4501 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
4502 LPWSAOVERLAPPED lpOverlapped
,
4503 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
4505 return WS2_sendto( s
, lpBuffers
, dwBufferCount
, lpNumberOfBytesSent
, dwFlags
,
4506 NULL
, 0, lpOverlapped
, lpCompletionRoutine
);
4509 /***********************************************************************
4510 * WSASendDisconnect (WS2_32.73)
4512 INT WINAPI
WSASendDisconnect( SOCKET s
, LPWSABUF lpBuffers
)
4514 return WS_shutdown( s
, SD_SEND
);
4518 static int WS2_sendto( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
4519 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
4520 const struct WS_sockaddr
*to
, int tolen
,
4521 LPWSAOVERLAPPED lpOverlapped
,
4522 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
4524 unsigned int i
, options
;
4525 int n
, fd
, err
, overlapped
;
4526 struct ws2_async
*wsa
= NULL
, localwsa
;
4527 int totalLength
= 0;
4531 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
4532 s
, lpBuffers
, dwBufferCount
, dwFlags
,
4533 to
, tolen
, lpOverlapped
, lpCompletionRoutine
);
4535 fd
= get_sock_fd( s
, FILE_WRITE_DATA
, &options
);
4536 TRACE( "fd=%d, options=%x\n", fd
, options
);
4538 if ( fd
== -1 ) return SOCKET_ERROR
;
4540 if (!lpOverlapped
&& !lpNumberOfBytesSent
)
4546 overlapped
= (lpOverlapped
|| lpCompletionRoutine
) &&
4547 !(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
));
4548 if (overlapped
|| dwBufferCount
> 1)
4550 if (!(wsa
= HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async
, iovec
[dwBufferCount
]) )))
4559 wsa
->hSocket
= SOCKET2HANDLE(s
);
4560 wsa
->addr
= (struct WS_sockaddr
*)to
;
4561 wsa
->addrlen
.val
= tolen
;
4562 wsa
->flags
= dwFlags
;
4563 wsa
->lpFlags
= &wsa
->flags
;
4564 wsa
->control
= NULL
;
4565 wsa
->n_iovecs
= dwBufferCount
;
4566 wsa
->first_iovec
= 0;
4567 for ( i
= 0; i
< dwBufferCount
; i
++ )
4569 wsa
->iovec
[i
].iov_base
= lpBuffers
[i
].buf
;
4570 wsa
->iovec
[i
].iov_len
= lpBuffers
[i
].len
;
4571 totalLength
+= lpBuffers
[i
].len
;
4574 n
= WS2_send( fd
, wsa
);
4575 if (n
== -1 && errno
!= EAGAIN
)
4583 IO_STATUS_BLOCK
*iosb
= lpOverlapped
? (IO_STATUS_BLOCK
*)lpOverlapped
: &wsa
->local_iosb
;
4584 ULONG_PTR cvalue
= (lpOverlapped
&& ((ULONG_PTR
)lpOverlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)lpOverlapped
: 0;
4586 wsa
->user_overlapped
= lpOverlapped
;
4587 wsa
->completion_func
= lpCompletionRoutine
;
4588 release_sock_fd( s
, fd
);
4590 if (n
== -1 || n
< totalLength
)
4592 iosb
->u
.Status
= STATUS_PENDING
;
4593 iosb
->Information
= n
== -1 ? 0 : n
;
4595 SERVER_START_REQ( register_async
)
4597 req
->type
= ASYNC_TYPE_WRITE
;
4598 req
->async
.handle
= wine_server_obj_handle( wsa
->hSocket
);
4599 req
->async
.callback
= wine_server_client_ptr( WS2_async_send
);
4600 req
->async
.iosb
= wine_server_client_ptr( iosb
);
4601 req
->async
.arg
= wine_server_client_ptr( wsa
);
4602 req
->async
.event
= wine_server_obj_handle( lpCompletionRoutine
? 0 : lpOverlapped
->hEvent
);
4603 req
->async
.cvalue
= cvalue
;
4604 err
= wine_server_call( req
);
4608 /* Enable the event only after starting the async. The server will deliver it as soon as
4609 the async is done. */
4610 _enable_event(SOCKET2HANDLE(s
), FD_WRITE
, 0, 0);
4612 if (err
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
4613 WSASetLastError( NtStatusToWSAError( err
));
4614 return SOCKET_ERROR
;
4617 iosb
->u
.Status
= STATUS_SUCCESS
;
4618 iosb
->Information
= n
;
4619 if (lpNumberOfBytesSent
) *lpNumberOfBytesSent
= n
;
4620 if (!wsa
->completion_func
)
4622 if (cvalue
) WS_AddCompletion( s
, cvalue
, STATUS_SUCCESS
, n
);
4623 if (lpOverlapped
->hEvent
) SetEvent( lpOverlapped
->hEvent
);
4624 HeapFree( GetProcessHeap(), 0, wsa
);
4626 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC
)ws2_async_apc
,
4627 (ULONG_PTR
)wsa
, (ULONG_PTR
)iosb
, 0 );
4632 if ((err
= _is_blocking( s
, &is_blocking
)))
4634 err
= NtStatusToWSAError( err
);
4640 /* On a blocking non-overlapped stream socket,
4641 * sending blocks until the entire buffer is sent. */
4642 DWORD timeout_start
= GetTickCount();
4644 bytes_sent
= n
== -1 ? 0 : n
;
4646 while (wsa
->first_iovec
< wsa
->n_iovecs
)
4649 int timeout
= GET_SNDTIMEO(fd
);
4653 timeout
-= GetTickCount() - timeout_start
;
4654 if (timeout
< 0) timeout
= 0;
4658 pfd
.events
= POLLOUT
;
4660 if (!timeout
|| !poll( &pfd
, 1, timeout
))
4663 goto error
; /* msdn says a timeout in send is fatal */
4666 n
= WS2_send( fd
, wsa
);
4667 if (n
== -1 && errno
!= EAGAIN
)
4677 else /* non-blocking */
4679 if (n
< totalLength
)
4680 _enable_event(SOCKET2HANDLE(s
), FD_WRITE
, 0, 0);
4683 err
= WSAEWOULDBLOCK
;
4689 TRACE(" -> %i bytes\n", bytes_sent
);
4691 if (lpNumberOfBytesSent
) *lpNumberOfBytesSent
= bytes_sent
;
4692 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
4693 release_sock_fd( s
, fd
);
4698 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
4699 release_sock_fd( s
, fd
);
4700 WARN(" -> ERROR %d\n", err
);
4701 WSASetLastError(err
);
4702 return SOCKET_ERROR
;
4705 /***********************************************************************
4706 * WSASendTo (WS2_32.74)
4708 INT WINAPI
WSASendTo( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
4709 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
4710 const struct WS_sockaddr
*to
, int tolen
,
4711 LPWSAOVERLAPPED lpOverlapped
,
4712 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
4714 return WS2_sendto( s
, lpBuffers
, dwBufferCount
,
4715 lpNumberOfBytesSent
, dwFlags
,
4717 lpOverlapped
, lpCompletionRoutine
);
4720 /***********************************************************************
4721 * sendto (WS2_32.20)
4723 int WINAPI
WS_sendto(SOCKET s
, const char *buf
, int len
, int flags
,
4724 const struct WS_sockaddr
*to
, int tolen
)
4730 wsabuf
.buf
= (char*) buf
;
4732 if ( WS2_sendto(s
, &wsabuf
, 1, &n
, flags
, to
, tolen
, NULL
, NULL
) == SOCKET_ERROR
)
4733 return SOCKET_ERROR
;
4738 /***********************************************************************
4739 * setsockopt (WS2_32.21)
4741 int WINAPI
WS_setsockopt(SOCKET s
, int level
, int optname
,
4742 const char *optval
, int optlen
)
4746 struct linger linger
;
4747 struct timeval tval
;
4749 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
4750 s
, level
, optname
, optval
, optlen
);
4752 /* some broken apps pass the value directly instead of a pointer to it */
4753 if(optlen
&& IS_INTRESOURCE(optval
))
4755 SetLastError(WSAEFAULT
);
4756 return SOCKET_ERROR
;
4764 /* Some options need some conversion before they can be sent to
4765 * setsockopt. The conversions are done here, then they will fall through
4766 * to the general case. Special options that are not passed to
4767 * setsockopt follow below that.*/
4769 case WS_SO_DONTLINGER
:
4772 SetLastError(WSAEFAULT
);
4773 return SOCKET_ERROR
;
4775 linger
.l_onoff
= *(const int*)optval
== 0;
4776 linger
.l_linger
= 0;
4778 optname
= SO_LINGER
;
4779 optval
= (char*)&linger
;
4780 optlen
= sizeof(struct linger
);
4786 SetLastError(WSAEFAULT
);
4787 return SOCKET_ERROR
;
4789 linger
.l_onoff
= ((LINGER
*)optval
)->l_onoff
;
4790 linger
.l_linger
= ((LINGER
*)optval
)->l_linger
;
4792 optname
= SO_LINGER
;
4793 optval
= (char*)&linger
;
4794 optlen
= sizeof(struct linger
);
4798 if (*(const int*)optval
< 2048)
4800 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval
);
4805 /* The options listed here don't need any special handling. Thanks to
4806 * the conversion happening above, options from there will fall through
4808 case WS_SO_ACCEPTCONN
:
4809 case WS_SO_BROADCAST
:
4811 case WS_SO_KEEPALIVE
:
4812 case WS_SO_OOBINLINE
:
4813 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
4814 * however, using it the BSD way fixes bug 8513 and seems to be what
4815 * most programmers assume, anyway */
4816 case WS_SO_REUSEADDR
:
4819 convert_sockopt(&level
, &optname
);
4822 /* SO_DEBUG is a privileged operation, ignore it. */
4824 TRACE("Ignoring SO_DEBUG\n");
4827 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
4828 * socket. According to MSDN, this option is silently ignored.*/
4829 case WS_SO_DONTROUTE
:
4830 TRACE("Ignoring SO_DONTROUTE\n");
4833 /* Stops two sockets from being bound to the same port. Always happens
4834 * on unix systems, so just drop it. */
4835 case WS_SO_EXCLUSIVEADDRUSE
:
4836 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
4839 /* After a ConnectEx call succeeds, the socket can't be used with half of the
4840 * normal winsock functions on windows. We don't have that problem. */
4841 case WS_SO_UPDATE_CONNECT_CONTEXT
:
4842 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
4845 /* After a AcceptEx call succeeds, the socket can't be used with half of the
4846 * normal winsock functions on windows. We don't have that problem. */
4847 case WS_SO_UPDATE_ACCEPT_CONTEXT
:
4848 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
4851 /* SO_OPENTYPE does not require a valid socket handle. */
4852 case WS_SO_OPENTYPE
:
4853 if (!optlen
|| optlen
< sizeof(int) || !optval
)
4855 SetLastError(WSAEFAULT
);
4856 return SOCKET_ERROR
;
4858 get_per_thread_data()->opentype
= *(const int *)optval
;
4859 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval
) );
4863 case WS_SO_RCVTIMEO
:
4866 case WS_SO_SNDTIMEO
:
4868 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
4869 if (optval
&& optlen
== sizeof(UINT32
)) {
4870 /* WinSock passes milliseconds instead of struct timeval */
4871 tval
.tv_usec
= (*(const UINT32
*)optval
% 1000) * 1000;
4872 tval
.tv_sec
= *(const UINT32
*)optval
/ 1000;
4873 /* min of 500 milliseconds */
4874 if (tval
.tv_sec
== 0 && tval
.tv_usec
&& tval
.tv_usec
< 500000)
4875 tval
.tv_usec
= 500000;
4876 optlen
= sizeof(struct timeval
);
4877 optval
= (char*)&tval
;
4878 } else if (optlen
== sizeof(struct timeval
)) {
4879 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen
);
4881 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen
);
4884 convert_sockopt(&level
, &optname
);
4889 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname
);
4890 SetLastError(WSAENOPROTOOPT
);
4891 return SOCKET_ERROR
;
4893 break; /* case WS_SOL_SOCKET */
4896 case WS_NSPROTO_IPX
:
4900 return set_ipx_packettype(s
, *(int*)optval
);
4902 case IPX_FILTERPTYPE
:
4903 /* Sets the receive filter packet type, at the moment we don't support it */
4904 FIXME("IPX_FILTERPTYPE: %x\n", *optval
);
4905 /* Returning 0 is better for now than returning a SOCKET_ERROR */
4909 FIXME("opt_name:%x\n", optname
);
4910 return SOCKET_ERROR
;
4912 break; /* case WS_NSPROTO_IPX */
4915 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4916 case WS_IPPROTO_TCP
:
4919 case WS_TCP_NODELAY
:
4920 convert_sockopt(&level
, &optname
);
4923 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname
);
4924 return SOCKET_ERROR
;
4931 case WS_IP_ADD_MEMBERSHIP
:
4932 case WS_IP_DROP_MEMBERSHIP
:
4936 case WS_IP_MULTICAST_IF
:
4937 case WS_IP_MULTICAST_LOOP
:
4938 case WS_IP_MULTICAST_TTL
:
4945 #ifdef IP_UNICAST_IF
4946 case WS_IP_UNICAST_IF
:
4948 convert_sockopt(&level
, &optname
);
4950 case WS_IP_DONTFRAGMENT
:
4951 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
4954 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname
);
4955 return SOCKET_ERROR
;
4959 case WS_IPPROTO_IPV6
:
4962 #ifdef IPV6_ADD_MEMBERSHIP
4963 case WS_IPV6_ADD_MEMBERSHIP
:
4965 #ifdef IPV6_DROP_MEMBERSHIP
4966 case WS_IPV6_DROP_MEMBERSHIP
:
4968 case WS_IPV6_MULTICAST_IF
:
4969 case WS_IPV6_MULTICAST_HOPS
:
4970 case WS_IPV6_MULTICAST_LOOP
:
4971 case WS_IPV6_UNICAST_HOPS
:
4972 case WS_IPV6_V6ONLY
:
4973 #ifdef IPV6_UNICAST_IF
4974 case WS_IPV6_UNICAST_IF
:
4976 convert_sockopt(&level
, &optname
);
4978 case WS_IPV6_DONTFRAG
:
4979 FIXME("IPV6_DONTFRAG is silently ignored!\n");
4981 case WS_IPV6_PROTECTION_LEVEL
:
4982 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
4985 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname
);
4986 return SOCKET_ERROR
;
4991 WARN("Unknown level: 0x%08x\n", level
);
4992 SetLastError(WSAEINVAL
);
4993 return SOCKET_ERROR
;
4994 } /* end switch(level) */
4996 /* avoid endianness issues if argument is a 16-bit int */
4997 if (optval
&& optlen
< sizeof(int))
4999 woptval
= *((const INT16
*) optval
);
5000 optval
= (char*) &woptval
;
5003 fd
= get_sock_fd( s
, 0, NULL
);
5004 if (fd
== -1) return SOCKET_ERROR
;
5006 if (setsockopt(fd
, level
, optname
, optval
, optlen
) == 0)
5009 if (level
== SOL_SOCKET
&& optname
== SO_REUSEADDR
&&
5010 setsockopt(fd
, level
, SO_REUSEPORT
, optval
, optlen
) != 0)
5012 SetLastError(wsaErrno());
5013 release_sock_fd( s
, fd
);
5014 return SOCKET_ERROR
;
5017 release_sock_fd( s
, fd
);
5020 TRACE("Setting socket error, %d\n", wsaErrno());
5021 SetLastError(wsaErrno());
5022 release_sock_fd( s
, fd
);
5024 return SOCKET_ERROR
;
5027 /***********************************************************************
5028 * shutdown (WS2_32.22)
5030 int WINAPI
WS_shutdown(SOCKET s
, int how
)
5032 int fd
, err
= WSAENOTSOCK
;
5033 unsigned int options
, clear_flags
= 0;
5035 fd
= get_sock_fd( s
, 0, &options
);
5036 TRACE("socket %04lx, how %i %x\n", s
, how
, options
);
5039 return SOCKET_ERROR
;
5043 case SD_RECEIVE
: /* drop receives */
5044 clear_flags
|= FD_READ
;
5046 case SD_SEND
: /* drop sends */
5047 clear_flags
|= FD_WRITE
;
5049 case SD_BOTH
: /* drop all */
5050 clear_flags
|= FD_READ
|FD_WRITE
;
5053 clear_flags
|= FD_WINE_LISTENING
;
5056 if (!(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
)))
5061 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_READ
);
5064 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_WRITE
);
5068 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_READ
);
5069 if (!err
) err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_WRITE
);
5072 if (err
) goto error
;
5074 else /* non-overlapped mode */
5076 if ( shutdown( fd
, how
) )
5083 release_sock_fd( s
, fd
);
5084 _enable_event( SOCKET2HANDLE(s
), 0, 0, clear_flags
);
5085 if ( how
> 1) WSAAsyncSelect( s
, 0, 0, 0 );
5089 release_sock_fd( s
, fd
);
5090 _enable_event( SOCKET2HANDLE(s
), 0, 0, clear_flags
);
5091 WSASetLastError( err
);
5092 return SOCKET_ERROR
;
5095 /***********************************************************************
5096 * socket (WS2_32.23)
5098 SOCKET WINAPI
WS_socket(int af
, int type
, int protocol
)
5100 TRACE("af=%d type=%d protocol=%d\n", af
, type
, protocol
);
5102 return WSASocketA( af
, type
, protocol
, NULL
, 0,
5103 get_per_thread_data()->opentype
? 0 : WSA_FLAG_OVERLAPPED
);
5107 /***********************************************************************
5108 * gethostbyaddr (WS2_32.51)
5110 struct WS_hostent
* WINAPI
WS_gethostbyaddr(const char *addr
, int len
, int type
)
5112 struct WS_hostent
*retval
= NULL
;
5113 struct hostent
* host
;
5114 int unixtype
= convert_af_w2u(type
);
5115 const char *paddr
= addr
;
5116 unsigned long loopback
;
5117 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5119 int ebufsize
= 1024;
5120 struct hostent hostentry
;
5121 int locerr
= ENOBUFS
;
5124 /* convert back the magic loopback address if necessary */
5125 if (unixtype
== AF_INET
&& len
== 4 && !memcmp(addr
, magic_loopback_addr
, 4))
5127 loopback
= htonl(INADDR_LOOPBACK
);
5128 paddr
= (char*) &loopback
;
5131 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5133 extrabuf
=HeapAlloc(GetProcessHeap(),0,ebufsize
) ;
5135 int res
= gethostbyaddr_r(paddr
, len
, unixtype
,
5136 &hostentry
, extrabuf
, ebufsize
, &host
, &locerr
);
5137 if (res
!= ERANGE
) break;
5139 extrabuf
=HeapReAlloc(GetProcessHeap(),0,extrabuf
,ebufsize
) ;
5141 if (host
) retval
= WS_dup_he(host
);
5142 else SetLastError((locerr
< 0) ? wsaErrno() : wsaHerrno(locerr
));
5143 HeapFree(GetProcessHeap(),0,extrabuf
);
5145 EnterCriticalSection( &csWSgetXXXbyYYY
);
5146 host
= gethostbyaddr(paddr
, len
, unixtype
);
5147 if (host
) retval
= WS_dup_he(host
);
5148 else SetLastError((h_errno
< 0) ? wsaErrno() : wsaHerrno(h_errno
));
5149 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5151 TRACE("ptr %p, len %d, type %d ret %p\n", addr
, len
, type
, retval
);
5155 /***********************************************************************
5156 * WS_get_local_ips (INTERNAL)
5158 * Returns the list of local IP addresses by going through the network
5159 * adapters and using the local routing table to sort the addresses
5160 * from highest routing priority to lowest routing priority. This
5161 * functionality is inferred from the description for obtaining local
5162 * IP addresses given in the Knowledge Base Article Q160215.
5164 * Please note that the returned hostent is only freed when the thread
5165 * closes and is replaced if another hostent is requested.
5167 static struct WS_hostent
* WS_get_local_ips( char *hostname
)
5169 int last_metric
, numroutes
= 0, i
, j
;
5171 PIP_ADAPTER_INFO adapters
= NULL
, k
;
5172 struct WS_hostent
*hostlist
= NULL
;
5173 PMIB_IPFORWARDTABLE routes
= NULL
;
5174 struct route
*route_addrs
= NULL
;
5175 DWORD adap_size
, route_size
;
5177 /* Obtain the size of the adapter list and routing table, also allocate memory */
5178 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
5180 if (GetIpForwardTable(NULL
, &route_size
, FALSE
) != ERROR_INSUFFICIENT_BUFFER
)
5182 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
5183 routes
= HeapAlloc(GetProcessHeap(), 0, route_size
);
5184 route_addrs
= HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
5185 if (adapters
== NULL
|| routes
== NULL
|| route_addrs
== NULL
)
5187 /* Obtain the adapter list and the full routing table */
5188 if (GetAdaptersInfo(adapters
, &adap_size
) != NO_ERROR
)
5190 if (GetIpForwardTable(routes
, &route_size
, FALSE
) != NO_ERROR
)
5192 /* Store the interface associated with each route */
5193 for (n
= 0; n
< routes
->dwNumEntries
; n
++)
5197 BOOL exists
= FALSE
;
5199 if (routes
->table
[n
].u1
.ForwardType
!= MIB_IPROUTE_TYPE_DIRECT
)
5201 ifindex
= routes
->table
[n
].dwForwardIfIndex
;
5202 ifmetric
= routes
->table
[n
].dwForwardMetric1
;
5203 /* Only store the lowest valued metric for an interface */
5204 for (j
= 0; j
< numroutes
; j
++)
5206 if (route_addrs
[j
].interface
== ifindex
)
5208 if (route_addrs
[j
].metric
> ifmetric
)
5209 route_addrs
[j
].metric
= ifmetric
;
5215 route_addrs
= HeapReAlloc(GetProcessHeap(), 0, route_addrs
, (numroutes
+1)*sizeof(struct route
));
5216 if (route_addrs
== NULL
)
5217 goto cleanup
; /* Memory allocation error, fail gracefully */
5218 route_addrs
[numroutes
].interface
= ifindex
;
5219 route_addrs
[numroutes
].metric
= ifmetric
;
5220 /* If no IP is found in the next step (for whatever reason)
5221 * then fall back to the magic loopback address.
5223 memcpy(&(route_addrs
[numroutes
].addr
.s_addr
), magic_loopback_addr
, 4);
5227 goto cleanup
; /* No routes, fall back to the Magic IP */
5228 /* Find the IP address associated with each found interface */
5229 for (i
= 0; i
< numroutes
; i
++)
5231 for (k
= adapters
; k
!= NULL
; k
= k
->Next
)
5233 char *ip
= k
->IpAddressList
.IpAddress
.String
;
5235 if (route_addrs
[i
].interface
== k
->Index
)
5236 route_addrs
[i
].addr
.s_addr
= (in_addr_t
) inet_addr(ip
);
5239 /* Allocate a hostent and enough memory for all the IPs,
5240 * including the NULL at the end of the list.
5242 hostlist
= WS_create_he(hostname
, 1, 0, numroutes
+1, sizeof(struct in_addr
));
5243 if (hostlist
== NULL
)
5244 goto cleanup
; /* Failed to allocate a hostent for the list of IPs */
5245 hostlist
->h_addr_list
[numroutes
] = NULL
; /* NULL-terminate the address list */
5246 hostlist
->h_aliases
[0] = NULL
; /* NULL-terminate the alias list */
5247 hostlist
->h_addrtype
= AF_INET
;
5248 hostlist
->h_length
= sizeof(struct in_addr
); /* = 4 */
5249 /* Reorder the entries when placing them in the host list, Windows expects
5250 * the IP list in order from highest priority to lowest (the critical thing
5251 * is that most applications expect the first IP to be the default route).
5254 for (i
= 0; i
< numroutes
; i
++)
5256 struct in_addr addr
;
5257 int metric
= 0xFFFF;
5259 memcpy(&addr
, magic_loopback_addr
, 4);
5260 for (j
= 0; j
< numroutes
; j
++)
5262 int this_metric
= route_addrs
[j
].metric
;
5264 if (this_metric
> last_metric
&& this_metric
< metric
)
5266 addr
= route_addrs
[j
].addr
;
5267 metric
= this_metric
;
5270 last_metric
= metric
;
5271 (*(struct in_addr
*) hostlist
->h_addr_list
[i
]) = addr
;
5274 /* Cleanup all allocated memory except the address list,
5275 * the address list is used by the calling app.
5278 HeapFree(GetProcessHeap(), 0, route_addrs
);
5279 HeapFree(GetProcessHeap(), 0, adapters
);
5280 HeapFree(GetProcessHeap(), 0, routes
);
5284 /***********************************************************************
5285 * gethostbyname (WS2_32.52)
5287 struct WS_hostent
* WINAPI
WS_gethostbyname(const char* name
)
5289 struct WS_hostent
*retval
= NULL
;
5290 struct hostent
* host
;
5291 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5294 struct hostent hostentry
;
5295 int locerr
= ENOBUFS
;
5299 SetLastError(WSANOTINITIALISED
);
5302 if( gethostname( hostname
, 100) == -1) {
5303 SetLastError( WSAENOBUFS
); /* appropriate ? */
5306 if( !name
|| !name
[0]) {
5309 /* If the hostname of the local machine is requested then return the
5310 * complete list of local IP addresses */
5311 if(strcmp(name
, hostname
) == 0)
5312 retval
= WS_get_local_ips(hostname
);
5313 /* If any other hostname was requested (or the routing table lookup failed)
5314 * then return the IP found by the host OS */
5317 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5319 extrabuf
=HeapAlloc(GetProcessHeap(),0,ebufsize
) ;
5321 int res
= gethostbyname_r(name
, &hostentry
, extrabuf
, ebufsize
, &host
, &locerr
);
5322 if( res
!= ERANGE
) break;
5324 extrabuf
=HeapReAlloc(GetProcessHeap(),0,extrabuf
,ebufsize
) ;
5326 if (!host
) SetLastError((locerr
< 0) ? wsaErrno() : wsaHerrno(locerr
));
5328 EnterCriticalSection( &csWSgetXXXbyYYY
);
5329 host
= gethostbyname(name
);
5330 if (!host
) SetLastError((h_errno
< 0) ? wsaErrno() : wsaHerrno(h_errno
));
5332 if (host
) retval
= WS_dup_he(host
);
5333 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5334 HeapFree(GetProcessHeap(),0,extrabuf
);
5336 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5339 if (retval
&& retval
->h_addr_list
[0][0] == 127 &&
5340 strcmp(name
, "localhost") != 0)
5342 /* hostname != "localhost" but has loopback address. replace by our
5343 * special address.*/
5344 memcpy(retval
->h_addr_list
[0], magic_loopback_addr
, 4);
5346 TRACE( "%s ret %p\n", debugstr_a(name
), retval
);
5351 /***********************************************************************
5352 * getprotobyname (WS2_32.53)
5354 struct WS_protoent
* WINAPI
WS_getprotobyname(const char* name
)
5356 struct WS_protoent
* retval
= NULL
;
5357 #ifdef HAVE_GETPROTOBYNAME
5358 struct protoent
* proto
;
5359 EnterCriticalSection( &csWSgetXXXbyYYY
);
5360 if( (proto
= getprotobyname(name
)) != NULL
)
5362 retval
= WS_dup_pe(proto
);
5365 MESSAGE("protocol %s not found; You might want to add "
5366 "this to /etc/protocols\n", debugstr_a(name
) );
5367 SetLastError(WSANO_DATA
);
5369 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5371 TRACE( "%s ret %p\n", debugstr_a(name
), retval
);
5376 /***********************************************************************
5377 * getprotobynumber (WS2_32.54)
5379 struct WS_protoent
* WINAPI
WS_getprotobynumber(int number
)
5381 struct WS_protoent
* retval
= NULL
;
5382 #ifdef HAVE_GETPROTOBYNUMBER
5383 struct protoent
* proto
;
5384 EnterCriticalSection( &csWSgetXXXbyYYY
);
5385 if( (proto
= getprotobynumber(number
)) != NULL
)
5387 retval
= WS_dup_pe(proto
);
5390 MESSAGE("protocol number %d not found; You might want to add "
5391 "this to /etc/protocols\n", number
);
5392 SetLastError(WSANO_DATA
);
5394 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5396 TRACE("%i ret %p\n", number
, retval
);
5401 /***********************************************************************
5402 * getservbyname (WS2_32.55)
5404 struct WS_servent
* WINAPI
WS_getservbyname(const char *name
, const char *proto
)
5406 struct WS_servent
* retval
= NULL
;
5407 struct servent
* serv
;
5409 char *proto_str
= NULL
;
5411 if (!(name_str
= strdup_lower(name
))) return NULL
;
5413 if (proto
&& *proto
)
5415 if (!(proto_str
= strdup_lower(proto
)))
5417 HeapFree( GetProcessHeap(), 0, name_str
);
5422 EnterCriticalSection( &csWSgetXXXbyYYY
);
5423 serv
= getservbyname(name_str
, proto_str
);
5426 retval
= WS_dup_se(serv
);
5428 else SetLastError(WSANO_DATA
);
5429 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5430 HeapFree( GetProcessHeap(), 0, proto_str
);
5431 HeapFree( GetProcessHeap(), 0, name_str
);
5432 TRACE( "%s, %s ret %p\n", debugstr_a(name
), debugstr_a(proto
), retval
);
5436 /***********************************************************************
5437 * freeaddrinfo (WS2_32.@)
5439 void WINAPI
WS_freeaddrinfo(struct WS_addrinfo
*res
)
5442 struct WS_addrinfo
*next
;
5444 HeapFree(GetProcessHeap(),0,res
->ai_canonname
);
5445 HeapFree(GetProcessHeap(),0,res
->ai_addr
);
5446 next
= res
->ai_next
;
5447 HeapFree(GetProcessHeap(),0,res
);
5452 /* helper functions for getaddrinfo()/getnameinfo() */
5453 static int convert_aiflag_w2u(int winflags
) {
5457 for (i
=0;i
<sizeof(ws_aiflag_map
)/sizeof(ws_aiflag_map
[0]);i
++)
5458 if (ws_aiflag_map
[i
][0] & winflags
) {
5459 unixflags
|= ws_aiflag_map
[i
][1];
5460 winflags
&= ~ws_aiflag_map
[i
][0];
5463 FIXME("Unhandled windows AI_xxx flags %x\n", winflags
);
5467 static int convert_niflag_w2u(int winflags
) {
5471 for (i
=0;i
<sizeof(ws_niflag_map
)/sizeof(ws_niflag_map
[0]);i
++)
5472 if (ws_niflag_map
[i
][0] & winflags
) {
5473 unixflags
|= ws_niflag_map
[i
][1];
5474 winflags
&= ~ws_niflag_map
[i
][0];
5477 FIXME("Unhandled windows NI_xxx flags %x\n", winflags
);
5481 static int convert_aiflag_u2w(int unixflags
) {
5485 for (i
=0;i
<sizeof(ws_aiflag_map
)/sizeof(ws_aiflag_map
[0]);i
++)
5486 if (ws_aiflag_map
[i
][1] & unixflags
) {
5487 winflags
|= ws_aiflag_map
[i
][0];
5488 unixflags
&= ~ws_aiflag_map
[i
][1];
5490 if (unixflags
) /* will warn usually */
5491 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags
);
5495 static int convert_eai_u2w(int unixret
) {
5498 if (!unixret
) return 0;
5500 for (i
=0;ws_eai_map
[i
][0];i
++)
5501 if (ws_eai_map
[i
][1] == unixret
)
5502 return ws_eai_map
[i
][0];
5504 if (unixret
== EAI_SYSTEM
)
5505 /* There are broken versions of glibc which return EAI_SYSTEM
5506 * and set errno to 0 instead of returning EAI_NONAME.
5508 return errno
? sock_get_error( errno
) : WS_EAI_NONAME
;
5510 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret
);
5514 static char *get_hostname(void)
5519 GetComputerNameExA( ComputerNamePhysicalDnsHostname
, NULL
, &size
);
5520 if (GetLastError() != ERROR_MORE_DATA
) return NULL
;
5521 if (!(ret
= HeapAlloc( GetProcessHeap(), 0, size
))) return NULL
;
5522 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname
, ret
, &size
))
5524 HeapFree( GetProcessHeap(), 0, ret
);
5530 /***********************************************************************
5531 * getaddrinfo (WS2_32.@)
5533 int WINAPI
WS_getaddrinfo(LPCSTR nodename
, LPCSTR servname
, const struct WS_addrinfo
*hints
, struct WS_addrinfo
**res
)
5535 #ifdef HAVE_GETADDRINFO
5536 struct addrinfo
*unixaires
= NULL
;
5538 struct addrinfo unixhints
, *punixhints
= NULL
;
5539 char *hostname
= NULL
;
5543 if (!nodename
&& !servname
) return WSAHOST_NOT_FOUND
;
5547 else if (!nodename
[0])
5549 node
= hostname
= get_hostname();
5550 if (!node
) return WSA_NOT_ENOUGH_MEMORY
;
5555 /* servname tweak required by OSX and BSD kernels */
5556 if (servname
&& !servname
[0]) servname
= "0";
5559 punixhints
= &unixhints
;
5561 memset(&unixhints
, 0, sizeof(unixhints
));
5562 punixhints
->ai_flags
= convert_aiflag_w2u(hints
->ai_flags
);
5564 /* zero is a wildcard, no need to convert */
5565 if (hints
->ai_family
)
5566 punixhints
->ai_family
= convert_af_w2u(hints
->ai_family
);
5567 if (hints
->ai_socktype
)
5568 punixhints
->ai_socktype
= convert_socktype_w2u(hints
->ai_socktype
);
5569 if (hints
->ai_protocol
)
5570 punixhints
->ai_protocol
= max(convert_proto_w2u(hints
->ai_protocol
), 0);
5572 if (punixhints
->ai_socktype
< 0)
5574 WSASetLastError(WSAESOCKTNOSUPPORT
);
5575 HeapFree(GetProcessHeap(), 0, hostname
);
5576 return SOCKET_ERROR
;
5579 /* windows allows invalid combinations of socket type and protocol, unix does not.
5580 * fix the parameters here to make getaddrinfo call always work */
5581 if (punixhints
->ai_protocol
== IPPROTO_TCP
&&
5582 punixhints
->ai_socktype
!= SOCK_STREAM
&& punixhints
->ai_socktype
!= SOCK_SEQPACKET
)
5583 punixhints
->ai_socktype
= 0;
5585 else if (punixhints
->ai_protocol
== IPPROTO_UDP
&& punixhints
->ai_socktype
!= SOCK_DGRAM
)
5586 punixhints
->ai_socktype
= 0;
5588 else if (IS_IPX_PROTO(punixhints
->ai_protocol
) && punixhints
->ai_socktype
!= SOCK_DGRAM
)
5589 punixhints
->ai_socktype
= 0;
5592 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
5593 result
= getaddrinfo(node
, servname
, punixhints
, &unixaires
);
5595 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename
), debugstr_a(servname
), hints
, res
, result
);
5596 HeapFree(GetProcessHeap(), 0, hostname
);
5599 struct addrinfo
*xuai
= unixaires
;
5600 struct WS_addrinfo
**xai
= res
;
5604 struct WS_addrinfo
*ai
= HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY
, sizeof(struct WS_addrinfo
));
5610 *xai
= ai
;xai
= &ai
->ai_next
;
5611 ai
->ai_flags
= convert_aiflag_u2w(xuai
->ai_flags
);
5612 ai
->ai_family
= convert_af_u2w(xuai
->ai_family
);
5613 /* copy whatever was sent in the hints */
5615 ai
->ai_socktype
= hints
->ai_socktype
;
5616 ai
->ai_protocol
= hints
->ai_protocol
;
5618 ai
->ai_socktype
= convert_socktype_u2w(xuai
->ai_socktype
);
5619 ai
->ai_protocol
= convert_proto_u2w(xuai
->ai_protocol
);
5621 if (xuai
->ai_canonname
) {
5622 TRACE("canon name - %s\n",debugstr_a(xuai
->ai_canonname
));
5623 ai
->ai_canonname
= HeapAlloc(GetProcessHeap(),0,strlen(xuai
->ai_canonname
)+1);
5624 if (!ai
->ai_canonname
)
5626 strcpy(ai
->ai_canonname
,xuai
->ai_canonname
);
5628 len
= xuai
->ai_addrlen
;
5629 ai
->ai_addr
= HeapAlloc(GetProcessHeap(),0,len
);
5632 ai
->ai_addrlen
= len
;
5634 int winlen
= ai
->ai_addrlen
;
5636 if (!ws_sockaddr_u2ws(xuai
->ai_addr
, ai
->ai_addr
, &winlen
)) {
5637 ai
->ai_addrlen
= winlen
;
5641 ai
->ai_addr
= HeapReAlloc(GetProcessHeap(),0,ai
->ai_addr
,len
);
5644 ai
->ai_addrlen
= len
;
5646 xuai
= xuai
->ai_next
;
5648 freeaddrinfo(unixaires
);
5650 if (TRACE_ON(winsock
))
5652 struct WS_addrinfo
*ai
= *res
;
5655 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
5656 ai
, ai
->ai_flags
, ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
, ai
->ai_addrlen
,
5657 ai
->ai_canonname
, debugstr_sockaddr(ai
->ai_addr
));
5662 result
= convert_eai_u2w(result
);
5667 if (*res
) WS_freeaddrinfo(*res
);
5668 if (unixaires
) freeaddrinfo(unixaires
);
5669 return WSA_NOT_ENOUGH_MEMORY
;
5671 FIXME("getaddrinfo() failed, not found during buildtime.\n");
5676 static struct WS_addrinfoW
*addrinfo_AtoW(const struct WS_addrinfo
*ai
)
5678 struct WS_addrinfoW
*ret
;
5680 if (!(ret
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW
)))) return NULL
;
5681 ret
->ai_flags
= ai
->ai_flags
;
5682 ret
->ai_family
= ai
->ai_family
;
5683 ret
->ai_socktype
= ai
->ai_socktype
;
5684 ret
->ai_protocol
= ai
->ai_protocol
;
5685 ret
->ai_addrlen
= ai
->ai_addrlen
;
5686 ret
->ai_canonname
= NULL
;
5687 ret
->ai_addr
= NULL
;
5688 ret
->ai_next
= NULL
;
5689 if (ai
->ai_canonname
)
5691 int len
= MultiByteToWideChar(CP_ACP
, 0, ai
->ai_canonname
, -1, NULL
, 0);
5692 if (!(ret
->ai_canonname
= HeapAlloc(GetProcessHeap(), 0, len
)))
5694 HeapFree(GetProcessHeap(), 0, ret
);
5697 MultiByteToWideChar(CP_ACP
, 0, ai
->ai_canonname
, -1, ret
->ai_canonname
, len
);
5701 if (!(ret
->ai_addr
= HeapAlloc(GetProcessHeap(), 0, ai
->ai_addrlen
)))
5703 HeapFree(GetProcessHeap(), 0, ret
->ai_canonname
);
5704 HeapFree(GetProcessHeap(), 0, ret
);
5707 memcpy(ret
->ai_addr
, ai
->ai_addr
, ai
->ai_addrlen
);
5712 static struct WS_addrinfoW
*addrinfo_list_AtoW(const struct WS_addrinfo
*info
)
5714 struct WS_addrinfoW
*ret
, *infoW
;
5716 if (!(ret
= infoW
= addrinfo_AtoW(info
))) return NULL
;
5717 while (info
->ai_next
)
5719 if (!(infoW
->ai_next
= addrinfo_AtoW(info
->ai_next
)))
5724 infoW
= infoW
->ai_next
;
5725 info
= info
->ai_next
;
5730 static struct WS_addrinfo
*addrinfo_WtoA(const struct WS_addrinfoW
*ai
)
5732 struct WS_addrinfo
*ret
;
5734 if (!(ret
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo
)))) return NULL
;
5735 ret
->ai_flags
= ai
->ai_flags
;
5736 ret
->ai_family
= ai
->ai_family
;
5737 ret
->ai_socktype
= ai
->ai_socktype
;
5738 ret
->ai_protocol
= ai
->ai_protocol
;
5739 ret
->ai_addrlen
= ai
->ai_addrlen
;
5740 ret
->ai_canonname
= NULL
;
5741 ret
->ai_addr
= NULL
;
5742 ret
->ai_next
= NULL
;
5743 if (ai
->ai_canonname
)
5745 int len
= WideCharToMultiByte(CP_ACP
, 0, ai
->ai_canonname
, -1, NULL
, 0, NULL
, NULL
);
5746 if (!(ret
->ai_canonname
= HeapAlloc(GetProcessHeap(), 0, len
)))
5748 HeapFree(GetProcessHeap(), 0, ret
);
5751 WideCharToMultiByte(CP_ACP
, 0, ai
->ai_canonname
, -1, ret
->ai_canonname
, len
, NULL
, NULL
);
5755 if (!(ret
->ai_addr
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr
))))
5757 HeapFree(GetProcessHeap(), 0, ret
->ai_canonname
);
5758 HeapFree(GetProcessHeap(), 0, ret
);
5761 memcpy(ret
->ai_addr
, ai
->ai_addr
, sizeof(struct WS_sockaddr
));
5766 /***********************************************************************
5767 * GetAddrInfoW (WS2_32.@)
5769 int WINAPI
GetAddrInfoW(LPCWSTR nodename
, LPCWSTR servname
, const ADDRINFOW
*hints
, PADDRINFOW
*res
)
5772 char *nodenameA
= NULL
, *servnameA
= NULL
;
5773 struct WS_addrinfo
*resA
, *hintsA
= NULL
;
5778 len
= WideCharToMultiByte(CP_ACP
, 0, nodename
, -1, NULL
, 0, NULL
, NULL
);
5779 if (!(nodenameA
= HeapAlloc(GetProcessHeap(), 0, len
))) return EAI_MEMORY
;
5780 WideCharToMultiByte(CP_ACP
, 0, nodename
, -1, nodenameA
, len
, NULL
, NULL
);
5784 len
= WideCharToMultiByte(CP_ACP
, 0, servname
, -1, NULL
, 0, NULL
, NULL
);
5785 if (!(servnameA
= HeapAlloc(GetProcessHeap(), 0, len
)))
5787 HeapFree(GetProcessHeap(), 0, nodenameA
);
5790 WideCharToMultiByte(CP_ACP
, 0, servname
, -1, servnameA
, len
, NULL
, NULL
);
5793 if (hints
) hintsA
= addrinfo_WtoA(hints
);
5794 ret
= WS_getaddrinfo(nodenameA
, servnameA
, hintsA
, &resA
);
5795 WS_freeaddrinfo(hintsA
);
5799 *res
= addrinfo_list_AtoW(resA
);
5800 WS_freeaddrinfo(resA
);
5803 HeapFree(GetProcessHeap(), 0, nodenameA
);
5804 HeapFree(GetProcessHeap(), 0, servnameA
);
5808 /***********************************************************************
5809 * FreeAddrInfoW (WS2_32.@)
5811 void WINAPI
FreeAddrInfoW(PADDRINFOW ai
)
5816 HeapFree(GetProcessHeap(), 0, ai
->ai_canonname
);
5817 HeapFree(GetProcessHeap(), 0, ai
->ai_addr
);
5819 HeapFree(GetProcessHeap(), 0, ai
);
5824 int WINAPI
WS_getnameinfo(const SOCKADDR
*sa
, WS_socklen_t salen
, PCHAR host
,
5825 DWORD hostlen
, PCHAR serv
, DWORD servlen
, INT flags
)
5827 #ifdef HAVE_GETNAMEINFO
5829 union generic_unix_sockaddr sa_u
;
5832 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa
), salen
, host
, hostlen
,
5833 serv
, servlen
, flags
);
5835 size
= ws_sockaddr_ws2u(sa
, salen
, &sa_u
);
5838 WSASetLastError(WSAEFAULT
);
5839 return WSA_NOT_ENOUGH_MEMORY
;
5841 ret
= getnameinfo(&sa_u
.addr
, size
, host
, hostlen
, serv
, servlen
, convert_niflag_w2u(flags
));
5842 return convert_eai_u2w(ret
);
5844 FIXME("getnameinfo() failed, not found during buildtime.\n");
5849 int WINAPI
GetNameInfoW(const SOCKADDR
*sa
, WS_socklen_t salen
, PWCHAR host
,
5850 DWORD hostlen
, PWCHAR serv
, DWORD servlen
, INT flags
)
5853 char *hostA
= NULL
, *servA
= NULL
;
5855 if (host
&& (!(hostA
= HeapAlloc(GetProcessHeap(), 0, hostlen
)))) return EAI_MEMORY
;
5856 if (serv
&& (!(servA
= HeapAlloc(GetProcessHeap(), 0, servlen
))))
5858 HeapFree(GetProcessHeap(), 0, hostA
);
5862 ret
= WS_getnameinfo(sa
, salen
, hostA
, hostlen
, servA
, servlen
, flags
);
5865 if (host
) MultiByteToWideChar(CP_ACP
, 0, hostA
, -1, host
, hostlen
);
5866 if (serv
) MultiByteToWideChar(CP_ACP
, 0, servA
, -1, serv
, servlen
);
5869 HeapFree(GetProcessHeap(), 0, hostA
);
5870 HeapFree(GetProcessHeap(), 0, servA
);
5874 /***********************************************************************
5875 * getservbyport (WS2_32.56)
5877 struct WS_servent
* WINAPI
WS_getservbyport(int port
, const char *proto
)
5879 struct WS_servent
* retval
= NULL
;
5880 #ifdef HAVE_GETSERVBYPORT
5881 struct servent
* serv
;
5882 char *proto_str
= NULL
;
5884 if (proto
&& *proto
)
5886 if (!(proto_str
= strdup_lower(proto
))) return NULL
;
5888 EnterCriticalSection( &csWSgetXXXbyYYY
);
5889 if( (serv
= getservbyport(port
, proto_str
)) != NULL
) {
5890 retval
= WS_dup_se(serv
);
5892 else SetLastError(WSANO_DATA
);
5893 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5894 HeapFree( GetProcessHeap(), 0, proto_str
);
5896 TRACE("%d (i.e. port %d), %s ret %p\n", port
, (int)ntohl(port
), debugstr_a(proto
), retval
);
5901 /***********************************************************************
5902 * gethostname (WS2_32.57)
5904 int WINAPI
WS_gethostname(char *name
, int namelen
)
5906 TRACE("name %p, len %d\n", name
, namelen
);
5908 if (gethostname(name
, namelen
) == 0)
5910 TRACE("<- '%s'\n", name
);
5913 SetLastError((errno
== EINVAL
) ? WSAEFAULT
: wsaErrno());
5914 TRACE("<- ERROR !\n");
5915 return SOCKET_ERROR
;
5919 /* ------------------------------------- Windows sockets extensions -- *
5921 * ------------------------------------------------------------------- */
5923 /***********************************************************************
5924 * WSAEnumNetworkEvents (WS2_32.36)
5926 int WINAPI
WSAEnumNetworkEvents(SOCKET s
, WSAEVENT hEvent
, LPWSANETWORKEVENTS lpEvent
)
5930 int errors
[FD_MAX_EVENTS
];
5932 TRACE("%08lx, hEvent %p, lpEvent %p\n", s
, hEvent
, lpEvent
);
5934 SERVER_START_REQ( get_socket_event
)
5936 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
5937 req
->service
= TRUE
;
5938 req
->c_event
= wine_server_obj_handle( hEvent
);
5939 wine_server_set_reply( req
, errors
, sizeof(errors
) );
5940 if (!(ret
= wine_server_call(req
))) lpEvent
->lNetworkEvents
= reply
->pmask
& reply
->mask
;
5945 for (i
= 0; i
< FD_MAX_EVENTS
; i
++)
5946 lpEvent
->iErrorCode
[i
] = NtStatusToWSAError(errors
[i
]);
5949 SetLastError(WSAEINVAL
);
5950 return SOCKET_ERROR
;
5953 /***********************************************************************
5954 * WSAEventSelect (WS2_32.39)
5956 int WINAPI
WSAEventSelect(SOCKET s
, WSAEVENT hEvent
, LONG lEvent
)
5960 TRACE("%08lx, hEvent %p, event %08x\n", s
, hEvent
, lEvent
);
5962 SERVER_START_REQ( set_socket_event
)
5964 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
5966 req
->event
= wine_server_obj_handle( hEvent
);
5969 ret
= wine_server_call( req
);
5973 SetLastError(WSAEINVAL
);
5974 return SOCKET_ERROR
;
5977 /**********************************************************************
5978 * WSAGetOverlappedResult (WS2_32.40)
5980 BOOL WINAPI
WSAGetOverlappedResult( SOCKET s
, LPWSAOVERLAPPED lpOverlapped
,
5981 LPDWORD lpcbTransfer
, BOOL fWait
,
5986 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
5987 s
, lpOverlapped
, lpcbTransfer
, fWait
, lpdwFlags
);
5989 if ( lpOverlapped
== NULL
)
5991 ERR( "Invalid pointer\n" );
5992 WSASetLastError(WSA_INVALID_PARAMETER
);
5996 status
= lpOverlapped
->Internal
;
5997 if (status
== STATUS_PENDING
)
6001 SetLastError( WSA_IO_INCOMPLETE
);
6005 if (WaitForSingleObject( lpOverlapped
->hEvent
? lpOverlapped
->hEvent
: SOCKET2HANDLE(s
),
6006 INFINITE
) == WAIT_FAILED
)
6008 status
= lpOverlapped
->Internal
;
6012 *lpcbTransfer
= lpOverlapped
->InternalHigh
;
6015 *lpdwFlags
= lpOverlapped
->u
.s
.Offset
;
6017 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
6022 /***********************************************************************
6023 * WSAAsyncSelect (WS2_32.101)
6025 INT WINAPI
WSAAsyncSelect(SOCKET s
, HWND hWnd
, UINT uMsg
, LONG lEvent
)
6029 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s
, hWnd
, uMsg
, lEvent
);
6031 SERVER_START_REQ( set_socket_event
)
6033 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
6036 req
->window
= wine_server_user_handle( hWnd
);
6038 ret
= wine_server_call( req
);
6042 SetLastError(WSAEINVAL
);
6043 return SOCKET_ERROR
;
6046 /***********************************************************************
6047 * WSACreateEvent (WS2_32.31)
6050 WSAEVENT WINAPI
WSACreateEvent(void)
6052 /* Create a manual-reset event, with initial state: unsignaled */
6055 return CreateEventW(NULL
, TRUE
, FALSE
, NULL
);
6058 /***********************************************************************
6059 * WSACloseEvent (WS2_32.29)
6062 BOOL WINAPI
WSACloseEvent(WSAEVENT event
)
6064 TRACE ("event=%p\n", event
);
6066 return CloseHandle(event
);
6069 /***********************************************************************
6070 * WSASocketA (WS2_32.78)
6073 SOCKET WINAPI
WSASocketA(int af
, int type
, int protocol
,
6074 LPWSAPROTOCOL_INFOA lpProtocolInfo
,
6075 GROUP g
, DWORD dwFlags
)
6078 WSAPROTOCOL_INFOW info
;
6080 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6081 af
, type
, protocol
, lpProtocolInfo
, g
, dwFlags
);
6083 if (!lpProtocolInfo
) return WSASocketW(af
, type
, protocol
, NULL
, g
, dwFlags
);
6085 memcpy(&info
, lpProtocolInfo
, FIELD_OFFSET(WSAPROTOCOL_INFOW
, szProtocol
));
6086 len
= MultiByteToWideChar(CP_ACP
, 0, lpProtocolInfo
->szProtocol
, -1,
6087 info
.szProtocol
, WSAPROTOCOL_LEN
+ 1);
6091 WSASetLastError( WSAEINVAL
);
6092 return SOCKET_ERROR
;
6095 return WSASocketW(af
, type
, protocol
, &info
, g
, dwFlags
);
6098 /***********************************************************************
6099 * WSASocketW (WS2_32.79)
6102 SOCKET WINAPI
WSASocketW(int af
, int type
, int protocol
,
6103 LPWSAPROTOCOL_INFOW lpProtocolInfo
,
6104 GROUP g
, DWORD dwFlags
)
6108 int unixaf
, unixtype
, ipxptype
= -1;
6111 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
6112 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
6115 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6116 af
, type
, protocol
, lpProtocolInfo
, g
, dwFlags
);
6120 err
= WSANOTINITIALISED
;
6124 /* hack for WSADuplicateSocket */
6125 if (lpProtocolInfo
&& lpProtocolInfo
->dwServiceFlags4
== 0xff00ff00) {
6126 ret
= lpProtocolInfo
->dwServiceFlags3
;
6127 TRACE("\tgot duplicate %04lx\n", ret
);
6133 if (af
== FROM_PROTOCOL_INFO
|| !af
)
6134 af
= lpProtocolInfo
->iAddressFamily
;
6135 if (type
== FROM_PROTOCOL_INFO
|| !type
)
6136 type
= lpProtocolInfo
->iSocketType
;
6137 if (protocol
== FROM_PROTOCOL_INFO
|| !protocol
)
6138 protocol
= lpProtocolInfo
->iProtocol
;
6141 if (!type
&& (af
|| protocol
))
6143 int autoproto
= protocol
;
6144 WSAPROTOCOL_INFOW infow
;
6146 /* default to the first valid protocol */
6148 autoproto
= valid_protocols
[0];
6149 else if(IS_IPX_PROTO(autoproto
))
6150 autoproto
= WS_NSPROTO_IPX
;
6152 if (WS_EnterSingleProtocolW(autoproto
, &infow
))
6154 type
= infow
.iSocketType
;
6156 /* after win2003 it's no longer possible to pass AF_UNSPEC
6157 using the protocol info struct */
6158 if (!lpProtocolInfo
&& af
== WS_AF_UNSPEC
)
6159 af
= infow
.iAddressFamily
;
6164 Windows has an extension to the IPX protocol that allows one to create sockets
6165 and set the IPX packet type at the same time, to do that a caller will use
6166 a protocol like NSPROTO_IPX + <PACKET TYPE>
6168 if (IS_IPX_PROTO(protocol
))
6169 ipxptype
= protocol
- WS_NSPROTO_IPX
;
6171 /* convert the socket family, type and protocol */
6172 unixaf
= convert_af_w2u(af
);
6173 unixtype
= convert_socktype_w2u(type
);
6174 protocol
= convert_proto_w2u(protocol
);
6175 if (unixaf
== AF_UNSPEC
) unixaf
= -1;
6177 /* filter invalid parameters */
6180 /* the type could not be converted */
6181 if (type
&& unixtype
< 0)
6183 err
= WSAESOCKTNOSUPPORT
;
6187 err
= WSAEPROTONOSUPPORT
;
6192 /* both family and protocol can't be invalid */
6199 /* family could not be converted and neither socket type */
6200 if (unixtype
< 0 && af
>= 0)
6203 err
= WSAESOCKTNOSUPPORT
;
6207 err
= WSAEAFNOSUPPORT
;
6211 SERVER_START_REQ( create_socket
)
6213 req
->family
= unixaf
;
6214 req
->type
= unixtype
;
6215 req
->protocol
= protocol
;
6216 req
->access
= GENERIC_READ
|GENERIC_WRITE
|SYNCHRONIZE
;
6217 req
->attributes
= OBJ_INHERIT
;
6218 req
->flags
= dwFlags
;
6219 set_error( wine_server_call( req
) );
6220 ret
= HANDLE2SOCKET( wine_server_ptr_handle( reply
->handle
));
6225 TRACE("\tcreated %04lx\n", ret
);
6227 set_ipx_packettype(ret
, ipxptype
);
6231 err
= GetLastError();
6232 if (err
== WSAEACCES
) /* raw socket denied */
6234 if (type
== SOCK_RAW
)
6235 ERR_(winediag
)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
6237 ERR_(winediag
)("Failed to create socket, this requires special permissions.\n");
6241 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
6242 if (err
== WSAEINVAL
)
6243 err
= WSAESOCKTNOSUPPORT
;
6244 else if (err
== WSAEOPNOTSUPP
)
6245 err
= WSAEPROTONOSUPPORT
;
6249 WARN("\t\tfailed, error %d!\n", err
);
6251 return INVALID_SOCKET
;
6254 /***********************************************************************
6255 * WSAJoinLeaf (WS2_32.58)
6258 SOCKET WINAPI
WSAJoinLeaf(
6260 const struct WS_sockaddr
*addr
,
6262 LPWSABUF lpCallerData
,
6263 LPWSABUF lpCalleeData
,
6269 return INVALID_SOCKET
;
6272 /***********************************************************************
6273 * __WSAFDIsSet (WS2_32.151)
6275 int WINAPI
__WSAFDIsSet(SOCKET s
, WS_fd_set
*set
)
6277 int i
= set
->fd_count
;
6279 TRACE("(%ld,%p(%i))\n", s
, set
, i
);
6282 if (set
->fd_array
[i
] == s
) return 1;
6286 /***********************************************************************
6287 * WSAIsBlocking (WS2_32.114)
6289 BOOL WINAPI
WSAIsBlocking(void)
6291 /* By default WinSock should set all its sockets to non-blocking mode
6292 * and poll in PeekMessage loop when processing "blocking" ones. This
6293 * function is supposed to tell if the program is in this loop. Our
6294 * blocking calls are truly blocking so we always return FALSE.
6296 * Note: It is allowed to call this function without prior WSAStartup().
6303 /***********************************************************************
6304 * WSACancelBlockingCall (WS2_32.113)
6306 INT WINAPI
WSACancelBlockingCall(void)
6312 static INT WINAPI
WSA_DefaultBlockingHook( FARPROC x
)
6314 FIXME("How was this called?\n");
6319 /***********************************************************************
6320 * WSASetBlockingHook (WS2_32.109)
6322 FARPROC WINAPI
WSASetBlockingHook(FARPROC lpBlockFunc
)
6324 FARPROC prev
= blocking_hook
;
6325 blocking_hook
= lpBlockFunc
;
6326 TRACE("hook %p\n", lpBlockFunc
);
6331 /***********************************************************************
6332 * WSAUnhookBlockingHook (WS2_32.110)
6334 INT WINAPI
WSAUnhookBlockingHook(void)
6336 blocking_hook
= (FARPROC
)WSA_DefaultBlockingHook
;
6341 /* ----------------------------------- end of API stuff */
6343 /* ----------------------------------- helper functions -
6345 * TODO: Merge WS_dup_..() stuff into one function that
6346 * would operate with a generic structure containing internal
6347 * pointers (via a template of some kind).
6350 static int list_size(char** l
, int item_size
)
6355 j
+= (item_size
) ? item_size
: strlen(l
[i
]) + 1;
6356 j
+= (i
+ 1) * sizeof(char*); }
6360 static int list_dup(char** l_src
, char** l_to
, int item_size
)
6365 for (i
= 0; l_src
[i
]; i
++) ;
6366 p
= (char *)(l_to
+ i
+ 1);
6367 for (i
= 0; l_src
[i
]; i
++)
6369 int count
= ( item_size
) ? item_size
: strlen(l_src
[i
]) + 1;
6370 memcpy(p
, l_src
[i
], count
);
6375 return p
- (char *)l_to
;
6380 /* create a hostent entry
6382 * Creates the entry with enough memory for the name, aliases
6383 * addresses, and the address pointers. Also copies the name
6384 * and sets up all the pointers.
6386 * NOTE: The alias and address lists must be allocated with room
6387 * for the NULL item terminating the list. This is true even if
6388 * the list has no items ("aliases" and "addresses" must be
6389 * at least "1", a truly empty list is invalid).
6391 static struct WS_hostent
*WS_create_he(char *name
, int aliases
, int aliases_size
, int addresses
, int address_length
)
6393 struct WS_hostent
*p_to
;
6395 int size
= (sizeof(struct WS_hostent
) +
6397 sizeof(char *) * aliases
+
6399 sizeof(char *) * addresses
+
6400 address_length
* (addresses
- 1)), i
;
6402 if (!(p_to
= check_buffer_he(size
))) return NULL
;
6403 memset(p_to
, 0, size
);
6405 /* Use the memory in the same way winsock does.
6406 * First set the pointer for aliases, second set the pointers for addresses.
6407 * Third fill the addresses indexes, fourth jump aliases names size.
6408 * Fifth fill the hostname.
6409 * NOTE: This method is valid for OS version's >= XP.
6411 p
= (char *)(p_to
+ 1);
6412 p_to
->h_aliases
= (char **)p
;
6413 p
+= sizeof(char *)*aliases
;
6415 p_to
->h_addr_list
= (char **)p
;
6416 p
+= sizeof(char *)*addresses
;
6418 for (i
= 0, addresses
--; i
< addresses
; i
++, p
+= address_length
)
6419 p_to
->h_addr_list
[i
] = p
;
6421 /* NOTE: h_aliases must be filled in manually because we don't know each string
6422 * size, leave these pointers NULL (already set to NULL by memset earlier).
6432 /* duplicate hostent entry
6433 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
6434 * Ditto for protoent and servent.
6436 static struct WS_hostent
*WS_dup_he(const struct hostent
* p_he
)
6438 int i
, addresses
= 0, alias_size
= 0;
6439 struct WS_hostent
*p_to
;
6442 for( i
= 0; p_he
->h_aliases
[i
]; i
++) alias_size
+= strlen(p_he
->h_aliases
[i
]) + 1;
6443 while (p_he
->h_addr_list
[addresses
]) addresses
++;
6445 p_to
= WS_create_he(p_he
->h_name
, i
+ 1, alias_size
, addresses
+ 1, p_he
->h_length
);
6447 if (!p_to
) return NULL
;
6448 p_to
->h_addrtype
= convert_af_u2w(p_he
->h_addrtype
);
6449 p_to
->h_length
= p_he
->h_length
;
6451 for(i
= 0, p
= p_to
->h_addr_list
[0]; p_he
->h_addr_list
[i
]; i
++, p
+= p_to
->h_length
)
6452 memcpy(p
, p_he
->h_addr_list
[i
], p_to
->h_length
);
6454 /* Fill the aliases after the IP data */
6455 for(i
= 0; p_he
->h_aliases
[i
]; i
++)
6457 p_to
->h_aliases
[i
] = p
;
6458 strcpy(p
, p_he
->h_aliases
[i
]);
6465 /* ----- protoent */
6467 static struct WS_protoent
*WS_dup_pe(const struct protoent
* p_pe
)
6470 struct WS_protoent
*p_to
;
6472 int size
= (sizeof(*p_pe
) +
6473 strlen(p_pe
->p_name
) + 1 +
6474 list_size(p_pe
->p_aliases
, 0));
6476 if (!(p_to
= check_buffer_pe(size
))) return NULL
;
6477 p_to
->p_proto
= p_pe
->p_proto
;
6479 p
= (char *)(p_to
+ 1);
6481 strcpy(p
, p_pe
->p_name
);
6484 p_to
->p_aliases
= (char **)p
;
6485 list_dup(p_pe
->p_aliases
, p_to
->p_aliases
, 0);
6491 static struct WS_servent
*WS_dup_se(const struct servent
* p_se
)
6494 struct WS_servent
*p_to
;
6496 int size
= (sizeof(*p_se
) +
6497 strlen(p_se
->s_proto
) + 1 +
6498 strlen(p_se
->s_name
) + 1 +
6499 list_size(p_se
->s_aliases
, 0));
6501 if (!(p_to
= check_buffer_se(size
))) return NULL
;
6502 p_to
->s_port
= p_se
->s_port
;
6504 p
= (char *)(p_to
+ 1);
6506 strcpy(p
, p_se
->s_name
);
6510 strcpy(p
, p_se
->s_proto
);
6513 p_to
->s_aliases
= (char **)p
;
6514 list_dup(p_se
->s_aliases
, p_to
->s_aliases
, 0);
6519 /***********************************************************************
6520 * WSARecv (WS2_32.67)
6522 int WINAPI
WSARecv(SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
6523 LPDWORD NumberOfBytesReceived
, LPDWORD lpFlags
,
6524 LPWSAOVERLAPPED lpOverlapped
,
6525 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
6527 return WS2_recv_base(s
, lpBuffers
, dwBufferCount
, NumberOfBytesReceived
, lpFlags
,
6528 NULL
, NULL
, lpOverlapped
, lpCompletionRoutine
, NULL
);
6531 static int WS2_recv_base( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
6532 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
,
6533 struct WS_sockaddr
*lpFrom
,
6534 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
6535 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
,
6536 LPWSABUF lpControlBuffer
)
6538 unsigned int i
, options
;
6539 int n
, fd
, err
, overlapped
;
6540 struct ws2_async
*wsa
, localwsa
;
6542 DWORD timeout_start
= GetTickCount();
6543 ULONG_PTR cvalue
= (lpOverlapped
&& ((ULONG_PTR
)lpOverlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)lpOverlapped
: 0;
6545 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
6546 s
, lpBuffers
, dwBufferCount
, *lpFlags
, lpFrom
,
6547 (lpFromlen
? *lpFromlen
: -1),
6548 lpOverlapped
, lpCompletionRoutine
);
6550 fd
= get_sock_fd( s
, FILE_READ_DATA
, &options
);
6551 TRACE( "fd=%d, options=%x\n", fd
, options
);
6553 if (fd
== -1) return SOCKET_ERROR
;
6555 overlapped
= (lpOverlapped
|| lpCompletionRoutine
) &&
6556 !(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
));
6557 if (overlapped
|| dwBufferCount
> 1)
6559 if (!(wsa
= HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async
, iovec
[dwBufferCount
]) )))
6568 wsa
->hSocket
= SOCKET2HANDLE(s
);
6569 wsa
->flags
= *lpFlags
;
6570 wsa
->lpFlags
= lpFlags
;
6572 wsa
->addrlen
.ptr
= lpFromlen
;
6573 wsa
->control
= lpControlBuffer
;
6574 wsa
->n_iovecs
= dwBufferCount
;
6575 wsa
->first_iovec
= 0;
6576 for (i
= 0; i
< dwBufferCount
; i
++)
6578 /* check buffer first to trigger write watches */
6579 if (IsBadWritePtr( lpBuffers
[i
].buf
, lpBuffers
[i
].len
))
6584 wsa
->iovec
[i
].iov_base
= lpBuffers
[i
].buf
;
6585 wsa
->iovec
[i
].iov_len
= lpBuffers
[i
].len
;
6590 n
= WS2_recv( fd
, wsa
);
6593 if (errno
!= EAGAIN
)
6595 int loc_errno
= errno
;
6597 if (cvalue
) WS_AddCompletion( s
, cvalue
, sock_get_ntstatus(loc_errno
), 0 );
6601 else if (lpNumberOfBytesRecvd
) *lpNumberOfBytesRecvd
= n
;
6605 IO_STATUS_BLOCK
*iosb
= lpOverlapped
? (IO_STATUS_BLOCK
*)lpOverlapped
: &wsa
->local_iosb
;
6607 wsa
->user_overlapped
= lpOverlapped
;
6608 wsa
->completion_func
= lpCompletionRoutine
;
6609 release_sock_fd( s
, fd
);
6613 iosb
->u
.Status
= STATUS_PENDING
;
6614 iosb
->Information
= 0;
6616 SERVER_START_REQ( register_async
)
6618 req
->type
= ASYNC_TYPE_READ
;
6619 req
->async
.handle
= wine_server_obj_handle( wsa
->hSocket
);
6620 req
->async
.callback
= wine_server_client_ptr( WS2_async_recv
);
6621 req
->async
.iosb
= wine_server_client_ptr( iosb
);
6622 req
->async
.arg
= wine_server_client_ptr( wsa
);
6623 req
->async
.event
= wine_server_obj_handle( lpCompletionRoutine
? 0 : lpOverlapped
->hEvent
);
6624 req
->async
.cvalue
= cvalue
;
6625 err
= wine_server_call( req
);
6629 if (err
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
6630 WSASetLastError( NtStatusToWSAError( err
));
6631 return SOCKET_ERROR
;
6634 iosb
->u
.Status
= STATUS_SUCCESS
;
6635 iosb
->Information
= n
;
6636 if (!wsa
->completion_func
)
6638 if (cvalue
) WS_AddCompletion( s
, cvalue
, STATUS_SUCCESS
, n
);
6639 if (lpOverlapped
->hEvent
) SetEvent( lpOverlapped
->hEvent
);
6640 HeapFree( GetProcessHeap(), 0, wsa
);
6642 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC
)ws2_async_apc
,
6643 (ULONG_PTR
)wsa
, (ULONG_PTR
)iosb
, 0 );
6644 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
6650 if ((err
= _is_blocking( s
, &is_blocking
)))
6652 err
= NtStatusToWSAError( err
);
6659 int timeout
= GET_RCVTIMEO(fd
);
6662 timeout
-= GetTickCount() - timeout_start
;
6663 if (timeout
< 0) timeout
= 0;
6667 pfd
.events
= POLLIN
;
6668 if (*lpFlags
& WS_MSG_OOB
) pfd
.events
|= POLLPRI
;
6670 if (!timeout
|| !poll( &pfd
, 1, timeout
))
6673 /* a timeout is not fatal */
6674 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
6680 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
6681 err
= WSAEWOULDBLOCK
;
6686 TRACE(" -> %i bytes\n", n
);
6687 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
6688 release_sock_fd( s
, fd
);
6689 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
6694 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
6695 release_sock_fd( s
, fd
);
6696 WARN(" -> ERROR %d\n", err
);
6697 WSASetLastError( err
);
6698 return SOCKET_ERROR
;
6701 /***********************************************************************
6702 * WSARecvFrom (WS2_32.69)
6704 INT WINAPI
WSARecvFrom( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
6705 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
, struct WS_sockaddr
*lpFrom
,
6706 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
6707 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
6710 return WS2_recv_base( s
, lpBuffers
, dwBufferCount
,
6711 lpNumberOfBytesRecvd
, lpFlags
,
6713 lpOverlapped
, lpCompletionRoutine
, NULL
);
6716 /***********************************************************************
6717 * WSCInstallProvider (WS2_32.88)
6719 INT WINAPI
WSCInstallProvider( const LPGUID lpProviderId
,
6720 LPCWSTR lpszProviderDllPath
,
6721 const LPWSAPROTOCOL_INFOW lpProtocolInfoList
,
6722 DWORD dwNumberOfEntries
,
6725 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId
),
6726 debugstr_w(lpszProviderDllPath
), lpProtocolInfoList
,
6727 dwNumberOfEntries
, lpErrno
);
6733 /***********************************************************************
6734 * WSCDeinstallProvider (WS2_32.83)
6736 INT WINAPI
WSCDeinstallProvider(LPGUID lpProviderId
, LPINT lpErrno
)
6738 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId
), lpErrno
);
6744 /***********************************************************************
6745 * WSAAccept (WS2_32.26)
6747 SOCKET WINAPI
WSAAccept( SOCKET s
, struct WS_sockaddr
*addr
, LPINT addrlen
,
6748 LPCONDITIONPROC lpfnCondition
, DWORD_PTR dwCallbackData
)
6752 WSABUF CallerId
, CallerData
, CalleeId
, CalleeData
;
6753 /* QOS SQOS, GQOS; */
6756 SOCKADDR src_addr
, dst_addr
;
6758 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
6759 s
, addr
, addrlen
, lpfnCondition
, dwCallbackData
);
6761 cs
= WS_accept(s
, addr
, addrlen
);
6762 if (cs
== SOCKET_ERROR
) return SOCKET_ERROR
;
6763 if (!lpfnCondition
) return cs
;
6765 if (addr
&& addrlen
)
6767 CallerId
.buf
= (char *)addr
;
6768 CallerId
.len
= *addrlen
;
6772 size
= sizeof(src_addr
);
6773 WS_getpeername(cs
, &src_addr
, &size
);
6774 CallerId
.buf
= (char *)&src_addr
;
6775 CallerId
.len
= size
;
6777 CallerData
.buf
= NULL
;
6780 size
= sizeof(dst_addr
);
6781 WS_getsockname(cs
, &dst_addr
, &size
);
6783 CalleeId
.buf
= (char *)&dst_addr
;
6784 CalleeId
.len
= sizeof(dst_addr
);
6786 ret
= (*lpfnCondition
)(&CallerId
, &CallerData
, NULL
, NULL
,
6787 &CalleeId
, &CalleeData
, &g
, dwCallbackData
);
6794 SERVER_START_REQ( set_socket_deferred
)
6796 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
6797 req
->deferred
= wine_server_obj_handle( SOCKET2HANDLE(cs
) );
6798 if ( !wine_server_call_err ( req
) )
6800 SetLastError( WSATRY_AGAIN
);
6801 WS_closesocket( cs
);
6805 return SOCKET_ERROR
;
6808 SetLastError(WSAECONNREFUSED
);
6809 return SOCKET_ERROR
;
6811 FIXME("Unknown return type from Condition function\n");
6812 SetLastError(WSAENOTSOCK
);
6813 return SOCKET_ERROR
;
6817 /***********************************************************************
6818 * WSADuplicateSocketA (WS2_32.32)
6820 int WINAPI
WSADuplicateSocketA( SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOA lpProtocolInfo
)
6822 return WS_DuplicateSocket(FALSE
, s
, dwProcessId
, (LPWSAPROTOCOL_INFOW
) lpProtocolInfo
);
6825 /***********************************************************************
6826 * WSADuplicateSocketW (WS2_32.33)
6828 int WINAPI
WSADuplicateSocketW( SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOW lpProtocolInfo
)
6830 return WS_DuplicateSocket(TRUE
, s
, dwProcessId
, lpProtocolInfo
);
6833 /***********************************************************************
6834 * WSAInstallServiceClassA (WS2_32.48)
6836 int WINAPI
WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info
)
6838 FIXME("Request to install service %s\n",debugstr_a(info
->lpszServiceClassName
));
6839 WSASetLastError(WSAEACCES
);
6840 return SOCKET_ERROR
;
6843 /***********************************************************************
6844 * WSAInstallServiceClassW (WS2_32.49)
6846 int WINAPI
WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info
)
6848 FIXME("Request to install service %s\n",debugstr_w(info
->lpszServiceClassName
));
6849 WSASetLastError(WSAEACCES
);
6850 return SOCKET_ERROR
;
6853 /***********************************************************************
6854 * WSARemoveServiceClass (WS2_32.70)
6856 int WINAPI
WSARemoveServiceClass(LPGUID info
)
6858 FIXME("Request to remove service %p\n",info
);
6859 WSASetLastError(WSATYPE_NOT_FOUND
);
6860 return SOCKET_ERROR
;
6863 /***********************************************************************
6864 * inet_ntop (WS2_32.@)
6866 PCSTR WINAPI
WS_inet_ntop( INT family
, PVOID addr
, PSTR buffer
, SIZE_T len
)
6868 #ifdef HAVE_INET_NTOP
6869 struct WS_in6_addr
*in6
;
6870 struct WS_in_addr
*in
;
6873 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family
, addr
, buffer
, len
);
6876 WSASetLastError( STATUS_INVALID_PARAMETER
);
6885 pdst
= inet_ntop( AF_INET
, &in
->WS_s_addr
, buffer
, len
);
6891 pdst
= inet_ntop( AF_INET6
, in6
->WS_s6_addr
, buffer
, len
);
6895 WSASetLastError( WSAEAFNOSUPPORT
);
6899 if (!pdst
) WSASetLastError( STATUS_INVALID_PARAMETER
);
6902 FIXME( "not supported on this platform\n" );
6903 WSASetLastError( WSAEAFNOSUPPORT
);
6908 /***********************************************************************
6909 * WSAStringToAddressA (WS2_32.80)
6911 INT WINAPI
WSAStringToAddressA(LPSTR AddressString
,
6913 LPWSAPROTOCOL_INFOA lpProtocolInfo
,
6914 LPSOCKADDR lpAddress
,
6915 LPINT lpAddressLength
)
6918 LPSTR workBuffer
=NULL
,ptrPort
;
6920 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString
), AddressFamily
,
6921 lpProtocolInfo
, lpAddress
, lpAddressLength
);
6923 if (!lpAddressLength
|| !lpAddress
) return SOCKET_ERROR
;
6927 WSASetLastError(WSAEINVAL
);
6928 return SOCKET_ERROR
;
6932 FIXME("ProtocolInfo not implemented.\n");
6934 workBuffer
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
,
6935 strlen(AddressString
) + 1);
6938 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
6939 return SOCKET_ERROR
;
6942 strcpy(workBuffer
, AddressString
);
6944 switch(AddressFamily
)
6948 struct in_addr inetaddr
;
6950 /* If lpAddressLength is too small, tell caller the size we need */
6951 if (*lpAddressLength
< sizeof(SOCKADDR_IN
))
6953 *lpAddressLength
= sizeof(SOCKADDR_IN
);
6957 *lpAddressLength
= sizeof(SOCKADDR_IN
);
6958 memset(lpAddress
, 0, sizeof(SOCKADDR_IN
));
6960 ((LPSOCKADDR_IN
)lpAddress
)->sin_family
= WS_AF_INET
;
6962 ptrPort
= strchr(workBuffer
, ':');
6965 ((LPSOCKADDR_IN
)lpAddress
)->sin_port
= htons(atoi(ptrPort
+1));
6970 ((LPSOCKADDR_IN
)lpAddress
)->sin_port
= 0;
6973 if(inet_aton(workBuffer
, &inetaddr
) > 0)
6975 ((LPSOCKADDR_IN
)lpAddress
)->sin_addr
.WS_s_addr
= inetaddr
.s_addr
;
6986 struct in6_addr inetaddr
;
6987 /* If lpAddressLength is too small, tell caller the size we need */
6988 if (*lpAddressLength
< sizeof(SOCKADDR_IN6
))
6990 *lpAddressLength
= sizeof(SOCKADDR_IN6
);
6994 #ifdef HAVE_INET_PTON
6995 *lpAddressLength
= sizeof(SOCKADDR_IN6
);
6996 memset(lpAddress
, 0, sizeof(SOCKADDR_IN6
));
6998 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_family
= WS_AF_INET6
;
7000 /* This one is a bit tricky. An IPv6 address contains colons, so the
7001 * check from IPv4 doesn't work like that. However, IPv6 addresses that
7002 * contain a port are written with braces like [fd12:3456:7890::1]:12345
7003 * so what we will do is to look for ']', check if the next char is a
7004 * colon, and if it is, parse the port as in IPv4. */
7006 ptrPort
= strchr(workBuffer
, ']');
7007 if(ptrPort
&& *(++ptrPort
) == ':')
7009 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_port
= htons(atoi(ptrPort
+1));
7014 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_port
= 0;
7017 if(inet_pton(AF_INET6
, workBuffer
, &inetaddr
) > 0)
7019 memcpy(&((LPSOCKADDR_IN6
)lpAddress
)->sin6_addr
, &inetaddr
,
7020 sizeof(struct in6_addr
));
7024 #endif /* HAVE_INET_PTON */
7030 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
7031 TRACE("Unsupported address family specified: %d.\n", AddressFamily
);
7035 HeapFree(GetProcessHeap(), 0, workBuffer
);
7038 WSASetLastError(res
);
7039 return SOCKET_ERROR
;
7042 /***********************************************************************
7043 * WSAStringToAddressW (WS2_32.81)
7045 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
7046 * If this should be the case, it would be required to map these digits
7047 * to Unicode digits (0-9) using FoldString first.
7049 INT WINAPI
WSAStringToAddressW(LPWSTR AddressString
,
7051 LPWSAPROTOCOL_INFOW lpProtocolInfo
,
7052 LPSOCKADDR lpAddress
,
7053 LPINT lpAddressLength
)
7056 LPSTR workBuffer
=NULL
;
7057 WSAPROTOCOL_INFOA infoA
;
7058 LPWSAPROTOCOL_INFOA lpProtoInfoA
= NULL
;
7060 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString
), AddressFamily
, lpProtocolInfo
,
7061 lpAddress
, lpAddressLength
);
7063 if (!lpAddressLength
|| !lpAddress
) return SOCKET_ERROR
;
7065 /* if ProtocolInfo is available - convert to ANSI variant */
7068 lpProtoInfoA
= &infoA
;
7069 memcpy( lpProtoInfoA
, lpProtocolInfo
, FIELD_OFFSET( WSAPROTOCOL_INFOA
, szProtocol
) );
7071 if (!WideCharToMultiByte( CP_ACP
, 0, lpProtocolInfo
->szProtocol
, -1,
7072 lpProtoInfoA
->szProtocol
, WSAPROTOCOL_LEN
+1, NULL
, NULL
))
7074 WSASetLastError( WSAEINVAL
);
7075 return SOCKET_ERROR
;
7081 /* Translate AddressString to ANSI code page - assumes that only
7082 standard digits 0-9 are used with this API call */
7083 sBuffer
= WideCharToMultiByte( CP_ACP
, 0, AddressString
, -1, NULL
, 0, NULL
, NULL
);
7084 workBuffer
= HeapAlloc( GetProcessHeap(), 0, sBuffer
);
7088 WideCharToMultiByte( CP_ACP
, 0, AddressString
, -1, workBuffer
, sBuffer
, NULL
, NULL
);
7089 res
= WSAStringToAddressA(workBuffer
,AddressFamily
,lpProtoInfoA
,
7090 lpAddress
,lpAddressLength
);
7091 HeapFree( GetProcessHeap(), 0, workBuffer
);
7095 res
= WSA_NOT_ENOUGH_MEMORY
;
7100 WSASetLastError(res
);
7101 return SOCKET_ERROR
;
7104 /***********************************************************************
7105 * WSAAddressToStringA (WS2_32.27)
7107 * See WSAAddressToStringW
7109 INT WINAPI
WSAAddressToStringA( LPSOCKADDR sockaddr
, DWORD len
,
7110 LPWSAPROTOCOL_INFOA info
, LPSTR string
,
7114 CHAR buffer
[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7117 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr
, len
, info
, string
, lenstr
);
7119 if (!sockaddr
) return SOCKET_ERROR
;
7120 if (!string
|| !lenstr
) return SOCKET_ERROR
;
7122 switch(sockaddr
->sa_family
)
7125 if (len
< sizeof(SOCKADDR_IN
)) return SOCKET_ERROR
;
7126 sprintf( buffer
, "%u.%u.%u.%u:%u",
7127 (unsigned int)(ntohl( ((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
) >> 24 & 0xff),
7128 (unsigned int)(ntohl( ((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
) >> 16 & 0xff),
7129 (unsigned int)(ntohl( ((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
) >> 8 & 0xff),
7130 (unsigned int)(ntohl( ((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
) & 0xff),
7131 ntohs( ((SOCKADDR_IN
*)sockaddr
)->sin_port
) );
7133 p
= strchr( buffer
, ':' );
7134 if (!((SOCKADDR_IN
*)sockaddr
)->sin_port
) *p
= 0;
7139 struct WS_sockaddr_in6
*sockaddr6
= (LPSOCKADDR_IN6
) sockaddr
;
7142 if (len
< sizeof(SOCKADDR_IN6
)) return SOCKET_ERROR
;
7143 if ((sockaddr6
->sin6_port
))
7144 strcpy(buffer
, "[");
7145 if (!WS_inet_ntop(WS_AF_INET6
, &sockaddr6
->sin6_addr
, buffer
+strlen(buffer
), sizeof(buffer
)))
7147 WSASetLastError(WSAEINVAL
);
7148 return SOCKET_ERROR
;
7150 if ((sockaddr6
->sin6_scope_id
))
7151 sprintf(buffer
+strlen(buffer
), "%%%u", sockaddr6
->sin6_scope_id
);
7152 if ((sockaddr6
->sin6_port
))
7153 sprintf(buffer
+strlen(buffer
), "]:%u", ntohs(sockaddr6
->sin6_port
));
7158 WSASetLastError(WSAEINVAL
);
7159 return SOCKET_ERROR
;
7162 size
= strlen( buffer
) + 1;
7167 WSASetLastError(WSAEFAULT
);
7168 return SOCKET_ERROR
;
7171 TRACE("=> %s,%u bytes\n", debugstr_a(buffer
), size
);
7173 strcpy( string
, buffer
);
7177 /***********************************************************************
7178 * WSAAddressToStringW (WS2_32.28)
7180 * Convert a sockaddr address into a readable address string.
7183 * sockaddr [I] Pointer to a sockaddr structure.
7184 * len [I] Size of the sockaddr structure.
7185 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
7186 * string [I/O] Pointer to a buffer to receive the address string.
7187 * lenstr [I/O] Size of the receive buffer in WCHARs.
7191 * Failure: SOCKET_ERROR
7194 * The 'info' parameter is ignored.
7196 INT WINAPI
WSAAddressToStringW( LPSOCKADDR sockaddr
, DWORD len
,
7197 LPWSAPROTOCOL_INFOW info
, LPWSTR string
,
7202 WCHAR buffer
[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7205 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr
, len
, info
, string
, lenstr
);
7208 ret
= WSAAddressToStringA(sockaddr
, len
, NULL
, bufAddr
, &size
);
7210 if (ret
) return ret
;
7212 MultiByteToWideChar( CP_ACP
, 0, bufAddr
, size
, buffer
, sizeof( buffer
)/sizeof(WCHAR
));
7217 WSASetLastError(WSAEFAULT
);
7218 return SOCKET_ERROR
;
7221 TRACE("=> %s,%u bytes\n", debugstr_w(buffer
), size
);
7223 lstrcpyW( string
, buffer
);
7227 /***********************************************************************
7228 * WSAEnumNameSpaceProvidersA (WS2_32.34)
7230 INT WINAPI
WSAEnumNameSpaceProvidersA( LPDWORD len
, LPWSANAMESPACE_INFOA buffer
)
7232 FIXME( "(%p %p) Stub!\n", len
, buffer
);
7236 /***********************************************************************
7237 * WSAEnumNameSpaceProvidersW (WS2_32.35)
7239 INT WINAPI
WSAEnumNameSpaceProvidersW( LPDWORD len
, LPWSANAMESPACE_INFOW buffer
)
7241 FIXME( "(%p %p) Stub!\n", len
, buffer
);
7245 /***********************************************************************
7246 * WSAGetQOSByName (WS2_32.41)
7248 BOOL WINAPI
WSAGetQOSByName( SOCKET s
, LPWSABUF lpQOSName
, LPQOS lpQOS
)
7250 FIXME( "(0x%04lx %p %p) Stub!\n", s
, lpQOSName
, lpQOS
);
7254 /***********************************************************************
7255 * WSAGetServiceClassInfoA (WS2_32.42)
7257 INT WINAPI
WSAGetServiceClassInfoA( LPGUID provider
, LPGUID service
, LPDWORD len
,
7258 LPWSASERVICECLASSINFOA info
)
7260 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider
), debugstr_guid(service
),
7262 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
7263 return SOCKET_ERROR
;
7266 /***********************************************************************
7267 * WSAGetServiceClassInfoW (WS2_32.43)
7269 INT WINAPI
WSAGetServiceClassInfoW( LPGUID provider
, LPGUID service
, LPDWORD len
,
7270 LPWSASERVICECLASSINFOW info
)
7272 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider
), debugstr_guid(service
),
7274 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
7275 return SOCKET_ERROR
;
7278 /***********************************************************************
7279 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
7281 INT WINAPI
WSAGetServiceClassNameByClassIdA( LPGUID
class, LPSTR service
, LPDWORD len
)
7283 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service
, len
);
7284 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
7285 return SOCKET_ERROR
;
7288 /***********************************************************************
7289 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
7291 INT WINAPI
WSAGetServiceClassNameByClassIdW( LPGUID
class, LPWSTR service
, LPDWORD len
)
7293 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service
, len
);
7294 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
7295 return SOCKET_ERROR
;
7298 /***********************************************************************
7299 * WSALookupServiceBeginA (WS2_32.59)
7301 INT WINAPI
WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions
,
7302 DWORD dwControlFlags
,
7305 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions
, dwControlFlags
,
7307 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
7308 return SOCKET_ERROR
;
7311 /***********************************************************************
7312 * WSALookupServiceBeginW (WS2_32.60)
7314 INT WINAPI
WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions
,
7315 DWORD dwControlFlags
,
7318 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions
, dwControlFlags
,
7320 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
7321 return SOCKET_ERROR
;
7324 /***********************************************************************
7325 * WSALookupServiceEnd (WS2_32.61)
7327 INT WINAPI
WSALookupServiceEnd( HANDLE lookup
)
7329 FIXME("(%p) Stub!\n", lookup
);
7333 /***********************************************************************
7334 * WSALookupServiceNextA (WS2_32.62)
7336 INT WINAPI
WSALookupServiceNextA( HANDLE lookup
, DWORD flags
, LPDWORD len
, LPWSAQUERYSETA results
)
7338 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup
, flags
, len
, results
);
7339 WSASetLastError(WSA_E_NO_MORE
);
7340 return SOCKET_ERROR
;
7343 /***********************************************************************
7344 * WSALookupServiceNextW (WS2_32.63)
7346 INT WINAPI
WSALookupServiceNextW( HANDLE lookup
, DWORD flags
, LPDWORD len
, LPWSAQUERYSETW results
)
7348 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup
, flags
, len
, results
);
7349 WSASetLastError(WSA_E_NO_MORE
);
7350 return SOCKET_ERROR
;
7353 /***********************************************************************
7354 * WSANtohl (WS2_32.64)
7356 INT WINAPI
WSANtohl( SOCKET s
, WS_u_long netlong
, WS_u_long
* lphostlong
)
7358 TRACE( "(0x%04lx 0x%08x %p)\n", s
, netlong
, lphostlong
);
7360 if (!lphostlong
) return WSAEFAULT
;
7362 *lphostlong
= ntohl( netlong
);
7366 /***********************************************************************
7367 * WSANtohs (WS2_32.65)
7369 INT WINAPI
WSANtohs( SOCKET s
, WS_u_short netshort
, WS_u_short
* lphostshort
)
7371 TRACE( "(0x%04lx 0x%08x %p)\n", s
, netshort
, lphostshort
);
7373 if (!lphostshort
) return WSAEFAULT
;
7375 *lphostshort
= ntohs( netshort
);
7379 /***********************************************************************
7380 * WSAProviderConfigChange (WS2_32.66)
7382 INT WINAPI
WSAProviderConfigChange( LPHANDLE handle
, LPWSAOVERLAPPED overlapped
,
7383 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
7385 FIXME( "(%p %p %p) Stub!\n", handle
, overlapped
, completion
);
7386 return SOCKET_ERROR
;
7389 /***********************************************************************
7390 * WSARecvDisconnect (WS2_32.68)
7392 INT WINAPI
WSARecvDisconnect( SOCKET s
, LPWSABUF disconnectdata
)
7394 TRACE( "(0x%04lx %p)\n", s
, disconnectdata
);
7396 return WS_shutdown( s
, SD_RECEIVE
);
7399 /***********************************************************************
7400 * WSASetServiceA (WS2_32.76)
7402 INT WINAPI
WSASetServiceA( LPWSAQUERYSETA query
, WSAESETSERVICEOP operation
, DWORD flags
)
7404 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query
, operation
, flags
);
7408 /***********************************************************************
7409 * WSASetServiceW (WS2_32.77)
7411 INT WINAPI
WSASetServiceW( LPWSAQUERYSETW query
, WSAESETSERVICEOP operation
, DWORD flags
)
7413 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query
, operation
, flags
);
7417 /***********************************************************************
7418 * WSCEnableNSProvider (WS2_32.84)
7420 INT WINAPI
WSCEnableNSProvider( LPGUID provider
, BOOL enable
)
7422 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider
), enable
);
7426 /***********************************************************************
7427 * WSCGetProviderPath (WS2_32.86)
7429 INT WINAPI
WSCGetProviderPath( LPGUID provider
, LPWSTR path
, LPINT len
, LPINT errcode
)
7431 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider
), path
, len
, errcode
);
7433 if (!errcode
|| !provider
|| !len
) return WSAEFAULT
;
7435 *errcode
= WSAEINVAL
;
7436 return SOCKET_ERROR
;
7439 /***********************************************************************
7440 * WSCInstallNameSpace (WS2_32.87)
7442 INT WINAPI
WSCInstallNameSpace( LPWSTR identifier
, LPWSTR path
, DWORD
namespace,
7443 DWORD version
, LPGUID provider
)
7445 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier
), debugstr_w(path
),
7446 namespace, version
, debugstr_guid(provider
) );
7450 /***********************************************************************
7451 * WSCUnInstallNameSpace (WS2_32.89)
7453 INT WINAPI
WSCUnInstallNameSpace( LPGUID lpProviderId
)
7455 FIXME("(%p) Stub!\n", lpProviderId
);
7459 /***********************************************************************
7460 * WSCWriteProviderOrder (WS2_32.91)
7462 INT WINAPI
WSCWriteProviderOrder( LPDWORD entry
, DWORD number
)
7464 FIXME("(%p 0x%08x) Stub!\n", entry
, number
);
7468 /***********************************************************************
7469 * WSANSPIoctl (WS2_32.91)
7471 INT WINAPI
WSANSPIoctl( HANDLE hLookup
, DWORD dwControlCode
, LPVOID lpvInBuffer
,
7472 DWORD cbInBuffer
, LPVOID lpvOutBuffer
, DWORD cbOutBuffer
,
7473 LPDWORD lpcbBytesReturned
, LPWSACOMPLETION lpCompletion
)
7475 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup
, dwControlCode
,
7476 lpvInBuffer
, cbInBuffer
, lpvOutBuffer
, cbOutBuffer
, lpcbBytesReturned
, lpCompletion
);
7477 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
7478 return SOCKET_ERROR
;
7481 /*****************************************************************************
7482 * WSAEnumProtocolsA [WS2_32.@]
7484 * see function WSAEnumProtocolsW
7486 INT WINAPI
WSAEnumProtocolsA( LPINT protocols
, LPWSAPROTOCOL_INFOA buffer
, LPDWORD len
)
7488 return WS_EnumProtocols( FALSE
, protocols
, (LPWSAPROTOCOL_INFOW
) buffer
, len
);
7491 /*****************************************************************************
7492 * WSAEnumProtocolsW [WS2_32.@]
7494 * Retrieves information about specified set of active network protocols.
7497 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
7498 * retrieves information on all available protocols.
7499 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
7501 * len [I/O] Pointer to a variable specifying buffer size. On output
7502 * the variable holds the number of bytes needed when the
7503 * specified size is too small.
7506 * Success: number of WSAPROTOCOL_INFO structures in buffer.
7507 * Failure: SOCKET_ERROR
7510 * NT4SP5 does not return SPX if protocols == NULL
7513 * - NT4SP5 returns in addition these list of NETBIOS protocols
7514 * (address family 17), each entry two times one for socket type 2 and 5
7516 * iProtocol szProtocol
7517 * 0x80000000 \Device\NwlnkNb
7518 * 0xfffffffa \Device\NetBT_CBENT7
7519 * 0xfffffffb \Device\Nbf_CBENT7
7520 * 0xfffffffc \Device\NetBT_NdisWan5
7521 * 0xfffffffd \Device\NetBT_El9202
7522 * 0xfffffffe \Device\Nbf_El9202
7523 * 0xffffffff \Device\Nbf_NdisWan4
7525 * - there is no check that the operating system supports the returned
7528 INT WINAPI
WSAEnumProtocolsW( LPINT protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
)
7530 return WS_EnumProtocols( TRUE
, protocols
, buffer
, len
);
7533 /*****************************************************************************
7534 * WSCEnumProtocols [WS2_32.@]
7537 * protocols [I] Null-terminated array of iProtocol values.
7538 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
7539 * len [I/O] Size of buffer on input/output.
7540 * errno [O] Error code.
7543 * Success: number of protocols to be reported on.
7544 * Failure: SOCKET_ERROR. error is in errno.
7547 * Doesn't supply info on layered protocols.
7550 INT WINAPI
WSCEnumProtocols( LPINT protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
, LPINT err
)
7552 INT ret
= WSAEnumProtocolsW( protocols
, buffer
, len
);
7554 if (ret
== SOCKET_ERROR
) *err
= WSAENOBUFS
;