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
),
533 MAP_OPTION( AI_V4MAPPED
),
535 MAP_OPTION( AI_ADDRCONFIG
),
538 static const int ws_niflag_map
[][2] =
540 MAP_OPTION( NI_NOFQDN
),
541 MAP_OPTION( NI_NUMERICHOST
),
542 MAP_OPTION( NI_NAMEREQD
),
543 MAP_OPTION( NI_NUMERICSERV
),
544 MAP_OPTION( NI_DGRAM
),
547 static const int ws_eai_map
[][2] =
549 MAP_OPTION( EAI_AGAIN
),
550 MAP_OPTION( EAI_BADFLAGS
),
551 MAP_OPTION( EAI_FAIL
),
552 MAP_OPTION( EAI_FAMILY
),
553 MAP_OPTION( EAI_MEMORY
),
554 /* Note: EAI_NODATA is deprecated, but still
555 * used by Windows and Linux... We map the newer
556 * EAI_NONAME to EAI_NODATA for now until Windows
560 MAP_OPTION( EAI_NODATA
),
563 { WS_EAI_NODATA
, EAI_NONAME
},
566 MAP_OPTION( EAI_SERVICE
),
567 MAP_OPTION( EAI_SOCKTYPE
),
571 static const char magic_loopback_addr
[] = {127, 12, 34, 56};
573 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
575 static inline WSACMSGHDR
*fill_control_message(int level
, int type
, WSACMSGHDR
*current
, ULONG
*maxsize
, void *data
, int len
)
577 ULONG msgsize
= sizeof(WSACMSGHDR
) + WSA_CMSG_ALIGN(len
);
578 char *ptr
= (char *) current
+ sizeof(WSACMSGHDR
);
580 /* Make sure there is at least enough room for this entry */
581 if (msgsize
> *maxsize
)
584 /* Fill in the entry */
585 current
->cmsg_len
= sizeof(WSACMSGHDR
) + len
;
586 current
->cmsg_level
= level
;
587 current
->cmsg_type
= type
;
588 memcpy(ptr
, data
, len
);
589 /* Return the pointer to where next entry should go */
590 return (WSACMSGHDR
*) (ptr
+ WSA_CMSG_ALIGN(len
));
592 #endif /* IP_PKTINFO */
594 static inline int convert_control_headers(struct msghdr
*hdr
, WSABUF
*control
)
597 WSACMSGHDR
*cmsg_win
= (WSACMSGHDR
*) control
->buf
, *ptr
;
598 ULONG ctlsize
= control
->len
;
599 struct cmsghdr
*cmsg_unix
;
602 /* Loop over all the headers, converting as appropriate */
603 for (cmsg_unix
= CMSG_FIRSTHDR(hdr
); cmsg_unix
!= NULL
; cmsg_unix
= CMSG_NXTHDR(hdr
, cmsg_unix
))
605 switch(cmsg_unix
->cmsg_level
)
608 switch(cmsg_unix
->cmsg_type
)
612 /* Convert the Unix IP_PKTINFO structure to the Windows version */
613 struct in_pktinfo
*data_unix
= (struct in_pktinfo
*) CMSG_DATA(cmsg_unix
);
614 struct WS_in_pktinfo data_win
;
616 memcpy(&data_win
.ipi_addr
,&data_unix
->ipi_addr
.s_addr
,4); /* 4 bytes = 32 address bits */
617 data_win
.ipi_ifindex
= data_unix
->ipi_ifindex
;
618 ptr
= fill_control_message(WS_IPPROTO_IP
, WS_IP_PKTINFO
, ptr
, &ctlsize
,
619 (void*)&data_win
, sizeof(data_win
));
620 if (!ptr
) goto error
;
623 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix
->cmsg_type
);
628 FIXME("Unhandled message header level %d\n", cmsg_unix
->cmsg_level
);
634 /* Set the length of the returned control headers */
635 control
->len
= (ptr
== NULL
? 0 : (char*)ptr
- (char*)cmsg_win
);
636 return (ptr
!= NULL
);
637 #else /* IP_PKTINFO */
640 #endif /* IP_PKTINFO */
642 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
644 /* ----------------------------------- error handling */
646 static NTSTATUS
sock_get_ntstatus( int err
)
650 case EBADF
: return STATUS_INVALID_HANDLE
;
651 case EBUSY
: return STATUS_DEVICE_BUSY
;
653 case EACCES
: return STATUS_ACCESS_DENIED
;
654 case EFAULT
: return STATUS_NO_MEMORY
;
655 case EINVAL
: return STATUS_INVALID_PARAMETER
;
657 case EMFILE
: return STATUS_TOO_MANY_OPENED_FILES
;
658 case EWOULDBLOCK
: return STATUS_CANT_WAIT
;
659 case EINPROGRESS
: return STATUS_PENDING
;
660 case EALREADY
: return STATUS_NETWORK_BUSY
;
661 case ENOTSOCK
: return STATUS_OBJECT_TYPE_MISMATCH
;
662 case EDESTADDRREQ
: return STATUS_INVALID_PARAMETER
;
663 case EMSGSIZE
: return STATUS_BUFFER_OVERFLOW
;
664 case EPROTONOSUPPORT
:
665 case ESOCKTNOSUPPORT
:
668 case EPROTOTYPE
: return STATUS_NOT_SUPPORTED
;
669 case ENOPROTOOPT
: return STATUS_INVALID_PARAMETER
;
670 case EOPNOTSUPP
: return STATUS_NOT_SUPPORTED
;
671 case EADDRINUSE
: return STATUS_ADDRESS_ALREADY_ASSOCIATED
;
672 case EADDRNOTAVAIL
: return STATUS_INVALID_PARAMETER
;
673 case ECONNREFUSED
: return STATUS_CONNECTION_REFUSED
;
674 case ESHUTDOWN
: return STATUS_PIPE_DISCONNECTED
;
675 case ENOTCONN
: return STATUS_CONNECTION_DISCONNECTED
;
676 case ETIMEDOUT
: return STATUS_IO_TIMEOUT
;
677 case ENETUNREACH
: return STATUS_NETWORK_UNREACHABLE
;
678 case ENETDOWN
: return STATUS_NETWORK_BUSY
;
680 case ECONNRESET
: return STATUS_CONNECTION_RESET
;
681 case ECONNABORTED
: return STATUS_CONNECTION_ABORTED
;
683 case 0: return STATUS_SUCCESS
;
685 WARN("Unknown errno %d!\n", err
);
686 return STATUS_UNSUCCESSFUL
;
690 static UINT
sock_get_error( int err
)
694 case EINTR
: return WSAEINTR
;
695 case EBADF
: return WSAEBADF
;
697 case EACCES
: return WSAEACCES
;
698 case EFAULT
: return WSAEFAULT
;
699 case EINVAL
: return WSAEINVAL
;
700 case EMFILE
: return WSAEMFILE
;
701 case EWOULDBLOCK
: return WSAEWOULDBLOCK
;
702 case EINPROGRESS
: return WSAEINPROGRESS
;
703 case EALREADY
: return WSAEALREADY
;
704 case ENOTSOCK
: return WSAENOTSOCK
;
705 case EDESTADDRREQ
: return WSAEDESTADDRREQ
;
706 case EMSGSIZE
: return WSAEMSGSIZE
;
707 case EPROTOTYPE
: return WSAEPROTOTYPE
;
708 case ENOPROTOOPT
: return WSAENOPROTOOPT
;
709 case EPROTONOSUPPORT
: return WSAEPROTONOSUPPORT
;
710 case ESOCKTNOSUPPORT
: return WSAESOCKTNOSUPPORT
;
711 case EOPNOTSUPP
: return WSAEOPNOTSUPP
;
712 case EPFNOSUPPORT
: return WSAEPFNOSUPPORT
;
713 case EAFNOSUPPORT
: return WSAEAFNOSUPPORT
;
714 case EADDRINUSE
: return WSAEADDRINUSE
;
715 case EADDRNOTAVAIL
: return WSAEADDRNOTAVAIL
;
716 case ENETDOWN
: return WSAENETDOWN
;
717 case ENETUNREACH
: return WSAENETUNREACH
;
718 case ENETRESET
: return WSAENETRESET
;
719 case ECONNABORTED
: return WSAECONNABORTED
;
721 case ECONNRESET
: return WSAECONNRESET
;
722 case ENOBUFS
: return WSAENOBUFS
;
723 case EISCONN
: return WSAEISCONN
;
724 case ENOTCONN
: return WSAENOTCONN
;
725 case ESHUTDOWN
: return WSAESHUTDOWN
;
726 case ETOOMANYREFS
: return WSAETOOMANYREFS
;
727 case ETIMEDOUT
: return WSAETIMEDOUT
;
728 case ECONNREFUSED
: return WSAECONNREFUSED
;
729 case ELOOP
: return WSAELOOP
;
730 case ENAMETOOLONG
: return WSAENAMETOOLONG
;
731 case EHOSTDOWN
: return WSAEHOSTDOWN
;
732 case EHOSTUNREACH
: return WSAEHOSTUNREACH
;
733 case ENOTEMPTY
: return WSAENOTEMPTY
;
735 case EPROCLIM
: return WSAEPROCLIM
;
738 case EUSERS
: return WSAEUSERS
;
741 case EDQUOT
: return WSAEDQUOT
;
744 case ESTALE
: return WSAESTALE
;
747 case EREMOTE
: return WSAEREMOTE
;
750 /* just in case we ever get here and there are no problems */
753 WARN("Unknown errno %d!\n", err
);
754 return WSAEOPNOTSUPP
;
758 static UINT
wsaErrno(void)
760 int loc_errno
= errno
;
761 WARN("errno %d, (%s).\n", loc_errno
, strerror(loc_errno
));
763 return sock_get_error( loc_errno
);
766 /* most ws2 overlapped functions return an ntstatus-based error code */
767 static NTSTATUS
wsaErrStatus(void)
769 int loc_errno
= errno
;
770 WARN("errno %d, (%s).\n", loc_errno
, strerror(loc_errno
));
772 return sock_get_ntstatus(loc_errno
);
775 static UINT
wsaHerrno(int loc_errno
)
777 WARN("h_errno %d.\n", loc_errno
);
781 case HOST_NOT_FOUND
: return WSAHOST_NOT_FOUND
;
782 case TRY_AGAIN
: return WSATRY_AGAIN
;
783 case NO_RECOVERY
: return WSANO_RECOVERY
;
784 case NO_DATA
: return WSANO_DATA
;
785 case ENOBUFS
: return WSAENOBUFS
;
789 WARN("Unknown h_errno %d!\n", loc_errno
);
790 return WSAEOPNOTSUPP
;
794 static inline DWORD
NtStatusToWSAError( const DWORD status
)
796 /* We only need to cover the status codes set by server async request handling */
800 case STATUS_SUCCESS
: wserr
= 0; break;
801 case STATUS_PENDING
: wserr
= WSA_IO_PENDING
; break;
802 case STATUS_OBJECT_TYPE_MISMATCH
: wserr
= WSAENOTSOCK
; break;
803 case STATUS_INVALID_HANDLE
: wserr
= WSAEBADF
; break;
804 case STATUS_INVALID_PARAMETER
: wserr
= WSAEINVAL
; break;
805 case STATUS_PIPE_DISCONNECTED
: wserr
= WSAESHUTDOWN
; break;
806 case STATUS_NETWORK_BUSY
: wserr
= WSAEALREADY
; break;
807 case STATUS_NETWORK_UNREACHABLE
: wserr
= WSAENETUNREACH
; break;
808 case STATUS_CONNECTION_REFUSED
: wserr
= WSAECONNREFUSED
; break;
809 case STATUS_CONNECTION_DISCONNECTED
: wserr
= WSAENOTCONN
; break;
810 case STATUS_CONNECTION_RESET
: wserr
= WSAECONNRESET
; break;
811 case STATUS_CONNECTION_ABORTED
: wserr
= WSAECONNABORTED
; break;
812 case STATUS_CANCELLED
: wserr
= WSA_OPERATION_ABORTED
; break;
813 case STATUS_ADDRESS_ALREADY_ASSOCIATED
: wserr
= WSAEADDRINUSE
; break;
814 case STATUS_IO_TIMEOUT
:
815 case STATUS_TIMEOUT
: wserr
= WSAETIMEDOUT
; break;
816 case STATUS_NO_MEMORY
: wserr
= WSAEFAULT
; break;
817 case STATUS_ACCESS_DENIED
: wserr
= WSAEACCES
; break;
818 case STATUS_TOO_MANY_OPENED_FILES
: wserr
= WSAEMFILE
; break;
819 case STATUS_CANT_WAIT
: wserr
= WSAEWOULDBLOCK
; break;
820 case STATUS_BUFFER_OVERFLOW
: wserr
= WSAEMSGSIZE
; break;
821 case STATUS_NOT_SUPPORTED
: wserr
= WSAEOPNOTSUPP
; break;
822 case STATUS_HOST_UNREACHABLE
: wserr
= WSAEHOSTUNREACH
; break;
825 wserr
= RtlNtStatusToDosError( status
);
826 FIXME( "Status code %08x converted to DOS error code %x\n", status
, wserr
);
831 /* set last error code from NT status without mapping WSA errors */
832 static inline unsigned int set_error( unsigned int err
)
836 err
= NtStatusToWSAError( err
);
842 static inline int get_sock_fd( SOCKET s
, DWORD access
, unsigned int *options
)
845 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s
), access
, &fd
, options
) ))
850 static inline void release_sock_fd( SOCKET s
, int fd
)
852 wine_server_release_fd( SOCKET2HANDLE(s
), fd
);
855 static void _enable_event( HANDLE s
, unsigned int event
,
856 unsigned int sstate
, unsigned int cstate
)
858 SERVER_START_REQ( enable_socket_event
)
860 req
->handle
= wine_server_obj_handle( s
);
862 req
->sstate
= sstate
;
863 req
->cstate
= cstate
;
864 wine_server_call( req
);
869 static NTSTATUS
_is_blocking(SOCKET s
, BOOL
*ret
)
872 SERVER_START_REQ( get_socket_event
)
874 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
875 req
->service
= FALSE
;
877 status
= wine_server_call( req
);
878 *ret
= (reply
->state
& FD_WINE_NONBLOCKING
) == 0;
884 static unsigned int _get_sock_mask(SOCKET s
)
887 SERVER_START_REQ( get_socket_event
)
889 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
890 req
->service
= FALSE
;
892 wine_server_call( req
);
899 static void _sync_sock_state(SOCKET s
)
902 /* do a dummy wineserver request in order to let
903 the wineserver run through its select loop once */
904 (void)_is_blocking(s
, &dummy
);
907 static int _get_sock_error(SOCKET s
, unsigned int bit
)
909 int events
[FD_MAX_EVENTS
];
911 SERVER_START_REQ( get_socket_event
)
913 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
914 req
->service
= FALSE
;
916 wine_server_set_reply( req
, events
, sizeof(events
) );
917 wine_server_call( req
);
923 static struct per_thread_data
*get_per_thread_data(void)
925 struct per_thread_data
* ptb
= NtCurrentTeb()->WinSockData
;
926 /* lazy initialization */
929 ptb
= HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(*ptb
) );
930 NtCurrentTeb()->WinSockData
= ptb
;
935 static void free_per_thread_data(void)
937 struct per_thread_data
* ptb
= NtCurrentTeb()->WinSockData
;
941 /* delete scratch buffers */
942 HeapFree( GetProcessHeap(), 0, ptb
->he_buffer
);
943 HeapFree( GetProcessHeap(), 0, ptb
->se_buffer
);
944 HeapFree( GetProcessHeap(), 0, ptb
->pe_buffer
);
945 ptb
->he_buffer
= NULL
;
946 ptb
->se_buffer
= NULL
;
947 ptb
->pe_buffer
= NULL
;
949 HeapFree( GetProcessHeap(), 0, ptb
);
950 NtCurrentTeb()->WinSockData
= NULL
;
953 /***********************************************************************
954 * DllMain (WS2_32.init)
956 BOOL WINAPI
DllMain(HINSTANCE hInstDLL
, DWORD fdwReason
, LPVOID fImpLoad
)
958 TRACE("%p 0x%x %p\n", hInstDLL
, fdwReason
, fImpLoad
);
960 case DLL_PROCESS_ATTACH
:
962 case DLL_PROCESS_DETACH
:
964 free_per_thread_data();
965 DeleteCriticalSection(&csWSgetXXXbyYYY
);
967 case DLL_THREAD_DETACH
:
968 free_per_thread_data();
974 /***********************************************************************
977 * Converts socket flags from Windows format.
978 * Return 1 if converted, 0 if not (error).
980 static int convert_sockopt(INT
*level
, INT
*optname
)
987 for(i
=0; i
<sizeof(ws_sock_map
)/sizeof(ws_sock_map
[0]); i
++) {
988 if( ws_sock_map
[i
][0] == *optname
)
990 *optname
= ws_sock_map
[i
][1];
994 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname
);
997 *level
= IPPROTO_TCP
;
998 for(i
=0; i
<sizeof(ws_tcp_map
)/sizeof(ws_tcp_map
[0]); i
++) {
999 if ( ws_tcp_map
[i
][0] == *optname
)
1001 *optname
= ws_tcp_map
[i
][1];
1005 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname
);
1008 *level
= IPPROTO_IP
;
1009 for(i
=0; i
<sizeof(ws_ip_map
)/sizeof(ws_ip_map
[0]); i
++) {
1010 if (ws_ip_map
[i
][0] == *optname
)
1012 *optname
= ws_ip_map
[i
][1];
1016 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname
);
1018 case WS_IPPROTO_IPV6
:
1019 *level
= IPPROTO_IPV6
;
1020 for(i
=0; i
<sizeof(ws_ipv6_map
)/sizeof(ws_ipv6_map
[0]); i
++) {
1021 if (ws_ipv6_map
[i
][0] == *optname
)
1023 *optname
= ws_ipv6_map
[i
][1];
1027 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname
);
1029 default: FIXME("Unimplemented or unknown socket level\n");
1034 /* ----------------------------------- Per-thread info (or per-process?) */
1036 static char *strdup_lower(const char *str
)
1039 char *ret
= HeapAlloc( GetProcessHeap(), 0, strlen(str
) + 1 );
1043 for (i
= 0; str
[i
]; i
++) ret
[i
] = tolower(str
[i
]);
1046 else SetLastError(WSAENOBUFS
);
1050 static inline int sock_error_p(int s
)
1052 unsigned int optval
;
1053 socklen_t optlen
= sizeof(optval
);
1054 getsockopt(s
, SOL_SOCKET
, SO_ERROR
, (void *) &optval
, &optlen
);
1055 if (optval
) WARN("\t[%i] error: %d\n", s
, optval
);
1059 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1060 * from an fd and return the value converted to milli seconds
1061 * or -1 if there is an infinite time out */
1062 static inline int get_rcvsnd_timeo( int fd
, int optname
)
1065 socklen_t len
= sizeof(tv
);
1066 int ret
= getsockopt(fd
, SOL_SOCKET
, optname
, &tv
, &len
);
1068 ret
= tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000;
1069 if( ret
<= 0 ) /* tv == {0,0} means infinite time out */
1074 /* macro wrappers for portability */
1076 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
1078 #define GET_RCVTIMEO(fd) (-1)
1082 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
1084 #define GET_SNDTIMEO(fd) (-1)
1087 /* utility: given an fd, will block until one of the events occurs */
1088 static inline int do_block( int fd
, int events
, int timeout
)
1094 pfd
.events
= events
;
1096 while ((ret
= poll(&pfd
, 1, timeout
)) < 0)
1107 convert_af_w2u(int windowsaf
) {
1110 for (i
=0;i
<sizeof(ws_af_map
)/sizeof(ws_af_map
[0]);i
++)
1111 if (ws_af_map
[i
][0] == windowsaf
)
1112 return ws_af_map
[i
][1];
1113 FIXME("unhandled Windows address family %d\n", windowsaf
);
1118 convert_af_u2w(int unixaf
) {
1121 for (i
=0;i
<sizeof(ws_af_map
)/sizeof(ws_af_map
[0]);i
++)
1122 if (ws_af_map
[i
][1] == unixaf
)
1123 return ws_af_map
[i
][0];
1124 FIXME("unhandled UNIX address family %d\n", unixaf
);
1129 convert_proto_w2u(int windowsproto
) {
1132 for (i
=0;i
<sizeof(ws_proto_map
)/sizeof(ws_proto_map
[0]);i
++)
1133 if (ws_proto_map
[i
][0] == windowsproto
)
1134 return ws_proto_map
[i
][1];
1136 /* check for extended IPX */
1137 if (IS_IPX_PROTO(windowsproto
))
1138 return windowsproto
;
1140 FIXME("unhandled Windows socket protocol %d\n", windowsproto
);
1145 convert_proto_u2w(int unixproto
) {
1148 for (i
=0;i
<sizeof(ws_proto_map
)/sizeof(ws_proto_map
[0]);i
++)
1149 if (ws_proto_map
[i
][1] == unixproto
)
1150 return ws_proto_map
[i
][0];
1152 /* if value is inside IPX range just return it - the kernel simply
1153 * echoes the value used in the socket() function */
1154 if (IS_IPX_PROTO(unixproto
))
1157 FIXME("unhandled UNIX socket protocol %d\n", unixproto
);
1162 convert_socktype_w2u(int windowssocktype
) {
1165 for (i
=0;i
<sizeof(ws_socktype_map
)/sizeof(ws_socktype_map
[0]);i
++)
1166 if (ws_socktype_map
[i
][0] == windowssocktype
)
1167 return ws_socktype_map
[i
][1];
1168 FIXME("unhandled Windows socket type %d\n", windowssocktype
);
1173 convert_socktype_u2w(int unixsocktype
) {
1176 for (i
=0;i
<sizeof(ws_socktype_map
)/sizeof(ws_socktype_map
[0]);i
++)
1177 if (ws_socktype_map
[i
][1] == unixsocktype
)
1178 return ws_socktype_map
[i
][0];
1179 FIXME("unhandled UNIX socket type %d\n", unixsocktype
);
1183 static int set_ipx_packettype(int sock
, int ptype
)
1186 int fd
= get_sock_fd( sock
, 0, NULL
), ret
= 0;
1187 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype
, fd
);
1189 if (fd
== -1) return SOCKET_ERROR
;
1191 /* We try to set the ipx type on ipx socket level. */
1193 if(setsockopt(fd
, SOL_IPX
, IPX_TYPE
, &ptype
, sizeof(ptype
)) == -1)
1195 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1201 /* Should we retrieve val using a getsockopt call and then
1202 * set the modified one? */
1204 setsockopt(fd
, 0, SO_DEFAULT_HEADERS
, &val
, sizeof(struct ipx
));
1207 release_sock_fd( sock
, fd
);
1210 WARN("IPX support is not enabled, can't set packet type\n");
1211 return SOCKET_ERROR
;
1215 /* ----------------------------------- API -----
1217 * Init / cleanup / error checking.
1220 /***********************************************************************
1221 * WSAStartup (WS2_32.115)
1223 int WINAPI
WSAStartup(WORD wVersionRequested
, LPWSADATA lpWSAData
)
1225 TRACE("verReq=%x\n", wVersionRequested
);
1227 if (LOBYTE(wVersionRequested
) < 1)
1228 return WSAVERNOTSUPPORTED
;
1230 if (!lpWSAData
) return WSAEINVAL
;
1234 /* that's the whole of the negotiation for now */
1235 lpWSAData
->wVersion
= wVersionRequested
;
1236 /* return winsock information */
1237 lpWSAData
->wHighVersion
= 0x0202;
1238 strcpy(lpWSAData
->szDescription
, "WinSock 2.0" );
1239 strcpy(lpWSAData
->szSystemStatus
, "Running" );
1240 lpWSAData
->iMaxSockets
= WS_MAX_SOCKETS_PER_PROCESS
;
1241 lpWSAData
->iMaxUdpDg
= WS_MAX_UDP_DATAGRAM
;
1242 /* don't do anything with lpWSAData->lpVendorInfo */
1243 /* (some apps don't allocate the space for this field) */
1245 TRACE("succeeded starts: %d\n", num_startup
);
1250 /***********************************************************************
1251 * WSACleanup (WS2_32.116)
1253 INT WINAPI
WSACleanup(void)
1257 TRACE("pending cleanups: %d\n", num_startup
);
1260 SetLastError(WSANOTINITIALISED
);
1261 return SOCKET_ERROR
;
1265 /***********************************************************************
1266 * WSAGetLastError (WS2_32.111)
1268 INT WINAPI
WSAGetLastError(void)
1270 return GetLastError();
1273 /***********************************************************************
1274 * WSASetLastError (WS2_32.112)
1276 void WINAPI
WSASetLastError(INT iError
) {
1277 SetLastError(iError
);
1280 static struct WS_hostent
*check_buffer_he(int size
)
1282 struct per_thread_data
* ptb
= get_per_thread_data();
1285 if (ptb
->he_len
>= size
) return ptb
->he_buffer
;
1286 HeapFree( GetProcessHeap(), 0, ptb
->he_buffer
);
1288 ptb
->he_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->he_len
= size
) );
1289 if (!ptb
->he_buffer
) SetLastError(WSAENOBUFS
);
1290 return ptb
->he_buffer
;
1293 static struct WS_servent
*check_buffer_se(int size
)
1295 struct per_thread_data
* ptb
= get_per_thread_data();
1298 if (ptb
->se_len
>= size
) return ptb
->se_buffer
;
1299 HeapFree( GetProcessHeap(), 0, ptb
->se_buffer
);
1301 ptb
->se_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->se_len
= size
) );
1302 if (!ptb
->se_buffer
) SetLastError(WSAENOBUFS
);
1303 return ptb
->se_buffer
;
1306 static struct WS_protoent
*check_buffer_pe(int size
)
1308 struct per_thread_data
* ptb
= get_per_thread_data();
1311 if (ptb
->pe_len
>= size
) return ptb
->pe_buffer
;
1312 HeapFree( GetProcessHeap(), 0, ptb
->pe_buffer
);
1314 ptb
->pe_buffer
= HeapAlloc( GetProcessHeap(), 0, (ptb
->pe_len
= size
) );
1315 if (!ptb
->pe_buffer
) SetLastError(WSAENOBUFS
);
1316 return ptb
->pe_buffer
;
1319 /* ----------------------------------- i/o APIs */
1321 static inline BOOL
supported_pf(int pf
)
1341 static inline BOOL
supported_protocol(int protocol
)
1344 for (i
= 0; i
< sizeof(valid_protocols
) / sizeof(valid_protocols
[0]); i
++)
1345 if (protocol
== valid_protocols
[i
])
1350 /**********************************************************************/
1352 /* Returns the length of the converted address if successful, 0 if it was too small to
1355 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr
* wsaddr
, int wsaddrlen
,
1356 union generic_unix_sockaddr
*uaddr
)
1358 unsigned int uaddrlen
= 0;
1360 switch (wsaddr
->sa_family
)
1365 const struct WS_sockaddr_ipx
* wsipx
=(const struct WS_sockaddr_ipx
*)wsaddr
;
1366 struct sockaddr_ipx
* uipx
= (struct sockaddr_ipx
*)uaddr
;
1368 if (wsaddrlen
<sizeof(struct WS_sockaddr_ipx
))
1371 uaddrlen
= sizeof(struct sockaddr_ipx
);
1372 memset( uaddr
, 0, uaddrlen
);
1373 uipx
->sipx_family
=AF_IPX
;
1374 uipx
->sipx_port
=wsipx
->sa_socket
;
1375 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1378 memcpy(&uipx
->sipx_network
,wsipx
->sa_netnum
,sizeof(uipx
->sipx_network
)+sizeof(uipx
->sipx_node
));
1379 #ifdef IPX_FRAME_NONE
1380 uipx
->sipx_type
=IPX_FRAME_NONE
;
1386 struct sockaddr_in6
* uin6
= (struct sockaddr_in6
*)uaddr
;
1387 const struct WS_sockaddr_in6
* win6
= (const struct WS_sockaddr_in6
*)wsaddr
;
1389 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1390 * scope_id, one without.
1392 if (wsaddrlen
>= sizeof(struct WS_sockaddr_in6_old
)) {
1393 uaddrlen
= sizeof(struct sockaddr_in6
);
1394 memset( uaddr
, 0, uaddrlen
);
1395 uin6
->sin6_family
= AF_INET6
;
1396 uin6
->sin6_port
= win6
->sin6_port
;
1397 uin6
->sin6_flowinfo
= win6
->sin6_flowinfo
;
1398 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1399 if (wsaddrlen
>= sizeof(struct WS_sockaddr_in6
)) uin6
->sin6_scope_id
= win6
->sin6_scope_id
;
1401 memcpy(&uin6
->sin6_addr
,&win6
->sin6_addr
,16); /* 16 bytes = 128 address bits */
1404 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen
);
1408 struct sockaddr_in
* uin
= (struct sockaddr_in
*)uaddr
;
1409 const struct WS_sockaddr_in
* win
= (const struct WS_sockaddr_in
*)wsaddr
;
1411 if (wsaddrlen
<sizeof(struct WS_sockaddr_in
))
1413 uaddrlen
= sizeof(struct sockaddr_in
);
1414 memset( uaddr
, 0, uaddrlen
);
1415 uin
->sin_family
= AF_INET
;
1416 uin
->sin_port
= win
->sin_port
;
1417 memcpy(&uin
->sin_addr
,&win
->sin_addr
,4); /* 4 bytes = 32 address bits */
1422 struct sockaddr_irda
*uin
= (struct sockaddr_irda
*)uaddr
;
1423 const SOCKADDR_IRDA
*win
= (const SOCKADDR_IRDA
*)wsaddr
;
1425 if (wsaddrlen
< sizeof(SOCKADDR_IRDA
))
1427 uaddrlen
= sizeof(struct sockaddr_irda
);
1428 memset( uaddr
, 0, uaddrlen
);
1429 uin
->sir_family
= AF_IRDA
;
1430 if (!strncmp( win
->irdaServiceName
, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1432 unsigned int lsap_sel
= 0;
1434 sscanf( win
->irdaServiceName
, "LSAP-SEL%u", &lsap_sel
);
1435 uin
->sir_lsap_sel
= lsap_sel
;
1439 uin
->sir_lsap_sel
= LSAP_ANY
;
1440 memcpy( uin
->sir_name
, win
->irdaServiceName
, 25 );
1442 memcpy( &uin
->sir_addr
, win
->irdaDeviceID
, sizeof(uin
->sir_addr
) );
1446 case WS_AF_UNSPEC
: {
1447 /* Try to determine the needed space by the passed windows sockaddr space */
1448 switch (wsaddrlen
) {
1449 default: /* likely an ipv4 address */
1450 case sizeof(struct WS_sockaddr_in
):
1451 uaddrlen
= sizeof(struct sockaddr_in
);
1454 case sizeof(struct WS_sockaddr_ipx
):
1455 uaddrlen
= sizeof(struct sockaddr_ipx
);
1459 case sizeof(SOCKADDR_IRDA
):
1460 uaddrlen
= sizeof(struct sockaddr_irda
);
1463 case sizeof(struct WS_sockaddr_in6
):
1464 case sizeof(struct WS_sockaddr_in6_old
):
1465 uaddrlen
= sizeof(struct sockaddr_in6
);
1468 memset( uaddr
, 0, uaddrlen
);
1472 FIXME("Unknown address family %d, return NULL.\n", wsaddr
->sa_family
);
1478 static BOOL
is_sockaddr_bound(const struct sockaddr
*uaddr
, int uaddrlen
)
1480 switch (uaddr
->sa_family
)
1485 static const struct sockaddr_ipx emptyAddr
;
1486 struct sockaddr_ipx
*ipx
= (struct sockaddr_ipx
*) uaddr
;
1487 return ipx
->sipx_port
1488 || memcmp(&ipx
->sipx_network
, &emptyAddr
.sipx_network
, sizeof(emptyAddr
.sipx_network
))
1489 || memcmp(&ipx
->sipx_node
, &emptyAddr
.sipx_node
, sizeof(emptyAddr
.sipx_node
));
1494 static const struct sockaddr_in6 emptyAddr
;
1495 const struct sockaddr_in6
*in6
= (const struct sockaddr_in6
*) uaddr
;
1496 return in6
->sin6_port
|| memcmp(&in6
->sin6_addr
, &emptyAddr
.sin6_addr
, sizeof(struct in6_addr
));
1500 static const struct sockaddr_in emptyAddr
;
1501 const struct sockaddr_in
*in
= (const struct sockaddr_in
*) uaddr
;
1502 return in
->sin_port
|| memcmp(&in
->sin_addr
, &emptyAddr
.sin_addr
, sizeof(struct in_addr
));
1507 FIXME("unknown address family %d\n", uaddr
->sa_family
);
1512 /* Returns 0 if successful, -1 if the buffer is too small */
1513 static int ws_sockaddr_u2ws(const struct sockaddr
* uaddr
, struct WS_sockaddr
* wsaddr
, int* wsaddrlen
)
1517 switch(uaddr
->sa_family
)
1522 const struct sockaddr_ipx
* uipx
=(const struct sockaddr_ipx
*)uaddr
;
1523 struct WS_sockaddr_ipx
* wsipx
=(struct WS_sockaddr_ipx
*)wsaddr
;
1526 switch (*wsaddrlen
) /* how much can we copy? */
1530 *wsaddrlen
= sizeof(*wsipx
);
1531 wsipx
->sa_socket
=uipx
->sipx_port
;
1535 memcpy(wsipx
->sa_nodenum
,uipx
->sipx_node
,sizeof(wsipx
->sa_nodenum
));
1543 memcpy(wsipx
->sa_netnum
,&uipx
->sipx_network
,sizeof(wsipx
->sa_netnum
));
1549 wsipx
->sa_family
=WS_AF_IPX
;
1561 const struct sockaddr_irda
*uin
= (const struct sockaddr_irda
*)uaddr
;
1562 SOCKADDR_IRDA
*win
= (SOCKADDR_IRDA
*)wsaddr
;
1564 if (*wsaddrlen
< sizeof(SOCKADDR_IRDA
))
1566 win
->irdaAddressFamily
= WS_AF_IRDA
;
1567 memcpy( win
->irdaDeviceID
, &uin
->sir_addr
, sizeof(win
->irdaDeviceID
) );
1568 if (uin
->sir_lsap_sel
!= LSAP_ANY
)
1569 sprintf( win
->irdaServiceName
, "LSAP-SEL%u", uin
->sir_lsap_sel
);
1571 memcpy( win
->irdaServiceName
, uin
->sir_name
,
1572 sizeof(win
->irdaServiceName
) );
1577 const struct sockaddr_in6
* uin6
= (const struct sockaddr_in6
*)uaddr
;
1578 struct WS_sockaddr_in6_old
* win6old
= (struct WS_sockaddr_in6_old
*)wsaddr
;
1580 if (*wsaddrlen
< sizeof(struct WS_sockaddr_in6_old
))
1582 win6old
->sin6_family
= WS_AF_INET6
;
1583 win6old
->sin6_port
= uin6
->sin6_port
;
1584 win6old
->sin6_flowinfo
= uin6
->sin6_flowinfo
;
1585 memcpy(&win6old
->sin6_addr
,&uin6
->sin6_addr
,16); /* 16 bytes = 128 address bits */
1586 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1587 if (*wsaddrlen
>= sizeof(struct WS_sockaddr_in6
)) {
1588 struct WS_sockaddr_in6
* win6
= (struct WS_sockaddr_in6
*)wsaddr
;
1589 win6
->sin6_scope_id
= uin6
->sin6_scope_id
;
1590 *wsaddrlen
= sizeof(struct WS_sockaddr_in6
);
1593 *wsaddrlen
= sizeof(struct WS_sockaddr_in6_old
);
1595 *wsaddrlen
= sizeof(struct WS_sockaddr_in6_old
);
1600 const struct sockaddr_in
* uin
= (const struct sockaddr_in
*)uaddr
;
1601 struct WS_sockaddr_in
* win
= (struct WS_sockaddr_in
*)wsaddr
;
1603 if (*wsaddrlen
< sizeof(struct WS_sockaddr_in
))
1605 win
->sin_family
= WS_AF_INET
;
1606 win
->sin_port
= uin
->sin_port
;
1607 memcpy(&win
->sin_addr
,&uin
->sin_addr
,4); /* 4 bytes = 32 address bits */
1608 memset(win
->sin_zero
, 0, 8); /* Make sure the null padding is null */
1609 *wsaddrlen
= sizeof(struct WS_sockaddr_in
);
1613 memset(wsaddr
,0,*wsaddrlen
);
1617 FIXME("Unknown address family %d\n", uaddr
->sa_family
);
1623 static INT
WS_DuplicateSocket(BOOL unicode
, SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOW lpProtocolInfo
)
1627 WSAPROTOCOL_INFOW infow
;
1629 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
1630 unicode
, s
, dwProcessId
, lpProtocolInfo
);
1632 if (!ws_protocol_info(s
, unicode
, &infow
, &size
))
1633 return SOCKET_ERROR
;
1635 if (!(hProcess
= OpenProcess(PROCESS_DUP_HANDLE
, FALSE
, dwProcessId
)))
1637 SetLastError(WSAEINVAL
);
1638 return SOCKET_ERROR
;
1641 if (!lpProtocolInfo
)
1643 CloseHandle(hProcess
);
1644 SetLastError(WSAEFAULT
);
1645 return SOCKET_ERROR
;
1648 /* I don't know what the real Windoze does next, this is a hack */
1649 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
1650 * the target use the global duplicate, or we could copy a reference to us to the structure
1651 * and let the target duplicate it from us, but let's do it as simple as possible */
1652 memcpy(lpProtocolInfo
, &infow
, size
);
1653 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s
),
1654 hProcess
, (LPHANDLE
)&lpProtocolInfo
->dwServiceFlags3
,
1655 0, FALSE
, DUPLICATE_SAME_ACCESS
);
1656 CloseHandle(hProcess
);
1657 lpProtocolInfo
->dwServiceFlags4
= 0xff00ff00; /* magic */
1661 /*****************************************************************************
1662 * WS_EnterSingleProtocolW [internal]
1664 * enters the protocol information of one given protocol into the given
1668 * TRUE if a protocol was entered into the buffer.
1671 * - only implemented for IPX, SPX, SPXII, TCP, UDP
1672 * - there is no check that the operating system supports the returned
1675 static BOOL
WS_EnterSingleProtocolW( INT protocol
, WSAPROTOCOL_INFOW
* info
)
1677 memset( info
, 0, sizeof(WSAPROTOCOL_INFOW
) );
1678 info
->iProtocol
= protocol
;
1682 case WS_IPPROTO_TCP
:
1683 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_EXPEDITED_DATA
|
1684 XP1_GRACEFUL_CLOSE
| XP1_GUARANTEED_ORDER
|
1685 XP1_GUARANTEED_DELIVERY
;
1686 info
->ProviderId
= ProviderIdIP
;
1687 info
->dwCatalogEntryId
= 0x3e9;
1688 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1689 info
->ProtocolChain
.ChainLen
= 1;
1691 info
->iAddressFamily
= WS_AF_INET
;
1692 info
->iMaxSockAddr
= 0x10;
1693 info
->iMinSockAddr
= 0x10;
1694 info
->iSocketType
= WS_SOCK_STREAM
;
1695 strcpyW( info
->szProtocol
, NameTcpW
);
1698 case WS_IPPROTO_UDP
:
1699 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_SUPPORT_BROADCAST
|
1700 XP1_SUPPORT_MULTIPOINT
| XP1_MESSAGE_ORIENTED
|
1702 info
->ProviderId
= ProviderIdIP
;
1703 info
->dwCatalogEntryId
= 0x3ea;
1704 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1705 info
->ProtocolChain
.ChainLen
= 1;
1707 info
->iAddressFamily
= WS_AF_INET
;
1708 info
->iMaxSockAddr
= 0x10;
1709 info
->iMinSockAddr
= 0x10;
1710 info
->iSocketType
= WS_SOCK_DGRAM
;
1711 info
->dwMessageSize
= 0xffbb;
1712 strcpyW( info
->szProtocol
, NameUdpW
);
1715 case WS_NSPROTO_IPX
:
1716 info
->dwServiceFlags1
= XP1_PARTIAL_MESSAGE
| XP1_SUPPORT_BROADCAST
|
1717 XP1_SUPPORT_MULTIPOINT
| XP1_MESSAGE_ORIENTED
|
1719 info
->ProviderId
= ProviderIdIPX
;
1720 info
->dwCatalogEntryId
= 0x406;
1721 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1722 info
->ProtocolChain
.ChainLen
= 1;
1724 info
->iAddressFamily
= WS_AF_IPX
;
1725 info
->iMaxSockAddr
= 0x10;
1726 info
->iMinSockAddr
= 0x0e;
1727 info
->iSocketType
= WS_SOCK_DGRAM
;
1728 info
->iProtocolMaxOffset
= 0xff;
1729 info
->dwMessageSize
= 0x240;
1730 strcpyW( info
->szProtocol
, NameIpxW
);
1733 case WS_NSPROTO_SPX
:
1734 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_PSEUDO_STREAM
|
1735 XP1_MESSAGE_ORIENTED
| XP1_GUARANTEED_ORDER
|
1736 XP1_GUARANTEED_DELIVERY
;
1737 info
->ProviderId
= ProviderIdSPX
;
1738 info
->dwCatalogEntryId
= 0x407;
1739 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1740 info
->ProtocolChain
.ChainLen
= 1;
1742 info
->iAddressFamily
= WS_AF_IPX
;
1743 info
->iMaxSockAddr
= 0x10;
1744 info
->iMinSockAddr
= 0x0e;
1745 info
->iSocketType
= WS_SOCK_SEQPACKET
;
1746 info
->dwMessageSize
= 0xffffffff;
1747 strcpyW( info
->szProtocol
, NameSpxW
);
1750 case WS_NSPROTO_SPXII
:
1751 info
->dwServiceFlags1
= XP1_IFS_HANDLES
| XP1_GRACEFUL_CLOSE
|
1752 XP1_PSEUDO_STREAM
| XP1_MESSAGE_ORIENTED
|
1753 XP1_GUARANTEED_ORDER
| XP1_GUARANTEED_DELIVERY
;
1754 info
->ProviderId
= ProviderIdSPX
;
1755 info
->dwCatalogEntryId
= 0x409;
1756 info
->dwProviderFlags
= PFL_MATCHES_PROTOCOL_ZERO
;
1757 info
->ProtocolChain
.ChainLen
= 1;
1759 info
->iAddressFamily
= WS_AF_IPX
;
1760 info
->iMaxSockAddr
= 0x10;
1761 info
->iMinSockAddr
= 0x0e;
1762 info
->iSocketType
= WS_SOCK_SEQPACKET
;
1763 info
->dwMessageSize
= 0xffffffff;
1764 strcpyW( info
->szProtocol
, NameSpxIIW
);
1768 FIXME("unknown Protocol <0x%08x>\n", protocol
);
1774 /*****************************************************************************
1775 * WS_EnterSingleProtocolA [internal]
1777 * see function WS_EnterSingleProtocolW
1780 static BOOL
WS_EnterSingleProtocolA( INT protocol
, WSAPROTOCOL_INFOA
* info
)
1782 WSAPROTOCOL_INFOW infow
;
1784 memset( info
, 0, sizeof(WSAPROTOCOL_INFOA
) );
1786 ret
= WS_EnterSingleProtocolW( protocol
, &infow
);
1789 /* convert the structure from W to A */
1790 memcpy( info
, &infow
, FIELD_OFFSET( WSAPROTOCOL_INFOA
, szProtocol
) );
1791 WideCharToMultiByte( CP_ACP
, 0, infow
.szProtocol
, -1,
1792 info
->szProtocol
, WSAPROTOCOL_LEN
+1, NULL
, NULL
);
1798 static INT
WS_EnumProtocols( BOOL unicode
, const INT
*protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
)
1800 INT i
= 0, items
= 0;
1804 LPWSAPROTOCOL_INFOA a
;
1805 LPWSAPROTOCOL_INFOW w
;
1809 if (!protocols
) protocols
= valid_protocols
;
1811 while (protocols
[i
])
1813 if(supported_protocol(protocols
[i
++]))
1817 size
= items
* (unicode
? sizeof(WSAPROTOCOL_INFOW
) : sizeof(WSAPROTOCOL_INFOA
));
1819 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
1820 unicode
, protocols
, buffer
, len
, len
? *len
: 0, items
, size
);
1822 if (*len
< size
|| !buffer
)
1825 WSASetLastError(WSAENOBUFS
);
1826 return SOCKET_ERROR
;
1829 for (i
= items
= 0; protocols
[i
]; i
++)
1831 if (!supported_protocol(protocols
[i
])) continue;
1834 if (WS_EnterSingleProtocolW( protocols
[i
], &info
.w
[items
] ))
1839 if (WS_EnterSingleProtocolA( protocols
[i
], &info
.a
[items
] ))
1846 static BOOL
ws_protocol_info(SOCKET s
, int unicode
, WSAPROTOCOL_INFOW
*buffer
, int *size
)
1850 *size
= unicode
? sizeof(WSAPROTOCOL_INFOW
) : sizeof(WSAPROTOCOL_INFOA
);
1851 memset(buffer
, 0, *size
);
1853 SERVER_START_REQ( get_socket_info
)
1855 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
1856 status
= wine_server_call( req
);
1859 buffer
->iAddressFamily
= convert_af_u2w(reply
->family
);
1860 buffer
->iSocketType
= convert_socktype_u2w(reply
->type
);
1861 buffer
->iProtocol
= convert_proto_u2w(reply
->protocol
);
1868 unsigned int err
= NtStatusToWSAError( status
);
1869 SetLastError( err
== WSAEBADF
? WSAENOTSOCK
: err
);
1874 WS_EnterSingleProtocolW( buffer
->iProtocol
, buffer
);
1876 WS_EnterSingleProtocolA( buffer
->iProtocol
, (WSAPROTOCOL_INFOA
*)buffer
);
1881 /**************************************************************************
1882 * Functions for handling overlapped I/O
1883 **************************************************************************/
1885 /* user APC called upon async completion */
1886 static void WINAPI
ws2_async_apc( void *arg
, IO_STATUS_BLOCK
*iosb
, ULONG reserved
)
1888 ws2_async
*wsa
= arg
;
1890 if (wsa
->completion_func
) wsa
->completion_func( NtStatusToWSAError(iosb
->u
.Status
),
1891 iosb
->Information
, wsa
->user_overlapped
,
1893 HeapFree( GetProcessHeap(), 0, wsa
);
1896 /***********************************************************************
1897 * WS2_recv (INTERNAL)
1899 * Workhorse for both synchronous and asynchronous recv() operations.
1901 static int WS2_recv( int fd
, struct ws2_async
*wsa
)
1903 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1907 union generic_unix_sockaddr unix_sockaddr
;
1910 hdr
.msg_name
= NULL
;
1914 hdr
.msg_namelen
= sizeof(unix_sockaddr
);
1915 hdr
.msg_name
= &unix_sockaddr
;
1918 hdr
.msg_namelen
= 0;
1920 hdr
.msg_iov
= wsa
->iovec
+ wsa
->first_iovec
;
1921 hdr
.msg_iovlen
= wsa
->n_iovecs
- wsa
->first_iovec
;
1922 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1923 hdr
.msg_accrights
= NULL
;
1924 hdr
.msg_accrightslen
= 0;
1926 hdr
.msg_control
= pktbuf
;
1927 hdr
.msg_controllen
= sizeof(pktbuf
);
1931 while ((n
= recvmsg(fd
, &hdr
, wsa
->flags
)) == -1)
1937 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1940 ERR("Message control headers cannot be properly supported on this system.\n");
1941 wsa
->control
->len
= 0;
1944 if (wsa
->control
&& !convert_control_headers(&hdr
, wsa
->control
))
1946 WARN("Application passed insufficient room for control headers.\n");
1947 *wsa
->lpFlags
|= WS_MSG_CTRUNC
;
1953 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1954 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1956 * quoting linux 2.6 net/ipv4/tcp.c:
1957 * "According to UNIX98, msg_name/msg_namelen are ignored
1958 * on connected socket. I was just happy when found this 8) --ANK"
1960 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1961 * connection-oriented sockets, so don't try to update lpFrom.
1963 if (wsa
->addr
&& hdr
.msg_namelen
)
1964 ws_sockaddr_u2ws( &unix_sockaddr
.addr
, wsa
->addr
, wsa
->addrlen
.ptr
);
1969 /***********************************************************************
1970 * WS2_async_recv (INTERNAL)
1972 * Handler for overlapped recv() operations.
1974 static NTSTATUS
WS2_async_recv( void* user
, IO_STATUS_BLOCK
* iosb
, NTSTATUS status
, void **apc
)
1976 ws2_async
* wsa
= user
;
1981 case STATUS_ALERTED
:
1982 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, FILE_READ_DATA
, &fd
, NULL
) ))
1985 result
= WS2_recv( fd
, wsa
);
1986 wine_server_release_fd( wsa
->hSocket
, fd
);
1989 status
= STATUS_SUCCESS
;
1990 _enable_event( wsa
->hSocket
, FD_READ
, 0, 0 );
1994 if (errno
== EAGAIN
)
1996 status
= STATUS_PENDING
;
1997 _enable_event( wsa
->hSocket
, FD_READ
, 0, 0 );
2002 status
= wsaErrStatus();
2007 if (status
!= STATUS_PENDING
)
2009 iosb
->u
.Status
= status
;
2010 iosb
->Information
= result
;
2011 *apc
= ws2_async_apc
;
2016 /* user APC called upon async accept completion */
2017 static void WINAPI
ws2_async_accept_apc( void *arg
, IO_STATUS_BLOCK
*iosb
, ULONG reserved
)
2019 struct ws2_accept_async
*wsa
= arg
;
2021 HeapFree( GetProcessHeap(), 0, wsa
->read
);
2022 HeapFree( GetProcessHeap(), 0, wsa
);
2025 /***********************************************************************
2026 * WS2_async_accept_recv (INTERNAL)
2028 * This function is used to finish the read part of an accept request. It is
2029 * needed to place the completion on the correct socket (listener).
2031 static NTSTATUS
WS2_async_accept_recv( void *arg
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
, void **apc
)
2034 struct ws2_accept_async
*wsa
= arg
;
2036 status
= WS2_async_recv( wsa
->read
, iosb
, status
, &junk
);
2037 if (status
== STATUS_PENDING
)
2040 if (wsa
->user_overlapped
->hEvent
)
2041 SetEvent(wsa
->user_overlapped
->hEvent
);
2043 WS_AddCompletion( HANDLE2SOCKET(wsa
->listen_socket
), wsa
->cvalue
, iosb
->u
.Status
, iosb
->Information
);
2045 *apc
= ws2_async_accept_apc
;
2049 /***********************************************************************
2050 * WS2_async_accept (INTERNAL)
2052 * This is the function called to satisfy the AcceptEx callback
2054 static NTSTATUS
WS2_async_accept( void *arg
, IO_STATUS_BLOCK
*iosb
, NTSTATUS status
, void **apc
)
2056 struct ws2_accept_async
*wsa
= arg
;
2060 TRACE("status: 0x%x listen: %p, accept: %p\n", status
, wsa
->listen_socket
, wsa
->accept_socket
);
2062 if (status
== STATUS_ALERTED
)
2064 SERVER_START_REQ( accept_into_socket
)
2066 req
->lhandle
= wine_server_obj_handle( wsa
->listen_socket
);
2067 req
->ahandle
= wine_server_obj_handle( wsa
->accept_socket
);
2068 status
= wine_server_call( req
);
2072 if (status
== STATUS_CANT_WAIT
)
2073 return STATUS_PENDING
;
2075 if (status
== STATUS_INVALID_HANDLE
)
2077 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2078 status
= STATUS_CANCELLED
;
2081 else if (status
== STATUS_HANDLES_CLOSED
)
2082 status
= STATUS_CANCELLED
; /* strange windows behavior */
2084 if (status
!= STATUS_SUCCESS
)
2087 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2088 addr
= ((char *)wsa
->buf
) + wsa
->data_len
;
2089 len
= wsa
->local_len
- sizeof(int);
2090 WS_getsockname(HANDLE2SOCKET(wsa
->accept_socket
),
2091 (struct WS_sockaddr
*)(addr
+ sizeof(int)), &len
);
2094 addr
+= wsa
->local_len
;
2095 len
= wsa
->remote_len
- sizeof(int);
2096 WS_getpeername(HANDLE2SOCKET(wsa
->accept_socket
),
2097 (struct WS_sockaddr
*)(addr
+ sizeof(int)), &len
);
2103 SERVER_START_REQ( register_async
)
2105 req
->type
= ASYNC_TYPE_READ
;
2106 req
->async
.handle
= wine_server_obj_handle( wsa
->accept_socket
);
2107 req
->async
.callback
= wine_server_client_ptr( WS2_async_accept_recv
);
2108 req
->async
.iosb
= wine_server_client_ptr( iosb
);
2109 req
->async
.arg
= wine_server_client_ptr( wsa
);
2110 status
= wine_server_call( req
);
2114 if (status
!= STATUS_PENDING
)
2117 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2118 * needs to be performed by WS2_async_accept_recv() first. */
2119 return STATUS_MORE_PROCESSING_REQUIRED
;
2122 iosb
->u
.Status
= status
;
2123 iosb
->Information
= 0;
2125 if (wsa
->user_overlapped
->hEvent
)
2126 SetEvent(wsa
->user_overlapped
->hEvent
);
2128 *apc
= ws2_async_accept_apc
;
2132 /***********************************************************************
2133 * WS2_send (INTERNAL)
2135 * Workhorse for both synchronous and asynchronous send() operations.
2137 static int WS2_send( int fd
, struct ws2_async
*wsa
)
2140 union generic_unix_sockaddr unix_addr
;
2143 hdr
.msg_name
= NULL
;
2144 hdr
.msg_namelen
= 0;
2148 hdr
.msg_name
= &unix_addr
;
2149 hdr
.msg_namelen
= ws_sockaddr_ws2u( wsa
->addr
, wsa
->addrlen
.val
, &unix_addr
);
2150 if ( !hdr
.msg_namelen
)
2156 #if defined(HAS_IPX) && defined(SOL_IPX)
2157 if(wsa
->addr
->sa_family
== WS_AF_IPX
)
2159 struct sockaddr_ipx
* uipx
= (struct sockaddr_ipx
*)hdr
.msg_name
;
2161 socklen_t len
= sizeof(int);
2163 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2164 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2165 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2166 * ipx type in the sockaddr_opx structure with the stored value.
2168 if(getsockopt(fd
, SOL_IPX
, IPX_TYPE
, &val
, &len
) != -1)
2169 uipx
->sipx_type
= val
;
2174 hdr
.msg_iov
= wsa
->iovec
+ wsa
->first_iovec
;
2175 hdr
.msg_iovlen
= wsa
->n_iovecs
- wsa
->first_iovec
;
2176 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2177 hdr
.msg_accrights
= NULL
;
2178 hdr
.msg_accrightslen
= 0;
2180 hdr
.msg_control
= NULL
;
2181 hdr
.msg_controllen
= 0;
2185 while ((ret
= sendmsg(fd
, &hdr
, wsa
->flags
)) == -1)
2192 while (wsa
->first_iovec
< wsa
->n_iovecs
&& wsa
->iovec
[wsa
->first_iovec
].iov_len
<= n
)
2193 n
-= wsa
->iovec
[wsa
->first_iovec
++].iov_len
;
2194 if (wsa
->first_iovec
< wsa
->n_iovecs
)
2196 wsa
->iovec
[wsa
->first_iovec
].iov_base
= (char*)wsa
->iovec
[wsa
->first_iovec
].iov_base
+ n
;
2197 wsa
->iovec
[wsa
->first_iovec
].iov_len
-= n
;
2202 /***********************************************************************
2203 * WS2_async_send (INTERNAL)
2205 * Handler for overlapped send() operations.
2207 static NTSTATUS
WS2_async_send(void* user
, IO_STATUS_BLOCK
* iosb
, NTSTATUS status
, void **apc
)
2209 ws2_async
* wsa
= user
;
2214 case STATUS_ALERTED
:
2215 if ( wsa
->n_iovecs
<= wsa
->first_iovec
)
2218 status
= STATUS_SUCCESS
;
2221 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, FILE_WRITE_DATA
, &fd
, NULL
) ))
2224 /* check to see if the data is ready (non-blocking) */
2225 result
= WS2_send( fd
, wsa
);
2226 wine_server_release_fd( wsa
->hSocket
, fd
);
2230 if (wsa
->first_iovec
< wsa
->n_iovecs
)
2231 status
= STATUS_PENDING
;
2233 status
= STATUS_SUCCESS
;
2235 iosb
->Information
+= result
;
2237 else if (errno
== EAGAIN
)
2239 status
= STATUS_PENDING
;
2243 status
= wsaErrStatus();
2247 if (status
!= STATUS_PENDING
)
2249 iosb
->u
.Status
= status
;
2250 *apc
= ws2_async_apc
;
2255 /***********************************************************************
2256 * WS2_async_shutdown (INTERNAL)
2258 * Handler for shutdown() operations on overlapped sockets.
2260 static NTSTATUS
WS2_async_shutdown( void* user
, PIO_STATUS_BLOCK iosb
, NTSTATUS status
, void **apc
)
2262 ws2_async
* wsa
= user
;
2267 case STATUS_ALERTED
:
2268 if ((status
= wine_server_handle_to_fd( wsa
->hSocket
, 0, &fd
, NULL
) ))
2271 switch ( wsa
->type
)
2273 case ASYNC_TYPE_READ
: err
= shutdown( fd
, 0 ); break;
2274 case ASYNC_TYPE_WRITE
: err
= shutdown( fd
, 1 ); break;
2276 status
= err
? wsaErrStatus() : STATUS_SUCCESS
;
2277 wine_server_release_fd( wsa
->hSocket
, fd
);
2280 iosb
->u
.Status
= status
;
2281 iosb
->Information
= 0;
2282 *apc
= ws2_async_apc
;
2286 /***********************************************************************
2287 * WS2_register_async_shutdown (INTERNAL)
2289 * Helper function for WS_shutdown() on overlapped sockets.
2291 static int WS2_register_async_shutdown( SOCKET s
, int type
)
2293 struct ws2_async
*wsa
;
2296 TRACE("s %ld type %d\n", s
, type
);
2298 wsa
= HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async
, iovec
[1] ));
2302 wsa
->hSocket
= SOCKET2HANDLE(s
);
2304 wsa
->completion_func
= NULL
;
2306 SERVER_START_REQ( register_async
)
2309 req
->async
.handle
= wine_server_obj_handle( wsa
->hSocket
);
2310 req
->async
.callback
= wine_server_client_ptr( WS2_async_shutdown
);
2311 req
->async
.iosb
= wine_server_client_ptr( &wsa
->local_iosb
);
2312 req
->async
.arg
= wine_server_client_ptr( wsa
);
2313 req
->async
.cvalue
= 0;
2314 status
= wine_server_call( req
);
2318 if (status
!= STATUS_PENDING
)
2320 HeapFree( GetProcessHeap(), 0, wsa
);
2321 return NtStatusToWSAError( status
);
2326 /***********************************************************************
2329 SOCKET WINAPI
WS_accept(SOCKET s
, struct WS_sockaddr
*addr
, int *addrlen32
)
2335 TRACE("socket %04lx\n", s
);
2336 status
= _is_blocking(s
, &is_blocking
);
2340 return INVALID_SOCKET
;
2344 /* try accepting first (if there is a deferred connection) */
2345 SERVER_START_REQ( accept_socket
)
2347 req
->lhandle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
2348 req
->access
= GENERIC_READ
|GENERIC_WRITE
|SYNCHRONIZE
;
2349 req
->attributes
= OBJ_INHERIT
;
2350 status
= wine_server_call( req
);
2351 as
= HANDLE2SOCKET( wine_server_ptr_handle( reply
->handle
));
2356 if (addr
&& WS_getpeername(as
, addr
, addrlen32
))
2359 return SOCKET_ERROR
;
2363 if (is_blocking
&& status
== STATUS_CANT_WAIT
)
2365 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
2367 do_block(fd
, POLLIN
, -1);
2368 _sync_sock_state(s
); /* let wineserver notice connection */
2369 release_sock_fd( s
, fd
);
2371 } while (is_blocking
&& status
== STATUS_CANT_WAIT
);
2374 return INVALID_SOCKET
;
2377 /***********************************************************************
2380 static BOOL WINAPI
WS2_AcceptEx(SOCKET listener
, SOCKET acceptor
, PVOID dest
, DWORD dest_len
,
2381 DWORD local_addr_len
, DWORD rem_addr_len
, LPDWORD received
,
2382 LPOVERLAPPED overlapped
)
2385 struct ws2_accept_async
*wsa
;
2387 ULONG_PTR cvalue
= (overlapped
&& ((ULONG_PTR
)overlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)overlapped
: 0;
2389 TRACE("(%lx, %lx, %p, %d, %d, %d, %p, %p)\n", listener
, acceptor
, dest
, dest_len
, local_addr_len
,
2390 rem_addr_len
, received
, overlapped
);
2394 SetLastError(WSAEINVAL
);
2400 SetLastError(WSA_INVALID_PARAMETER
);
2406 SetLastError(WSAEFAULT
);
2410 fd
= get_sock_fd( listener
, FILE_READ_DATA
, NULL
);
2413 SetLastError(WSAENOTSOCK
);
2416 release_sock_fd( listener
, fd
);
2418 fd
= get_sock_fd( acceptor
, FILE_READ_DATA
, NULL
);
2421 SetLastError(WSAENOTSOCK
);
2424 release_sock_fd( acceptor
, fd
);
2426 wsa
= HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa
) );
2429 SetLastError(WSAEFAULT
);
2433 wsa
->listen_socket
= SOCKET2HANDLE(listener
);
2434 wsa
->accept_socket
= SOCKET2HANDLE(acceptor
);
2435 wsa
->user_overlapped
= overlapped
;
2436 wsa
->cvalue
= cvalue
;
2438 wsa
->data_len
= dest_len
;
2439 wsa
->local_len
= local_addr_len
;
2440 wsa
->remote_len
= rem_addr_len
;
2445 /* set up a read request if we need it */
2446 wsa
->read
= HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async
, iovec
[1]) );
2449 HeapFree( GetProcessHeap(), 0, wsa
);
2450 SetLastError(WSAEFAULT
);
2454 wsa
->read
->hSocket
= wsa
->accept_socket
;
2455 wsa
->read
->flags
= 0;
2456 wsa
->read
->lpFlags
= &wsa
->read
->flags
;
2457 wsa
->read
->addr
= NULL
;
2458 wsa
->read
->addrlen
.ptr
= NULL
;
2459 wsa
->read
->control
= NULL
;
2460 wsa
->read
->n_iovecs
= 1;
2461 wsa
->read
->first_iovec
= 0;
2462 wsa
->read
->iovec
[0].iov_base
= wsa
->buf
;
2463 wsa
->read
->iovec
[0].iov_len
= wsa
->data_len
;
2466 SERVER_START_REQ( register_async
)
2468 req
->type
= ASYNC_TYPE_READ
;
2469 req
->async
.handle
= wine_server_obj_handle( SOCKET2HANDLE(listener
) );
2470 req
->async
.callback
= wine_server_client_ptr( WS2_async_accept
);
2471 req
->async
.iosb
= wine_server_client_ptr( overlapped
);
2472 req
->async
.arg
= wine_server_client_ptr( wsa
);
2473 req
->async
.cvalue
= cvalue
;
2474 /* We don't set event since we may also have to read */
2475 status
= wine_server_call( req
);
2479 if(status
!= STATUS_PENDING
)
2481 HeapFree( GetProcessHeap(), 0, wsa
->read
);
2482 HeapFree( GetProcessHeap(), 0, wsa
);
2485 SetLastError( NtStatusToWSAError(status
) );
2489 /***********************************************************************
2490 * GetAcceptExSockaddrs
2492 static void WINAPI
WS2_GetAcceptExSockaddrs(PVOID buffer
, DWORD data_size
, DWORD local_size
, DWORD remote_size
,
2493 struct WS_sockaddr
**local_addr
, LPINT local_addr_len
,
2494 struct WS_sockaddr
**remote_addr
, LPINT remote_addr_len
)
2496 char *cbuf
= buffer
;
2497 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer
, data_size
, local_size
, remote_size
, local_addr
,
2498 local_addr_len
, remote_addr
, remote_addr_len
);
2501 *local_addr_len
= *(int *) cbuf
;
2502 *local_addr
= (struct WS_sockaddr
*)(cbuf
+ sizeof(int));
2506 *remote_addr_len
= *(int *) cbuf
;
2507 *remote_addr
= (struct WS_sockaddr
*)(cbuf
+ sizeof(int));
2510 /***********************************************************************
2513 int WINAPI
WSASendMsg( SOCKET s
, LPWSAMSG msg
, DWORD dwFlags
, LPDWORD lpNumberOfBytesSent
,
2514 LPWSAOVERLAPPED lpOverlapped
,
2515 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
2519 SetLastError( WSAEFAULT
);
2520 return SOCKET_ERROR
;
2523 return WS2_sendto( s
, msg
->lpBuffers
, msg
->dwBufferCount
, lpNumberOfBytesSent
,
2524 dwFlags
, msg
->name
, msg
->namelen
,
2525 lpOverlapped
, lpCompletionRoutine
);
2528 /***********************************************************************
2531 * Perform a receive operation that is capable of returning message
2532 * control headers. It is important to note that the WSAMSG parameter
2533 * must remain valid throughout the operation, even when an overlapped
2534 * receive is performed.
2536 static int WINAPI
WS2_WSARecvMsg( SOCKET s
, LPWSAMSG msg
, LPDWORD lpNumberOfBytesRecvd
,
2537 LPWSAOVERLAPPED lpOverlapped
,
2538 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
2542 SetLastError( WSAEFAULT
);
2543 return SOCKET_ERROR
;
2546 return WS2_recv_base( s
, msg
->lpBuffers
, msg
->dwBufferCount
, lpNumberOfBytesRecvd
,
2547 &msg
->dwFlags
, msg
->name
, &msg
->namelen
,
2548 lpOverlapped
, lpCompletionRoutine
, &msg
->Control
);
2551 /***********************************************************************
2552 * interface_bind (INTERNAL)
2554 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
2555 * operating only on the specified interface. This restriction consists of two components:
2556 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
2557 * 2) An incoming packet restriction dropping packets not meant for the interface.
2558 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
2559 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
2560 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
2561 * to receive broadcast packets on a socket that is bound to a specific network interface.
2563 static BOOL
interface_bind( SOCKET s
, int fd
, struct sockaddr
*addr
)
2565 struct sockaddr_in
*in_sock
= (struct sockaddr_in
*) addr
;
2566 unsigned int sock_type
= 0;
2567 socklen_t optlen
= sizeof(sock_type
);
2568 in_addr_t bind_addr
= in_sock
->sin_addr
.s_addr
;
2569 PIP_ADAPTER_INFO adapters
= NULL
, adapter
;
2574 if (bind_addr
== htonl(INADDR_ANY
) || bind_addr
== htonl(INADDR_LOOPBACK
))
2575 return FALSE
; /* Not binding to a network adapter, special interface binding unnecessary. */
2576 if (getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, &sock_type
, &optlen
) == -1 || sock_type
!= SOCK_DGRAM
)
2577 return FALSE
; /* Special interface binding is only necessary for UDP datagrams. */
2578 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
2580 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
2581 if (adapters
== NULL
|| GetAdaptersInfo(adapters
, &adap_size
) != NO_ERROR
)
2583 /* Search the IPv4 adapter list for the appropriate binding interface */
2584 for (adapter
= adapters
; adapter
!= NULL
; adapter
= adapter
->Next
)
2586 in_addr_t adapter_addr
= (in_addr_t
) inet_addr(adapter
->IpAddressList
.IpAddress
.String
);
2588 if (bind_addr
== adapter_addr
)
2590 #if defined(IP_BOUND_IF)
2591 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
2592 if (setsockopt(fd
, IPPROTO_IP
, IP_BOUND_IF
, &adapter
->Index
, sizeof(adapter
->Index
)) != 0)
2595 #elif defined(LINUX_BOUND_IF)
2596 in_addr_t ifindex
= (in_addr_t
) htonl(adapter
->Index
);
2597 struct interface_filter specific_interface_filter
;
2598 struct sock_fprog filter_prog
;
2600 if (setsockopt(fd
, IPPROTO_IP
, IP_UNICAST_IF
, &ifindex
, sizeof(ifindex
)) != 0)
2601 goto cleanup
; /* Failed to suggest egress interface */
2602 specific_interface_filter
= generic_interface_filter
;
2603 specific_interface_filter
.iface_rule
.k
= adapter
->Index
;
2604 specific_interface_filter
.ip_rule
.k
= htonl(adapter_addr
);
2605 filter_prog
.len
= sizeof(generic_interface_filter
)/sizeof(struct sock_filter
);
2606 filter_prog
.filter
= (struct sock_filter
*) &specific_interface_filter
;
2607 if (setsockopt(fd
, SOL_SOCKET
, SO_ATTACH_FILTER
, &filter_prog
, sizeof(filter_prog
)) != 0)
2608 goto cleanup
; /* Failed to specify incoming packet filter */
2611 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
2612 "receiving broadcast packets will not work on socket %04lx.\n", s
);
2617 /* Will soon be switching to INADDR_ANY: permit address reuse */
2618 if (ret
&& setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &enable
, sizeof(enable
)) == 0)
2619 TRACE("Socket %04lx bound to interface index %d\n", s
, adapter
->Index
);
2625 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s
);
2626 HeapFree(GetProcessHeap(), 0, adapters
);
2630 /***********************************************************************
2633 int WINAPI
WS_bind(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
)
2635 int fd
= get_sock_fd( s
, 0, NULL
);
2636 int res
= SOCKET_ERROR
;
2638 TRACE("socket %04lx, ptr %p %s, length %d\n", s
, name
, debugstr_sockaddr(name
), namelen
);
2642 if (!name
|| (name
->sa_family
&& !supported_pf(name
->sa_family
)))
2644 SetLastError(WSAEAFNOSUPPORT
);
2648 union generic_unix_sockaddr uaddr
;
2649 unsigned int uaddrlen
= ws_sockaddr_ws2u(name
, namelen
, &uaddr
);
2652 SetLastError(WSAEFAULT
);
2657 const struct sockaddr_in6
*in6
= (const struct sockaddr_in6
*) &uaddr
;
2658 if (name
->sa_family
== WS_AF_INET6
&&
2659 !memcmp(&in6
->sin6_addr
, &in6addr_any
, sizeof(struct in6_addr
)))
2662 if (setsockopt(fd
, IPPROTO_IPV6
, IPV6_V6ONLY
, &enable
, sizeof(enable
)) == -1)
2664 release_sock_fd( s
, fd
);
2665 SetLastError(WSAEAFNOSUPPORT
);
2666 return SOCKET_ERROR
;
2670 if (name
->sa_family
== WS_AF_INET
)
2672 struct sockaddr_in
*in4
= (struct sockaddr_in
*) &uaddr
;
2673 if (memcmp(&in4
->sin_addr
, magic_loopback_addr
, 4) == 0)
2675 /* Trying to bind to the default host interface, using
2676 * INADDR_ANY instead*/
2677 WARN("Trying to bind to magic IP address, using "
2678 "INADDR_ANY instead.\n");
2679 in4
->sin_addr
.s_addr
= htonl(INADDR_ANY
);
2681 else if (interface_bind(s
, fd
, &uaddr
.addr
))
2682 in4
->sin_addr
.s_addr
= htonl(INADDR_ANY
);
2684 if (bind(fd
, &uaddr
.addr
, uaddrlen
) < 0)
2686 int loc_errno
= errno
;
2687 WARN("\tfailure - errno = %i\n", errno
);
2692 SetLastError(WSAENOTSOCK
);
2695 SetLastError(WSAEINVAL
);
2700 socklen_t optlen
= sizeof(optval
);
2701 /* Windows >= 2003 will return different results depending on
2702 * SO_REUSEADDR, WSAEACCES may be returned representing that
2703 * the socket hijacking protection prevented the bind */
2704 if (!getsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *)&optval
, &optlen
) && optval
)
2706 SetLastError(WSAEACCES
);
2712 SetLastError(wsaErrno());
2718 res
=0; /* success */
2722 release_sock_fd( s
, fd
);
2727 /***********************************************************************
2728 * closesocket (WS2_32.3)
2730 int WINAPI
WS_closesocket(SOCKET s
)
2732 TRACE("socket %04lx\n", s
);
2733 if (CloseHandle(SOCKET2HANDLE(s
))) return 0;
2734 return SOCKET_ERROR
;
2737 static int do_connect(int fd
, const struct WS_sockaddr
* name
, int namelen
)
2739 union generic_unix_sockaddr uaddr
;
2740 unsigned int uaddrlen
= ws_sockaddr_ws2u(name
, namelen
, &uaddr
);
2745 if (name
->sa_family
== WS_AF_INET
)
2747 struct sockaddr_in
*in4
= (struct sockaddr_in
*) &uaddr
;
2748 if (memcmp(&in4
->sin_addr
, magic_loopback_addr
, 4) == 0)
2750 /* Trying to connect to magic replace-loopback address,
2751 * assuming we really want to connect to localhost */
2752 TRACE("Trying to connect to magic IP address, using "
2753 "INADDR_LOOPBACK instead.\n");
2754 in4
->sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
2758 if (connect(fd
, &uaddr
.addr
, uaddrlen
) == 0)
2764 /***********************************************************************
2765 * connect (WS2_32.4)
2767 int WINAPI
WS_connect(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
)
2769 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
2771 TRACE("socket %04lx, ptr %p %s, length %d\n", s
, name
, debugstr_sockaddr(name
), namelen
);
2777 int ret
= do_connect(fd
, name
, namelen
);
2779 goto connect_success
;
2781 if (ret
== WSAEINPROGRESS
)
2783 /* tell wineserver that a connection is in progress */
2784 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
2786 FD_WINE_CONNECTED
|FD_WINE_LISTENING
);
2787 status
= _is_blocking( s
, &is_blocking
);
2790 release_sock_fd( s
, fd
);
2791 set_error( status
);
2792 return SOCKET_ERROR
;
2798 do_block(fd
, POLLIN
| POLLOUT
, -1);
2799 _sync_sock_state(s
); /* let wineserver notice connection */
2800 /* retrieve any error codes from it */
2801 result
= _get_sock_error(s
, FD_CONNECT_BIT
);
2803 SetLastError(NtStatusToWSAError(result
));
2806 goto connect_success
;
2811 SetLastError(WSAEWOULDBLOCK
);
2818 release_sock_fd( s
, fd
);
2820 return SOCKET_ERROR
;
2823 release_sock_fd( s
, fd
);
2824 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
2825 FD_WINE_CONNECTED
|FD_READ
|FD_WRITE
,
2826 FD_CONNECT
|FD_WINE_LISTENING
);
2830 /***********************************************************************
2831 * WSAConnect (WS2_32.30)
2833 int WINAPI
WSAConnect( SOCKET s
, const struct WS_sockaddr
* name
, int namelen
,
2834 LPWSABUF lpCallerData
, LPWSABUF lpCalleeData
,
2835 LPQOS lpSQOS
, LPQOS lpGQOS
)
2837 if ( lpCallerData
|| lpCalleeData
|| lpSQOS
|| lpGQOS
)
2838 FIXME("unsupported parameters!\n");
2839 return WS_connect( s
, name
, namelen
);
2842 /***********************************************************************
2845 static BOOL WINAPI
WS2_ConnectEx(SOCKET s
, const struct WS_sockaddr
* name
, int namelen
,
2846 PVOID sendBuf
, DWORD sendBufLen
, LPDWORD sent
, LPOVERLAPPED ov
)
2848 int fd
, ret
, status
;
2849 union generic_unix_sockaddr uaddr
;
2850 socklen_t uaddrlen
= sizeof(uaddr
);
2854 SetLastError( ERROR_INVALID_PARAMETER
);
2858 fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
);
2861 SetLastError( WSAENOTSOCK
);
2865 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
2866 s
, name
, debugstr_sockaddr(name
), namelen
, sendBuf
, sendBufLen
, ov
);
2868 if (getsockname(fd
, &uaddr
.addr
, &uaddrlen
) != 0)
2870 SetLastError(wsaErrno());
2873 else if (!is_sockaddr_bound(&uaddr
.addr
, uaddrlen
))
2875 SetLastError(WSAEINVAL
);
2879 ret
= do_connect(fd
, name
, namelen
);
2884 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
2885 FD_WINE_CONNECTED
|FD_READ
|FD_WRITE
,
2886 FD_CONNECT
|FD_WINE_LISTENING
);
2888 wsabuf
.len
= sendBufLen
;
2889 wsabuf
.buf
= (char*) sendBuf
;
2891 /* WSASend takes care of completion if need be */
2892 if (WSASend(s
, &wsabuf
, sendBuf
? 1 : 0, sent
, 0, ov
, NULL
) != SOCKET_ERROR
)
2893 goto connection_success
;
2895 else if (ret
== WSAEINPROGRESS
)
2897 struct ws2_async
*wsa
;
2898 ULONG_PTR cvalue
= (((ULONG_PTR
)ov
->hEvent
& 1) == 0) ? (ULONG_PTR
)ov
: 0;
2900 _enable_event(SOCKET2HANDLE(s
), FD_CONNECT
|FD_READ
|FD_WRITE
,
2902 FD_WINE_CONNECTED
|FD_WINE_LISTENING
);
2904 /* Indirectly call WSASend */
2905 if (!(wsa
= HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async
, iovec
[1] ))))
2907 SetLastError(WSAEFAULT
);
2911 IO_STATUS_BLOCK
*iosb
= (IO_STATUS_BLOCK
*)ov
;
2912 iosb
->u
.Status
= STATUS_PENDING
;
2913 iosb
->Information
= 0;
2915 wsa
->hSocket
= SOCKET2HANDLE(s
);
2917 wsa
->addrlen
.val
= 0;
2919 wsa
->lpFlags
= &wsa
->flags
;
2920 wsa
->control
= NULL
;
2921 wsa
->n_iovecs
= sendBuf
? 1 : 0;
2922 wsa
->first_iovec
= 0;
2923 wsa
->completion_func
= NULL
;
2924 wsa
->iovec
[0].iov_base
= sendBuf
;
2925 wsa
->iovec
[0].iov_len
= sendBufLen
;
2927 SERVER_START_REQ( register_async
)
2929 req
->type
= ASYNC_TYPE_WRITE
;
2930 req
->async
.handle
= wine_server_obj_handle( wsa
->hSocket
);
2931 req
->async
.callback
= wine_server_client_ptr( WS2_async_send
);
2932 req
->async
.iosb
= wine_server_client_ptr( iosb
);
2933 req
->async
.arg
= wine_server_client_ptr( wsa
);
2934 req
->async
.event
= wine_server_obj_handle( ov
->hEvent
);
2935 req
->async
.cvalue
= cvalue
;
2936 status
= wine_server_call( req
);
2940 if (status
!= STATUS_PENDING
) HeapFree(GetProcessHeap(), 0, wsa
);
2942 /* If the connect already failed */
2943 if (status
== STATUS_PIPE_DISCONNECTED
)
2944 status
= _get_sock_error(s
, FD_CONNECT_BIT
);
2945 SetLastError( NtStatusToWSAError(status
) );
2953 release_sock_fd( s
, fd
);
2957 release_sock_fd( s
, fd
);
2962 /***********************************************************************
2963 * getpeername (WS2_32.5)
2965 int WINAPI
WS_getpeername(SOCKET s
, struct WS_sockaddr
*name
, int *namelen
)
2970 TRACE("socket: %04lx, ptr %p, len %08x\n", s
, name
, namelen
? *namelen
: 0);
2972 fd
= get_sock_fd( s
, 0, NULL
);
2977 union generic_unix_sockaddr uaddr
;
2978 socklen_t uaddrlen
= sizeof(uaddr
);
2980 if (getpeername(fd
, &uaddr
.addr
, &uaddrlen
) == 0)
2982 if (!name
|| !namelen
)
2983 SetLastError(WSAEFAULT
);
2984 else if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
2985 /* The buffer was too small */
2986 SetLastError(WSAEFAULT
);
2991 SetLastError(wsaErrno());
2992 release_sock_fd( s
, fd
);
2997 /***********************************************************************
2998 * getsockname (WS2_32.6)
3000 int WINAPI
WS_getsockname(SOCKET s
, struct WS_sockaddr
*name
, int *namelen
)
3005 TRACE("socket: %04lx, ptr %p, len %08x\n", s
, name
, namelen
? *namelen
: 0);
3007 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3008 if( (name
== NULL
) || (namelen
== NULL
) )
3010 SetLastError( WSAEFAULT
);
3011 return SOCKET_ERROR
;
3014 fd
= get_sock_fd( s
, 0, NULL
);
3019 union generic_unix_sockaddr uaddr
;
3020 socklen_t uaddrlen
= sizeof(uaddr
);
3022 if (getsockname(fd
, &uaddr
.addr
, &uaddrlen
) != 0)
3024 SetLastError(wsaErrno());
3026 else if (!is_sockaddr_bound(&uaddr
.addr
, uaddrlen
))
3028 SetLastError(WSAEINVAL
);
3030 else if (ws_sockaddr_u2ws(&uaddr
.addr
, name
, namelen
) != 0)
3032 /* The buffer was too small */
3033 SetLastError(WSAEFAULT
);
3038 TRACE("=> %s\n", debugstr_sockaddr(name
));
3040 release_sock_fd( s
, fd
);
3045 /***********************************************************************
3046 * getsockopt (WS2_32.7)
3048 INT WINAPI
WS_getsockopt(SOCKET s
, INT level
,
3049 INT optname
, char *optval
, INT
*optlen
)
3054 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
3055 s
, level
, optname
, optval
, optlen
? *optlen
: 0);
3063 /* Handle common cases. The special cases are below, sorted
3065 case WS_SO_BROADCAST
:
3068 case WS_SO_KEEPALIVE
:
3069 case WS_SO_OOBINLINE
:
3071 case WS_SO_REUSEADDR
:
3073 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3074 return SOCKET_ERROR
;
3075 convert_sockopt(&level
, &optname
);
3076 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3078 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3081 release_sock_fd( s
, fd
);
3083 case WS_SO_ACCEPTCONN
:
3084 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3085 return SOCKET_ERROR
;
3086 if (getsockopt(fd
, SOL_SOCKET
, SO_ACCEPTCONN
, optval
, (socklen_t
*)optlen
) != 0 )
3088 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3093 /* BSD returns != 0 while Windows return exact == 1 */
3094 if (*(int *)optval
) *(int *)optval
= 1;
3096 release_sock_fd( s
, fd
);
3098 case WS_SO_DONTLINGER
:
3100 struct linger lingval
;
3101 socklen_t len
= sizeof(struct linger
);
3103 if (!optlen
|| *optlen
< sizeof(BOOL
)|| !optval
)
3105 SetLastError(WSAEFAULT
);
3106 return SOCKET_ERROR
;
3108 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3109 return SOCKET_ERROR
;
3111 if (getsockopt(fd
, SOL_SOCKET
, SO_LINGER
, &lingval
, &len
) != 0 )
3113 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3118 *(BOOL
*)optval
= !lingval
.l_onoff
;
3119 *optlen
= sizeof(BOOL
);
3122 release_sock_fd( s
, fd
);
3126 case WS_SO_CONNECT_TIME
:
3128 static int pretendtime
= 0;
3129 struct WS_sockaddr addr
;
3130 int len
= sizeof(addr
);
3132 if (!optlen
|| *optlen
< sizeof(DWORD
) || !optval
)
3134 SetLastError(WSAEFAULT
);
3135 return SOCKET_ERROR
;
3137 if (WS_getpeername(s
, &addr
, &len
) == SOCKET_ERROR
)
3138 *(DWORD
*)optval
= ~0u;
3141 if (!pretendtime
) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3142 *(DWORD
*)optval
= pretendtime
++;
3144 *optlen
= sizeof(DWORD
);
3147 /* As mentioned in setsockopt, Windows ignores this, so we
3148 * always return true here */
3149 case WS_SO_DONTROUTE
:
3150 if (!optlen
|| *optlen
< sizeof(BOOL
) || !optval
)
3152 SetLastError(WSAEFAULT
);
3153 return SOCKET_ERROR
;
3155 *(BOOL
*)optval
= TRUE
;
3156 *optlen
= sizeof(BOOL
);
3161 struct linger lingval
;
3163 socklen_t len
= sizeof(struct linger
), slen
= sizeof(int);
3165 /* struct linger and LINGER have different sizes */
3166 if (!optlen
|| *optlen
< sizeof(LINGER
) || !optval
)
3168 SetLastError(WSAEFAULT
);
3169 return SOCKET_ERROR
;
3171 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3172 return SOCKET_ERROR
;
3174 if ((getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, &so_type
, &slen
) == 0 && so_type
== SOCK_DGRAM
))
3176 SetLastError(WSAENOPROTOOPT
);
3179 else if (getsockopt(fd
, SOL_SOCKET
, SO_LINGER
, &lingval
, &len
) != 0)
3181 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3186 ((LINGER
*)optval
)->l_onoff
= lingval
.l_onoff
;
3187 ((LINGER
*)optval
)->l_linger
= lingval
.l_linger
;
3188 *optlen
= sizeof(struct linger
);
3191 release_sock_fd( s
, fd
);
3195 case WS_SO_MAX_MSG_SIZE
:
3196 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
3198 SetLastError(WSAEFAULT
);
3199 return SOCKET_ERROR
;
3201 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3202 *(int *)optval
= 65507;
3203 *optlen
= sizeof(int);
3206 /* SO_OPENTYPE does not require a valid socket handle. */
3207 case WS_SO_OPENTYPE
:
3208 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
3210 SetLastError(WSAEFAULT
);
3211 return SOCKET_ERROR
;
3213 *(int *)optval
= get_per_thread_data()->opentype
;
3214 *optlen
= sizeof(int);
3215 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval
) );
3217 case WS_SO_PROTOCOL_INFOA
:
3218 case WS_SO_PROTOCOL_INFOW
:
3221 WSAPROTOCOL_INFOW infow
;
3223 ret
= ws_protocol_info(s
, optname
== WS_SO_PROTOCOL_INFOW
, &infow
, &size
);
3226 if (!optlen
|| !optval
|| *optlen
< size
)
3228 if(optlen
) *optlen
= size
;
3230 SetLastError(WSAEFAULT
);
3233 memcpy(optval
, &infow
, size
);
3235 return ret
? 0 : SOCKET_ERROR
;
3238 case WS_SO_RCVTIMEO
:
3241 case WS_SO_SNDTIMEO
:
3243 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3246 socklen_t len
= sizeof(struct timeval
);
3248 if (!optlen
|| *optlen
< sizeof(int)|| !optval
)
3250 SetLastError(WSAEFAULT
);
3251 return SOCKET_ERROR
;
3253 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3254 return SOCKET_ERROR
;
3256 convert_sockopt(&level
, &optname
);
3257 if (getsockopt(fd
, level
, optname
, &tv
, &len
) != 0 )
3259 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3264 *(int *)optval
= tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000;
3265 *optlen
= sizeof(int);
3268 release_sock_fd( s
, fd
);
3274 if (!optlen
|| *optlen
< sizeof(int) || !optval
)
3276 SetLastError(WSAEFAULT
);
3277 return SOCKET_ERROR
;
3279 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3280 return SOCKET_ERROR
;
3282 if (getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, optval
, (socklen_t
*)optlen
) != 0 )
3284 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3288 (*(int *)optval
) = convert_socktype_u2w(*(int *)optval
);
3290 release_sock_fd( s
, fd
);
3294 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname
);
3295 SetLastError(WSAENOPROTOOPT
);
3296 return SOCKET_ERROR
;
3297 } /* end switch(optname) */
3298 }/* end case WS_SOL_SOCKET */
3300 case WS_NSPROTO_IPX
:
3302 struct WS_sockaddr_ipx addr
;
3303 IPX_ADDRESS_DATA
*data
;
3308 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
3310 if(getsockopt(fd
, SOL_IPX
, IPX_TYPE
, optval
, (socklen_t
*)optlen
) == -1)
3317 socklen_t len
=sizeof(struct ipx
);
3318 if(getsockopt(fd
, 0, SO_DEFAULT_HEADERS
, &val
, &len
) == -1 )
3321 *optval
= (int)val
.ipx_pt
;
3324 TRACE("ptype: %d (fd: %d)\n", *(int*)optval
, fd
);
3325 release_sock_fd( s
, fd
);
3330 * On a Win2000 system with one network card there are usually
3331 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
3332 * Using this call you can then retrieve info about this all.
3333 * In case of Linux it is a bit different. Usually you have
3334 * only "one" device active and further it is not possible to
3335 * query things like the linkspeed.
3337 FIXME("IPX_ADDRESS\n");
3338 namelen
= sizeof(struct WS_sockaddr_ipx
);
3339 memset(&addr
, 0, sizeof(struct WS_sockaddr_ipx
));
3340 WS_getsockname(s
, (struct WS_sockaddr
*)&addr
, &namelen
);
3342 data
= (IPX_ADDRESS_DATA
*)optval
;
3343 memcpy(data
->nodenum
,addr
.sa_nodenum
,sizeof(data
->nodenum
));
3344 memcpy(data
->netnum
,addr
.sa_netnum
,sizeof(data
->netnum
));
3345 data
->adapternum
= 0;
3346 data
->wan
= FALSE
; /* We are not on a wan for now .. */
3347 data
->status
= FALSE
; /* Since we are not on a wan, the wan link isn't up */
3348 data
->maxpkt
= 1467; /* This value is the default one, at least on Win2k/WinXP */
3349 data
->linkspeed
= 100000; /* Set the line speed in 100bit/s to 10 Mbit;
3350 * note 1MB = 1000kB in this case */
3353 case IPX_MAX_ADAPTER_NUM
:
3354 FIXME("IPX_MAX_ADAPTER_NUM\n");
3355 *(int*)optval
= 1; /* As noted under IPX_ADDRESS we have just one card. */
3359 FIXME("IPX optname:%x\n", optname
);
3360 return SOCKET_ERROR
;
3361 }/* end switch(optname) */
3362 } /* end case WS_NSPROTO_IPX */
3366 #define MAX_IRDA_DEVICES 10
3371 case WS_IRLMP_ENUMDEVICES
:
3373 char buf
[sizeof(struct irda_device_list
) +
3374 (MAX_IRDA_DEVICES
- 1) * sizeof(struct irda_device_info
)];
3376 socklen_t len
= sizeof(buf
);
3378 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3379 return SOCKET_ERROR
;
3380 res
= getsockopt( fd
, SOL_IRLMP
, IRLMP_ENUMDEVICES
, buf
, &len
);
3381 release_sock_fd( s
, fd
);
3384 SetLastError(wsaErrno());
3385 return SOCKET_ERROR
;
3389 struct irda_device_list
*src
= (struct irda_device_list
*)buf
;
3390 DEVICELIST
*dst
= (DEVICELIST
*)optval
;
3391 INT needed
= sizeof(DEVICELIST
);
3395 needed
+= (src
->len
- 1) * sizeof(IRDA_DEVICE_INFO
);
3396 if (*optlen
< needed
)
3398 SetLastError(WSAEFAULT
);
3399 return SOCKET_ERROR
;
3402 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src
->len
);
3403 dst
->numDevice
= src
->len
;
3404 for (i
= 0; i
< src
->len
; i
++)
3406 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
3407 src
->dev
[i
].saddr
, src
->dev
[i
].daddr
,
3408 src
->dev
[i
].info
, src
->dev
[i
].hints
[0],
3409 src
->dev
[i
].hints
[1]);
3410 memcpy( dst
->Device
[i
].irdaDeviceID
,
3412 sizeof(dst
->Device
[i
].irdaDeviceID
) ) ;
3413 memcpy( dst
->Device
[i
].irdaDeviceName
,
3415 sizeof(dst
->Device
[i
].irdaDeviceName
) ) ;
3416 memcpy( &dst
->Device
[i
].irdaDeviceHints1
,
3417 &src
->dev
[i
].hints
[0],
3418 sizeof(dst
->Device
[i
].irdaDeviceHints1
) ) ;
3419 memcpy( &dst
->Device
[i
].irdaDeviceHints2
,
3420 &src
->dev
[i
].hints
[1],
3421 sizeof(dst
->Device
[i
].irdaDeviceHints2
) ) ;
3422 dst
->Device
[i
].irdaCharSet
= src
->dev
[i
].charset
;
3428 FIXME("IrDA optname:0x%x\n", optname
);
3429 return SOCKET_ERROR
;
3431 break; /* case WS_SOL_IRLMP */
3432 #undef MAX_IRDA_DEVICES
3435 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3436 case WS_IPPROTO_TCP
:
3439 case WS_TCP_NODELAY
:
3440 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3441 return SOCKET_ERROR
;
3442 convert_sockopt(&level
, &optname
);
3443 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3445 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3448 release_sock_fd( s
, fd
);
3451 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname
);
3452 return SOCKET_ERROR
;
3457 case WS_IP_ADD_MEMBERSHIP
:
3458 case WS_IP_DROP_MEMBERSHIP
:
3462 case WS_IP_MULTICAST_IF
:
3463 case WS_IP_MULTICAST_LOOP
:
3464 case WS_IP_MULTICAST_TTL
:
3471 #ifdef IP_UNICAST_IF
3472 case WS_IP_UNICAST_IF
:
3474 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3475 return SOCKET_ERROR
;
3476 convert_sockopt(&level
, &optname
);
3477 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3479 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3482 release_sock_fd( s
, fd
);
3484 case WS_IP_DONTFRAGMENT
:
3485 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
3486 *(BOOL
*)optval
= FALSE
;
3489 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname
);
3490 return SOCKET_ERROR
;
3492 case WS_IPPROTO_IPV6
:
3495 #ifdef IPV6_ADD_MEMBERSHIP
3496 case WS_IPV6_ADD_MEMBERSHIP
:
3498 #ifdef IPV6_DROP_MEMBERSHIP
3499 case WS_IPV6_DROP_MEMBERSHIP
:
3501 case WS_IPV6_MULTICAST_IF
:
3502 case WS_IPV6_MULTICAST_HOPS
:
3503 case WS_IPV6_MULTICAST_LOOP
:
3504 case WS_IPV6_UNICAST_HOPS
:
3505 case WS_IPV6_V6ONLY
:
3506 #ifdef IPV6_UNICAST_IF
3507 case WS_IPV6_UNICAST_IF
:
3509 if ( (fd
= get_sock_fd( s
, 0, NULL
)) == -1)
3510 return SOCKET_ERROR
;
3511 convert_sockopt(&level
, &optname
);
3512 if (getsockopt(fd
, level
, optname
, optval
, (socklen_t
*)optlen
) != 0 )
3514 SetLastError((errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno());
3517 release_sock_fd( s
, fd
);
3519 case WS_IPV6_DONTFRAG
:
3520 FIXME("WS_IPV6_DONTFRAG is always false!\n");
3521 *(BOOL
*)optval
= FALSE
;
3524 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname
);
3525 return SOCKET_ERROR
;
3528 WARN("Unknown level: 0x%08x\n", level
);
3529 SetLastError(WSAEINVAL
);
3530 return SOCKET_ERROR
;
3531 } /* end switch(level) */
3534 /***********************************************************************
3537 WS_u_long WINAPI
WS_htonl(WS_u_long hostlong
)
3539 return htonl(hostlong
);
3543 /***********************************************************************
3546 WS_u_short WINAPI
WS_htons(WS_u_short hostshort
)
3548 return htons(hostshort
);
3551 /***********************************************************************
3552 * WSAHtonl (WS2_32.46)
3553 * From MSDN description of error codes, this function should also
3554 * check if WinSock has been initialized and the socket is a valid
3555 * socket. But why? This function only translates a host byte order
3556 * u_long into a network byte order u_long...
3558 int WINAPI
WSAHtonl(SOCKET s
, WS_u_long hostlong
, WS_u_long
*lpnetlong
)
3562 *lpnetlong
= htonl(hostlong
);
3565 WSASetLastError(WSAEFAULT
);
3566 return SOCKET_ERROR
;
3569 /***********************************************************************
3570 * WSAHtons (WS2_32.47)
3571 * From MSDN description of error codes, this function should also
3572 * check if WinSock has been initialized and the socket is a valid
3573 * socket. But why? This function only translates a host byte order
3574 * u_short into a network byte order u_short...
3576 int WINAPI
WSAHtons(SOCKET s
, WS_u_short hostshort
, WS_u_short
*lpnetshort
)
3581 *lpnetshort
= htons(hostshort
);
3584 WSASetLastError(WSAEFAULT
);
3585 return SOCKET_ERROR
;
3589 /***********************************************************************
3590 * inet_addr (WS2_32.11)
3592 WS_u_long WINAPI
WS_inet_addr(const char *cp
)
3594 if (!cp
) return INADDR_NONE
;
3595 return inet_addr(cp
);
3599 /***********************************************************************
3602 WS_u_long WINAPI
WS_ntohl(WS_u_long netlong
)
3604 return ntohl(netlong
);
3608 /***********************************************************************
3611 WS_u_short WINAPI
WS_ntohs(WS_u_short netshort
)
3613 return ntohs(netshort
);
3617 /***********************************************************************
3618 * inet_ntoa (WS2_32.12)
3620 char* WINAPI
WS_inet_ntoa(struct WS_in_addr in
)
3622 char* s
= inet_ntoa(*((struct in_addr
*)&in
));
3625 struct per_thread_data
*data
= get_per_thread_data();
3626 strcpy(data
->ntoa_buffer
, s
);
3627 return data
->ntoa_buffer
;
3629 SetLastError(wsaErrno());
3633 static const char *debugstr_wsaioctl(DWORD ioctl
)
3635 const char *buf_type
, *family
;
3637 switch(ioctl
& 0x18000000)
3642 case WS_IOC_PROTOCOL
:
3643 family
= "IOC_PROTOCOL";
3646 family
= "IOC_VENDOR";
3648 default: /* WS_IOC_UNIX */
3650 BYTE size
= (ioctl
>> 16) & WS_IOCPARM_MASK
;
3651 char x
= (ioctl
& 0xff00) >> 8;
3652 BYTE y
= ioctl
& 0xff;
3655 switch (ioctl
& (WS_IOC_VOID
|WS_IOC_INOUT
))
3659 sprintf(args
, "%d, %d", x
, y
);
3663 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
3667 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
3671 sprintf(args
, "'%c', %d, %d", x
, y
, size
);
3674 return wine_dbg_sprintf("%s(%s)", buf_type
, args
);
3678 /* We are different from WS_IOC_UNIX. */
3679 switch (ioctl
& (WS_IOC_VOID
|WS_IOC_INOUT
))
3682 buf_type
= "_WSAIO";
3685 buf_type
= "_WSAIORW";
3688 buf_type
= "_WSAIOW";
3691 buf_type
= "_WSAIOR";
3698 return wine_dbg_sprintf("%s(%s, %d)", buf_type
, family
,
3699 (USHORT
)(ioctl
& 0xffff));
3702 /* do an ioctl call through the server */
3703 static DWORD
server_ioctl_sock( SOCKET s
, DWORD code
, LPVOID in_buff
, DWORD in_size
,
3704 LPVOID out_buff
, DWORD out_size
, LPDWORD ret_size
,
3705 LPWSAOVERLAPPED overlapped
,
3706 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
3708 HANDLE event
= overlapped
? overlapped
->hEvent
: 0;
3709 HANDLE handle
= SOCKET2HANDLE( s
);
3710 struct ws2_async
*wsa
;
3712 PIO_STATUS_BLOCK io
;
3714 if (!(wsa
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wsa
) )))
3715 return WSA_NOT_ENOUGH_MEMORY
;
3716 wsa
->hSocket
= handle
;
3717 wsa
->user_overlapped
= overlapped
;
3718 wsa
->completion_func
= completion
;
3719 io
= (overlapped
? (PIO_STATUS_BLOCK
)overlapped
: &wsa
->local_iosb
);
3721 status
= NtDeviceIoControlFile( handle
, event
, (PIO_APC_ROUTINE
)ws2_async_apc
, wsa
, io
, code
,
3722 in_buff
, in_size
, out_buff
, out_size
);
3723 if (status
== STATUS_NOT_SUPPORTED
)
3725 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
3726 code
, code
>> 16, (code
>> 14) & 3, (code
>> 2) & 0xfff, code
& 3);
3728 else if (status
== STATUS_SUCCESS
)
3729 *ret_size
= io
->Information
; /* "Information" is the size written to the output buffer */
3731 if (status
!= STATUS_PENDING
) RtlFreeHeap( GetProcessHeap(), 0, wsa
);
3733 return NtStatusToWSAError( status
);
3736 /**********************************************************************
3737 * WSAIoctl (WS2_32.50)
3740 INT WINAPI
WSAIoctl(SOCKET s
, DWORD code
, LPVOID in_buff
, DWORD in_size
, LPVOID out_buff
,
3741 DWORD out_size
, LPDWORD ret_size
, LPWSAOVERLAPPED overlapped
,
3742 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
3745 DWORD status
= 0, total
= 0;
3747 TRACE("%ld, %s, %p, %d, %p, %d, %p, %p, %p\n",
3748 s
, debugstr_wsaioctl(code
), in_buff
, in_size
, out_buff
, out_size
, ret_size
, overlapped
, completion
);
3753 if (in_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(in_buff
))
3755 WSASetLastError(WSAEFAULT
);
3756 return SOCKET_ERROR
;
3758 TRACE("-> FIONBIO (%x)\n", *(WS_u_long
*)in_buff
);
3759 if (_get_sock_mask(s
))
3761 /* AsyncSelect()'ed sockets are always nonblocking */
3762 if (!*(WS_u_long
*)in_buff
) status
= WSAEINVAL
;
3765 if (*(WS_u_long
*)in_buff
)
3766 _enable_event(SOCKET2HANDLE(s
), 0, FD_WINE_NONBLOCKING
, 0);
3768 _enable_event(SOCKET2HANDLE(s
), 0, 0, FD_WINE_NONBLOCKING
);
3773 if (out_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(out_buff
))
3775 WSASetLastError(WSAEFAULT
);
3776 return SOCKET_ERROR
;
3778 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
3779 if (ioctl(fd
, FIONREAD
, out_buff
) == -1)
3780 status
= (errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno();
3781 release_sock_fd( s
, fd
);
3787 unsigned int oob
= 0, atmark
= 0;
3788 socklen_t oobsize
= sizeof(int);
3789 if (out_size
!= sizeof(WS_u_long
) || IS_INTRESOURCE(out_buff
))
3791 WSASetLastError(WSAEFAULT
);
3792 return SOCKET_ERROR
;
3794 if ((fd
= get_sock_fd( s
, 0, NULL
)) == -1) return SOCKET_ERROR
;
3795 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
3796 if ((getsockopt(fd
, SOL_SOCKET
, SO_OOBINLINE
, &oob
, &oobsize
) == -1)
3797 || (!oob
&& ioctl(fd
, SIOCATMARK
, &atmark
) == -1))
3798 status
= (errno
== EBADF
) ? WSAENOTSOCK
: wsaErrno();
3801 /* The SIOCATMARK value read from ioctl() is reversed
3802 * because BSD returns TRUE if it's in the OOB mark
3803 * while Windows returns TRUE if there are NO OOB bytes.
3805 (*(WS_u_long
*) out_buff
) = oob
| !atmark
;
3808 release_sock_fd( s
, fd
);
3813 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
3814 SetLastError(WSAEINVAL
);
3815 return SOCKET_ERROR
;
3817 case WS_SIO_GET_INTERFACE_LIST
:
3819 INTERFACE_INFO
* intArray
= out_buff
;
3820 DWORD size
, numInt
= 0, apiReturn
;
3822 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
3824 if (!out_buff
|| !ret_size
)
3826 WSASetLastError(WSAEFAULT
);
3827 return SOCKET_ERROR
;
3830 fd
= get_sock_fd( s
, 0, NULL
);
3831 if (fd
== -1) return SOCKET_ERROR
;
3833 apiReturn
= GetAdaptersInfo(NULL
, &size
);
3834 if (apiReturn
== ERROR_BUFFER_OVERFLOW
)
3836 PIP_ADAPTER_INFO table
= HeapAlloc(GetProcessHeap(),0,size
);
3840 if (GetAdaptersInfo(table
, &size
) == NO_ERROR
)
3842 PIP_ADAPTER_INFO ptr
;
3844 for (ptr
= table
, numInt
= 0; ptr
; ptr
= ptr
->Next
)
3846 unsigned int addr
, mask
, bcast
;
3847 struct ifreq ifInfo
;
3849 /* Skip interfaces without an IPv4 address. */
3850 if (ptr
->IpAddressList
.IpAddress
.String
[0] == '\0')
3853 if ((numInt
+ 1)*sizeof(INTERFACE_INFO
)/sizeof(IP_ADAPTER_INFO
) > out_size
)
3855 WARN("Buffer too small = %u, out_size = %u\n", numInt
+ 1, out_size
);
3860 /* Socket Status Flags */
3861 lstrcpynA(ifInfo
.ifr_name
, ptr
->AdapterName
, IFNAMSIZ
);
3862 if (ioctl(fd
, SIOCGIFFLAGS
, &ifInfo
) < 0)
3864 ERR("Error obtaining status flags for socket!\n");
3870 /* set flags; the values of IFF_* are not the same
3871 under Linux and Windows, therefore must generate
3873 intArray
->iiFlags
= 0;
3874 if (ifInfo
.ifr_flags
& IFF_BROADCAST
)
3875 intArray
->iiFlags
|= WS_IFF_BROADCAST
;
3876 #ifdef IFF_POINTOPOINT
3877 if (ifInfo
.ifr_flags
& IFF_POINTOPOINT
)
3878 intArray
->iiFlags
|= WS_IFF_POINTTOPOINT
;
3880 if (ifInfo
.ifr_flags
& IFF_LOOPBACK
)
3881 intArray
->iiFlags
|= WS_IFF_LOOPBACK
;
3882 if (ifInfo
.ifr_flags
& IFF_UP
)
3883 intArray
->iiFlags
|= WS_IFF_UP
;
3884 if (ifInfo
.ifr_flags
& IFF_MULTICAST
)
3885 intArray
->iiFlags
|= WS_IFF_MULTICAST
;
3888 addr
= inet_addr(ptr
->IpAddressList
.IpAddress
.String
);
3889 mask
= inet_addr(ptr
->IpAddressList
.IpMask
.String
);
3890 bcast
= addr
| ~mask
;
3891 intArray
->iiAddress
.AddressIn
.sin_family
= AF_INET
;
3892 intArray
->iiAddress
.AddressIn
.sin_port
= 0;
3893 intArray
->iiAddress
.AddressIn
.sin_addr
.WS_s_addr
=
3895 intArray
->iiNetmask
.AddressIn
.sin_family
= AF_INET
;
3896 intArray
->iiNetmask
.AddressIn
.sin_port
= 0;
3897 intArray
->iiNetmask
.AddressIn
.sin_addr
.WS_s_addr
=
3899 intArray
->iiBroadcastAddress
.AddressIn
.sin_family
=
3901 intArray
->iiBroadcastAddress
.AddressIn
.sin_port
= 0;
3902 intArray
->iiBroadcastAddress
.AddressIn
.sin_addr
.
3910 ERR("Unable to get interface table!\n");
3913 HeapFree(GetProcessHeap(),0,table
);
3915 else status
= WSAEINVAL
;
3917 else if (apiReturn
!= ERROR_NO_DATA
)
3919 ERR("Unable to get interface table!\n");
3922 /* Calculate the size of the array being returned */
3923 total
= sizeof(INTERFACE_INFO
) * numInt
;
3924 release_sock_fd( s
, fd
);
3928 case WS_SIO_ADDRESS_LIST_QUERY
:
3932 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
3936 WSASetLastError(WSAEFAULT
);
3937 return SOCKET_ERROR
;
3940 if (GetAdaptersInfo(NULL
, &size
) == ERROR_BUFFER_OVERFLOW
)
3942 IP_ADAPTER_INFO
*p
, *table
= HeapAlloc(GetProcessHeap(), 0, size
);
3945 if (!table
|| GetAdaptersInfo(table
, &size
))
3947 HeapFree(GetProcessHeap(), 0, table
);
3952 for (p
= table
, num
= 0; p
; p
= p
->Next
)
3953 if (p
->IpAddressList
.IpAddress
.String
[0]) num
++;
3955 total
= sizeof(SOCKET_ADDRESS_LIST
) + sizeof(SOCKET_ADDRESS
) * (num
- 1);
3956 total
+= sizeof(SOCKADDR
) * num
;
3958 if (total
> out_size
)
3960 HeapFree(GetProcessHeap(), 0, table
);
3969 SOCKET_ADDRESS_LIST
*sa_list
= out_buff
;
3970 SOCKADDR_IN
*sockaddr
;
3972 sa
= sa_list
->Address
;
3973 sockaddr
= (SOCKADDR_IN
*)((char *)sa
+ num
* sizeof(SOCKET_ADDRESS
));
3974 sa_list
->iAddressCount
= num
;
3976 for (p
= table
, i
= 0; p
; p
= p
->Next
)
3978 if (!p
->IpAddressList
.IpAddress
.String
[0]) continue;
3980 sa
[i
].lpSockaddr
= (SOCKADDR
*)&sockaddr
[i
];
3981 sa
[i
].iSockaddrLength
= sizeof(SOCKADDR
);
3983 sockaddr
[i
].sin_family
= AF_INET
;
3984 sockaddr
[i
].sin_port
= 0;
3985 sockaddr
[i
].sin_addr
.WS_s_addr
= inet_addr(p
->IpAddressList
.IpAddress
.String
);
3990 HeapFree(GetProcessHeap(), 0, table
);
3994 WARN("unable to get IP address list\n");
4001 FIXME("SIO_FLUSH: stub.\n");
4004 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER
:
4006 static const GUID connectex_guid
= WSAID_CONNECTEX
;
4007 static const GUID disconnectex_guid
= WSAID_DISCONNECTEX
;
4008 static const GUID acceptex_guid
= WSAID_ACCEPTEX
;
4009 static const GUID getaccepexsockaddrs_guid
= WSAID_GETACCEPTEXSOCKADDRS
;
4010 static const GUID transmitfile_guid
= WSAID_TRANSMITFILE
;
4011 static const GUID transmitpackets_guid
= WSAID_TRANSMITPACKETS
;
4012 static const GUID wsarecvmsg_guid
= WSAID_WSARECVMSG
;
4013 static const GUID wsasendmsg_guid
= WSAID_WSASENDMSG
;
4015 if ( IsEqualGUID(&connectex_guid
, in_buff
) )
4017 *(LPFN_CONNECTEX
*)out_buff
= WS2_ConnectEx
;
4020 else if ( IsEqualGUID(&disconnectex_guid
, in_buff
) )
4022 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
4024 else if ( IsEqualGUID(&acceptex_guid
, in_buff
) )
4026 *(LPFN_ACCEPTEX
*)out_buff
= WS2_AcceptEx
;
4029 else if ( IsEqualGUID(&getaccepexsockaddrs_guid
, in_buff
) )
4031 *(LPFN_GETACCEPTEXSOCKADDRS
*)out_buff
= WS2_GetAcceptExSockaddrs
;
4034 else if ( IsEqualGUID(&transmitfile_guid
, in_buff
) )
4036 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
4038 else if ( IsEqualGUID(&transmitpackets_guid
, in_buff
) )
4040 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
4042 else if ( IsEqualGUID(&wsarecvmsg_guid
, in_buff
) )
4044 *(LPFN_WSARECVMSG
*)out_buff
= WS2_WSARecvMsg
;
4047 else if ( IsEqualGUID(&wsasendmsg_guid
, in_buff
) )
4049 *(LPFN_WSASENDMSG
*)out_buff
= WSASendMsg
;
4053 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff
));
4055 status
= WSAEOPNOTSUPP
;
4058 case WS_SIO_KEEPALIVE_VALS
:
4060 struct tcp_keepalive
*k
;
4061 int keepalive
, keepidle
, keepintvl
;
4063 if (!in_buff
|| in_size
< sizeof(struct tcp_keepalive
))
4065 WSASetLastError(WSAEFAULT
);
4066 return SOCKET_ERROR
;
4070 keepalive
= k
->onoff
? 1 : 0;
4071 keepidle
= max( 1, (k
->keepalivetime
+ 500) / 1000 );
4072 keepintvl
= max( 1, (k
->keepaliveinterval
+ 500) / 1000 );
4074 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive
, keepidle
, keepintvl
);
4076 fd
= get_sock_fd(s
, 0, NULL
);
4077 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&keepalive
, sizeof(int)) == -1)
4079 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
4080 /* these values need to be set only if SO_KEEPALIVE is enabled */
4083 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPIDLE
, (void *)&keepidle
, sizeof(int)) == -1)
4085 else if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPINTVL
, (void *)&keepintvl
, sizeof(int)) == -1)
4090 FIXME("ignoring keepalive interval and timeout\n");
4092 release_sock_fd(s
, fd
);
4095 case WS_SIO_ROUTING_INTERFACE_QUERY
:
4097 struct WS_sockaddr
*daddr
= (struct WS_sockaddr
*)in_buff
;
4098 struct WS_sockaddr_in
*daddr_in
= (struct WS_sockaddr_in
*)daddr
;
4099 struct WS_sockaddr_in
*saddr_in
= out_buff
;
4100 MIB_IPFORWARDROW row
;
4101 PMIB_IPADDRTABLE ipAddrTable
= NULL
;
4102 DWORD size
, i
, found_index
;
4104 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4106 if (!in_buff
|| in_size
< sizeof(struct WS_sockaddr
) ||
4107 !out_buff
|| out_size
< sizeof(struct WS_sockaddr_in
) || !ret_size
)
4109 WSASetLastError(WSAEFAULT
);
4110 return SOCKET_ERROR
;
4112 if (daddr
->sa_family
!= AF_INET
)
4114 FIXME("unsupported address family %d\n", daddr
->sa_family
);
4115 status
= WSAEAFNOSUPPORT
;
4118 if (GetBestRoute(daddr_in
->sin_addr
.S_un
.S_addr
, 0, &row
) != NOERROR
||
4119 GetIpAddrTable(NULL
, &size
, FALSE
) != ERROR_INSUFFICIENT_BUFFER
)
4124 ipAddrTable
= HeapAlloc(GetProcessHeap(), 0, size
);
4125 if (GetIpAddrTable(ipAddrTable
, &size
, FALSE
))
4127 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
4131 for (i
= 0, found_index
= ipAddrTable
->dwNumEntries
;
4132 i
< ipAddrTable
->dwNumEntries
; i
++)
4134 if (ipAddrTable
->table
[i
].dwIndex
== row
.dwForwardIfIndex
)
4137 if (found_index
== ipAddrTable
->dwNumEntries
)
4139 ERR("no matching IP address for interface %d\n",
4140 row
.dwForwardIfIndex
);
4141 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
4145 saddr_in
->sin_family
= AF_INET
;
4146 saddr_in
->sin_addr
.S_un
.S_addr
= ipAddrTable
->table
[found_index
].dwAddr
;
4147 saddr_in
->sin_port
= 0;
4148 total
= sizeof(struct WS_sockaddr_in
);
4149 HeapFree(GetProcessHeap(), 0, ipAddrTable
);
4152 case WS_SIO_SET_COMPATIBILITY_MODE
:
4153 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4154 status
= WSAEOPNOTSUPP
;
4156 case WS_SIO_UDP_CONNRESET
:
4157 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4159 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4160 WSASetLastError(WSAEOPNOTSUPP
);
4161 return SOCKET_ERROR
;
4163 status
= WSAEOPNOTSUPP
;
4167 if (status
== WSAEOPNOTSUPP
)
4169 status
= server_ioctl_sock(s
, code
, in_buff
, in_size
, out_buff
, out_size
, &total
,
4170 overlapped
, completion
);
4171 if (status
!= WSAEOPNOTSUPP
)
4173 if (status
== 0 || status
== WSA_IO_PENDING
)
4174 TRACE("-> %s request\n", debugstr_wsaioctl(code
));
4176 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code
), status
);
4178 /* overlapped and completion operations will be handled by the server */
4183 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code
));
4188 FIXME( "completion routine %p not supported\n", completion
);
4190 else if (overlapped
)
4192 ULONG_PTR cvalue
= (overlapped
&& ((ULONG_PTR
)overlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)overlapped
: 0;
4193 overlapped
->Internal
= status
;
4194 overlapped
->InternalHigh
= total
;
4195 if (overlapped
->hEvent
) NtSetEvent( overlapped
->hEvent
, NULL
);
4196 if (cvalue
) WS_AddCompletion( HANDLE2SOCKET(s
), cvalue
, status
, total
);
4201 if (ret_size
) *ret_size
= total
;
4204 SetLastError( status
);
4205 return SOCKET_ERROR
;
4209 /***********************************************************************
4210 * ioctlsocket (WS2_32.10)
4212 int WINAPI
WS_ioctlsocket(SOCKET s
, LONG cmd
, WS_u_long
*argp
)
4215 return WSAIoctl( s
, cmd
, argp
, sizeof(WS_u_long
), argp
, sizeof(WS_u_long
), &ret_size
, NULL
, NULL
);
4218 /***********************************************************************
4219 * listen (WS2_32.13)
4221 int WINAPI
WS_listen(SOCKET s
, int backlog
)
4223 int fd
= get_sock_fd( s
, FILE_READ_DATA
, NULL
), ret
= SOCKET_ERROR
;
4225 TRACE("socket %04lx, backlog %d\n", s
, backlog
);
4228 union generic_unix_sockaddr uaddr
;
4229 socklen_t uaddrlen
= sizeof(uaddr
);
4231 if (getsockname(fd
, &uaddr
.addr
, &uaddrlen
) != 0)
4233 SetLastError(wsaErrno());
4235 else if (!is_sockaddr_bound(&uaddr
.addr
, uaddrlen
))
4237 SetLastError(WSAEINVAL
);
4239 else if (listen(fd
, backlog
) == 0)
4241 _enable_event(SOCKET2HANDLE(s
), FD_ACCEPT
,
4243 FD_CONNECT
|FD_WINE_CONNECTED
);
4247 SetLastError(wsaErrno());
4248 release_sock_fd( s
, fd
);
4251 SetLastError(WSAENOTSOCK
);
4255 /***********************************************************************
4258 int WINAPI
WS_recv(SOCKET s
, char *buf
, int len
, int flags
)
4260 DWORD n
, dwFlags
= flags
;
4266 if ( WS2_recv_base(s
, &wsabuf
, 1, &n
, &dwFlags
, NULL
, NULL
, NULL
, NULL
, NULL
) == SOCKET_ERROR
)
4267 return SOCKET_ERROR
;
4272 /***********************************************************************
4273 * recvfrom (WS2_32.17)
4275 int WINAPI
WS_recvfrom(SOCKET s
, char *buf
, INT len
, int flags
,
4276 struct WS_sockaddr
*from
, int *fromlen
)
4278 DWORD n
, dwFlags
= flags
;
4284 if ( WS2_recv_base(s
, &wsabuf
, 1, &n
, &dwFlags
, from
, fromlen
, NULL
, NULL
, NULL
) == SOCKET_ERROR
)
4285 return SOCKET_ERROR
;
4290 /* allocate a poll array for the corresponding fd sets */
4291 static struct pollfd
*fd_sets_to_poll( const WS_fd_set
*readfds
, const WS_fd_set
*writefds
,
4292 const WS_fd_set
*exceptfds
, int *count_ptr
)
4294 unsigned int i
, j
= 0, count
= 0;
4297 if (readfds
) count
+= readfds
->fd_count
;
4298 if (writefds
) count
+= writefds
->fd_count
;
4299 if (exceptfds
) count
+= exceptfds
->fd_count
;
4303 SetLastError(WSAEINVAL
);
4306 if (!(fds
= HeapAlloc( GetProcessHeap(), 0, count
* sizeof(fds
[0]))))
4308 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
4312 for (i
= 0; i
< readfds
->fd_count
; i
++, j
++)
4314 fds
[j
].fd
= get_sock_fd( readfds
->fd_array
[i
], FILE_READ_DATA
, NULL
);
4315 if (fds
[j
].fd
== -1) goto failed
;
4316 fds
[j
].events
= POLLIN
;
4320 for (i
= 0; i
< writefds
->fd_count
; i
++, j
++)
4322 fds
[j
].fd
= get_sock_fd( writefds
->fd_array
[i
], FILE_WRITE_DATA
, NULL
);
4323 if (fds
[j
].fd
== -1) goto failed
;
4324 fds
[j
].events
= POLLOUT
;
4328 for (i
= 0; i
< exceptfds
->fd_count
; i
++, j
++)
4330 fds
[j
].fd
= get_sock_fd( exceptfds
->fd_array
[i
], 0, NULL
);
4331 if (fds
[j
].fd
== -1) goto failed
;
4332 fds
[j
].events
= POLLHUP
;
4341 for (i
= 0; i
< readfds
->fd_count
&& j
< count
; i
++, j
++)
4342 release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
4344 for (i
= 0; i
< writefds
->fd_count
&& j
< count
; i
++, j
++)
4345 release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
4347 for (i
= 0; i
< exceptfds
->fd_count
&& j
< count
; i
++, j
++)
4348 release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
4349 HeapFree( GetProcessHeap(), 0, fds
);
4353 /* release the file descriptor obtained in fd_sets_to_poll */
4354 /* must be called with the original fd_set arrays, before calling get_poll_results */
4355 static void release_poll_fds( const WS_fd_set
*readfds
, const WS_fd_set
*writefds
,
4356 const WS_fd_set
*exceptfds
, struct pollfd
*fds
)
4358 unsigned int i
, j
= 0;
4362 for (i
= 0; i
< readfds
->fd_count
; i
++, j
++)
4363 if (fds
[j
].fd
!= -1) release_sock_fd( readfds
->fd_array
[i
], fds
[j
].fd
);
4367 for (i
= 0; i
< writefds
->fd_count
; i
++, j
++)
4368 if (fds
[j
].fd
!= -1) release_sock_fd( writefds
->fd_array
[i
], fds
[j
].fd
);
4372 for (i
= 0; i
< exceptfds
->fd_count
; i
++, j
++)
4373 if (fds
[j
].fd
!= -1)
4375 /* make sure we have a real error before releasing the fd */
4376 if (!sock_error_p( fds
[j
].fd
)) fds
[j
].revents
= 0;
4377 release_sock_fd( exceptfds
->fd_array
[i
], fds
[j
].fd
);
4382 /* map the poll results back into the Windows fd sets */
4383 static int get_poll_results( WS_fd_set
*readfds
, WS_fd_set
*writefds
, WS_fd_set
*exceptfds
,
4384 const struct pollfd
*fds
)
4386 unsigned int i
, j
= 0, k
, total
= 0;
4390 for (i
= k
= 0; i
< readfds
->fd_count
; i
++, j
++)
4391 if (fds
[j
].revents
) readfds
->fd_array
[k
++] = readfds
->fd_array
[i
];
4392 readfds
->fd_count
= k
;
4397 for (i
= k
= 0; i
< writefds
->fd_count
; i
++, j
++)
4398 if ((fds
[j
].revents
& POLLOUT
) && !(fds
[j
].revents
& POLLHUP
))
4399 writefds
->fd_array
[k
++] = writefds
->fd_array
[i
];
4400 writefds
->fd_count
= k
;
4405 for (i
= k
= 0; i
< exceptfds
->fd_count
; i
++, j
++)
4406 if (fds
[j
].revents
) exceptfds
->fd_array
[k
++] = exceptfds
->fd_array
[i
];
4407 exceptfds
->fd_count
= k
;
4414 /***********************************************************************
4415 * select (WS2_32.18)
4417 int WINAPI
WS_select(int nfds
, WS_fd_set
*ws_readfds
,
4418 WS_fd_set
*ws_writefds
, WS_fd_set
*ws_exceptfds
,
4419 const struct WS_timeval
* ws_timeout
)
4421 struct pollfd
*pollfds
;
4422 struct timeval tv1
, tv2
;
4424 int count
, ret
, timeout
= -1;
4426 TRACE("read %p, write %p, excp %p timeout %p\n",
4427 ws_readfds
, ws_writefds
, ws_exceptfds
, ws_timeout
);
4429 if (!(pollfds
= fd_sets_to_poll( ws_readfds
, ws_writefds
, ws_exceptfds
, &count
)))
4430 return SOCKET_ERROR
;
4434 torig
= (ws_timeout
->tv_sec
* 1000) + (ws_timeout
->tv_usec
+ 999) / 1000;
4436 gettimeofday( &tv1
, 0 );
4439 while ((ret
= poll( pollfds
, count
, timeout
)) < 0)
4443 if (!ws_timeout
) continue;
4444 gettimeofday( &tv2
, 0 );
4446 tv2
.tv_sec
-= tv1
.tv_sec
;
4447 tv2
.tv_usec
-= tv1
.tv_usec
;
4448 if (tv2
.tv_usec
< 0)
4450 tv2
.tv_usec
+= 1000000;
4454 timeout
= torig
- (tv2
.tv_sec
* 1000) - (tv2
.tv_usec
+ 999) / 1000;
4455 if (timeout
<= 0) break;
4458 release_poll_fds( ws_readfds
, ws_writefds
, ws_exceptfds
, pollfds
);
4460 if (ret
== -1) SetLastError(wsaErrno());
4461 else ret
= get_poll_results( ws_readfds
, ws_writefds
, ws_exceptfds
, pollfds
);
4462 HeapFree( GetProcessHeap(), 0, pollfds
);
4466 /* helper to send completion messages for client-only i/o operation case */
4467 static void WS_AddCompletion( SOCKET sock
, ULONG_PTR CompletionValue
, NTSTATUS CompletionStatus
,
4470 SERVER_START_REQ( add_fd_completion
)
4472 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(sock
) );
4473 req
->cvalue
= CompletionValue
;
4474 req
->status
= CompletionStatus
;
4475 req
->information
= Information
;
4476 wine_server_call( req
);
4482 /***********************************************************************
4485 int WINAPI
WS_send(SOCKET s
, const char *buf
, int len
, int flags
)
4491 wsabuf
.buf
= (char*) buf
;
4493 if ( WS2_sendto( s
, &wsabuf
, 1, &n
, flags
, NULL
, 0, NULL
, NULL
) == SOCKET_ERROR
)
4494 return SOCKET_ERROR
;
4499 /***********************************************************************
4500 * WSASend (WS2_32.72)
4502 INT WINAPI
WSASend( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
4503 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
4504 LPWSAOVERLAPPED lpOverlapped
,
4505 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
4507 return WS2_sendto( s
, lpBuffers
, dwBufferCount
, lpNumberOfBytesSent
, dwFlags
,
4508 NULL
, 0, lpOverlapped
, lpCompletionRoutine
);
4511 /***********************************************************************
4512 * WSASendDisconnect (WS2_32.73)
4514 INT WINAPI
WSASendDisconnect( SOCKET s
, LPWSABUF lpBuffers
)
4516 return WS_shutdown( s
, SD_SEND
);
4520 static int WS2_sendto( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
4521 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
4522 const struct WS_sockaddr
*to
, int tolen
,
4523 LPWSAOVERLAPPED lpOverlapped
,
4524 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
4526 unsigned int i
, options
;
4527 int n
, fd
, err
, overlapped
;
4528 struct ws2_async
*wsa
= NULL
, localwsa
;
4529 int totalLength
= 0;
4533 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
4534 s
, lpBuffers
, dwBufferCount
, dwFlags
,
4535 to
, tolen
, lpOverlapped
, lpCompletionRoutine
);
4537 fd
= get_sock_fd( s
, FILE_WRITE_DATA
, &options
);
4538 TRACE( "fd=%d, options=%x\n", fd
, options
);
4540 if ( fd
== -1 ) return SOCKET_ERROR
;
4542 if (!lpOverlapped
&& !lpNumberOfBytesSent
)
4548 overlapped
= (lpOverlapped
|| lpCompletionRoutine
) &&
4549 !(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
));
4550 if (overlapped
|| dwBufferCount
> 1)
4552 if (!(wsa
= HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async
, iovec
[dwBufferCount
]) )))
4561 wsa
->hSocket
= SOCKET2HANDLE(s
);
4562 wsa
->addr
= (struct WS_sockaddr
*)to
;
4563 wsa
->addrlen
.val
= tolen
;
4564 wsa
->flags
= dwFlags
;
4565 wsa
->lpFlags
= &wsa
->flags
;
4566 wsa
->control
= NULL
;
4567 wsa
->n_iovecs
= dwBufferCount
;
4568 wsa
->first_iovec
= 0;
4569 for ( i
= 0; i
< dwBufferCount
; i
++ )
4571 wsa
->iovec
[i
].iov_base
= lpBuffers
[i
].buf
;
4572 wsa
->iovec
[i
].iov_len
= lpBuffers
[i
].len
;
4573 totalLength
+= lpBuffers
[i
].len
;
4576 n
= WS2_send( fd
, wsa
);
4577 if (n
== -1 && errno
!= EAGAIN
)
4585 IO_STATUS_BLOCK
*iosb
= lpOverlapped
? (IO_STATUS_BLOCK
*)lpOverlapped
: &wsa
->local_iosb
;
4586 ULONG_PTR cvalue
= (lpOverlapped
&& ((ULONG_PTR
)lpOverlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)lpOverlapped
: 0;
4588 wsa
->user_overlapped
= lpOverlapped
;
4589 wsa
->completion_func
= lpCompletionRoutine
;
4590 release_sock_fd( s
, fd
);
4592 if (n
== -1 || n
< totalLength
)
4594 iosb
->u
.Status
= STATUS_PENDING
;
4595 iosb
->Information
= n
== -1 ? 0 : n
;
4597 SERVER_START_REQ( register_async
)
4599 req
->type
= ASYNC_TYPE_WRITE
;
4600 req
->async
.handle
= wine_server_obj_handle( wsa
->hSocket
);
4601 req
->async
.callback
= wine_server_client_ptr( WS2_async_send
);
4602 req
->async
.iosb
= wine_server_client_ptr( iosb
);
4603 req
->async
.arg
= wine_server_client_ptr( wsa
);
4604 req
->async
.event
= wine_server_obj_handle( lpCompletionRoutine
? 0 : lpOverlapped
->hEvent
);
4605 req
->async
.cvalue
= cvalue
;
4606 err
= wine_server_call( req
);
4610 /* Enable the event only after starting the async. The server will deliver it as soon as
4611 the async is done. */
4612 _enable_event(SOCKET2HANDLE(s
), FD_WRITE
, 0, 0);
4614 if (err
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
4615 WSASetLastError( NtStatusToWSAError( err
));
4616 return SOCKET_ERROR
;
4619 iosb
->u
.Status
= STATUS_SUCCESS
;
4620 iosb
->Information
= n
;
4621 if (lpNumberOfBytesSent
) *lpNumberOfBytesSent
= n
;
4622 if (!wsa
->completion_func
)
4624 if (cvalue
) WS_AddCompletion( s
, cvalue
, STATUS_SUCCESS
, n
);
4625 if (lpOverlapped
->hEvent
) SetEvent( lpOverlapped
->hEvent
);
4626 HeapFree( GetProcessHeap(), 0, wsa
);
4628 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC
)ws2_async_apc
,
4629 (ULONG_PTR
)wsa
, (ULONG_PTR
)iosb
, 0 );
4634 if ((err
= _is_blocking( s
, &is_blocking
)))
4636 err
= NtStatusToWSAError( err
);
4642 /* On a blocking non-overlapped stream socket,
4643 * sending blocks until the entire buffer is sent. */
4644 DWORD timeout_start
= GetTickCount();
4646 bytes_sent
= n
== -1 ? 0 : n
;
4648 while (wsa
->first_iovec
< wsa
->n_iovecs
)
4651 int timeout
= GET_SNDTIMEO(fd
);
4655 timeout
-= GetTickCount() - timeout_start
;
4656 if (timeout
< 0) timeout
= 0;
4660 pfd
.events
= POLLOUT
;
4662 if (!timeout
|| !poll( &pfd
, 1, timeout
))
4665 goto error
; /* msdn says a timeout in send is fatal */
4668 n
= WS2_send( fd
, wsa
);
4669 if (n
== -1 && errno
!= EAGAIN
)
4679 else /* non-blocking */
4681 if (n
< totalLength
)
4682 _enable_event(SOCKET2HANDLE(s
), FD_WRITE
, 0, 0);
4685 err
= WSAEWOULDBLOCK
;
4691 TRACE(" -> %i bytes\n", bytes_sent
);
4693 if (lpNumberOfBytesSent
) *lpNumberOfBytesSent
= bytes_sent
;
4694 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
4695 release_sock_fd( s
, fd
);
4700 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
4701 release_sock_fd( s
, fd
);
4702 WARN(" -> ERROR %d\n", err
);
4703 WSASetLastError(err
);
4704 return SOCKET_ERROR
;
4707 /***********************************************************************
4708 * WSASendTo (WS2_32.74)
4710 INT WINAPI
WSASendTo( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
4711 LPDWORD lpNumberOfBytesSent
, DWORD dwFlags
,
4712 const struct WS_sockaddr
*to
, int tolen
,
4713 LPWSAOVERLAPPED lpOverlapped
,
4714 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
4716 return WS2_sendto( s
, lpBuffers
, dwBufferCount
,
4717 lpNumberOfBytesSent
, dwFlags
,
4719 lpOverlapped
, lpCompletionRoutine
);
4722 /***********************************************************************
4723 * sendto (WS2_32.20)
4725 int WINAPI
WS_sendto(SOCKET s
, const char *buf
, int len
, int flags
,
4726 const struct WS_sockaddr
*to
, int tolen
)
4732 wsabuf
.buf
= (char*) buf
;
4734 if ( WS2_sendto(s
, &wsabuf
, 1, &n
, flags
, to
, tolen
, NULL
, NULL
) == SOCKET_ERROR
)
4735 return SOCKET_ERROR
;
4740 /***********************************************************************
4741 * setsockopt (WS2_32.21)
4743 int WINAPI
WS_setsockopt(SOCKET s
, int level
, int optname
,
4744 const char *optval
, int optlen
)
4748 struct linger linger
;
4749 struct timeval tval
;
4751 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
4752 s
, level
, optname
, optval
, optlen
);
4754 /* some broken apps pass the value directly instead of a pointer to it */
4755 if(optlen
&& IS_INTRESOURCE(optval
))
4757 SetLastError(WSAEFAULT
);
4758 return SOCKET_ERROR
;
4766 /* Some options need some conversion before they can be sent to
4767 * setsockopt. The conversions are done here, then they will fall through
4768 * to the general case. Special options that are not passed to
4769 * setsockopt follow below that.*/
4771 case WS_SO_DONTLINGER
:
4774 SetLastError(WSAEFAULT
);
4775 return SOCKET_ERROR
;
4777 linger
.l_onoff
= *(const int*)optval
== 0;
4778 linger
.l_linger
= 0;
4780 optname
= SO_LINGER
;
4781 optval
= (char*)&linger
;
4782 optlen
= sizeof(struct linger
);
4788 SetLastError(WSAEFAULT
);
4789 return SOCKET_ERROR
;
4791 linger
.l_onoff
= ((LINGER
*)optval
)->l_onoff
;
4792 linger
.l_linger
= ((LINGER
*)optval
)->l_linger
;
4794 optname
= SO_LINGER
;
4795 optval
= (char*)&linger
;
4796 optlen
= sizeof(struct linger
);
4800 if (*(const int*)optval
< 2048)
4802 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval
);
4807 /* The options listed here don't need any special handling. Thanks to
4808 * the conversion happening above, options from there will fall through
4810 case WS_SO_ACCEPTCONN
:
4811 case WS_SO_BROADCAST
:
4813 case WS_SO_KEEPALIVE
:
4814 case WS_SO_OOBINLINE
:
4815 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
4816 * however, using it the BSD way fixes bug 8513 and seems to be what
4817 * most programmers assume, anyway */
4818 case WS_SO_REUSEADDR
:
4821 convert_sockopt(&level
, &optname
);
4824 /* SO_DEBUG is a privileged operation, ignore it. */
4826 TRACE("Ignoring SO_DEBUG\n");
4829 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
4830 * socket. According to MSDN, this option is silently ignored.*/
4831 case WS_SO_DONTROUTE
:
4832 TRACE("Ignoring SO_DONTROUTE\n");
4835 /* Stops two sockets from being bound to the same port. Always happens
4836 * on unix systems, so just drop it. */
4837 case WS_SO_EXCLUSIVEADDRUSE
:
4838 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
4841 /* After a ConnectEx call succeeds, the socket can't be used with half of the
4842 * normal winsock functions on windows. We don't have that problem. */
4843 case WS_SO_UPDATE_CONNECT_CONTEXT
:
4844 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
4847 /* After a AcceptEx call succeeds, the socket can't be used with half of the
4848 * normal winsock functions on windows. We don't have that problem. */
4849 case WS_SO_UPDATE_ACCEPT_CONTEXT
:
4850 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
4853 /* SO_OPENTYPE does not require a valid socket handle. */
4854 case WS_SO_OPENTYPE
:
4855 if (!optlen
|| optlen
< sizeof(int) || !optval
)
4857 SetLastError(WSAEFAULT
);
4858 return SOCKET_ERROR
;
4860 get_per_thread_data()->opentype
= *(const int *)optval
;
4861 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval
) );
4865 case WS_SO_RCVTIMEO
:
4868 case WS_SO_SNDTIMEO
:
4870 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
4871 if (optval
&& optlen
== sizeof(UINT32
)) {
4872 /* WinSock passes milliseconds instead of struct timeval */
4873 tval
.tv_usec
= (*(const UINT32
*)optval
% 1000) * 1000;
4874 tval
.tv_sec
= *(const UINT32
*)optval
/ 1000;
4875 /* min of 500 milliseconds */
4876 if (tval
.tv_sec
== 0 && tval
.tv_usec
&& tval
.tv_usec
< 500000)
4877 tval
.tv_usec
= 500000;
4878 optlen
= sizeof(struct timeval
);
4879 optval
= (char*)&tval
;
4880 } else if (optlen
== sizeof(struct timeval
)) {
4881 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen
);
4883 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen
);
4886 convert_sockopt(&level
, &optname
);
4891 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname
);
4892 SetLastError(WSAENOPROTOOPT
);
4893 return SOCKET_ERROR
;
4895 break; /* case WS_SOL_SOCKET */
4898 case WS_NSPROTO_IPX
:
4902 return set_ipx_packettype(s
, *(int*)optval
);
4904 case IPX_FILTERPTYPE
:
4905 /* Sets the receive filter packet type, at the moment we don't support it */
4906 FIXME("IPX_FILTERPTYPE: %x\n", *optval
);
4907 /* Returning 0 is better for now than returning a SOCKET_ERROR */
4911 FIXME("opt_name:%x\n", optname
);
4912 return SOCKET_ERROR
;
4914 break; /* case WS_NSPROTO_IPX */
4917 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4918 case WS_IPPROTO_TCP
:
4921 case WS_TCP_NODELAY
:
4922 convert_sockopt(&level
, &optname
);
4925 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname
);
4926 return SOCKET_ERROR
;
4933 case WS_IP_ADD_MEMBERSHIP
:
4934 case WS_IP_DROP_MEMBERSHIP
:
4938 case WS_IP_MULTICAST_IF
:
4939 case WS_IP_MULTICAST_LOOP
:
4940 case WS_IP_MULTICAST_TTL
:
4947 #ifdef IP_UNICAST_IF
4948 case WS_IP_UNICAST_IF
:
4950 convert_sockopt(&level
, &optname
);
4952 case WS_IP_DONTFRAGMENT
:
4953 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
4956 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname
);
4957 return SOCKET_ERROR
;
4961 case WS_IPPROTO_IPV6
:
4964 #ifdef IPV6_ADD_MEMBERSHIP
4965 case WS_IPV6_ADD_MEMBERSHIP
:
4967 #ifdef IPV6_DROP_MEMBERSHIP
4968 case WS_IPV6_DROP_MEMBERSHIP
:
4970 case WS_IPV6_MULTICAST_IF
:
4971 case WS_IPV6_MULTICAST_HOPS
:
4972 case WS_IPV6_MULTICAST_LOOP
:
4973 case WS_IPV6_UNICAST_HOPS
:
4974 case WS_IPV6_V6ONLY
:
4975 #ifdef IPV6_UNICAST_IF
4976 case WS_IPV6_UNICAST_IF
:
4978 convert_sockopt(&level
, &optname
);
4980 case WS_IPV6_DONTFRAG
:
4981 FIXME("IPV6_DONTFRAG is silently ignored!\n");
4983 case WS_IPV6_PROTECTION_LEVEL
:
4984 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
4987 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname
);
4988 return SOCKET_ERROR
;
4993 WARN("Unknown level: 0x%08x\n", level
);
4994 SetLastError(WSAEINVAL
);
4995 return SOCKET_ERROR
;
4996 } /* end switch(level) */
4998 /* avoid endianness issues if argument is a 16-bit int */
4999 if (optval
&& optlen
< sizeof(int))
5001 woptval
= *((const INT16
*) optval
);
5002 optval
= (char*) &woptval
;
5005 fd
= get_sock_fd( s
, 0, NULL
);
5006 if (fd
== -1) return SOCKET_ERROR
;
5008 if (setsockopt(fd
, level
, optname
, optval
, optlen
) == 0)
5011 if (level
== SOL_SOCKET
&& optname
== SO_REUSEADDR
&&
5012 setsockopt(fd
, level
, SO_REUSEPORT
, optval
, optlen
) != 0)
5014 SetLastError(wsaErrno());
5015 release_sock_fd( s
, fd
);
5016 return SOCKET_ERROR
;
5019 release_sock_fd( s
, fd
);
5022 TRACE("Setting socket error, %d\n", wsaErrno());
5023 SetLastError(wsaErrno());
5024 release_sock_fd( s
, fd
);
5026 return SOCKET_ERROR
;
5029 /***********************************************************************
5030 * shutdown (WS2_32.22)
5032 int WINAPI
WS_shutdown(SOCKET s
, int how
)
5034 int fd
, err
= WSAENOTSOCK
;
5035 unsigned int options
, clear_flags
= 0;
5037 fd
= get_sock_fd( s
, 0, &options
);
5038 TRACE("socket %04lx, how %i %x\n", s
, how
, options
);
5041 return SOCKET_ERROR
;
5045 case SD_RECEIVE
: /* drop receives */
5046 clear_flags
|= FD_READ
;
5048 case SD_SEND
: /* drop sends */
5049 clear_flags
|= FD_WRITE
;
5051 case SD_BOTH
: /* drop all */
5052 clear_flags
|= FD_READ
|FD_WRITE
;
5055 clear_flags
|= FD_WINE_LISTENING
;
5058 if (!(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
)))
5063 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_READ
);
5066 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_WRITE
);
5070 err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_READ
);
5071 if (!err
) err
= WS2_register_async_shutdown( s
, ASYNC_TYPE_WRITE
);
5074 if (err
) goto error
;
5076 else /* non-overlapped mode */
5078 if ( shutdown( fd
, how
) )
5085 release_sock_fd( s
, fd
);
5086 _enable_event( SOCKET2HANDLE(s
), 0, 0, clear_flags
);
5087 if ( how
> 1) WSAAsyncSelect( s
, 0, 0, 0 );
5091 release_sock_fd( s
, fd
);
5092 _enable_event( SOCKET2HANDLE(s
), 0, 0, clear_flags
);
5093 WSASetLastError( err
);
5094 return SOCKET_ERROR
;
5097 /***********************************************************************
5098 * socket (WS2_32.23)
5100 SOCKET WINAPI
WS_socket(int af
, int type
, int protocol
)
5102 TRACE("af=%d type=%d protocol=%d\n", af
, type
, protocol
);
5104 return WSASocketA( af
, type
, protocol
, NULL
, 0,
5105 get_per_thread_data()->opentype
? 0 : WSA_FLAG_OVERLAPPED
);
5109 /***********************************************************************
5110 * gethostbyaddr (WS2_32.51)
5112 struct WS_hostent
* WINAPI
WS_gethostbyaddr(const char *addr
, int len
, int type
)
5114 struct WS_hostent
*retval
= NULL
;
5115 struct hostent
* host
;
5116 int unixtype
= convert_af_w2u(type
);
5117 const char *paddr
= addr
;
5118 unsigned long loopback
;
5119 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5121 int ebufsize
= 1024;
5122 struct hostent hostentry
;
5123 int locerr
= ENOBUFS
;
5126 /* convert back the magic loopback address if necessary */
5127 if (unixtype
== AF_INET
&& len
== 4 && !memcmp(addr
, magic_loopback_addr
, 4))
5129 loopback
= htonl(INADDR_LOOPBACK
);
5130 paddr
= (char*) &loopback
;
5133 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5135 extrabuf
=HeapAlloc(GetProcessHeap(),0,ebufsize
) ;
5137 int res
= gethostbyaddr_r(paddr
, len
, unixtype
,
5138 &hostentry
, extrabuf
, ebufsize
, &host
, &locerr
);
5139 if (res
!= ERANGE
) break;
5141 extrabuf
=HeapReAlloc(GetProcessHeap(),0,extrabuf
,ebufsize
) ;
5143 if (host
) retval
= WS_dup_he(host
);
5144 else SetLastError((locerr
< 0) ? wsaErrno() : wsaHerrno(locerr
));
5145 HeapFree(GetProcessHeap(),0,extrabuf
);
5147 EnterCriticalSection( &csWSgetXXXbyYYY
);
5148 host
= gethostbyaddr(paddr
, len
, unixtype
);
5149 if (host
) retval
= WS_dup_he(host
);
5150 else SetLastError((h_errno
< 0) ? wsaErrno() : wsaHerrno(h_errno
));
5151 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5153 TRACE("ptr %p, len %d, type %d ret %p\n", addr
, len
, type
, retval
);
5157 /***********************************************************************
5158 * WS_get_local_ips (INTERNAL)
5160 * Returns the list of local IP addresses by going through the network
5161 * adapters and using the local routing table to sort the addresses
5162 * from highest routing priority to lowest routing priority. This
5163 * functionality is inferred from the description for obtaining local
5164 * IP addresses given in the Knowledge Base Article Q160215.
5166 * Please note that the returned hostent is only freed when the thread
5167 * closes and is replaced if another hostent is requested.
5169 static struct WS_hostent
* WS_get_local_ips( char *hostname
)
5171 int last_metric
, numroutes
= 0, i
, j
;
5173 PIP_ADAPTER_INFO adapters
= NULL
, k
;
5174 struct WS_hostent
*hostlist
= NULL
;
5175 PMIB_IPFORWARDTABLE routes
= NULL
;
5176 struct route
*route_addrs
= NULL
;
5177 DWORD adap_size
, route_size
;
5179 /* Obtain the size of the adapter list and routing table, also allocate memory */
5180 if (GetAdaptersInfo(NULL
, &adap_size
) != ERROR_BUFFER_OVERFLOW
)
5182 if (GetIpForwardTable(NULL
, &route_size
, FALSE
) != ERROR_INSUFFICIENT_BUFFER
)
5184 adapters
= HeapAlloc(GetProcessHeap(), 0, adap_size
);
5185 routes
= HeapAlloc(GetProcessHeap(), 0, route_size
);
5186 route_addrs
= HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
5187 if (adapters
== NULL
|| routes
== NULL
|| route_addrs
== NULL
)
5189 /* Obtain the adapter list and the full routing table */
5190 if (GetAdaptersInfo(adapters
, &adap_size
) != NO_ERROR
)
5192 if (GetIpForwardTable(routes
, &route_size
, FALSE
) != NO_ERROR
)
5194 /* Store the interface associated with each route */
5195 for (n
= 0; n
< routes
->dwNumEntries
; n
++)
5199 BOOL exists
= FALSE
;
5201 if (routes
->table
[n
].u1
.ForwardType
!= MIB_IPROUTE_TYPE_DIRECT
)
5203 ifindex
= routes
->table
[n
].dwForwardIfIndex
;
5204 ifmetric
= routes
->table
[n
].dwForwardMetric1
;
5205 /* Only store the lowest valued metric for an interface */
5206 for (j
= 0; j
< numroutes
; j
++)
5208 if (route_addrs
[j
].interface
== ifindex
)
5210 if (route_addrs
[j
].metric
> ifmetric
)
5211 route_addrs
[j
].metric
= ifmetric
;
5217 route_addrs
= HeapReAlloc(GetProcessHeap(), 0, route_addrs
, (numroutes
+1)*sizeof(struct route
));
5218 if (route_addrs
== NULL
)
5219 goto cleanup
; /* Memory allocation error, fail gracefully */
5220 route_addrs
[numroutes
].interface
= ifindex
;
5221 route_addrs
[numroutes
].metric
= ifmetric
;
5222 /* If no IP is found in the next step (for whatever reason)
5223 * then fall back to the magic loopback address.
5225 memcpy(&(route_addrs
[numroutes
].addr
.s_addr
), magic_loopback_addr
, 4);
5229 goto cleanup
; /* No routes, fall back to the Magic IP */
5230 /* Find the IP address associated with each found interface */
5231 for (i
= 0; i
< numroutes
; i
++)
5233 for (k
= adapters
; k
!= NULL
; k
= k
->Next
)
5235 char *ip
= k
->IpAddressList
.IpAddress
.String
;
5237 if (route_addrs
[i
].interface
== k
->Index
)
5238 route_addrs
[i
].addr
.s_addr
= (in_addr_t
) inet_addr(ip
);
5241 /* Allocate a hostent and enough memory for all the IPs,
5242 * including the NULL at the end of the list.
5244 hostlist
= WS_create_he(hostname
, 1, 0, numroutes
+1, sizeof(struct in_addr
));
5245 if (hostlist
== NULL
)
5246 goto cleanup
; /* Failed to allocate a hostent for the list of IPs */
5247 hostlist
->h_addr_list
[numroutes
] = NULL
; /* NULL-terminate the address list */
5248 hostlist
->h_aliases
[0] = NULL
; /* NULL-terminate the alias list */
5249 hostlist
->h_addrtype
= AF_INET
;
5250 hostlist
->h_length
= sizeof(struct in_addr
); /* = 4 */
5251 /* Reorder the entries when placing them in the host list, Windows expects
5252 * the IP list in order from highest priority to lowest (the critical thing
5253 * is that most applications expect the first IP to be the default route).
5256 for (i
= 0; i
< numroutes
; i
++)
5258 struct in_addr addr
;
5259 int metric
= 0xFFFF;
5261 memcpy(&addr
, magic_loopback_addr
, 4);
5262 for (j
= 0; j
< numroutes
; j
++)
5264 int this_metric
= route_addrs
[j
].metric
;
5266 if (this_metric
> last_metric
&& this_metric
< metric
)
5268 addr
= route_addrs
[j
].addr
;
5269 metric
= this_metric
;
5272 last_metric
= metric
;
5273 (*(struct in_addr
*) hostlist
->h_addr_list
[i
]) = addr
;
5276 /* Cleanup all allocated memory except the address list,
5277 * the address list is used by the calling app.
5280 HeapFree(GetProcessHeap(), 0, route_addrs
);
5281 HeapFree(GetProcessHeap(), 0, adapters
);
5282 HeapFree(GetProcessHeap(), 0, routes
);
5286 /***********************************************************************
5287 * gethostbyname (WS2_32.52)
5289 struct WS_hostent
* WINAPI
WS_gethostbyname(const char* name
)
5291 struct WS_hostent
*retval
= NULL
;
5292 struct hostent
* host
;
5293 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5296 struct hostent hostentry
;
5297 int locerr
= ENOBUFS
;
5301 SetLastError(WSANOTINITIALISED
);
5304 if( gethostname( hostname
, 100) == -1) {
5305 SetLastError( WSAENOBUFS
); /* appropriate ? */
5308 if( !name
|| !name
[0]) {
5311 /* If the hostname of the local machine is requested then return the
5312 * complete list of local IP addresses */
5313 if(strcmp(name
, hostname
) == 0)
5314 retval
= WS_get_local_ips(hostname
);
5315 /* If any other hostname was requested (or the routing table lookup failed)
5316 * then return the IP found by the host OS */
5319 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5321 extrabuf
=HeapAlloc(GetProcessHeap(),0,ebufsize
) ;
5323 int res
= gethostbyname_r(name
, &hostentry
, extrabuf
, ebufsize
, &host
, &locerr
);
5324 if( res
!= ERANGE
) break;
5326 extrabuf
=HeapReAlloc(GetProcessHeap(),0,extrabuf
,ebufsize
) ;
5328 if (!host
) SetLastError((locerr
< 0) ? wsaErrno() : wsaHerrno(locerr
));
5330 EnterCriticalSection( &csWSgetXXXbyYYY
);
5331 host
= gethostbyname(name
);
5332 if (!host
) SetLastError((h_errno
< 0) ? wsaErrno() : wsaHerrno(h_errno
));
5334 if (host
) retval
= WS_dup_he(host
);
5335 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5336 HeapFree(GetProcessHeap(),0,extrabuf
);
5338 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5341 if (retval
&& retval
->h_addr_list
[0][0] == 127 &&
5342 strcmp(name
, "localhost") != 0)
5344 /* hostname != "localhost" but has loopback address. replace by our
5345 * special address.*/
5346 memcpy(retval
->h_addr_list
[0], magic_loopback_addr
, 4);
5348 TRACE( "%s ret %p\n", debugstr_a(name
), retval
);
5353 /***********************************************************************
5354 * getprotobyname (WS2_32.53)
5356 struct WS_protoent
* WINAPI
WS_getprotobyname(const char* name
)
5358 struct WS_protoent
* retval
= NULL
;
5359 #ifdef HAVE_GETPROTOBYNAME
5360 struct protoent
* proto
;
5361 EnterCriticalSection( &csWSgetXXXbyYYY
);
5362 if( (proto
= getprotobyname(name
)) != NULL
)
5364 retval
= WS_dup_pe(proto
);
5367 MESSAGE("protocol %s not found; You might want to add "
5368 "this to /etc/protocols\n", debugstr_a(name
) );
5369 SetLastError(WSANO_DATA
);
5371 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5373 TRACE( "%s ret %p\n", debugstr_a(name
), retval
);
5378 /***********************************************************************
5379 * getprotobynumber (WS2_32.54)
5381 struct WS_protoent
* WINAPI
WS_getprotobynumber(int number
)
5383 struct WS_protoent
* retval
= NULL
;
5384 #ifdef HAVE_GETPROTOBYNUMBER
5385 struct protoent
* proto
;
5386 EnterCriticalSection( &csWSgetXXXbyYYY
);
5387 if( (proto
= getprotobynumber(number
)) != NULL
)
5389 retval
= WS_dup_pe(proto
);
5392 MESSAGE("protocol number %d not found; You might want to add "
5393 "this to /etc/protocols\n", number
);
5394 SetLastError(WSANO_DATA
);
5396 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5398 TRACE("%i ret %p\n", number
, retval
);
5403 /***********************************************************************
5404 * getservbyname (WS2_32.55)
5406 struct WS_servent
* WINAPI
WS_getservbyname(const char *name
, const char *proto
)
5408 struct WS_servent
* retval
= NULL
;
5409 struct servent
* serv
;
5411 char *proto_str
= NULL
;
5413 if (!(name_str
= strdup_lower(name
))) return NULL
;
5415 if (proto
&& *proto
)
5417 if (!(proto_str
= strdup_lower(proto
)))
5419 HeapFree( GetProcessHeap(), 0, name_str
);
5424 EnterCriticalSection( &csWSgetXXXbyYYY
);
5425 serv
= getservbyname(name_str
, proto_str
);
5428 retval
= WS_dup_se(serv
);
5430 else SetLastError(WSANO_DATA
);
5431 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5432 HeapFree( GetProcessHeap(), 0, proto_str
);
5433 HeapFree( GetProcessHeap(), 0, name_str
);
5434 TRACE( "%s, %s ret %p\n", debugstr_a(name
), debugstr_a(proto
), retval
);
5438 /***********************************************************************
5439 * freeaddrinfo (WS2_32.@)
5441 void WINAPI
WS_freeaddrinfo(struct WS_addrinfo
*res
)
5444 struct WS_addrinfo
*next
;
5446 HeapFree(GetProcessHeap(),0,res
->ai_canonname
);
5447 HeapFree(GetProcessHeap(),0,res
->ai_addr
);
5448 next
= res
->ai_next
;
5449 HeapFree(GetProcessHeap(),0,res
);
5454 /* helper functions for getaddrinfo()/getnameinfo() */
5455 static int convert_aiflag_w2u(int winflags
) {
5459 for (i
=0;i
<sizeof(ws_aiflag_map
)/sizeof(ws_aiflag_map
[0]);i
++)
5460 if (ws_aiflag_map
[i
][0] & winflags
) {
5461 unixflags
|= ws_aiflag_map
[i
][1];
5462 winflags
&= ~ws_aiflag_map
[i
][0];
5465 FIXME("Unhandled windows AI_xxx flags %x\n", winflags
);
5469 static int convert_niflag_w2u(int winflags
) {
5473 for (i
=0;i
<sizeof(ws_niflag_map
)/sizeof(ws_niflag_map
[0]);i
++)
5474 if (ws_niflag_map
[i
][0] & winflags
) {
5475 unixflags
|= ws_niflag_map
[i
][1];
5476 winflags
&= ~ws_niflag_map
[i
][0];
5479 FIXME("Unhandled windows NI_xxx flags %x\n", winflags
);
5483 static int convert_aiflag_u2w(int unixflags
) {
5487 for (i
=0;i
<sizeof(ws_aiflag_map
)/sizeof(ws_aiflag_map
[0]);i
++)
5488 if (ws_aiflag_map
[i
][1] & unixflags
) {
5489 winflags
|= ws_aiflag_map
[i
][0];
5490 unixflags
&= ~ws_aiflag_map
[i
][1];
5492 if (unixflags
) /* will warn usually */
5493 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags
);
5497 static int convert_eai_u2w(int unixret
) {
5500 if (!unixret
) return 0;
5502 for (i
=0;ws_eai_map
[i
][0];i
++)
5503 if (ws_eai_map
[i
][1] == unixret
)
5504 return ws_eai_map
[i
][0];
5506 if (unixret
== EAI_SYSTEM
)
5507 /* There are broken versions of glibc which return EAI_SYSTEM
5508 * and set errno to 0 instead of returning EAI_NONAME.
5510 return errno
? sock_get_error( errno
) : WS_EAI_NONAME
;
5512 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret
);
5516 static char *get_hostname(void)
5521 GetComputerNameExA( ComputerNamePhysicalDnsHostname
, NULL
, &size
);
5522 if (GetLastError() != ERROR_MORE_DATA
) return NULL
;
5523 if (!(ret
= HeapAlloc( GetProcessHeap(), 0, size
))) return NULL
;
5524 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname
, ret
, &size
))
5526 HeapFree( GetProcessHeap(), 0, ret
);
5532 /***********************************************************************
5533 * getaddrinfo (WS2_32.@)
5535 int WINAPI
WS_getaddrinfo(LPCSTR nodename
, LPCSTR servname
, const struct WS_addrinfo
*hints
, struct WS_addrinfo
**res
)
5537 #ifdef HAVE_GETADDRINFO
5538 struct addrinfo
*unixaires
= NULL
;
5540 struct addrinfo unixhints
, *punixhints
= NULL
;
5541 char *hostname
= NULL
;
5545 if (!nodename
&& !servname
) return WSAHOST_NOT_FOUND
;
5549 else if (!nodename
[0])
5551 node
= hostname
= get_hostname();
5552 if (!node
) return WSA_NOT_ENOUGH_MEMORY
;
5557 /* servname tweak required by OSX and BSD kernels */
5558 if (servname
&& !servname
[0]) servname
= "0";
5561 punixhints
= &unixhints
;
5563 memset(&unixhints
, 0, sizeof(unixhints
));
5564 punixhints
->ai_flags
= convert_aiflag_w2u(hints
->ai_flags
);
5566 /* zero is a wildcard, no need to convert */
5567 if (hints
->ai_family
)
5568 punixhints
->ai_family
= convert_af_w2u(hints
->ai_family
);
5569 if (hints
->ai_socktype
)
5570 punixhints
->ai_socktype
= convert_socktype_w2u(hints
->ai_socktype
);
5571 if (hints
->ai_protocol
)
5572 punixhints
->ai_protocol
= max(convert_proto_w2u(hints
->ai_protocol
), 0);
5574 if (punixhints
->ai_socktype
< 0)
5576 WSASetLastError(WSAESOCKTNOSUPPORT
);
5577 HeapFree(GetProcessHeap(), 0, hostname
);
5578 return SOCKET_ERROR
;
5581 /* windows allows invalid combinations of socket type and protocol, unix does not.
5582 * fix the parameters here to make getaddrinfo call always work */
5583 if (punixhints
->ai_protocol
== IPPROTO_TCP
&&
5584 punixhints
->ai_socktype
!= SOCK_STREAM
&& punixhints
->ai_socktype
!= SOCK_SEQPACKET
)
5585 punixhints
->ai_socktype
= 0;
5587 else if (punixhints
->ai_protocol
== IPPROTO_UDP
&& punixhints
->ai_socktype
!= SOCK_DGRAM
)
5588 punixhints
->ai_socktype
= 0;
5590 else if (IS_IPX_PROTO(punixhints
->ai_protocol
) && punixhints
->ai_socktype
!= SOCK_DGRAM
)
5591 punixhints
->ai_socktype
= 0;
5594 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
5595 result
= getaddrinfo(node
, servname
, punixhints
, &unixaires
);
5597 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename
), debugstr_a(servname
), hints
, res
, result
);
5598 HeapFree(GetProcessHeap(), 0, hostname
);
5601 struct addrinfo
*xuai
= unixaires
;
5602 struct WS_addrinfo
**xai
= res
;
5606 struct WS_addrinfo
*ai
= HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY
, sizeof(struct WS_addrinfo
));
5612 *xai
= ai
;xai
= &ai
->ai_next
;
5613 ai
->ai_flags
= convert_aiflag_u2w(xuai
->ai_flags
);
5614 ai
->ai_family
= convert_af_u2w(xuai
->ai_family
);
5615 /* copy whatever was sent in the hints */
5617 ai
->ai_socktype
= hints
->ai_socktype
;
5618 ai
->ai_protocol
= hints
->ai_protocol
;
5620 ai
->ai_socktype
= convert_socktype_u2w(xuai
->ai_socktype
);
5621 ai
->ai_protocol
= convert_proto_u2w(xuai
->ai_protocol
);
5623 if (xuai
->ai_canonname
) {
5624 TRACE("canon name - %s\n",debugstr_a(xuai
->ai_canonname
));
5625 ai
->ai_canonname
= HeapAlloc(GetProcessHeap(),0,strlen(xuai
->ai_canonname
)+1);
5626 if (!ai
->ai_canonname
)
5628 strcpy(ai
->ai_canonname
,xuai
->ai_canonname
);
5630 len
= xuai
->ai_addrlen
;
5631 ai
->ai_addr
= HeapAlloc(GetProcessHeap(),0,len
);
5634 ai
->ai_addrlen
= len
;
5636 int winlen
= ai
->ai_addrlen
;
5638 if (!ws_sockaddr_u2ws(xuai
->ai_addr
, ai
->ai_addr
, &winlen
)) {
5639 ai
->ai_addrlen
= winlen
;
5643 ai
->ai_addr
= HeapReAlloc(GetProcessHeap(),0,ai
->ai_addr
,len
);
5646 ai
->ai_addrlen
= len
;
5648 xuai
= xuai
->ai_next
;
5650 freeaddrinfo(unixaires
);
5652 if (TRACE_ON(winsock
))
5654 struct WS_addrinfo
*ai
= *res
;
5657 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
5658 ai
, ai
->ai_flags
, ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
, ai
->ai_addrlen
,
5659 ai
->ai_canonname
, debugstr_sockaddr(ai
->ai_addr
));
5664 result
= convert_eai_u2w(result
);
5669 if (*res
) WS_freeaddrinfo(*res
);
5670 if (unixaires
) freeaddrinfo(unixaires
);
5671 return WSA_NOT_ENOUGH_MEMORY
;
5673 FIXME("getaddrinfo() failed, not found during buildtime.\n");
5678 static struct WS_addrinfoW
*addrinfo_AtoW(const struct WS_addrinfo
*ai
)
5680 struct WS_addrinfoW
*ret
;
5682 if (!(ret
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW
)))) return NULL
;
5683 ret
->ai_flags
= ai
->ai_flags
;
5684 ret
->ai_family
= ai
->ai_family
;
5685 ret
->ai_socktype
= ai
->ai_socktype
;
5686 ret
->ai_protocol
= ai
->ai_protocol
;
5687 ret
->ai_addrlen
= ai
->ai_addrlen
;
5688 ret
->ai_canonname
= NULL
;
5689 ret
->ai_addr
= NULL
;
5690 ret
->ai_next
= NULL
;
5691 if (ai
->ai_canonname
)
5693 int len
= MultiByteToWideChar(CP_ACP
, 0, ai
->ai_canonname
, -1, NULL
, 0);
5694 if (!(ret
->ai_canonname
= HeapAlloc(GetProcessHeap(), 0, len
)))
5696 HeapFree(GetProcessHeap(), 0, ret
);
5699 MultiByteToWideChar(CP_ACP
, 0, ai
->ai_canonname
, -1, ret
->ai_canonname
, len
);
5703 if (!(ret
->ai_addr
= HeapAlloc(GetProcessHeap(), 0, ai
->ai_addrlen
)))
5705 HeapFree(GetProcessHeap(), 0, ret
->ai_canonname
);
5706 HeapFree(GetProcessHeap(), 0, ret
);
5709 memcpy(ret
->ai_addr
, ai
->ai_addr
, ai
->ai_addrlen
);
5714 static struct WS_addrinfoW
*addrinfo_list_AtoW(const struct WS_addrinfo
*info
)
5716 struct WS_addrinfoW
*ret
, *infoW
;
5718 if (!(ret
= infoW
= addrinfo_AtoW(info
))) return NULL
;
5719 while (info
->ai_next
)
5721 if (!(infoW
->ai_next
= addrinfo_AtoW(info
->ai_next
)))
5726 infoW
= infoW
->ai_next
;
5727 info
= info
->ai_next
;
5732 static struct WS_addrinfo
*addrinfo_WtoA(const struct WS_addrinfoW
*ai
)
5734 struct WS_addrinfo
*ret
;
5736 if (!(ret
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo
)))) return NULL
;
5737 ret
->ai_flags
= ai
->ai_flags
;
5738 ret
->ai_family
= ai
->ai_family
;
5739 ret
->ai_socktype
= ai
->ai_socktype
;
5740 ret
->ai_protocol
= ai
->ai_protocol
;
5741 ret
->ai_addrlen
= ai
->ai_addrlen
;
5742 ret
->ai_canonname
= NULL
;
5743 ret
->ai_addr
= NULL
;
5744 ret
->ai_next
= NULL
;
5745 if (ai
->ai_canonname
)
5747 int len
= WideCharToMultiByte(CP_ACP
, 0, ai
->ai_canonname
, -1, NULL
, 0, NULL
, NULL
);
5748 if (!(ret
->ai_canonname
= HeapAlloc(GetProcessHeap(), 0, len
)))
5750 HeapFree(GetProcessHeap(), 0, ret
);
5753 WideCharToMultiByte(CP_ACP
, 0, ai
->ai_canonname
, -1, ret
->ai_canonname
, len
, NULL
, NULL
);
5757 if (!(ret
->ai_addr
= HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr
))))
5759 HeapFree(GetProcessHeap(), 0, ret
->ai_canonname
);
5760 HeapFree(GetProcessHeap(), 0, ret
);
5763 memcpy(ret
->ai_addr
, ai
->ai_addr
, sizeof(struct WS_sockaddr
));
5768 /***********************************************************************
5769 * GetAddrInfoW (WS2_32.@)
5771 int WINAPI
GetAddrInfoW(LPCWSTR nodename
, LPCWSTR servname
, const ADDRINFOW
*hints
, PADDRINFOW
*res
)
5774 char *nodenameA
= NULL
, *servnameA
= NULL
;
5775 struct WS_addrinfo
*resA
, *hintsA
= NULL
;
5780 len
= WideCharToMultiByte(CP_ACP
, 0, nodename
, -1, NULL
, 0, NULL
, NULL
);
5781 if (!(nodenameA
= HeapAlloc(GetProcessHeap(), 0, len
))) return EAI_MEMORY
;
5782 WideCharToMultiByte(CP_ACP
, 0, nodename
, -1, nodenameA
, len
, NULL
, NULL
);
5786 len
= WideCharToMultiByte(CP_ACP
, 0, servname
, -1, NULL
, 0, NULL
, NULL
);
5787 if (!(servnameA
= HeapAlloc(GetProcessHeap(), 0, len
)))
5789 HeapFree(GetProcessHeap(), 0, nodenameA
);
5792 WideCharToMultiByte(CP_ACP
, 0, servname
, -1, servnameA
, len
, NULL
, NULL
);
5795 if (hints
) hintsA
= addrinfo_WtoA(hints
);
5796 ret
= WS_getaddrinfo(nodenameA
, servnameA
, hintsA
, &resA
);
5797 WS_freeaddrinfo(hintsA
);
5801 *res
= addrinfo_list_AtoW(resA
);
5802 WS_freeaddrinfo(resA
);
5805 HeapFree(GetProcessHeap(), 0, nodenameA
);
5806 HeapFree(GetProcessHeap(), 0, servnameA
);
5810 /***********************************************************************
5811 * FreeAddrInfoW (WS2_32.@)
5813 void WINAPI
FreeAddrInfoW(PADDRINFOW ai
)
5818 HeapFree(GetProcessHeap(), 0, ai
->ai_canonname
);
5819 HeapFree(GetProcessHeap(), 0, ai
->ai_addr
);
5821 HeapFree(GetProcessHeap(), 0, ai
);
5826 int WINAPI
WS_getnameinfo(const SOCKADDR
*sa
, WS_socklen_t salen
, PCHAR host
,
5827 DWORD hostlen
, PCHAR serv
, DWORD servlen
, INT flags
)
5829 #ifdef HAVE_GETNAMEINFO
5831 union generic_unix_sockaddr sa_u
;
5834 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa
), salen
, host
, hostlen
,
5835 serv
, servlen
, flags
);
5837 size
= ws_sockaddr_ws2u(sa
, salen
, &sa_u
);
5840 WSASetLastError(WSAEFAULT
);
5841 return WSA_NOT_ENOUGH_MEMORY
;
5843 ret
= getnameinfo(&sa_u
.addr
, size
, host
, hostlen
, serv
, servlen
, convert_niflag_w2u(flags
));
5844 return convert_eai_u2w(ret
);
5846 FIXME("getnameinfo() failed, not found during buildtime.\n");
5851 int WINAPI
GetNameInfoW(const SOCKADDR
*sa
, WS_socklen_t salen
, PWCHAR host
,
5852 DWORD hostlen
, PWCHAR serv
, DWORD servlen
, INT flags
)
5855 char *hostA
= NULL
, *servA
= NULL
;
5857 if (host
&& (!(hostA
= HeapAlloc(GetProcessHeap(), 0, hostlen
)))) return EAI_MEMORY
;
5858 if (serv
&& (!(servA
= HeapAlloc(GetProcessHeap(), 0, servlen
))))
5860 HeapFree(GetProcessHeap(), 0, hostA
);
5864 ret
= WS_getnameinfo(sa
, salen
, hostA
, hostlen
, servA
, servlen
, flags
);
5867 if (host
) MultiByteToWideChar(CP_ACP
, 0, hostA
, -1, host
, hostlen
);
5868 if (serv
) MultiByteToWideChar(CP_ACP
, 0, servA
, -1, serv
, servlen
);
5871 HeapFree(GetProcessHeap(), 0, hostA
);
5872 HeapFree(GetProcessHeap(), 0, servA
);
5876 /***********************************************************************
5877 * getservbyport (WS2_32.56)
5879 struct WS_servent
* WINAPI
WS_getservbyport(int port
, const char *proto
)
5881 struct WS_servent
* retval
= NULL
;
5882 #ifdef HAVE_GETSERVBYPORT
5883 struct servent
* serv
;
5884 char *proto_str
= NULL
;
5886 if (proto
&& *proto
)
5888 if (!(proto_str
= strdup_lower(proto
))) return NULL
;
5890 EnterCriticalSection( &csWSgetXXXbyYYY
);
5891 if( (serv
= getservbyport(port
, proto_str
)) != NULL
) {
5892 retval
= WS_dup_se(serv
);
5894 else SetLastError(WSANO_DATA
);
5895 LeaveCriticalSection( &csWSgetXXXbyYYY
);
5896 HeapFree( GetProcessHeap(), 0, proto_str
);
5898 TRACE("%d (i.e. port %d), %s ret %p\n", port
, (int)ntohl(port
), debugstr_a(proto
), retval
);
5903 /***********************************************************************
5904 * gethostname (WS2_32.57)
5906 int WINAPI
WS_gethostname(char *name
, int namelen
)
5908 TRACE("name %p, len %d\n", name
, namelen
);
5910 if (gethostname(name
, namelen
) == 0)
5912 TRACE("<- '%s'\n", name
);
5915 SetLastError((errno
== EINVAL
) ? WSAEFAULT
: wsaErrno());
5916 TRACE("<- ERROR !\n");
5917 return SOCKET_ERROR
;
5921 /* ------------------------------------- Windows sockets extensions -- *
5923 * ------------------------------------------------------------------- */
5925 /***********************************************************************
5926 * WSAEnumNetworkEvents (WS2_32.36)
5928 int WINAPI
WSAEnumNetworkEvents(SOCKET s
, WSAEVENT hEvent
, LPWSANETWORKEVENTS lpEvent
)
5932 int errors
[FD_MAX_EVENTS
];
5934 TRACE("%08lx, hEvent %p, lpEvent %p\n", s
, hEvent
, lpEvent
);
5936 SERVER_START_REQ( get_socket_event
)
5938 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
5939 req
->service
= TRUE
;
5940 req
->c_event
= wine_server_obj_handle( hEvent
);
5941 wine_server_set_reply( req
, errors
, sizeof(errors
) );
5942 if (!(ret
= wine_server_call(req
))) lpEvent
->lNetworkEvents
= reply
->pmask
& reply
->mask
;
5947 for (i
= 0; i
< FD_MAX_EVENTS
; i
++)
5948 lpEvent
->iErrorCode
[i
] = NtStatusToWSAError(errors
[i
]);
5951 SetLastError(WSAEINVAL
);
5952 return SOCKET_ERROR
;
5955 /***********************************************************************
5956 * WSAEventSelect (WS2_32.39)
5958 int WINAPI
WSAEventSelect(SOCKET s
, WSAEVENT hEvent
, LONG lEvent
)
5962 TRACE("%08lx, hEvent %p, event %08x\n", s
, hEvent
, lEvent
);
5964 SERVER_START_REQ( set_socket_event
)
5966 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
5968 req
->event
= wine_server_obj_handle( hEvent
);
5971 ret
= wine_server_call( req
);
5975 SetLastError(WSAEINVAL
);
5976 return SOCKET_ERROR
;
5979 /**********************************************************************
5980 * WSAGetOverlappedResult (WS2_32.40)
5982 BOOL WINAPI
WSAGetOverlappedResult( SOCKET s
, LPWSAOVERLAPPED lpOverlapped
,
5983 LPDWORD lpcbTransfer
, BOOL fWait
,
5988 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
5989 s
, lpOverlapped
, lpcbTransfer
, fWait
, lpdwFlags
);
5991 if ( lpOverlapped
== NULL
)
5993 ERR( "Invalid pointer\n" );
5994 WSASetLastError(WSA_INVALID_PARAMETER
);
5998 status
= lpOverlapped
->Internal
;
5999 if (status
== STATUS_PENDING
)
6003 SetLastError( WSA_IO_INCOMPLETE
);
6007 if (WaitForSingleObject( lpOverlapped
->hEvent
? lpOverlapped
->hEvent
: SOCKET2HANDLE(s
),
6008 INFINITE
) == WAIT_FAILED
)
6010 status
= lpOverlapped
->Internal
;
6014 *lpcbTransfer
= lpOverlapped
->InternalHigh
;
6017 *lpdwFlags
= lpOverlapped
->u
.s
.Offset
;
6019 if (status
) SetLastError( RtlNtStatusToDosError(status
) );
6024 /***********************************************************************
6025 * WSAAsyncSelect (WS2_32.101)
6027 INT WINAPI
WSAAsyncSelect(SOCKET s
, HWND hWnd
, UINT uMsg
, LONG lEvent
)
6031 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s
, hWnd
, uMsg
, lEvent
);
6033 SERVER_START_REQ( set_socket_event
)
6035 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
6038 req
->window
= wine_server_user_handle( hWnd
);
6040 ret
= wine_server_call( req
);
6044 SetLastError(WSAEINVAL
);
6045 return SOCKET_ERROR
;
6048 /***********************************************************************
6049 * WSACreateEvent (WS2_32.31)
6052 WSAEVENT WINAPI
WSACreateEvent(void)
6054 /* Create a manual-reset event, with initial state: unsignaled */
6057 return CreateEventW(NULL
, TRUE
, FALSE
, NULL
);
6060 /***********************************************************************
6061 * WSACloseEvent (WS2_32.29)
6064 BOOL WINAPI
WSACloseEvent(WSAEVENT event
)
6066 TRACE ("event=%p\n", event
);
6068 return CloseHandle(event
);
6071 /***********************************************************************
6072 * WSASocketA (WS2_32.78)
6075 SOCKET WINAPI
WSASocketA(int af
, int type
, int protocol
,
6076 LPWSAPROTOCOL_INFOA lpProtocolInfo
,
6077 GROUP g
, DWORD dwFlags
)
6080 WSAPROTOCOL_INFOW info
;
6082 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6083 af
, type
, protocol
, lpProtocolInfo
, g
, dwFlags
);
6085 if (!lpProtocolInfo
) return WSASocketW(af
, type
, protocol
, NULL
, g
, dwFlags
);
6087 memcpy(&info
, lpProtocolInfo
, FIELD_OFFSET(WSAPROTOCOL_INFOW
, szProtocol
));
6088 len
= MultiByteToWideChar(CP_ACP
, 0, lpProtocolInfo
->szProtocol
, -1,
6089 info
.szProtocol
, WSAPROTOCOL_LEN
+ 1);
6093 WSASetLastError( WSAEINVAL
);
6094 return SOCKET_ERROR
;
6097 return WSASocketW(af
, type
, protocol
, &info
, g
, dwFlags
);
6100 /***********************************************************************
6101 * WSASocketW (WS2_32.79)
6104 SOCKET WINAPI
WSASocketW(int af
, int type
, int protocol
,
6105 LPWSAPROTOCOL_INFOW lpProtocolInfo
,
6106 GROUP g
, DWORD dwFlags
)
6110 int unixaf
, unixtype
, ipxptype
= -1;
6113 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
6114 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
6117 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6118 af
, type
, protocol
, lpProtocolInfo
, g
, dwFlags
);
6122 err
= WSANOTINITIALISED
;
6126 /* hack for WSADuplicateSocket */
6127 if (lpProtocolInfo
&& lpProtocolInfo
->dwServiceFlags4
== 0xff00ff00) {
6128 ret
= lpProtocolInfo
->dwServiceFlags3
;
6129 TRACE("\tgot duplicate %04lx\n", ret
);
6135 if (af
== FROM_PROTOCOL_INFO
|| !af
)
6136 af
= lpProtocolInfo
->iAddressFamily
;
6137 if (type
== FROM_PROTOCOL_INFO
|| !type
)
6138 type
= lpProtocolInfo
->iSocketType
;
6139 if (protocol
== FROM_PROTOCOL_INFO
|| !protocol
)
6140 protocol
= lpProtocolInfo
->iProtocol
;
6143 if (!type
&& (af
|| protocol
))
6145 int autoproto
= protocol
;
6146 WSAPROTOCOL_INFOW infow
;
6148 /* default to the first valid protocol */
6150 autoproto
= valid_protocols
[0];
6151 else if(IS_IPX_PROTO(autoproto
))
6152 autoproto
= WS_NSPROTO_IPX
;
6154 if (WS_EnterSingleProtocolW(autoproto
, &infow
))
6156 type
= infow
.iSocketType
;
6158 /* after win2003 it's no longer possible to pass AF_UNSPEC
6159 using the protocol info struct */
6160 if (!lpProtocolInfo
&& af
== WS_AF_UNSPEC
)
6161 af
= infow
.iAddressFamily
;
6166 Windows has an extension to the IPX protocol that allows one to create sockets
6167 and set the IPX packet type at the same time, to do that a caller will use
6168 a protocol like NSPROTO_IPX + <PACKET TYPE>
6170 if (IS_IPX_PROTO(protocol
))
6171 ipxptype
= protocol
- WS_NSPROTO_IPX
;
6173 /* convert the socket family, type and protocol */
6174 unixaf
= convert_af_w2u(af
);
6175 unixtype
= convert_socktype_w2u(type
);
6176 protocol
= convert_proto_w2u(protocol
);
6177 if (unixaf
== AF_UNSPEC
) unixaf
= -1;
6179 /* filter invalid parameters */
6182 /* the type could not be converted */
6183 if (type
&& unixtype
< 0)
6185 err
= WSAESOCKTNOSUPPORT
;
6189 err
= WSAEPROTONOSUPPORT
;
6194 /* both family and protocol can't be invalid */
6201 /* family could not be converted and neither socket type */
6202 if (unixtype
< 0 && af
>= 0)
6205 err
= WSAESOCKTNOSUPPORT
;
6209 err
= WSAEAFNOSUPPORT
;
6213 SERVER_START_REQ( create_socket
)
6215 req
->family
= unixaf
;
6216 req
->type
= unixtype
;
6217 req
->protocol
= protocol
;
6218 req
->access
= GENERIC_READ
|GENERIC_WRITE
|SYNCHRONIZE
;
6219 req
->attributes
= OBJ_INHERIT
;
6220 req
->flags
= dwFlags
;
6221 set_error( wine_server_call( req
) );
6222 ret
= HANDLE2SOCKET( wine_server_ptr_handle( reply
->handle
));
6227 TRACE("\tcreated %04lx\n", ret
);
6229 set_ipx_packettype(ret
, ipxptype
);
6233 err
= GetLastError();
6234 if (err
== WSAEACCES
) /* raw socket denied */
6236 if (type
== SOCK_RAW
)
6237 ERR_(winediag
)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
6239 ERR_(winediag
)("Failed to create socket, this requires special permissions.\n");
6243 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
6244 if (err
== WSAEINVAL
)
6245 err
= WSAESOCKTNOSUPPORT
;
6246 else if (err
== WSAEOPNOTSUPP
)
6247 err
= WSAEPROTONOSUPPORT
;
6251 WARN("\t\tfailed, error %d!\n", err
);
6253 return INVALID_SOCKET
;
6256 /***********************************************************************
6257 * WSAJoinLeaf (WS2_32.58)
6260 SOCKET WINAPI
WSAJoinLeaf(
6262 const struct WS_sockaddr
*addr
,
6264 LPWSABUF lpCallerData
,
6265 LPWSABUF lpCalleeData
,
6271 return INVALID_SOCKET
;
6274 /***********************************************************************
6275 * __WSAFDIsSet (WS2_32.151)
6277 int WINAPI
__WSAFDIsSet(SOCKET s
, WS_fd_set
*set
)
6279 int i
= set
->fd_count
;
6281 TRACE("(%ld,%p(%i))\n", s
, set
, i
);
6284 if (set
->fd_array
[i
] == s
) return 1;
6288 /***********************************************************************
6289 * WSAIsBlocking (WS2_32.114)
6291 BOOL WINAPI
WSAIsBlocking(void)
6293 /* By default WinSock should set all its sockets to non-blocking mode
6294 * and poll in PeekMessage loop when processing "blocking" ones. This
6295 * function is supposed to tell if the program is in this loop. Our
6296 * blocking calls are truly blocking so we always return FALSE.
6298 * Note: It is allowed to call this function without prior WSAStartup().
6305 /***********************************************************************
6306 * WSACancelBlockingCall (WS2_32.113)
6308 INT WINAPI
WSACancelBlockingCall(void)
6314 static INT WINAPI
WSA_DefaultBlockingHook( FARPROC x
)
6316 FIXME("How was this called?\n");
6321 /***********************************************************************
6322 * WSASetBlockingHook (WS2_32.109)
6324 FARPROC WINAPI
WSASetBlockingHook(FARPROC lpBlockFunc
)
6326 FARPROC prev
= blocking_hook
;
6327 blocking_hook
= lpBlockFunc
;
6328 TRACE("hook %p\n", lpBlockFunc
);
6333 /***********************************************************************
6334 * WSAUnhookBlockingHook (WS2_32.110)
6336 INT WINAPI
WSAUnhookBlockingHook(void)
6338 blocking_hook
= (FARPROC
)WSA_DefaultBlockingHook
;
6343 /* ----------------------------------- end of API stuff */
6345 /* ----------------------------------- helper functions -
6347 * TODO: Merge WS_dup_..() stuff into one function that
6348 * would operate with a generic structure containing internal
6349 * pointers (via a template of some kind).
6352 static int list_size(char** l
, int item_size
)
6357 j
+= (item_size
) ? item_size
: strlen(l
[i
]) + 1;
6358 j
+= (i
+ 1) * sizeof(char*); }
6362 static int list_dup(char** l_src
, char** l_to
, int item_size
)
6367 for (i
= 0; l_src
[i
]; i
++) ;
6368 p
= (char *)(l_to
+ i
+ 1);
6369 for (i
= 0; l_src
[i
]; i
++)
6371 int count
= ( item_size
) ? item_size
: strlen(l_src
[i
]) + 1;
6372 memcpy(p
, l_src
[i
], count
);
6377 return p
- (char *)l_to
;
6382 /* create a hostent entry
6384 * Creates the entry with enough memory for the name, aliases
6385 * addresses, and the address pointers. Also copies the name
6386 * and sets up all the pointers.
6388 * NOTE: The alias and address lists must be allocated with room
6389 * for the NULL item terminating the list. This is true even if
6390 * the list has no items ("aliases" and "addresses" must be
6391 * at least "1", a truly empty list is invalid).
6393 static struct WS_hostent
*WS_create_he(char *name
, int aliases
, int aliases_size
, int addresses
, int address_length
)
6395 struct WS_hostent
*p_to
;
6397 int size
= (sizeof(struct WS_hostent
) +
6399 sizeof(char *) * aliases
+
6401 sizeof(char *) * addresses
+
6402 address_length
* (addresses
- 1)), i
;
6404 if (!(p_to
= check_buffer_he(size
))) return NULL
;
6405 memset(p_to
, 0, size
);
6407 /* Use the memory in the same way winsock does.
6408 * First set the pointer for aliases, second set the pointers for addresses.
6409 * Third fill the addresses indexes, fourth jump aliases names size.
6410 * Fifth fill the hostname.
6411 * NOTE: This method is valid for OS version's >= XP.
6413 p
= (char *)(p_to
+ 1);
6414 p_to
->h_aliases
= (char **)p
;
6415 p
+= sizeof(char *)*aliases
;
6417 p_to
->h_addr_list
= (char **)p
;
6418 p
+= sizeof(char *)*addresses
;
6420 for (i
= 0, addresses
--; i
< addresses
; i
++, p
+= address_length
)
6421 p_to
->h_addr_list
[i
] = p
;
6423 /* NOTE: h_aliases must be filled in manually because we don't know each string
6424 * size, leave these pointers NULL (already set to NULL by memset earlier).
6434 /* duplicate hostent entry
6435 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
6436 * Ditto for protoent and servent.
6438 static struct WS_hostent
*WS_dup_he(const struct hostent
* p_he
)
6440 int i
, addresses
= 0, alias_size
= 0;
6441 struct WS_hostent
*p_to
;
6444 for( i
= 0; p_he
->h_aliases
[i
]; i
++) alias_size
+= strlen(p_he
->h_aliases
[i
]) + 1;
6445 while (p_he
->h_addr_list
[addresses
]) addresses
++;
6447 p_to
= WS_create_he(p_he
->h_name
, i
+ 1, alias_size
, addresses
+ 1, p_he
->h_length
);
6449 if (!p_to
) return NULL
;
6450 p_to
->h_addrtype
= convert_af_u2w(p_he
->h_addrtype
);
6451 p_to
->h_length
= p_he
->h_length
;
6453 for(i
= 0, p
= p_to
->h_addr_list
[0]; p_he
->h_addr_list
[i
]; i
++, p
+= p_to
->h_length
)
6454 memcpy(p
, p_he
->h_addr_list
[i
], p_to
->h_length
);
6456 /* Fill the aliases after the IP data */
6457 for(i
= 0; p_he
->h_aliases
[i
]; i
++)
6459 p_to
->h_aliases
[i
] = p
;
6460 strcpy(p
, p_he
->h_aliases
[i
]);
6467 /* ----- protoent */
6469 static struct WS_protoent
*WS_dup_pe(const struct protoent
* p_pe
)
6472 struct WS_protoent
*p_to
;
6474 int size
= (sizeof(*p_pe
) +
6475 strlen(p_pe
->p_name
) + 1 +
6476 list_size(p_pe
->p_aliases
, 0));
6478 if (!(p_to
= check_buffer_pe(size
))) return NULL
;
6479 p_to
->p_proto
= p_pe
->p_proto
;
6481 p
= (char *)(p_to
+ 1);
6483 strcpy(p
, p_pe
->p_name
);
6486 p_to
->p_aliases
= (char **)p
;
6487 list_dup(p_pe
->p_aliases
, p_to
->p_aliases
, 0);
6493 static struct WS_servent
*WS_dup_se(const struct servent
* p_se
)
6496 struct WS_servent
*p_to
;
6498 int size
= (sizeof(*p_se
) +
6499 strlen(p_se
->s_proto
) + 1 +
6500 strlen(p_se
->s_name
) + 1 +
6501 list_size(p_se
->s_aliases
, 0));
6503 if (!(p_to
= check_buffer_se(size
))) return NULL
;
6504 p_to
->s_port
= p_se
->s_port
;
6506 p
= (char *)(p_to
+ 1);
6508 strcpy(p
, p_se
->s_name
);
6512 strcpy(p
, p_se
->s_proto
);
6515 p_to
->s_aliases
= (char **)p
;
6516 list_dup(p_se
->s_aliases
, p_to
->s_aliases
, 0);
6521 /***********************************************************************
6522 * WSARecv (WS2_32.67)
6524 int WINAPI
WSARecv(SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
6525 LPDWORD NumberOfBytesReceived
, LPDWORD lpFlags
,
6526 LPWSAOVERLAPPED lpOverlapped
,
6527 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
6529 return WS2_recv_base(s
, lpBuffers
, dwBufferCount
, NumberOfBytesReceived
, lpFlags
,
6530 NULL
, NULL
, lpOverlapped
, lpCompletionRoutine
, NULL
);
6533 static int WS2_recv_base( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
6534 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
,
6535 struct WS_sockaddr
*lpFrom
,
6536 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
6537 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
,
6538 LPWSABUF lpControlBuffer
)
6540 unsigned int i
, options
;
6541 int n
, fd
, err
, overlapped
;
6542 struct ws2_async
*wsa
, localwsa
;
6544 DWORD timeout_start
= GetTickCount();
6545 ULONG_PTR cvalue
= (lpOverlapped
&& ((ULONG_PTR
)lpOverlapped
->hEvent
& 1) == 0) ? (ULONG_PTR
)lpOverlapped
: 0;
6547 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
6548 s
, lpBuffers
, dwBufferCount
, *lpFlags
, lpFrom
,
6549 (lpFromlen
? *lpFromlen
: -1),
6550 lpOverlapped
, lpCompletionRoutine
);
6552 fd
= get_sock_fd( s
, FILE_READ_DATA
, &options
);
6553 TRACE( "fd=%d, options=%x\n", fd
, options
);
6555 if (fd
== -1) return SOCKET_ERROR
;
6557 overlapped
= (lpOverlapped
|| lpCompletionRoutine
) &&
6558 !(options
& (FILE_SYNCHRONOUS_IO_ALERT
| FILE_SYNCHRONOUS_IO_NONALERT
));
6559 if (overlapped
|| dwBufferCount
> 1)
6561 if (!(wsa
= HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async
, iovec
[dwBufferCount
]) )))
6570 wsa
->hSocket
= SOCKET2HANDLE(s
);
6571 wsa
->flags
= *lpFlags
;
6572 wsa
->lpFlags
= lpFlags
;
6574 wsa
->addrlen
.ptr
= lpFromlen
;
6575 wsa
->control
= lpControlBuffer
;
6576 wsa
->n_iovecs
= dwBufferCount
;
6577 wsa
->first_iovec
= 0;
6578 for (i
= 0; i
< dwBufferCount
; i
++)
6580 /* check buffer first to trigger write watches */
6581 if (IsBadWritePtr( lpBuffers
[i
].buf
, lpBuffers
[i
].len
))
6586 wsa
->iovec
[i
].iov_base
= lpBuffers
[i
].buf
;
6587 wsa
->iovec
[i
].iov_len
= lpBuffers
[i
].len
;
6592 n
= WS2_recv( fd
, wsa
);
6595 if (errno
!= EAGAIN
)
6597 int loc_errno
= errno
;
6599 if (cvalue
) WS_AddCompletion( s
, cvalue
, sock_get_ntstatus(loc_errno
), 0 );
6603 else if (lpNumberOfBytesRecvd
) *lpNumberOfBytesRecvd
= n
;
6607 IO_STATUS_BLOCK
*iosb
= lpOverlapped
? (IO_STATUS_BLOCK
*)lpOverlapped
: &wsa
->local_iosb
;
6609 wsa
->user_overlapped
= lpOverlapped
;
6610 wsa
->completion_func
= lpCompletionRoutine
;
6611 release_sock_fd( s
, fd
);
6615 iosb
->u
.Status
= STATUS_PENDING
;
6616 iosb
->Information
= 0;
6618 SERVER_START_REQ( register_async
)
6620 req
->type
= ASYNC_TYPE_READ
;
6621 req
->async
.handle
= wine_server_obj_handle( wsa
->hSocket
);
6622 req
->async
.callback
= wine_server_client_ptr( WS2_async_recv
);
6623 req
->async
.iosb
= wine_server_client_ptr( iosb
);
6624 req
->async
.arg
= wine_server_client_ptr( wsa
);
6625 req
->async
.event
= wine_server_obj_handle( lpCompletionRoutine
? 0 : lpOverlapped
->hEvent
);
6626 req
->async
.cvalue
= cvalue
;
6627 err
= wine_server_call( req
);
6631 if (err
!= STATUS_PENDING
) HeapFree( GetProcessHeap(), 0, wsa
);
6632 WSASetLastError( NtStatusToWSAError( err
));
6633 return SOCKET_ERROR
;
6636 iosb
->u
.Status
= STATUS_SUCCESS
;
6637 iosb
->Information
= n
;
6638 if (!wsa
->completion_func
)
6640 if (cvalue
) WS_AddCompletion( s
, cvalue
, STATUS_SUCCESS
, n
);
6641 if (lpOverlapped
->hEvent
) SetEvent( lpOverlapped
->hEvent
);
6642 HeapFree( GetProcessHeap(), 0, wsa
);
6644 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC
)ws2_async_apc
,
6645 (ULONG_PTR
)wsa
, (ULONG_PTR
)iosb
, 0 );
6646 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
6652 if ((err
= _is_blocking( s
, &is_blocking
)))
6654 err
= NtStatusToWSAError( err
);
6661 int timeout
= GET_RCVTIMEO(fd
);
6664 timeout
-= GetTickCount() - timeout_start
;
6665 if (timeout
< 0) timeout
= 0;
6669 pfd
.events
= POLLIN
;
6670 if (*lpFlags
& WS_MSG_OOB
) pfd
.events
|= POLLPRI
;
6672 if (!timeout
|| !poll( &pfd
, 1, timeout
))
6675 /* a timeout is not fatal */
6676 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
6682 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
6683 err
= WSAEWOULDBLOCK
;
6688 TRACE(" -> %i bytes\n", n
);
6689 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
6690 release_sock_fd( s
, fd
);
6691 _enable_event(SOCKET2HANDLE(s
), FD_READ
, 0, 0);
6696 if (wsa
!= &localwsa
) HeapFree( GetProcessHeap(), 0, wsa
);
6697 release_sock_fd( s
, fd
);
6698 WARN(" -> ERROR %d\n", err
);
6699 WSASetLastError( err
);
6700 return SOCKET_ERROR
;
6703 /***********************************************************************
6704 * WSARecvFrom (WS2_32.69)
6706 INT WINAPI
WSARecvFrom( SOCKET s
, LPWSABUF lpBuffers
, DWORD dwBufferCount
,
6707 LPDWORD lpNumberOfBytesRecvd
, LPDWORD lpFlags
, struct WS_sockaddr
*lpFrom
,
6708 LPINT lpFromlen
, LPWSAOVERLAPPED lpOverlapped
,
6709 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
)
6712 return WS2_recv_base( s
, lpBuffers
, dwBufferCount
,
6713 lpNumberOfBytesRecvd
, lpFlags
,
6715 lpOverlapped
, lpCompletionRoutine
, NULL
);
6718 /***********************************************************************
6719 * WSCInstallProvider (WS2_32.88)
6721 INT WINAPI
WSCInstallProvider( const LPGUID lpProviderId
,
6722 LPCWSTR lpszProviderDllPath
,
6723 const LPWSAPROTOCOL_INFOW lpProtocolInfoList
,
6724 DWORD dwNumberOfEntries
,
6727 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId
),
6728 debugstr_w(lpszProviderDllPath
), lpProtocolInfoList
,
6729 dwNumberOfEntries
, lpErrno
);
6735 /***********************************************************************
6736 * WSCDeinstallProvider (WS2_32.83)
6738 INT WINAPI
WSCDeinstallProvider(LPGUID lpProviderId
, LPINT lpErrno
)
6740 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId
), lpErrno
);
6746 /***********************************************************************
6747 * WSAAccept (WS2_32.26)
6749 SOCKET WINAPI
WSAAccept( SOCKET s
, struct WS_sockaddr
*addr
, LPINT addrlen
,
6750 LPCONDITIONPROC lpfnCondition
, DWORD_PTR dwCallbackData
)
6754 WSABUF CallerId
, CallerData
, CalleeId
, CalleeData
;
6755 /* QOS SQOS, GQOS; */
6758 SOCKADDR src_addr
, dst_addr
;
6760 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
6761 s
, addr
, addrlen
, lpfnCondition
, dwCallbackData
);
6763 cs
= WS_accept(s
, addr
, addrlen
);
6764 if (cs
== SOCKET_ERROR
) return SOCKET_ERROR
;
6765 if (!lpfnCondition
) return cs
;
6767 if (addr
&& addrlen
)
6769 CallerId
.buf
= (char *)addr
;
6770 CallerId
.len
= *addrlen
;
6774 size
= sizeof(src_addr
);
6775 WS_getpeername(cs
, &src_addr
, &size
);
6776 CallerId
.buf
= (char *)&src_addr
;
6777 CallerId
.len
= size
;
6779 CallerData
.buf
= NULL
;
6782 size
= sizeof(dst_addr
);
6783 WS_getsockname(cs
, &dst_addr
, &size
);
6785 CalleeId
.buf
= (char *)&dst_addr
;
6786 CalleeId
.len
= sizeof(dst_addr
);
6788 ret
= (*lpfnCondition
)(&CallerId
, &CallerData
, NULL
, NULL
,
6789 &CalleeId
, &CalleeData
, &g
, dwCallbackData
);
6796 SERVER_START_REQ( set_socket_deferred
)
6798 req
->handle
= wine_server_obj_handle( SOCKET2HANDLE(s
) );
6799 req
->deferred
= wine_server_obj_handle( SOCKET2HANDLE(cs
) );
6800 if ( !wine_server_call_err ( req
) )
6802 SetLastError( WSATRY_AGAIN
);
6803 WS_closesocket( cs
);
6807 return SOCKET_ERROR
;
6810 SetLastError(WSAECONNREFUSED
);
6811 return SOCKET_ERROR
;
6813 FIXME("Unknown return type from Condition function\n");
6814 SetLastError(WSAENOTSOCK
);
6815 return SOCKET_ERROR
;
6819 /***********************************************************************
6820 * WSADuplicateSocketA (WS2_32.32)
6822 int WINAPI
WSADuplicateSocketA( SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOA lpProtocolInfo
)
6824 return WS_DuplicateSocket(FALSE
, s
, dwProcessId
, (LPWSAPROTOCOL_INFOW
) lpProtocolInfo
);
6827 /***********************************************************************
6828 * WSADuplicateSocketW (WS2_32.33)
6830 int WINAPI
WSADuplicateSocketW( SOCKET s
, DWORD dwProcessId
, LPWSAPROTOCOL_INFOW lpProtocolInfo
)
6832 return WS_DuplicateSocket(TRUE
, s
, dwProcessId
, lpProtocolInfo
);
6835 /***********************************************************************
6836 * WSAInstallServiceClassA (WS2_32.48)
6838 int WINAPI
WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info
)
6840 FIXME("Request to install service %s\n",debugstr_a(info
->lpszServiceClassName
));
6841 WSASetLastError(WSAEACCES
);
6842 return SOCKET_ERROR
;
6845 /***********************************************************************
6846 * WSAInstallServiceClassW (WS2_32.49)
6848 int WINAPI
WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info
)
6850 FIXME("Request to install service %s\n",debugstr_w(info
->lpszServiceClassName
));
6851 WSASetLastError(WSAEACCES
);
6852 return SOCKET_ERROR
;
6855 /***********************************************************************
6856 * WSARemoveServiceClass (WS2_32.70)
6858 int WINAPI
WSARemoveServiceClass(LPGUID info
)
6860 FIXME("Request to remove service %p\n",info
);
6861 WSASetLastError(WSATYPE_NOT_FOUND
);
6862 return SOCKET_ERROR
;
6865 /***********************************************************************
6866 * inet_ntop (WS2_32.@)
6868 PCSTR WINAPI
WS_inet_ntop( INT family
, PVOID addr
, PSTR buffer
, SIZE_T len
)
6870 #ifdef HAVE_INET_NTOP
6871 struct WS_in6_addr
*in6
;
6872 struct WS_in_addr
*in
;
6875 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family
, addr
, buffer
, len
);
6878 WSASetLastError( STATUS_INVALID_PARAMETER
);
6887 pdst
= inet_ntop( AF_INET
, &in
->WS_s_addr
, buffer
, len
);
6893 pdst
= inet_ntop( AF_INET6
, in6
->WS_s6_addr
, buffer
, len
);
6897 WSASetLastError( WSAEAFNOSUPPORT
);
6901 if (!pdst
) WSASetLastError( STATUS_INVALID_PARAMETER
);
6904 FIXME( "not supported on this platform\n" );
6905 WSASetLastError( WSAEAFNOSUPPORT
);
6910 /***********************************************************************
6911 * WSAStringToAddressA (WS2_32.80)
6913 INT WINAPI
WSAStringToAddressA(LPSTR AddressString
,
6915 LPWSAPROTOCOL_INFOA lpProtocolInfo
,
6916 LPSOCKADDR lpAddress
,
6917 LPINT lpAddressLength
)
6920 LPSTR workBuffer
=NULL
,ptrPort
;
6922 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString
), AddressFamily
,
6923 lpProtocolInfo
, lpAddress
, lpAddressLength
);
6925 if (!lpAddressLength
|| !lpAddress
) return SOCKET_ERROR
;
6929 WSASetLastError(WSAEINVAL
);
6930 return SOCKET_ERROR
;
6934 FIXME("ProtocolInfo not implemented.\n");
6936 workBuffer
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
,
6937 strlen(AddressString
) + 1);
6940 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
6941 return SOCKET_ERROR
;
6944 strcpy(workBuffer
, AddressString
);
6946 switch(AddressFamily
)
6950 struct in_addr inetaddr
;
6952 /* If lpAddressLength is too small, tell caller the size we need */
6953 if (*lpAddressLength
< sizeof(SOCKADDR_IN
))
6955 *lpAddressLength
= sizeof(SOCKADDR_IN
);
6959 *lpAddressLength
= sizeof(SOCKADDR_IN
);
6960 memset(lpAddress
, 0, sizeof(SOCKADDR_IN
));
6962 ((LPSOCKADDR_IN
)lpAddress
)->sin_family
= WS_AF_INET
;
6964 ptrPort
= strchr(workBuffer
, ':');
6967 ((LPSOCKADDR_IN
)lpAddress
)->sin_port
= htons(atoi(ptrPort
+1));
6972 ((LPSOCKADDR_IN
)lpAddress
)->sin_port
= 0;
6975 if(inet_aton(workBuffer
, &inetaddr
) > 0)
6977 ((LPSOCKADDR_IN
)lpAddress
)->sin_addr
.WS_s_addr
= inetaddr
.s_addr
;
6988 struct in6_addr inetaddr
;
6989 /* If lpAddressLength is too small, tell caller the size we need */
6990 if (*lpAddressLength
< sizeof(SOCKADDR_IN6
))
6992 *lpAddressLength
= sizeof(SOCKADDR_IN6
);
6996 #ifdef HAVE_INET_PTON
6997 *lpAddressLength
= sizeof(SOCKADDR_IN6
);
6998 memset(lpAddress
, 0, sizeof(SOCKADDR_IN6
));
7000 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_family
= WS_AF_INET6
;
7002 /* This one is a bit tricky. An IPv6 address contains colons, so the
7003 * check from IPv4 doesn't work like that. However, IPv6 addresses that
7004 * contain a port are written with braces like [fd12:3456:7890::1]:12345
7005 * so what we will do is to look for ']', check if the next char is a
7006 * colon, and if it is, parse the port as in IPv4. */
7008 ptrPort
= strchr(workBuffer
, ']');
7009 if(ptrPort
&& *(++ptrPort
) == ':')
7011 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_port
= htons(atoi(ptrPort
+1));
7016 ((LPSOCKADDR_IN6
)lpAddress
)->sin6_port
= 0;
7019 if(inet_pton(AF_INET6
, workBuffer
, &inetaddr
) > 0)
7021 memcpy(&((LPSOCKADDR_IN6
)lpAddress
)->sin6_addr
, &inetaddr
,
7022 sizeof(struct in6_addr
));
7026 #endif /* HAVE_INET_PTON */
7032 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
7033 TRACE("Unsupported address family specified: %d.\n", AddressFamily
);
7037 HeapFree(GetProcessHeap(), 0, workBuffer
);
7040 WSASetLastError(res
);
7041 return SOCKET_ERROR
;
7044 /***********************************************************************
7045 * WSAStringToAddressW (WS2_32.81)
7047 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
7048 * If this should be the case, it would be required to map these digits
7049 * to Unicode digits (0-9) using FoldString first.
7051 INT WINAPI
WSAStringToAddressW(LPWSTR AddressString
,
7053 LPWSAPROTOCOL_INFOW lpProtocolInfo
,
7054 LPSOCKADDR lpAddress
,
7055 LPINT lpAddressLength
)
7058 LPSTR workBuffer
=NULL
;
7059 WSAPROTOCOL_INFOA infoA
;
7060 LPWSAPROTOCOL_INFOA lpProtoInfoA
= NULL
;
7062 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString
), AddressFamily
, lpProtocolInfo
,
7063 lpAddress
, lpAddressLength
);
7065 if (!lpAddressLength
|| !lpAddress
) return SOCKET_ERROR
;
7067 /* if ProtocolInfo is available - convert to ANSI variant */
7070 lpProtoInfoA
= &infoA
;
7071 memcpy( lpProtoInfoA
, lpProtocolInfo
, FIELD_OFFSET( WSAPROTOCOL_INFOA
, szProtocol
) );
7073 if (!WideCharToMultiByte( CP_ACP
, 0, lpProtocolInfo
->szProtocol
, -1,
7074 lpProtoInfoA
->szProtocol
, WSAPROTOCOL_LEN
+1, NULL
, NULL
))
7076 WSASetLastError( WSAEINVAL
);
7077 return SOCKET_ERROR
;
7083 /* Translate AddressString to ANSI code page - assumes that only
7084 standard digits 0-9 are used with this API call */
7085 sBuffer
= WideCharToMultiByte( CP_ACP
, 0, AddressString
, -1, NULL
, 0, NULL
, NULL
);
7086 workBuffer
= HeapAlloc( GetProcessHeap(), 0, sBuffer
);
7090 WideCharToMultiByte( CP_ACP
, 0, AddressString
, -1, workBuffer
, sBuffer
, NULL
, NULL
);
7091 res
= WSAStringToAddressA(workBuffer
,AddressFamily
,lpProtoInfoA
,
7092 lpAddress
,lpAddressLength
);
7093 HeapFree( GetProcessHeap(), 0, workBuffer
);
7097 res
= WSA_NOT_ENOUGH_MEMORY
;
7102 WSASetLastError(res
);
7103 return SOCKET_ERROR
;
7106 /***********************************************************************
7107 * WSAAddressToStringA (WS2_32.27)
7109 * See WSAAddressToStringW
7111 INT WINAPI
WSAAddressToStringA( LPSOCKADDR sockaddr
, DWORD len
,
7112 LPWSAPROTOCOL_INFOA info
, LPSTR string
,
7116 CHAR buffer
[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7119 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr
, len
, info
, string
, lenstr
);
7121 if (!sockaddr
) return SOCKET_ERROR
;
7122 if (!string
|| !lenstr
) return SOCKET_ERROR
;
7124 switch(sockaddr
->sa_family
)
7127 if (len
< sizeof(SOCKADDR_IN
)) return SOCKET_ERROR
;
7128 sprintf( buffer
, "%u.%u.%u.%u:%u",
7129 (unsigned int)(ntohl( ((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
) >> 24 & 0xff),
7130 (unsigned int)(ntohl( ((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
) >> 16 & 0xff),
7131 (unsigned int)(ntohl( ((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
) >> 8 & 0xff),
7132 (unsigned int)(ntohl( ((SOCKADDR_IN
*)sockaddr
)->sin_addr
.WS_s_addr
) & 0xff),
7133 ntohs( ((SOCKADDR_IN
*)sockaddr
)->sin_port
) );
7135 p
= strchr( buffer
, ':' );
7136 if (!((SOCKADDR_IN
*)sockaddr
)->sin_port
) *p
= 0;
7141 struct WS_sockaddr_in6
*sockaddr6
= (LPSOCKADDR_IN6
) sockaddr
;
7144 if (len
< sizeof(SOCKADDR_IN6
)) return SOCKET_ERROR
;
7145 if ((sockaddr6
->sin6_port
))
7146 strcpy(buffer
, "[");
7147 if (!WS_inet_ntop(WS_AF_INET6
, &sockaddr6
->sin6_addr
, buffer
+strlen(buffer
), sizeof(buffer
)))
7149 WSASetLastError(WSAEINVAL
);
7150 return SOCKET_ERROR
;
7152 if ((sockaddr6
->sin6_scope_id
))
7153 sprintf(buffer
+strlen(buffer
), "%%%u", sockaddr6
->sin6_scope_id
);
7154 if ((sockaddr6
->sin6_port
))
7155 sprintf(buffer
+strlen(buffer
), "]:%u", ntohs(sockaddr6
->sin6_port
));
7160 WSASetLastError(WSAEINVAL
);
7161 return SOCKET_ERROR
;
7164 size
= strlen( buffer
) + 1;
7169 WSASetLastError(WSAEFAULT
);
7170 return SOCKET_ERROR
;
7173 TRACE("=> %s,%u bytes\n", debugstr_a(buffer
), size
);
7175 strcpy( string
, buffer
);
7179 /***********************************************************************
7180 * WSAAddressToStringW (WS2_32.28)
7182 * Convert a sockaddr address into a readable address string.
7185 * sockaddr [I] Pointer to a sockaddr structure.
7186 * len [I] Size of the sockaddr structure.
7187 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
7188 * string [I/O] Pointer to a buffer to receive the address string.
7189 * lenstr [I/O] Size of the receive buffer in WCHARs.
7193 * Failure: SOCKET_ERROR
7196 * The 'info' parameter is ignored.
7198 INT WINAPI
WSAAddressToStringW( LPSOCKADDR sockaddr
, DWORD len
,
7199 LPWSAPROTOCOL_INFOW info
, LPWSTR string
,
7204 WCHAR buffer
[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7207 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr
, len
, info
, string
, lenstr
);
7210 ret
= WSAAddressToStringA(sockaddr
, len
, NULL
, bufAddr
, &size
);
7212 if (ret
) return ret
;
7214 MultiByteToWideChar( CP_ACP
, 0, bufAddr
, size
, buffer
, sizeof( buffer
)/sizeof(WCHAR
));
7219 WSASetLastError(WSAEFAULT
);
7220 return SOCKET_ERROR
;
7223 TRACE("=> %s,%u bytes\n", debugstr_w(buffer
), size
);
7225 lstrcpyW( string
, buffer
);
7229 /***********************************************************************
7230 * WSAEnumNameSpaceProvidersA (WS2_32.34)
7232 INT WINAPI
WSAEnumNameSpaceProvidersA( LPDWORD len
, LPWSANAMESPACE_INFOA buffer
)
7234 FIXME( "(%p %p) Stub!\n", len
, buffer
);
7238 /***********************************************************************
7239 * WSAEnumNameSpaceProvidersW (WS2_32.35)
7241 INT WINAPI
WSAEnumNameSpaceProvidersW( LPDWORD len
, LPWSANAMESPACE_INFOW buffer
)
7243 FIXME( "(%p %p) Stub!\n", len
, buffer
);
7247 /***********************************************************************
7248 * WSAGetQOSByName (WS2_32.41)
7250 BOOL WINAPI
WSAGetQOSByName( SOCKET s
, LPWSABUF lpQOSName
, LPQOS lpQOS
)
7252 FIXME( "(0x%04lx %p %p) Stub!\n", s
, lpQOSName
, lpQOS
);
7256 /***********************************************************************
7257 * WSAGetServiceClassInfoA (WS2_32.42)
7259 INT WINAPI
WSAGetServiceClassInfoA( LPGUID provider
, LPGUID service
, LPDWORD len
,
7260 LPWSASERVICECLASSINFOA info
)
7262 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider
), debugstr_guid(service
),
7264 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
7265 return SOCKET_ERROR
;
7268 /***********************************************************************
7269 * WSAGetServiceClassInfoW (WS2_32.43)
7271 INT WINAPI
WSAGetServiceClassInfoW( LPGUID provider
, LPGUID service
, LPDWORD len
,
7272 LPWSASERVICECLASSINFOW info
)
7274 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider
), debugstr_guid(service
),
7276 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
7277 return SOCKET_ERROR
;
7280 /***********************************************************************
7281 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
7283 INT WINAPI
WSAGetServiceClassNameByClassIdA( LPGUID
class, LPSTR service
, LPDWORD len
)
7285 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service
, len
);
7286 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
7287 return SOCKET_ERROR
;
7290 /***********************************************************************
7291 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
7293 INT WINAPI
WSAGetServiceClassNameByClassIdW( LPGUID
class, LPWSTR service
, LPDWORD len
)
7295 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service
, len
);
7296 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
7297 return SOCKET_ERROR
;
7300 /***********************************************************************
7301 * WSALookupServiceBeginA (WS2_32.59)
7303 INT WINAPI
WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions
,
7304 DWORD dwControlFlags
,
7307 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions
, dwControlFlags
,
7309 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
7310 return SOCKET_ERROR
;
7313 /***********************************************************************
7314 * WSALookupServiceBeginW (WS2_32.60)
7316 INT WINAPI
WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions
,
7317 DWORD dwControlFlags
,
7320 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions
, dwControlFlags
,
7322 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
7323 return SOCKET_ERROR
;
7326 /***********************************************************************
7327 * WSALookupServiceEnd (WS2_32.61)
7329 INT WINAPI
WSALookupServiceEnd( HANDLE lookup
)
7331 FIXME("(%p) Stub!\n", lookup
);
7335 /***********************************************************************
7336 * WSALookupServiceNextA (WS2_32.62)
7338 INT WINAPI
WSALookupServiceNextA( HANDLE lookup
, DWORD flags
, LPDWORD len
, LPWSAQUERYSETA results
)
7340 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup
, flags
, len
, results
);
7341 WSASetLastError(WSA_E_NO_MORE
);
7342 return SOCKET_ERROR
;
7345 /***********************************************************************
7346 * WSALookupServiceNextW (WS2_32.63)
7348 INT WINAPI
WSALookupServiceNextW( HANDLE lookup
, DWORD flags
, LPDWORD len
, LPWSAQUERYSETW results
)
7350 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup
, flags
, len
, results
);
7351 WSASetLastError(WSA_E_NO_MORE
);
7352 return SOCKET_ERROR
;
7355 /***********************************************************************
7356 * WSANtohl (WS2_32.64)
7358 INT WINAPI
WSANtohl( SOCKET s
, WS_u_long netlong
, WS_u_long
* lphostlong
)
7360 TRACE( "(0x%04lx 0x%08x %p)\n", s
, netlong
, lphostlong
);
7362 if (!lphostlong
) return WSAEFAULT
;
7364 *lphostlong
= ntohl( netlong
);
7368 /***********************************************************************
7369 * WSANtohs (WS2_32.65)
7371 INT WINAPI
WSANtohs( SOCKET s
, WS_u_short netshort
, WS_u_short
* lphostshort
)
7373 TRACE( "(0x%04lx 0x%08x %p)\n", s
, netshort
, lphostshort
);
7375 if (!lphostshort
) return WSAEFAULT
;
7377 *lphostshort
= ntohs( netshort
);
7381 /***********************************************************************
7382 * WSAProviderConfigChange (WS2_32.66)
7384 INT WINAPI
WSAProviderConfigChange( LPHANDLE handle
, LPWSAOVERLAPPED overlapped
,
7385 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion
)
7387 FIXME( "(%p %p %p) Stub!\n", handle
, overlapped
, completion
);
7388 return SOCKET_ERROR
;
7391 /***********************************************************************
7392 * WSARecvDisconnect (WS2_32.68)
7394 INT WINAPI
WSARecvDisconnect( SOCKET s
, LPWSABUF disconnectdata
)
7396 TRACE( "(0x%04lx %p)\n", s
, disconnectdata
);
7398 return WS_shutdown( s
, SD_RECEIVE
);
7401 /***********************************************************************
7402 * WSASetServiceA (WS2_32.76)
7404 INT WINAPI
WSASetServiceA( LPWSAQUERYSETA query
, WSAESETSERVICEOP operation
, DWORD flags
)
7406 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query
, operation
, flags
);
7410 /***********************************************************************
7411 * WSASetServiceW (WS2_32.77)
7413 INT WINAPI
WSASetServiceW( LPWSAQUERYSETW query
, WSAESETSERVICEOP operation
, DWORD flags
)
7415 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query
, operation
, flags
);
7419 /***********************************************************************
7420 * WSCEnableNSProvider (WS2_32.84)
7422 INT WINAPI
WSCEnableNSProvider( LPGUID provider
, BOOL enable
)
7424 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider
), enable
);
7428 /***********************************************************************
7429 * WSCGetProviderPath (WS2_32.86)
7431 INT WINAPI
WSCGetProviderPath( LPGUID provider
, LPWSTR path
, LPINT len
, LPINT errcode
)
7433 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider
), path
, len
, errcode
);
7435 if (!errcode
|| !provider
|| !len
) return WSAEFAULT
;
7437 *errcode
= WSAEINVAL
;
7438 return SOCKET_ERROR
;
7441 /***********************************************************************
7442 * WSCInstallNameSpace (WS2_32.87)
7444 INT WINAPI
WSCInstallNameSpace( LPWSTR identifier
, LPWSTR path
, DWORD
namespace,
7445 DWORD version
, LPGUID provider
)
7447 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier
), debugstr_w(path
),
7448 namespace, version
, debugstr_guid(provider
) );
7452 /***********************************************************************
7453 * WSCUnInstallNameSpace (WS2_32.89)
7455 INT WINAPI
WSCUnInstallNameSpace( LPGUID lpProviderId
)
7457 FIXME("(%p) Stub!\n", lpProviderId
);
7461 /***********************************************************************
7462 * WSCWriteProviderOrder (WS2_32.91)
7464 INT WINAPI
WSCWriteProviderOrder( LPDWORD entry
, DWORD number
)
7466 FIXME("(%p 0x%08x) Stub!\n", entry
, number
);
7470 /***********************************************************************
7471 * WSANSPIoctl (WS2_32.91)
7473 INT WINAPI
WSANSPIoctl( HANDLE hLookup
, DWORD dwControlCode
, LPVOID lpvInBuffer
,
7474 DWORD cbInBuffer
, LPVOID lpvOutBuffer
, DWORD cbOutBuffer
,
7475 LPDWORD lpcbBytesReturned
, LPWSACOMPLETION lpCompletion
)
7477 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup
, dwControlCode
,
7478 lpvInBuffer
, cbInBuffer
, lpvOutBuffer
, cbOutBuffer
, lpcbBytesReturned
, lpCompletion
);
7479 WSASetLastError(WSA_NOT_ENOUGH_MEMORY
);
7480 return SOCKET_ERROR
;
7483 /*****************************************************************************
7484 * WSAEnumProtocolsA [WS2_32.@]
7486 * see function WSAEnumProtocolsW
7488 INT WINAPI
WSAEnumProtocolsA( LPINT protocols
, LPWSAPROTOCOL_INFOA buffer
, LPDWORD len
)
7490 return WS_EnumProtocols( FALSE
, protocols
, (LPWSAPROTOCOL_INFOW
) buffer
, len
);
7493 /*****************************************************************************
7494 * WSAEnumProtocolsW [WS2_32.@]
7496 * Retrieves information about specified set of active network protocols.
7499 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
7500 * retrieves information on all available protocols.
7501 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
7503 * len [I/O] Pointer to a variable specifying buffer size. On output
7504 * the variable holds the number of bytes needed when the
7505 * specified size is too small.
7508 * Success: number of WSAPROTOCOL_INFO structures in buffer.
7509 * Failure: SOCKET_ERROR
7512 * NT4SP5 does not return SPX if protocols == NULL
7515 * - NT4SP5 returns in addition these list of NETBIOS protocols
7516 * (address family 17), each entry two times one for socket type 2 and 5
7518 * iProtocol szProtocol
7519 * 0x80000000 \Device\NwlnkNb
7520 * 0xfffffffa \Device\NetBT_CBENT7
7521 * 0xfffffffb \Device\Nbf_CBENT7
7522 * 0xfffffffc \Device\NetBT_NdisWan5
7523 * 0xfffffffd \Device\NetBT_El9202
7524 * 0xfffffffe \Device\Nbf_El9202
7525 * 0xffffffff \Device\Nbf_NdisWan4
7527 * - there is no check that the operating system supports the returned
7530 INT WINAPI
WSAEnumProtocolsW( LPINT protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
)
7532 return WS_EnumProtocols( TRUE
, protocols
, buffer
, len
);
7535 /*****************************************************************************
7536 * WSCEnumProtocols [WS2_32.@]
7539 * protocols [I] Null-terminated array of iProtocol values.
7540 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
7541 * len [I/O] Size of buffer on input/output.
7542 * errno [O] Error code.
7545 * Success: number of protocols to be reported on.
7546 * Failure: SOCKET_ERROR. error is in errno.
7549 * Doesn't supply info on layered protocols.
7552 INT WINAPI
WSCEnumProtocols( LPINT protocols
, LPWSAPROTOCOL_INFOW buffer
, LPDWORD len
, LPINT err
)
7554 INT ret
= WSAEnumProtocolsW( protocols
, buffer
, len
);
7556 if (ret
== SOCKET_ERROR
) *err
= WSAENOBUFS
;