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>
79 #ifdef HAVE_SYS_ERRNO_H
80 #include <sys/errno.h>
89 #ifdef HAVE_ARPA_NAMESER_H
90 # include <arpa/nameser.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 #include "iphlpapi.h"
150 #include "wine/server.h"
151 #include "wine/debug.h"
152 #include "wine/exception.h"
153 #include "wine/unicode.h"
156 # include "wsnwlink.h"
160 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
161 # define sipx_network sipx_addr.x_net
162 # define sipx_node sipx_addr.x_host.c_host
163 #endif /* __FreeBSD__ */
166 #define INADDR_NONE ~0UL
169 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
170 WINE_DECLARE_DEBUG_CHANNEL(winediag);
174 * The actual definition of WSASendTo, wrapped in a different function name
175 * so that internal calls from ws2_32 itself will not trigger programs like
176 * Garena, which hooks WSASendTo/WSARecvFrom calls.
178 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
179 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
180 const struct WS_sockaddr *to, int tolen,
181 LPWSAOVERLAPPED lpOverlapped,
182 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine );
185 * Internal fundamental receive function, essentially WSARecvFrom with an
186 * additional parameter to support message control headers.
188 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
189 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
190 struct WS_sockaddr *lpFrom,
191 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
192 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
193 LPWSABUF lpControlBuffer );
195 /* critical section to protect some non-reentrant net function */
196 static CRITICAL_SECTION csWSgetXXXbyYYY;
197 static CRITICAL_SECTION_DEBUG critsect_debug =
199 0, 0, &csWSgetXXXbyYYY,
200 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
201 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
203 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
205 union generic_unix_sockaddr
207 struct sockaddr addr;
208 char data[128]; /* should be big enough for all families */
211 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
213 if (!a) return "(nil)";
214 switch (a->sa_family)
217 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
218 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
219 ntohs(((const struct sockaddr_in *)a)->sin_port));
224 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
226 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
228 p = "(unknown IPv6 address)";
229 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
230 p, ntohs(sin->sin6_port));
236 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
237 addr = ntohl( addr );
238 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
240 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
243 return wine_dbg_sprintf("{ family %d }", a->sa_family);
247 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
248 #define SOCKET2HANDLE(s) ((HANDLE)(s))
249 #define HANDLE2SOCKET(h) ((SOCKET)(h))
251 /****************************************************************
252 * Async IO declarations
253 ****************************************************************/
255 typedef struct ws2_async
259 LPWSAOVERLAPPED user_overlapped;
260 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
261 IO_STATUS_BLOCK local_iosb;
262 struct WS_sockaddr *addr;
265 int val; /* for send operations */
266 int *ptr; /* for recv operations */
271 unsigned int n_iovecs;
272 unsigned int first_iovec;
273 struct iovec iovec[1];
276 typedef struct ws2_accept_async
278 HANDLE listen_socket;
279 HANDLE accept_socket;
280 LPOVERLAPPED user_overlapped;
282 PVOID buf; /* buffer to write data to */
286 struct ws2_async *read;
289 /****************************************************************/
291 /* ----------------------------------- internal data */
293 /* ws_... struct conversion flags */
295 typedef struct /* WSAAsyncSelect() control struct */
297 HANDLE service, event, sock;
303 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
304 #define WS_MAX_UDP_DATAGRAM 1024
305 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
307 /* hostent's, servent's and protent's are stored in one buffer per thread,
308 * as documented on MSDN for the functions that return any of the buffers */
309 struct per_thread_data
312 struct WS_hostent *he_buffer;
313 struct WS_servent *se_buffer;
314 struct WS_protoent *pe_buffer;
320 /* internal: routing description information */
327 static INT num_startup; /* reference counter */
328 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
330 /* function prototypes */
331 static struct WS_hostent *WS_create_he(char *name, int aliases, int addresses, int fill_addresses);
332 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
333 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
334 static struct WS_servent *WS_dup_se(const struct servent* p_se);
336 int WSAIOCTL_GetInterfaceCount(void);
337 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
339 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG Information );
341 #define MAP_OPTION(opt) { WS_##opt, opt }
343 static const int ws_sock_map[][2] =
345 MAP_OPTION( SO_DEBUG ),
346 MAP_OPTION( SO_ACCEPTCONN ),
347 MAP_OPTION( SO_REUSEADDR ),
348 MAP_OPTION( SO_KEEPALIVE ),
349 MAP_OPTION( SO_DONTROUTE ),
350 MAP_OPTION( SO_BROADCAST ),
351 MAP_OPTION( SO_LINGER ),
352 MAP_OPTION( SO_OOBINLINE ),
353 MAP_OPTION( SO_SNDBUF ),
354 MAP_OPTION( SO_RCVBUF ),
355 MAP_OPTION( SO_ERROR ),
356 MAP_OPTION( SO_TYPE ),
358 MAP_OPTION( SO_RCVTIMEO ),
361 MAP_OPTION( SO_SNDTIMEO ),
365 static const int ws_tcp_map[][2] =
368 MAP_OPTION( TCP_NODELAY ),
372 static const int ws_ip_map[][2] =
374 MAP_OPTION( IP_MULTICAST_IF ),
375 MAP_OPTION( IP_MULTICAST_TTL ),
376 MAP_OPTION( IP_MULTICAST_LOOP ),
377 MAP_OPTION( IP_ADD_MEMBERSHIP ),
378 MAP_OPTION( IP_DROP_MEMBERSHIP ),
379 MAP_OPTION( IP_OPTIONS ),
381 MAP_OPTION( IP_HDRINCL ),
383 MAP_OPTION( IP_TOS ),
384 MAP_OPTION( IP_TTL ),
386 MAP_OPTION( IP_PKTINFO ),
390 static const int ws_ipv6_map[][2] =
392 #ifdef IPV6_ADD_MEMBERSHIP
393 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
395 #ifdef IPV6_DROP_MEMBERSHIP
396 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
398 MAP_OPTION( IPV6_MULTICAST_IF ),
399 MAP_OPTION( IPV6_MULTICAST_HOPS ),
400 MAP_OPTION( IPV6_MULTICAST_LOOP ),
401 MAP_OPTION( IPV6_UNICAST_HOPS ),
402 MAP_OPTION( IPV6_V6ONLY ),
405 static const int ws_af_map[][2] =
407 MAP_OPTION( AF_UNSPEC ),
408 MAP_OPTION( AF_INET ),
409 MAP_OPTION( AF_INET6 ),
411 MAP_OPTION( AF_IPX ),
414 MAP_OPTION( AF_IRDA ),
416 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
419 static const int ws_socktype_map[][2] =
421 MAP_OPTION( SOCK_DGRAM ),
422 MAP_OPTION( SOCK_STREAM ),
423 MAP_OPTION( SOCK_RAW ),
424 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
427 static const int ws_proto_map[][2] =
429 MAP_OPTION( IPPROTO_IP ),
430 MAP_OPTION( IPPROTO_TCP ),
431 MAP_OPTION( IPPROTO_UDP ),
432 MAP_OPTION( IPPROTO_ICMP ),
433 MAP_OPTION( IPPROTO_IGMP ),
434 MAP_OPTION( IPPROTO_RAW ),
435 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
438 static const int ws_aiflag_map[][2] =
440 MAP_OPTION( AI_PASSIVE ),
441 MAP_OPTION( AI_CANONNAME ),
442 MAP_OPTION( AI_NUMERICHOST ),
443 MAP_OPTION( AI_ADDRCONFIG ),
446 static const int ws_niflag_map[][2] =
448 MAP_OPTION( NI_NOFQDN ),
449 MAP_OPTION( NI_NUMERICHOST ),
450 MAP_OPTION( NI_NAMEREQD ),
451 MAP_OPTION( NI_NUMERICSERV ),
452 MAP_OPTION( NI_DGRAM ),
455 static const int ws_eai_map[][2] =
457 MAP_OPTION( EAI_AGAIN ),
458 MAP_OPTION( EAI_BADFLAGS ),
459 MAP_OPTION( EAI_FAIL ),
460 MAP_OPTION( EAI_FAMILY ),
461 MAP_OPTION( EAI_MEMORY ),
462 /* Note: EAI_NODATA is deprecated, but still
463 * used by Windows and Linux... We map the newer
464 * EAI_NONAME to EAI_NODATA for now until Windows
468 MAP_OPTION( EAI_NODATA ),
471 { WS_EAI_NODATA, EAI_NONAME },
474 MAP_OPTION( EAI_SERVICE ),
475 MAP_OPTION( EAI_SOCKTYPE ),
479 static const char magic_loopback_addr[] = {127, 12, 34, 56};
481 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
482 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
484 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
485 char *ptr = (char *) current + sizeof(WSACMSGHDR);
487 /* Make sure there is at least enough room for this entry */
488 if (msgsize > *maxsize)
491 /* Fill in the entry */
492 current->cmsg_len = sizeof(WSACMSGHDR) + len;
493 current->cmsg_level = level;
494 current->cmsg_type = type;
495 memcpy(ptr, data, len);
496 /* Return the pointer to where next entry should go */
497 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
500 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
503 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
504 ULONG ctlsize = control->len;
505 struct cmsghdr *cmsg_unix;
508 /* Loop over all the headers, converting as appropriate */
509 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
511 switch(cmsg_unix->cmsg_level)
514 switch(cmsg_unix->cmsg_type)
518 /* Convert the Unix IP_PKTINFO structure to the Windows version */
519 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
520 struct WS_in_pktinfo data_win;
522 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
523 data_win.ipi_ifindex = data_unix->ipi_ifindex;
524 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
525 (void*)&data_win, sizeof(data_win));
526 if (!ptr) goto error;
529 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
534 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
540 /* Set the length of the returned control headers */
541 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
542 return (ptr != NULL);
543 #else /* IP_PKTINFO */
546 #endif /* IP_PKTINFO */
548 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
550 /* ----------------------------------- error handling */
552 static NTSTATUS sock_get_ntstatus( int err )
556 case EBADF: return STATUS_INVALID_HANDLE;
557 case EBUSY: return STATUS_DEVICE_BUSY;
559 case EACCES: return STATUS_ACCESS_DENIED;
560 case EFAULT: return STATUS_NO_MEMORY;
561 case EINVAL: return STATUS_INVALID_PARAMETER;
563 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
564 case EWOULDBLOCK: return STATUS_CANT_WAIT;
565 case EINPROGRESS: return STATUS_PENDING;
566 case EALREADY: return STATUS_NETWORK_BUSY;
567 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
568 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
569 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
570 case EPROTONOSUPPORT:
571 case ESOCKTNOSUPPORT:
574 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
575 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
576 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
577 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
578 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
579 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
580 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
581 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
582 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
583 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
584 case ENETDOWN: return STATUS_NETWORK_BUSY;
586 case ECONNRESET: return STATUS_CONNECTION_RESET;
587 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
589 case 0: return STATUS_SUCCESS;
591 WARN("Unknown errno %d!\n", err);
592 return STATUS_UNSUCCESSFUL;
596 static UINT sock_get_error( int err )
600 case EINTR: return WSAEINTR;
601 case EBADF: return WSAEBADF;
603 case EACCES: return WSAEACCES;
604 case EFAULT: return WSAEFAULT;
605 case EINVAL: return WSAEINVAL;
606 case EMFILE: return WSAEMFILE;
607 case EWOULDBLOCK: return WSAEWOULDBLOCK;
608 case EINPROGRESS: return WSAEINPROGRESS;
609 case EALREADY: return WSAEALREADY;
610 case ENOTSOCK: return WSAENOTSOCK;
611 case EDESTADDRREQ: return WSAEDESTADDRREQ;
612 case EMSGSIZE: return WSAEMSGSIZE;
613 case EPROTOTYPE: return WSAEPROTOTYPE;
614 case ENOPROTOOPT: return WSAENOPROTOOPT;
615 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
616 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
617 case EOPNOTSUPP: return WSAEOPNOTSUPP;
618 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
619 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
620 case EADDRINUSE: return WSAEADDRINUSE;
621 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
622 case ENETDOWN: return WSAENETDOWN;
623 case ENETUNREACH: return WSAENETUNREACH;
624 case ENETRESET: return WSAENETRESET;
625 case ECONNABORTED: return WSAECONNABORTED;
627 case ECONNRESET: return WSAECONNRESET;
628 case ENOBUFS: return WSAENOBUFS;
629 case EISCONN: return WSAEISCONN;
630 case ENOTCONN: return WSAENOTCONN;
631 case ESHUTDOWN: return WSAESHUTDOWN;
632 case ETOOMANYREFS: return WSAETOOMANYREFS;
633 case ETIMEDOUT: return WSAETIMEDOUT;
634 case ECONNREFUSED: return WSAECONNREFUSED;
635 case ELOOP: return WSAELOOP;
636 case ENAMETOOLONG: return WSAENAMETOOLONG;
637 case EHOSTDOWN: return WSAEHOSTDOWN;
638 case EHOSTUNREACH: return WSAEHOSTUNREACH;
639 case ENOTEMPTY: return WSAENOTEMPTY;
641 case EPROCLIM: return WSAEPROCLIM;
644 case EUSERS: return WSAEUSERS;
647 case EDQUOT: return WSAEDQUOT;
650 case ESTALE: return WSAESTALE;
653 case EREMOTE: return WSAEREMOTE;
656 /* just in case we ever get here and there are no problems */
659 WARN("Unknown errno %d!\n", err);
660 return WSAEOPNOTSUPP;
664 static UINT wsaErrno(void)
666 int loc_errno = errno;
667 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
669 return sock_get_error( loc_errno );
672 /* most ws2 overlapped functions return an ntstatus-based error code */
673 static NTSTATUS wsaErrStatus(void)
675 int loc_errno = errno;
676 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
678 return sock_get_ntstatus(loc_errno);
681 static UINT wsaHerrno(int loc_errno)
683 WARN("h_errno %d.\n", loc_errno);
687 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
688 case TRY_AGAIN: return WSATRY_AGAIN;
689 case NO_RECOVERY: return WSANO_RECOVERY;
690 case NO_DATA: return WSANO_DATA;
691 case ENOBUFS: return WSAENOBUFS;
695 WARN("Unknown h_errno %d!\n", loc_errno);
696 return WSAEOPNOTSUPP;
700 static inline DWORD NtStatusToWSAError( const DWORD status )
702 /* We only need to cover the status codes set by server async request handling */
706 case STATUS_SUCCESS: wserr = 0; break;
707 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
708 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
709 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
710 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
711 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
712 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
713 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
714 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
715 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
716 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
717 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
718 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
719 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
720 case STATUS_IO_TIMEOUT:
721 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
722 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
723 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
724 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
725 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
726 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
727 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
728 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
731 wserr = RtlNtStatusToDosError( status );
732 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
737 /* set last error code from NT status without mapping WSA errors */
738 static inline unsigned int set_error( unsigned int err )
742 err = NtStatusToWSAError( err );
748 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
751 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
756 static inline void release_sock_fd( SOCKET s, int fd )
758 wine_server_release_fd( SOCKET2HANDLE(s), fd );
761 static void _enable_event( HANDLE s, unsigned int event,
762 unsigned int sstate, unsigned int cstate )
764 SERVER_START_REQ( enable_socket_event )
766 req->handle = wine_server_obj_handle( s );
768 req->sstate = sstate;
769 req->cstate = cstate;
770 wine_server_call( req );
775 static int _is_blocking(SOCKET s)
778 SERVER_START_REQ( get_socket_event )
780 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
781 req->service = FALSE;
783 wine_server_call( req );
784 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
790 static unsigned int _get_sock_mask(SOCKET s)
793 SERVER_START_REQ( get_socket_event )
795 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
796 req->service = FALSE;
798 wine_server_call( req );
805 static void _sync_sock_state(SOCKET s)
807 /* do a dummy wineserver request in order to let
808 the wineserver run through its select loop once */
809 (void)_is_blocking(s);
812 static int _get_sock_error(SOCKET s, unsigned int bit)
814 int events[FD_MAX_EVENTS];
816 SERVER_START_REQ( get_socket_event )
818 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
819 req->service = FALSE;
821 wine_server_set_reply( req, events, sizeof(events) );
822 wine_server_call( req );
828 static struct per_thread_data *get_per_thread_data(void)
830 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
831 /* lazy initialization */
834 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
835 NtCurrentTeb()->WinSockData = ptb;
840 static void free_per_thread_data(void)
842 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
846 /* delete scratch buffers */
847 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
848 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
849 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
850 ptb->he_buffer = NULL;
851 ptb->se_buffer = NULL;
852 ptb->pe_buffer = NULL;
854 HeapFree( GetProcessHeap(), 0, ptb );
855 NtCurrentTeb()->WinSockData = NULL;
858 /***********************************************************************
859 * DllMain (WS2_32.init)
861 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
863 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
865 case DLL_PROCESS_ATTACH:
867 case DLL_PROCESS_DETACH:
868 free_per_thread_data();
871 case DLL_THREAD_DETACH:
872 free_per_thread_data();
878 /***********************************************************************
881 * Converts socket flags from Windows format.
882 * Return 1 if converted, 0 if not (error).
884 static int convert_sockopt(INT *level, INT *optname)
891 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
892 if( ws_sock_map[i][0] == *optname )
894 *optname = ws_sock_map[i][1];
898 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
901 *level = IPPROTO_TCP;
902 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
903 if ( ws_tcp_map[i][0] == *optname )
905 *optname = ws_tcp_map[i][1];
909 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
913 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
914 if (ws_ip_map[i][0] == *optname )
916 *optname = ws_ip_map[i][1];
920 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
922 case WS_IPPROTO_IPV6:
923 *level = IPPROTO_IPV6;
924 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
925 if (ws_ipv6_map[i][0] == *optname )
927 *optname = ws_ipv6_map[i][1];
931 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
933 default: FIXME("Unimplemented or unknown socket level\n");
938 /* ----------------------------------- Per-thread info (or per-process?) */
940 static char *strdup_lower(const char *str)
943 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
947 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
950 else SetLastError(WSAENOBUFS);
954 static inline int sock_error_p(int s)
956 unsigned int optval, optlen;
958 optlen = sizeof(optval);
959 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
960 if (optval) WARN("\t[%i] error: %d\n", s, optval);
964 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
965 * from an fd and return the value converted to milli seconds
966 * or -1 if there is an infinite time out */
967 static inline int get_rcvsnd_timeo( int fd, int optname)
970 unsigned int len = sizeof(tv);
971 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
973 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
974 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
979 /* macro wrappers for portability */
981 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
983 #define GET_RCVTIMEO(fd) (-1)
987 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
989 #define GET_SNDTIMEO(fd) (-1)
992 /* utility: given an fd, will block until one of the events occurs */
993 static inline int do_block( int fd, int events, int timeout )
1001 while ((ret = poll(&pfd, 1, timeout)) < 0)
1012 convert_af_w2u(int windowsaf) {
1015 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1016 if (ws_af_map[i][0] == windowsaf)
1017 return ws_af_map[i][1];
1018 FIXME("unhandled Windows address family %d\n", windowsaf);
1023 convert_af_u2w(int unixaf) {
1026 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1027 if (ws_af_map[i][1] == unixaf)
1028 return ws_af_map[i][0];
1029 FIXME("unhandled UNIX address family %d\n", unixaf);
1034 convert_proto_w2u(int windowsproto) {
1037 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1038 if (ws_proto_map[i][0] == windowsproto)
1039 return ws_proto_map[i][1];
1040 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1045 convert_proto_u2w(int unixproto) {
1048 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1049 if (ws_proto_map[i][1] == unixproto)
1050 return ws_proto_map[i][0];
1051 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1056 convert_socktype_w2u(int windowssocktype) {
1059 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1060 if (ws_socktype_map[i][0] == windowssocktype)
1061 return ws_socktype_map[i][1];
1062 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1067 convert_socktype_u2w(int unixsocktype) {
1070 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1071 if (ws_socktype_map[i][1] == unixsocktype)
1072 return ws_socktype_map[i][0];
1073 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1077 /* ----------------------------------- API -----
1079 * Init / cleanup / error checking.
1082 /***********************************************************************
1083 * WSAStartup (WS2_32.115)
1085 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1087 TRACE("verReq=%x\n", wVersionRequested);
1089 if (LOBYTE(wVersionRequested) < 1)
1090 return WSAVERNOTSUPPORTED;
1092 if (!lpWSAData) return WSAEINVAL;
1096 /* that's the whole of the negotiation for now */
1097 lpWSAData->wVersion = wVersionRequested;
1098 /* return winsock information */
1099 lpWSAData->wHighVersion = 0x0202;
1100 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1101 strcpy(lpWSAData->szSystemStatus, "Running" );
1102 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1103 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1104 /* don't do anything with lpWSAData->lpVendorInfo */
1105 /* (some apps don't allocate the space for this field) */
1107 TRACE("succeeded\n");
1112 /***********************************************************************
1113 * WSACleanup (WS2_32.116)
1115 INT WINAPI WSACleanup(void)
1121 SetLastError(WSANOTINITIALISED);
1122 return SOCKET_ERROR;
1126 /***********************************************************************
1127 * WSAGetLastError (WS2_32.111)
1129 INT WINAPI WSAGetLastError(void)
1131 return GetLastError();
1134 /***********************************************************************
1135 * WSASetLastError (WS2_32.112)
1137 void WINAPI WSASetLastError(INT iError) {
1138 SetLastError(iError);
1141 static struct WS_hostent *check_buffer_he(int size)
1143 struct per_thread_data * ptb = get_per_thread_data();
1146 if (ptb->he_len >= size ) return ptb->he_buffer;
1147 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1149 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1150 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1151 return ptb->he_buffer;
1154 static struct WS_servent *check_buffer_se(int size)
1156 struct per_thread_data * ptb = get_per_thread_data();
1159 if (ptb->se_len >= size ) return ptb->se_buffer;
1160 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1162 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1163 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1164 return ptb->se_buffer;
1167 static struct WS_protoent *check_buffer_pe(int size)
1169 struct per_thread_data * ptb = get_per_thread_data();
1172 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1173 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1175 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1176 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1177 return ptb->pe_buffer;
1180 /* ----------------------------------- i/o APIs */
1182 static inline BOOL supported_pf(int pf)
1203 /**********************************************************************/
1205 /* Returns the length of the converted address if successful, 0 if it was too small to
1208 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1209 union generic_unix_sockaddr *uaddr)
1211 unsigned int uaddrlen = 0;
1213 switch (wsaddr->sa_family)
1218 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1219 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1221 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1224 uaddrlen = sizeof(struct sockaddr_ipx);
1225 memset( uaddr, 0, uaddrlen );
1226 uipx->sipx_family=AF_IPX;
1227 uipx->sipx_port=wsipx->sa_socket;
1228 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1231 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1232 #ifdef IPX_FRAME_NONE
1233 uipx->sipx_type=IPX_FRAME_NONE;
1239 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1240 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1242 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1243 * scope_id, one without.
1245 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1246 uaddrlen = sizeof(struct sockaddr_in6);
1247 memset( uaddr, 0, uaddrlen );
1248 uin6->sin6_family = AF_INET6;
1249 uin6->sin6_port = win6->sin6_port;
1250 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1251 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1252 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1254 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1257 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1261 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1262 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1264 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1266 uaddrlen = sizeof(struct sockaddr_in);
1267 memset( uaddr, 0, uaddrlen );
1268 uin->sin_family = AF_INET;
1269 uin->sin_port = win->sin_port;
1270 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1275 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1276 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1278 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1280 uaddrlen = sizeof(struct sockaddr_irda);
1281 memset( uaddr, 0, uaddrlen );
1282 uin->sir_family = AF_IRDA;
1283 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1285 unsigned int lsap_sel = 0;
1287 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1288 uin->sir_lsap_sel = lsap_sel;
1292 uin->sir_lsap_sel = LSAP_ANY;
1293 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1295 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1299 case WS_AF_UNSPEC: {
1300 /* Try to determine the needed space by the passed windows sockaddr space */
1301 switch (wsaddrlen) {
1302 default: /* likely a ipv4 address */
1303 case sizeof(struct WS_sockaddr_in):
1304 uaddrlen = sizeof(struct sockaddr_in);
1307 case sizeof(struct WS_sockaddr_ipx):
1308 uaddrlen = sizeof(struct sockaddr_ipx);
1312 case sizeof(SOCKADDR_IRDA):
1313 uaddrlen = sizeof(struct sockaddr_irda);
1316 case sizeof(struct WS_sockaddr_in6):
1317 case sizeof(struct WS_sockaddr_in6_old):
1318 uaddrlen = sizeof(struct sockaddr_in6);
1321 memset( uaddr, 0, uaddrlen );
1325 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1331 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1333 switch (uaddr->sa_family)
1337 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
1342 static const struct sockaddr_in6 emptyAddr;
1343 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1344 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1348 static const struct sockaddr_in emptyAddr;
1349 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1350 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1355 FIXME("unknown address family %d\n", uaddr->sa_family);
1360 /* Returns 0 if successful, -1 if the buffer is too small */
1361 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1365 switch(uaddr->sa_family)
1370 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1371 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1374 switch (*wsaddrlen) /* how much can we copy? */
1378 *wsaddrlen = sizeof(*wsipx);
1379 wsipx->sa_socket=uipx->sipx_port;
1383 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1391 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1397 wsipx->sa_family=WS_AF_IPX;
1409 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1410 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1412 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1414 win->irdaAddressFamily = WS_AF_IRDA;
1415 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1416 if (uin->sir_lsap_sel != LSAP_ANY)
1417 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1419 memcpy( win->irdaServiceName, uin->sir_name,
1420 sizeof(win->irdaServiceName) );
1425 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1426 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1428 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1430 win6old->sin6_family = WS_AF_INET6;
1431 win6old->sin6_port = uin6->sin6_port;
1432 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1433 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1434 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1435 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1436 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1437 win6->sin6_scope_id = uin6->sin6_scope_id;
1438 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1441 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1443 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1448 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1449 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1451 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1453 win->sin_family = WS_AF_INET;
1454 win->sin_port = uin->sin_port;
1455 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1456 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1457 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1461 memset(wsaddr,0,*wsaddrlen);
1465 FIXME("Unknown address family %d\n", uaddr->sa_family);
1471 /**************************************************************************
1472 * Functions for handling overlapped I/O
1473 **************************************************************************/
1475 /* user APC called upon async completion */
1476 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1478 ws2_async *wsa = arg;
1480 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1481 iosb->Information, wsa->user_overlapped,
1483 HeapFree( GetProcessHeap(), 0, wsa );
1486 /***********************************************************************
1487 * WS2_recv (INTERNAL)
1489 * Workhorse for both synchronous and asynchronous recv() operations.
1491 static int WS2_recv( int fd, struct ws2_async *wsa )
1493 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1497 union generic_unix_sockaddr unix_sockaddr;
1500 hdr.msg_name = NULL;
1504 hdr.msg_namelen = sizeof(unix_sockaddr);
1505 hdr.msg_name = &unix_sockaddr;
1508 hdr.msg_namelen = 0;
1510 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1511 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1512 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1513 hdr.msg_accrights = NULL;
1514 hdr.msg_accrightslen = 0;
1516 hdr.msg_control = pktbuf;
1517 hdr.msg_controllen = sizeof(pktbuf);
1521 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1524 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1527 ERR("Message control headers cannot be properly supported on this system.\n");
1528 wsa->control->len = 0;
1531 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
1533 WARN("Application passed insufficient room for control headers.\n");
1534 *wsa->lpFlags |= WS_MSG_CTRUNC;
1540 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1541 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1543 * quoting linux 2.6 net/ipv4/tcp.c:
1544 * "According to UNIX98, msg_name/msg_namelen are ignored
1545 * on connected socket. I was just happy when found this 8) --ANK"
1547 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1548 * connection-oriented sockets, so don't try to update lpFrom.
1550 if (wsa->addr && hdr.msg_namelen)
1551 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1556 /***********************************************************************
1557 * WS2_async_recv (INTERNAL)
1559 * Handler for overlapped recv() operations.
1561 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1563 ws2_async* wsa = user;
1568 case STATUS_ALERTED:
1569 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1572 result = WS2_recv( fd, wsa );
1573 wine_server_release_fd( wsa->hSocket, fd );
1576 status = STATUS_SUCCESS;
1577 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1581 if (errno == EINTR || errno == EAGAIN)
1583 status = STATUS_PENDING;
1584 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1589 status = wsaErrStatus();
1594 if (status != STATUS_PENDING)
1596 iosb->u.Status = status;
1597 iosb->Information = result;
1598 *apc = ws2_async_apc;
1603 /* user APC called upon async accept completion */
1604 static void WINAPI ws2_async_accept_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1606 struct ws2_accept_async *wsa = arg;
1608 HeapFree( GetProcessHeap(), 0, wsa->read );
1609 HeapFree( GetProcessHeap(), 0, wsa );
1612 /***********************************************************************
1613 * WS2_async_accept_recv (INTERNAL)
1615 * This function is used to finish the read part of an accept request. It is
1616 * needed to place the completion on the correct socket (listener).
1618 static NTSTATUS WS2_async_accept_recv( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
1621 struct ws2_accept_async *wsa = arg;
1623 status = WS2_async_recv( wsa->read, iosb, status, &junk );
1624 if (status == STATUS_PENDING)
1627 if (wsa->user_overlapped->hEvent)
1628 SetEvent(wsa->user_overlapped->hEvent);
1630 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
1632 *apc = ws2_async_accept_apc;
1636 /***********************************************************************
1637 * WS2_async_accept (INTERNAL)
1639 * This is the function called to satisfy the AcceptEx callback
1641 static NTSTATUS WS2_async_accept( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
1643 struct ws2_accept_async *wsa = arg;
1647 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
1649 if (status == STATUS_ALERTED)
1651 SERVER_START_REQ( accept_into_socket )
1653 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
1654 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
1655 status = wine_server_call( req );
1659 if (status == STATUS_CANT_WAIT)
1660 return STATUS_PENDING;
1662 if (status == STATUS_INVALID_HANDLE)
1664 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
1665 status = STATUS_CANCELLED;
1668 else if (status == STATUS_HANDLES_CLOSED)
1669 status = STATUS_CANCELLED; /* strange windows behavior */
1671 if (status != STATUS_SUCCESS)
1674 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
1675 addr = ((char *)wsa->buf) + wsa->data_len;
1676 len = wsa->local_len - sizeof(int);
1677 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
1678 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
1681 addr += wsa->local_len;
1682 len = wsa->remote_len - sizeof(int);
1683 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
1684 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
1690 SERVER_START_REQ( register_async )
1692 req->type = ASYNC_TYPE_READ;
1693 req->async.handle = wine_server_obj_handle( wsa->accept_socket );
1694 req->async.callback = wine_server_client_ptr( WS2_async_accept_recv );
1695 req->async.iosb = wine_server_client_ptr( iosb );
1696 req->async.arg = wine_server_client_ptr( wsa );
1697 status = wine_server_call( req );
1701 if (status != STATUS_PENDING)
1704 return STATUS_SUCCESS;
1707 iosb->u.Status = status;
1708 iosb->Information = 0;
1710 if (wsa->user_overlapped->hEvent)
1711 SetEvent(wsa->user_overlapped->hEvent);
1713 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
1715 *apc = ws2_async_accept_apc;
1719 /***********************************************************************
1720 * WS2_send (INTERNAL)
1722 * Workhorse for both synchronous and asynchronous send() operations.
1724 static int WS2_send( int fd, struct ws2_async *wsa )
1727 union generic_unix_sockaddr unix_addr;
1730 hdr.msg_name = NULL;
1731 hdr.msg_namelen = 0;
1735 hdr.msg_name = &unix_addr;
1736 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
1737 if ( !hdr.msg_namelen )
1743 #if defined(HAVE_IPX) && defined(SOL_IPX)
1744 if(wsa->addr->sa_family == WS_AF_IPX)
1746 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1748 unsigned int len=sizeof(int);
1750 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1751 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1752 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1753 * ipx type in the sockaddr_opx structure with the stored value.
1755 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1756 uipx->sipx_type = val;
1761 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1762 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1763 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1764 hdr.msg_accrights = NULL;
1765 hdr.msg_accrightslen = 0;
1767 hdr.msg_control = NULL;
1768 hdr.msg_controllen = 0;
1772 ret = sendmsg(fd, &hdr, wsa->flags);
1776 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
1777 n -= wsa->iovec[wsa->first_iovec++].iov_len;
1778 if (wsa->first_iovec < wsa->n_iovecs)
1780 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
1781 wsa->iovec[wsa->first_iovec].iov_len -= n;
1787 /***********************************************************************
1788 * WS2_async_send (INTERNAL)
1790 * Handler for overlapped send() operations.
1792 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1794 ws2_async* wsa = user;
1799 case STATUS_ALERTED:
1800 if ( wsa->n_iovecs <= wsa->first_iovec )
1803 status = STATUS_SUCCESS;
1806 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1809 /* check to see if the data is ready (non-blocking) */
1810 result = WS2_send( fd, wsa );
1811 wine_server_release_fd( wsa->hSocket, fd );
1815 if (wsa->first_iovec < wsa->n_iovecs)
1816 status = STATUS_PENDING;
1818 status = STATUS_SUCCESS;
1820 iosb->Information += result;
1822 else if (errno == EINTR || errno == EAGAIN)
1824 status = STATUS_PENDING;
1828 status = wsaErrStatus();
1832 if (status != STATUS_PENDING)
1834 iosb->u.Status = status;
1835 *apc = ws2_async_apc;
1840 /***********************************************************************
1841 * WS2_async_shutdown (INTERNAL)
1843 * Handler for shutdown() operations on overlapped sockets.
1845 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
1847 ws2_async* wsa = user;
1852 case STATUS_ALERTED:
1853 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1856 switch ( wsa->type )
1858 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1859 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1861 status = err ? wsaErrStatus() : STATUS_SUCCESS;
1862 wine_server_release_fd( wsa->hSocket, fd );
1865 iosb->u.Status = status;
1866 iosb->Information = 0;
1867 *apc = ws2_async_apc;
1871 /***********************************************************************
1872 * WS2_register_async_shutdown (INTERNAL)
1874 * Helper function for WS_shutdown() on overlapped sockets.
1876 static int WS2_register_async_shutdown( SOCKET s, int type )
1878 struct ws2_async *wsa;
1881 TRACE("s %ld type %d\n", s, type);
1883 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1887 wsa->hSocket = SOCKET2HANDLE(s);
1889 wsa->completion_func = NULL;
1891 SERVER_START_REQ( register_async )
1894 req->async.handle = wine_server_obj_handle( wsa->hSocket );
1895 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
1896 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
1897 req->async.arg = wine_server_client_ptr( wsa );
1898 req->async.cvalue = 0;
1899 status = wine_server_call( req );
1903 if (status != STATUS_PENDING)
1905 HeapFree( GetProcessHeap(), 0, wsa );
1906 return NtStatusToWSAError( status );
1911 /***********************************************************************
1914 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1921 TRACE("socket %04lx\n", s );
1922 is_blocking = _is_blocking(s);
1925 /* try accepting first (if there is a deferred connection) */
1926 SERVER_START_REQ( accept_socket )
1928 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1929 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1930 req->attributes = OBJ_INHERIT;
1931 status = wine_server_call( req );
1932 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
1937 if (addr) WS_getpeername(as, addr, addrlen32);
1940 if (is_blocking && status == STATUS_CANT_WAIT)
1942 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1944 do_block(fd, POLLIN, -1);
1945 _sync_sock_state(s); /* let wineserver notice connection */
1946 release_sock_fd( s, fd );
1948 } while (is_blocking && status == STATUS_CANT_WAIT);
1951 return INVALID_SOCKET;
1954 /***********************************************************************
1957 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
1958 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
1959 LPOVERLAPPED overlapped)
1962 struct ws2_accept_async *wsa;
1964 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
1966 TRACE("(%lx, %lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
1967 rem_addr_len, received, overlapped);
1971 SetLastError(WSAEINVAL);
1977 SetLastError(WSA_INVALID_PARAMETER);
1981 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
1984 SetLastError(WSAENOTSOCK);
1987 release_sock_fd( listener, fd );
1989 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
1992 SetLastError(WSAEINVAL);
1995 release_sock_fd( acceptor, fd );
1997 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
2000 SetLastError(WSAEFAULT);
2004 wsa->listen_socket = SOCKET2HANDLE(listener);
2005 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2006 wsa->user_overlapped = overlapped;
2007 wsa->cvalue = cvalue;
2009 wsa->data_len = dest_len;
2010 wsa->local_len = local_addr_len;
2011 wsa->remote_len = rem_addr_len;
2016 /* set up a read request if we need it */
2017 wsa->read = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[1]) );
2020 HeapFree( GetProcessHeap(), 0, wsa );
2021 SetLastError(WSAEFAULT);
2025 wsa->read->hSocket = wsa->accept_socket;
2026 wsa->read->flags = 0;
2027 wsa->read->lpFlags = &wsa->read->flags;
2028 wsa->read->addr = NULL;
2029 wsa->read->addrlen.ptr = NULL;
2030 wsa->read->control = NULL;
2031 wsa->read->n_iovecs = 1;
2032 wsa->read->first_iovec = 0;
2033 wsa->read->iovec[0].iov_base = wsa->buf;
2034 wsa->read->iovec[0].iov_len = wsa->data_len;
2037 SERVER_START_REQ( register_async )
2039 req->type = ASYNC_TYPE_READ;
2040 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2041 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2042 req->async.iosb = wine_server_client_ptr( overlapped );
2043 req->async.arg = wine_server_client_ptr( wsa );
2044 /* We don't set event or completion since we may also have to read */
2045 status = wine_server_call( req );
2049 if(status != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
2051 SetLastError( NtStatusToWSAError(status) );
2055 /***********************************************************************
2056 * GetAcceptExSockaddrs
2058 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2059 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2060 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2062 char *cbuf = buffer;
2063 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2064 local_addr_len, remote_addr, remote_addr_len );
2067 *local_addr_len = *(int *) cbuf;
2068 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2072 *remote_addr_len = *(int *) cbuf;
2073 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2076 /***********************************************************************
2079 * Perform a receive operation that is capable of returning message
2080 * control headers. It is important to note that the WSAMSG parameter
2081 * must remain valid throughout the operation, even when an overlapped
2082 * receive is performed.
2084 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2085 LPWSAOVERLAPPED lpOverlapped,
2086 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2090 SetLastError( WSAEFAULT );
2091 return SOCKET_ERROR;
2094 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2095 &msg->dwFlags, msg->name, &msg->namelen,
2096 lpOverlapped, lpCompletionRoutine, &msg->Control );
2099 /***********************************************************************
2102 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2104 int fd = get_sock_fd( s, 0, NULL );
2105 int res = SOCKET_ERROR;
2107 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2111 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2113 SetLastError(WSAEAFNOSUPPORT);
2117 union generic_unix_sockaddr uaddr;
2118 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2121 SetLastError(WSAEFAULT);
2126 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2127 if (name->sa_family == WS_AF_INET6 &&
2128 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2131 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2133 release_sock_fd( s, fd );
2134 SetLastError(WSAEAFNOSUPPORT);
2135 return SOCKET_ERROR;
2139 if (name->sa_family == WS_AF_INET)
2141 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2142 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2144 /* Trying to bind to the default host interface, using
2145 * INADDR_ANY instead*/
2146 WARN("Trying to bind to magic IP address, using "
2147 "INADDR_ANY instead.\n");
2148 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
2151 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2153 int loc_errno = errno;
2154 WARN("\tfailure - errno = %i\n", errno);
2159 SetLastError(WSAENOTSOCK);
2162 SetLastError(WSAEINVAL);
2165 SetLastError(wsaErrno());
2171 res=0; /* success */
2175 release_sock_fd( s, fd );
2180 /***********************************************************************
2181 * closesocket (WS2_32.3)
2183 int WINAPI WS_closesocket(SOCKET s)
2185 TRACE("socket %04lx\n", s);
2186 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
2187 return SOCKET_ERROR;
2190 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2192 union generic_unix_sockaddr uaddr;
2193 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2198 if (name->sa_family == WS_AF_INET)
2200 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2201 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2203 /* Trying to connect to magic replace-loopback address,
2204 * assuming we really want to connect to localhost */
2205 TRACE("Trying to connect to magic IP address, using "
2206 "INADDR_LOOPBACK instead.\n");
2207 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
2211 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
2217 /***********************************************************************
2218 * connect (WS2_32.4)
2220 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
2222 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2224 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2228 int ret = do_connect(fd, name, namelen);
2230 goto connect_success;
2232 if (ret == WSAEINPROGRESS)
2234 /* tell wineserver that a connection is in progress */
2235 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2237 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2238 if (_is_blocking(s))
2242 do_block(fd, POLLIN | POLLOUT, -1);
2243 _sync_sock_state(s); /* let wineserver notice connection */
2244 /* retrieve any error codes from it */
2245 result = _get_sock_error(s, FD_CONNECT_BIT);
2247 SetLastError(NtStatusToWSAError(result));
2250 goto connect_success;
2255 SetLastError(WSAEWOULDBLOCK);
2262 release_sock_fd( s, fd );
2264 return SOCKET_ERROR;
2267 release_sock_fd( s, fd );
2268 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2269 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2270 FD_CONNECT|FD_WINE_LISTENING);
2274 /***********************************************************************
2275 * WSAConnect (WS2_32.30)
2277 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
2278 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
2279 LPQOS lpSQOS, LPQOS lpGQOS )
2281 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
2282 FIXME("unsupported parameters!\n");
2283 return WS_connect( s, name, namelen );
2286 /***********************************************************************
2289 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
2290 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
2292 int fd, ret, status;
2296 SetLastError( ERROR_INVALID_PARAMETER );
2300 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2303 SetLastError( WSAENOTSOCK );
2307 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
2308 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
2310 /* FIXME: technically the socket has to be bound */
2311 ret = do_connect(fd, name, namelen);
2316 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2317 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2318 FD_CONNECT|FD_WINE_LISTENING);
2320 wsabuf.len = sendBufLen;
2321 wsabuf.buf = (char*) sendBuf;
2323 /* WSASend takes care of completion if need be */
2324 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
2325 goto connection_success;
2327 else if (ret == WSAEINPROGRESS)
2329 struct ws2_async *wsa;
2330 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
2332 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2334 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2336 /* Indirectly call WSASend */
2337 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) )))
2339 SetLastError(WSAEFAULT);
2343 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
2344 iosb->u.Status = STATUS_PENDING;
2345 iosb->Information = 0;
2347 wsa->hSocket = SOCKET2HANDLE(s);
2349 wsa->addrlen.val = 0;
2351 wsa->lpFlags = &wsa->flags;
2352 wsa->control = NULL;
2353 wsa->n_iovecs = sendBuf ? 1 : 0;
2354 wsa->first_iovec = 0;
2355 wsa->completion_func = NULL;
2356 wsa->iovec[0].iov_base = sendBuf;
2357 wsa->iovec[0].iov_len = sendBufLen;
2359 SERVER_START_REQ( register_async )
2361 req->type = ASYNC_TYPE_WRITE;
2362 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2363 req->async.callback = wine_server_client_ptr( WS2_async_send );
2364 req->async.iosb = wine_server_client_ptr( iosb );
2365 req->async.arg = wine_server_client_ptr( wsa );
2366 req->async.event = wine_server_obj_handle( ov->hEvent );
2367 req->async.cvalue = cvalue;
2368 status = wine_server_call( req );
2372 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
2374 /* If the connect already failed */
2375 if (status == STATUS_PIPE_DISCONNECTED)
2376 status = _get_sock_error(s, FD_CONNECT_BIT);
2377 SetLastError( NtStatusToWSAError(status) );
2385 release_sock_fd( s, fd );
2389 release_sock_fd( s, fd );
2394 /***********************************************************************
2395 * getpeername (WS2_32.5)
2397 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
2402 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen?*namelen:0);
2404 fd = get_sock_fd( s, 0, NULL );
2409 union generic_unix_sockaddr uaddr;
2410 unsigned int uaddrlen = sizeof(uaddr);
2412 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
2414 if (!name || !namelen)
2415 SetLastError(WSAEFAULT);
2416 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2417 /* The buffer was too small */
2418 SetLastError(WSAEFAULT);
2423 SetLastError(wsaErrno());
2424 release_sock_fd( s, fd );
2429 /***********************************************************************
2430 * getsockname (WS2_32.6)
2432 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
2437 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
2439 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
2440 if( (name == NULL) || (namelen == NULL) )
2442 SetLastError( WSAEFAULT );
2443 return SOCKET_ERROR;
2446 fd = get_sock_fd( s, 0, NULL );
2451 union generic_unix_sockaddr uaddr;
2452 unsigned int uaddrlen = sizeof(uaddr);
2454 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2456 SetLastError(wsaErrno());
2458 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2460 SetLastError(WSAEINVAL);
2462 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2464 /* The buffer was too small */
2465 SetLastError(WSAEFAULT);
2471 release_sock_fd( s, fd );
2476 /***********************************************************************
2477 * getsockopt (WS2_32.7)
2479 INT WINAPI WS_getsockopt(SOCKET s, INT level,
2480 INT optname, char *optval, INT *optlen)
2485 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2486 s, level, optname, optval, *optlen);
2494 /* Handle common cases. The special cases are below, sorted
2496 case WS_SO_ACCEPTCONN:
2497 case WS_SO_BROADCAST:
2500 case WS_SO_KEEPALIVE:
2501 case WS_SO_OOBINLINE:
2503 case WS_SO_REUSEADDR:
2506 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2507 return SOCKET_ERROR;
2508 convert_sockopt(&level, &optname);
2509 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2511 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2514 release_sock_fd( s, fd );
2517 case WS_SO_DONTLINGER:
2519 struct linger lingval;
2520 unsigned int len = sizeof(struct linger);
2522 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
2524 SetLastError(WSAEFAULT);
2525 return SOCKET_ERROR;
2527 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2528 return SOCKET_ERROR;
2530 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
2532 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2537 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
2538 *optlen = sizeof(BOOL);
2541 release_sock_fd( s, fd );
2545 case WS_SO_CONNECT_TIME:
2547 static int pretendtime = 0;
2549 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
2550 if (!optlen || *optlen < sizeof(DWORD) || !optval)
2552 SetLastError(WSAEFAULT);
2553 return SOCKET_ERROR;
2555 *(DWORD*)optval = pretendtime++;
2556 *optlen = sizeof(DWORD);
2559 /* As mentioned in setsockopt, Windows ignores this, so we
2560 * always return true here */
2561 case WS_SO_DONTROUTE:
2562 if (!optlen || *optlen < sizeof(BOOL) || !optval)
2564 SetLastError(WSAEFAULT);
2565 return SOCKET_ERROR;
2567 *(BOOL *)optval = TRUE;
2568 *optlen = sizeof(BOOL);
2573 struct linger lingval;
2574 unsigned int len = sizeof(struct linger);
2576 /* struct linger and LINGER have different sizes */
2577 if (!optlen || *optlen < sizeof(LINGER) || !optval)
2579 SetLastError(WSAEFAULT);
2580 return SOCKET_ERROR;
2582 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2583 return SOCKET_ERROR;
2585 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
2587 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2592 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
2593 ((LINGER *)optval)->l_linger = lingval.l_linger;
2594 *optlen = sizeof(struct linger);
2597 release_sock_fd( s, fd );
2601 case WS_SO_MAX_MSG_SIZE:
2602 if (!optlen || *optlen < sizeof(int) || !optval)
2604 SetLastError(WSAEFAULT);
2605 return SOCKET_ERROR;
2607 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
2608 *(int *)optval = 65507;
2609 *optlen = sizeof(int);
2612 /* SO_OPENTYPE does not require a valid socket handle. */
2613 case WS_SO_OPENTYPE:
2614 if (!optlen || *optlen < sizeof(int) || !optval)
2616 SetLastError(WSAEFAULT);
2617 return SOCKET_ERROR;
2619 *(int *)optval = get_per_thread_data()->opentype;
2620 *optlen = sizeof(int);
2621 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2625 case WS_SO_RCVTIMEO:
2628 case WS_SO_SNDTIMEO:
2630 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
2633 unsigned int len = sizeof(struct timeval);
2635 if (!optlen || *optlen < sizeof(int)|| !optval)
2637 SetLastError(WSAEFAULT);
2638 return SOCKET_ERROR;
2640 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2641 return SOCKET_ERROR;
2643 convert_sockopt(&level, &optname);
2644 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
2646 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2651 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
2652 *optlen = sizeof(int);
2655 release_sock_fd( s, fd );
2660 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
2661 SetLastError(WSAENOPROTOOPT);
2662 return SOCKET_ERROR;
2663 } /* end switch(optname) */
2664 }/* end case WS_SOL_SOCKET */
2668 struct WS_sockaddr_ipx addr;
2669 IPX_ADDRESS_DATA *data;
2674 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
2676 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
2683 socklen_t len=sizeof(struct ipx);
2684 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
2687 *optval = (int)val.ipx_pt;
2690 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
2691 release_sock_fd( s, fd );
2696 * On a Win2000 system with one network card there are usually
2697 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
2698 * Using this call you can then retrieve info about this all.
2699 * In case of Linux it is a bit different. Usually you have
2700 * only "one" device active and further it is not possible to
2701 * query things like the linkspeed.
2703 FIXME("IPX_ADDRESS\n");
2704 namelen = sizeof(struct WS_sockaddr_ipx);
2705 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
2706 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
2708 data = (IPX_ADDRESS_DATA*)optval;
2709 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
2710 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
2711 data->adapternum = 0;
2712 data->wan = FALSE; /* We are not on a wan for now .. */
2713 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
2714 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
2715 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
2716 * note 1MB = 1000kB in this case */
2719 case IPX_MAX_ADAPTER_NUM:
2720 FIXME("IPX_MAX_ADAPTER_NUM\n");
2721 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
2725 FIXME("IPX optname:%x\n", optname);
2726 return SOCKET_ERROR;
2727 }/* end switch(optname) */
2728 } /* end case NSPROTO_IPX */
2735 case WS_IRLMP_ENUMDEVICES:
2737 static const int MAX_IRDA_DEVICES = 10;
2738 char buf[sizeof(struct irda_device_list) +
2739 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
2741 socklen_t len = sizeof(buf);
2743 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2744 return SOCKET_ERROR;
2745 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
2748 SetLastError(wsaErrno());
2749 return SOCKET_ERROR;
2753 struct irda_device_list *src = (struct irda_device_list *)buf;
2754 DEVICELIST *dst = (DEVICELIST *)optval;
2755 INT needed = sizeof(DEVICELIST), i;
2758 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
2759 if (*optlen < needed)
2761 SetLastError(WSAEFAULT);
2762 return SOCKET_ERROR;
2765 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
2766 dst->numDevice = src->len;
2767 for (i = 0; i < src->len; i++)
2769 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
2770 src->dev[i].saddr, src->dev[i].daddr,
2771 src->dev[i].info, src->dev[i].hints[0],
2772 src->dev[i].hints[1]);
2773 memcpy( dst->Device[i].irdaDeviceID,
2775 sizeof(dst->Device[i].irdaDeviceID) ) ;
2776 memcpy( dst->Device[i].irdaDeviceName,
2778 sizeof(dst->Device[i].irdaDeviceName) ) ;
2779 memcpy( &dst->Device[i].irdaDeviceHints1,
2780 &src->dev[i].hints[0],
2781 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
2782 memcpy( &dst->Device[i].irdaDeviceHints2,
2783 &src->dev[i].hints[1],
2784 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
2785 dst->Device[i].irdaCharSet = src->dev[i].charset;
2791 FIXME("IrDA optname:0x%x\n", optname);
2792 return SOCKET_ERROR;
2794 break; /* case WS_SOL_IRLMP */
2797 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
2798 case WS_IPPROTO_TCP:
2801 case WS_TCP_NODELAY:
2802 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2803 return SOCKET_ERROR;
2804 convert_sockopt(&level, &optname);
2805 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2807 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2810 release_sock_fd( s, fd );
2813 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
2814 return SOCKET_ERROR;
2819 case WS_IP_ADD_MEMBERSHIP:
2820 case WS_IP_DROP_MEMBERSHIP:
2824 case WS_IP_MULTICAST_IF:
2825 case WS_IP_MULTICAST_LOOP:
2826 case WS_IP_MULTICAST_TTL:
2833 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2834 return SOCKET_ERROR;
2835 convert_sockopt(&level, &optname);
2836 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2838 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2841 release_sock_fd( s, fd );
2843 case WS_IP_DONTFRAGMENT:
2844 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
2845 *(BOOL*)optval = FALSE;
2848 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
2849 return SOCKET_ERROR;
2851 case WS_IPPROTO_IPV6:
2854 #ifdef IPV6_ADD_MEMBERSHIP
2855 case WS_IPV6_ADD_MEMBERSHIP:
2857 #ifdef IPV6_DROP_MEMBERSHIP
2858 case WS_IPV6_DROP_MEMBERSHIP:
2860 case WS_IPV6_MULTICAST_IF:
2861 case WS_IPV6_MULTICAST_HOPS:
2862 case WS_IPV6_MULTICAST_LOOP:
2863 case WS_IPV6_UNICAST_HOPS:
2864 case WS_IPV6_V6ONLY:
2865 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2866 return SOCKET_ERROR;
2867 convert_sockopt(&level, &optname);
2868 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2870 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2873 release_sock_fd( s, fd );
2875 case WS_IPV6_DONTFRAG:
2876 FIXME("WS_IPV6_DONTFRAG is always false!\n");
2877 *(BOOL*)optval = FALSE;
2880 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
2881 return SOCKET_ERROR;
2884 WARN("Unknown level: 0x%08x\n", level);
2885 SetLastError(WSAEINVAL);
2886 return SOCKET_ERROR;
2887 } /* end switch(level) */
2890 /***********************************************************************
2893 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
2895 return htonl(hostlong);
2899 /***********************************************************************
2902 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
2904 return htons(hostshort);
2907 /***********************************************************************
2908 * WSAHtonl (WS2_32.46)
2909 * From MSDN description of error codes, this function should also
2910 * check if WinSock has been initialized and the socket is a valid
2911 * socket. But why? This function only translates a host byte order
2912 * u_long into a network byte order u_long...
2914 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
2918 *lpnetlong = htonl(hostlong);
2921 WSASetLastError(WSAEFAULT);
2922 return SOCKET_ERROR;
2925 /***********************************************************************
2926 * WSAHtons (WS2_32.47)
2927 * From MSDN description of error codes, this function should also
2928 * check if WinSock has been initialized and the socket is a valid
2929 * socket. But why? This function only translates a host byte order
2930 * u_short into a network byte order u_short...
2932 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2937 *lpnetshort = htons(hostshort);
2940 WSASetLastError(WSAEFAULT);
2941 return SOCKET_ERROR;
2945 /***********************************************************************
2946 * inet_addr (WS2_32.11)
2948 WS_u_long WINAPI WS_inet_addr(const char *cp)
2950 if (!cp) return INADDR_NONE;
2951 return inet_addr(cp);
2955 /***********************************************************************
2958 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2960 return ntohl(netlong);
2964 /***********************************************************************
2967 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2969 return ntohs(netshort);
2973 /***********************************************************************
2974 * inet_ntoa (WS2_32.12)
2976 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2978 /* use "buffer for dummies" here because some applications have a
2979 * propensity to decode addresses in ws_hostent structure without
2980 * saving them first...
2982 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2984 char* s = inet_ntoa(*((struct in_addr*)&in));
2990 SetLastError(wsaErrno());
2994 static const char *debugstr_wsaioctl(DWORD ioctl)
2996 const char *buf_type, *family;
2998 switch(ioctl & 0x18000000)
3003 case WS_IOC_PROTOCOL:
3004 family = "IOC_PROTOCOL";
3007 family = "IOC_VENDOR";
3009 default: /* WS_IOC_UNIX */
3011 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
3012 char x = (ioctl & 0xff00) >> 8;
3013 BYTE y = ioctl & 0xff;
3016 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3020 sprintf(args, "%d, %d", x, y);
3024 sprintf(args, "'%c', %d, %d", x, y, size);
3028 sprintf(args, "'%c', %d, %d", x, y, size);
3032 sprintf(args, "'%c', %d, %d", x, y, size);
3035 return wine_dbg_sprintf("%s(%s)", buf_type, args);
3039 /* We are different from WS_IOC_UNIX. */
3040 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3043 buf_type = "_WSAIO";
3046 buf_type = "_WSAIORW";
3049 buf_type = "_WSAIOW";
3052 buf_type = "_WSAIOR";
3059 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
3060 (USHORT)(ioctl & 0xffff));
3063 /**********************************************************************
3064 * WSAIoctl (WS2_32.50)
3067 INT WINAPI WSAIoctl(SOCKET s,
3068 DWORD dwIoControlCode,
3071 LPVOID lpbOutBuffer,
3073 LPDWORD lpcbBytesReturned,
3074 LPWSAOVERLAPPED lpOverlapped,
3075 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
3077 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
3078 s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpbOutBuffer,
3079 cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
3081 switch( dwIoControlCode )
3084 if (cbInBuffer != sizeof(WS_u_long)) {
3085 WSASetLastError(WSAEFAULT);
3086 return SOCKET_ERROR;
3088 return WS_ioctlsocket( s, WS_FIONBIO, lpvInBuffer);
3091 if (cbOutBuffer != sizeof(WS_u_long)) {
3092 WSASetLastError(WSAEFAULT);
3093 return SOCKET_ERROR;
3095 return WS_ioctlsocket( s, WS_FIONREAD, lpbOutBuffer);
3097 case WS_SIO_GET_INTERFACE_LIST:
3099 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
3100 DWORD size, numInt, apiReturn;
3103 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
3107 WSASetLastError(WSAEFAULT);
3108 return SOCKET_ERROR;
3110 if (!lpcbBytesReturned)
3112 WSASetLastError(WSAEFAULT);
3113 return SOCKET_ERROR;
3116 fd = get_sock_fd( s, 0, NULL );
3117 if (fd == -1) return SOCKET_ERROR;
3119 apiReturn = GetAdaptersInfo(NULL, &size);
3120 if (apiReturn == ERROR_NO_DATA)
3124 else if (apiReturn == ERROR_BUFFER_OVERFLOW)
3126 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
3130 if (GetAdaptersInfo(table, &size) == NO_ERROR)
3132 PIP_ADAPTER_INFO ptr;
3134 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > cbOutBuffer)
3136 WARN("Buffer too small = %u, cbOutBuffer = %u\n", size, cbOutBuffer);
3137 HeapFree(GetProcessHeap(),0,table);
3138 release_sock_fd( s, fd );
3139 WSASetLastError(WSAEFAULT);
3140 return SOCKET_ERROR;
3142 for (ptr = table, numInt = 0; ptr;
3143 ptr = ptr->Next, intArray++, numInt++)
3145 unsigned int addr, mask, bcast;
3146 struct ifreq ifInfo;
3148 /* Socket Status Flags */
3149 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
3150 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
3152 ERR("Error obtaining status flags for socket!\n");
3153 HeapFree(GetProcessHeap(),0,table);
3154 release_sock_fd( s, fd );
3155 WSASetLastError(WSAEINVAL);
3156 return SOCKET_ERROR;
3160 /* set flags; the values of IFF_* are not the same
3161 under Linux and Windows, therefore must generate
3163 intArray->iiFlags = 0;
3164 if (ifInfo.ifr_flags & IFF_BROADCAST)
3165 intArray->iiFlags |= WS_IFF_BROADCAST;
3166 #ifdef IFF_POINTOPOINT
3167 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
3168 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
3170 if (ifInfo.ifr_flags & IFF_LOOPBACK)
3171 intArray->iiFlags |= WS_IFF_LOOPBACK;
3172 if (ifInfo.ifr_flags & IFF_UP)
3173 intArray->iiFlags |= WS_IFF_UP;
3174 if (ifInfo.ifr_flags & IFF_MULTICAST)
3175 intArray->iiFlags |= WS_IFF_MULTICAST;
3178 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
3179 mask = inet_addr(ptr->IpAddressList.IpMask.String);
3180 bcast = addr | ~mask;
3181 intArray->iiAddress.AddressIn.sin_family = AF_INET;
3182 intArray->iiAddress.AddressIn.sin_port = 0;
3183 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
3185 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
3186 intArray->iiNetmask.AddressIn.sin_port = 0;
3187 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
3189 intArray->iiBroadcastAddress.AddressIn.sin_family =
3191 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
3192 intArray->iiBroadcastAddress.AddressIn.sin_addr.
3198 ERR("Unable to get interface table!\n");
3199 release_sock_fd( s, fd );
3200 HeapFree(GetProcessHeap(),0,table);
3201 WSASetLastError(WSAEINVAL);
3202 return SOCKET_ERROR;
3204 HeapFree(GetProcessHeap(),0,table);
3208 release_sock_fd( s, fd );
3209 WSASetLastError(WSAEINVAL);
3210 return SOCKET_ERROR;
3215 ERR("Unable to get interface table!\n");
3216 release_sock_fd( s, fd );
3217 WSASetLastError(WSAEINVAL);
3218 return SOCKET_ERROR;
3220 /* Calculate the size of the array being returned */
3221 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
3222 release_sock_fd( s, fd );
3226 case WS_SIO_ADDRESS_LIST_CHANGE:
3227 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
3228 /* FIXME: error and return code depend on whether socket was created
3229 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
3232 case WS_SIO_ADDRESS_LIST_QUERY:
3236 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
3238 if (!lpcbBytesReturned)
3240 WSASetLastError(WSAEFAULT);
3241 return SOCKET_ERROR;
3244 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
3246 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
3249 if (!table || GetAdaptersInfo(table, &size))
3251 HeapFree(GetProcessHeap(), 0, table);
3252 WSASetLastError(WSAEINVAL);
3253 return SOCKET_ERROR;
3256 for (p = table, num = 0; p; p = p->Next)
3257 if (p->IpAddressList.IpAddress.String[0]) num++;
3259 need = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
3260 need += sizeof(SOCKADDR) * num;
3261 *lpcbBytesReturned = need;
3263 if (need > cbOutBuffer)
3265 HeapFree(GetProcessHeap(), 0, table);
3266 WSASetLastError(WSAEFAULT);
3267 return SOCKET_ERROR;
3274 SOCKET_ADDRESS_LIST *sa_list = (SOCKET_ADDRESS_LIST *)lpbOutBuffer;
3275 SOCKADDR_IN *sockaddr;
3277 sa = sa_list->Address;
3278 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
3279 sa_list->iAddressCount = num;
3281 for (p = table, i = 0; p; p = p->Next)
3283 if (!p->IpAddressList.IpAddress.String[0]) continue;
3285 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
3286 sa[i].iSockaddrLength = sizeof(SOCKADDR);
3288 sockaddr[i].sin_family = AF_INET;
3289 sockaddr[i].sin_port = 0;
3290 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
3295 HeapFree(GetProcessHeap(), 0, table);
3300 WARN("unable to get IP address list\n");
3301 WSASetLastError(WSAEINVAL);
3302 return SOCKET_ERROR;
3306 FIXME("SIO_FLUSH: stub.\n");
3309 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
3311 static const GUID connectex_guid = WSAID_CONNECTEX;
3312 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
3313 static const GUID acceptex_guid = WSAID_ACCEPTEX;
3314 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
3315 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
3316 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
3317 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
3318 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
3320 if ( IsEqualGUID(&connectex_guid, lpvInBuffer) )
3322 *(LPFN_CONNECTEX *)lpbOutBuffer = WS2_ConnectEx;
3325 else if ( IsEqualGUID(&disconnectex_guid, lpvInBuffer) )
3327 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
3329 else if ( IsEqualGUID(&acceptex_guid, lpvInBuffer) )
3331 *(LPFN_ACCEPTEX *)lpbOutBuffer = WS2_AcceptEx;
3334 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, lpvInBuffer) )
3336 *(LPFN_GETACCEPTEXSOCKADDRS *)lpbOutBuffer = WS2_GetAcceptExSockaddrs;
3339 else if ( IsEqualGUID(&transmitfile_guid, lpvInBuffer) )
3341 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
3343 else if ( IsEqualGUID(&transmitpackets_guid, lpvInBuffer) )
3345 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
3347 else if ( IsEqualGUID(&wsarecvmsg_guid, lpvInBuffer) )
3349 *(LPFN_WSARECVMSG *)lpbOutBuffer = WS2_WSARecvMsg;
3352 else if ( IsEqualGUID(&wsasendmsg_guid, lpvInBuffer) )
3354 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented WSASendMsg\n");
3357 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(lpvInBuffer));
3359 WSASetLastError(WSAEOPNOTSUPP);
3360 return SOCKET_ERROR;
3363 case WS_SIO_KEEPALIVE_VALS:
3366 struct tcp_keepalive *k = lpvInBuffer;
3367 int keepalive = k->onoff ? 1 : 0;
3368 int keepidle = k->keepalivetime / 1000;
3369 int keepintvl = k->keepaliveinterval / 1000;
3373 WSASetLastError(WSAEINVAL);
3374 return SOCKET_ERROR;
3377 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
3379 fd = get_sock_fd(s, 0, NULL);
3380 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
3382 release_sock_fd(s, fd);
3383 WSASetLastError(WSAEINVAL);
3384 return SOCKET_ERROR;
3386 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
3387 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
3389 release_sock_fd(s, fd);
3390 WSASetLastError(WSAEINVAL);
3391 return SOCKET_ERROR;
3393 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
3395 release_sock_fd(s, fd);
3396 WSASetLastError(WSAEINVAL);
3397 return SOCKET_ERROR;
3400 FIXME("ignoring keepalive interval and timeout\n");
3403 release_sock_fd(s, fd);
3406 case WS_SIO_ROUTING_INTERFACE_QUERY:
3408 struct WS_sockaddr *daddr = (struct WS_sockaddr *)lpvInBuffer;
3409 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
3410 struct WS_sockaddr_in *saddr_in = (struct WS_sockaddr_in *)lpbOutBuffer;
3411 MIB_IPFORWARDROW row;
3412 PMIB_IPADDRTABLE ipAddrTable = NULL;
3413 DWORD size, i, found_index;
3415 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
3419 WSASetLastError(WSAEFAULT);
3420 return SOCKET_ERROR;
3422 if (cbInBuffer < sizeof(struct WS_sockaddr))
3424 WSASetLastError(WSAEFAULT);
3425 return SOCKET_ERROR;
3429 WSASetLastError(WSAEFAULT);
3430 return SOCKET_ERROR;
3432 if (!lpcbBytesReturned)
3434 WSASetLastError(WSAEFAULT);
3435 return SOCKET_ERROR;
3437 if (daddr->sa_family != AF_INET)
3439 FIXME("unsupported address family %d\n", daddr->sa_family);
3440 WSASetLastError(WSAEAFNOSUPPORT);
3441 return SOCKET_ERROR;
3443 if (cbOutBuffer < sizeof(struct WS_sockaddr_in))
3445 WSASetLastError(WSAEFAULT);
3446 return SOCKET_ERROR;
3448 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR)
3450 WSASetLastError(WSAEFAULT);
3451 return SOCKET_ERROR;
3453 if (GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
3455 WSASetLastError(WSAEFAULT);
3456 return SOCKET_ERROR;
3458 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
3459 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
3461 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3462 WSASetLastError(WSAEFAULT);
3463 return SOCKET_ERROR;
3465 for (i = 0, found_index = ipAddrTable->dwNumEntries;
3466 i < ipAddrTable->dwNumEntries; i++)
3468 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
3471 if (found_index == ipAddrTable->dwNumEntries)
3473 ERR("no matching IP address for interface %d\n",
3474 row.dwForwardIfIndex);
3475 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3476 WSASetLastError(WSAEFAULT);
3477 return SOCKET_ERROR;
3479 saddr_in->sin_family = AF_INET;
3480 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
3481 saddr_in->sin_port = 0;
3482 *lpcbBytesReturned = sizeof(struct WS_sockaddr_in);
3483 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3486 case WS_SIO_UDP_CONNRESET:
3487 FIXME("WS_SIO_UDP_CONNRESET stub\n");
3490 FIXME("unsupported WS_IOCTL cmd (%s)\n",
3491 debugstr_wsaioctl(dwIoControlCode));
3492 WSASetLastError(WSAEOPNOTSUPP);
3493 return SOCKET_ERROR;
3500 /***********************************************************************
3501 * ioctlsocket (WS2_32.10)
3503 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
3508 TRACE("socket %04lx, cmd %08x, ptr %p\n", s, cmd, argp);
3509 /* broken apps like defcon pass the argp value directly instead of a pointer to it */
3510 if(IS_INTRESOURCE(argp))
3512 SetLastError(WSAEFAULT);
3513 return SOCKET_ERROR;
3523 if( _get_sock_mask(s) )
3525 /* AsyncSelect()'ed sockets are always nonblocking */
3526 if (*argp) return 0;
3527 SetLastError(WSAEINVAL);
3528 return SOCKET_ERROR;
3531 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
3533 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
3541 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
3542 SetLastError(WSAEINVAL);
3543 return SOCKET_ERROR;
3545 case SIOCGIFBRDADDR:
3546 case SIOCGIFNETMASK:
3548 /* These don't need any special handling. They are used by
3549 WsControl, and are here to suppress an unnecessary warning. */
3553 /* Netscape tries hard to use bogus ioctl 0x667e */
3554 /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
3555 * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
3557 WARN("\tunknown WS_IOCTL cmd (%08x)\n", cmd);
3561 fd = get_sock_fd( s, 0, NULL );
3564 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
3566 release_sock_fd( s, fd );
3569 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3570 release_sock_fd( s, fd );
3572 return SOCKET_ERROR;
3575 /***********************************************************************
3576 * listen (WS2_32.13)
3578 int WINAPI WS_listen(SOCKET s, int backlog)
3580 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3582 TRACE("socket %04lx, backlog %d\n", s, backlog);
3585 if (listen(fd, backlog) == 0)
3587 release_sock_fd( s, fd );
3588 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
3590 FD_CONNECT|FD_WINE_CONNECTED);
3593 SetLastError(wsaErrno());
3594 release_sock_fd( s, fd );
3596 return SOCKET_ERROR;
3599 /***********************************************************************
3602 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
3604 DWORD n, dwFlags = flags;
3610 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
3611 return SOCKET_ERROR;
3616 /***********************************************************************
3617 * recvfrom (WS2_32.17)
3619 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
3620 struct WS_sockaddr *from, int *fromlen)
3622 DWORD n, dwFlags = flags;
3628 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
3629 return SOCKET_ERROR;
3634 /* allocate a poll array for the corresponding fd sets */
3635 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
3636 const WS_fd_set *exceptfds, int *count_ptr )
3638 unsigned int i, j = 0, count = 0;
3641 if (readfds) count += readfds->fd_count;
3642 if (writefds) count += writefds->fd_count;
3643 if (exceptfds) count += exceptfds->fd_count;
3647 SetLastError(WSAEINVAL);
3650 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
3652 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
3656 for (i = 0; i < readfds->fd_count; i++, j++)
3658 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
3659 if (fds[j].fd == -1) goto failed;
3660 fds[j].events = POLLIN;
3664 for (i = 0; i < writefds->fd_count; i++, j++)
3666 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
3667 if (fds[j].fd == -1) goto failed;
3668 fds[j].events = POLLOUT;
3672 for (i = 0; i < exceptfds->fd_count; i++, j++)
3674 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
3675 if (fds[j].fd == -1) goto failed;
3676 fds[j].events = POLLHUP;
3685 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
3686 release_sock_fd( readfds->fd_array[i], fds[j].fd );
3688 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
3689 release_sock_fd( writefds->fd_array[i], fds[j].fd );
3691 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
3692 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
3693 HeapFree( GetProcessHeap(), 0, fds );
3697 /* release the file descriptor obtained in fd_sets_to_poll */
3698 /* must be called with the original fd_set arrays, before calling get_poll_results */
3699 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
3700 const WS_fd_set *exceptfds, struct pollfd *fds )
3702 unsigned int i, j = 0;
3706 for (i = 0; i < readfds->fd_count; i++, j++)
3707 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
3711 for (i = 0; i < writefds->fd_count; i++, j++)
3712 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
3716 for (i = 0; i < exceptfds->fd_count; i++, j++)
3717 if (fds[j].fd != -1)
3719 /* make sure we have a real error before releasing the fd */
3720 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
3721 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
3726 /* map the poll results back into the Windows fd sets */
3727 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
3728 const struct pollfd *fds )
3730 unsigned int i, j = 0, k, total = 0;
3734 for (i = k = 0; i < readfds->fd_count; i++, j++)
3735 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
3736 readfds->fd_count = k;
3741 for (i = k = 0; i < writefds->fd_count; i++, j++)
3742 if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
3743 writefds->fd_count = k;
3748 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
3749 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
3750 exceptfds->fd_count = k;
3757 /***********************************************************************
3758 * select (WS2_32.18)
3760 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
3761 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
3762 const struct WS_timeval* ws_timeout)
3764 struct pollfd *pollfds;
3765 struct timeval tv1, tv2;
3767 int count, ret, timeout = -1;
3769 TRACE("read %p, write %p, excp %p timeout %p\n",
3770 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
3772 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
3773 return SOCKET_ERROR;
3777 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
3779 gettimeofday( &tv1, 0 );
3782 while ((ret = poll( pollfds, count, timeout )) < 0)
3786 if (!ws_timeout) continue;
3787 gettimeofday( &tv2, 0 );
3789 tv2.tv_sec -= tv1.tv_sec;
3790 tv2.tv_usec -= tv1.tv_usec;
3791 if (tv2.tv_usec < 0)
3793 tv2.tv_usec += 1000000;
3797 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
3798 if (timeout <= 0) break;
3801 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3803 if (ret == -1) SetLastError(wsaErrno());
3804 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3805 HeapFree( GetProcessHeap(), 0, pollfds );
3809 /* helper to send completion messages for client-only i/o operation case */
3810 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
3813 SERVER_START_REQ( add_fd_completion )
3815 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
3816 req->cvalue = CompletionValue;
3817 req->status = CompletionStatus;
3818 req->information = Information;
3819 wine_server_call( req );
3825 /***********************************************************************
3828 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
3834 wsabuf.buf = (char*) buf;
3836 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
3837 return SOCKET_ERROR;
3842 /***********************************************************************
3843 * WSASend (WS2_32.72)
3845 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3846 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3847 LPWSAOVERLAPPED lpOverlapped,
3848 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3850 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
3851 NULL, 0, lpOverlapped, lpCompletionRoutine );
3854 /***********************************************************************
3855 * WSASendDisconnect (WS2_32.73)
3857 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
3859 return WS_shutdown( s, SD_SEND );
3863 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3864 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3865 const struct WS_sockaddr *to, int tolen,
3866 LPWSAOVERLAPPED lpOverlapped,
3867 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3869 unsigned int i, options;
3871 struct ws2_async *wsa;
3872 int totalLength = 0;
3873 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
3875 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
3876 s, lpBuffers, dwBufferCount, dwFlags,
3877 to, tolen, lpOverlapped, lpCompletionRoutine);
3879 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
3880 TRACE( "fd=%d, options=%x\n", fd, options );
3882 if ( fd == -1 ) return SOCKET_ERROR;
3884 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
3890 wsa->hSocket = SOCKET2HANDLE(s);
3891 wsa->addr = (struct WS_sockaddr *)to;
3892 wsa->addrlen.val = tolen;
3893 wsa->flags = dwFlags;
3894 wsa->lpFlags = &wsa->flags;
3895 wsa->control = NULL;
3896 wsa->n_iovecs = dwBufferCount;
3897 wsa->first_iovec = 0;
3898 for ( i = 0; i < dwBufferCount; i++ )
3900 wsa->iovec[i].iov_base = lpBuffers[i].buf;
3901 wsa->iovec[i].iov_len = lpBuffers[i].len;
3902 totalLength += lpBuffers[i].len;
3905 if (!lpNumberOfBytesSent)
3913 n = WS2_send( fd, wsa );
3914 if (n != -1 || errno != EINTR) break;
3916 if (n == -1 && errno != EAGAIN)
3918 int loc_errno = errno;
3920 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
3924 if ((lpOverlapped || lpCompletionRoutine) &&
3925 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3927 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
3929 wsa->user_overlapped = lpOverlapped;
3930 wsa->completion_func = lpCompletionRoutine;
3931 release_sock_fd( s, fd );
3933 if (n == -1 || n < totalLength)
3935 iosb->u.Status = STATUS_PENDING;
3936 iosb->Information = n == -1 ? 0 : n;
3938 SERVER_START_REQ( register_async )
3940 req->type = ASYNC_TYPE_WRITE;
3941 req->async.handle = wine_server_obj_handle( wsa->hSocket );
3942 req->async.callback = wine_server_client_ptr( WS2_async_send );
3943 req->async.iosb = wine_server_client_ptr( iosb );
3944 req->async.arg = wine_server_client_ptr( wsa );
3945 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
3946 req->async.cvalue = cvalue;
3947 err = wine_server_call( req );
3951 /* Enable the event only after starting the async. The server will deliver it as soon as
3952 the async is done. */
3953 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
3955 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
3956 WSASetLastError( NtStatusToWSAError( err ));
3957 return SOCKET_ERROR;
3960 iosb->u.Status = STATUS_SUCCESS;
3961 iosb->Information = n;
3962 *lpNumberOfBytesSent = n;
3963 if (!wsa->completion_func)
3965 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
3966 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
3967 HeapFree( GetProcessHeap(), 0, wsa );
3969 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
3970 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
3975 if ( _is_blocking(s) )
3977 /* On a blocking non-overlapped stream socket,
3978 * sending blocks until the entire buffer is sent. */
3979 DWORD timeout_start = GetTickCount();
3981 *lpNumberOfBytesSent = n == -1 ? 0 : n;
3983 while (wsa->first_iovec < wsa->n_iovecs)
3986 int timeout = GET_SNDTIMEO(fd);
3990 timeout -= GetTickCount() - timeout_start;
3991 if (timeout < 0) timeout = 0;
3995 pfd.events = POLLOUT;
3997 if (!timeout || !poll( &pfd, 1, timeout ))
4000 goto error; /* msdn says a timeout in send is fatal */
4003 n = WS2_send( fd, wsa );
4004 if (n == -1 && errno != EAGAIN && errno != EINTR)
4011 *lpNumberOfBytesSent += n;
4014 else /* non-blocking */
4016 if (n < totalLength)
4017 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4020 err = WSAEWOULDBLOCK;
4023 *lpNumberOfBytesSent = n;
4026 TRACE(" -> %i bytes\n", *lpNumberOfBytesSent);
4028 HeapFree( GetProcessHeap(), 0, wsa );
4029 release_sock_fd( s, fd );
4034 HeapFree( GetProcessHeap(), 0, wsa );
4035 release_sock_fd( s, fd );
4036 WARN(" -> ERROR %d\n", err);
4037 WSASetLastError(err);
4038 return SOCKET_ERROR;
4041 /***********************************************************************
4042 * WSASendTo (WS2_32.74)
4044 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4045 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4046 const struct WS_sockaddr *to, int tolen,
4047 LPWSAOVERLAPPED lpOverlapped,
4048 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4050 return WS2_sendto( s, lpBuffers, dwBufferCount,
4051 lpNumberOfBytesSent, dwFlags,
4053 lpOverlapped, lpCompletionRoutine );
4056 /***********************************************************************
4057 * sendto (WS2_32.20)
4059 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
4060 const struct WS_sockaddr *to, int tolen)
4066 wsabuf.buf = (char*) buf;
4068 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
4069 return SOCKET_ERROR;
4074 /***********************************************************************
4075 * setsockopt (WS2_32.21)
4077 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
4078 const char *optval, int optlen)
4082 struct linger linger;
4083 struct timeval tval;
4085 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
4086 s, level, optname, optval, optlen);
4088 /* some broken apps pass the value directly instead of a pointer to it */
4089 if(optlen && IS_INTRESOURCE(optval))
4091 SetLastError(WSAEFAULT);
4092 return SOCKET_ERROR;
4100 /* Some options need some conversion before they can be sent to
4101 * setsockopt. The conversions are done here, then they will fall though
4102 * to the general case. Special options that are not passed to
4103 * setsockopt follow below that.*/
4105 case WS_SO_DONTLINGER:
4106 linger.l_onoff = *((const int*)optval) ? 0: 1;
4107 linger.l_linger = 0;
4109 optname = SO_LINGER;
4110 optval = (char*)&linger;
4111 optlen = sizeof(struct linger);
4115 linger.l_onoff = ((LINGER*)optval)->l_onoff;
4116 linger.l_linger = ((LINGER*)optval)->l_linger;
4117 /* FIXME: what is documented behavior if SO_LINGER optval
4120 optname = SO_LINGER;
4121 optval = (char*)&linger;
4122 optlen = sizeof(struct linger);
4126 if (*(const int*)optval < 2048)
4128 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
4133 /* The options listed here don't need any special handling. Thanks to
4134 * the conversion happening above, options from there will fall through
4136 case WS_SO_ACCEPTCONN:
4137 case WS_SO_BROADCAST:
4139 case WS_SO_KEEPALIVE:
4140 case WS_SO_OOBINLINE:
4141 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
4142 * however, using it the BSD way fixes bug 8513 and seems to be what
4143 * most programmers assume, anyway */
4144 case WS_SO_REUSEADDR:
4147 convert_sockopt(&level, &optname);
4150 /* SO_DEBUG is a privileged operation, ignore it. */
4152 TRACE("Ignoring SO_DEBUG\n");
4155 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
4156 * socket. According to MSDN, this option is silently ignored.*/
4157 case WS_SO_DONTROUTE:
4158 TRACE("Ignoring SO_DONTROUTE\n");
4161 /* Stops two sockets from being bound to the same port. Always happens
4162 * on unix systems, so just drop it. */
4163 case WS_SO_EXCLUSIVEADDRUSE:
4164 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
4167 /* After a ConnectEx call succeeds, the socket can't be used with half of the
4168 * normal winsock functions on windows. We don't have that problem. */
4169 case WS_SO_UPDATE_CONNECT_CONTEXT:
4170 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
4173 /* After a AcceptEx call succeeds, the socket can't be used with half of the
4174 * normal winsock functions on windows. We don't have that problem. */
4175 case WS_SO_UPDATE_ACCEPT_CONTEXT:
4176 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
4179 /* SO_OPENTYPE does not require a valid socket handle. */
4180 case WS_SO_OPENTYPE:
4181 if (!optlen || optlen < sizeof(int) || !optval)
4183 SetLastError(WSAEFAULT);
4184 return SOCKET_ERROR;
4186 get_per_thread_data()->opentype = *(const int *)optval;
4187 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
4191 case WS_SO_RCVTIMEO:
4194 case WS_SO_SNDTIMEO:
4196 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
4197 if (optval && optlen == sizeof(UINT32)) {
4198 /* WinSock passes milliseconds instead of struct timeval */
4199 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
4200 tval.tv_sec = *(const UINT32*)optval / 1000;
4201 /* min of 500 milliseconds */
4202 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
4203 tval.tv_usec = 500000;
4204 optlen = sizeof(struct timeval);
4205 optval = (char*)&tval;
4206 } else if (optlen == sizeof(struct timeval)) {
4207 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
4209 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
4212 convert_sockopt(&level, &optname);
4217 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4218 SetLastError(WSAENOPROTOOPT);
4219 return SOCKET_ERROR;
4221 break; /* case WS_SOL_SOCKET */
4228 fd = get_sock_fd( s, 0, NULL );
4229 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
4231 /* We try to set the ipx type on ipx socket level. */
4233 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
4235 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
4236 release_sock_fd( s, fd );
4237 return SOCKET_ERROR;
4242 /* Should we retrieve val using a getsockopt call and then
4243 * set the modified one? */
4244 val.ipx_pt = *optval;
4245 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
4248 release_sock_fd( s, fd );
4251 case IPX_FILTERPTYPE:
4252 /* Sets the receive filter packet type, at the moment we don't support it */
4253 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
4254 /* Returning 0 is better for now than returning a SOCKET_ERROR */
4258 FIXME("opt_name:%x\n", optname);
4259 return SOCKET_ERROR;
4261 break; /* case NSPROTO_IPX */
4264 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4265 case WS_IPPROTO_TCP:
4268 case WS_TCP_NODELAY:
4269 convert_sockopt(&level, &optname);
4272 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4273 return SOCKET_ERROR;
4280 case WS_IP_ADD_MEMBERSHIP:
4281 case WS_IP_DROP_MEMBERSHIP:
4285 case WS_IP_MULTICAST_IF:
4286 case WS_IP_MULTICAST_LOOP:
4287 case WS_IP_MULTICAST_TTL:
4294 convert_sockopt(&level, &optname);
4296 case WS_IP_DONTFRAGMENT:
4297 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
4300 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4301 return SOCKET_ERROR;
4305 case WS_IPPROTO_IPV6:
4308 #ifdef IPV6_ADD_MEMBERSHIP
4309 case WS_IPV6_ADD_MEMBERSHIP:
4311 #ifdef IPV6_DROP_MEMBERSHIP
4312 case WS_IPV6_DROP_MEMBERSHIP:
4314 case WS_IPV6_MULTICAST_IF:
4315 case WS_IPV6_MULTICAST_HOPS:
4316 case WS_IPV6_MULTICAST_LOOP:
4317 case WS_IPV6_UNICAST_HOPS:
4318 case WS_IPV6_V6ONLY:
4319 convert_sockopt(&level, &optname);
4321 case WS_IPV6_DONTFRAG:
4322 FIXME("IPV6_DONTFRAG is silently ignored!\n");
4325 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4326 return SOCKET_ERROR;
4331 WARN("Unknown level: 0x%08x\n", level);
4332 SetLastError(WSAEINVAL);
4333 return SOCKET_ERROR;
4334 } /* end switch(level) */
4336 /* avoid endianness issues if argument is a 16-bit int */
4337 if (optval && optlen < sizeof(int))
4339 woptval= *((const INT16 *) optval);
4340 optval= (char*) &woptval;
4343 fd = get_sock_fd( s, 0, NULL );
4344 if (fd == -1) return SOCKET_ERROR;
4346 if (setsockopt(fd, level, optname, optval, optlen) == 0)
4348 release_sock_fd( s, fd );
4351 TRACE("Setting socket error, %d\n", wsaErrno());
4352 SetLastError(wsaErrno());
4353 release_sock_fd( s, fd );
4355 return SOCKET_ERROR;
4358 /***********************************************************************
4359 * shutdown (WS2_32.22)
4361 int WINAPI WS_shutdown(SOCKET s, int how)
4363 int fd, err = WSAENOTSOCK;
4364 unsigned int options, clear_flags = 0;
4366 fd = get_sock_fd( s, 0, &options );
4367 TRACE("socket %04lx, how %i %x\n", s, how, options );
4370 return SOCKET_ERROR;
4374 case 0: /* drop receives */
4375 clear_flags |= FD_READ;
4377 case 1: /* drop sends */
4378 clear_flags |= FD_WRITE;
4380 case 2: /* drop all */
4381 clear_flags |= FD_READ|FD_WRITE;
4383 clear_flags |= FD_WINE_LISTENING;
4386 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4391 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4394 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4398 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4399 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4402 if (err) goto error;
4404 else /* non-overlapped mode */
4406 if ( shutdown( fd, how ) )
4413 release_sock_fd( s, fd );
4414 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4415 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
4419 release_sock_fd( s, fd );
4420 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4421 WSASetLastError( err );
4422 return SOCKET_ERROR;
4425 /***********************************************************************
4426 * socket (WS2_32.23)
4428 SOCKET WINAPI WS_socket(int af, int type, int protocol)
4430 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
4432 return WSASocketA( af, type, protocol, NULL, 0,
4433 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
4437 /***********************************************************************
4438 * gethostbyaddr (WS2_32.51)
4440 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
4442 struct WS_hostent *retval = NULL;
4443 struct hostent* host;
4445 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4448 struct hostent hostentry;
4451 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4453 int res = gethostbyaddr_r(addr, len, type,
4454 &hostentry, extrabuf, ebufsize, &host, &locerr);
4455 if( res != ERANGE) break;
4457 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4459 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4461 EnterCriticalSection( &csWSgetXXXbyYYY );
4462 host = gethostbyaddr(addr, len, type);
4463 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4465 if( host != NULL ) retval = WS_dup_he(host);
4466 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4467 HeapFree(GetProcessHeap(),0,extrabuf);
4469 LeaveCriticalSection( &csWSgetXXXbyYYY );
4471 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
4475 /***********************************************************************
4476 * WS_get_local_ips (INTERNAL)
4478 * Returns the list of local IP addresses by going through the network
4479 * adapters and using the local routing table to sort the addresses
4480 * from highest routing priority to lowest routing priority. This
4481 * functionality is inferred from the description for obtaining local
4482 * IP addresses given in the Knowledge Base Article Q160215.
4484 * Please note that the returned hostent is only freed when the thread
4485 * closes and is replaced if another hostent is requested.
4487 static struct WS_hostent* WS_get_local_ips( char *hostname )
4489 int last_metric, numroutes = 0, i, j;
4490 PIP_ADAPTER_INFO adapters = NULL, k;
4491 struct WS_hostent *hostlist = NULL;
4492 PMIB_IPFORWARDTABLE routes = NULL;
4493 struct route *route_addrs = NULL;
4494 DWORD adap_size, route_size;
4496 /* Obtain the size of the adapter list and routing table, also allocate memory */
4497 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
4499 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4501 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
4502 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
4503 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
4504 if (adapters == NULL || routes == NULL || route_addrs == NULL)
4506 /* Obtain the adapter list and the full routing table */
4507 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
4509 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
4511 /* Store the interface associated with each route */
4512 for (i = 0; i < routes->dwNumEntries; i++)
4514 DWORD ifindex, ifmetric, exists = FALSE;
4516 if (routes->table[i].dwForwardType != MIB_IPROUTE_TYPE_DIRECT)
4518 ifindex = routes->table[i].dwForwardIfIndex;
4519 ifmetric = routes->table[i].dwForwardMetric1;
4520 /* Only store the lowest valued metric for an interface */
4521 for (j = 0; j < numroutes; j++)
4523 if (route_addrs[j].interface == ifindex)
4525 if (route_addrs[j].metric > ifmetric)
4526 route_addrs[j].metric = ifmetric;
4532 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
4533 if (route_addrs == NULL)
4534 goto cleanup; /* Memory allocation error, fail gracefully */
4535 route_addrs[numroutes].interface = ifindex;
4536 route_addrs[numroutes].metric = ifmetric;
4537 /* If no IP is found in the next step (for whatever reason)
4538 * then fall back to the magic loopback address.
4540 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
4544 goto cleanup; /* No routes, fall back to the Magic IP */
4545 /* Find the IP address associated with each found interface */
4546 for (i = 0; i < numroutes; i++)
4548 for (k = adapters; k != NULL; k = k->Next)
4550 char *ip = k->IpAddressList.IpAddress.String;
4552 if (route_addrs[i].interface == k->Index)
4553 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
4556 /* Allocate a hostent and enough memory for all the IPs,
4557 * including the NULL at the end of the list.
4559 hostlist = WS_create_he(hostname, 1, numroutes+1, TRUE);
4560 if (hostlist == NULL)
4561 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
4562 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
4563 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
4564 hostlist->h_addrtype = AF_INET;
4565 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
4566 /* Reorder the entries when placing them in the host list, Windows expects
4567 * the IP list in order from highest priority to lowest (the critical thing
4568 * is that most applications expect the first IP to be the default route).
4571 for (i = 0; i < numroutes; i++)
4573 struct in_addr addr;
4574 int metric = 0xFFFF;
4576 memcpy(&addr, magic_loopback_addr, 4);
4577 for (j = 0; j < numroutes; j++)
4579 int this_metric = route_addrs[j].metric;
4581 if (this_metric > last_metric && this_metric < metric)
4583 addr = route_addrs[j].addr;
4584 metric = this_metric;
4587 last_metric = metric;
4588 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
4591 /* Cleanup all allocated memory except the address list,
4592 * the address list is used by the calling app.
4595 HeapFree(GetProcessHeap(), 0, route_addrs);
4596 HeapFree(GetProcessHeap(), 0, adapters);
4597 HeapFree(GetProcessHeap(), 0, routes);
4601 /***********************************************************************
4602 * gethostbyname (WS2_32.52)
4604 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
4606 struct WS_hostent *retval = NULL;
4607 struct hostent* host;
4608 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4611 struct hostent hostentry;
4612 int locerr = ENOBUFS;
4616 SetLastError(WSANOTINITIALISED);
4619 if( gethostname( hostname, 100) == -1) {
4620 SetLastError( WSAENOBUFS); /* appropriate ? */
4623 if( !name || !name[0]) {
4626 /* If the hostname of the local machine is requested then return the
4627 * complete list of local IP addresses */
4628 if(strcmp(name, hostname) == 0)
4629 retval = WS_get_local_ips(hostname);
4630 /* If any other hostname was requested (or the routing table lookup failed)
4631 * then return the IP found by the host OS */
4634 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4636 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4638 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
4639 if( res != ERANGE) break;
4641 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4643 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4645 EnterCriticalSection( &csWSgetXXXbyYYY );
4646 host = gethostbyname(name);
4647 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4649 if (host) retval = WS_dup_he(host);
4650 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4651 HeapFree(GetProcessHeap(),0,extrabuf);
4653 LeaveCriticalSection( &csWSgetXXXbyYYY );
4656 if (retval && retval->h_addr_list[0][0] == 127 &&
4657 strcmp(name, "localhost") != 0)
4659 /* hostname != "localhost" but has loopback address. replace by our
4660 * special address.*/
4661 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
4663 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4668 /***********************************************************************
4669 * getprotobyname (WS2_32.53)
4671 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
4673 struct WS_protoent* retval = NULL;
4674 #ifdef HAVE_GETPROTOBYNAME
4675 struct protoent* proto;
4676 EnterCriticalSection( &csWSgetXXXbyYYY );
4677 if( (proto = getprotobyname(name)) != NULL )
4679 retval = WS_dup_pe(proto);
4682 MESSAGE("protocol %s not found; You might want to add "
4683 "this to /etc/protocols\n", debugstr_a(name) );
4684 SetLastError(WSANO_DATA);
4686 LeaveCriticalSection( &csWSgetXXXbyYYY );
4688 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4693 /***********************************************************************
4694 * getprotobynumber (WS2_32.54)
4696 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
4698 struct WS_protoent* retval = NULL;
4699 #ifdef HAVE_GETPROTOBYNUMBER
4700 struct protoent* proto;
4701 EnterCriticalSection( &csWSgetXXXbyYYY );
4702 if( (proto = getprotobynumber(number)) != NULL )
4704 retval = WS_dup_pe(proto);
4707 MESSAGE("protocol number %d not found; You might want to add "
4708 "this to /etc/protocols\n", number );
4709 SetLastError(WSANO_DATA);
4711 LeaveCriticalSection( &csWSgetXXXbyYYY );
4713 TRACE("%i ret %p\n", number, retval);
4718 /***********************************************************************
4719 * getservbyname (WS2_32.55)
4721 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
4723 struct WS_servent* retval = NULL;
4724 struct servent* serv;
4726 char *proto_str = NULL;
4728 if (!(name_str = strdup_lower(name))) return NULL;
4730 if (proto && *proto)
4732 if (!(proto_str = strdup_lower(proto)))
4734 HeapFree( GetProcessHeap(), 0, name_str );
4739 EnterCriticalSection( &csWSgetXXXbyYYY );
4740 serv = getservbyname(name_str, proto_str);
4743 retval = WS_dup_se(serv);
4745 else SetLastError(WSANO_DATA);
4746 LeaveCriticalSection( &csWSgetXXXbyYYY );
4747 HeapFree( GetProcessHeap(), 0, proto_str );
4748 HeapFree( GetProcessHeap(), 0, name_str );
4749 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
4753 /***********************************************************************
4754 * freeaddrinfo (WS2_32.@)
4756 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
4759 struct WS_addrinfo *next;
4761 HeapFree(GetProcessHeap(),0,res->ai_canonname);
4762 HeapFree(GetProcessHeap(),0,res->ai_addr);
4763 next = res->ai_next;
4764 HeapFree(GetProcessHeap(),0,res);
4769 /* helper functions for getaddrinfo()/getnameinfo() */
4770 static int convert_aiflag_w2u(int winflags) {
4774 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4775 if (ws_aiflag_map[i][0] & winflags) {
4776 unixflags |= ws_aiflag_map[i][1];
4777 winflags &= ~ws_aiflag_map[i][0];
4780 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
4784 static int convert_niflag_w2u(int winflags) {
4788 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
4789 if (ws_niflag_map[i][0] & winflags) {
4790 unixflags |= ws_niflag_map[i][1];
4791 winflags &= ~ws_niflag_map[i][0];
4794 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
4798 static int convert_aiflag_u2w(int unixflags) {
4802 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4803 if (ws_aiflag_map[i][1] & unixflags) {
4804 winflags |= ws_aiflag_map[i][0];
4805 unixflags &= ~ws_aiflag_map[i][1];
4807 if (unixflags) /* will warn usually */
4808 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
4812 static int convert_eai_u2w(int unixret) {
4815 for (i=0;ws_eai_map[i][0];i++)
4816 if (ws_eai_map[i][1] == unixret)
4817 return ws_eai_map[i][0];
4821 /***********************************************************************
4822 * getaddrinfo (WS2_32.@)
4824 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
4826 #ifdef HAVE_GETADDRINFO
4827 struct addrinfo *unixaires = NULL;
4829 struct addrinfo unixhints, *punixhints = NULL;
4830 CHAR *node = NULL, *serv = NULL;
4833 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
4836 if (!(serv = strdup_lower(servname))) {
4837 HeapFree(GetProcessHeap(), 0, node);
4838 return WSA_NOT_ENOUGH_MEMORY;
4843 punixhints = &unixhints;
4845 memset(&unixhints, 0, sizeof(unixhints));
4846 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
4847 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
4848 punixhints->ai_family = 0;
4850 punixhints->ai_family = convert_af_w2u(hints->ai_family);
4851 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
4852 punixhints->ai_socktype = 0;
4854 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
4855 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
4856 punixhints->ai_protocol = 0;
4858 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
4861 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
4862 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
4864 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
4866 HeapFree(GetProcessHeap(), 0, node);
4867 HeapFree(GetProcessHeap(), 0, serv);
4870 struct addrinfo *xuai = unixaires;
4871 struct WS_addrinfo **xai = res;
4875 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
4881 *xai = ai;xai = &ai->ai_next;
4882 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
4883 ai->ai_family = convert_af_u2w(xuai->ai_family);
4884 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
4885 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
4886 if (xuai->ai_canonname) {
4887 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
4888 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
4889 if (!ai->ai_canonname)
4891 strcpy(ai->ai_canonname,xuai->ai_canonname);
4893 len = xuai->ai_addrlen;
4894 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
4897 ai->ai_addrlen = len;
4899 int winlen = ai->ai_addrlen;
4901 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
4902 ai->ai_addrlen = winlen;
4906 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
4909 ai->ai_addrlen = len;
4911 xuai = xuai->ai_next;
4913 freeaddrinfo(unixaires);
4915 result = convert_eai_u2w(result);
4921 if (*res) WS_freeaddrinfo(*res);
4922 if (unixaires) freeaddrinfo(unixaires);
4924 return WSA_NOT_ENOUGH_MEMORY;
4926 FIXME("getaddrinfo() failed, not found during buildtime.\n");
4931 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
4933 struct WS_addrinfoW *ret;
4935 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
4936 ret->ai_flags = ai->ai_flags;
4937 ret->ai_family = ai->ai_family;
4938 ret->ai_socktype = ai->ai_socktype;
4939 ret->ai_protocol = ai->ai_protocol;
4940 ret->ai_addrlen = ai->ai_addrlen;
4941 ret->ai_canonname = NULL;
4942 ret->ai_addr = NULL;
4943 ret->ai_next = NULL;
4944 if (ai->ai_canonname)
4946 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
4947 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
4949 HeapFree(GetProcessHeap(), 0, ret);
4952 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
4956 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
4958 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
4959 HeapFree(GetProcessHeap(), 0, ret);
4962 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
4967 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
4969 struct WS_addrinfoW *ret, *infoW;
4971 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
4972 while (info->ai_next)
4974 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
4979 infoW = infoW->ai_next;
4980 info = info->ai_next;
4985 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
4987 struct WS_addrinfo *ret;
4989 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
4990 ret->ai_flags = ai->ai_flags;
4991 ret->ai_family = ai->ai_family;
4992 ret->ai_socktype = ai->ai_socktype;
4993 ret->ai_protocol = ai->ai_protocol;
4994 ret->ai_addrlen = ai->ai_addrlen;
4995 ret->ai_canonname = NULL;
4996 ret->ai_addr = NULL;
4997 ret->ai_next = NULL;
4998 if (ai->ai_canonname)
5000 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
5001 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5003 HeapFree(GetProcessHeap(), 0, ret);
5006 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
5010 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5012 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5013 HeapFree(GetProcessHeap(), 0, ret);
5016 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5021 /***********************************************************************
5022 * GetAddrInfoW (WS2_32.@)
5024 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
5027 char *nodenameA, *servnameA = NULL;
5028 struct WS_addrinfo *resA, *hintsA = NULL;
5030 if (!nodename) return WSAHOST_NOT_FOUND;
5032 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
5033 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
5034 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
5038 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
5039 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
5041 HeapFree(GetProcessHeap(), 0, nodenameA);
5044 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
5047 if (hints) hintsA = addrinfo_WtoA(hints);
5048 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
5049 WS_freeaddrinfo(hintsA);
5053 *res = addrinfo_list_AtoW(resA);
5054 WS_freeaddrinfo(resA);
5057 HeapFree(GetProcessHeap(), 0, nodenameA);
5058 HeapFree(GetProcessHeap(), 0, servnameA);
5062 /***********************************************************************
5063 * FreeAddrInfoW (WS2_32.@)
5065 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
5070 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
5071 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
5073 HeapFree(GetProcessHeap(), 0, ai);
5078 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
5079 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
5081 #ifdef HAVE_GETNAMEINFO
5083 union generic_unix_sockaddr sa_u;
5086 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
5087 serv, servlen, flags);
5089 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
5092 WSASetLastError(WSAEFAULT);
5093 return WSA_NOT_ENOUGH_MEMORY;
5095 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
5096 return convert_eai_u2w(ret);
5098 FIXME("getnameinfo() failed, not found during buildtime.\n");
5103 /***********************************************************************
5104 * getservbyport (WS2_32.56)
5106 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
5108 struct WS_servent* retval = NULL;
5109 #ifdef HAVE_GETSERVBYPORT
5110 struct servent* serv;
5111 char *proto_str = NULL;
5113 if (proto && *proto)
5115 if (!(proto_str = strdup_lower(proto))) return NULL;
5117 EnterCriticalSection( &csWSgetXXXbyYYY );
5118 if( (serv = getservbyport(port, proto_str)) != NULL ) {
5119 retval = WS_dup_se(serv);
5121 else SetLastError(WSANO_DATA);
5122 LeaveCriticalSection( &csWSgetXXXbyYYY );
5123 HeapFree( GetProcessHeap(), 0, proto_str );
5125 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
5130 /***********************************************************************
5131 * gethostname (WS2_32.57)
5133 int WINAPI WS_gethostname(char *name, int namelen)
5135 TRACE("name %p, len %d\n", name, namelen);
5137 if (gethostname(name, namelen) == 0)
5139 TRACE("<- '%s'\n", name);
5142 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
5143 TRACE("<- ERROR !\n");
5144 return SOCKET_ERROR;
5148 /* ------------------------------------- Windows sockets extensions -- *
5150 * ------------------------------------------------------------------- */
5152 /***********************************************************************
5153 * WSAEnumNetworkEvents (WS2_32.36)
5155 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
5159 int errors[FD_MAX_EVENTS];
5161 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
5163 SERVER_START_REQ( get_socket_event )
5165 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5166 req->service = TRUE;
5167 req->c_event = wine_server_obj_handle( hEvent );
5168 wine_server_set_reply( req, errors, sizeof(errors) );
5169 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
5174 for (i = 0; i < FD_MAX_EVENTS; i++)
5175 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
5178 SetLastError(WSAEINVAL);
5179 return SOCKET_ERROR;
5182 /***********************************************************************
5183 * WSAEventSelect (WS2_32.39)
5185 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
5189 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
5191 SERVER_START_REQ( set_socket_event )
5193 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5195 req->event = wine_server_obj_handle( hEvent );
5198 ret = wine_server_call( req );
5202 SetLastError(WSAEINVAL);
5203 return SOCKET_ERROR;
5206 /**********************************************************************
5207 * WSAGetOverlappedResult (WS2_32.40)
5209 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
5210 LPDWORD lpcbTransfer, BOOL fWait,
5215 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
5216 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
5218 if ( lpOverlapped == NULL )
5220 ERR( "Invalid pointer\n" );
5221 WSASetLastError(WSA_INVALID_PARAMETER);
5225 status = lpOverlapped->Internal;
5226 if (status == STATUS_PENDING)
5230 SetLastError( WSA_IO_INCOMPLETE );
5234 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
5235 INFINITE ) == WAIT_FAILED)
5237 status = lpOverlapped->Internal;
5241 *lpcbTransfer = lpOverlapped->InternalHigh;
5244 *lpdwFlags = lpOverlapped->u.s.Offset;
5246 if (status) SetLastError( RtlNtStatusToDosError(status) );
5251 /***********************************************************************
5252 * WSAAsyncSelect (WS2_32.101)
5254 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
5258 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
5260 SERVER_START_REQ( set_socket_event )
5262 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5265 req->window = wine_server_user_handle( hWnd );
5267 ret = wine_server_call( req );
5271 SetLastError(WSAEINVAL);
5272 return SOCKET_ERROR;
5275 /***********************************************************************
5276 * WSACreateEvent (WS2_32.31)
5279 WSAEVENT WINAPI WSACreateEvent(void)
5281 /* Create a manual-reset event, with initial state: unsignaled */
5284 return CreateEventW(NULL, TRUE, FALSE, NULL);
5287 /***********************************************************************
5288 * WSACloseEvent (WS2_32.29)
5291 BOOL WINAPI WSACloseEvent(WSAEVENT event)
5293 TRACE ("event=%p\n", event);
5295 return CloseHandle(event);
5298 /***********************************************************************
5299 * WSASocketA (WS2_32.78)
5302 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
5303 LPWSAPROTOCOL_INFOA lpProtocolInfo,
5304 GROUP g, DWORD dwFlags)
5307 WSAPROTOCOL_INFOW info;
5309 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5310 af, type, protocol, lpProtocolInfo, g, dwFlags);
5312 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
5314 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
5315 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5316 info.szProtocol, WSAPROTOCOL_LEN + 1);
5320 WSASetLastError( WSAEINVAL);
5321 return SOCKET_ERROR;
5324 return WSASocketW(af, type, protocol, &info, g, dwFlags);
5327 /***********************************************************************
5328 * WSASocketW (WS2_32.79)
5331 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
5332 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5333 GROUP g, DWORD dwFlags)
5338 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
5339 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
5342 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5343 af, type, protocol, lpProtocolInfo, g, dwFlags );
5345 /* hack for WSADuplicateSocket */
5346 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
5347 ret = lpProtocolInfo->dwCatalogEntryId;
5348 TRACE("\tgot duplicate %04lx\n", ret);
5352 /* convert the socket family and type */
5353 af = convert_af_w2u(af);
5354 type = convert_socktype_w2u(type);
5358 if (af == FROM_PROTOCOL_INFO)
5359 af = lpProtocolInfo->iAddressFamily;
5360 if (type == FROM_PROTOCOL_INFO)
5361 type = lpProtocolInfo->iSocketType;
5362 if (protocol == FROM_PROTOCOL_INFO)
5363 protocol = lpProtocolInfo->iProtocol;
5366 if ( af == AF_UNSPEC) /* did they not specify the address family? */
5370 if (type == SOCK_STREAM) { af = AF_INET; break; }
5372 if (type == SOCK_DGRAM) { af = AF_INET; break; }
5373 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
5376 SERVER_START_REQ( create_socket )
5380 req->protocol = protocol;
5381 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
5382 req->attributes = OBJ_INHERIT;
5383 req->flags = dwFlags;
5384 set_error( wine_server_call( req ) );
5385 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
5390 TRACE("\tcreated %04lx\n", ret );
5394 if (GetLastError() == WSAEACCES) /* raw socket denied */
5396 if (type == SOCK_RAW)
5397 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
5399 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
5400 SetLastError(WSAESOCKTNOSUPPORT);
5403 WARN("\t\tfailed!\n");
5404 return INVALID_SOCKET;
5407 /***********************************************************************
5408 * WSAJoinLeaf (WS2_32.58)
5411 SOCKET WINAPI WSAJoinLeaf(
5413 const struct WS_sockaddr *addr,
5415 LPWSABUF lpCallerData,
5416 LPWSABUF lpCalleeData,
5422 return INVALID_SOCKET;
5425 /***********************************************************************
5426 * __WSAFDIsSet (WS2_32.151)
5428 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
5430 int i = set->fd_count;
5432 TRACE("(%ld,%p(%i))\n", s, set, i);
5435 if (set->fd_array[i] == s) return 1;
5439 /***********************************************************************
5440 * WSAIsBlocking (WS2_32.114)
5442 BOOL WINAPI WSAIsBlocking(void)
5444 /* By default WinSock should set all its sockets to non-blocking mode
5445 * and poll in PeekMessage loop when processing "blocking" ones. This
5446 * function is supposed to tell if the program is in this loop. Our
5447 * blocking calls are truly blocking so we always return FALSE.
5449 * Note: It is allowed to call this function without prior WSAStartup().
5456 /***********************************************************************
5457 * WSACancelBlockingCall (WS2_32.113)
5459 INT WINAPI WSACancelBlockingCall(void)
5465 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
5467 FIXME("How was this called?\n");
5472 /***********************************************************************
5473 * WSASetBlockingHook (WS2_32.109)
5475 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
5477 FARPROC prev = blocking_hook;
5478 blocking_hook = lpBlockFunc;
5479 TRACE("hook %p\n", lpBlockFunc);
5484 /***********************************************************************
5485 * WSAUnhookBlockingHook (WS2_32.110)
5487 INT WINAPI WSAUnhookBlockingHook(void)
5489 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
5494 /* ----------------------------------- end of API stuff */
5496 /* ----------------------------------- helper functions -
5498 * TODO: Merge WS_dup_..() stuff into one function that
5499 * would operate with a generic structure containing internal
5500 * pointers (via a template of some kind).
5503 static int list_size(char** l, int item_size)
5508 j += (item_size) ? item_size : strlen(l[i]) + 1;
5509 j += (i + 1) * sizeof(char*); }
5513 static int list_dup(char** l_src, char** l_to, int item_size)
5518 for (i = 0; l_src[i]; i++) ;
5519 p = (char *)(l_to + i + 1);
5520 for (i = 0; l_src[i]; i++)
5522 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
5523 memcpy(p, l_src[i], count);
5528 return p - (char *)l_to;
5533 /* create a hostent entry
5535 * Creates the entry with enough memory for the name, aliases
5536 * addresses, and the address pointers. Also copies the name
5537 * and sets up all the pointers. If "fill_addresses" is set then
5538 * sufficient memory for the addresses is also allocated and the
5539 * address pointers are set to this memory.
5541 * NOTE: The alias and address lists must be allocated with room
5542 * for the NULL item terminating the list. This is true even if
5543 * the list has no items ("aliases" and "addresses" must be
5544 * at least "1", a truly empty list is invalid).
5546 static struct WS_hostent *WS_create_he(char *name, int aliases, int addresses, int fill_addresses)
5548 struct WS_hostent *p_to;
5551 int size = (sizeof(struct WS_hostent) +
5553 sizeof(char *)*aliases +
5554 sizeof(char *)*addresses);
5556 /* Allocate enough memory for the addresses */
5558 size += sizeof(struct in_addr)*addresses;
5560 if (!(p_to = check_buffer_he(size))) return NULL;
5561 memset(p_to, 0, size);
5563 p = (char *)(p_to + 1);
5568 p_to->h_aliases = (char **)p;
5569 p += sizeof(char *)*aliases;
5570 p_to->h_addr_list = (char **)p;
5571 p += sizeof(char *)*addresses;
5576 /* NOTE: h_aliases must be filled in manually, leave these
5577 * pointers NULL (already set to NULL by memset earlier).
5580 /* Fill in the list of address pointers */
5581 for (i = 0; i < addresses; i++)
5582 p_to->h_addr_list[i] = (p += sizeof(struct in_addr));
5583 p += sizeof(struct in_addr);
5588 /* duplicate hostent entry
5589 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
5590 * Ditto for protoent and servent.
5592 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
5594 int addresses = list_size(p_he->h_addr_list, p_he->h_length);
5595 int aliases = list_size(p_he->h_aliases, 0);
5596 struct WS_hostent *p_to;
5598 p_to = WS_create_he(p_he->h_name, aliases, addresses, FALSE);
5600 if (!p_to) return NULL;
5601 p_to->h_addrtype = p_he->h_addrtype;
5602 p_to->h_length = p_he->h_length;
5604 list_dup(p_he->h_aliases, p_to->h_aliases, 0);
5605 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
5609 /* ----- protoent */
5611 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
5614 struct WS_protoent *p_to;
5616 int size = (sizeof(*p_pe) +
5617 strlen(p_pe->p_name) + 1 +
5618 list_size(p_pe->p_aliases, 0));
5620 if (!(p_to = check_buffer_pe(size))) return NULL;
5621 p_to->p_proto = p_pe->p_proto;
5623 p = (char *)(p_to + 1);
5625 strcpy(p, p_pe->p_name);
5628 p_to->p_aliases = (char **)p;
5629 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
5635 static struct WS_servent *WS_dup_se(const struct servent* p_se)
5638 struct WS_servent *p_to;
5640 int size = (sizeof(*p_se) +
5641 strlen(p_se->s_proto) + 1 +
5642 strlen(p_se->s_name) + 1 +
5643 list_size(p_se->s_aliases, 0));
5645 if (!(p_to = check_buffer_se(size))) return NULL;
5646 p_to->s_port = p_se->s_port;
5648 p = (char *)(p_to + 1);
5650 strcpy(p, p_se->s_name);
5654 strcpy(p, p_se->s_proto);
5657 p_to->s_aliases = (char **)p;
5658 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
5663 /***********************************************************************
5664 * WSARecv (WS2_32.67)
5666 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5667 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
5668 LPWSAOVERLAPPED lpOverlapped,
5669 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
5671 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
5672 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
5675 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5676 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
5677 struct WS_sockaddr *lpFrom,
5678 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
5679 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
5680 LPWSABUF lpControlBuffer )
5682 unsigned int i, options;
5684 struct ws2_async *wsa;
5685 DWORD timeout_start = GetTickCount();
5686 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5688 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
5689 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
5690 (lpFromlen ? *lpFromlen : -1),
5691 lpOverlapped, lpCompletionRoutine);
5693 fd = get_sock_fd( s, FILE_READ_DATA, &options );
5694 TRACE( "fd=%d, options=%x\n", fd, options );
5696 if (fd == -1) return SOCKET_ERROR;
5698 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
5704 wsa->hSocket = SOCKET2HANDLE(s);
5705 wsa->flags = *lpFlags;
5706 wsa->lpFlags = lpFlags;
5708 wsa->addrlen.ptr = lpFromlen;
5709 wsa->control = lpControlBuffer;
5710 wsa->n_iovecs = dwBufferCount;
5711 wsa->first_iovec = 0;
5712 for (i = 0; i < dwBufferCount; i++)
5714 /* check buffer first to trigger write watches */
5715 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
5720 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5721 wsa->iovec[i].iov_len = lpBuffers[i].len;
5726 n = WS2_recv( fd, wsa );
5729 if (errno == EINTR) continue;
5730 if (errno != EAGAIN)
5732 int loc_errno = errno;
5734 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
5739 *lpNumberOfBytesRecvd = n;
5741 if ((lpOverlapped || lpCompletionRoutine) &&
5742 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5744 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5746 wsa->user_overlapped = lpOverlapped;
5747 wsa->completion_func = lpCompletionRoutine;
5748 release_sock_fd( s, fd );
5752 iosb->u.Status = STATUS_PENDING;
5753 iosb->Information = 0;
5755 SERVER_START_REQ( register_async )
5757 req->type = ASYNC_TYPE_READ;
5758 req->async.handle = wine_server_obj_handle( wsa->hSocket );
5759 req->async.callback = wine_server_client_ptr( WS2_async_recv );
5760 req->async.iosb = wine_server_client_ptr( iosb );
5761 req->async.arg = wine_server_client_ptr( wsa );
5762 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
5763 req->async.cvalue = cvalue;
5764 err = wine_server_call( req );
5768 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5769 WSASetLastError( NtStatusToWSAError( err ));
5770 return SOCKET_ERROR;
5773 iosb->u.Status = STATUS_SUCCESS;
5774 iosb->Information = n;
5775 if (!wsa->completion_func)
5777 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5778 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5779 HeapFree( GetProcessHeap(), 0, wsa );
5781 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5782 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5783 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5789 if ( _is_blocking(s) )
5792 int timeout = GET_RCVTIMEO(fd);
5795 timeout -= GetTickCount() - timeout_start;
5796 if (timeout < 0) timeout = 0;
5800 pfd.events = POLLIN;
5801 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
5803 if (!timeout || !poll( &pfd, 1, timeout ))
5806 /* a timeout is not fatal */
5807 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5813 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5814 err = WSAEWOULDBLOCK;
5819 TRACE(" -> %i bytes\n", n);
5820 HeapFree( GetProcessHeap(), 0, wsa );
5821 release_sock_fd( s, fd );
5822 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5827 HeapFree( GetProcessHeap(), 0, wsa );
5828 release_sock_fd( s, fd );
5829 WARN(" -> ERROR %d\n", err);
5830 WSASetLastError( err );
5831 return SOCKET_ERROR;
5834 /***********************************************************************
5835 * WSARecvFrom (WS2_32.69)
5837 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5838 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
5839 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
5840 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5843 return WS2_recv_base( s, lpBuffers, dwBufferCount,
5844 lpNumberOfBytesRecvd, lpFlags,
5846 lpOverlapped, lpCompletionRoutine, NULL );
5849 /***********************************************************************
5850 * WSCInstallProvider (WS2_32.88)
5852 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
5853 LPCWSTR lpszProviderDllPath,
5854 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
5855 DWORD dwNumberOfEntries,
5858 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
5859 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
5860 dwNumberOfEntries, lpErrno);
5866 /***********************************************************************
5867 * WSCDeinstallProvider (WS2_32.83)
5869 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
5871 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
5877 /***********************************************************************
5878 * WSAAccept (WS2_32.26)
5880 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
5881 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
5884 int ret = 0, size = 0;
5885 WSABUF CallerId, CallerData, CalleeId, CalleeData;
5886 /* QOS SQOS, GQOS; */
5889 SOCKADDR src_addr, dst_addr;
5891 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %d\n",
5892 s, addr, addrlen, lpfnCondition, dwCallbackData);
5895 size = sizeof(src_addr);
5896 cs = WS_accept(s, &src_addr, &size);
5898 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
5900 if (!lpfnCondition) return cs;
5902 CallerId.buf = (char *)&src_addr;
5903 CallerId.len = sizeof(src_addr);
5905 CallerData.buf = NULL;
5908 WS_getsockname(cs, &dst_addr, &size);
5910 CalleeId.buf = (char *)&dst_addr;
5911 CalleeId.len = sizeof(dst_addr);
5914 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
5915 &CalleeId, &CalleeData, &g, dwCallbackData);
5920 if (addr && addrlen)
5921 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
5924 SERVER_START_REQ( set_socket_deferred )
5926 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5927 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
5928 if ( !wine_server_call_err ( req ) )
5930 SetLastError( WSATRY_AGAIN );
5931 WS_closesocket( cs );
5935 return SOCKET_ERROR;
5938 SetLastError(WSAECONNREFUSED);
5939 return SOCKET_ERROR;
5941 FIXME("Unknown return type from Condition function\n");
5942 SetLastError(WSAENOTSOCK);
5943 return SOCKET_ERROR;
5947 /***********************************************************************
5948 * WSADuplicateSocketA (WS2_32.32)
5950 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
5954 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
5955 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
5956 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
5957 /* I don't know what the real Windoze does next, this is a hack */
5958 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
5959 * the target use the global duplicate, or we could copy a reference to us to the structure
5960 * and let the target duplicate it from us, but let's do it as simple as possible */
5961 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
5962 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
5963 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
5964 0, FALSE, DUPLICATE_SAME_ACCESS);
5965 CloseHandle(hProcess);
5966 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
5970 /***********************************************************************
5971 * WSADuplicateSocketW (WS2_32.33)
5973 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
5977 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
5979 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
5980 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
5981 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
5982 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
5983 0, FALSE, DUPLICATE_SAME_ACCESS);
5984 CloseHandle(hProcess);
5985 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
5989 /***********************************************************************
5990 * WSAInstallServiceClassA (WS2_32.48)
5992 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
5994 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
5995 WSASetLastError(WSAEACCES);
5996 return SOCKET_ERROR;
5999 /***********************************************************************
6000 * WSAInstallServiceClassW (WS2_32.49)
6002 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
6004 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
6005 WSASetLastError(WSAEACCES);
6006 return SOCKET_ERROR;
6009 /***********************************************************************
6010 * WSARemoveServiceClass (WS2_32.70)
6012 int WINAPI WSARemoveServiceClass(LPGUID info)
6014 FIXME("Request to remove service %p\n",info);
6015 WSASetLastError(WSATYPE_NOT_FOUND);
6016 return SOCKET_ERROR;
6019 /***********************************************************************
6020 * inet_ntop (WS2_32.@)
6022 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
6024 #ifdef HAVE_INET_NTOP
6025 struct WS_in6_addr *in6;
6026 struct WS_in_addr *in;
6029 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
6032 WSASetLastError( STATUS_INVALID_PARAMETER );
6041 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
6047 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
6051 WSASetLastError( WSAEAFNOSUPPORT );
6055 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
6058 FIXME( "not supported on this platform\n" );
6059 WSASetLastError( WSAEAFNOSUPPORT );
6064 /***********************************************************************
6065 * WSAStringToAddressA (WS2_32.80)
6067 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
6069 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6070 LPSOCKADDR lpAddress,
6071 LPINT lpAddressLength)
6074 LPSTR workBuffer=NULL,ptrPort;
6076 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
6077 lpProtocolInfo, lpAddress, lpAddressLength );
6079 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6083 WSASetLastError(WSAEINVAL);
6084 return SOCKET_ERROR;
6088 FIXME("ProtocolInfo not implemented.\n");
6090 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
6091 strlen(AddressString) + 1);
6094 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6095 return SOCKET_ERROR;
6098 strcpy(workBuffer, AddressString);
6100 switch(AddressFamily)
6104 struct in_addr inetaddr;
6106 /* If lpAddressLength is too small, tell caller the size we need */
6107 if (*lpAddressLength < sizeof(SOCKADDR_IN))
6109 *lpAddressLength = sizeof(SOCKADDR_IN);
6113 *lpAddressLength = sizeof(SOCKADDR_IN);
6114 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
6116 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
6118 ptrPort = strchr(workBuffer, ':');
6121 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
6126 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
6129 if(inet_aton(workBuffer, &inetaddr) > 0)
6131 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
6142 struct in6_addr inetaddr;
6143 /* If lpAddressLength is too small, tell caller the size we need */
6144 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
6146 *lpAddressLength = sizeof(SOCKADDR_IN6);
6150 #ifdef HAVE_INET_PTON
6151 *lpAddressLength = sizeof(SOCKADDR_IN6);
6152 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
6154 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
6156 /* This one is a bit tricky. An IPv6 address contains colons, so the
6157 * check from IPv4 doesn't work like that. However, IPv6 addresses that
6158 * contain a port are written with braces like [fd12:3456:7890::1]:12345
6159 * so what we will do is to look for ']', check if the next char is a
6160 * colon, and if it is, parse the port as in IPv4. */
6162 ptrPort = strchr(workBuffer, ']');
6163 if(ptrPort && *(++ptrPort) == ':')
6165 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
6170 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
6173 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
6175 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
6176 sizeof(struct in6_addr));
6180 #endif /* HAVE_INET_PTON */
6186 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
6187 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
6191 HeapFree(GetProcessHeap(), 0, workBuffer);
6194 WSASetLastError(res);
6195 return SOCKET_ERROR;
6198 /***********************************************************************
6199 * WSAStringToAddressW (WS2_32.81)
6201 * Does anybody know if this functions allows to use hebrew/arabic/chinese... digits?
6202 * If this should be the case, it would be required to map these digits
6203 * to Unicode digits (0-9) using FoldString first.
6205 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
6207 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6208 LPSOCKADDR lpAddress,
6209 LPINT lpAddressLength)
6212 LPSTR workBuffer=NULL;
6213 WSAPROTOCOL_INFOA infoA;
6214 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
6216 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
6217 lpAddress, lpAddressLength );
6219 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6221 /* if ProtocolInfo is available - convert to ANSI variant */
6224 lpProtoInfoA = &infoA;
6225 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
6227 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6228 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
6230 WSASetLastError( WSAEINVAL);
6231 return SOCKET_ERROR;
6237 /* Translate AddressString to ANSI code page - assumes that only
6238 standard digits 0-9 are used with this API call */
6239 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
6240 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
6244 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
6245 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
6246 lpAddress,lpAddressLength);
6247 HeapFree( GetProcessHeap(), 0, workBuffer );
6251 res = WSA_NOT_ENOUGH_MEMORY;
6256 WSASetLastError(res);
6257 return SOCKET_ERROR;
6260 /***********************************************************************
6261 * WSAAddressToStringA (WS2_32.27)
6263 * See WSAAddressToStringW
6265 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
6266 LPWSAPROTOCOL_INFOA info, LPSTR string,
6270 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6273 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6275 if (!sockaddr) return SOCKET_ERROR;
6276 if (!string || !lenstr) return SOCKET_ERROR;
6278 switch(sockaddr->sa_family)
6281 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
6282 sprintf( buffer, "%u.%u.%u.%u:%u",
6283 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
6284 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
6285 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
6286 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
6287 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
6289 p = strchr( buffer, ':' );
6290 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
6295 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
6298 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
6299 if ((sockaddr6->sin6_port))
6300 strcpy(buffer, "[");
6301 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
6303 WSASetLastError(WSAEINVAL);
6304 return SOCKET_ERROR;
6306 if ((sockaddr6->sin6_scope_id))
6307 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
6308 if ((sockaddr6->sin6_port))
6309 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
6314 WSASetLastError(WSAEINVAL);
6315 return SOCKET_ERROR;
6318 size = strlen( buffer ) + 1;
6323 WSASetLastError(WSAEFAULT);
6324 return SOCKET_ERROR;
6328 strcpy( string, buffer );
6332 /***********************************************************************
6333 * WSAAddressToStringW (WS2_32.28)
6335 * Convert a sockaddr address into a readable address string.
6338 * sockaddr [I] Pointer to a sockaddr structure.
6339 * len [I] Size of the sockaddr structure.
6340 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
6341 * string [I/O] Pointer to a buffer to receive the address string.
6342 * lenstr [I/O] Size of the receive buffer in WCHARs.
6346 * Failure: SOCKET_ERROR
6349 * The 'info' parameter is ignored.
6351 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
6352 LPWSAPROTOCOL_INFOW info, LPWSTR string,
6357 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6360 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6363 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
6365 if (ret) return ret;
6367 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
6372 WSASetLastError(WSAEFAULT);
6373 return SOCKET_ERROR;
6377 lstrcpyW( string, buffer );
6381 /***********************************************************************
6382 * WSAEnumNameSpaceProvidersA (WS2_32.34)
6384 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
6386 FIXME( "(%p %p) Stub!\n", len, buffer );
6390 /***********************************************************************
6391 * WSAEnumNameSpaceProvidersW (WS2_32.35)
6393 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
6395 FIXME( "(%p %p) Stub!\n", len, buffer );
6399 /***********************************************************************
6400 * WSAGetQOSByName (WS2_32.41)
6402 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
6404 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
6408 /***********************************************************************
6409 * WSAGetServiceClassInfoA (WS2_32.42)
6411 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
6412 LPWSASERVICECLASSINFOA info )
6414 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
6416 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6417 return SOCKET_ERROR;
6420 /***********************************************************************
6421 * WSAGetServiceClassInfoW (WS2_32.43)
6423 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
6424 LPWSASERVICECLASSINFOW info )
6426 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
6428 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6429 return SOCKET_ERROR;
6432 /***********************************************************************
6433 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
6435 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
6437 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6438 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6439 return SOCKET_ERROR;
6442 /***********************************************************************
6443 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
6445 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
6447 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6448 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6449 return SOCKET_ERROR;
6452 /***********************************************************************
6453 * WSALookupServiceBeginA (WS2_32.59)
6455 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
6456 DWORD dwControlFlags,
6459 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6461 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6462 return SOCKET_ERROR;
6465 /***********************************************************************
6466 * WSALookupServiceBeginW (WS2_32.60)
6468 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
6469 DWORD dwControlFlags,
6472 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6474 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6475 return SOCKET_ERROR;
6478 /***********************************************************************
6479 * WSALookupServiceBeginW (WS2_32.61)
6481 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
6483 FIXME("(%p) Stub!\n", lookup );
6487 /***********************************************************************
6488 * WSALookupServiceNextA (WS2_32.62)
6490 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
6492 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6493 WSASetLastError(WSA_E_NO_MORE);
6494 return SOCKET_ERROR;
6497 /***********************************************************************
6498 * WSALookupServiceNextW (WS2_32.63)
6500 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
6502 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6503 WSASetLastError(WSA_E_NO_MORE);
6504 return SOCKET_ERROR;
6507 /***********************************************************************
6508 * WSANtohl (WS2_32.64)
6510 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
6512 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
6514 if (!lphostlong) return WSAEFAULT;
6516 *lphostlong = ntohl( netlong );
6520 /***********************************************************************
6521 * WSANtohs (WS2_32.65)
6523 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
6525 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
6527 if (!lphostshort) return WSAEFAULT;
6529 *lphostshort = ntohs( netshort );
6533 /***********************************************************************
6534 * WSAProviderConfigChange (WS2_32.66)
6536 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
6537 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
6539 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
6540 return SOCKET_ERROR;
6543 /***********************************************************************
6544 * WSARecvDisconnect (WS2_32.68)
6546 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
6548 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
6550 return WS_shutdown( s, 0 );
6553 /***********************************************************************
6554 * WSASetServiceA (WS2_32.76)
6556 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
6558 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6562 /***********************************************************************
6563 * WSASetServiceW (WS2_32.77)
6565 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
6567 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6571 /***********************************************************************
6572 * WSCEnableNSProvider (WS2_32.84)
6574 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
6576 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
6580 /***********************************************************************
6581 * WSCGetProviderPath (WS2_32.86)
6583 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
6585 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
6587 if (!errcode || !provider || !len) return WSAEFAULT;
6589 *errcode = WSAEINVAL;
6590 return SOCKET_ERROR;
6593 /***********************************************************************
6594 * WSCInstallNameSpace (WS2_32.87)
6596 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
6597 DWORD version, LPGUID provider )
6599 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
6600 namespace, version, debugstr_guid(provider) );
6604 /***********************************************************************
6605 * WSCUnInstallNameSpace (WS2_32.89)
6607 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
6609 FIXME("(%p) Stub!\n", lpProviderId);
6613 /***********************************************************************
6614 * WSCWriteProviderOrder (WS2_32.91)
6616 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
6618 FIXME("(%p 0x%08x) Stub!\n", entry, number);
6622 /***********************************************************************
6623 * WSANSPIoctl (WS2_32.91)
6625 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
6626 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
6627 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
6629 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
6630 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
6631 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6632 return SOCKET_ERROR;