2 * based on Windows Sockets 1.1 specs
4 * Copyright (C) 1993,1994,1996,1997 John Brezak, Erik Bos, Alex Korobka.
5 * Copyright (C) 2005 Marcus Meissner
6 * Copyright (C) 2006-2008 Kai Blin
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 * NOTE: If you make any changes to fix a particular app, make sure
23 * they don't break something else like Netscape or telnet and ftp
24 * clients and servers (www.winsite.com got a lot of those).
28 #include "wine/port.h"
33 #include <sys/types.h>
37 #ifdef HAVE_SYS_IOCTL_H
38 # include <sys/ioctl.h>
40 #ifdef HAVE_SYS_FILIO_H
41 # include <sys/filio.h>
43 #ifdef HAVE_SYS_SOCKIO_H
44 # include <sys/sockio.h>
48 # include <sys/so_ioctl.h>
51 #ifdef HAVE_SYS_PARAM_H
52 # include <sys/param.h>
58 #ifdef HAVE_SYS_WAIT_H
59 # include <sys/wait.h>
64 #ifdef HAVE_SYS_SOCKET_H
65 #include <sys/socket.h>
67 #ifdef HAVE_NETINET_IN_H
68 # include <netinet/in.h>
70 #ifdef HAVE_NETINET_TCP_H
71 # include <netinet/tcp.h>
73 #ifdef HAVE_ARPA_INET_H
74 # include <arpa/inet.h>
86 #ifdef HAVE_ARPA_NAMESER_H
87 # include <arpa/nameser.h>
95 #ifdef HAVE_LINUX_FILTER_H
96 # include <linux/filter.h>
99 #ifdef HAVE_NETIPX_IPX_H
100 # include <netipx/ipx.h>
102 #elif defined(HAVE_LINUX_IPX_H)
103 # ifdef HAVE_ASM_TYPES_H
104 # include <asm/types.h>
106 # ifdef HAVE_LINUX_TYPES_H
107 # include <linux/types.h>
109 # include <linux/ipx.h>
113 #ifdef HAVE_LINUX_IRDA_H
114 # ifdef HAVE_LINUX_TYPES_H
115 # include <linux/types.h>
117 # include <linux/irda.h>
124 #ifdef HAVE_SYS_POLL_H
125 # include <sys/poll.h>
127 #ifdef HAVE_SYS_TIME_H
128 # include <sys/time.h>
131 #define NONAMELESSUNION
132 #define NONAMELESSSTRUCT
133 #include "ntstatus.h"
134 #define WIN32_NO_STATUS
139 #include "winerror.h"
141 #include "winsock2.h"
143 #include "ws2tcpip.h"
149 #define USE_WC_PREFIX /* For CMSG_DATA */
150 #include "iphlpapi.h"
151 #include "wine/server.h"
152 #include "wine/debug.h"
153 #include "wine/exception.h"
154 #include "wine/unicode.h"
157 # include "wsnwlink.h"
160 #if defined(linux) && !defined(IP_UNICAST_IF)
161 #define IP_UNICAST_IF 50
164 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
165 # define sipx_network sipx_addr.x_net
166 # define sipx_node sipx_addr.x_host.c_host
167 #endif /* __FreeBSD__ */
170 #define INADDR_NONE ~0UL
173 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
174 WINE_DECLARE_DEBUG_CHANNEL(winediag);
176 #if defined(IP_UNICAST_IF) && defined(SO_ATTACH_FILTER)
177 # define LINUX_BOUND_IF
178 struct interface_filter {
179 struct sock_filter iface_memaddr;
180 struct sock_filter iface_rule;
181 struct sock_filter return_keep;
182 struct sock_filter return_dump;
184 # define FILTER_JUMP_DUMP(here) (u_char)(offsetof(struct interface_filter, return_dump) \
185 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
186 /sizeof(struct sock_filter)
187 # define FILTER_JUMP_KEEP(here) (u_char)(offsetof(struct interface_filter, return_keep) \
188 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
189 /sizeof(struct sock_filter)
190 static struct interface_filter generic_interface_filter = {
191 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_AD_OFF+SKF_AD_IFINDEX),
192 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(iface_rule), FILTER_JUMP_DUMP(iface_rule)),
193 BPF_STMT(BPF_RET+BPF_K, (u_int)-1), /* keep packet */
194 BPF_STMT(BPF_RET+BPF_K, 0) /* dump packet */
196 #endif /* LINUX_BOUND_IF */
199 * The actual definition of WSASendTo, wrapped in a different function name
200 * so that internal calls from ws2_32 itself will not trigger programs like
201 * Garena, which hooks WSASendTo/WSARecvFrom calls.
203 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
204 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
205 const struct WS_sockaddr *to, int tolen,
206 LPWSAOVERLAPPED lpOverlapped,
207 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine );
210 * Internal fundamental receive function, essentially WSARecvFrom with an
211 * additional parameter to support message control headers.
213 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
214 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
215 struct WS_sockaddr *lpFrom,
216 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
217 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
218 LPWSABUF lpControlBuffer );
220 /* critical section to protect some non-reentrant net function */
221 static CRITICAL_SECTION csWSgetXXXbyYYY;
222 static CRITICAL_SECTION_DEBUG critsect_debug =
224 0, 0, &csWSgetXXXbyYYY,
225 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
226 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
228 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
230 union generic_unix_sockaddr
232 struct sockaddr addr;
233 char data[128]; /* should be big enough for all families */
236 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
238 if (!a) return "(nil)";
239 switch (a->sa_family)
242 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
243 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
244 ntohs(((const struct sockaddr_in *)a)->sin_port));
249 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
251 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
253 p = "(unknown IPv6 address)";
254 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
255 p, ntohs(sin->sin6_port));
261 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
262 addr = ntohl( addr );
263 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
265 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
268 return wine_dbg_sprintf("{ family %d }", a->sa_family);
272 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
273 #define SOCKET2HANDLE(s) ((HANDLE)(s))
274 #define HANDLE2SOCKET(h) ((SOCKET)(h))
276 /****************************************************************
277 * Async IO declarations
278 ****************************************************************/
280 typedef struct ws2_async
284 LPWSAOVERLAPPED user_overlapped;
285 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
286 IO_STATUS_BLOCK local_iosb;
287 struct WS_sockaddr *addr;
290 int val; /* for send operations */
291 int *ptr; /* for recv operations */
296 unsigned int n_iovecs;
297 unsigned int first_iovec;
298 struct iovec iovec[1];
301 typedef struct ws2_accept_async
303 HANDLE listen_socket;
304 HANDLE accept_socket;
305 LPOVERLAPPED user_overlapped;
307 PVOID buf; /* buffer to write data to */
311 struct ws2_async *read;
314 /****************************************************************/
316 /* ----------------------------------- internal data */
318 /* ws_... struct conversion flags */
320 typedef struct /* WSAAsyncSelect() control struct */
322 HANDLE service, event, sock;
328 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
329 #define WS_MAX_UDP_DATAGRAM 1024
330 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
332 /* hostent's, servent's and protent's are stored in one buffer per thread,
333 * as documented on MSDN for the functions that return any of the buffers */
334 struct per_thread_data
337 struct WS_hostent *he_buffer;
338 struct WS_servent *se_buffer;
339 struct WS_protoent *pe_buffer;
345 /* internal: routing description information */
352 static INT num_startup; /* reference counter */
353 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
355 /* function prototypes */
356 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length);
357 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
358 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
359 static struct WS_servent *WS_dup_se(const struct servent* p_se);
361 int WSAIOCTL_GetInterfaceCount(void);
362 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
364 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG Information );
366 #define MAP_OPTION(opt) { WS_##opt, opt }
368 static const int ws_sock_map[][2] =
370 MAP_OPTION( SO_DEBUG ),
371 MAP_OPTION( SO_ACCEPTCONN ),
372 MAP_OPTION( SO_REUSEADDR ),
373 MAP_OPTION( SO_KEEPALIVE ),
374 MAP_OPTION( SO_DONTROUTE ),
375 MAP_OPTION( SO_BROADCAST ),
376 MAP_OPTION( SO_LINGER ),
377 MAP_OPTION( SO_OOBINLINE ),
378 MAP_OPTION( SO_SNDBUF ),
379 MAP_OPTION( SO_RCVBUF ),
380 MAP_OPTION( SO_ERROR ),
381 MAP_OPTION( SO_TYPE ),
383 MAP_OPTION( SO_RCVTIMEO ),
386 MAP_OPTION( SO_SNDTIMEO ),
390 static const int ws_tcp_map[][2] =
393 MAP_OPTION( TCP_NODELAY ),
397 static const int ws_ip_map[][2] =
399 MAP_OPTION( IP_MULTICAST_IF ),
400 MAP_OPTION( IP_MULTICAST_TTL ),
401 MAP_OPTION( IP_MULTICAST_LOOP ),
402 MAP_OPTION( IP_ADD_MEMBERSHIP ),
403 MAP_OPTION( IP_DROP_MEMBERSHIP ),
404 MAP_OPTION( IP_OPTIONS ),
406 MAP_OPTION( IP_HDRINCL ),
408 MAP_OPTION( IP_TOS ),
409 MAP_OPTION( IP_TTL ),
411 MAP_OPTION( IP_PKTINFO ),
414 MAP_OPTION( IP_UNICAST_IF ),
418 static const int ws_ipv6_map[][2] =
420 #ifdef IPV6_ADD_MEMBERSHIP
421 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
423 #ifdef IPV6_DROP_MEMBERSHIP
424 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
426 MAP_OPTION( IPV6_MULTICAST_IF ),
427 MAP_OPTION( IPV6_MULTICAST_HOPS ),
428 MAP_OPTION( IPV6_MULTICAST_LOOP ),
429 MAP_OPTION( IPV6_UNICAST_HOPS ),
430 MAP_OPTION( IPV6_V6ONLY ),
431 #ifdef IPV6_UNICAST_IF
432 MAP_OPTION( IPV6_UNICAST_IF ),
436 static const int ws_af_map[][2] =
438 MAP_OPTION( AF_UNSPEC ),
439 MAP_OPTION( AF_INET ),
440 MAP_OPTION( AF_INET6 ),
442 MAP_OPTION( AF_IPX ),
445 MAP_OPTION( AF_IRDA ),
447 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
450 static const int ws_socktype_map[][2] =
452 MAP_OPTION( SOCK_DGRAM ),
453 MAP_OPTION( SOCK_STREAM ),
454 MAP_OPTION( SOCK_RAW ),
455 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
458 static const int ws_proto_map[][2] =
460 MAP_OPTION( IPPROTO_IP ),
461 MAP_OPTION( IPPROTO_TCP ),
462 MAP_OPTION( IPPROTO_UDP ),
463 MAP_OPTION( IPPROTO_ICMP ),
464 MAP_OPTION( IPPROTO_IGMP ),
465 MAP_OPTION( IPPROTO_RAW ),
466 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
469 static const int ws_aiflag_map[][2] =
471 MAP_OPTION( AI_PASSIVE ),
472 MAP_OPTION( AI_CANONNAME ),
473 MAP_OPTION( AI_NUMERICHOST ),
474 MAP_OPTION( AI_ADDRCONFIG ),
477 static const int ws_niflag_map[][2] =
479 MAP_OPTION( NI_NOFQDN ),
480 MAP_OPTION( NI_NUMERICHOST ),
481 MAP_OPTION( NI_NAMEREQD ),
482 MAP_OPTION( NI_NUMERICSERV ),
483 MAP_OPTION( NI_DGRAM ),
486 static const int ws_eai_map[][2] =
488 MAP_OPTION( EAI_AGAIN ),
489 MAP_OPTION( EAI_BADFLAGS ),
490 MAP_OPTION( EAI_FAIL ),
491 MAP_OPTION( EAI_FAMILY ),
492 MAP_OPTION( EAI_MEMORY ),
493 /* Note: EAI_NODATA is deprecated, but still
494 * used by Windows and Linux... We map the newer
495 * EAI_NONAME to EAI_NODATA for now until Windows
499 MAP_OPTION( EAI_NODATA ),
502 { WS_EAI_NODATA, EAI_NONAME },
505 MAP_OPTION( EAI_SERVICE ),
506 MAP_OPTION( EAI_SOCKTYPE ),
510 static const char magic_loopback_addr[] = {127, 12, 34, 56};
512 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
513 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
515 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
516 char *ptr = (char *) current + sizeof(WSACMSGHDR);
518 /* Make sure there is at least enough room for this entry */
519 if (msgsize > *maxsize)
522 /* Fill in the entry */
523 current->cmsg_len = sizeof(WSACMSGHDR) + len;
524 current->cmsg_level = level;
525 current->cmsg_type = type;
526 memcpy(ptr, data, len);
527 /* Return the pointer to where next entry should go */
528 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
531 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
534 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
535 ULONG ctlsize = control->len;
536 struct cmsghdr *cmsg_unix;
539 /* Loop over all the headers, converting as appropriate */
540 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
542 switch(cmsg_unix->cmsg_level)
545 switch(cmsg_unix->cmsg_type)
549 /* Convert the Unix IP_PKTINFO structure to the Windows version */
550 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
551 struct WS_in_pktinfo data_win;
553 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
554 data_win.ipi_ifindex = data_unix->ipi_ifindex;
555 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
556 (void*)&data_win, sizeof(data_win));
557 if (!ptr) goto error;
560 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
565 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
571 /* Set the length of the returned control headers */
572 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
573 return (ptr != NULL);
574 #else /* IP_PKTINFO */
577 #endif /* IP_PKTINFO */
579 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
581 /* ----------------------------------- error handling */
583 static NTSTATUS sock_get_ntstatus( int err )
587 case EBADF: return STATUS_INVALID_HANDLE;
588 case EBUSY: return STATUS_DEVICE_BUSY;
590 case EACCES: return STATUS_ACCESS_DENIED;
591 case EFAULT: return STATUS_NO_MEMORY;
592 case EINVAL: return STATUS_INVALID_PARAMETER;
594 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
595 case EWOULDBLOCK: return STATUS_CANT_WAIT;
596 case EINPROGRESS: return STATUS_PENDING;
597 case EALREADY: return STATUS_NETWORK_BUSY;
598 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
599 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
600 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
601 case EPROTONOSUPPORT:
602 case ESOCKTNOSUPPORT:
605 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
606 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
607 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
608 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
609 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
610 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
611 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
612 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
613 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
614 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
615 case ENETDOWN: return STATUS_NETWORK_BUSY;
617 case ECONNRESET: return STATUS_CONNECTION_RESET;
618 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
620 case 0: return STATUS_SUCCESS;
622 WARN("Unknown errno %d!\n", err);
623 return STATUS_UNSUCCESSFUL;
627 static UINT sock_get_error( int err )
631 case EINTR: return WSAEINTR;
632 case EBADF: return WSAEBADF;
634 case EACCES: return WSAEACCES;
635 case EFAULT: return WSAEFAULT;
636 case EINVAL: return WSAEINVAL;
637 case EMFILE: return WSAEMFILE;
638 case EWOULDBLOCK: return WSAEWOULDBLOCK;
639 case EINPROGRESS: return WSAEINPROGRESS;
640 case EALREADY: return WSAEALREADY;
641 case ENOTSOCK: return WSAENOTSOCK;
642 case EDESTADDRREQ: return WSAEDESTADDRREQ;
643 case EMSGSIZE: return WSAEMSGSIZE;
644 case EPROTOTYPE: return WSAEPROTOTYPE;
645 case ENOPROTOOPT: return WSAENOPROTOOPT;
646 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
647 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
648 case EOPNOTSUPP: return WSAEOPNOTSUPP;
649 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
650 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
651 case EADDRINUSE: return WSAEADDRINUSE;
652 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
653 case ENETDOWN: return WSAENETDOWN;
654 case ENETUNREACH: return WSAENETUNREACH;
655 case ENETRESET: return WSAENETRESET;
656 case ECONNABORTED: return WSAECONNABORTED;
658 case ECONNRESET: return WSAECONNRESET;
659 case ENOBUFS: return WSAENOBUFS;
660 case EISCONN: return WSAEISCONN;
661 case ENOTCONN: return WSAENOTCONN;
662 case ESHUTDOWN: return WSAESHUTDOWN;
663 case ETOOMANYREFS: return WSAETOOMANYREFS;
664 case ETIMEDOUT: return WSAETIMEDOUT;
665 case ECONNREFUSED: return WSAECONNREFUSED;
666 case ELOOP: return WSAELOOP;
667 case ENAMETOOLONG: return WSAENAMETOOLONG;
668 case EHOSTDOWN: return WSAEHOSTDOWN;
669 case EHOSTUNREACH: return WSAEHOSTUNREACH;
670 case ENOTEMPTY: return WSAENOTEMPTY;
672 case EPROCLIM: return WSAEPROCLIM;
675 case EUSERS: return WSAEUSERS;
678 case EDQUOT: return WSAEDQUOT;
681 case ESTALE: return WSAESTALE;
684 case EREMOTE: return WSAEREMOTE;
687 /* just in case we ever get here and there are no problems */
690 WARN("Unknown errno %d!\n", err);
691 return WSAEOPNOTSUPP;
695 static UINT wsaErrno(void)
697 int loc_errno = errno;
698 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
700 return sock_get_error( loc_errno );
703 /* most ws2 overlapped functions return an ntstatus-based error code */
704 static NTSTATUS wsaErrStatus(void)
706 int loc_errno = errno;
707 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
709 return sock_get_ntstatus(loc_errno);
712 static UINT wsaHerrno(int loc_errno)
714 WARN("h_errno %d.\n", loc_errno);
718 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
719 case TRY_AGAIN: return WSATRY_AGAIN;
720 case NO_RECOVERY: return WSANO_RECOVERY;
721 case NO_DATA: return WSANO_DATA;
722 case ENOBUFS: return WSAENOBUFS;
726 WARN("Unknown h_errno %d!\n", loc_errno);
727 return WSAEOPNOTSUPP;
731 static inline DWORD NtStatusToWSAError( const DWORD status )
733 /* We only need to cover the status codes set by server async request handling */
737 case STATUS_SUCCESS: wserr = 0; break;
738 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
739 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
740 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
741 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
742 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
743 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
744 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
745 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
746 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
747 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
748 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
749 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
750 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
751 case STATUS_IO_TIMEOUT:
752 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
753 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
754 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
755 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
756 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
757 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
758 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
759 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
762 wserr = RtlNtStatusToDosError( status );
763 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
768 /* set last error code from NT status without mapping WSA errors */
769 static inline unsigned int set_error( unsigned int err )
773 err = NtStatusToWSAError( err );
779 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
782 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
787 static inline void release_sock_fd( SOCKET s, int fd )
789 wine_server_release_fd( SOCKET2HANDLE(s), fd );
792 static void _enable_event( HANDLE s, unsigned int event,
793 unsigned int sstate, unsigned int cstate )
795 SERVER_START_REQ( enable_socket_event )
797 req->handle = wine_server_obj_handle( s );
799 req->sstate = sstate;
800 req->cstate = cstate;
801 wine_server_call( req );
806 static int _is_blocking(SOCKET s)
809 SERVER_START_REQ( get_socket_event )
811 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
812 req->service = FALSE;
814 wine_server_call( req );
815 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
821 static unsigned int _get_sock_mask(SOCKET s)
824 SERVER_START_REQ( get_socket_event )
826 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
827 req->service = FALSE;
829 wine_server_call( req );
836 static void _sync_sock_state(SOCKET s)
838 /* do a dummy wineserver request in order to let
839 the wineserver run through its select loop once */
840 (void)_is_blocking(s);
843 static int _get_sock_error(SOCKET s, unsigned int bit)
845 int events[FD_MAX_EVENTS];
847 SERVER_START_REQ( get_socket_event )
849 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
850 req->service = FALSE;
852 wine_server_set_reply( req, events, sizeof(events) );
853 wine_server_call( req );
859 static struct per_thread_data *get_per_thread_data(void)
861 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
862 /* lazy initialization */
865 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
866 NtCurrentTeb()->WinSockData = ptb;
871 static void free_per_thread_data(void)
873 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
877 /* delete scratch buffers */
878 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
879 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
880 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
881 ptb->he_buffer = NULL;
882 ptb->se_buffer = NULL;
883 ptb->pe_buffer = NULL;
885 HeapFree( GetProcessHeap(), 0, ptb );
886 NtCurrentTeb()->WinSockData = NULL;
889 /***********************************************************************
890 * DllMain (WS2_32.init)
892 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
894 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
896 case DLL_PROCESS_ATTACH:
898 case DLL_PROCESS_DETACH:
899 free_per_thread_data();
900 DeleteCriticalSection(&csWSgetXXXbyYYY);
903 case DLL_THREAD_DETACH:
904 free_per_thread_data();
910 /***********************************************************************
913 * Converts socket flags from Windows format.
914 * Return 1 if converted, 0 if not (error).
916 static int convert_sockopt(INT *level, INT *optname)
923 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
924 if( ws_sock_map[i][0] == *optname )
926 *optname = ws_sock_map[i][1];
930 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
933 *level = IPPROTO_TCP;
934 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
935 if ( ws_tcp_map[i][0] == *optname )
937 *optname = ws_tcp_map[i][1];
941 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
945 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
946 if (ws_ip_map[i][0] == *optname )
948 *optname = ws_ip_map[i][1];
952 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
954 case WS_IPPROTO_IPV6:
955 *level = IPPROTO_IPV6;
956 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
957 if (ws_ipv6_map[i][0] == *optname )
959 *optname = ws_ipv6_map[i][1];
963 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
965 default: FIXME("Unimplemented or unknown socket level\n");
970 /* ----------------------------------- Per-thread info (or per-process?) */
972 static char *strdup_lower(const char *str)
975 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
979 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
982 else SetLastError(WSAENOBUFS);
986 static inline int sock_error_p(int s)
988 unsigned int optval, optlen;
990 optlen = sizeof(optval);
991 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
992 if (optval) WARN("\t[%i] error: %d\n", s, optval);
996 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
997 * from an fd and return the value converted to milli seconds
998 * or -1 if there is an infinite time out */
999 static inline int get_rcvsnd_timeo( int fd, int optname)
1002 unsigned int len = sizeof(tv);
1003 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
1005 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1006 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
1011 /* macro wrappers for portability */
1013 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
1015 #define GET_RCVTIMEO(fd) (-1)
1019 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
1021 #define GET_SNDTIMEO(fd) (-1)
1024 /* utility: given an fd, will block until one of the events occurs */
1025 static inline int do_block( int fd, int events, int timeout )
1031 pfd.events = events;
1033 while ((ret = poll(&pfd, 1, timeout)) < 0)
1044 convert_af_w2u(int windowsaf) {
1047 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1048 if (ws_af_map[i][0] == windowsaf)
1049 return ws_af_map[i][1];
1050 FIXME("unhandled Windows address family %d\n", windowsaf);
1055 convert_af_u2w(int unixaf) {
1058 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1059 if (ws_af_map[i][1] == unixaf)
1060 return ws_af_map[i][0];
1061 FIXME("unhandled UNIX address family %d\n", unixaf);
1066 convert_proto_w2u(int windowsproto) {
1069 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1070 if (ws_proto_map[i][0] == windowsproto)
1071 return ws_proto_map[i][1];
1072 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1077 convert_proto_u2w(int unixproto) {
1080 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1081 if (ws_proto_map[i][1] == unixproto)
1082 return ws_proto_map[i][0];
1083 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1088 convert_socktype_w2u(int windowssocktype) {
1091 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1092 if (ws_socktype_map[i][0] == windowssocktype)
1093 return ws_socktype_map[i][1];
1094 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1099 convert_socktype_u2w(int unixsocktype) {
1102 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1103 if (ws_socktype_map[i][1] == unixsocktype)
1104 return ws_socktype_map[i][0];
1105 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1109 /* ----------------------------------- API -----
1111 * Init / cleanup / error checking.
1114 /***********************************************************************
1115 * WSAStartup (WS2_32.115)
1117 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1119 TRACE("verReq=%x\n", wVersionRequested);
1121 if (LOBYTE(wVersionRequested) < 1)
1122 return WSAVERNOTSUPPORTED;
1124 if (!lpWSAData) return WSAEINVAL;
1128 /* that's the whole of the negotiation for now */
1129 lpWSAData->wVersion = wVersionRequested;
1130 /* return winsock information */
1131 lpWSAData->wHighVersion = 0x0202;
1132 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1133 strcpy(lpWSAData->szSystemStatus, "Running" );
1134 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1135 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1136 /* don't do anything with lpWSAData->lpVendorInfo */
1137 /* (some apps don't allocate the space for this field) */
1139 TRACE("succeeded\n");
1144 /***********************************************************************
1145 * WSACleanup (WS2_32.116)
1147 INT WINAPI WSACleanup(void)
1153 SetLastError(WSANOTINITIALISED);
1154 return SOCKET_ERROR;
1158 /***********************************************************************
1159 * WSAGetLastError (WS2_32.111)
1161 INT WINAPI WSAGetLastError(void)
1163 return GetLastError();
1166 /***********************************************************************
1167 * WSASetLastError (WS2_32.112)
1169 void WINAPI WSASetLastError(INT iError) {
1170 SetLastError(iError);
1173 static struct WS_hostent *check_buffer_he(int size)
1175 struct per_thread_data * ptb = get_per_thread_data();
1178 if (ptb->he_len >= size ) return ptb->he_buffer;
1179 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1181 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1182 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1183 return ptb->he_buffer;
1186 static struct WS_servent *check_buffer_se(int size)
1188 struct per_thread_data * ptb = get_per_thread_data();
1191 if (ptb->se_len >= size ) return ptb->se_buffer;
1192 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1194 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1195 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1196 return ptb->se_buffer;
1199 static struct WS_protoent *check_buffer_pe(int size)
1201 struct per_thread_data * ptb = get_per_thread_data();
1204 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1205 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1207 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1208 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1209 return ptb->pe_buffer;
1212 /* ----------------------------------- i/o APIs */
1214 static inline BOOL supported_pf(int pf)
1235 /**********************************************************************/
1237 /* Returns the length of the converted address if successful, 0 if it was too small to
1240 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1241 union generic_unix_sockaddr *uaddr)
1243 unsigned int uaddrlen = 0;
1245 switch (wsaddr->sa_family)
1250 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1251 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1253 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1256 uaddrlen = sizeof(struct sockaddr_ipx);
1257 memset( uaddr, 0, uaddrlen );
1258 uipx->sipx_family=AF_IPX;
1259 uipx->sipx_port=wsipx->sa_socket;
1260 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1263 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1264 #ifdef IPX_FRAME_NONE
1265 uipx->sipx_type=IPX_FRAME_NONE;
1271 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1272 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1274 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1275 * scope_id, one without.
1277 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1278 uaddrlen = sizeof(struct sockaddr_in6);
1279 memset( uaddr, 0, uaddrlen );
1280 uin6->sin6_family = AF_INET6;
1281 uin6->sin6_port = win6->sin6_port;
1282 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1283 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1284 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1286 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1289 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1293 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1294 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1296 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1298 uaddrlen = sizeof(struct sockaddr_in);
1299 memset( uaddr, 0, uaddrlen );
1300 uin->sin_family = AF_INET;
1301 uin->sin_port = win->sin_port;
1302 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1307 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1308 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1310 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1312 uaddrlen = sizeof(struct sockaddr_irda);
1313 memset( uaddr, 0, uaddrlen );
1314 uin->sir_family = AF_IRDA;
1315 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1317 unsigned int lsap_sel = 0;
1319 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1320 uin->sir_lsap_sel = lsap_sel;
1324 uin->sir_lsap_sel = LSAP_ANY;
1325 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1327 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1331 case WS_AF_UNSPEC: {
1332 /* Try to determine the needed space by the passed windows sockaddr space */
1333 switch (wsaddrlen) {
1334 default: /* likely a ipv4 address */
1335 case sizeof(struct WS_sockaddr_in):
1336 uaddrlen = sizeof(struct sockaddr_in);
1339 case sizeof(struct WS_sockaddr_ipx):
1340 uaddrlen = sizeof(struct sockaddr_ipx);
1344 case sizeof(SOCKADDR_IRDA):
1345 uaddrlen = sizeof(struct sockaddr_irda);
1348 case sizeof(struct WS_sockaddr_in6):
1349 case sizeof(struct WS_sockaddr_in6_old):
1350 uaddrlen = sizeof(struct sockaddr_in6);
1353 memset( uaddr, 0, uaddrlen );
1357 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1363 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1365 switch (uaddr->sa_family)
1369 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
1374 static const struct sockaddr_in6 emptyAddr;
1375 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1376 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1380 static const struct sockaddr_in emptyAddr;
1381 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1382 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1387 FIXME("unknown address family %d\n", uaddr->sa_family);
1392 /* Returns 0 if successful, -1 if the buffer is too small */
1393 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1397 switch(uaddr->sa_family)
1402 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1403 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1406 switch (*wsaddrlen) /* how much can we copy? */
1410 *wsaddrlen = sizeof(*wsipx);
1411 wsipx->sa_socket=uipx->sipx_port;
1415 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1423 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1429 wsipx->sa_family=WS_AF_IPX;
1441 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1442 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1444 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1446 win->irdaAddressFamily = WS_AF_IRDA;
1447 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1448 if (uin->sir_lsap_sel != LSAP_ANY)
1449 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1451 memcpy( win->irdaServiceName, uin->sir_name,
1452 sizeof(win->irdaServiceName) );
1457 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1458 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1460 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1462 win6old->sin6_family = WS_AF_INET6;
1463 win6old->sin6_port = uin6->sin6_port;
1464 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1465 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1466 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1467 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1468 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1469 win6->sin6_scope_id = uin6->sin6_scope_id;
1470 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1473 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1475 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1480 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1481 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1483 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1485 win->sin_family = WS_AF_INET;
1486 win->sin_port = uin->sin_port;
1487 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1488 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1489 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1493 memset(wsaddr,0,*wsaddrlen);
1497 FIXME("Unknown address family %d\n", uaddr->sa_family);
1503 /**************************************************************************
1504 * Functions for handling overlapped I/O
1505 **************************************************************************/
1507 /* user APC called upon async completion */
1508 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1510 ws2_async *wsa = arg;
1512 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1513 iosb->Information, wsa->user_overlapped,
1515 HeapFree( GetProcessHeap(), 0, wsa );
1518 /***********************************************************************
1519 * WS2_recv (INTERNAL)
1521 * Workhorse for both synchronous and asynchronous recv() operations.
1523 static int WS2_recv( int fd, struct ws2_async *wsa )
1525 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1529 union generic_unix_sockaddr unix_sockaddr;
1532 hdr.msg_name = NULL;
1536 hdr.msg_namelen = sizeof(unix_sockaddr);
1537 hdr.msg_name = &unix_sockaddr;
1540 hdr.msg_namelen = 0;
1542 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1543 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1544 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1545 hdr.msg_accrights = NULL;
1546 hdr.msg_accrightslen = 0;
1548 hdr.msg_control = pktbuf;
1549 hdr.msg_controllen = sizeof(pktbuf);
1553 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1556 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1559 ERR("Message control headers cannot be properly supported on this system.\n");
1560 wsa->control->len = 0;
1563 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
1565 WARN("Application passed insufficient room for control headers.\n");
1566 *wsa->lpFlags |= WS_MSG_CTRUNC;
1572 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1573 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1575 * quoting linux 2.6 net/ipv4/tcp.c:
1576 * "According to UNIX98, msg_name/msg_namelen are ignored
1577 * on connected socket. I was just happy when found this 8) --ANK"
1579 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1580 * connection-oriented sockets, so don't try to update lpFrom.
1582 if (wsa->addr && hdr.msg_namelen)
1583 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1588 /***********************************************************************
1589 * WS2_async_recv (INTERNAL)
1591 * Handler for overlapped recv() operations.
1593 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1595 ws2_async* wsa = user;
1600 case STATUS_ALERTED:
1601 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1604 result = WS2_recv( fd, wsa );
1605 wine_server_release_fd( wsa->hSocket, fd );
1608 status = STATUS_SUCCESS;
1609 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1613 if (errno == EINTR || errno == EAGAIN)
1615 status = STATUS_PENDING;
1616 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1621 status = wsaErrStatus();
1626 if (status != STATUS_PENDING)
1628 iosb->u.Status = status;
1629 iosb->Information = result;
1630 *apc = ws2_async_apc;
1635 /* user APC called upon async accept completion */
1636 static void WINAPI ws2_async_accept_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1638 struct ws2_accept_async *wsa = arg;
1640 HeapFree( GetProcessHeap(), 0, wsa->read );
1641 HeapFree( GetProcessHeap(), 0, wsa );
1644 /***********************************************************************
1645 * WS2_async_accept_recv (INTERNAL)
1647 * This function is used to finish the read part of an accept request. It is
1648 * needed to place the completion on the correct socket (listener).
1650 static NTSTATUS WS2_async_accept_recv( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
1653 struct ws2_accept_async *wsa = arg;
1655 status = WS2_async_recv( wsa->read, iosb, status, &junk );
1656 if (status == STATUS_PENDING)
1659 if (wsa->user_overlapped->hEvent)
1660 SetEvent(wsa->user_overlapped->hEvent);
1662 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
1664 *apc = ws2_async_accept_apc;
1668 /***********************************************************************
1669 * WS2_async_accept (INTERNAL)
1671 * This is the function called to satisfy the AcceptEx callback
1673 static NTSTATUS WS2_async_accept( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
1675 struct ws2_accept_async *wsa = arg;
1679 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
1681 if (status == STATUS_ALERTED)
1683 SERVER_START_REQ( accept_into_socket )
1685 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
1686 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
1687 status = wine_server_call( req );
1691 if (status == STATUS_CANT_WAIT)
1692 return STATUS_PENDING;
1694 if (status == STATUS_INVALID_HANDLE)
1696 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
1697 status = STATUS_CANCELLED;
1700 else if (status == STATUS_HANDLES_CLOSED)
1701 status = STATUS_CANCELLED; /* strange windows behavior */
1703 if (status != STATUS_SUCCESS)
1706 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
1707 addr = ((char *)wsa->buf) + wsa->data_len;
1708 len = wsa->local_len - sizeof(int);
1709 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
1710 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
1713 addr += wsa->local_len;
1714 len = wsa->remote_len - sizeof(int);
1715 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
1716 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
1722 SERVER_START_REQ( register_async )
1724 req->type = ASYNC_TYPE_READ;
1725 req->async.handle = wine_server_obj_handle( wsa->accept_socket );
1726 req->async.callback = wine_server_client_ptr( WS2_async_accept_recv );
1727 req->async.iosb = wine_server_client_ptr( iosb );
1728 req->async.arg = wine_server_client_ptr( wsa );
1729 status = wine_server_call( req );
1733 if (status != STATUS_PENDING)
1736 /* The APC has finished but no completion should be sent for the operation yet, additional processing
1737 * needs to be performed by WS2_async_accept_recv() first. */
1738 return STATUS_MORE_PROCESSING_REQUIRED;
1741 iosb->u.Status = status;
1742 iosb->Information = 0;
1744 if (wsa->user_overlapped->hEvent)
1745 SetEvent(wsa->user_overlapped->hEvent);
1747 *apc = ws2_async_accept_apc;
1751 /***********************************************************************
1752 * WS2_send (INTERNAL)
1754 * Workhorse for both synchronous and asynchronous send() operations.
1756 static int WS2_send( int fd, struct ws2_async *wsa )
1759 union generic_unix_sockaddr unix_addr;
1762 hdr.msg_name = NULL;
1763 hdr.msg_namelen = 0;
1767 hdr.msg_name = &unix_addr;
1768 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
1769 if ( !hdr.msg_namelen )
1775 #if defined(HAVE_IPX) && defined(SOL_IPX)
1776 if(wsa->addr->sa_family == WS_AF_IPX)
1778 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1780 unsigned int len=sizeof(int);
1782 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1783 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1784 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1785 * ipx type in the sockaddr_opx structure with the stored value.
1787 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1788 uipx->sipx_type = val;
1793 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1794 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1795 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1796 hdr.msg_accrights = NULL;
1797 hdr.msg_accrightslen = 0;
1799 hdr.msg_control = NULL;
1800 hdr.msg_controllen = 0;
1804 ret = sendmsg(fd, &hdr, wsa->flags);
1808 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
1809 n -= wsa->iovec[wsa->first_iovec++].iov_len;
1810 if (wsa->first_iovec < wsa->n_iovecs)
1812 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
1813 wsa->iovec[wsa->first_iovec].iov_len -= n;
1819 /***********************************************************************
1820 * WS2_async_send (INTERNAL)
1822 * Handler for overlapped send() operations.
1824 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1826 ws2_async* wsa = user;
1831 case STATUS_ALERTED:
1832 if ( wsa->n_iovecs <= wsa->first_iovec )
1835 status = STATUS_SUCCESS;
1838 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1841 /* check to see if the data is ready (non-blocking) */
1842 result = WS2_send( fd, wsa );
1843 wine_server_release_fd( wsa->hSocket, fd );
1847 if (wsa->first_iovec < wsa->n_iovecs)
1848 status = STATUS_PENDING;
1850 status = STATUS_SUCCESS;
1852 iosb->Information += result;
1854 else if (errno == EINTR || errno == EAGAIN)
1856 status = STATUS_PENDING;
1860 status = wsaErrStatus();
1864 if (status != STATUS_PENDING)
1866 iosb->u.Status = status;
1867 *apc = ws2_async_apc;
1872 /***********************************************************************
1873 * WS2_async_shutdown (INTERNAL)
1875 * Handler for shutdown() operations on overlapped sockets.
1877 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
1879 ws2_async* wsa = user;
1884 case STATUS_ALERTED:
1885 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1888 switch ( wsa->type )
1890 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1891 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1893 status = err ? wsaErrStatus() : STATUS_SUCCESS;
1894 wine_server_release_fd( wsa->hSocket, fd );
1897 iosb->u.Status = status;
1898 iosb->Information = 0;
1899 *apc = ws2_async_apc;
1903 /***********************************************************************
1904 * WS2_register_async_shutdown (INTERNAL)
1906 * Helper function for WS_shutdown() on overlapped sockets.
1908 static int WS2_register_async_shutdown( SOCKET s, int type )
1910 struct ws2_async *wsa;
1913 TRACE("s %ld type %d\n", s, type);
1915 wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async, iovec[1] ));
1919 wsa->hSocket = SOCKET2HANDLE(s);
1921 wsa->completion_func = NULL;
1923 SERVER_START_REQ( register_async )
1926 req->async.handle = wine_server_obj_handle( wsa->hSocket );
1927 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
1928 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
1929 req->async.arg = wine_server_client_ptr( wsa );
1930 req->async.cvalue = 0;
1931 status = wine_server_call( req );
1935 if (status != STATUS_PENDING)
1937 HeapFree( GetProcessHeap(), 0, wsa );
1938 return NtStatusToWSAError( status );
1943 /***********************************************************************
1946 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1953 TRACE("socket %04lx\n", s );
1954 is_blocking = _is_blocking(s);
1957 /* try accepting first (if there is a deferred connection) */
1958 SERVER_START_REQ( accept_socket )
1960 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1961 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1962 req->attributes = OBJ_INHERIT;
1963 status = wine_server_call( req );
1964 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
1969 if (addr) WS_getpeername(as, addr, addrlen32);
1972 if (is_blocking && status == STATUS_CANT_WAIT)
1974 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1976 do_block(fd, POLLIN, -1);
1977 _sync_sock_state(s); /* let wineserver notice connection */
1978 release_sock_fd( s, fd );
1980 } while (is_blocking && status == STATUS_CANT_WAIT);
1983 return INVALID_SOCKET;
1986 /***********************************************************************
1989 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
1990 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
1991 LPOVERLAPPED overlapped)
1994 struct ws2_accept_async *wsa;
1996 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
1998 TRACE("(%lx, %lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
1999 rem_addr_len, received, overlapped);
2003 SetLastError(WSAEINVAL);
2009 SetLastError(WSA_INVALID_PARAMETER);
2013 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
2016 SetLastError(WSAENOTSOCK);
2019 release_sock_fd( listener, fd );
2021 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
2024 SetLastError(WSAEINVAL);
2027 release_sock_fd( acceptor, fd );
2029 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
2032 SetLastError(WSAEFAULT);
2036 wsa->listen_socket = SOCKET2HANDLE(listener);
2037 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2038 wsa->user_overlapped = overlapped;
2039 wsa->cvalue = cvalue;
2041 wsa->data_len = dest_len;
2042 wsa->local_len = local_addr_len;
2043 wsa->remote_len = rem_addr_len;
2048 /* set up a read request if we need it */
2049 wsa->read = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[1]) );
2052 HeapFree( GetProcessHeap(), 0, wsa );
2053 SetLastError(WSAEFAULT);
2057 wsa->read->hSocket = wsa->accept_socket;
2058 wsa->read->flags = 0;
2059 wsa->read->lpFlags = &wsa->read->flags;
2060 wsa->read->addr = NULL;
2061 wsa->read->addrlen.ptr = NULL;
2062 wsa->read->control = NULL;
2063 wsa->read->n_iovecs = 1;
2064 wsa->read->first_iovec = 0;
2065 wsa->read->iovec[0].iov_base = wsa->buf;
2066 wsa->read->iovec[0].iov_len = wsa->data_len;
2069 SERVER_START_REQ( register_async )
2071 req->type = ASYNC_TYPE_READ;
2072 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2073 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2074 req->async.iosb = wine_server_client_ptr( overlapped );
2075 req->async.arg = wine_server_client_ptr( wsa );
2076 req->async.cvalue = cvalue;
2077 /* We don't set event since we may also have to read */
2078 status = wine_server_call( req );
2082 if(status != STATUS_PENDING)
2084 HeapFree( GetProcessHeap(), 0, wsa->read );
2085 HeapFree( GetProcessHeap(), 0, wsa );
2088 SetLastError( NtStatusToWSAError(status) );
2092 /***********************************************************************
2093 * GetAcceptExSockaddrs
2095 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2096 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2097 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2099 char *cbuf = buffer;
2100 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2101 local_addr_len, remote_addr, remote_addr_len );
2104 *local_addr_len = *(int *) cbuf;
2105 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2109 *remote_addr_len = *(int *) cbuf;
2110 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2113 /***********************************************************************
2116 * Perform a receive operation that is capable of returning message
2117 * control headers. It is important to note that the WSAMSG parameter
2118 * must remain valid throughout the operation, even when an overlapped
2119 * receive is performed.
2121 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2122 LPWSAOVERLAPPED lpOverlapped,
2123 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2127 SetLastError( WSAEFAULT );
2128 return SOCKET_ERROR;
2131 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2132 &msg->dwFlags, msg->name, &msg->namelen,
2133 lpOverlapped, lpCompletionRoutine, &msg->Control );
2136 /***********************************************************************
2137 * interface_bind (INTERNAL)
2139 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
2140 * operating only on the specified interface. This restriction consists of two components:
2141 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
2142 * 2) An incoming packet restriction dropping packets not meant for the interface.
2143 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
2144 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
2145 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
2146 * to receive broadcast packets on a socket that is bound to a specific network interface.
2148 static BOOL interface_bind( SOCKET s, int fd, struct sockaddr *addr )
2150 struct sockaddr_in *in_sock = (struct sockaddr_in *) addr;
2151 unsigned int sock_type = 0, optlen = sizeof(sock_type);
2152 in_addr_t bind_addr = in_sock->sin_addr.s_addr;
2153 PIP_ADAPTER_INFO adapters = NULL, adapter;
2158 if (bind_addr == htonl(WS_INADDR_ANY) || bind_addr == htonl(WS_INADDR_LOOPBACK))
2159 return FALSE; /* Not binding to a network adapter, special interface binding unnecessary. */
2160 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &sock_type, &optlen) == -1 || sock_type != SOCK_DGRAM)
2161 return FALSE; /* Special interface binding is only necessary for UDP datagrams. */
2162 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
2164 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
2165 if (adapters == NULL || GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
2167 /* Search the IPv4 adapter list for the appropriate binding interface */
2168 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
2170 in_addr_t adapter_addr = (in_addr_t) inet_addr(adapter->IpAddressList.IpAddress.String);
2172 if (bind_addr == adapter_addr)
2174 #if defined(IP_BOUND_IF)
2175 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
2176 if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &adapter->Index, sizeof(adapter->Index)) != 0)
2179 #elif defined(LINUX_BOUND_IF)
2180 in_addr_t ifindex = (in_addr_t) htonl(adapter->Index);
2181 struct interface_filter specific_interface_filter;
2182 struct sock_fprog filter_prog;
2184 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex)) != 0)
2185 goto cleanup; /* Failed to suggest egress interface */
2186 memcpy(&specific_interface_filter, &generic_interface_filter, sizeof(generic_interface_filter));
2187 specific_interface_filter.iface_rule.k = adapter->Index;
2188 filter_prog.len = sizeof(generic_interface_filter)/sizeof(struct sock_filter);
2189 filter_prog.filter = (struct sock_filter *) &specific_interface_filter;
2190 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) != 0)
2191 goto cleanup; /* Failed to specify incoming packet filter */
2194 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
2195 "receiving broadcast packets will not work on socket %04lx.\n", s);
2200 /* Will soon be switching to INADDR_ANY: permit address reuse */
2201 if (ret && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == 0)
2202 TRACE("Socket %04lx bound to interface index %d\n", s, adapter->Index);
2208 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s);
2209 HeapFree(GetProcessHeap(), 0, adapters);
2213 /***********************************************************************
2216 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2218 int fd = get_sock_fd( s, 0, NULL );
2219 int res = SOCKET_ERROR;
2221 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2225 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2227 SetLastError(WSAEAFNOSUPPORT);
2231 union generic_unix_sockaddr uaddr;
2232 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2235 SetLastError(WSAEFAULT);
2240 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2241 if (name->sa_family == WS_AF_INET6 &&
2242 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2245 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2247 release_sock_fd( s, fd );
2248 SetLastError(WSAEAFNOSUPPORT);
2249 return SOCKET_ERROR;
2253 if (name->sa_family == WS_AF_INET)
2255 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2256 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2258 /* Trying to bind to the default host interface, using
2259 * INADDR_ANY instead*/
2260 WARN("Trying to bind to magic IP address, using "
2261 "INADDR_ANY instead.\n");
2262 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
2264 else if (interface_bind(s, fd, &uaddr.addr))
2265 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
2267 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2269 int loc_errno = errno;
2270 WARN("\tfailure - errno = %i\n", errno);
2275 SetLastError(WSAENOTSOCK);
2278 SetLastError(WSAEINVAL);
2281 SetLastError(wsaErrno());
2287 res=0; /* success */
2291 release_sock_fd( s, fd );
2296 /***********************************************************************
2297 * closesocket (WS2_32.3)
2299 int WINAPI WS_closesocket(SOCKET s)
2301 TRACE("socket %04lx\n", s);
2302 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
2303 return SOCKET_ERROR;
2306 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2308 union generic_unix_sockaddr uaddr;
2309 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2314 if (name->sa_family == WS_AF_INET)
2316 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2317 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2319 /* Trying to connect to magic replace-loopback address,
2320 * assuming we really want to connect to localhost */
2321 TRACE("Trying to connect to magic IP address, using "
2322 "INADDR_LOOPBACK instead.\n");
2323 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
2327 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
2333 /***********************************************************************
2334 * connect (WS2_32.4)
2336 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
2338 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2340 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2344 int ret = do_connect(fd, name, namelen);
2346 goto connect_success;
2348 if (ret == WSAEINPROGRESS)
2350 /* tell wineserver that a connection is in progress */
2351 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2353 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2354 if (_is_blocking(s))
2358 do_block(fd, POLLIN | POLLOUT, -1);
2359 _sync_sock_state(s); /* let wineserver notice connection */
2360 /* retrieve any error codes from it */
2361 result = _get_sock_error(s, FD_CONNECT_BIT);
2363 SetLastError(NtStatusToWSAError(result));
2366 goto connect_success;
2371 SetLastError(WSAEWOULDBLOCK);
2378 release_sock_fd( s, fd );
2380 return SOCKET_ERROR;
2383 release_sock_fd( s, fd );
2384 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2385 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2386 FD_CONNECT|FD_WINE_LISTENING);
2390 /***********************************************************************
2391 * WSAConnect (WS2_32.30)
2393 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
2394 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
2395 LPQOS lpSQOS, LPQOS lpGQOS )
2397 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
2398 FIXME("unsupported parameters!\n");
2399 return WS_connect( s, name, namelen );
2402 /***********************************************************************
2405 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
2406 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
2408 int fd, ret, status;
2412 SetLastError( ERROR_INVALID_PARAMETER );
2416 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2419 SetLastError( WSAENOTSOCK );
2423 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
2424 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
2426 /* FIXME: technically the socket has to be bound */
2427 ret = do_connect(fd, name, namelen);
2432 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2433 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2434 FD_CONNECT|FD_WINE_LISTENING);
2436 wsabuf.len = sendBufLen;
2437 wsabuf.buf = (char*) sendBuf;
2439 /* WSASend takes care of completion if need be */
2440 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
2441 goto connection_success;
2443 else if (ret == WSAEINPROGRESS)
2445 struct ws2_async *wsa;
2446 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
2448 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2450 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2452 /* Indirectly call WSASend */
2453 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async, iovec[1] ))))
2455 SetLastError(WSAEFAULT);
2459 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
2460 iosb->u.Status = STATUS_PENDING;
2461 iosb->Information = 0;
2463 wsa->hSocket = SOCKET2HANDLE(s);
2465 wsa->addrlen.val = 0;
2467 wsa->lpFlags = &wsa->flags;
2468 wsa->control = NULL;
2469 wsa->n_iovecs = sendBuf ? 1 : 0;
2470 wsa->first_iovec = 0;
2471 wsa->completion_func = NULL;
2472 wsa->iovec[0].iov_base = sendBuf;
2473 wsa->iovec[0].iov_len = sendBufLen;
2475 SERVER_START_REQ( register_async )
2477 req->type = ASYNC_TYPE_WRITE;
2478 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2479 req->async.callback = wine_server_client_ptr( WS2_async_send );
2480 req->async.iosb = wine_server_client_ptr( iosb );
2481 req->async.arg = wine_server_client_ptr( wsa );
2482 req->async.event = wine_server_obj_handle( ov->hEvent );
2483 req->async.cvalue = cvalue;
2484 status = wine_server_call( req );
2488 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
2490 /* If the connect already failed */
2491 if (status == STATUS_PIPE_DISCONNECTED)
2492 status = _get_sock_error(s, FD_CONNECT_BIT);
2493 SetLastError( NtStatusToWSAError(status) );
2501 release_sock_fd( s, fd );
2505 release_sock_fd( s, fd );
2510 /***********************************************************************
2511 * getpeername (WS2_32.5)
2513 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
2518 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
2520 fd = get_sock_fd( s, 0, NULL );
2525 union generic_unix_sockaddr uaddr;
2526 unsigned int uaddrlen = sizeof(uaddr);
2528 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
2530 if (!name || !namelen)
2531 SetLastError(WSAEFAULT);
2532 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2533 /* The buffer was too small */
2534 SetLastError(WSAEFAULT);
2539 SetLastError(wsaErrno());
2540 release_sock_fd( s, fd );
2545 /***********************************************************************
2546 * getsockname (WS2_32.6)
2548 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
2553 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
2555 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
2556 if( (name == NULL) || (namelen == NULL) )
2558 SetLastError( WSAEFAULT );
2559 return SOCKET_ERROR;
2562 fd = get_sock_fd( s, 0, NULL );
2567 union generic_unix_sockaddr uaddr;
2568 unsigned int uaddrlen = sizeof(uaddr);
2570 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2572 SetLastError(wsaErrno());
2574 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2576 SetLastError(WSAEINVAL);
2578 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2580 /* The buffer was too small */
2581 SetLastError(WSAEFAULT);
2587 release_sock_fd( s, fd );
2592 /***********************************************************************
2593 * getsockopt (WS2_32.7)
2595 INT WINAPI WS_getsockopt(SOCKET s, INT level,
2596 INT optname, char *optval, INT *optlen)
2601 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2602 s, level, optname, optval, *optlen);
2610 /* Handle common cases. The special cases are below, sorted
2612 case WS_SO_ACCEPTCONN:
2613 case WS_SO_BROADCAST:
2616 case WS_SO_KEEPALIVE:
2617 case WS_SO_OOBINLINE:
2619 case WS_SO_REUSEADDR:
2622 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2623 return SOCKET_ERROR;
2624 convert_sockopt(&level, &optname);
2625 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2627 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2630 release_sock_fd( s, fd );
2633 case WS_SO_DONTLINGER:
2635 struct linger lingval;
2636 unsigned int len = sizeof(struct linger);
2638 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
2640 SetLastError(WSAEFAULT);
2641 return SOCKET_ERROR;
2643 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2644 return SOCKET_ERROR;
2646 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
2648 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2653 *(BOOL *)optval = !lingval.l_onoff;
2654 *optlen = sizeof(BOOL);
2657 release_sock_fd( s, fd );
2661 case WS_SO_CONNECT_TIME:
2663 static int pretendtime = 0;
2664 struct WS_sockaddr addr;
2665 int len = sizeof(addr);
2667 if (!optlen || *optlen < sizeof(DWORD) || !optval)
2669 SetLastError(WSAEFAULT);
2670 return SOCKET_ERROR;
2672 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
2673 *(DWORD *)optval = ~0u;
2676 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
2677 *(DWORD *)optval = pretendtime++;
2679 *optlen = sizeof(DWORD);
2682 /* As mentioned in setsockopt, Windows ignores this, so we
2683 * always return true here */
2684 case WS_SO_DONTROUTE:
2685 if (!optlen || *optlen < sizeof(BOOL) || !optval)
2687 SetLastError(WSAEFAULT);
2688 return SOCKET_ERROR;
2690 *(BOOL *)optval = TRUE;
2691 *optlen = sizeof(BOOL);
2696 struct linger lingval;
2698 unsigned int len = sizeof(struct linger), slen = sizeof(int);
2700 /* struct linger and LINGER have different sizes */
2701 if (!optlen || *optlen < sizeof(LINGER) || !optval)
2703 SetLastError(WSAEFAULT);
2704 return SOCKET_ERROR;
2706 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2707 return SOCKET_ERROR;
2709 if ((getsockopt(fd, SOL_SOCKET, SO_TYPE, &so_type, &slen) == 0 && so_type == SOCK_DGRAM))
2711 SetLastError(WSAENOPROTOOPT);
2714 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
2716 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2721 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
2722 ((LINGER *)optval)->l_linger = lingval.l_linger;
2723 *optlen = sizeof(struct linger);
2726 release_sock_fd( s, fd );
2730 case WS_SO_MAX_MSG_SIZE:
2731 if (!optlen || *optlen < sizeof(int) || !optval)
2733 SetLastError(WSAEFAULT);
2734 return SOCKET_ERROR;
2736 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
2737 *(int *)optval = 65507;
2738 *optlen = sizeof(int);
2741 /* SO_OPENTYPE does not require a valid socket handle. */
2742 case WS_SO_OPENTYPE:
2743 if (!optlen || *optlen < sizeof(int) || !optval)
2745 SetLastError(WSAEFAULT);
2746 return SOCKET_ERROR;
2748 *(int *)optval = get_per_thread_data()->opentype;
2749 *optlen = sizeof(int);
2750 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2754 case WS_SO_RCVTIMEO:
2757 case WS_SO_SNDTIMEO:
2759 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
2762 unsigned int len = sizeof(struct timeval);
2764 if (!optlen || *optlen < sizeof(int)|| !optval)
2766 SetLastError(WSAEFAULT);
2767 return SOCKET_ERROR;
2769 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2770 return SOCKET_ERROR;
2772 convert_sockopt(&level, &optname);
2773 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
2775 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2780 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
2781 *optlen = sizeof(int);
2784 release_sock_fd( s, fd );
2789 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
2790 SetLastError(WSAENOPROTOOPT);
2791 return SOCKET_ERROR;
2792 } /* end switch(optname) */
2793 }/* end case WS_SOL_SOCKET */
2797 struct WS_sockaddr_ipx addr;
2798 IPX_ADDRESS_DATA *data;
2803 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
2805 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
2812 socklen_t len=sizeof(struct ipx);
2813 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
2816 *optval = (int)val.ipx_pt;
2819 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
2820 release_sock_fd( s, fd );
2825 * On a Win2000 system with one network card there are usually
2826 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
2827 * Using this call you can then retrieve info about this all.
2828 * In case of Linux it is a bit different. Usually you have
2829 * only "one" device active and further it is not possible to
2830 * query things like the linkspeed.
2832 FIXME("IPX_ADDRESS\n");
2833 namelen = sizeof(struct WS_sockaddr_ipx);
2834 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
2835 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
2837 data = (IPX_ADDRESS_DATA*)optval;
2838 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
2839 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
2840 data->adapternum = 0;
2841 data->wan = FALSE; /* We are not on a wan for now .. */
2842 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
2843 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
2844 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
2845 * note 1MB = 1000kB in this case */
2848 case IPX_MAX_ADAPTER_NUM:
2849 FIXME("IPX_MAX_ADAPTER_NUM\n");
2850 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
2854 FIXME("IPX optname:%x\n", optname);
2855 return SOCKET_ERROR;
2856 }/* end switch(optname) */
2857 } /* end case NSPROTO_IPX */
2864 case WS_IRLMP_ENUMDEVICES:
2866 static const int MAX_IRDA_DEVICES = 10;
2867 char buf[sizeof(struct irda_device_list) +
2868 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
2870 socklen_t len = sizeof(buf);
2872 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2873 return SOCKET_ERROR;
2874 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
2877 SetLastError(wsaErrno());
2878 return SOCKET_ERROR;
2882 struct irda_device_list *src = (struct irda_device_list *)buf;
2883 DEVICELIST *dst = (DEVICELIST *)optval;
2884 INT needed = sizeof(DEVICELIST), i;
2887 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
2888 if (*optlen < needed)
2890 SetLastError(WSAEFAULT);
2891 return SOCKET_ERROR;
2894 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
2895 dst->numDevice = src->len;
2896 for (i = 0; i < src->len; i++)
2898 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
2899 src->dev[i].saddr, src->dev[i].daddr,
2900 src->dev[i].info, src->dev[i].hints[0],
2901 src->dev[i].hints[1]);
2902 memcpy( dst->Device[i].irdaDeviceID,
2904 sizeof(dst->Device[i].irdaDeviceID) ) ;
2905 memcpy( dst->Device[i].irdaDeviceName,
2907 sizeof(dst->Device[i].irdaDeviceName) ) ;
2908 memcpy( &dst->Device[i].irdaDeviceHints1,
2909 &src->dev[i].hints[0],
2910 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
2911 memcpy( &dst->Device[i].irdaDeviceHints2,
2912 &src->dev[i].hints[1],
2913 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
2914 dst->Device[i].irdaCharSet = src->dev[i].charset;
2920 FIXME("IrDA optname:0x%x\n", optname);
2921 return SOCKET_ERROR;
2923 break; /* case WS_SOL_IRLMP */
2926 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
2927 case WS_IPPROTO_TCP:
2930 case WS_TCP_NODELAY:
2931 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2932 return SOCKET_ERROR;
2933 convert_sockopt(&level, &optname);
2934 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2936 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2939 release_sock_fd( s, fd );
2942 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
2943 return SOCKET_ERROR;
2948 case WS_IP_ADD_MEMBERSHIP:
2949 case WS_IP_DROP_MEMBERSHIP:
2953 case WS_IP_MULTICAST_IF:
2954 case WS_IP_MULTICAST_LOOP:
2955 case WS_IP_MULTICAST_TTL:
2962 #ifdef IP_UNICAST_IF
2963 case WS_IP_UNICAST_IF:
2965 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2966 return SOCKET_ERROR;
2967 convert_sockopt(&level, &optname);
2968 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2970 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2973 release_sock_fd( s, fd );
2975 case WS_IP_DONTFRAGMENT:
2976 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
2977 *(BOOL*)optval = FALSE;
2980 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
2981 return SOCKET_ERROR;
2983 case WS_IPPROTO_IPV6:
2986 #ifdef IPV6_ADD_MEMBERSHIP
2987 case WS_IPV6_ADD_MEMBERSHIP:
2989 #ifdef IPV6_DROP_MEMBERSHIP
2990 case WS_IPV6_DROP_MEMBERSHIP:
2992 case WS_IPV6_MULTICAST_IF:
2993 case WS_IPV6_MULTICAST_HOPS:
2994 case WS_IPV6_MULTICAST_LOOP:
2995 case WS_IPV6_UNICAST_HOPS:
2996 case WS_IPV6_V6ONLY:
2997 #ifdef IPV6_UNICAST_IF
2998 case WS_IPV6_UNICAST_IF:
3000 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3001 return SOCKET_ERROR;
3002 convert_sockopt(&level, &optname);
3003 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
3005 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3008 release_sock_fd( s, fd );
3010 case WS_IPV6_DONTFRAG:
3011 FIXME("WS_IPV6_DONTFRAG is always false!\n");
3012 *(BOOL*)optval = FALSE;
3015 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
3016 return SOCKET_ERROR;
3019 WARN("Unknown level: 0x%08x\n", level);
3020 SetLastError(WSAEINVAL);
3021 return SOCKET_ERROR;
3022 } /* end switch(level) */
3025 /***********************************************************************
3028 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
3030 return htonl(hostlong);
3034 /***********************************************************************
3037 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
3039 return htons(hostshort);
3042 /***********************************************************************
3043 * WSAHtonl (WS2_32.46)
3044 * From MSDN description of error codes, this function should also
3045 * check if WinSock has been initialized and the socket is a valid
3046 * socket. But why? This function only translates a host byte order
3047 * u_long into a network byte order u_long...
3049 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
3053 *lpnetlong = htonl(hostlong);
3056 WSASetLastError(WSAEFAULT);
3057 return SOCKET_ERROR;
3060 /***********************************************************************
3061 * WSAHtons (WS2_32.47)
3062 * From MSDN description of error codes, this function should also
3063 * check if WinSock has been initialized and the socket is a valid
3064 * socket. But why? This function only translates a host byte order
3065 * u_short into a network byte order u_short...
3067 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
3072 *lpnetshort = htons(hostshort);
3075 WSASetLastError(WSAEFAULT);
3076 return SOCKET_ERROR;
3080 /***********************************************************************
3081 * inet_addr (WS2_32.11)
3083 WS_u_long WINAPI WS_inet_addr(const char *cp)
3085 if (!cp) return INADDR_NONE;
3086 return inet_addr(cp);
3090 /***********************************************************************
3093 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
3095 return ntohl(netlong);
3099 /***********************************************************************
3102 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
3104 return ntohs(netshort);
3108 /***********************************************************************
3109 * inet_ntoa (WS2_32.12)
3111 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
3113 /* use "buffer for dummies" here because some applications have a
3114 * propensity to decode addresses in ws_hostent structure without
3115 * saving them first...
3117 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
3119 char* s = inet_ntoa(*((struct in_addr*)&in));
3125 SetLastError(wsaErrno());
3129 static const char *debugstr_wsaioctl(DWORD ioctl)
3131 const char *buf_type, *family;
3133 switch(ioctl & 0x18000000)
3138 case WS_IOC_PROTOCOL:
3139 family = "IOC_PROTOCOL";
3142 family = "IOC_VENDOR";
3144 default: /* WS_IOC_UNIX */
3146 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
3147 char x = (ioctl & 0xff00) >> 8;
3148 BYTE y = ioctl & 0xff;
3151 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3155 sprintf(args, "%d, %d", x, y);
3159 sprintf(args, "'%c', %d, %d", x, y, size);
3163 sprintf(args, "'%c', %d, %d", x, y, size);
3167 sprintf(args, "'%c', %d, %d", x, y, size);
3170 return wine_dbg_sprintf("%s(%s)", buf_type, args);
3174 /* We are different from WS_IOC_UNIX. */
3175 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3178 buf_type = "_WSAIO";
3181 buf_type = "_WSAIORW";
3184 buf_type = "_WSAIOW";
3187 buf_type = "_WSAIOR";
3194 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
3195 (USHORT)(ioctl & 0xffff));
3198 /**********************************************************************
3199 * WSAIoctl (WS2_32.50)
3202 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
3203 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
3204 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
3207 DWORD status = 0, total = 0;
3209 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
3210 s, code, in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
3215 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
3217 WSASetLastError(WSAEFAULT);
3218 return SOCKET_ERROR;
3220 if (_get_sock_mask(s))
3222 /* AsyncSelect()'ed sockets are always nonblocking */
3223 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
3226 if (*(WS_u_long *)in_buff)
3227 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
3229 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
3234 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3236 WSASetLastError(WSAEFAULT);
3237 return SOCKET_ERROR;
3239 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3240 if (ioctl(fd, FIONREAD, out_buff ) == -1)
3241 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3242 release_sock_fd( s, fd );
3248 unsigned int oob = 0, oobsize = sizeof(int), atmark = 0;
3249 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3251 WSASetLastError(WSAEFAULT);
3252 return SOCKET_ERROR;
3254 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3255 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
3256 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
3257 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
3258 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3261 /* The SIOCATMARK value read from ioctl() is reversed
3262 * because BSD returns TRUE if it's in the OOB mark
3263 * while Windows returns TRUE if there are NO OOB bytes.
3265 (*(WS_u_long *) out_buff) = oob | !atmark;
3268 release_sock_fd( s, fd );
3273 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
3274 SetLastError(WSAEINVAL);
3275 return SOCKET_ERROR;
3277 case WS_SIO_GET_INTERFACE_LIST:
3279 INTERFACE_INFO* intArray = out_buff;
3280 DWORD size, numInt = 0, apiReturn;
3282 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
3284 if (!out_buff || !ret_size)
3286 WSASetLastError(WSAEFAULT);
3287 return SOCKET_ERROR;
3290 fd = get_sock_fd( s, 0, NULL );
3291 if (fd == -1) return SOCKET_ERROR;
3293 apiReturn = GetAdaptersInfo(NULL, &size);
3294 if (apiReturn == ERROR_BUFFER_OVERFLOW)
3296 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
3300 if (GetAdaptersInfo(table, &size) == NO_ERROR)
3302 PIP_ADAPTER_INFO ptr;
3304 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
3306 unsigned int addr, mask, bcast;
3307 struct ifreq ifInfo;
3309 /* Skip interfaces without an IPv4 address. */
3310 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
3313 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
3315 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
3320 /* Socket Status Flags */
3321 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
3322 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
3324 ERR("Error obtaining status flags for socket!\n");
3330 /* set flags; the values of IFF_* are not the same
3331 under Linux and Windows, therefore must generate
3333 intArray->iiFlags = 0;
3334 if (ifInfo.ifr_flags & IFF_BROADCAST)
3335 intArray->iiFlags |= WS_IFF_BROADCAST;
3336 #ifdef IFF_POINTOPOINT
3337 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
3338 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
3340 if (ifInfo.ifr_flags & IFF_LOOPBACK)
3341 intArray->iiFlags |= WS_IFF_LOOPBACK;
3342 if (ifInfo.ifr_flags & IFF_UP)
3343 intArray->iiFlags |= WS_IFF_UP;
3344 if (ifInfo.ifr_flags & IFF_MULTICAST)
3345 intArray->iiFlags |= WS_IFF_MULTICAST;
3348 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
3349 mask = inet_addr(ptr->IpAddressList.IpMask.String);
3350 bcast = addr | ~mask;
3351 intArray->iiAddress.AddressIn.sin_family = AF_INET;
3352 intArray->iiAddress.AddressIn.sin_port = 0;
3353 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
3355 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
3356 intArray->iiNetmask.AddressIn.sin_port = 0;
3357 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
3359 intArray->iiBroadcastAddress.AddressIn.sin_family =
3361 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
3362 intArray->iiBroadcastAddress.AddressIn.sin_addr.
3370 ERR("Unable to get interface table!\n");
3373 HeapFree(GetProcessHeap(),0,table);
3375 else status = WSAEINVAL;
3377 else if (apiReturn != ERROR_NO_DATA)
3379 ERR("Unable to get interface table!\n");
3382 /* Calculate the size of the array being returned */
3383 total = sizeof(INTERFACE_INFO) * numInt;
3384 release_sock_fd( s, fd );
3388 case WS_SIO_ADDRESS_LIST_CHANGE:
3389 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
3390 /* FIXME: error and return code depend on whether socket was created
3391 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
3394 case WS_SIO_ADDRESS_LIST_QUERY:
3398 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
3402 WSASetLastError(WSAEFAULT);
3403 return SOCKET_ERROR;
3406 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
3408 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
3411 if (!table || GetAdaptersInfo(table, &size))
3413 HeapFree(GetProcessHeap(), 0, table);
3418 for (p = table, num = 0; p; p = p->Next)
3419 if (p->IpAddressList.IpAddress.String[0]) num++;
3421 total = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
3422 total += sizeof(SOCKADDR) * num;
3424 if (total > out_size)
3426 HeapFree(GetProcessHeap(), 0, table);
3435 SOCKET_ADDRESS_LIST *sa_list = out_buff;
3436 SOCKADDR_IN *sockaddr;
3438 sa = sa_list->Address;
3439 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
3440 sa_list->iAddressCount = num;
3442 for (p = table, i = 0; p; p = p->Next)
3444 if (!p->IpAddressList.IpAddress.String[0]) continue;
3446 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
3447 sa[i].iSockaddrLength = sizeof(SOCKADDR);
3449 sockaddr[i].sin_family = AF_INET;
3450 sockaddr[i].sin_port = 0;
3451 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
3456 HeapFree(GetProcessHeap(), 0, table);
3460 WARN("unable to get IP address list\n");
3467 FIXME("SIO_FLUSH: stub.\n");
3470 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
3472 static const GUID connectex_guid = WSAID_CONNECTEX;
3473 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
3474 static const GUID acceptex_guid = WSAID_ACCEPTEX;
3475 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
3476 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
3477 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
3478 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
3479 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
3481 if ( IsEqualGUID(&connectex_guid, in_buff) )
3483 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
3486 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
3488 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
3490 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
3492 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
3495 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
3497 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
3500 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
3502 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
3504 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
3506 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
3508 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
3510 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
3513 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
3515 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented WSASendMsg\n");
3518 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
3520 status = WSAEOPNOTSUPP;
3523 case WS_SIO_KEEPALIVE_VALS:
3525 struct tcp_keepalive *k;
3526 int keepalive, keepidle, keepintvl;
3528 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
3530 WSASetLastError(WSAEFAULT);
3531 return SOCKET_ERROR;
3535 keepalive = k->onoff ? 1 : 0;
3536 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
3537 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
3539 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
3541 fd = get_sock_fd(s, 0, NULL);
3542 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
3544 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
3545 /* these values need to be set only if SO_KEEPALIVE is enabled */
3548 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
3550 else if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
3555 FIXME("ignoring keepalive interval and timeout\n");
3557 release_sock_fd(s, fd);
3560 case WS_SIO_ROUTING_INTERFACE_QUERY:
3562 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
3563 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
3564 struct WS_sockaddr_in *saddr_in = out_buff;
3565 MIB_IPFORWARDROW row;
3566 PMIB_IPADDRTABLE ipAddrTable = NULL;
3567 DWORD size, i, found_index;
3569 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
3571 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
3572 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
3574 WSASetLastError(WSAEFAULT);
3575 return SOCKET_ERROR;
3577 if (daddr->sa_family != AF_INET)
3579 FIXME("unsupported address family %d\n", daddr->sa_family);
3580 status = WSAEAFNOSUPPORT;
3583 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
3584 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
3589 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
3590 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
3592 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3596 for (i = 0, found_index = ipAddrTable->dwNumEntries;
3597 i < ipAddrTable->dwNumEntries; i++)
3599 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
3602 if (found_index == ipAddrTable->dwNumEntries)
3604 ERR("no matching IP address for interface %d\n",
3605 row.dwForwardIfIndex);
3606 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3610 saddr_in->sin_family = AF_INET;
3611 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
3612 saddr_in->sin_port = 0;
3613 total = sizeof(struct WS_sockaddr_in);
3614 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3617 case WS_SIO_SET_COMPATIBILITY_MODE:
3618 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
3619 status = WSAEOPNOTSUPP;
3621 case WS_SIO_UDP_CONNRESET:
3622 FIXME("WS_SIO_UDP_CONNRESET stub\n");
3624 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
3625 WSASetLastError(WSAEOPNOTSUPP);
3626 return SOCKET_ERROR;
3628 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
3629 status = WSAEOPNOTSUPP;
3635 FIXME( "completion routine %p not supported\n", completion );
3637 else if (overlapped)
3639 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
3640 overlapped->Internal = status;
3641 overlapped->InternalHigh = total;
3642 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
3643 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
3648 if (ret_size) *ret_size = total;
3651 SetLastError( status );
3652 return SOCKET_ERROR;
3656 /***********************************************************************
3657 * ioctlsocket (WS2_32.10)
3659 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
3662 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
3665 /***********************************************************************
3666 * listen (WS2_32.13)
3668 int WINAPI WS_listen(SOCKET s, int backlog)
3670 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3672 TRACE("socket %04lx, backlog %d\n", s, backlog);
3675 if (listen(fd, backlog) == 0)
3677 release_sock_fd( s, fd );
3678 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
3680 FD_CONNECT|FD_WINE_CONNECTED);
3683 SetLastError(wsaErrno());
3684 release_sock_fd( s, fd );
3686 return SOCKET_ERROR;
3689 /***********************************************************************
3692 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
3694 DWORD n, dwFlags = flags;
3700 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
3701 return SOCKET_ERROR;
3706 /***********************************************************************
3707 * recvfrom (WS2_32.17)
3709 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
3710 struct WS_sockaddr *from, int *fromlen)
3712 DWORD n, dwFlags = flags;
3718 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
3719 return SOCKET_ERROR;
3724 /* allocate a poll array for the corresponding fd sets */
3725 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
3726 const WS_fd_set *exceptfds, int *count_ptr )
3728 unsigned int i, j = 0, count = 0;
3731 if (readfds) count += readfds->fd_count;
3732 if (writefds) count += writefds->fd_count;
3733 if (exceptfds) count += exceptfds->fd_count;
3737 SetLastError(WSAEINVAL);
3740 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
3742 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
3746 for (i = 0; i < readfds->fd_count; i++, j++)
3748 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
3749 if (fds[j].fd == -1) goto failed;
3750 fds[j].events = POLLIN;
3754 for (i = 0; i < writefds->fd_count; i++, j++)
3756 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
3757 if (fds[j].fd == -1) goto failed;
3758 fds[j].events = POLLOUT;
3762 for (i = 0; i < exceptfds->fd_count; i++, j++)
3764 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
3765 if (fds[j].fd == -1) goto failed;
3766 fds[j].events = POLLHUP;
3775 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
3776 release_sock_fd( readfds->fd_array[i], fds[j].fd );
3778 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
3779 release_sock_fd( writefds->fd_array[i], fds[j].fd );
3781 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
3782 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
3783 HeapFree( GetProcessHeap(), 0, fds );
3787 /* release the file descriptor obtained in fd_sets_to_poll */
3788 /* must be called with the original fd_set arrays, before calling get_poll_results */
3789 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
3790 const WS_fd_set *exceptfds, struct pollfd *fds )
3792 unsigned int i, j = 0;
3796 for (i = 0; i < readfds->fd_count; i++, j++)
3797 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
3801 for (i = 0; i < writefds->fd_count; i++, j++)
3802 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
3806 for (i = 0; i < exceptfds->fd_count; i++, j++)
3807 if (fds[j].fd != -1)
3809 /* make sure we have a real error before releasing the fd */
3810 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
3811 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
3816 /* map the poll results back into the Windows fd sets */
3817 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
3818 const struct pollfd *fds )
3820 unsigned int i, j = 0, k, total = 0;
3824 for (i = k = 0; i < readfds->fd_count; i++, j++)
3825 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
3826 readfds->fd_count = k;
3831 for (i = k = 0; i < writefds->fd_count; i++, j++)
3832 if ((fds[j].revents & POLLOUT) && !(fds[j].revents & POLLHUP))
3833 writefds->fd_array[k++] = writefds->fd_array[i];
3834 writefds->fd_count = k;
3839 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
3840 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
3841 exceptfds->fd_count = k;
3848 /***********************************************************************
3849 * select (WS2_32.18)
3851 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
3852 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
3853 const struct WS_timeval* ws_timeout)
3855 struct pollfd *pollfds;
3856 struct timeval tv1, tv2;
3858 int count, ret, timeout = -1;
3860 TRACE("read %p, write %p, excp %p timeout %p\n",
3861 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
3863 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
3864 return SOCKET_ERROR;
3868 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
3870 gettimeofday( &tv1, 0 );
3873 while ((ret = poll( pollfds, count, timeout )) < 0)
3877 if (!ws_timeout) continue;
3878 gettimeofday( &tv2, 0 );
3880 tv2.tv_sec -= tv1.tv_sec;
3881 tv2.tv_usec -= tv1.tv_usec;
3882 if (tv2.tv_usec < 0)
3884 tv2.tv_usec += 1000000;
3888 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
3889 if (timeout <= 0) break;
3892 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3894 if (ret == -1) SetLastError(wsaErrno());
3895 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3896 HeapFree( GetProcessHeap(), 0, pollfds );
3900 /* helper to send completion messages for client-only i/o operation case */
3901 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
3904 SERVER_START_REQ( add_fd_completion )
3906 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
3907 req->cvalue = CompletionValue;
3908 req->status = CompletionStatus;
3909 req->information = Information;
3910 wine_server_call( req );
3916 /***********************************************************************
3919 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
3925 wsabuf.buf = (char*) buf;
3927 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
3928 return SOCKET_ERROR;
3933 /***********************************************************************
3934 * WSASend (WS2_32.72)
3936 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3937 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3938 LPWSAOVERLAPPED lpOverlapped,
3939 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3941 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
3942 NULL, 0, lpOverlapped, lpCompletionRoutine );
3945 /***********************************************************************
3946 * WSASendDisconnect (WS2_32.73)
3948 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
3950 return WS_shutdown( s, SD_SEND );
3954 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3955 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3956 const struct WS_sockaddr *to, int tolen,
3957 LPWSAOVERLAPPED lpOverlapped,
3958 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3960 unsigned int i, options;
3962 struct ws2_async *wsa = NULL;
3963 int totalLength = 0;
3964 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
3967 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
3968 s, lpBuffers, dwBufferCount, dwFlags,
3969 to, tolen, lpOverlapped, lpCompletionRoutine);
3971 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
3972 TRACE( "fd=%d, options=%x\n", fd, options );
3974 if ( fd == -1 ) return SOCKET_ERROR;
3976 if (!lpOverlapped && !lpNumberOfBytesSent)
3981 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
3987 wsa->hSocket = SOCKET2HANDLE(s);
3988 wsa->addr = (struct WS_sockaddr *)to;
3989 wsa->addrlen.val = tolen;
3990 wsa->flags = dwFlags;
3991 wsa->lpFlags = &wsa->flags;
3992 wsa->control = NULL;
3993 wsa->n_iovecs = dwBufferCount;
3994 wsa->first_iovec = 0;
3995 for ( i = 0; i < dwBufferCount; i++ )
3997 wsa->iovec[i].iov_base = lpBuffers[i].buf;
3998 wsa->iovec[i].iov_len = lpBuffers[i].len;
3999 totalLength += lpBuffers[i].len;
4004 n = WS2_send( fd, wsa );
4005 if (n != -1 || errno != EINTR) break;
4007 if (n == -1 && errno != EAGAIN)
4013 if ((lpOverlapped || lpCompletionRoutine) &&
4014 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4016 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4018 wsa->user_overlapped = lpOverlapped;
4019 wsa->completion_func = lpCompletionRoutine;
4020 release_sock_fd( s, fd );
4022 if (n == -1 || n < totalLength)
4024 iosb->u.Status = STATUS_PENDING;
4025 iosb->Information = n == -1 ? 0 : n;
4027 SERVER_START_REQ( register_async )
4029 req->type = ASYNC_TYPE_WRITE;
4030 req->async.handle = wine_server_obj_handle( wsa->hSocket );
4031 req->async.callback = wine_server_client_ptr( WS2_async_send );
4032 req->async.iosb = wine_server_client_ptr( iosb );
4033 req->async.arg = wine_server_client_ptr( wsa );
4034 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
4035 req->async.cvalue = cvalue;
4036 err = wine_server_call( req );
4040 /* Enable the event only after starting the async. The server will deliver it as soon as
4041 the async is done. */
4042 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4044 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4045 WSASetLastError( NtStatusToWSAError( err ));
4046 return SOCKET_ERROR;
4049 iosb->u.Status = STATUS_SUCCESS;
4050 iosb->Information = n;
4051 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
4052 if (!wsa->completion_func)
4054 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4055 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
4056 HeapFree( GetProcessHeap(), 0, wsa );
4058 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4059 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4064 if ( _is_blocking(s) )
4066 /* On a blocking non-overlapped stream socket,
4067 * sending blocks until the entire buffer is sent. */
4068 DWORD timeout_start = GetTickCount();
4070 bytes_sent = n == -1 ? 0 : n;
4072 while (wsa->first_iovec < wsa->n_iovecs)
4075 int timeout = GET_SNDTIMEO(fd);
4079 timeout -= GetTickCount() - timeout_start;
4080 if (timeout < 0) timeout = 0;
4084 pfd.events = POLLOUT;
4086 if (!timeout || !poll( &pfd, 1, timeout ))
4089 goto error; /* msdn says a timeout in send is fatal */
4092 n = WS2_send( fd, wsa );
4093 if (n == -1 && errno != EAGAIN && errno != EINTR)
4103 else /* non-blocking */
4105 if (n < totalLength)
4106 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4109 err = WSAEWOULDBLOCK;
4115 TRACE(" -> %i bytes\n", bytes_sent);
4117 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
4118 HeapFree( GetProcessHeap(), 0, wsa );
4119 release_sock_fd( s, fd );
4124 HeapFree( GetProcessHeap(), 0, wsa );
4125 release_sock_fd( s, fd );
4126 WARN(" -> ERROR %d\n", err);
4127 WSASetLastError(err);
4128 return SOCKET_ERROR;
4131 /***********************************************************************
4132 * WSASendTo (WS2_32.74)
4134 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4135 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4136 const struct WS_sockaddr *to, int tolen,
4137 LPWSAOVERLAPPED lpOverlapped,
4138 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4140 return WS2_sendto( s, lpBuffers, dwBufferCount,
4141 lpNumberOfBytesSent, dwFlags,
4143 lpOverlapped, lpCompletionRoutine );
4146 /***********************************************************************
4147 * sendto (WS2_32.20)
4149 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
4150 const struct WS_sockaddr *to, int tolen)
4156 wsabuf.buf = (char*) buf;
4158 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
4159 return SOCKET_ERROR;
4164 /***********************************************************************
4165 * setsockopt (WS2_32.21)
4167 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
4168 const char *optval, int optlen)
4172 struct linger linger;
4173 struct timeval tval;
4175 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
4176 s, level, optname, optval, optlen);
4178 /* some broken apps pass the value directly instead of a pointer to it */
4179 if(optlen && IS_INTRESOURCE(optval))
4181 SetLastError(WSAEFAULT);
4182 return SOCKET_ERROR;
4190 /* Some options need some conversion before they can be sent to
4191 * setsockopt. The conversions are done here, then they will fall though
4192 * to the general case. Special options that are not passed to
4193 * setsockopt follow below that.*/
4195 case WS_SO_DONTLINGER:
4198 SetLastError(WSAEFAULT);
4199 return SOCKET_ERROR;
4201 linger.l_onoff = *(const int*)optval == 0;
4202 linger.l_linger = 0;
4204 optname = SO_LINGER;
4205 optval = (char*)&linger;
4206 optlen = sizeof(struct linger);
4212 SetLastError(WSAEFAULT);
4213 return SOCKET_ERROR;
4215 linger.l_onoff = ((LINGER*)optval)->l_onoff;
4216 linger.l_linger = ((LINGER*)optval)->l_linger;
4218 optname = SO_LINGER;
4219 optval = (char*)&linger;
4220 optlen = sizeof(struct linger);
4224 if (*(const int*)optval < 2048)
4226 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
4231 /* The options listed here don't need any special handling. Thanks to
4232 * the conversion happening above, options from there will fall through
4234 case WS_SO_ACCEPTCONN:
4235 case WS_SO_BROADCAST:
4237 case WS_SO_KEEPALIVE:
4238 case WS_SO_OOBINLINE:
4239 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
4240 * however, using it the BSD way fixes bug 8513 and seems to be what
4241 * most programmers assume, anyway */
4242 case WS_SO_REUSEADDR:
4245 convert_sockopt(&level, &optname);
4248 /* SO_DEBUG is a privileged operation, ignore it. */
4250 TRACE("Ignoring SO_DEBUG\n");
4253 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
4254 * socket. According to MSDN, this option is silently ignored.*/
4255 case WS_SO_DONTROUTE:
4256 TRACE("Ignoring SO_DONTROUTE\n");
4259 /* Stops two sockets from being bound to the same port. Always happens
4260 * on unix systems, so just drop it. */
4261 case WS_SO_EXCLUSIVEADDRUSE:
4262 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
4265 /* After a ConnectEx call succeeds, the socket can't be used with half of the
4266 * normal winsock functions on windows. We don't have that problem. */
4267 case WS_SO_UPDATE_CONNECT_CONTEXT:
4268 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
4271 /* After a AcceptEx call succeeds, the socket can't be used with half of the
4272 * normal winsock functions on windows. We don't have that problem. */
4273 case WS_SO_UPDATE_ACCEPT_CONTEXT:
4274 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
4277 /* SO_OPENTYPE does not require a valid socket handle. */
4278 case WS_SO_OPENTYPE:
4279 if (!optlen || optlen < sizeof(int) || !optval)
4281 SetLastError(WSAEFAULT);
4282 return SOCKET_ERROR;
4284 get_per_thread_data()->opentype = *(const int *)optval;
4285 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
4289 case WS_SO_RCVTIMEO:
4292 case WS_SO_SNDTIMEO:
4294 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
4295 if (optval && optlen == sizeof(UINT32)) {
4296 /* WinSock passes milliseconds instead of struct timeval */
4297 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
4298 tval.tv_sec = *(const UINT32*)optval / 1000;
4299 /* min of 500 milliseconds */
4300 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
4301 tval.tv_usec = 500000;
4302 optlen = sizeof(struct timeval);
4303 optval = (char*)&tval;
4304 } else if (optlen == sizeof(struct timeval)) {
4305 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
4307 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
4310 convert_sockopt(&level, &optname);
4315 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4316 SetLastError(WSAENOPROTOOPT);
4317 return SOCKET_ERROR;
4319 break; /* case WS_SOL_SOCKET */
4326 fd = get_sock_fd( s, 0, NULL );
4327 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
4329 /* We try to set the ipx type on ipx socket level. */
4331 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
4333 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
4334 release_sock_fd( s, fd );
4335 return SOCKET_ERROR;
4340 /* Should we retrieve val using a getsockopt call and then
4341 * set the modified one? */
4342 val.ipx_pt = *optval;
4343 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
4346 release_sock_fd( s, fd );
4349 case IPX_FILTERPTYPE:
4350 /* Sets the receive filter packet type, at the moment we don't support it */
4351 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
4352 /* Returning 0 is better for now than returning a SOCKET_ERROR */
4356 FIXME("opt_name:%x\n", optname);
4357 return SOCKET_ERROR;
4359 break; /* case NSPROTO_IPX */
4362 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4363 case WS_IPPROTO_TCP:
4366 case WS_TCP_NODELAY:
4367 convert_sockopt(&level, &optname);
4370 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4371 return SOCKET_ERROR;
4378 case WS_IP_ADD_MEMBERSHIP:
4379 case WS_IP_DROP_MEMBERSHIP:
4383 case WS_IP_MULTICAST_IF:
4384 case WS_IP_MULTICAST_LOOP:
4385 case WS_IP_MULTICAST_TTL:
4392 #ifdef IP_UNICAST_IF
4393 case WS_IP_UNICAST_IF:
4395 convert_sockopt(&level, &optname);
4397 case WS_IP_DONTFRAGMENT:
4398 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
4401 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4402 return SOCKET_ERROR;
4406 case WS_IPPROTO_IPV6:
4409 #ifdef IPV6_ADD_MEMBERSHIP
4410 case WS_IPV6_ADD_MEMBERSHIP:
4412 #ifdef IPV6_DROP_MEMBERSHIP
4413 case WS_IPV6_DROP_MEMBERSHIP:
4415 case WS_IPV6_MULTICAST_IF:
4416 case WS_IPV6_MULTICAST_HOPS:
4417 case WS_IPV6_MULTICAST_LOOP:
4418 case WS_IPV6_UNICAST_HOPS:
4419 case WS_IPV6_V6ONLY:
4420 #ifdef IPV6_UNICAST_IF
4421 case WS_IPV6_UNICAST_IF:
4423 convert_sockopt(&level, &optname);
4425 case WS_IPV6_DONTFRAG:
4426 FIXME("IPV6_DONTFRAG is silently ignored!\n");
4428 case WS_IPV6_PROTECTION_LEVEL:
4429 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
4432 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4433 return SOCKET_ERROR;
4438 WARN("Unknown level: 0x%08x\n", level);
4439 SetLastError(WSAEINVAL);
4440 return SOCKET_ERROR;
4441 } /* end switch(level) */
4443 /* avoid endianness issues if argument is a 16-bit int */
4444 if (optval && optlen < sizeof(int))
4446 woptval= *((const INT16 *) optval);
4447 optval= (char*) &woptval;
4450 fd = get_sock_fd( s, 0, NULL );
4451 if (fd == -1) return SOCKET_ERROR;
4453 if (setsockopt(fd, level, optname, optval, optlen) == 0)
4455 release_sock_fd( s, fd );
4458 TRACE("Setting socket error, %d\n", wsaErrno());
4459 SetLastError(wsaErrno());
4460 release_sock_fd( s, fd );
4462 return SOCKET_ERROR;
4465 /***********************************************************************
4466 * shutdown (WS2_32.22)
4468 int WINAPI WS_shutdown(SOCKET s, int how)
4470 int fd, err = WSAENOTSOCK;
4471 unsigned int options, clear_flags = 0;
4473 fd = get_sock_fd( s, 0, &options );
4474 TRACE("socket %04lx, how %i %x\n", s, how, options );
4477 return SOCKET_ERROR;
4481 case 0: /* drop receives */
4482 clear_flags |= FD_READ;
4484 case 1: /* drop sends */
4485 clear_flags |= FD_WRITE;
4487 case 2: /* drop all */
4488 clear_flags |= FD_READ|FD_WRITE;
4491 clear_flags |= FD_WINE_LISTENING;
4494 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4499 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4502 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4506 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4507 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4510 if (err) goto error;
4512 else /* non-overlapped mode */
4514 if ( shutdown( fd, how ) )
4521 release_sock_fd( s, fd );
4522 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4523 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
4527 release_sock_fd( s, fd );
4528 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4529 WSASetLastError( err );
4530 return SOCKET_ERROR;
4533 /***********************************************************************
4534 * socket (WS2_32.23)
4536 SOCKET WINAPI WS_socket(int af, int type, int protocol)
4538 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
4540 return WSASocketA( af, type, protocol, NULL, 0,
4541 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
4545 /***********************************************************************
4546 * gethostbyaddr (WS2_32.51)
4548 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
4550 struct WS_hostent *retval = NULL;
4551 struct hostent* host;
4553 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4556 struct hostent hostentry;
4559 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4561 int res = gethostbyaddr_r(addr, len, type,
4562 &hostentry, extrabuf, ebufsize, &host, &locerr);
4563 if( res != ERANGE) break;
4565 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4567 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4569 EnterCriticalSection( &csWSgetXXXbyYYY );
4570 host = gethostbyaddr(addr, len, type);
4571 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4573 if( host != NULL ) retval = WS_dup_he(host);
4574 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4575 HeapFree(GetProcessHeap(),0,extrabuf);
4577 LeaveCriticalSection( &csWSgetXXXbyYYY );
4579 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
4583 /***********************************************************************
4584 * WS_get_local_ips (INTERNAL)
4586 * Returns the list of local IP addresses by going through the network
4587 * adapters and using the local routing table to sort the addresses
4588 * from highest routing priority to lowest routing priority. This
4589 * functionality is inferred from the description for obtaining local
4590 * IP addresses given in the Knowledge Base Article Q160215.
4592 * Please note that the returned hostent is only freed when the thread
4593 * closes and is replaced if another hostent is requested.
4595 static struct WS_hostent* WS_get_local_ips( char *hostname )
4597 int last_metric, numroutes = 0, i, j;
4598 PIP_ADAPTER_INFO adapters = NULL, k;
4599 struct WS_hostent *hostlist = NULL;
4600 PMIB_IPFORWARDTABLE routes = NULL;
4601 struct route *route_addrs = NULL;
4602 DWORD adap_size, route_size;
4604 /* Obtain the size of the adapter list and routing table, also allocate memory */
4605 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
4607 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4609 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
4610 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
4611 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
4612 if (adapters == NULL || routes == NULL || route_addrs == NULL)
4614 /* Obtain the adapter list and the full routing table */
4615 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
4617 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
4619 /* Store the interface associated with each route */
4620 for (i = 0; i < routes->dwNumEntries; i++)
4623 DWORD ifmetric, exists = FALSE;
4625 if (routes->table[i].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
4627 ifindex = routes->table[i].dwForwardIfIndex;
4628 ifmetric = routes->table[i].dwForwardMetric1;
4629 /* Only store the lowest valued metric for an interface */
4630 for (j = 0; j < numroutes; j++)
4632 if (route_addrs[j].interface == ifindex)
4634 if (route_addrs[j].metric > ifmetric)
4635 route_addrs[j].metric = ifmetric;
4641 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
4642 if (route_addrs == NULL)
4643 goto cleanup; /* Memory allocation error, fail gracefully */
4644 route_addrs[numroutes].interface = ifindex;
4645 route_addrs[numroutes].metric = ifmetric;
4646 /* If no IP is found in the next step (for whatever reason)
4647 * then fall back to the magic loopback address.
4649 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
4653 goto cleanup; /* No routes, fall back to the Magic IP */
4654 /* Find the IP address associated with each found interface */
4655 for (i = 0; i < numroutes; i++)
4657 for (k = adapters; k != NULL; k = k->Next)
4659 char *ip = k->IpAddressList.IpAddress.String;
4661 if (route_addrs[i].interface == k->Index)
4662 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
4665 /* Allocate a hostent and enough memory for all the IPs,
4666 * including the NULL at the end of the list.
4668 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
4669 if (hostlist == NULL)
4670 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
4671 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
4672 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
4673 hostlist->h_addrtype = AF_INET;
4674 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
4675 /* Reorder the entries when placing them in the host list, Windows expects
4676 * the IP list in order from highest priority to lowest (the critical thing
4677 * is that most applications expect the first IP to be the default route).
4680 for (i = 0; i < numroutes; i++)
4682 struct in_addr addr;
4683 int metric = 0xFFFF;
4685 memcpy(&addr, magic_loopback_addr, 4);
4686 for (j = 0; j < numroutes; j++)
4688 int this_metric = route_addrs[j].metric;
4690 if (this_metric > last_metric && this_metric < metric)
4692 addr = route_addrs[j].addr;
4693 metric = this_metric;
4696 last_metric = metric;
4697 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
4700 /* Cleanup all allocated memory except the address list,
4701 * the address list is used by the calling app.
4704 HeapFree(GetProcessHeap(), 0, route_addrs);
4705 HeapFree(GetProcessHeap(), 0, adapters);
4706 HeapFree(GetProcessHeap(), 0, routes);
4710 /***********************************************************************
4711 * gethostbyname (WS2_32.52)
4713 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
4715 struct WS_hostent *retval = NULL;
4716 struct hostent* host;
4717 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4720 struct hostent hostentry;
4721 int locerr = ENOBUFS;
4725 SetLastError(WSANOTINITIALISED);
4728 if( gethostname( hostname, 100) == -1) {
4729 SetLastError( WSAENOBUFS); /* appropriate ? */
4732 if( !name || !name[0]) {
4735 /* If the hostname of the local machine is requested then return the
4736 * complete list of local IP addresses */
4737 if(strcmp(name, hostname) == 0)
4738 retval = WS_get_local_ips(hostname);
4739 /* If any other hostname was requested (or the routing table lookup failed)
4740 * then return the IP found by the host OS */
4743 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4745 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4747 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
4748 if( res != ERANGE) break;
4750 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4752 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4754 EnterCriticalSection( &csWSgetXXXbyYYY );
4755 host = gethostbyname(name);
4756 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4758 if (host) retval = WS_dup_he(host);
4759 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4760 HeapFree(GetProcessHeap(),0,extrabuf);
4762 LeaveCriticalSection( &csWSgetXXXbyYYY );
4765 if (retval && retval->h_addr_list[0][0] == 127 &&
4766 strcmp(name, "localhost") != 0)
4768 /* hostname != "localhost" but has loopback address. replace by our
4769 * special address.*/
4770 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
4772 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4777 /***********************************************************************
4778 * getprotobyname (WS2_32.53)
4780 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
4782 struct WS_protoent* retval = NULL;
4783 #ifdef HAVE_GETPROTOBYNAME
4784 struct protoent* proto;
4785 EnterCriticalSection( &csWSgetXXXbyYYY );
4786 if( (proto = getprotobyname(name)) != NULL )
4788 retval = WS_dup_pe(proto);
4791 MESSAGE("protocol %s not found; You might want to add "
4792 "this to /etc/protocols\n", debugstr_a(name) );
4793 SetLastError(WSANO_DATA);
4795 LeaveCriticalSection( &csWSgetXXXbyYYY );
4797 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4802 /***********************************************************************
4803 * getprotobynumber (WS2_32.54)
4805 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
4807 struct WS_protoent* retval = NULL;
4808 #ifdef HAVE_GETPROTOBYNUMBER
4809 struct protoent* proto;
4810 EnterCriticalSection( &csWSgetXXXbyYYY );
4811 if( (proto = getprotobynumber(number)) != NULL )
4813 retval = WS_dup_pe(proto);
4816 MESSAGE("protocol number %d not found; You might want to add "
4817 "this to /etc/protocols\n", number );
4818 SetLastError(WSANO_DATA);
4820 LeaveCriticalSection( &csWSgetXXXbyYYY );
4822 TRACE("%i ret %p\n", number, retval);
4827 /***********************************************************************
4828 * getservbyname (WS2_32.55)
4830 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
4832 struct WS_servent* retval = NULL;
4833 struct servent* serv;
4835 char *proto_str = NULL;
4837 if (!(name_str = strdup_lower(name))) return NULL;
4839 if (proto && *proto)
4841 if (!(proto_str = strdup_lower(proto)))
4843 HeapFree( GetProcessHeap(), 0, name_str );
4848 EnterCriticalSection( &csWSgetXXXbyYYY );
4849 serv = getservbyname(name_str, proto_str);
4852 retval = WS_dup_se(serv);
4854 else SetLastError(WSANO_DATA);
4855 LeaveCriticalSection( &csWSgetXXXbyYYY );
4856 HeapFree( GetProcessHeap(), 0, proto_str );
4857 HeapFree( GetProcessHeap(), 0, name_str );
4858 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
4862 /***********************************************************************
4863 * freeaddrinfo (WS2_32.@)
4865 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
4868 struct WS_addrinfo *next;
4870 HeapFree(GetProcessHeap(),0,res->ai_canonname);
4871 HeapFree(GetProcessHeap(),0,res->ai_addr);
4872 next = res->ai_next;
4873 HeapFree(GetProcessHeap(),0,res);
4878 /* helper functions for getaddrinfo()/getnameinfo() */
4879 static int convert_aiflag_w2u(int winflags) {
4883 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4884 if (ws_aiflag_map[i][0] & winflags) {
4885 unixflags |= ws_aiflag_map[i][1];
4886 winflags &= ~ws_aiflag_map[i][0];
4889 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
4893 static int convert_niflag_w2u(int winflags) {
4897 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
4898 if (ws_niflag_map[i][0] & winflags) {
4899 unixflags |= ws_niflag_map[i][1];
4900 winflags &= ~ws_niflag_map[i][0];
4903 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
4907 static int convert_aiflag_u2w(int unixflags) {
4911 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4912 if (ws_aiflag_map[i][1] & unixflags) {
4913 winflags |= ws_aiflag_map[i][0];
4914 unixflags &= ~ws_aiflag_map[i][1];
4916 if (unixflags) /* will warn usually */
4917 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
4921 static int convert_eai_u2w(int unixret) {
4924 for (i=0;ws_eai_map[i][0];i++)
4925 if (ws_eai_map[i][1] == unixret)
4926 return ws_eai_map[i][0];
4930 static char *get_hostname(void)
4935 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
4936 if (GetLastError() != ERROR_MORE_DATA) return NULL;
4937 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
4938 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
4940 HeapFree( GetProcessHeap(), 0, ret );
4946 /***********************************************************************
4947 * getaddrinfo (WS2_32.@)
4949 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
4951 #ifdef HAVE_GETADDRINFO
4952 struct addrinfo *unixaires = NULL;
4954 struct addrinfo unixhints, *punixhints = NULL;
4955 char *hostname = NULL;
4958 if (!nodename && !servname) return WSAHOST_NOT_FOUND;
4962 else if (!nodename[0])
4964 node = hostname = get_hostname();
4965 if (!node) return WSA_NOT_ENOUGH_MEMORY;
4971 punixhints = &unixhints;
4973 memset(&unixhints, 0, sizeof(unixhints));
4974 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
4975 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
4976 punixhints->ai_family = 0;
4978 punixhints->ai_family = convert_af_w2u(hints->ai_family);
4979 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
4980 punixhints->ai_socktype = 0;
4982 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
4983 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
4984 punixhints->ai_protocol = 0;
4986 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
4989 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
4990 result = getaddrinfo(node, servname, punixhints, &unixaires);
4992 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
4993 HeapFree(GetProcessHeap(), 0, hostname);
4996 struct addrinfo *xuai = unixaires;
4997 struct WS_addrinfo **xai = res;
5001 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
5007 *xai = ai;xai = &ai->ai_next;
5008 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
5009 ai->ai_family = convert_af_u2w(xuai->ai_family);
5010 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
5011 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
5012 if (xuai->ai_canonname) {
5013 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
5014 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
5015 if (!ai->ai_canonname)
5017 strcpy(ai->ai_canonname,xuai->ai_canonname);
5019 len = xuai->ai_addrlen;
5020 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
5023 ai->ai_addrlen = len;
5025 int winlen = ai->ai_addrlen;
5027 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
5028 ai->ai_addrlen = winlen;
5032 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
5035 ai->ai_addrlen = len;
5037 xuai = xuai->ai_next;
5039 freeaddrinfo(unixaires);
5041 result = convert_eai_u2w(result);
5047 if (*res) WS_freeaddrinfo(*res);
5048 if (unixaires) freeaddrinfo(unixaires);
5050 return WSA_NOT_ENOUGH_MEMORY;
5052 FIXME("getaddrinfo() failed, not found during buildtime.\n");
5057 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
5059 struct WS_addrinfoW *ret;
5061 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
5062 ret->ai_flags = ai->ai_flags;
5063 ret->ai_family = ai->ai_family;
5064 ret->ai_socktype = ai->ai_socktype;
5065 ret->ai_protocol = ai->ai_protocol;
5066 ret->ai_addrlen = ai->ai_addrlen;
5067 ret->ai_canonname = NULL;
5068 ret->ai_addr = NULL;
5069 ret->ai_next = NULL;
5070 if (ai->ai_canonname)
5072 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
5073 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5075 HeapFree(GetProcessHeap(), 0, ret);
5078 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
5082 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5084 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5085 HeapFree(GetProcessHeap(), 0, ret);
5088 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5093 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
5095 struct WS_addrinfoW *ret, *infoW;
5097 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
5098 while (info->ai_next)
5100 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
5105 infoW = infoW->ai_next;
5106 info = info->ai_next;
5111 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
5113 struct WS_addrinfo *ret;
5115 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
5116 ret->ai_flags = ai->ai_flags;
5117 ret->ai_family = ai->ai_family;
5118 ret->ai_socktype = ai->ai_socktype;
5119 ret->ai_protocol = ai->ai_protocol;
5120 ret->ai_addrlen = ai->ai_addrlen;
5121 ret->ai_canonname = NULL;
5122 ret->ai_addr = NULL;
5123 ret->ai_next = NULL;
5124 if (ai->ai_canonname)
5126 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
5127 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5129 HeapFree(GetProcessHeap(), 0, ret);
5132 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
5136 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5138 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5139 HeapFree(GetProcessHeap(), 0, ret);
5142 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5147 /***********************************************************************
5148 * GetAddrInfoW (WS2_32.@)
5150 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
5153 char *nodenameA = NULL, *servnameA = NULL;
5154 struct WS_addrinfo *resA, *hintsA = NULL;
5158 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
5159 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
5160 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
5164 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
5165 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
5167 HeapFree(GetProcessHeap(), 0, nodenameA);
5170 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
5173 if (hints) hintsA = addrinfo_WtoA(hints);
5174 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
5175 WS_freeaddrinfo(hintsA);
5179 *res = addrinfo_list_AtoW(resA);
5180 WS_freeaddrinfo(resA);
5183 HeapFree(GetProcessHeap(), 0, nodenameA);
5184 HeapFree(GetProcessHeap(), 0, servnameA);
5188 /***********************************************************************
5189 * FreeAddrInfoW (WS2_32.@)
5191 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
5196 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
5197 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
5199 HeapFree(GetProcessHeap(), 0, ai);
5204 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
5205 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
5207 #ifdef HAVE_GETNAMEINFO
5209 union generic_unix_sockaddr sa_u;
5212 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
5213 serv, servlen, flags);
5215 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
5218 WSASetLastError(WSAEFAULT);
5219 return WSA_NOT_ENOUGH_MEMORY;
5221 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
5222 return convert_eai_u2w(ret);
5224 FIXME("getnameinfo() failed, not found during buildtime.\n");
5229 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
5230 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
5233 char *hostA = NULL, *servA = NULL;
5235 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
5236 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
5238 HeapFree(GetProcessHeap(), 0, hostA);
5242 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
5245 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
5246 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
5249 HeapFree(GetProcessHeap(), 0, hostA);
5250 HeapFree(GetProcessHeap(), 0, servA);
5254 /***********************************************************************
5255 * getservbyport (WS2_32.56)
5257 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
5259 struct WS_servent* retval = NULL;
5260 #ifdef HAVE_GETSERVBYPORT
5261 struct servent* serv;
5262 char *proto_str = NULL;
5264 if (proto && *proto)
5266 if (!(proto_str = strdup_lower(proto))) return NULL;
5268 EnterCriticalSection( &csWSgetXXXbyYYY );
5269 if( (serv = getservbyport(port, proto_str)) != NULL ) {
5270 retval = WS_dup_se(serv);
5272 else SetLastError(WSANO_DATA);
5273 LeaveCriticalSection( &csWSgetXXXbyYYY );
5274 HeapFree( GetProcessHeap(), 0, proto_str );
5276 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
5281 /***********************************************************************
5282 * gethostname (WS2_32.57)
5284 int WINAPI WS_gethostname(char *name, int namelen)
5286 TRACE("name %p, len %d\n", name, namelen);
5288 if (gethostname(name, namelen) == 0)
5290 TRACE("<- '%s'\n", name);
5293 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
5294 TRACE("<- ERROR !\n");
5295 return SOCKET_ERROR;
5299 /* ------------------------------------- Windows sockets extensions -- *
5301 * ------------------------------------------------------------------- */
5303 /***********************************************************************
5304 * WSAEnumNetworkEvents (WS2_32.36)
5306 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
5310 int errors[FD_MAX_EVENTS];
5312 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
5314 SERVER_START_REQ( get_socket_event )
5316 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5317 req->service = TRUE;
5318 req->c_event = wine_server_obj_handle( hEvent );
5319 wine_server_set_reply( req, errors, sizeof(errors) );
5320 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
5325 for (i = 0; i < FD_MAX_EVENTS; i++)
5326 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
5329 SetLastError(WSAEINVAL);
5330 return SOCKET_ERROR;
5333 /***********************************************************************
5334 * WSAEventSelect (WS2_32.39)
5336 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
5340 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
5342 SERVER_START_REQ( set_socket_event )
5344 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5346 req->event = wine_server_obj_handle( hEvent );
5349 ret = wine_server_call( req );
5353 SetLastError(WSAEINVAL);
5354 return SOCKET_ERROR;
5357 /**********************************************************************
5358 * WSAGetOverlappedResult (WS2_32.40)
5360 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
5361 LPDWORD lpcbTransfer, BOOL fWait,
5366 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
5367 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
5369 if ( lpOverlapped == NULL )
5371 ERR( "Invalid pointer\n" );
5372 WSASetLastError(WSA_INVALID_PARAMETER);
5376 status = lpOverlapped->Internal;
5377 if (status == STATUS_PENDING)
5381 SetLastError( WSA_IO_INCOMPLETE );
5385 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
5386 INFINITE ) == WAIT_FAILED)
5388 status = lpOverlapped->Internal;
5392 *lpcbTransfer = lpOverlapped->InternalHigh;
5395 *lpdwFlags = lpOverlapped->u.s.Offset;
5397 if (status) SetLastError( RtlNtStatusToDosError(status) );
5402 /***********************************************************************
5403 * WSAAsyncSelect (WS2_32.101)
5405 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
5409 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
5411 SERVER_START_REQ( set_socket_event )
5413 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5416 req->window = wine_server_user_handle( hWnd );
5418 ret = wine_server_call( req );
5422 SetLastError(WSAEINVAL);
5423 return SOCKET_ERROR;
5426 /***********************************************************************
5427 * WSACreateEvent (WS2_32.31)
5430 WSAEVENT WINAPI WSACreateEvent(void)
5432 /* Create a manual-reset event, with initial state: unsignaled */
5435 return CreateEventW(NULL, TRUE, FALSE, NULL);
5438 /***********************************************************************
5439 * WSACloseEvent (WS2_32.29)
5442 BOOL WINAPI WSACloseEvent(WSAEVENT event)
5444 TRACE ("event=%p\n", event);
5446 return CloseHandle(event);
5449 /***********************************************************************
5450 * WSASocketA (WS2_32.78)
5453 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
5454 LPWSAPROTOCOL_INFOA lpProtocolInfo,
5455 GROUP g, DWORD dwFlags)
5458 WSAPROTOCOL_INFOW info;
5460 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5461 af, type, protocol, lpProtocolInfo, g, dwFlags);
5463 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
5465 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
5466 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5467 info.szProtocol, WSAPROTOCOL_LEN + 1);
5471 WSASetLastError( WSAEINVAL);
5472 return SOCKET_ERROR;
5475 return WSASocketW(af, type, protocol, &info, g, dwFlags);
5478 /***********************************************************************
5479 * WSASocketW (WS2_32.79)
5482 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
5483 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5484 GROUP g, DWORD dwFlags)
5489 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
5490 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
5493 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5494 af, type, protocol, lpProtocolInfo, g, dwFlags );
5496 /* hack for WSADuplicateSocket */
5497 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
5498 ret = lpProtocolInfo->dwCatalogEntryId;
5499 TRACE("\tgot duplicate %04lx\n", ret);
5503 /* convert the socket family and type */
5504 af = convert_af_w2u(af);
5505 type = convert_socktype_w2u(type);
5509 if (af == FROM_PROTOCOL_INFO)
5510 af = lpProtocolInfo->iAddressFamily;
5511 if (type == FROM_PROTOCOL_INFO)
5512 type = lpProtocolInfo->iSocketType;
5513 if (protocol == FROM_PROTOCOL_INFO)
5514 protocol = lpProtocolInfo->iProtocol;
5517 if ( af == AF_UNSPEC) /* did they not specify the address family? */
5519 if ((protocol == IPPROTO_TCP && type == SOCK_STREAM) ||
5520 (protocol == IPPROTO_UDP && type == SOCK_DGRAM))
5526 SetLastError(WSAEPROTOTYPE);
5527 return INVALID_SOCKET;
5531 SERVER_START_REQ( create_socket )
5535 req->protocol = protocol;
5536 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
5537 req->attributes = OBJ_INHERIT;
5538 req->flags = dwFlags;
5539 set_error( wine_server_call( req ) );
5540 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
5545 TRACE("\tcreated %04lx\n", ret );
5549 if (GetLastError() == WSAEACCES) /* raw socket denied */
5551 if (type == SOCK_RAW)
5552 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
5554 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
5555 SetLastError(WSAESOCKTNOSUPPORT);
5558 WARN("\t\tfailed!\n");
5559 return INVALID_SOCKET;
5562 /***********************************************************************
5563 * WSAJoinLeaf (WS2_32.58)
5566 SOCKET WINAPI WSAJoinLeaf(
5568 const struct WS_sockaddr *addr,
5570 LPWSABUF lpCallerData,
5571 LPWSABUF lpCalleeData,
5577 return INVALID_SOCKET;
5580 /***********************************************************************
5581 * __WSAFDIsSet (WS2_32.151)
5583 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
5585 int i = set->fd_count;
5587 TRACE("(%ld,%p(%i))\n", s, set, i);
5590 if (set->fd_array[i] == s) return 1;
5594 /***********************************************************************
5595 * WSAIsBlocking (WS2_32.114)
5597 BOOL WINAPI WSAIsBlocking(void)
5599 /* By default WinSock should set all its sockets to non-blocking mode
5600 * and poll in PeekMessage loop when processing "blocking" ones. This
5601 * function is supposed to tell if the program is in this loop. Our
5602 * blocking calls are truly blocking so we always return FALSE.
5604 * Note: It is allowed to call this function without prior WSAStartup().
5611 /***********************************************************************
5612 * WSACancelBlockingCall (WS2_32.113)
5614 INT WINAPI WSACancelBlockingCall(void)
5620 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
5622 FIXME("How was this called?\n");
5627 /***********************************************************************
5628 * WSASetBlockingHook (WS2_32.109)
5630 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
5632 FARPROC prev = blocking_hook;
5633 blocking_hook = lpBlockFunc;
5634 TRACE("hook %p\n", lpBlockFunc);
5639 /***********************************************************************
5640 * WSAUnhookBlockingHook (WS2_32.110)
5642 INT WINAPI WSAUnhookBlockingHook(void)
5644 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
5649 /* ----------------------------------- end of API stuff */
5651 /* ----------------------------------- helper functions -
5653 * TODO: Merge WS_dup_..() stuff into one function that
5654 * would operate with a generic structure containing internal
5655 * pointers (via a template of some kind).
5658 static int list_size(char** l, int item_size)
5663 j += (item_size) ? item_size : strlen(l[i]) + 1;
5664 j += (i + 1) * sizeof(char*); }
5668 static int list_dup(char** l_src, char** l_to, int item_size)
5673 for (i = 0; l_src[i]; i++) ;
5674 p = (char *)(l_to + i + 1);
5675 for (i = 0; l_src[i]; i++)
5677 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
5678 memcpy(p, l_src[i], count);
5683 return p - (char *)l_to;
5688 /* create a hostent entry
5690 * Creates the entry with enough memory for the name, aliases
5691 * addresses, and the address pointers. Also copies the name
5692 * and sets up all the pointers.
5694 * NOTE: The alias and address lists must be allocated with room
5695 * for the NULL item terminating the list. This is true even if
5696 * the list has no items ("aliases" and "addresses" must be
5697 * at least "1", a truly empty list is invalid).
5699 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
5701 struct WS_hostent *p_to;
5703 int size = (sizeof(struct WS_hostent) +
5705 sizeof(char *) * aliases +
5707 sizeof(char *) * addresses +
5708 address_length * (addresses - 1)), i;
5710 if (!(p_to = check_buffer_he(size))) return NULL;
5711 memset(p_to, 0, size);
5713 /* Use the memory in the same way winsock does.
5714 * First set the pointer for aliases, second set the pointers for addresses.
5715 * Third fill the addresses indexes, fourth jump aliases names size.
5716 * Fifth fill the hostname.
5717 * NOTE: This method is valid for OS version's >= XP.
5719 p = (char *)(p_to + 1);
5720 p_to->h_aliases = (char **)p;
5721 p += sizeof(char *)*aliases;
5723 p_to->h_addr_list = (char **)p;
5724 p += sizeof(char *)*addresses;
5726 for (i = 0, addresses--; i < addresses; i++, p += address_length)
5727 p_to->h_addr_list[i] = p;
5729 /* NOTE: h_aliases must be filled in manually because we don't know each string
5730 * size, leave these pointers NULL (already set to NULL by memset earlier).
5740 /* duplicate hostent entry
5741 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
5742 * Ditto for protoent and servent.
5744 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
5746 int i, addresses = 0, alias_size = 0;
5747 struct WS_hostent *p_to;
5750 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
5751 while (p_he->h_addr_list[addresses]) addresses++;
5753 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
5755 if (!p_to) return NULL;
5756 p_to->h_addrtype = p_he->h_addrtype;
5757 p_to->h_length = p_he->h_length;
5759 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
5760 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
5762 /* Fill the aliases after the IP data */
5763 for(i = 0; p_he->h_aliases[i]; i++)
5765 p_to->h_aliases[i] = p;
5766 strcpy(p, p_he->h_aliases[i]);
5773 /* ----- protoent */
5775 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
5778 struct WS_protoent *p_to;
5780 int size = (sizeof(*p_pe) +
5781 strlen(p_pe->p_name) + 1 +
5782 list_size(p_pe->p_aliases, 0));
5784 if (!(p_to = check_buffer_pe(size))) return NULL;
5785 p_to->p_proto = p_pe->p_proto;
5787 p = (char *)(p_to + 1);
5789 strcpy(p, p_pe->p_name);
5792 p_to->p_aliases = (char **)p;
5793 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
5799 static struct WS_servent *WS_dup_se(const struct servent* p_se)
5802 struct WS_servent *p_to;
5804 int size = (sizeof(*p_se) +
5805 strlen(p_se->s_proto) + 1 +
5806 strlen(p_se->s_name) + 1 +
5807 list_size(p_se->s_aliases, 0));
5809 if (!(p_to = check_buffer_se(size))) return NULL;
5810 p_to->s_port = p_se->s_port;
5812 p = (char *)(p_to + 1);
5814 strcpy(p, p_se->s_name);
5818 strcpy(p, p_se->s_proto);
5821 p_to->s_aliases = (char **)p;
5822 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
5827 /***********************************************************************
5828 * WSARecv (WS2_32.67)
5830 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5831 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
5832 LPWSAOVERLAPPED lpOverlapped,
5833 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
5835 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
5836 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
5839 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5840 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
5841 struct WS_sockaddr *lpFrom,
5842 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
5843 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
5844 LPWSABUF lpControlBuffer )
5846 unsigned int i, options;
5848 struct ws2_async *wsa;
5849 DWORD timeout_start = GetTickCount();
5850 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5852 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
5853 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
5854 (lpFromlen ? *lpFromlen : -1),
5855 lpOverlapped, lpCompletionRoutine);
5857 fd = get_sock_fd( s, FILE_READ_DATA, &options );
5858 TRACE( "fd=%d, options=%x\n", fd, options );
5860 if (fd == -1) return SOCKET_ERROR;
5862 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
5868 wsa->hSocket = SOCKET2HANDLE(s);
5869 wsa->flags = *lpFlags;
5870 wsa->lpFlags = lpFlags;
5872 wsa->addrlen.ptr = lpFromlen;
5873 wsa->control = lpControlBuffer;
5874 wsa->n_iovecs = dwBufferCount;
5875 wsa->first_iovec = 0;
5876 for (i = 0; i < dwBufferCount; i++)
5878 /* check buffer first to trigger write watches */
5879 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
5884 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5885 wsa->iovec[i].iov_len = lpBuffers[i].len;
5890 n = WS2_recv( fd, wsa );
5893 if (errno == EINTR) continue;
5894 if (errno != EAGAIN)
5896 int loc_errno = errno;
5898 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
5902 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
5904 if ((lpOverlapped || lpCompletionRoutine) &&
5905 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5907 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5909 wsa->user_overlapped = lpOverlapped;
5910 wsa->completion_func = lpCompletionRoutine;
5911 release_sock_fd( s, fd );
5915 iosb->u.Status = STATUS_PENDING;
5916 iosb->Information = 0;
5918 SERVER_START_REQ( register_async )
5920 req->type = ASYNC_TYPE_READ;
5921 req->async.handle = wine_server_obj_handle( wsa->hSocket );
5922 req->async.callback = wine_server_client_ptr( WS2_async_recv );
5923 req->async.iosb = wine_server_client_ptr( iosb );
5924 req->async.arg = wine_server_client_ptr( wsa );
5925 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
5926 req->async.cvalue = cvalue;
5927 err = wine_server_call( req );
5931 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5932 WSASetLastError( NtStatusToWSAError( err ));
5933 return SOCKET_ERROR;
5936 iosb->u.Status = STATUS_SUCCESS;
5937 iosb->Information = n;
5938 if (!wsa->completion_func)
5940 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5941 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5942 HeapFree( GetProcessHeap(), 0, wsa );
5944 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5945 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5946 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5952 if ( _is_blocking(s) )
5955 int timeout = GET_RCVTIMEO(fd);
5958 timeout -= GetTickCount() - timeout_start;
5959 if (timeout < 0) timeout = 0;
5963 pfd.events = POLLIN;
5964 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
5966 if (!timeout || !poll( &pfd, 1, timeout ))
5969 /* a timeout is not fatal */
5970 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5976 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5977 err = WSAEWOULDBLOCK;
5982 TRACE(" -> %i bytes\n", n);
5983 HeapFree( GetProcessHeap(), 0, wsa );
5984 release_sock_fd( s, fd );
5985 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5990 HeapFree( GetProcessHeap(), 0, wsa );
5991 release_sock_fd( s, fd );
5992 WARN(" -> ERROR %d\n", err);
5993 WSASetLastError( err );
5994 return SOCKET_ERROR;
5997 /***********************************************************************
5998 * WSARecvFrom (WS2_32.69)
6000 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6001 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
6002 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6003 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
6006 return WS2_recv_base( s, lpBuffers, dwBufferCount,
6007 lpNumberOfBytesRecvd, lpFlags,
6009 lpOverlapped, lpCompletionRoutine, NULL );
6012 /***********************************************************************
6013 * WSCInstallProvider (WS2_32.88)
6015 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
6016 LPCWSTR lpszProviderDllPath,
6017 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
6018 DWORD dwNumberOfEntries,
6021 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
6022 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
6023 dwNumberOfEntries, lpErrno);
6029 /***********************************************************************
6030 * WSCDeinstallProvider (WS2_32.83)
6032 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
6034 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
6040 /***********************************************************************
6041 * WSAAccept (WS2_32.26)
6043 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
6044 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
6047 int ret = 0, size = 0;
6048 WSABUF CallerId, CallerData, CalleeId, CalleeData;
6049 /* QOS SQOS, GQOS; */
6052 SOCKADDR src_addr, dst_addr;
6054 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
6055 s, addr, addrlen, lpfnCondition, dwCallbackData);
6058 size = sizeof(src_addr);
6059 cs = WS_accept(s, &src_addr, &size);
6061 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
6063 if (!lpfnCondition) return cs;
6065 CallerId.buf = (char *)&src_addr;
6066 CallerId.len = sizeof(src_addr);
6068 CallerData.buf = NULL;
6071 WS_getsockname(cs, &dst_addr, &size);
6073 CalleeId.buf = (char *)&dst_addr;
6074 CalleeId.len = sizeof(dst_addr);
6077 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
6078 &CalleeId, &CalleeData, &g, dwCallbackData);
6083 if (addr && addrlen)
6084 memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
6087 SERVER_START_REQ( set_socket_deferred )
6089 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6090 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
6091 if ( !wine_server_call_err ( req ) )
6093 SetLastError( WSATRY_AGAIN );
6094 WS_closesocket( cs );
6098 return SOCKET_ERROR;
6101 SetLastError(WSAECONNREFUSED);
6102 return SOCKET_ERROR;
6104 FIXME("Unknown return type from Condition function\n");
6105 SetLastError(WSAENOTSOCK);
6106 return SOCKET_ERROR;
6110 /***********************************************************************
6111 * WSADuplicateSocketA (WS2_32.32)
6113 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
6117 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
6118 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
6119 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
6120 /* I don't know what the real Windoze does next, this is a hack */
6121 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
6122 * the target use the global duplicate, or we could copy a reference to us to the structure
6123 * and let the target duplicate it from us, but let's do it as simple as possible */
6124 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
6125 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
6126 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
6127 0, FALSE, DUPLICATE_SAME_ACCESS);
6128 CloseHandle(hProcess);
6129 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
6133 /***********************************************************************
6134 * WSADuplicateSocketW (WS2_32.33)
6136 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
6140 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
6142 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
6143 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
6144 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
6145 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
6146 0, FALSE, DUPLICATE_SAME_ACCESS);
6147 CloseHandle(hProcess);
6148 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
6152 /***********************************************************************
6153 * WSAInstallServiceClassA (WS2_32.48)
6155 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
6157 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
6158 WSASetLastError(WSAEACCES);
6159 return SOCKET_ERROR;
6162 /***********************************************************************
6163 * WSAInstallServiceClassW (WS2_32.49)
6165 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
6167 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
6168 WSASetLastError(WSAEACCES);
6169 return SOCKET_ERROR;
6172 /***********************************************************************
6173 * WSARemoveServiceClass (WS2_32.70)
6175 int WINAPI WSARemoveServiceClass(LPGUID info)
6177 FIXME("Request to remove service %p\n",info);
6178 WSASetLastError(WSATYPE_NOT_FOUND);
6179 return SOCKET_ERROR;
6182 /***********************************************************************
6183 * inet_ntop (WS2_32.@)
6185 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
6187 #ifdef HAVE_INET_NTOP
6188 struct WS_in6_addr *in6;
6189 struct WS_in_addr *in;
6192 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
6195 WSASetLastError( STATUS_INVALID_PARAMETER );
6204 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
6210 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
6214 WSASetLastError( WSAEAFNOSUPPORT );
6218 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
6221 FIXME( "not supported on this platform\n" );
6222 WSASetLastError( WSAEAFNOSUPPORT );
6227 /***********************************************************************
6228 * WSAStringToAddressA (WS2_32.80)
6230 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
6232 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6233 LPSOCKADDR lpAddress,
6234 LPINT lpAddressLength)
6237 LPSTR workBuffer=NULL,ptrPort;
6239 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
6240 lpProtocolInfo, lpAddress, lpAddressLength );
6242 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6246 WSASetLastError(WSAEINVAL);
6247 return SOCKET_ERROR;
6251 FIXME("ProtocolInfo not implemented.\n");
6253 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
6254 strlen(AddressString) + 1);
6257 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6258 return SOCKET_ERROR;
6261 strcpy(workBuffer, AddressString);
6263 switch(AddressFamily)
6267 struct in_addr inetaddr;
6269 /* If lpAddressLength is too small, tell caller the size we need */
6270 if (*lpAddressLength < sizeof(SOCKADDR_IN))
6272 *lpAddressLength = sizeof(SOCKADDR_IN);
6276 *lpAddressLength = sizeof(SOCKADDR_IN);
6277 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
6279 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
6281 ptrPort = strchr(workBuffer, ':');
6284 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
6289 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
6292 if(inet_aton(workBuffer, &inetaddr) > 0)
6294 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
6305 struct in6_addr inetaddr;
6306 /* If lpAddressLength is too small, tell caller the size we need */
6307 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
6309 *lpAddressLength = sizeof(SOCKADDR_IN6);
6313 #ifdef HAVE_INET_PTON
6314 *lpAddressLength = sizeof(SOCKADDR_IN6);
6315 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
6317 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
6319 /* This one is a bit tricky. An IPv6 address contains colons, so the
6320 * check from IPv4 doesn't work like that. However, IPv6 addresses that
6321 * contain a port are written with braces like [fd12:3456:7890::1]:12345
6322 * so what we will do is to look for ']', check if the next char is a
6323 * colon, and if it is, parse the port as in IPv4. */
6325 ptrPort = strchr(workBuffer, ']');
6326 if(ptrPort && *(++ptrPort) == ':')
6328 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
6333 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
6336 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
6338 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
6339 sizeof(struct in6_addr));
6343 #endif /* HAVE_INET_PTON */
6349 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
6350 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
6354 HeapFree(GetProcessHeap(), 0, workBuffer);
6357 WSASetLastError(res);
6358 return SOCKET_ERROR;
6361 /***********************************************************************
6362 * WSAStringToAddressW (WS2_32.81)
6364 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
6365 * If this should be the case, it would be required to map these digits
6366 * to Unicode digits (0-9) using FoldString first.
6368 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
6370 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6371 LPSOCKADDR lpAddress,
6372 LPINT lpAddressLength)
6375 LPSTR workBuffer=NULL;
6376 WSAPROTOCOL_INFOA infoA;
6377 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
6379 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
6380 lpAddress, lpAddressLength );
6382 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6384 /* if ProtocolInfo is available - convert to ANSI variant */
6387 lpProtoInfoA = &infoA;
6388 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
6390 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6391 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
6393 WSASetLastError( WSAEINVAL);
6394 return SOCKET_ERROR;
6400 /* Translate AddressString to ANSI code page - assumes that only
6401 standard digits 0-9 are used with this API call */
6402 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
6403 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
6407 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
6408 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
6409 lpAddress,lpAddressLength);
6410 HeapFree( GetProcessHeap(), 0, workBuffer );
6414 res = WSA_NOT_ENOUGH_MEMORY;
6419 WSASetLastError(res);
6420 return SOCKET_ERROR;
6423 /***********************************************************************
6424 * WSAAddressToStringA (WS2_32.27)
6426 * See WSAAddressToStringW
6428 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
6429 LPWSAPROTOCOL_INFOA info, LPSTR string,
6433 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6436 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6438 if (!sockaddr) return SOCKET_ERROR;
6439 if (!string || !lenstr) return SOCKET_ERROR;
6441 switch(sockaddr->sa_family)
6444 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
6445 sprintf( buffer, "%u.%u.%u.%u:%u",
6446 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
6447 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
6448 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
6449 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
6450 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
6452 p = strchr( buffer, ':' );
6453 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
6458 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
6461 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
6462 if ((sockaddr6->sin6_port))
6463 strcpy(buffer, "[");
6464 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
6466 WSASetLastError(WSAEINVAL);
6467 return SOCKET_ERROR;
6469 if ((sockaddr6->sin6_scope_id))
6470 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
6471 if ((sockaddr6->sin6_port))
6472 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
6477 WSASetLastError(WSAEINVAL);
6478 return SOCKET_ERROR;
6481 size = strlen( buffer ) + 1;
6486 WSASetLastError(WSAEFAULT);
6487 return SOCKET_ERROR;
6491 strcpy( string, buffer );
6495 /***********************************************************************
6496 * WSAAddressToStringW (WS2_32.28)
6498 * Convert a sockaddr address into a readable address string.
6501 * sockaddr [I] Pointer to a sockaddr structure.
6502 * len [I] Size of the sockaddr structure.
6503 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
6504 * string [I/O] Pointer to a buffer to receive the address string.
6505 * lenstr [I/O] Size of the receive buffer in WCHARs.
6509 * Failure: SOCKET_ERROR
6512 * The 'info' parameter is ignored.
6514 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
6515 LPWSAPROTOCOL_INFOW info, LPWSTR string,
6520 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6523 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6526 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
6528 if (ret) return ret;
6530 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
6535 WSASetLastError(WSAEFAULT);
6536 return SOCKET_ERROR;
6540 lstrcpyW( string, buffer );
6544 /***********************************************************************
6545 * WSAEnumNameSpaceProvidersA (WS2_32.34)
6547 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
6549 FIXME( "(%p %p) Stub!\n", len, buffer );
6553 /***********************************************************************
6554 * WSAEnumNameSpaceProvidersW (WS2_32.35)
6556 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
6558 FIXME( "(%p %p) Stub!\n", len, buffer );
6562 /***********************************************************************
6563 * WSAGetQOSByName (WS2_32.41)
6565 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
6567 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
6571 /***********************************************************************
6572 * WSAGetServiceClassInfoA (WS2_32.42)
6574 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
6575 LPWSASERVICECLASSINFOA info )
6577 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
6579 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6580 return SOCKET_ERROR;
6583 /***********************************************************************
6584 * WSAGetServiceClassInfoW (WS2_32.43)
6586 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
6587 LPWSASERVICECLASSINFOW info )
6589 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
6591 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6592 return SOCKET_ERROR;
6595 /***********************************************************************
6596 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
6598 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
6600 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6601 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6602 return SOCKET_ERROR;
6605 /***********************************************************************
6606 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
6608 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
6610 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6611 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6612 return SOCKET_ERROR;
6615 /***********************************************************************
6616 * WSALookupServiceBeginA (WS2_32.59)
6618 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
6619 DWORD dwControlFlags,
6622 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6624 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6625 return SOCKET_ERROR;
6628 /***********************************************************************
6629 * WSALookupServiceBeginW (WS2_32.60)
6631 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
6632 DWORD dwControlFlags,
6635 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6637 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6638 return SOCKET_ERROR;
6641 /***********************************************************************
6642 * WSALookupServiceEnd (WS2_32.61)
6644 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
6646 FIXME("(%p) Stub!\n", lookup );
6650 /***********************************************************************
6651 * WSALookupServiceNextA (WS2_32.62)
6653 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
6655 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6656 WSASetLastError(WSA_E_NO_MORE);
6657 return SOCKET_ERROR;
6660 /***********************************************************************
6661 * WSALookupServiceNextW (WS2_32.63)
6663 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
6665 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6666 WSASetLastError(WSA_E_NO_MORE);
6667 return SOCKET_ERROR;
6670 /***********************************************************************
6671 * WSANtohl (WS2_32.64)
6673 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
6675 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
6677 if (!lphostlong) return WSAEFAULT;
6679 *lphostlong = ntohl( netlong );
6683 /***********************************************************************
6684 * WSANtohs (WS2_32.65)
6686 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
6688 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
6690 if (!lphostshort) return WSAEFAULT;
6692 *lphostshort = ntohs( netshort );
6696 /***********************************************************************
6697 * WSAProviderConfigChange (WS2_32.66)
6699 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
6700 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
6702 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
6703 return SOCKET_ERROR;
6706 /***********************************************************************
6707 * WSARecvDisconnect (WS2_32.68)
6709 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
6711 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
6713 return WS_shutdown( s, 0 );
6716 /***********************************************************************
6717 * WSASetServiceA (WS2_32.76)
6719 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
6721 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6725 /***********************************************************************
6726 * WSASetServiceW (WS2_32.77)
6728 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
6730 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6734 /***********************************************************************
6735 * WSCEnableNSProvider (WS2_32.84)
6737 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
6739 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
6743 /***********************************************************************
6744 * WSCGetProviderPath (WS2_32.86)
6746 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
6748 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
6750 if (!errcode || !provider || !len) return WSAEFAULT;
6752 *errcode = WSAEINVAL;
6753 return SOCKET_ERROR;
6756 /***********************************************************************
6757 * WSCInstallNameSpace (WS2_32.87)
6759 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
6760 DWORD version, LPGUID provider )
6762 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
6763 namespace, version, debugstr_guid(provider) );
6767 /***********************************************************************
6768 * WSCUnInstallNameSpace (WS2_32.89)
6770 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
6772 FIXME("(%p) Stub!\n", lpProviderId);
6776 /***********************************************************************
6777 * WSCWriteProviderOrder (WS2_32.91)
6779 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
6781 FIXME("(%p 0x%08x) Stub!\n", entry, number);
6785 /***********************************************************************
6786 * WSANSPIoctl (WS2_32.91)
6788 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
6789 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
6790 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
6792 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
6793 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
6794 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6795 return SOCKET_ERROR;