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)
4456 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
4457 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
4459 SetLastError(wsaErrno());
4460 release_sock_fd( s, fd );
4461 return SOCKET_ERROR;
4464 release_sock_fd( s, fd );
4467 TRACE("Setting socket error, %d\n", wsaErrno());
4468 SetLastError(wsaErrno());
4469 release_sock_fd( s, fd );
4471 return SOCKET_ERROR;
4474 /***********************************************************************
4475 * shutdown (WS2_32.22)
4477 int WINAPI WS_shutdown(SOCKET s, int how)
4479 int fd, err = WSAENOTSOCK;
4480 unsigned int options, clear_flags = 0;
4482 fd = get_sock_fd( s, 0, &options );
4483 TRACE("socket %04lx, how %i %x\n", s, how, options );
4486 return SOCKET_ERROR;
4490 case 0: /* drop receives */
4491 clear_flags |= FD_READ;
4493 case 1: /* drop sends */
4494 clear_flags |= FD_WRITE;
4496 case 2: /* drop all */
4497 clear_flags |= FD_READ|FD_WRITE;
4500 clear_flags |= FD_WINE_LISTENING;
4503 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4508 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4511 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4515 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4516 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4519 if (err) goto error;
4521 else /* non-overlapped mode */
4523 if ( shutdown( fd, how ) )
4530 release_sock_fd( s, fd );
4531 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4532 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
4536 release_sock_fd( s, fd );
4537 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4538 WSASetLastError( err );
4539 return SOCKET_ERROR;
4542 /***********************************************************************
4543 * socket (WS2_32.23)
4545 SOCKET WINAPI WS_socket(int af, int type, int protocol)
4547 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
4549 return WSASocketA( af, type, protocol, NULL, 0,
4550 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
4554 /***********************************************************************
4555 * gethostbyaddr (WS2_32.51)
4557 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
4559 struct WS_hostent *retval = NULL;
4560 struct hostent* host;
4562 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4565 struct hostent hostentry;
4568 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4570 int res = gethostbyaddr_r(addr, len, type,
4571 &hostentry, extrabuf, ebufsize, &host, &locerr);
4572 if( res != ERANGE) break;
4574 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4576 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4578 EnterCriticalSection( &csWSgetXXXbyYYY );
4579 host = gethostbyaddr(addr, len, type);
4580 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4582 if( host != NULL ) retval = WS_dup_he(host);
4583 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4584 HeapFree(GetProcessHeap(),0,extrabuf);
4586 LeaveCriticalSection( &csWSgetXXXbyYYY );
4588 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
4592 /***********************************************************************
4593 * WS_get_local_ips (INTERNAL)
4595 * Returns the list of local IP addresses by going through the network
4596 * adapters and using the local routing table to sort the addresses
4597 * from highest routing priority to lowest routing priority. This
4598 * functionality is inferred from the description for obtaining local
4599 * IP addresses given in the Knowledge Base Article Q160215.
4601 * Please note that the returned hostent is only freed when the thread
4602 * closes and is replaced if another hostent is requested.
4604 static struct WS_hostent* WS_get_local_ips( char *hostname )
4606 int last_metric, numroutes = 0, i, j;
4607 PIP_ADAPTER_INFO adapters = NULL, k;
4608 struct WS_hostent *hostlist = NULL;
4609 PMIB_IPFORWARDTABLE routes = NULL;
4610 struct route *route_addrs = NULL;
4611 DWORD adap_size, route_size;
4613 /* Obtain the size of the adapter list and routing table, also allocate memory */
4614 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
4616 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4618 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
4619 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
4620 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
4621 if (adapters == NULL || routes == NULL || route_addrs == NULL)
4623 /* Obtain the adapter list and the full routing table */
4624 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
4626 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
4628 /* Store the interface associated with each route */
4629 for (i = 0; i < routes->dwNumEntries; i++)
4632 DWORD ifmetric, exists = FALSE;
4634 if (routes->table[i].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
4636 ifindex = routes->table[i].dwForwardIfIndex;
4637 ifmetric = routes->table[i].dwForwardMetric1;
4638 /* Only store the lowest valued metric for an interface */
4639 for (j = 0; j < numroutes; j++)
4641 if (route_addrs[j].interface == ifindex)
4643 if (route_addrs[j].metric > ifmetric)
4644 route_addrs[j].metric = ifmetric;
4650 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
4651 if (route_addrs == NULL)
4652 goto cleanup; /* Memory allocation error, fail gracefully */
4653 route_addrs[numroutes].interface = ifindex;
4654 route_addrs[numroutes].metric = ifmetric;
4655 /* If no IP is found in the next step (for whatever reason)
4656 * then fall back to the magic loopback address.
4658 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
4662 goto cleanup; /* No routes, fall back to the Magic IP */
4663 /* Find the IP address associated with each found interface */
4664 for (i = 0; i < numroutes; i++)
4666 for (k = adapters; k != NULL; k = k->Next)
4668 char *ip = k->IpAddressList.IpAddress.String;
4670 if (route_addrs[i].interface == k->Index)
4671 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
4674 /* Allocate a hostent and enough memory for all the IPs,
4675 * including the NULL at the end of the list.
4677 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
4678 if (hostlist == NULL)
4679 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
4680 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
4681 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
4682 hostlist->h_addrtype = AF_INET;
4683 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
4684 /* Reorder the entries when placing them in the host list, Windows expects
4685 * the IP list in order from highest priority to lowest (the critical thing
4686 * is that most applications expect the first IP to be the default route).
4689 for (i = 0; i < numroutes; i++)
4691 struct in_addr addr;
4692 int metric = 0xFFFF;
4694 memcpy(&addr, magic_loopback_addr, 4);
4695 for (j = 0; j < numroutes; j++)
4697 int this_metric = route_addrs[j].metric;
4699 if (this_metric > last_metric && this_metric < metric)
4701 addr = route_addrs[j].addr;
4702 metric = this_metric;
4705 last_metric = metric;
4706 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
4709 /* Cleanup all allocated memory except the address list,
4710 * the address list is used by the calling app.
4713 HeapFree(GetProcessHeap(), 0, route_addrs);
4714 HeapFree(GetProcessHeap(), 0, adapters);
4715 HeapFree(GetProcessHeap(), 0, routes);
4719 /***********************************************************************
4720 * gethostbyname (WS2_32.52)
4722 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
4724 struct WS_hostent *retval = NULL;
4725 struct hostent* host;
4726 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4729 struct hostent hostentry;
4730 int locerr = ENOBUFS;
4734 SetLastError(WSANOTINITIALISED);
4737 if( gethostname( hostname, 100) == -1) {
4738 SetLastError( WSAENOBUFS); /* appropriate ? */
4741 if( !name || !name[0]) {
4744 /* If the hostname of the local machine is requested then return the
4745 * complete list of local IP addresses */
4746 if(strcmp(name, hostname) == 0)
4747 retval = WS_get_local_ips(hostname);
4748 /* If any other hostname was requested (or the routing table lookup failed)
4749 * then return the IP found by the host OS */
4752 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4754 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4756 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
4757 if( res != ERANGE) break;
4759 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4761 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4763 EnterCriticalSection( &csWSgetXXXbyYYY );
4764 host = gethostbyname(name);
4765 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4767 if (host) retval = WS_dup_he(host);
4768 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4769 HeapFree(GetProcessHeap(),0,extrabuf);
4771 LeaveCriticalSection( &csWSgetXXXbyYYY );
4774 if (retval && retval->h_addr_list[0][0] == 127 &&
4775 strcmp(name, "localhost") != 0)
4777 /* hostname != "localhost" but has loopback address. replace by our
4778 * special address.*/
4779 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
4781 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4786 /***********************************************************************
4787 * getprotobyname (WS2_32.53)
4789 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
4791 struct WS_protoent* retval = NULL;
4792 #ifdef HAVE_GETPROTOBYNAME
4793 struct protoent* proto;
4794 EnterCriticalSection( &csWSgetXXXbyYYY );
4795 if( (proto = getprotobyname(name)) != NULL )
4797 retval = WS_dup_pe(proto);
4800 MESSAGE("protocol %s not found; You might want to add "
4801 "this to /etc/protocols\n", debugstr_a(name) );
4802 SetLastError(WSANO_DATA);
4804 LeaveCriticalSection( &csWSgetXXXbyYYY );
4806 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4811 /***********************************************************************
4812 * getprotobynumber (WS2_32.54)
4814 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
4816 struct WS_protoent* retval = NULL;
4817 #ifdef HAVE_GETPROTOBYNUMBER
4818 struct protoent* proto;
4819 EnterCriticalSection( &csWSgetXXXbyYYY );
4820 if( (proto = getprotobynumber(number)) != NULL )
4822 retval = WS_dup_pe(proto);
4825 MESSAGE("protocol number %d not found; You might want to add "
4826 "this to /etc/protocols\n", number );
4827 SetLastError(WSANO_DATA);
4829 LeaveCriticalSection( &csWSgetXXXbyYYY );
4831 TRACE("%i ret %p\n", number, retval);
4836 /***********************************************************************
4837 * getservbyname (WS2_32.55)
4839 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
4841 struct WS_servent* retval = NULL;
4842 struct servent* serv;
4844 char *proto_str = NULL;
4846 if (!(name_str = strdup_lower(name))) return NULL;
4848 if (proto && *proto)
4850 if (!(proto_str = strdup_lower(proto)))
4852 HeapFree( GetProcessHeap(), 0, name_str );
4857 EnterCriticalSection( &csWSgetXXXbyYYY );
4858 serv = getservbyname(name_str, proto_str);
4861 retval = WS_dup_se(serv);
4863 else SetLastError(WSANO_DATA);
4864 LeaveCriticalSection( &csWSgetXXXbyYYY );
4865 HeapFree( GetProcessHeap(), 0, proto_str );
4866 HeapFree( GetProcessHeap(), 0, name_str );
4867 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
4871 /***********************************************************************
4872 * freeaddrinfo (WS2_32.@)
4874 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
4877 struct WS_addrinfo *next;
4879 HeapFree(GetProcessHeap(),0,res->ai_canonname);
4880 HeapFree(GetProcessHeap(),0,res->ai_addr);
4881 next = res->ai_next;
4882 HeapFree(GetProcessHeap(),0,res);
4887 /* helper functions for getaddrinfo()/getnameinfo() */
4888 static int convert_aiflag_w2u(int winflags) {
4892 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4893 if (ws_aiflag_map[i][0] & winflags) {
4894 unixflags |= ws_aiflag_map[i][1];
4895 winflags &= ~ws_aiflag_map[i][0];
4898 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
4902 static int convert_niflag_w2u(int winflags) {
4906 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
4907 if (ws_niflag_map[i][0] & winflags) {
4908 unixflags |= ws_niflag_map[i][1];
4909 winflags &= ~ws_niflag_map[i][0];
4912 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
4916 static int convert_aiflag_u2w(int unixflags) {
4920 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4921 if (ws_aiflag_map[i][1] & unixflags) {
4922 winflags |= ws_aiflag_map[i][0];
4923 unixflags &= ~ws_aiflag_map[i][1];
4925 if (unixflags) /* will warn usually */
4926 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
4930 static int convert_eai_u2w(int unixret) {
4933 for (i=0;ws_eai_map[i][0];i++)
4934 if (ws_eai_map[i][1] == unixret)
4935 return ws_eai_map[i][0];
4939 static char *get_hostname(void)
4944 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
4945 if (GetLastError() != ERROR_MORE_DATA) return NULL;
4946 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
4947 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
4949 HeapFree( GetProcessHeap(), 0, ret );
4955 /***********************************************************************
4956 * getaddrinfo (WS2_32.@)
4958 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
4960 #ifdef HAVE_GETADDRINFO
4961 struct addrinfo *unixaires = NULL;
4963 struct addrinfo unixhints, *punixhints = NULL;
4964 char *hostname = NULL;
4967 if (!nodename && !servname) return WSAHOST_NOT_FOUND;
4971 else if (!nodename[0])
4973 node = hostname = get_hostname();
4974 if (!node) return WSA_NOT_ENOUGH_MEMORY;
4980 punixhints = &unixhints;
4982 memset(&unixhints, 0, sizeof(unixhints));
4983 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
4984 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
4985 punixhints->ai_family = 0;
4987 punixhints->ai_family = convert_af_w2u(hints->ai_family);
4988 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
4989 punixhints->ai_socktype = 0;
4991 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
4992 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
4993 punixhints->ai_protocol = 0;
4995 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
4998 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
4999 result = getaddrinfo(node, servname, punixhints, &unixaires);
5001 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
5002 HeapFree(GetProcessHeap(), 0, hostname);
5005 struct addrinfo *xuai = unixaires;
5006 struct WS_addrinfo **xai = res;
5010 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
5016 *xai = ai;xai = &ai->ai_next;
5017 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
5018 ai->ai_family = convert_af_u2w(xuai->ai_family);
5019 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
5020 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
5021 if (xuai->ai_canonname) {
5022 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
5023 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
5024 if (!ai->ai_canonname)
5026 strcpy(ai->ai_canonname,xuai->ai_canonname);
5028 len = xuai->ai_addrlen;
5029 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
5032 ai->ai_addrlen = len;
5034 int winlen = ai->ai_addrlen;
5036 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
5037 ai->ai_addrlen = winlen;
5041 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
5044 ai->ai_addrlen = len;
5046 xuai = xuai->ai_next;
5048 freeaddrinfo(unixaires);
5050 result = convert_eai_u2w(result);
5056 if (*res) WS_freeaddrinfo(*res);
5057 if (unixaires) freeaddrinfo(unixaires);
5059 return WSA_NOT_ENOUGH_MEMORY;
5061 FIXME("getaddrinfo() failed, not found during buildtime.\n");
5066 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
5068 struct WS_addrinfoW *ret;
5070 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
5071 ret->ai_flags = ai->ai_flags;
5072 ret->ai_family = ai->ai_family;
5073 ret->ai_socktype = ai->ai_socktype;
5074 ret->ai_protocol = ai->ai_protocol;
5075 ret->ai_addrlen = ai->ai_addrlen;
5076 ret->ai_canonname = NULL;
5077 ret->ai_addr = NULL;
5078 ret->ai_next = NULL;
5079 if (ai->ai_canonname)
5081 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
5082 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5084 HeapFree(GetProcessHeap(), 0, ret);
5087 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
5091 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5093 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5094 HeapFree(GetProcessHeap(), 0, ret);
5097 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5102 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
5104 struct WS_addrinfoW *ret, *infoW;
5106 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
5107 while (info->ai_next)
5109 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
5114 infoW = infoW->ai_next;
5115 info = info->ai_next;
5120 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
5122 struct WS_addrinfo *ret;
5124 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
5125 ret->ai_flags = ai->ai_flags;
5126 ret->ai_family = ai->ai_family;
5127 ret->ai_socktype = ai->ai_socktype;
5128 ret->ai_protocol = ai->ai_protocol;
5129 ret->ai_addrlen = ai->ai_addrlen;
5130 ret->ai_canonname = NULL;
5131 ret->ai_addr = NULL;
5132 ret->ai_next = NULL;
5133 if (ai->ai_canonname)
5135 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
5136 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5138 HeapFree(GetProcessHeap(), 0, ret);
5141 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
5145 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5147 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5148 HeapFree(GetProcessHeap(), 0, ret);
5151 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5156 /***********************************************************************
5157 * GetAddrInfoW (WS2_32.@)
5159 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
5162 char *nodenameA = NULL, *servnameA = NULL;
5163 struct WS_addrinfo *resA, *hintsA = NULL;
5167 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
5168 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
5169 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
5173 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
5174 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
5176 HeapFree(GetProcessHeap(), 0, nodenameA);
5179 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
5182 if (hints) hintsA = addrinfo_WtoA(hints);
5183 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
5184 WS_freeaddrinfo(hintsA);
5188 *res = addrinfo_list_AtoW(resA);
5189 WS_freeaddrinfo(resA);
5192 HeapFree(GetProcessHeap(), 0, nodenameA);
5193 HeapFree(GetProcessHeap(), 0, servnameA);
5197 /***********************************************************************
5198 * FreeAddrInfoW (WS2_32.@)
5200 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
5205 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
5206 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
5208 HeapFree(GetProcessHeap(), 0, ai);
5213 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
5214 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
5216 #ifdef HAVE_GETNAMEINFO
5218 union generic_unix_sockaddr sa_u;
5221 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
5222 serv, servlen, flags);
5224 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
5227 WSASetLastError(WSAEFAULT);
5228 return WSA_NOT_ENOUGH_MEMORY;
5230 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
5231 return convert_eai_u2w(ret);
5233 FIXME("getnameinfo() failed, not found during buildtime.\n");
5238 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
5239 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
5242 char *hostA = NULL, *servA = NULL;
5244 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
5245 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
5247 HeapFree(GetProcessHeap(), 0, hostA);
5251 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
5254 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
5255 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
5258 HeapFree(GetProcessHeap(), 0, hostA);
5259 HeapFree(GetProcessHeap(), 0, servA);
5263 /***********************************************************************
5264 * getservbyport (WS2_32.56)
5266 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
5268 struct WS_servent* retval = NULL;
5269 #ifdef HAVE_GETSERVBYPORT
5270 struct servent* serv;
5271 char *proto_str = NULL;
5273 if (proto && *proto)
5275 if (!(proto_str = strdup_lower(proto))) return NULL;
5277 EnterCriticalSection( &csWSgetXXXbyYYY );
5278 if( (serv = getservbyport(port, proto_str)) != NULL ) {
5279 retval = WS_dup_se(serv);
5281 else SetLastError(WSANO_DATA);
5282 LeaveCriticalSection( &csWSgetXXXbyYYY );
5283 HeapFree( GetProcessHeap(), 0, proto_str );
5285 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
5290 /***********************************************************************
5291 * gethostname (WS2_32.57)
5293 int WINAPI WS_gethostname(char *name, int namelen)
5295 TRACE("name %p, len %d\n", name, namelen);
5297 if (gethostname(name, namelen) == 0)
5299 TRACE("<- '%s'\n", name);
5302 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
5303 TRACE("<- ERROR !\n");
5304 return SOCKET_ERROR;
5308 /* ------------------------------------- Windows sockets extensions -- *
5310 * ------------------------------------------------------------------- */
5312 /***********************************************************************
5313 * WSAEnumNetworkEvents (WS2_32.36)
5315 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
5319 int errors[FD_MAX_EVENTS];
5321 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
5323 SERVER_START_REQ( get_socket_event )
5325 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5326 req->service = TRUE;
5327 req->c_event = wine_server_obj_handle( hEvent );
5328 wine_server_set_reply( req, errors, sizeof(errors) );
5329 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
5334 for (i = 0; i < FD_MAX_EVENTS; i++)
5335 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
5338 SetLastError(WSAEINVAL);
5339 return SOCKET_ERROR;
5342 /***********************************************************************
5343 * WSAEventSelect (WS2_32.39)
5345 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
5349 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
5351 SERVER_START_REQ( set_socket_event )
5353 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5355 req->event = wine_server_obj_handle( hEvent );
5358 ret = wine_server_call( req );
5362 SetLastError(WSAEINVAL);
5363 return SOCKET_ERROR;
5366 /**********************************************************************
5367 * WSAGetOverlappedResult (WS2_32.40)
5369 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
5370 LPDWORD lpcbTransfer, BOOL fWait,
5375 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
5376 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
5378 if ( lpOverlapped == NULL )
5380 ERR( "Invalid pointer\n" );
5381 WSASetLastError(WSA_INVALID_PARAMETER);
5385 status = lpOverlapped->Internal;
5386 if (status == STATUS_PENDING)
5390 SetLastError( WSA_IO_INCOMPLETE );
5394 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
5395 INFINITE ) == WAIT_FAILED)
5397 status = lpOverlapped->Internal;
5401 *lpcbTransfer = lpOverlapped->InternalHigh;
5404 *lpdwFlags = lpOverlapped->u.s.Offset;
5406 if (status) SetLastError( RtlNtStatusToDosError(status) );
5411 /***********************************************************************
5412 * WSAAsyncSelect (WS2_32.101)
5414 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
5418 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
5420 SERVER_START_REQ( set_socket_event )
5422 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5425 req->window = wine_server_user_handle( hWnd );
5427 ret = wine_server_call( req );
5431 SetLastError(WSAEINVAL);
5432 return SOCKET_ERROR;
5435 /***********************************************************************
5436 * WSACreateEvent (WS2_32.31)
5439 WSAEVENT WINAPI WSACreateEvent(void)
5441 /* Create a manual-reset event, with initial state: unsignaled */
5444 return CreateEventW(NULL, TRUE, FALSE, NULL);
5447 /***********************************************************************
5448 * WSACloseEvent (WS2_32.29)
5451 BOOL WINAPI WSACloseEvent(WSAEVENT event)
5453 TRACE ("event=%p\n", event);
5455 return CloseHandle(event);
5458 /***********************************************************************
5459 * WSASocketA (WS2_32.78)
5462 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
5463 LPWSAPROTOCOL_INFOA lpProtocolInfo,
5464 GROUP g, DWORD dwFlags)
5467 WSAPROTOCOL_INFOW info;
5469 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5470 af, type, protocol, lpProtocolInfo, g, dwFlags);
5472 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
5474 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
5475 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5476 info.szProtocol, WSAPROTOCOL_LEN + 1);
5480 WSASetLastError( WSAEINVAL);
5481 return SOCKET_ERROR;
5484 return WSASocketW(af, type, protocol, &info, g, dwFlags);
5487 /***********************************************************************
5488 * WSASocketW (WS2_32.79)
5491 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
5492 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5493 GROUP g, DWORD dwFlags)
5498 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
5499 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
5502 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5503 af, type, protocol, lpProtocolInfo, g, dwFlags );
5505 /* hack for WSADuplicateSocket */
5506 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
5507 ret = lpProtocolInfo->dwCatalogEntryId;
5508 TRACE("\tgot duplicate %04lx\n", ret);
5512 /* convert the socket family and type */
5513 af = convert_af_w2u(af);
5514 type = convert_socktype_w2u(type);
5518 if (af == FROM_PROTOCOL_INFO)
5519 af = lpProtocolInfo->iAddressFamily;
5520 if (type == FROM_PROTOCOL_INFO)
5521 type = lpProtocolInfo->iSocketType;
5522 if (protocol == FROM_PROTOCOL_INFO)
5523 protocol = lpProtocolInfo->iProtocol;
5526 if ( af == AF_UNSPEC) /* did they not specify the address family? */
5528 if ((protocol == IPPROTO_TCP && type == SOCK_STREAM) ||
5529 (protocol == IPPROTO_UDP && type == SOCK_DGRAM))
5535 SetLastError(WSAEPROTOTYPE);
5536 return INVALID_SOCKET;
5540 SERVER_START_REQ( create_socket )
5544 req->protocol = protocol;
5545 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
5546 req->attributes = OBJ_INHERIT;
5547 req->flags = dwFlags;
5548 set_error( wine_server_call( req ) );
5549 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
5554 TRACE("\tcreated %04lx\n", ret );
5558 if (GetLastError() == WSAEACCES) /* raw socket denied */
5560 if (type == SOCK_RAW)
5561 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
5563 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
5564 SetLastError(WSAESOCKTNOSUPPORT);
5567 WARN("\t\tfailed!\n");
5568 return INVALID_SOCKET;
5571 /***********************************************************************
5572 * WSAJoinLeaf (WS2_32.58)
5575 SOCKET WINAPI WSAJoinLeaf(
5577 const struct WS_sockaddr *addr,
5579 LPWSABUF lpCallerData,
5580 LPWSABUF lpCalleeData,
5586 return INVALID_SOCKET;
5589 /***********************************************************************
5590 * __WSAFDIsSet (WS2_32.151)
5592 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
5594 int i = set->fd_count;
5596 TRACE("(%ld,%p(%i))\n", s, set, i);
5599 if (set->fd_array[i] == s) return 1;
5603 /***********************************************************************
5604 * WSAIsBlocking (WS2_32.114)
5606 BOOL WINAPI WSAIsBlocking(void)
5608 /* By default WinSock should set all its sockets to non-blocking mode
5609 * and poll in PeekMessage loop when processing "blocking" ones. This
5610 * function is supposed to tell if the program is in this loop. Our
5611 * blocking calls are truly blocking so we always return FALSE.
5613 * Note: It is allowed to call this function without prior WSAStartup().
5620 /***********************************************************************
5621 * WSACancelBlockingCall (WS2_32.113)
5623 INT WINAPI WSACancelBlockingCall(void)
5629 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
5631 FIXME("How was this called?\n");
5636 /***********************************************************************
5637 * WSASetBlockingHook (WS2_32.109)
5639 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
5641 FARPROC prev = blocking_hook;
5642 blocking_hook = lpBlockFunc;
5643 TRACE("hook %p\n", lpBlockFunc);
5648 /***********************************************************************
5649 * WSAUnhookBlockingHook (WS2_32.110)
5651 INT WINAPI WSAUnhookBlockingHook(void)
5653 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
5658 /* ----------------------------------- end of API stuff */
5660 /* ----------------------------------- helper functions -
5662 * TODO: Merge WS_dup_..() stuff into one function that
5663 * would operate with a generic structure containing internal
5664 * pointers (via a template of some kind).
5667 static int list_size(char** l, int item_size)
5672 j += (item_size) ? item_size : strlen(l[i]) + 1;
5673 j += (i + 1) * sizeof(char*); }
5677 static int list_dup(char** l_src, char** l_to, int item_size)
5682 for (i = 0; l_src[i]; i++) ;
5683 p = (char *)(l_to + i + 1);
5684 for (i = 0; l_src[i]; i++)
5686 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
5687 memcpy(p, l_src[i], count);
5692 return p - (char *)l_to;
5697 /* create a hostent entry
5699 * Creates the entry with enough memory for the name, aliases
5700 * addresses, and the address pointers. Also copies the name
5701 * and sets up all the pointers.
5703 * NOTE: The alias and address lists must be allocated with room
5704 * for the NULL item terminating the list. This is true even if
5705 * the list has no items ("aliases" and "addresses" must be
5706 * at least "1", a truly empty list is invalid).
5708 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
5710 struct WS_hostent *p_to;
5712 int size = (sizeof(struct WS_hostent) +
5714 sizeof(char *) * aliases +
5716 sizeof(char *) * addresses +
5717 address_length * (addresses - 1)), i;
5719 if (!(p_to = check_buffer_he(size))) return NULL;
5720 memset(p_to, 0, size);
5722 /* Use the memory in the same way winsock does.
5723 * First set the pointer for aliases, second set the pointers for addresses.
5724 * Third fill the addresses indexes, fourth jump aliases names size.
5725 * Fifth fill the hostname.
5726 * NOTE: This method is valid for OS version's >= XP.
5728 p = (char *)(p_to + 1);
5729 p_to->h_aliases = (char **)p;
5730 p += sizeof(char *)*aliases;
5732 p_to->h_addr_list = (char **)p;
5733 p += sizeof(char *)*addresses;
5735 for (i = 0, addresses--; i < addresses; i++, p += address_length)
5736 p_to->h_addr_list[i] = p;
5738 /* NOTE: h_aliases must be filled in manually because we don't know each string
5739 * size, leave these pointers NULL (already set to NULL by memset earlier).
5749 /* duplicate hostent entry
5750 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
5751 * Ditto for protoent and servent.
5753 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
5755 int i, addresses = 0, alias_size = 0;
5756 struct WS_hostent *p_to;
5759 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
5760 while (p_he->h_addr_list[addresses]) addresses++;
5762 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
5764 if (!p_to) return NULL;
5765 p_to->h_addrtype = p_he->h_addrtype;
5766 p_to->h_length = p_he->h_length;
5768 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
5769 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
5771 /* Fill the aliases after the IP data */
5772 for(i = 0; p_he->h_aliases[i]; i++)
5774 p_to->h_aliases[i] = p;
5775 strcpy(p, p_he->h_aliases[i]);
5782 /* ----- protoent */
5784 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
5787 struct WS_protoent *p_to;
5789 int size = (sizeof(*p_pe) +
5790 strlen(p_pe->p_name) + 1 +
5791 list_size(p_pe->p_aliases, 0));
5793 if (!(p_to = check_buffer_pe(size))) return NULL;
5794 p_to->p_proto = p_pe->p_proto;
5796 p = (char *)(p_to + 1);
5798 strcpy(p, p_pe->p_name);
5801 p_to->p_aliases = (char **)p;
5802 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
5808 static struct WS_servent *WS_dup_se(const struct servent* p_se)
5811 struct WS_servent *p_to;
5813 int size = (sizeof(*p_se) +
5814 strlen(p_se->s_proto) + 1 +
5815 strlen(p_se->s_name) + 1 +
5816 list_size(p_se->s_aliases, 0));
5818 if (!(p_to = check_buffer_se(size))) return NULL;
5819 p_to->s_port = p_se->s_port;
5821 p = (char *)(p_to + 1);
5823 strcpy(p, p_se->s_name);
5827 strcpy(p, p_se->s_proto);
5830 p_to->s_aliases = (char **)p;
5831 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
5836 /***********************************************************************
5837 * WSARecv (WS2_32.67)
5839 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5840 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
5841 LPWSAOVERLAPPED lpOverlapped,
5842 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
5844 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
5845 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
5848 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5849 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
5850 struct WS_sockaddr *lpFrom,
5851 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
5852 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
5853 LPWSABUF lpControlBuffer )
5855 unsigned int i, options;
5857 struct ws2_async *wsa;
5858 DWORD timeout_start = GetTickCount();
5859 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5861 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
5862 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
5863 (lpFromlen ? *lpFromlen : -1),
5864 lpOverlapped, lpCompletionRoutine);
5866 fd = get_sock_fd( s, FILE_READ_DATA, &options );
5867 TRACE( "fd=%d, options=%x\n", fd, options );
5869 if (fd == -1) return SOCKET_ERROR;
5871 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
5877 wsa->hSocket = SOCKET2HANDLE(s);
5878 wsa->flags = *lpFlags;
5879 wsa->lpFlags = lpFlags;
5881 wsa->addrlen.ptr = lpFromlen;
5882 wsa->control = lpControlBuffer;
5883 wsa->n_iovecs = dwBufferCount;
5884 wsa->first_iovec = 0;
5885 for (i = 0; i < dwBufferCount; i++)
5887 /* check buffer first to trigger write watches */
5888 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
5893 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5894 wsa->iovec[i].iov_len = lpBuffers[i].len;
5899 n = WS2_recv( fd, wsa );
5902 if (errno == EINTR) continue;
5903 if (errno != EAGAIN)
5905 int loc_errno = errno;
5907 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
5911 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
5913 if ((lpOverlapped || lpCompletionRoutine) &&
5914 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5916 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5918 wsa->user_overlapped = lpOverlapped;
5919 wsa->completion_func = lpCompletionRoutine;
5920 release_sock_fd( s, fd );
5924 iosb->u.Status = STATUS_PENDING;
5925 iosb->Information = 0;
5927 SERVER_START_REQ( register_async )
5929 req->type = ASYNC_TYPE_READ;
5930 req->async.handle = wine_server_obj_handle( wsa->hSocket );
5931 req->async.callback = wine_server_client_ptr( WS2_async_recv );
5932 req->async.iosb = wine_server_client_ptr( iosb );
5933 req->async.arg = wine_server_client_ptr( wsa );
5934 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
5935 req->async.cvalue = cvalue;
5936 err = wine_server_call( req );
5940 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5941 WSASetLastError( NtStatusToWSAError( err ));
5942 return SOCKET_ERROR;
5945 iosb->u.Status = STATUS_SUCCESS;
5946 iosb->Information = n;
5947 if (!wsa->completion_func)
5949 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5950 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5951 HeapFree( GetProcessHeap(), 0, wsa );
5953 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5954 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5955 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5961 if ( _is_blocking(s) )
5964 int timeout = GET_RCVTIMEO(fd);
5967 timeout -= GetTickCount() - timeout_start;
5968 if (timeout < 0) timeout = 0;
5972 pfd.events = POLLIN;
5973 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
5975 if (!timeout || !poll( &pfd, 1, timeout ))
5978 /* a timeout is not fatal */
5979 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5985 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5986 err = WSAEWOULDBLOCK;
5991 TRACE(" -> %i bytes\n", n);
5992 HeapFree( GetProcessHeap(), 0, wsa );
5993 release_sock_fd( s, fd );
5994 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5999 HeapFree( GetProcessHeap(), 0, wsa );
6000 release_sock_fd( s, fd );
6001 WARN(" -> ERROR %d\n", err);
6002 WSASetLastError( err );
6003 return SOCKET_ERROR;
6006 /***********************************************************************
6007 * WSARecvFrom (WS2_32.69)
6009 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6010 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
6011 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6012 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
6015 return WS2_recv_base( s, lpBuffers, dwBufferCount,
6016 lpNumberOfBytesRecvd, lpFlags,
6018 lpOverlapped, lpCompletionRoutine, NULL );
6021 /***********************************************************************
6022 * WSCInstallProvider (WS2_32.88)
6024 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
6025 LPCWSTR lpszProviderDllPath,
6026 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
6027 DWORD dwNumberOfEntries,
6030 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
6031 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
6032 dwNumberOfEntries, lpErrno);
6038 /***********************************************************************
6039 * WSCDeinstallProvider (WS2_32.83)
6041 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
6043 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
6049 /***********************************************************************
6050 * WSAAccept (WS2_32.26)
6052 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
6053 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
6056 int ret = 0, size = 0;
6057 WSABUF CallerId, CallerData, CalleeId, CalleeData;
6058 /* QOS SQOS, GQOS; */
6061 SOCKADDR src_addr, dst_addr;
6063 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
6064 s, addr, addrlen, lpfnCondition, dwCallbackData);
6067 size = sizeof(src_addr);
6068 cs = WS_accept(s, &src_addr, &size);
6070 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
6072 if (!lpfnCondition) return cs;
6074 CallerId.buf = (char *)&src_addr;
6075 CallerId.len = sizeof(src_addr);
6077 CallerData.buf = NULL;
6080 WS_getsockname(cs, &dst_addr, &size);
6082 CalleeId.buf = (char *)&dst_addr;
6083 CalleeId.len = sizeof(dst_addr);
6086 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
6087 &CalleeId, &CalleeData, &g, dwCallbackData);
6092 if (addr && addrlen)
6093 memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
6096 SERVER_START_REQ( set_socket_deferred )
6098 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6099 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
6100 if ( !wine_server_call_err ( req ) )
6102 SetLastError( WSATRY_AGAIN );
6103 WS_closesocket( cs );
6107 return SOCKET_ERROR;
6110 SetLastError(WSAECONNREFUSED);
6111 return SOCKET_ERROR;
6113 FIXME("Unknown return type from Condition function\n");
6114 SetLastError(WSAENOTSOCK);
6115 return SOCKET_ERROR;
6119 /***********************************************************************
6120 * WSADuplicateSocketA (WS2_32.32)
6122 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
6126 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
6127 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
6128 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
6129 /* I don't know what the real Windoze does next, this is a hack */
6130 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
6131 * the target use the global duplicate, or we could copy a reference to us to the structure
6132 * and let the target duplicate it from us, but let's do it as simple as possible */
6133 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
6134 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
6135 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
6136 0, FALSE, DUPLICATE_SAME_ACCESS);
6137 CloseHandle(hProcess);
6138 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
6142 /***********************************************************************
6143 * WSADuplicateSocketW (WS2_32.33)
6145 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
6149 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
6151 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
6152 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
6153 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
6154 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
6155 0, FALSE, DUPLICATE_SAME_ACCESS);
6156 CloseHandle(hProcess);
6157 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
6161 /***********************************************************************
6162 * WSAInstallServiceClassA (WS2_32.48)
6164 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
6166 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
6167 WSASetLastError(WSAEACCES);
6168 return SOCKET_ERROR;
6171 /***********************************************************************
6172 * WSAInstallServiceClassW (WS2_32.49)
6174 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
6176 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
6177 WSASetLastError(WSAEACCES);
6178 return SOCKET_ERROR;
6181 /***********************************************************************
6182 * WSARemoveServiceClass (WS2_32.70)
6184 int WINAPI WSARemoveServiceClass(LPGUID info)
6186 FIXME("Request to remove service %p\n",info);
6187 WSASetLastError(WSATYPE_NOT_FOUND);
6188 return SOCKET_ERROR;
6191 /***********************************************************************
6192 * inet_ntop (WS2_32.@)
6194 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
6196 #ifdef HAVE_INET_NTOP
6197 struct WS_in6_addr *in6;
6198 struct WS_in_addr *in;
6201 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
6204 WSASetLastError( STATUS_INVALID_PARAMETER );
6213 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
6219 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
6223 WSASetLastError( WSAEAFNOSUPPORT );
6227 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
6230 FIXME( "not supported on this platform\n" );
6231 WSASetLastError( WSAEAFNOSUPPORT );
6236 /***********************************************************************
6237 * WSAStringToAddressA (WS2_32.80)
6239 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
6241 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6242 LPSOCKADDR lpAddress,
6243 LPINT lpAddressLength)
6246 LPSTR workBuffer=NULL,ptrPort;
6248 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
6249 lpProtocolInfo, lpAddress, lpAddressLength );
6251 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6255 WSASetLastError(WSAEINVAL);
6256 return SOCKET_ERROR;
6260 FIXME("ProtocolInfo not implemented.\n");
6262 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
6263 strlen(AddressString) + 1);
6266 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6267 return SOCKET_ERROR;
6270 strcpy(workBuffer, AddressString);
6272 switch(AddressFamily)
6276 struct in_addr inetaddr;
6278 /* If lpAddressLength is too small, tell caller the size we need */
6279 if (*lpAddressLength < sizeof(SOCKADDR_IN))
6281 *lpAddressLength = sizeof(SOCKADDR_IN);
6285 *lpAddressLength = sizeof(SOCKADDR_IN);
6286 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
6288 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
6290 ptrPort = strchr(workBuffer, ':');
6293 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
6298 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
6301 if(inet_aton(workBuffer, &inetaddr) > 0)
6303 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
6314 struct in6_addr inetaddr;
6315 /* If lpAddressLength is too small, tell caller the size we need */
6316 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
6318 *lpAddressLength = sizeof(SOCKADDR_IN6);
6322 #ifdef HAVE_INET_PTON
6323 *lpAddressLength = sizeof(SOCKADDR_IN6);
6324 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
6326 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
6328 /* This one is a bit tricky. An IPv6 address contains colons, so the
6329 * check from IPv4 doesn't work like that. However, IPv6 addresses that
6330 * contain a port are written with braces like [fd12:3456:7890::1]:12345
6331 * so what we will do is to look for ']', check if the next char is a
6332 * colon, and if it is, parse the port as in IPv4. */
6334 ptrPort = strchr(workBuffer, ']');
6335 if(ptrPort && *(++ptrPort) == ':')
6337 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
6342 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
6345 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
6347 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
6348 sizeof(struct in6_addr));
6352 #endif /* HAVE_INET_PTON */
6358 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
6359 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
6363 HeapFree(GetProcessHeap(), 0, workBuffer);
6366 WSASetLastError(res);
6367 return SOCKET_ERROR;
6370 /***********************************************************************
6371 * WSAStringToAddressW (WS2_32.81)
6373 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
6374 * If this should be the case, it would be required to map these digits
6375 * to Unicode digits (0-9) using FoldString first.
6377 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
6379 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6380 LPSOCKADDR lpAddress,
6381 LPINT lpAddressLength)
6384 LPSTR workBuffer=NULL;
6385 WSAPROTOCOL_INFOA infoA;
6386 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
6388 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
6389 lpAddress, lpAddressLength );
6391 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6393 /* if ProtocolInfo is available - convert to ANSI variant */
6396 lpProtoInfoA = &infoA;
6397 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
6399 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6400 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
6402 WSASetLastError( WSAEINVAL);
6403 return SOCKET_ERROR;
6409 /* Translate AddressString to ANSI code page - assumes that only
6410 standard digits 0-9 are used with this API call */
6411 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
6412 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
6416 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
6417 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
6418 lpAddress,lpAddressLength);
6419 HeapFree( GetProcessHeap(), 0, workBuffer );
6423 res = WSA_NOT_ENOUGH_MEMORY;
6428 WSASetLastError(res);
6429 return SOCKET_ERROR;
6432 /***********************************************************************
6433 * WSAAddressToStringA (WS2_32.27)
6435 * See WSAAddressToStringW
6437 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
6438 LPWSAPROTOCOL_INFOA info, LPSTR string,
6442 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6445 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6447 if (!sockaddr) return SOCKET_ERROR;
6448 if (!string || !lenstr) return SOCKET_ERROR;
6450 switch(sockaddr->sa_family)
6453 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
6454 sprintf( buffer, "%u.%u.%u.%u:%u",
6455 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
6456 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
6457 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
6458 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
6459 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
6461 p = strchr( buffer, ':' );
6462 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
6467 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
6470 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
6471 if ((sockaddr6->sin6_port))
6472 strcpy(buffer, "[");
6473 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
6475 WSASetLastError(WSAEINVAL);
6476 return SOCKET_ERROR;
6478 if ((sockaddr6->sin6_scope_id))
6479 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
6480 if ((sockaddr6->sin6_port))
6481 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
6486 WSASetLastError(WSAEINVAL);
6487 return SOCKET_ERROR;
6490 size = strlen( buffer ) + 1;
6495 WSASetLastError(WSAEFAULT);
6496 return SOCKET_ERROR;
6500 strcpy( string, buffer );
6504 /***********************************************************************
6505 * WSAAddressToStringW (WS2_32.28)
6507 * Convert a sockaddr address into a readable address string.
6510 * sockaddr [I] Pointer to a sockaddr structure.
6511 * len [I] Size of the sockaddr structure.
6512 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
6513 * string [I/O] Pointer to a buffer to receive the address string.
6514 * lenstr [I/O] Size of the receive buffer in WCHARs.
6518 * Failure: SOCKET_ERROR
6521 * The 'info' parameter is ignored.
6523 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
6524 LPWSAPROTOCOL_INFOW info, LPWSTR string,
6529 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6532 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6535 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
6537 if (ret) return ret;
6539 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
6544 WSASetLastError(WSAEFAULT);
6545 return SOCKET_ERROR;
6549 lstrcpyW( string, buffer );
6553 /***********************************************************************
6554 * WSAEnumNameSpaceProvidersA (WS2_32.34)
6556 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
6558 FIXME( "(%p %p) Stub!\n", len, buffer );
6562 /***********************************************************************
6563 * WSAEnumNameSpaceProvidersW (WS2_32.35)
6565 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
6567 FIXME( "(%p %p) Stub!\n", len, buffer );
6571 /***********************************************************************
6572 * WSAGetQOSByName (WS2_32.41)
6574 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
6576 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
6580 /***********************************************************************
6581 * WSAGetServiceClassInfoA (WS2_32.42)
6583 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
6584 LPWSASERVICECLASSINFOA info )
6586 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
6588 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6589 return SOCKET_ERROR;
6592 /***********************************************************************
6593 * WSAGetServiceClassInfoW (WS2_32.43)
6595 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
6596 LPWSASERVICECLASSINFOW info )
6598 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
6600 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6601 return SOCKET_ERROR;
6604 /***********************************************************************
6605 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
6607 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
6609 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6610 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6611 return SOCKET_ERROR;
6614 /***********************************************************************
6615 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
6617 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
6619 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6620 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6621 return SOCKET_ERROR;
6624 /***********************************************************************
6625 * WSALookupServiceBeginA (WS2_32.59)
6627 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
6628 DWORD dwControlFlags,
6631 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6633 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6634 return SOCKET_ERROR;
6637 /***********************************************************************
6638 * WSALookupServiceBeginW (WS2_32.60)
6640 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
6641 DWORD dwControlFlags,
6644 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6646 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6647 return SOCKET_ERROR;
6650 /***********************************************************************
6651 * WSALookupServiceEnd (WS2_32.61)
6653 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
6655 FIXME("(%p) Stub!\n", lookup );
6659 /***********************************************************************
6660 * WSALookupServiceNextA (WS2_32.62)
6662 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
6664 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6665 WSASetLastError(WSA_E_NO_MORE);
6666 return SOCKET_ERROR;
6669 /***********************************************************************
6670 * WSALookupServiceNextW (WS2_32.63)
6672 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
6674 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6675 WSASetLastError(WSA_E_NO_MORE);
6676 return SOCKET_ERROR;
6679 /***********************************************************************
6680 * WSANtohl (WS2_32.64)
6682 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
6684 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
6686 if (!lphostlong) return WSAEFAULT;
6688 *lphostlong = ntohl( netlong );
6692 /***********************************************************************
6693 * WSANtohs (WS2_32.65)
6695 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
6697 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
6699 if (!lphostshort) return WSAEFAULT;
6701 *lphostshort = ntohs( netshort );
6705 /***********************************************************************
6706 * WSAProviderConfigChange (WS2_32.66)
6708 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
6709 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
6711 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
6712 return SOCKET_ERROR;
6715 /***********************************************************************
6716 * WSARecvDisconnect (WS2_32.68)
6718 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
6720 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
6722 return WS_shutdown( s, 0 );
6725 /***********************************************************************
6726 * WSASetServiceA (WS2_32.76)
6728 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
6730 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6734 /***********************************************************************
6735 * WSASetServiceW (WS2_32.77)
6737 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
6739 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6743 /***********************************************************************
6744 * WSCEnableNSProvider (WS2_32.84)
6746 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
6748 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
6752 /***********************************************************************
6753 * WSCGetProviderPath (WS2_32.86)
6755 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
6757 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
6759 if (!errcode || !provider || !len) return WSAEFAULT;
6761 *errcode = WSAEINVAL;
6762 return SOCKET_ERROR;
6765 /***********************************************************************
6766 * WSCInstallNameSpace (WS2_32.87)
6768 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
6769 DWORD version, LPGUID provider )
6771 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
6772 namespace, version, debugstr_guid(provider) );
6776 /***********************************************************************
6777 * WSCUnInstallNameSpace (WS2_32.89)
6779 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
6781 FIXME("(%p) Stub!\n", lpProviderId);
6785 /***********************************************************************
6786 * WSCWriteProviderOrder (WS2_32.91)
6788 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
6790 FIXME("(%p 0x%08x) Stub!\n", entry, number);
6794 /***********************************************************************
6795 * WSANSPIoctl (WS2_32.91)
6797 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
6798 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
6799 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
6801 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
6802 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
6803 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6804 return SOCKET_ERROR;