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;
1729 hdr.msg_name = NULL;
1730 hdr.msg_namelen = 0;
1734 hdr.msg_name = &unix_addr;
1735 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
1736 if ( !hdr.msg_namelen )
1742 #if defined(HAVE_IPX) && defined(SOL_IPX)
1743 if(wsa->addr->sa_family == WS_AF_IPX)
1745 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1747 unsigned int len=sizeof(int);
1749 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1750 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1751 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1752 * ipx type in the sockaddr_opx structure with the stored value.
1754 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1755 uipx->sipx_type = val;
1760 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1761 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1762 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1763 hdr.msg_accrights = NULL;
1764 hdr.msg_accrightslen = 0;
1766 hdr.msg_control = NULL;
1767 hdr.msg_controllen = 0;
1771 return sendmsg(fd, &hdr, wsa->flags);
1774 /***********************************************************************
1775 * WS2_async_send (INTERNAL)
1777 * Handler for overlapped send() operations.
1779 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1781 ws2_async* wsa = user;
1786 case STATUS_ALERTED:
1787 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1790 /* check to see if the data is ready (non-blocking) */
1791 result = WS2_send( fd, wsa );
1792 wine_server_release_fd( wsa->hSocket, fd );
1796 int totalLength = 0;
1798 status = STATUS_SUCCESS;
1799 for (i = 0; i < wsa->n_iovecs; i++)
1800 totalLength += wsa->iovec[i].iov_len;
1801 if (result < totalLength)
1802 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1806 if (errno == EINTR || errno == EAGAIN)
1808 status = STATUS_PENDING;
1809 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1813 status = wsaErrStatus();
1819 if (status != STATUS_PENDING)
1821 iosb->u.Status = status;
1822 iosb->Information = result;
1823 *apc = ws2_async_apc;
1828 /***********************************************************************
1829 * WS2_async_shutdown (INTERNAL)
1831 * Handler for shutdown() operations on overlapped sockets.
1833 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
1835 ws2_async* wsa = user;
1840 case STATUS_ALERTED:
1841 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1844 switch ( wsa->type )
1846 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1847 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1849 status = err ? wsaErrStatus() : STATUS_SUCCESS;
1850 wine_server_release_fd( wsa->hSocket, fd );
1853 iosb->u.Status = status;
1854 iosb->Information = 0;
1855 *apc = ws2_async_apc;
1859 /***********************************************************************
1860 * WS2_register_async_shutdown (INTERNAL)
1862 * Helper function for WS_shutdown() on overlapped sockets.
1864 static int WS2_register_async_shutdown( SOCKET s, int type )
1866 struct ws2_async *wsa;
1869 TRACE("s %ld type %d\n", s, type);
1871 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1875 wsa->hSocket = SOCKET2HANDLE(s);
1877 wsa->completion_func = NULL;
1879 SERVER_START_REQ( register_async )
1882 req->async.handle = wine_server_obj_handle( wsa->hSocket );
1883 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
1884 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
1885 req->async.arg = wine_server_client_ptr( wsa );
1886 req->async.cvalue = 0;
1887 status = wine_server_call( req );
1891 if (status != STATUS_PENDING)
1893 HeapFree( GetProcessHeap(), 0, wsa );
1894 return NtStatusToWSAError( status );
1899 /***********************************************************************
1902 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1909 TRACE("socket %04lx\n", s );
1910 is_blocking = _is_blocking(s);
1913 /* try accepting first (if there is a deferred connection) */
1914 SERVER_START_REQ( accept_socket )
1916 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1917 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1918 req->attributes = OBJ_INHERIT;
1919 status = wine_server_call( req );
1920 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
1925 if (addr) WS_getpeername(as, addr, addrlen32);
1928 if (is_blocking && status == STATUS_CANT_WAIT)
1930 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1932 do_block(fd, POLLIN, -1);
1933 _sync_sock_state(s); /* let wineserver notice connection */
1934 release_sock_fd( s, fd );
1936 } while (is_blocking && status == STATUS_CANT_WAIT);
1939 return INVALID_SOCKET;
1942 /***********************************************************************
1945 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
1946 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
1947 LPOVERLAPPED overlapped)
1950 struct ws2_accept_async *wsa;
1952 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
1954 TRACE("(%lx, %lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
1955 rem_addr_len, received, overlapped);
1959 SetLastError(WSAEINVAL);
1965 SetLastError(WSA_INVALID_PARAMETER);
1969 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
1972 SetLastError(WSAENOTSOCK);
1975 release_sock_fd( listener, fd );
1977 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
1980 SetLastError(WSAEINVAL);
1983 release_sock_fd( acceptor, fd );
1985 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1988 SetLastError(WSAEFAULT);
1992 wsa->listen_socket = SOCKET2HANDLE(listener);
1993 wsa->accept_socket = SOCKET2HANDLE(acceptor);
1994 wsa->user_overlapped = overlapped;
1995 wsa->cvalue = cvalue;
1997 wsa->data_len = dest_len;
1998 wsa->local_len = local_addr_len;
1999 wsa->remote_len = rem_addr_len;
2004 /* set up a read request if we need it */
2005 wsa->read = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[1]) );
2008 HeapFree( GetProcessHeap(), 0, wsa );
2009 SetLastError(WSAEFAULT);
2013 wsa->read->hSocket = wsa->accept_socket;
2014 wsa->read->flags = 0;
2015 wsa->read->lpFlags = &wsa->read->flags;
2016 wsa->read->addr = NULL;
2017 wsa->read->addrlen.ptr = NULL;
2018 wsa->read->control = NULL;
2019 wsa->read->n_iovecs = 1;
2020 wsa->read->first_iovec = 0;
2021 wsa->read->iovec[0].iov_base = wsa->buf;
2022 wsa->read->iovec[0].iov_len = wsa->data_len;
2025 SERVER_START_REQ( register_async )
2027 req->type = ASYNC_TYPE_READ;
2028 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2029 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2030 req->async.iosb = wine_server_client_ptr( overlapped );
2031 req->async.arg = wine_server_client_ptr( wsa );
2032 /* We don't set event or completion since we may also have to read */
2033 status = wine_server_call( req );
2037 if(status != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
2039 SetLastError( NtStatusToWSAError(status) );
2043 /***********************************************************************
2044 * GetAcceptExSockaddrs
2046 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2047 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2048 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2050 char *cbuf = buffer;
2051 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2052 local_addr_len, remote_addr, remote_addr_len );
2055 *local_addr_len = *(int *) cbuf;
2056 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2060 *remote_addr_len = *(int *) cbuf;
2061 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2064 /***********************************************************************
2067 * Perform a receive operation that is capable of returning message
2068 * control headers. It is important to note that the WSAMSG parameter
2069 * must remain valid throughout the operation, even when an overlapped
2070 * receive is performed.
2072 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2073 LPWSAOVERLAPPED lpOverlapped,
2074 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2078 SetLastError( WSAEFAULT );
2079 return SOCKET_ERROR;
2082 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2083 &msg->dwFlags, msg->name, &msg->namelen,
2084 lpOverlapped, lpCompletionRoutine, &msg->Control );
2087 /***********************************************************************
2090 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2092 int fd = get_sock_fd( s, 0, NULL );
2093 int res = SOCKET_ERROR;
2095 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2099 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2101 SetLastError(WSAEAFNOSUPPORT);
2105 union generic_unix_sockaddr uaddr;
2106 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2109 SetLastError(WSAEFAULT);
2114 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2115 if (name->sa_family == WS_AF_INET6 &&
2116 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2119 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2121 release_sock_fd( s, fd );
2122 SetLastError(WSAEAFNOSUPPORT);
2123 return SOCKET_ERROR;
2127 if (name->sa_family == WS_AF_INET)
2129 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2130 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2132 /* Trying to bind to the default host interface, using
2133 * INADDR_ANY instead*/
2134 WARN("Trying to bind to magic IP address, using "
2135 "INADDR_ANY instead.\n");
2136 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
2139 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2141 int loc_errno = errno;
2142 WARN("\tfailure - errno = %i\n", errno);
2147 SetLastError(WSAENOTSOCK);
2150 SetLastError(WSAEINVAL);
2153 SetLastError(wsaErrno());
2159 res=0; /* success */
2163 release_sock_fd( s, fd );
2168 /***********************************************************************
2169 * closesocket (WS2_32.3)
2171 int WINAPI WS_closesocket(SOCKET s)
2173 TRACE("socket %04lx\n", s);
2174 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
2175 return SOCKET_ERROR;
2178 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2180 union generic_unix_sockaddr uaddr;
2181 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2186 if (name->sa_family == WS_AF_INET)
2188 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2189 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2191 /* Trying to connect to magic replace-loopback address,
2192 * assuming we really want to connect to localhost */
2193 TRACE("Trying to connect to magic IP address, using "
2194 "INADDR_LOOPBACK instead.\n");
2195 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
2199 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
2205 /***********************************************************************
2206 * connect (WS2_32.4)
2208 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
2210 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2212 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2216 int ret = do_connect(fd, name, namelen);
2218 goto connect_success;
2220 if (ret == WSAEINPROGRESS)
2222 /* tell wineserver that a connection is in progress */
2223 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2225 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2226 if (_is_blocking(s))
2230 do_block(fd, POLLIN | POLLOUT, -1);
2231 _sync_sock_state(s); /* let wineserver notice connection */
2232 /* retrieve any error codes from it */
2233 result = _get_sock_error(s, FD_CONNECT_BIT);
2235 SetLastError(NtStatusToWSAError(result));
2238 goto connect_success;
2243 SetLastError(WSAEWOULDBLOCK);
2250 release_sock_fd( s, fd );
2252 return SOCKET_ERROR;
2255 release_sock_fd( s, fd );
2256 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2257 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2258 FD_CONNECT|FD_WINE_LISTENING);
2262 /***********************************************************************
2263 * WSAConnect (WS2_32.30)
2265 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
2266 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
2267 LPQOS lpSQOS, LPQOS lpGQOS )
2269 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
2270 FIXME("unsupported parameters!\n");
2271 return WS_connect( s, name, namelen );
2274 /***********************************************************************
2277 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
2278 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
2280 int fd, ret, status;
2284 SetLastError( ERROR_INVALID_PARAMETER );
2288 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2291 SetLastError( WSAENOTSOCK );
2295 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
2296 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
2298 /* FIXME: technically the socket has to be bound */
2299 ret = do_connect(fd, name, namelen);
2304 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2305 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2306 FD_CONNECT|FD_WINE_LISTENING);
2308 wsabuf.len = sendBufLen;
2309 wsabuf.buf = (char*) sendBuf;
2311 /* WSASend takes care of completion if need be */
2312 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
2313 goto connection_success;
2315 else if (ret == WSAEINPROGRESS)
2317 struct ws2_async *wsa;
2318 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
2320 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2322 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2324 /* Indirectly call WSASend */
2325 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) )))
2327 SetLastError(WSAEFAULT);
2331 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
2332 iosb->u.Status = STATUS_PENDING;
2333 iosb->Information = 0;
2335 wsa->hSocket = SOCKET2HANDLE(s);
2337 wsa->addrlen.val = 0;
2339 wsa->lpFlags = &wsa->flags;
2340 wsa->control = NULL;
2341 wsa->n_iovecs = sendBuf ? 1 : 0;
2342 wsa->first_iovec = 0;
2343 wsa->completion_func = NULL;
2344 wsa->iovec[0].iov_base = sendBuf;
2345 wsa->iovec[0].iov_len = sendBufLen;
2347 SERVER_START_REQ( register_async )
2349 req->type = ASYNC_TYPE_WRITE;
2350 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2351 req->async.callback = wine_server_client_ptr( WS2_async_send );
2352 req->async.iosb = wine_server_client_ptr( iosb );
2353 req->async.arg = wine_server_client_ptr( wsa );
2354 req->async.event = wine_server_obj_handle( ov->hEvent );
2355 req->async.cvalue = cvalue;
2356 status = wine_server_call( req );
2360 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
2362 /* If the connect already failed */
2363 if (status == STATUS_PIPE_DISCONNECTED)
2364 status = _get_sock_error(s, FD_CONNECT_BIT);
2365 SetLastError( NtStatusToWSAError(status) );
2373 release_sock_fd( s, fd );
2377 release_sock_fd( s, fd );
2382 /***********************************************************************
2383 * getpeername (WS2_32.5)
2385 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
2390 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen?*namelen:0);
2392 fd = get_sock_fd( s, 0, NULL );
2397 union generic_unix_sockaddr uaddr;
2398 unsigned int uaddrlen = sizeof(uaddr);
2400 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
2402 if (!name || !namelen)
2403 SetLastError(WSAEFAULT);
2404 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2405 /* The buffer was too small */
2406 SetLastError(WSAEFAULT);
2411 SetLastError(wsaErrno());
2412 release_sock_fd( s, fd );
2417 /***********************************************************************
2418 * getsockname (WS2_32.6)
2420 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
2425 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
2427 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
2428 if( (name == NULL) || (namelen == NULL) )
2430 SetLastError( WSAEFAULT );
2431 return SOCKET_ERROR;
2434 fd = get_sock_fd( s, 0, NULL );
2439 union generic_unix_sockaddr uaddr;
2440 unsigned int uaddrlen = sizeof(uaddr);
2442 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2444 SetLastError(wsaErrno());
2446 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2448 SetLastError(WSAEINVAL);
2450 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2452 /* The buffer was too small */
2453 SetLastError(WSAEFAULT);
2459 release_sock_fd( s, fd );
2464 /***********************************************************************
2465 * getsockopt (WS2_32.7)
2467 INT WINAPI WS_getsockopt(SOCKET s, INT level,
2468 INT optname, char *optval, INT *optlen)
2473 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2474 s, level, optname, optval, *optlen);
2482 /* Handle common cases. The special cases are below, sorted
2484 case WS_SO_ACCEPTCONN:
2485 case WS_SO_BROADCAST:
2488 case WS_SO_KEEPALIVE:
2489 case WS_SO_OOBINLINE:
2491 case WS_SO_REUSEADDR:
2494 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2495 return SOCKET_ERROR;
2496 convert_sockopt(&level, &optname);
2497 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2499 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2502 release_sock_fd( s, fd );
2505 case WS_SO_DONTLINGER:
2507 struct linger lingval;
2508 unsigned int len = sizeof(struct linger);
2510 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
2512 SetLastError(WSAEFAULT);
2513 return SOCKET_ERROR;
2515 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2516 return SOCKET_ERROR;
2518 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
2520 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2525 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
2526 *optlen = sizeof(BOOL);
2529 release_sock_fd( s, fd );
2533 /* As mentioned in setsockopt, Windows ignores this, so we
2534 * always return true here */
2535 case WS_SO_DONTROUTE:
2536 if (!optlen || *optlen < sizeof(BOOL) || !optval)
2538 SetLastError(WSAEFAULT);
2539 return SOCKET_ERROR;
2541 *(BOOL *)optval = TRUE;
2542 *optlen = sizeof(BOOL);
2547 struct linger lingval;
2548 unsigned int len = sizeof(struct linger);
2550 /* struct linger and LINGER have different sizes */
2551 if (!optlen || *optlen < sizeof(LINGER) || !optval)
2553 SetLastError(WSAEFAULT);
2554 return SOCKET_ERROR;
2556 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2557 return SOCKET_ERROR;
2559 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
2561 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2566 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
2567 ((LINGER *)optval)->l_linger = lingval.l_linger;
2568 *optlen = sizeof(struct linger);
2571 release_sock_fd( s, fd );
2575 case WS_SO_MAX_MSG_SIZE:
2576 if (!optlen || *optlen < sizeof(int) || !optval)
2578 SetLastError(WSAEFAULT);
2579 return SOCKET_ERROR;
2581 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
2582 *(int *)optval = 65507;
2583 *optlen = sizeof(int);
2586 /* SO_OPENTYPE does not require a valid socket handle. */
2587 case WS_SO_OPENTYPE:
2588 if (!optlen || *optlen < sizeof(int) || !optval)
2590 SetLastError(WSAEFAULT);
2591 return SOCKET_ERROR;
2593 *(int *)optval = get_per_thread_data()->opentype;
2594 *optlen = sizeof(int);
2595 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2599 case WS_SO_RCVTIMEO:
2602 case WS_SO_SNDTIMEO:
2604 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
2607 unsigned int len = sizeof(struct timeval);
2609 if (!optlen || *optlen < sizeof(int)|| !optval)
2611 SetLastError(WSAEFAULT);
2612 return SOCKET_ERROR;
2614 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2615 return SOCKET_ERROR;
2617 convert_sockopt(&level, &optname);
2618 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
2620 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2625 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
2626 *optlen = sizeof(int);
2629 release_sock_fd( s, fd );
2634 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
2635 SetLastError(WSAENOPROTOOPT);
2636 return SOCKET_ERROR;
2637 } /* end switch(optname) */
2638 }/* end case WS_SOL_SOCKET */
2642 struct WS_sockaddr_ipx addr;
2643 IPX_ADDRESS_DATA *data;
2648 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
2650 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
2657 socklen_t len=sizeof(struct ipx);
2658 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
2661 *optval = (int)val.ipx_pt;
2664 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
2665 release_sock_fd( s, fd );
2670 * On a Win2000 system with one network card there are usually
2671 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
2672 * Using this call you can then retrieve info about this all.
2673 * In case of Linux it is a bit different. Usually you have
2674 * only "one" device active and further it is not possible to
2675 * query things like the linkspeed.
2677 FIXME("IPX_ADDRESS\n");
2678 namelen = sizeof(struct WS_sockaddr_ipx);
2679 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
2680 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
2682 data = (IPX_ADDRESS_DATA*)optval;
2683 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
2684 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
2685 data->adapternum = 0;
2686 data->wan = FALSE; /* We are not on a wan for now .. */
2687 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
2688 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
2689 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
2690 * note 1MB = 1000kB in this case */
2693 case IPX_MAX_ADAPTER_NUM:
2694 FIXME("IPX_MAX_ADAPTER_NUM\n");
2695 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
2699 FIXME("IPX optname:%x\n", optname);
2700 return SOCKET_ERROR;
2701 }/* end switch(optname) */
2702 } /* end case NSPROTO_IPX */
2709 case WS_IRLMP_ENUMDEVICES:
2711 static const int MAX_IRDA_DEVICES = 10;
2712 char buf[sizeof(struct irda_device_list) +
2713 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
2715 socklen_t len = sizeof(buf);
2717 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2718 return SOCKET_ERROR;
2719 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
2722 SetLastError(wsaErrno());
2723 return SOCKET_ERROR;
2727 struct irda_device_list *src = (struct irda_device_list *)buf;
2728 DEVICELIST *dst = (DEVICELIST *)optval;
2729 INT needed = sizeof(DEVICELIST), i;
2732 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
2733 if (*optlen < needed)
2735 SetLastError(WSAEFAULT);
2736 return SOCKET_ERROR;
2739 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
2740 dst->numDevice = src->len;
2741 for (i = 0; i < src->len; i++)
2743 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
2744 src->dev[i].saddr, src->dev[i].daddr,
2745 src->dev[i].info, src->dev[i].hints[0],
2746 src->dev[i].hints[1]);
2747 memcpy( dst->Device[i].irdaDeviceID,
2749 sizeof(dst->Device[i].irdaDeviceID) ) ;
2750 memcpy( dst->Device[i].irdaDeviceName,
2752 sizeof(dst->Device[i].irdaDeviceName) ) ;
2753 memcpy( &dst->Device[i].irdaDeviceHints1,
2754 &src->dev[i].hints[0],
2755 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
2756 memcpy( &dst->Device[i].irdaDeviceHints2,
2757 &src->dev[i].hints[1],
2758 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
2759 dst->Device[i].irdaCharSet = src->dev[i].charset;
2765 FIXME("IrDA optname:0x%x\n", optname);
2766 return SOCKET_ERROR;
2768 break; /* case WS_SOL_IRLMP */
2771 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
2772 case WS_IPPROTO_TCP:
2775 case WS_TCP_NODELAY:
2776 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2777 return SOCKET_ERROR;
2778 convert_sockopt(&level, &optname);
2779 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2781 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2784 release_sock_fd( s, fd );
2787 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
2788 return SOCKET_ERROR;
2793 case WS_IP_ADD_MEMBERSHIP:
2794 case WS_IP_DROP_MEMBERSHIP:
2798 case WS_IP_MULTICAST_IF:
2799 case WS_IP_MULTICAST_LOOP:
2800 case WS_IP_MULTICAST_TTL:
2807 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2808 return SOCKET_ERROR;
2809 convert_sockopt(&level, &optname);
2810 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2812 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2815 release_sock_fd( s, fd );
2817 case WS_IP_DONTFRAGMENT:
2818 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
2819 *(BOOL*)optval = FALSE;
2822 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
2823 return SOCKET_ERROR;
2825 case WS_IPPROTO_IPV6:
2828 #ifdef IPV6_ADD_MEMBERSHIP
2829 case WS_IPV6_ADD_MEMBERSHIP:
2831 #ifdef IPV6_DROP_MEMBERSHIP
2832 case WS_IPV6_DROP_MEMBERSHIP:
2834 case WS_IPV6_MULTICAST_IF:
2835 case WS_IPV6_MULTICAST_HOPS:
2836 case WS_IPV6_MULTICAST_LOOP:
2837 case WS_IPV6_UNICAST_HOPS:
2838 case WS_IPV6_V6ONLY:
2839 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2840 return SOCKET_ERROR;
2841 convert_sockopt(&level, &optname);
2842 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2844 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2847 release_sock_fd( s, fd );
2849 case WS_IPV6_DONTFRAG:
2850 FIXME("WS_IPV6_DONTFRAG is always false!\n");
2851 *(BOOL*)optval = FALSE;
2854 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
2855 return SOCKET_ERROR;
2858 WARN("Unknown level: 0x%08x\n", level);
2859 SetLastError(WSAEINVAL);
2860 return SOCKET_ERROR;
2861 } /* end switch(level) */
2864 /***********************************************************************
2867 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
2869 return htonl(hostlong);
2873 /***********************************************************************
2876 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
2878 return htons(hostshort);
2881 /***********************************************************************
2882 * WSAHtonl (WS2_32.46)
2883 * From MSDN description of error codes, this function should also
2884 * check if WinSock has been initialized and the socket is a valid
2885 * socket. But why? This function only translates a host byte order
2886 * u_long into a network byte order u_long...
2888 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
2892 *lpnetlong = htonl(hostlong);
2895 WSASetLastError(WSAEFAULT);
2896 return SOCKET_ERROR;
2899 /***********************************************************************
2900 * WSAHtons (WS2_32.47)
2901 * From MSDN description of error codes, this function should also
2902 * check if WinSock has been initialized and the socket is a valid
2903 * socket. But why? This function only translates a host byte order
2904 * u_short into a network byte order u_short...
2906 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2911 *lpnetshort = htons(hostshort);
2914 WSASetLastError(WSAEFAULT);
2915 return SOCKET_ERROR;
2919 /***********************************************************************
2920 * inet_addr (WS2_32.11)
2922 WS_u_long WINAPI WS_inet_addr(const char *cp)
2924 if (!cp) return INADDR_NONE;
2925 return inet_addr(cp);
2929 /***********************************************************************
2932 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2934 return ntohl(netlong);
2938 /***********************************************************************
2941 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2943 return ntohs(netshort);
2947 /***********************************************************************
2948 * inet_ntoa (WS2_32.12)
2950 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2952 /* use "buffer for dummies" here because some applications have a
2953 * propensity to decode addresses in ws_hostent structure without
2954 * saving them first...
2956 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2958 char* s = inet_ntoa(*((struct in_addr*)&in));
2964 SetLastError(wsaErrno());
2968 static const char *debugstr_wsaioctl(DWORD ioctl)
2970 switch(ioctl & 0x18000000)
2974 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
2975 char x = (ioctl & 0xff00) >> 8;
2976 BYTE y = ioctl & 0xff;
2977 const char *buf_type;
2980 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
2984 sprintf(args, "%d, %d", x, y);
2988 sprintf(args, "'%c', %d, %d", x, y, size);
2992 sprintf(args, "'%c', %d, %d", x, y, size);
2996 sprintf(args, "'%c', %d, %d", x, y, size);
2999 return wine_dbg_sprintf("%s(%s)", buf_type, args);
3003 USHORT code = ioctl & 0xffff;
3004 const char *family, *buf_type;
3006 /* This switch looks redundant, but isn't: the case WS_IOC_UNIX
3007 * is handled differently than all others.
3009 switch(ioctl & 0x18000000)
3014 case WS_IOC_PROTOCOL:
3015 family = "IOC_PROTOCOL";
3018 family = "IOC_VENDOR";
3021 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3024 buf_type = "_WSAIO";
3027 buf_type = "_WSAIORW";
3030 buf_type = "_WSAIOW";
3033 buf_type = "_WSAIOR";
3039 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family, code);
3044 /**********************************************************************
3045 * WSAIoctl (WS2_32.50)
3048 INT WINAPI WSAIoctl(SOCKET s,
3049 DWORD dwIoControlCode,
3052 LPVOID lpbOutBuffer,
3054 LPDWORD lpcbBytesReturned,
3055 LPWSAOVERLAPPED lpOverlapped,
3056 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
3058 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
3059 s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpbOutBuffer,
3060 cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
3062 switch( dwIoControlCode )
3065 if (cbInBuffer != sizeof(WS_u_long)) {
3066 WSASetLastError(WSAEFAULT);
3067 return SOCKET_ERROR;
3069 return WS_ioctlsocket( s, WS_FIONBIO, lpvInBuffer);
3072 if (cbOutBuffer != sizeof(WS_u_long)) {
3073 WSASetLastError(WSAEFAULT);
3074 return SOCKET_ERROR;
3076 return WS_ioctlsocket( s, WS_FIONREAD, lpbOutBuffer);
3078 case WS_SIO_GET_INTERFACE_LIST:
3080 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
3081 DWORD size, numInt, apiReturn;
3084 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
3088 WSASetLastError(WSAEFAULT);
3089 return SOCKET_ERROR;
3091 if (!lpcbBytesReturned)
3093 WSASetLastError(WSAEFAULT);
3094 return SOCKET_ERROR;
3097 fd = get_sock_fd( s, 0, NULL );
3098 if (fd == -1) return SOCKET_ERROR;
3100 apiReturn = GetAdaptersInfo(NULL, &size);
3101 if (apiReturn == ERROR_NO_DATA)
3105 else if (apiReturn == ERROR_BUFFER_OVERFLOW)
3107 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
3111 if (GetAdaptersInfo(table, &size) == NO_ERROR)
3113 PIP_ADAPTER_INFO ptr;
3115 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > cbOutBuffer)
3117 WARN("Buffer too small = %u, cbOutBuffer = %u\n", size, cbOutBuffer);
3118 HeapFree(GetProcessHeap(),0,table);
3119 release_sock_fd( s, fd );
3120 WSASetLastError(WSAEFAULT);
3121 return SOCKET_ERROR;
3123 for (ptr = table, numInt = 0; ptr;
3124 ptr = ptr->Next, intArray++, numInt++)
3126 unsigned int addr, mask, bcast;
3127 struct ifreq ifInfo;
3129 /* Socket Status Flags */
3130 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
3131 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
3133 ERR("Error obtaining status flags for socket!\n");
3134 HeapFree(GetProcessHeap(),0,table);
3135 release_sock_fd( s, fd );
3136 WSASetLastError(WSAEINVAL);
3137 return SOCKET_ERROR;
3141 /* set flags; the values of IFF_* are not the same
3142 under Linux and Windows, therefore must generate
3144 intArray->iiFlags = 0;
3145 if (ifInfo.ifr_flags & IFF_BROADCAST)
3146 intArray->iiFlags |= WS_IFF_BROADCAST;
3147 #ifdef IFF_POINTOPOINT
3148 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
3149 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
3151 if (ifInfo.ifr_flags & IFF_LOOPBACK)
3152 intArray->iiFlags |= WS_IFF_LOOPBACK;
3153 if (ifInfo.ifr_flags & IFF_UP)
3154 intArray->iiFlags |= WS_IFF_UP;
3155 if (ifInfo.ifr_flags & IFF_MULTICAST)
3156 intArray->iiFlags |= WS_IFF_MULTICAST;
3159 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
3160 mask = inet_addr(ptr->IpAddressList.IpMask.String);
3161 bcast = addr | ~mask;
3162 intArray->iiAddress.AddressIn.sin_family = AF_INET;
3163 intArray->iiAddress.AddressIn.sin_port = 0;
3164 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
3166 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
3167 intArray->iiNetmask.AddressIn.sin_port = 0;
3168 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
3170 intArray->iiBroadcastAddress.AddressIn.sin_family =
3172 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
3173 intArray->iiBroadcastAddress.AddressIn.sin_addr.
3179 ERR("Unable to get interface table!\n");
3180 release_sock_fd( s, fd );
3181 HeapFree(GetProcessHeap(),0,table);
3182 WSASetLastError(WSAEINVAL);
3183 return SOCKET_ERROR;
3185 HeapFree(GetProcessHeap(),0,table);
3189 release_sock_fd( s, fd );
3190 WSASetLastError(WSAEINVAL);
3191 return SOCKET_ERROR;
3196 ERR("Unable to get interface table!\n");
3197 release_sock_fd( s, fd );
3198 WSASetLastError(WSAEINVAL);
3199 return SOCKET_ERROR;
3201 /* Calculate the size of the array being returned */
3202 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
3203 release_sock_fd( s, fd );
3207 case WS_SIO_ADDRESS_LIST_CHANGE:
3208 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
3209 /* FIXME: error and return code depend on whether socket was created
3210 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
3213 case WS_SIO_ADDRESS_LIST_QUERY:
3217 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
3219 if (!lpcbBytesReturned)
3221 WSASetLastError(WSAEFAULT);
3222 return SOCKET_ERROR;
3225 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
3227 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
3230 if (!table || GetAdaptersInfo(table, &size))
3232 HeapFree(GetProcessHeap(), 0, table);
3233 WSASetLastError(WSAEINVAL);
3234 return SOCKET_ERROR;
3237 for (p = table, num = 0; p; p = p->Next)
3238 if (p->IpAddressList.IpAddress.String[0]) num++;
3240 need = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
3241 need += sizeof(SOCKADDR) * num;
3242 *lpcbBytesReturned = need;
3244 if (need > cbOutBuffer)
3246 HeapFree(GetProcessHeap(), 0, table);
3247 WSASetLastError(WSAEFAULT);
3248 return SOCKET_ERROR;
3255 SOCKET_ADDRESS_LIST *sa_list = (SOCKET_ADDRESS_LIST *)lpbOutBuffer;
3256 SOCKADDR_IN *sockaddr;
3258 sa = sa_list->Address;
3259 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
3260 sa_list->iAddressCount = num;
3262 for (p = table, i = 0; p; p = p->Next)
3264 if (!p->IpAddressList.IpAddress.String[0]) continue;
3266 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
3267 sa[i].iSockaddrLength = sizeof(SOCKADDR);
3269 sockaddr[i].sin_family = AF_INET;
3270 sockaddr[i].sin_port = 0;
3271 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
3276 HeapFree(GetProcessHeap(), 0, table);
3281 WARN("unable to get IP address list\n");
3282 WSASetLastError(WSAEINVAL);
3283 return SOCKET_ERROR;
3287 FIXME("SIO_FLUSH: stub.\n");
3290 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
3292 static const GUID connectex_guid = WSAID_CONNECTEX;
3293 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
3294 static const GUID acceptex_guid = WSAID_ACCEPTEX;
3295 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
3296 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
3297 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
3298 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
3299 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
3301 if ( IsEqualGUID(&connectex_guid, lpvInBuffer) )
3303 *(LPFN_CONNECTEX *)lpbOutBuffer = WS2_ConnectEx;
3306 else if ( IsEqualGUID(&disconnectex_guid, lpvInBuffer) )
3308 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
3310 else if ( IsEqualGUID(&acceptex_guid, lpvInBuffer) )
3312 *(LPFN_ACCEPTEX *)lpbOutBuffer = WS2_AcceptEx;
3315 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, lpvInBuffer) )
3317 *(LPFN_GETACCEPTEXSOCKADDRS *)lpbOutBuffer = WS2_GetAcceptExSockaddrs;
3320 else if ( IsEqualGUID(&transmitfile_guid, lpvInBuffer) )
3322 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
3324 else if ( IsEqualGUID(&transmitpackets_guid, lpvInBuffer) )
3326 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
3328 else if ( IsEqualGUID(&wsarecvmsg_guid, lpvInBuffer) )
3330 *(LPFN_WSARECVMSG *)lpbOutBuffer = WS2_WSARecvMsg;
3333 else if ( IsEqualGUID(&wsasendmsg_guid, lpvInBuffer) )
3335 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented WSASendMsg\n");
3338 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(lpvInBuffer));
3340 WSASetLastError(WSAEOPNOTSUPP);
3341 return SOCKET_ERROR;
3344 case WS_SIO_KEEPALIVE_VALS:
3347 struct tcp_keepalive *k = lpvInBuffer;
3348 int keepalive = k->onoff ? 1 : 0;
3349 int keepidle = k->keepalivetime / 1000;
3350 int keepintvl = k->keepaliveinterval / 1000;
3354 WSASetLastError(WSAEINVAL);
3355 return SOCKET_ERROR;
3358 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
3360 fd = get_sock_fd(s, 0, NULL);
3361 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
3363 release_sock_fd(s, fd);
3364 WSASetLastError(WSAEINVAL);
3365 return SOCKET_ERROR;
3367 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
3368 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
3370 release_sock_fd(s, fd);
3371 WSASetLastError(WSAEINVAL);
3372 return SOCKET_ERROR;
3374 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
3376 release_sock_fd(s, fd);
3377 WSASetLastError(WSAEINVAL);
3378 return SOCKET_ERROR;
3381 FIXME("ignoring keepalive interval and timeout\n");
3384 release_sock_fd(s, fd);
3387 case WS_SIO_ROUTING_INTERFACE_QUERY:
3389 struct WS_sockaddr *daddr = (struct WS_sockaddr *)lpvInBuffer;
3390 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
3391 struct WS_sockaddr_in *saddr_in = (struct WS_sockaddr_in *)lpbOutBuffer;
3392 MIB_IPFORWARDROW row;
3393 PMIB_IPADDRTABLE ipAddrTable = NULL;
3394 DWORD size, i, found_index;
3396 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
3400 WSASetLastError(WSAEFAULT);
3401 return SOCKET_ERROR;
3403 if (cbInBuffer < sizeof(struct WS_sockaddr))
3405 WSASetLastError(WSAEFAULT);
3406 return SOCKET_ERROR;
3410 WSASetLastError(WSAEFAULT);
3411 return SOCKET_ERROR;
3413 if (!lpcbBytesReturned)
3415 WSASetLastError(WSAEFAULT);
3416 return SOCKET_ERROR;
3418 if (daddr->sa_family != AF_INET)
3420 FIXME("unsupported address family %d\n", daddr->sa_family);
3421 WSASetLastError(WSAEAFNOSUPPORT);
3422 return SOCKET_ERROR;
3424 if (cbOutBuffer < sizeof(struct WS_sockaddr_in))
3426 WSASetLastError(WSAEFAULT);
3427 return SOCKET_ERROR;
3429 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR)
3431 WSASetLastError(WSAEFAULT);
3432 return SOCKET_ERROR;
3434 if (GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
3436 WSASetLastError(WSAEFAULT);
3437 return SOCKET_ERROR;
3439 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
3440 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
3442 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3443 WSASetLastError(WSAEFAULT);
3444 return SOCKET_ERROR;
3446 for (i = 0, found_index = ipAddrTable->dwNumEntries;
3447 i < ipAddrTable->dwNumEntries; i++)
3449 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
3452 if (found_index == ipAddrTable->dwNumEntries)
3454 ERR("no matching IP address for interface %d\n",
3455 row.dwForwardIfIndex);
3456 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3457 WSASetLastError(WSAEFAULT);
3458 return SOCKET_ERROR;
3460 saddr_in->sin_family = AF_INET;
3461 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
3462 saddr_in->sin_port = 0;
3463 *lpcbBytesReturned = sizeof(struct WS_sockaddr_in);
3464 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3467 case WS_SIO_UDP_CONNRESET:
3468 FIXME("WS_SIO_UDP_CONNRESET stub\n");
3471 FIXME("unsupported WS_IOCTL cmd (%s)\n",
3472 debugstr_wsaioctl(dwIoControlCode));
3473 WSASetLastError(WSAEOPNOTSUPP);
3474 return SOCKET_ERROR;
3481 /***********************************************************************
3482 * ioctlsocket (WS2_32.10)
3484 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
3489 TRACE("socket %04lx, cmd %08x, ptr %p\n", s, cmd, argp);
3490 /* broken apps like defcon pass the argp value directly instead of a pointer to it */
3491 if(IS_INTRESOURCE(argp))
3493 SetLastError(WSAEFAULT);
3494 return SOCKET_ERROR;
3504 if( _get_sock_mask(s) )
3506 /* AsyncSelect()'ed sockets are always nonblocking */
3507 if (*argp) return 0;
3508 SetLastError(WSAEINVAL);
3509 return SOCKET_ERROR;
3512 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
3514 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
3522 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
3523 SetLastError(WSAEINVAL);
3524 return SOCKET_ERROR;
3526 case SIOCGIFBRDADDR:
3527 case SIOCGIFNETMASK:
3529 /* These don't need any special handling. They are used by
3530 WsControl, and are here to suppress an unnecessary warning. */
3534 /* Netscape tries hard to use bogus ioctl 0x667e */
3535 /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
3536 * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
3538 WARN("\tunknown WS_IOCTL cmd (%08x)\n", cmd);
3542 fd = get_sock_fd( s, 0, NULL );
3545 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
3547 release_sock_fd( s, fd );
3550 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3551 release_sock_fd( s, fd );
3553 return SOCKET_ERROR;
3556 /***********************************************************************
3557 * listen (WS2_32.13)
3559 int WINAPI WS_listen(SOCKET s, int backlog)
3561 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3563 TRACE("socket %04lx, backlog %d\n", s, backlog);
3566 if (listen(fd, backlog) == 0)
3568 release_sock_fd( s, fd );
3569 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
3571 FD_CONNECT|FD_WINE_CONNECTED);
3574 SetLastError(wsaErrno());
3575 release_sock_fd( s, fd );
3577 return SOCKET_ERROR;
3580 /***********************************************************************
3583 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
3585 DWORD n, dwFlags = flags;
3591 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
3592 return SOCKET_ERROR;
3597 /***********************************************************************
3598 * recvfrom (WS2_32.17)
3600 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
3601 struct WS_sockaddr *from, int *fromlen)
3603 DWORD n, dwFlags = flags;
3609 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
3610 return SOCKET_ERROR;
3615 /* allocate a poll array for the corresponding fd sets */
3616 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
3617 const WS_fd_set *exceptfds, int *count_ptr )
3619 unsigned int i, j = 0, count = 0;
3622 if (readfds) count += readfds->fd_count;
3623 if (writefds) count += writefds->fd_count;
3624 if (exceptfds) count += exceptfds->fd_count;
3628 SetLastError(WSAEINVAL);
3631 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
3633 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
3637 for (i = 0; i < readfds->fd_count; i++, j++)
3639 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
3640 if (fds[j].fd == -1) goto failed;
3641 fds[j].events = POLLIN;
3645 for (i = 0; i < writefds->fd_count; i++, j++)
3647 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
3648 if (fds[j].fd == -1) goto failed;
3649 fds[j].events = POLLOUT;
3653 for (i = 0; i < exceptfds->fd_count; i++, j++)
3655 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
3656 if (fds[j].fd == -1) goto failed;
3657 fds[j].events = POLLHUP;
3666 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
3667 release_sock_fd( readfds->fd_array[i], fds[j].fd );
3669 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
3670 release_sock_fd( writefds->fd_array[i], fds[j].fd );
3672 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
3673 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
3674 HeapFree( GetProcessHeap(), 0, fds );
3678 /* release the file descriptor obtained in fd_sets_to_poll */
3679 /* must be called with the original fd_set arrays, before calling get_poll_results */
3680 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
3681 const WS_fd_set *exceptfds, struct pollfd *fds )
3683 unsigned int i, j = 0;
3687 for (i = 0; i < readfds->fd_count; i++, j++)
3688 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
3692 for (i = 0; i < writefds->fd_count; i++, j++)
3693 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
3697 for (i = 0; i < exceptfds->fd_count; i++, j++)
3698 if (fds[j].fd != -1)
3700 /* make sure we have a real error before releasing the fd */
3701 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
3702 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
3707 /* map the poll results back into the Windows fd sets */
3708 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
3709 const struct pollfd *fds )
3711 unsigned int i, j = 0, k, total = 0;
3715 for (i = k = 0; i < readfds->fd_count; i++, j++)
3716 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
3717 readfds->fd_count = k;
3722 for (i = k = 0; i < writefds->fd_count; i++, j++)
3723 if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
3724 writefds->fd_count = k;
3729 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
3730 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
3731 exceptfds->fd_count = k;
3738 /***********************************************************************
3739 * select (WS2_32.18)
3741 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
3742 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
3743 const struct WS_timeval* ws_timeout)
3745 struct pollfd *pollfds;
3746 struct timeval tv1, tv2;
3748 int count, ret, timeout = -1;
3750 TRACE("read %p, write %p, excp %p timeout %p\n",
3751 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
3753 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
3754 return SOCKET_ERROR;
3758 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
3760 gettimeofday( &tv1, 0 );
3763 while ((ret = poll( pollfds, count, timeout )) < 0)
3767 if (!ws_timeout) continue;
3768 gettimeofday( &tv2, 0 );
3770 tv2.tv_sec -= tv1.tv_sec;
3771 tv2.tv_usec -= tv1.tv_usec;
3772 if (tv2.tv_usec < 0)
3774 tv2.tv_usec += 1000000;
3778 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
3779 if (timeout <= 0) break;
3782 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3784 if (ret == -1) SetLastError(wsaErrno());
3785 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3786 HeapFree( GetProcessHeap(), 0, pollfds );
3790 /* helper to send completion messages for client-only i/o operation case */
3791 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
3794 SERVER_START_REQ( add_fd_completion )
3796 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
3797 req->cvalue = CompletionValue;
3798 req->status = CompletionStatus;
3799 req->information = Information;
3800 wine_server_call( req );
3806 /***********************************************************************
3809 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
3815 wsabuf.buf = (char*) buf;
3817 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
3818 return SOCKET_ERROR;
3823 /***********************************************************************
3824 * WSASend (WS2_32.72)
3826 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3827 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3828 LPWSAOVERLAPPED lpOverlapped,
3829 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3831 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
3832 NULL, 0, lpOverlapped, lpCompletionRoutine );
3835 /***********************************************************************
3836 * WSASendDisconnect (WS2_32.73)
3838 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
3840 return WS_shutdown( s, SD_SEND );
3844 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3845 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3846 const struct WS_sockaddr *to, int tolen,
3847 LPWSAOVERLAPPED lpOverlapped,
3848 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3850 unsigned int i, options;
3852 struct ws2_async *wsa;
3853 int totalLength = 0;
3854 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
3856 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
3857 s, lpBuffers, dwBufferCount, dwFlags,
3858 to, tolen, lpOverlapped, lpCompletionRoutine);
3860 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
3861 TRACE( "fd=%d, options=%x\n", fd, options );
3863 if ( fd == -1 ) return SOCKET_ERROR;
3865 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
3871 wsa->hSocket = SOCKET2HANDLE(s);
3872 wsa->addr = (struct WS_sockaddr *)to;
3873 wsa->addrlen.val = tolen;
3874 wsa->flags = dwFlags;
3875 wsa->lpFlags = &wsa->flags;
3876 wsa->control = NULL;
3877 wsa->n_iovecs = dwBufferCount;
3878 wsa->first_iovec = 0;
3879 for ( i = 0; i < dwBufferCount; i++ )
3881 wsa->iovec[i].iov_base = lpBuffers[i].buf;
3882 wsa->iovec[i].iov_len = lpBuffers[i].len;
3883 totalLength += lpBuffers[i].len;
3886 if (!lpNumberOfBytesSent)
3894 n = WS2_send( fd, wsa );
3895 if (n != -1 || errno != EINTR) break;
3897 if (n == -1 && errno != EAGAIN)
3899 int loc_errno = errno;
3901 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
3905 if ((lpOverlapped || lpCompletionRoutine) &&
3906 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3908 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
3910 wsa->user_overlapped = lpOverlapped;
3911 wsa->completion_func = lpCompletionRoutine;
3912 release_sock_fd( s, fd );
3916 iosb->u.Status = STATUS_PENDING;
3917 iosb->Information = 0;
3919 SERVER_START_REQ( register_async )
3921 req->type = ASYNC_TYPE_WRITE;
3922 req->async.handle = wine_server_obj_handle( wsa->hSocket );
3923 req->async.callback = wine_server_client_ptr( WS2_async_send );
3924 req->async.iosb = wine_server_client_ptr( iosb );
3925 req->async.arg = wine_server_client_ptr( wsa );
3926 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
3927 req->async.cvalue = cvalue;
3928 err = wine_server_call( req );
3932 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
3933 WSASetLastError( NtStatusToWSAError( err ));
3934 return SOCKET_ERROR;
3937 iosb->u.Status = STATUS_SUCCESS;
3938 iosb->Information = n;
3939 *lpNumberOfBytesSent = n;
3940 if (!wsa->completion_func)
3942 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
3943 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
3944 HeapFree( GetProcessHeap(), 0, wsa );
3946 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
3947 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
3952 if ( _is_blocking(s) )
3954 /* On a blocking non-overlapped stream socket,
3955 * sending blocks until the entire buffer is sent. */
3956 DWORD timeout_start = GetTickCount();
3958 *lpNumberOfBytesSent = 0;
3960 while (wsa->first_iovec < dwBufferCount)
3963 int timeout = GET_SNDTIMEO(fd);
3967 *lpNumberOfBytesSent += n;
3968 while (wsa->first_iovec < dwBufferCount && wsa->iovec[wsa->first_iovec].iov_len <= n)
3969 n -= wsa->iovec[wsa->first_iovec++].iov_len;
3970 if (wsa->first_iovec >= dwBufferCount) break;
3971 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
3972 wsa->iovec[wsa->first_iovec].iov_len -= n;
3977 timeout -= GetTickCount() - timeout_start;
3978 if (timeout < 0) timeout = 0;
3982 pfd.events = POLLOUT;
3984 if (!timeout || !poll( &pfd, 1, timeout ))
3987 goto error; /* msdn says a timeout in send is fatal */
3990 n = WS2_send( fd, wsa );
3991 if (n == -1 && errno != EAGAIN && errno != EINTR)
3998 else /* non-blocking */
4000 if (n < totalLength)
4001 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4004 err = WSAEWOULDBLOCK;
4007 *lpNumberOfBytesSent = n;
4010 TRACE(" -> %i bytes\n", *lpNumberOfBytesSent);
4012 HeapFree( GetProcessHeap(), 0, wsa );
4013 release_sock_fd( s, fd );
4018 HeapFree( GetProcessHeap(), 0, wsa );
4019 release_sock_fd( s, fd );
4020 WARN(" -> ERROR %d\n", err);
4021 WSASetLastError(err);
4022 return SOCKET_ERROR;
4025 /***********************************************************************
4026 * WSASendTo (WS2_32.74)
4028 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4029 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4030 const struct WS_sockaddr *to, int tolen,
4031 LPWSAOVERLAPPED lpOverlapped,
4032 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4034 return WS2_sendto( s, lpBuffers, dwBufferCount,
4035 lpNumberOfBytesSent, dwFlags,
4037 lpOverlapped, lpCompletionRoutine );
4040 /***********************************************************************
4041 * sendto (WS2_32.20)
4043 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
4044 const struct WS_sockaddr *to, int tolen)
4050 wsabuf.buf = (char*) buf;
4052 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
4053 return SOCKET_ERROR;
4058 /***********************************************************************
4059 * setsockopt (WS2_32.21)
4061 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
4062 const char *optval, int optlen)
4066 struct linger linger;
4067 struct timeval tval;
4069 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
4070 s, level, optname, optval, optlen);
4072 /* some broken apps pass the value directly instead of a pointer to it */
4073 if(optlen && IS_INTRESOURCE(optval))
4075 SetLastError(WSAEFAULT);
4076 return SOCKET_ERROR;
4084 /* Some options need some conversion before they can be sent to
4085 * setsockopt. The conversions are done here, then they will fall though
4086 * to the general case. Special options that are not passed to
4087 * setsockopt follow below that.*/
4089 case WS_SO_DONTLINGER:
4090 linger.l_onoff = *((const int*)optval) ? 0: 1;
4091 linger.l_linger = 0;
4093 optname = SO_LINGER;
4094 optval = (char*)&linger;
4095 optlen = sizeof(struct linger);
4099 linger.l_onoff = ((LINGER*)optval)->l_onoff;
4100 linger.l_linger = ((LINGER*)optval)->l_linger;
4101 /* FIXME: what is documented behavior if SO_LINGER optval
4104 optname = SO_LINGER;
4105 optval = (char*)&linger;
4106 optlen = sizeof(struct linger);
4110 if (*(const int*)optval < 2048)
4112 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
4117 /* The options listed here don't need any special handling. Thanks to
4118 * the conversion happening above, options from there will fall through
4120 case WS_SO_ACCEPTCONN:
4121 case WS_SO_BROADCAST:
4123 case WS_SO_KEEPALIVE:
4124 case WS_SO_OOBINLINE:
4125 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
4126 * however, using it the BSD way fixes bug 8513 and seems to be what
4127 * most programmers assume, anyway */
4128 case WS_SO_REUSEADDR:
4131 convert_sockopt(&level, &optname);
4134 /* SO_DEBUG is a privileged operation, ignore it. */
4136 TRACE("Ignoring SO_DEBUG\n");
4139 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
4140 * socket. According to MSDN, this option is silently ignored.*/
4141 case WS_SO_DONTROUTE:
4142 TRACE("Ignoring SO_DONTROUTE\n");
4145 /* Stops two sockets from being bound to the same port. Always happens
4146 * on unix systems, so just drop it. */
4147 case WS_SO_EXCLUSIVEADDRUSE:
4148 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
4151 /* After a ConnectEx call succeeds, the socket can't be used with half of the
4152 * normal winsock functions on windows. We don't have that problem. */
4153 case WS_SO_UPDATE_CONNECT_CONTEXT:
4154 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
4157 /* After a AcceptEx call succeeds, the socket can't be used with half of the
4158 * normal winsock functions on windows. We don't have that problem. */
4159 case WS_SO_UPDATE_ACCEPT_CONTEXT:
4160 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
4163 /* SO_OPENTYPE does not require a valid socket handle. */
4164 case WS_SO_OPENTYPE:
4165 if (!optlen || optlen < sizeof(int) || !optval)
4167 SetLastError(WSAEFAULT);
4168 return SOCKET_ERROR;
4170 get_per_thread_data()->opentype = *(const int *)optval;
4171 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
4175 case WS_SO_RCVTIMEO:
4178 case WS_SO_SNDTIMEO:
4180 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
4181 if (optval && optlen == sizeof(UINT32)) {
4182 /* WinSock passes milliseconds instead of struct timeval */
4183 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
4184 tval.tv_sec = *(const UINT32*)optval / 1000;
4185 /* min of 500 milliseconds */
4186 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
4187 tval.tv_usec = 500000;
4188 optlen = sizeof(struct timeval);
4189 optval = (char*)&tval;
4190 } else if (optlen == sizeof(struct timeval)) {
4191 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
4193 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
4196 convert_sockopt(&level, &optname);
4201 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4202 SetLastError(WSAENOPROTOOPT);
4203 return SOCKET_ERROR;
4205 break; /* case WS_SOL_SOCKET */
4212 fd = get_sock_fd( s, 0, NULL );
4213 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
4215 /* We try to set the ipx type on ipx socket level. */
4217 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
4219 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
4220 release_sock_fd( s, fd );
4221 return SOCKET_ERROR;
4226 /* Should we retrieve val using a getsockopt call and then
4227 * set the modified one? */
4228 val.ipx_pt = *optval;
4229 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
4232 release_sock_fd( s, fd );
4235 case IPX_FILTERPTYPE:
4236 /* Sets the receive filter packet type, at the moment we don't support it */
4237 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
4238 /* Returning 0 is better for now than returning a SOCKET_ERROR */
4242 FIXME("opt_name:%x\n", optname);
4243 return SOCKET_ERROR;
4245 break; /* case NSPROTO_IPX */
4248 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4249 case WS_IPPROTO_TCP:
4252 case WS_TCP_NODELAY:
4253 convert_sockopt(&level, &optname);
4256 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4257 return SOCKET_ERROR;
4264 case WS_IP_ADD_MEMBERSHIP:
4265 case WS_IP_DROP_MEMBERSHIP:
4269 case WS_IP_MULTICAST_IF:
4270 case WS_IP_MULTICAST_LOOP:
4271 case WS_IP_MULTICAST_TTL:
4278 convert_sockopt(&level, &optname);
4280 case WS_IP_DONTFRAGMENT:
4281 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
4284 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4285 return SOCKET_ERROR;
4289 case WS_IPPROTO_IPV6:
4292 #ifdef IPV6_ADD_MEMBERSHIP
4293 case WS_IPV6_ADD_MEMBERSHIP:
4295 #ifdef IPV6_DROP_MEMBERSHIP
4296 case WS_IPV6_DROP_MEMBERSHIP:
4298 case WS_IPV6_MULTICAST_IF:
4299 case WS_IPV6_MULTICAST_HOPS:
4300 case WS_IPV6_MULTICAST_LOOP:
4301 case WS_IPV6_UNICAST_HOPS:
4302 case WS_IPV6_V6ONLY:
4303 convert_sockopt(&level, &optname);
4305 case WS_IPV6_DONTFRAG:
4306 FIXME("IPV6_DONTFRAG is silently ignored!\n");
4309 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4310 return SOCKET_ERROR;
4315 WARN("Unknown level: 0x%08x\n", level);
4316 SetLastError(WSAEINVAL);
4317 return SOCKET_ERROR;
4318 } /* end switch(level) */
4320 /* avoid endianness issues if argument is a 16-bit int */
4321 if (optval && optlen < sizeof(int))
4323 woptval= *((const INT16 *) optval);
4324 optval= (char*) &woptval;
4327 fd = get_sock_fd( s, 0, NULL );
4328 if (fd == -1) return SOCKET_ERROR;
4330 if (setsockopt(fd, level, optname, optval, optlen) == 0)
4332 release_sock_fd( s, fd );
4335 TRACE("Setting socket error, %d\n", wsaErrno());
4336 SetLastError(wsaErrno());
4337 release_sock_fd( s, fd );
4339 return SOCKET_ERROR;
4342 /***********************************************************************
4343 * shutdown (WS2_32.22)
4345 int WINAPI WS_shutdown(SOCKET s, int how)
4347 int fd, err = WSAENOTSOCK;
4348 unsigned int options, clear_flags = 0;
4350 fd = get_sock_fd( s, 0, &options );
4351 TRACE("socket %04lx, how %i %x\n", s, how, options );
4354 return SOCKET_ERROR;
4358 case 0: /* drop receives */
4359 clear_flags |= FD_READ;
4361 case 1: /* drop sends */
4362 clear_flags |= FD_WRITE;
4364 case 2: /* drop all */
4365 clear_flags |= FD_READ|FD_WRITE;
4367 clear_flags |= FD_WINE_LISTENING;
4370 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4375 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4378 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4382 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4383 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4386 if (err) goto error;
4388 else /* non-overlapped mode */
4390 if ( shutdown( fd, how ) )
4397 release_sock_fd( s, fd );
4398 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4399 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
4403 release_sock_fd( s, fd );
4404 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4405 WSASetLastError( err );
4406 return SOCKET_ERROR;
4409 /***********************************************************************
4410 * socket (WS2_32.23)
4412 SOCKET WINAPI WS_socket(int af, int type, int protocol)
4414 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
4416 return WSASocketA( af, type, protocol, NULL, 0,
4417 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
4421 /***********************************************************************
4422 * gethostbyaddr (WS2_32.51)
4424 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
4426 struct WS_hostent *retval = NULL;
4427 struct hostent* host;
4429 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4432 struct hostent hostentry;
4435 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4437 int res = gethostbyaddr_r(addr, len, type,
4438 &hostentry, extrabuf, ebufsize, &host, &locerr);
4439 if( res != ERANGE) break;
4441 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4443 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4445 EnterCriticalSection( &csWSgetXXXbyYYY );
4446 host = gethostbyaddr(addr, len, type);
4447 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4449 if( host != NULL ) retval = WS_dup_he(host);
4450 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4451 HeapFree(GetProcessHeap(),0,extrabuf);
4453 LeaveCriticalSection( &csWSgetXXXbyYYY );
4455 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
4459 /***********************************************************************
4460 * WS_get_local_ips (INTERNAL)
4462 * Returns the list of local IP addresses by going through the network
4463 * adapters and using the local routing table to sort the addresses
4464 * from highest routing priority to lowest routing priority. This
4465 * functionality is inferred from the description for obtaining local
4466 * IP addresses given in the Knowledge Base Article Q160215.
4468 * Please note that the returned hostent is only freed when the thread
4469 * closes and is replaced if another hostent is requested.
4471 static struct WS_hostent* WS_get_local_ips( char *hostname )
4473 int last_metric, numroutes = 0, i, j;
4474 PIP_ADAPTER_INFO adapters = NULL, k;
4475 struct WS_hostent *hostlist = NULL;
4476 PMIB_IPFORWARDTABLE routes = NULL;
4477 struct route *route_addrs = NULL;
4478 DWORD adap_size, route_size;
4480 /* Obtain the size of the adapter list and routing table, also allocate memory */
4481 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
4483 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4485 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
4486 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
4487 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
4488 if (adapters == NULL || routes == NULL || route_addrs == NULL)
4490 /* Obtain the adapter list and the full routing table */
4491 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
4493 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
4495 /* Store the interface associated with each route */
4496 for (i = 0; i < routes->dwNumEntries; i++)
4498 DWORD ifindex, ifmetric, exists = FALSE;
4500 if (routes->table[i].dwForwardType != MIB_IPROUTE_TYPE_DIRECT)
4502 ifindex = routes->table[i].dwForwardIfIndex;
4503 ifmetric = routes->table[i].dwForwardMetric1;
4504 /* Only store the lowest valued metric for an interface */
4505 for (j = 0; j < numroutes; j++)
4507 if (route_addrs[j].interface == ifindex)
4509 if (route_addrs[j].metric > ifmetric)
4510 route_addrs[j].metric = ifmetric;
4516 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
4517 if (route_addrs == NULL)
4518 goto cleanup; /* Memory allocation error, fail gracefully */
4519 route_addrs[numroutes].interface = ifindex;
4520 route_addrs[numroutes].metric = ifmetric;
4521 /* If no IP is found in the next step (for whatever reason)
4522 * then fall back to the magic loopback address.
4524 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
4528 goto cleanup; /* No routes, fall back to the Magic IP */
4529 /* Find the IP address associated with each found interface */
4530 for (i = 0; i < numroutes; i++)
4532 for (k = adapters; k != NULL; k = k->Next)
4534 char *ip = k->IpAddressList.IpAddress.String;
4536 if (route_addrs[i].interface == k->Index)
4537 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
4540 /* Allocate a hostent and enough memory for all the IPs,
4541 * including the NULL at the end of the list.
4543 hostlist = WS_create_he(hostname, 1, numroutes+1, TRUE);
4544 if (hostlist == NULL)
4545 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
4546 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
4547 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
4548 hostlist->h_addrtype = AF_INET;
4549 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
4550 /* Reorder the entries when placing them in the host list, Windows expects
4551 * the IP list in order from highest priority to lowest (the critical thing
4552 * is that most applications expect the first IP to be the default route).
4555 for (i = 0; i < numroutes; i++)
4557 struct in_addr addr;
4558 int metric = 0xFFFF;
4560 memcpy(&addr, magic_loopback_addr, 4);
4561 for (j = 0; j < numroutes; j++)
4563 int this_metric = route_addrs[j].metric;
4565 if (this_metric > last_metric && this_metric < metric)
4567 addr = route_addrs[j].addr;
4568 metric = this_metric;
4571 last_metric = metric;
4572 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
4575 /* Cleanup all allocated memory except the address list,
4576 * the address list is used by the calling app.
4579 HeapFree(GetProcessHeap(), 0, route_addrs);
4580 HeapFree(GetProcessHeap(), 0, adapters);
4581 HeapFree(GetProcessHeap(), 0, routes);
4585 /***********************************************************************
4586 * gethostbyname (WS2_32.52)
4588 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
4590 struct WS_hostent *retval = NULL;
4591 struct hostent* host;
4592 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4595 struct hostent hostentry;
4596 int locerr = ENOBUFS;
4599 if( gethostname( hostname, 100) == -1) {
4600 SetLastError( WSAENOBUFS); /* appropriate ? */
4603 if( !name || !name[0]) {
4606 /* If the hostname of the local machine is requested then return the
4607 * complete list of local IP addresses */
4608 if(strcmp(name, hostname) == 0)
4609 retval = WS_get_local_ips(hostname);
4610 /* If any other hostname was requested (or the routing table lookup failed)
4611 * then return the IP found by the host OS */
4614 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4616 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4618 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
4619 if( res != ERANGE) break;
4621 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4623 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4625 EnterCriticalSection( &csWSgetXXXbyYYY );
4626 host = gethostbyname(name);
4627 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4629 if (host) retval = WS_dup_he(host);
4630 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4631 HeapFree(GetProcessHeap(),0,extrabuf);
4633 LeaveCriticalSection( &csWSgetXXXbyYYY );
4636 if (retval && retval->h_addr_list[0][0] == 127 &&
4637 strcmp(name, "localhost") != 0)
4639 /* hostname != "localhost" but has loopback address. replace by our
4640 * special address.*/
4641 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
4643 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4648 /***********************************************************************
4649 * getprotobyname (WS2_32.53)
4651 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
4653 struct WS_protoent* retval = NULL;
4654 #ifdef HAVE_GETPROTOBYNAME
4655 struct protoent* proto;
4656 EnterCriticalSection( &csWSgetXXXbyYYY );
4657 if( (proto = getprotobyname(name)) != NULL )
4659 retval = WS_dup_pe(proto);
4662 MESSAGE("protocol %s not found; You might want to add "
4663 "this to /etc/protocols\n", debugstr_a(name) );
4664 SetLastError(WSANO_DATA);
4666 LeaveCriticalSection( &csWSgetXXXbyYYY );
4668 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4673 /***********************************************************************
4674 * getprotobynumber (WS2_32.54)
4676 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
4678 struct WS_protoent* retval = NULL;
4679 #ifdef HAVE_GETPROTOBYNUMBER
4680 struct protoent* proto;
4681 EnterCriticalSection( &csWSgetXXXbyYYY );
4682 if( (proto = getprotobynumber(number)) != NULL )
4684 retval = WS_dup_pe(proto);
4687 MESSAGE("protocol number %d not found; You might want to add "
4688 "this to /etc/protocols\n", number );
4689 SetLastError(WSANO_DATA);
4691 LeaveCriticalSection( &csWSgetXXXbyYYY );
4693 TRACE("%i ret %p\n", number, retval);
4698 /***********************************************************************
4699 * getservbyname (WS2_32.55)
4701 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
4703 struct WS_servent* retval = NULL;
4704 struct servent* serv;
4706 char *proto_str = NULL;
4708 if (!(name_str = strdup_lower(name))) return NULL;
4710 if (proto && *proto)
4712 if (!(proto_str = strdup_lower(proto)))
4714 HeapFree( GetProcessHeap(), 0, name_str );
4719 EnterCriticalSection( &csWSgetXXXbyYYY );
4720 serv = getservbyname(name_str, proto_str);
4723 retval = WS_dup_se(serv);
4725 else SetLastError(WSANO_DATA);
4726 LeaveCriticalSection( &csWSgetXXXbyYYY );
4727 HeapFree( GetProcessHeap(), 0, proto_str );
4728 HeapFree( GetProcessHeap(), 0, name_str );
4729 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
4733 /***********************************************************************
4734 * freeaddrinfo (WS2_32.@)
4736 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
4739 struct WS_addrinfo *next;
4741 HeapFree(GetProcessHeap(),0,res->ai_canonname);
4742 HeapFree(GetProcessHeap(),0,res->ai_addr);
4743 next = res->ai_next;
4744 HeapFree(GetProcessHeap(),0,res);
4749 /* helper functions for getaddrinfo()/getnameinfo() */
4750 static int convert_aiflag_w2u(int winflags) {
4754 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4755 if (ws_aiflag_map[i][0] & winflags) {
4756 unixflags |= ws_aiflag_map[i][1];
4757 winflags &= ~ws_aiflag_map[i][0];
4760 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
4764 static int convert_niflag_w2u(int winflags) {
4768 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
4769 if (ws_niflag_map[i][0] & winflags) {
4770 unixflags |= ws_niflag_map[i][1];
4771 winflags &= ~ws_niflag_map[i][0];
4774 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
4778 static int convert_aiflag_u2w(int unixflags) {
4782 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4783 if (ws_aiflag_map[i][1] & unixflags) {
4784 winflags |= ws_aiflag_map[i][0];
4785 unixflags &= ~ws_aiflag_map[i][1];
4787 if (unixflags) /* will warn usually */
4788 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
4792 static int convert_eai_u2w(int unixret) {
4795 for (i=0;ws_eai_map[i][0];i++)
4796 if (ws_eai_map[i][1] == unixret)
4797 return ws_eai_map[i][0];
4801 /***********************************************************************
4802 * getaddrinfo (WS2_32.@)
4804 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
4806 #ifdef HAVE_GETADDRINFO
4807 struct addrinfo *unixaires = NULL;
4809 struct addrinfo unixhints, *punixhints = NULL;
4810 CHAR *node = NULL, *serv = NULL;
4813 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
4816 if (!(serv = strdup_lower(servname))) {
4817 HeapFree(GetProcessHeap(), 0, node);
4818 return WSA_NOT_ENOUGH_MEMORY;
4823 punixhints = &unixhints;
4825 memset(&unixhints, 0, sizeof(unixhints));
4826 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
4827 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
4828 punixhints->ai_family = 0;
4830 punixhints->ai_family = convert_af_w2u(hints->ai_family);
4831 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
4832 punixhints->ai_socktype = 0;
4834 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
4835 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
4836 punixhints->ai_protocol = 0;
4838 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
4841 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
4842 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
4844 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
4846 HeapFree(GetProcessHeap(), 0, node);
4847 HeapFree(GetProcessHeap(), 0, serv);
4850 struct addrinfo *xuai = unixaires;
4851 struct WS_addrinfo **xai = res;
4855 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
4861 *xai = ai;xai = &ai->ai_next;
4862 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
4863 ai->ai_family = convert_af_u2w(xuai->ai_family);
4864 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
4865 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
4866 if (xuai->ai_canonname) {
4867 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
4868 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
4869 if (!ai->ai_canonname)
4871 strcpy(ai->ai_canonname,xuai->ai_canonname);
4873 len = xuai->ai_addrlen;
4874 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
4877 ai->ai_addrlen = len;
4879 int winlen = ai->ai_addrlen;
4881 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
4882 ai->ai_addrlen = winlen;
4886 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
4889 ai->ai_addrlen = len;
4891 xuai = xuai->ai_next;
4893 freeaddrinfo(unixaires);
4895 result = convert_eai_u2w(result);
4901 if (*res) WS_freeaddrinfo(*res);
4902 if (unixaires) freeaddrinfo(unixaires);
4904 return WSA_NOT_ENOUGH_MEMORY;
4906 FIXME("getaddrinfo() failed, not found during buildtime.\n");
4911 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
4913 struct WS_addrinfoW *ret;
4915 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
4916 ret->ai_flags = ai->ai_flags;
4917 ret->ai_family = ai->ai_family;
4918 ret->ai_socktype = ai->ai_socktype;
4919 ret->ai_protocol = ai->ai_protocol;
4920 ret->ai_addrlen = ai->ai_addrlen;
4921 ret->ai_canonname = NULL;
4922 ret->ai_addr = NULL;
4923 ret->ai_next = NULL;
4924 if (ai->ai_canonname)
4926 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
4927 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
4929 HeapFree(GetProcessHeap(), 0, ret);
4932 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
4936 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
4938 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
4939 HeapFree(GetProcessHeap(), 0, ret);
4942 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
4947 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
4949 struct WS_addrinfoW *ret, *infoW;
4951 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
4952 while (info->ai_next)
4954 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
4959 infoW = infoW->ai_next;
4960 info = info->ai_next;
4965 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
4967 struct WS_addrinfo *ret;
4969 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
4970 ret->ai_flags = ai->ai_flags;
4971 ret->ai_family = ai->ai_family;
4972 ret->ai_socktype = ai->ai_socktype;
4973 ret->ai_protocol = ai->ai_protocol;
4974 ret->ai_addrlen = ai->ai_addrlen;
4975 ret->ai_canonname = NULL;
4976 ret->ai_addr = NULL;
4977 ret->ai_next = NULL;
4978 if (ai->ai_canonname)
4980 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
4981 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
4983 HeapFree(GetProcessHeap(), 0, ret);
4986 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
4990 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
4992 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
4993 HeapFree(GetProcessHeap(), 0, ret);
4996 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5001 /***********************************************************************
5002 * GetAddrInfoW (WS2_32.@)
5004 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
5007 char *nodenameA, *servnameA = NULL;
5008 struct WS_addrinfo *resA, *hintsA = NULL;
5010 if (!nodename) return WSAHOST_NOT_FOUND;
5012 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
5013 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
5014 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
5018 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
5019 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
5021 HeapFree(GetProcessHeap(), 0, nodenameA);
5024 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
5027 if (hints) hintsA = addrinfo_WtoA(hints);
5028 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
5029 WS_freeaddrinfo(hintsA);
5033 *res = addrinfo_list_AtoW(resA);
5034 WS_freeaddrinfo(resA);
5037 HeapFree(GetProcessHeap(), 0, nodenameA);
5038 HeapFree(GetProcessHeap(), 0, servnameA);
5042 /***********************************************************************
5043 * FreeAddrInfoW (WS2_32.@)
5045 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
5050 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
5051 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
5053 HeapFree(GetProcessHeap(), 0, ai);
5058 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
5059 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
5061 #ifdef HAVE_GETNAMEINFO
5063 union generic_unix_sockaddr sa_u;
5066 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
5067 serv, servlen, flags);
5069 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
5072 WSASetLastError(WSAEFAULT);
5073 return WSA_NOT_ENOUGH_MEMORY;
5075 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
5076 return convert_eai_u2w(ret);
5078 FIXME("getnameinfo() failed, not found during buildtime.\n");
5083 /***********************************************************************
5084 * getservbyport (WS2_32.56)
5086 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
5088 struct WS_servent* retval = NULL;
5089 #ifdef HAVE_GETSERVBYPORT
5090 struct servent* serv;
5091 char *proto_str = NULL;
5093 if (proto && *proto)
5095 if (!(proto_str = strdup_lower(proto))) return NULL;
5097 EnterCriticalSection( &csWSgetXXXbyYYY );
5098 if( (serv = getservbyport(port, proto_str)) != NULL ) {
5099 retval = WS_dup_se(serv);
5101 else SetLastError(WSANO_DATA);
5102 LeaveCriticalSection( &csWSgetXXXbyYYY );
5103 HeapFree( GetProcessHeap(), 0, proto_str );
5105 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
5110 /***********************************************************************
5111 * gethostname (WS2_32.57)
5113 int WINAPI WS_gethostname(char *name, int namelen)
5115 TRACE("name %p, len %d\n", name, namelen);
5117 if (gethostname(name, namelen) == 0)
5119 TRACE("<- '%s'\n", name);
5122 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
5123 TRACE("<- ERROR !\n");
5124 return SOCKET_ERROR;
5128 /* ------------------------------------- Windows sockets extensions -- *
5130 * ------------------------------------------------------------------- */
5132 /***********************************************************************
5133 * WSAEnumNetworkEvents (WS2_32.36)
5135 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
5139 int errors[FD_MAX_EVENTS];
5141 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
5143 SERVER_START_REQ( get_socket_event )
5145 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5146 req->service = TRUE;
5147 req->c_event = wine_server_obj_handle( hEvent );
5148 wine_server_set_reply( req, errors, sizeof(errors) );
5149 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
5154 for (i = 0; i < FD_MAX_EVENTS; i++)
5155 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
5158 SetLastError(WSAEINVAL);
5159 return SOCKET_ERROR;
5162 /***********************************************************************
5163 * WSAEventSelect (WS2_32.39)
5165 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
5169 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
5171 SERVER_START_REQ( set_socket_event )
5173 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5175 req->event = wine_server_obj_handle( hEvent );
5178 ret = wine_server_call( req );
5182 SetLastError(WSAEINVAL);
5183 return SOCKET_ERROR;
5186 /**********************************************************************
5187 * WSAGetOverlappedResult (WS2_32.40)
5189 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
5190 LPDWORD lpcbTransfer, BOOL fWait,
5195 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
5196 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
5198 if ( lpOverlapped == NULL )
5200 ERR( "Invalid pointer\n" );
5201 WSASetLastError(WSA_INVALID_PARAMETER);
5205 status = lpOverlapped->Internal;
5206 if (status == STATUS_PENDING)
5210 SetLastError( WSA_IO_INCOMPLETE );
5214 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
5215 INFINITE ) == WAIT_FAILED)
5217 status = lpOverlapped->Internal;
5221 *lpcbTransfer = lpOverlapped->InternalHigh;
5224 *lpdwFlags = lpOverlapped->u.s.Offset;
5226 if (status) SetLastError( RtlNtStatusToDosError(status) );
5231 /***********************************************************************
5232 * WSAAsyncSelect (WS2_32.101)
5234 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
5238 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
5240 SERVER_START_REQ( set_socket_event )
5242 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5245 req->window = wine_server_user_handle( hWnd );
5247 ret = wine_server_call( req );
5251 SetLastError(WSAEINVAL);
5252 return SOCKET_ERROR;
5255 /***********************************************************************
5256 * WSACreateEvent (WS2_32.31)
5259 WSAEVENT WINAPI WSACreateEvent(void)
5261 /* Create a manual-reset event, with initial state: unsignaled */
5264 return CreateEventW(NULL, TRUE, FALSE, NULL);
5267 /***********************************************************************
5268 * WSACloseEvent (WS2_32.29)
5271 BOOL WINAPI WSACloseEvent(WSAEVENT event)
5273 TRACE ("event=%p\n", event);
5275 return CloseHandle(event);
5278 /***********************************************************************
5279 * WSASocketA (WS2_32.78)
5282 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
5283 LPWSAPROTOCOL_INFOA lpProtocolInfo,
5284 GROUP g, DWORD dwFlags)
5287 WSAPROTOCOL_INFOW info;
5289 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5290 af, type, protocol, lpProtocolInfo, g, dwFlags);
5292 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
5294 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
5295 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5296 info.szProtocol, WSAPROTOCOL_LEN + 1);
5300 WSASetLastError( WSAEINVAL);
5301 return SOCKET_ERROR;
5304 return WSASocketW(af, type, protocol, &info, g, dwFlags);
5307 /***********************************************************************
5308 * WSASocketW (WS2_32.79)
5311 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
5312 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5313 GROUP g, DWORD dwFlags)
5318 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
5319 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
5322 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5323 af, type, protocol, lpProtocolInfo, g, dwFlags );
5325 /* hack for WSADuplicateSocket */
5326 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
5327 ret = lpProtocolInfo->dwCatalogEntryId;
5328 TRACE("\tgot duplicate %04lx\n", ret);
5332 /* convert the socket family and type */
5333 af = convert_af_w2u(af);
5334 type = convert_socktype_w2u(type);
5338 if (af == FROM_PROTOCOL_INFO)
5339 af = lpProtocolInfo->iAddressFamily;
5340 if (type == FROM_PROTOCOL_INFO)
5341 type = lpProtocolInfo->iSocketType;
5342 if (protocol == FROM_PROTOCOL_INFO)
5343 protocol = lpProtocolInfo->iProtocol;
5346 if ( af == AF_UNSPEC) /* did they not specify the address family? */
5350 if (type == SOCK_STREAM) { af = AF_INET; break; }
5352 if (type == SOCK_DGRAM) { af = AF_INET; break; }
5353 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
5356 SERVER_START_REQ( create_socket )
5360 req->protocol = protocol;
5361 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
5362 req->attributes = OBJ_INHERIT;
5363 req->flags = dwFlags;
5364 set_error( wine_server_call( req ) );
5365 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
5370 TRACE("\tcreated %04lx\n", ret );
5374 if (GetLastError() == WSAEACCES) /* raw socket denied */
5376 if (type == SOCK_RAW)
5377 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
5379 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
5380 SetLastError(WSAESOCKTNOSUPPORT);
5383 WARN("\t\tfailed!\n");
5384 return INVALID_SOCKET;
5387 /***********************************************************************
5388 * WSAJoinLeaf (WS2_32.58)
5391 SOCKET WINAPI WSAJoinLeaf(
5393 const struct WS_sockaddr *addr,
5395 LPWSABUF lpCallerData,
5396 LPWSABUF lpCalleeData,
5402 return INVALID_SOCKET;
5405 /***********************************************************************
5406 * __WSAFDIsSet (WS2_32.151)
5408 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
5410 int i = set->fd_count;
5412 TRACE("(%ld,%p(%i))\n", s, set, i);
5415 if (set->fd_array[i] == s) return 1;
5419 /***********************************************************************
5420 * WSAIsBlocking (WS2_32.114)
5422 BOOL WINAPI WSAIsBlocking(void)
5424 /* By default WinSock should set all its sockets to non-blocking mode
5425 * and poll in PeekMessage loop when processing "blocking" ones. This
5426 * function is supposed to tell if the program is in this loop. Our
5427 * blocking calls are truly blocking so we always return FALSE.
5429 * Note: It is allowed to call this function without prior WSAStartup().
5436 /***********************************************************************
5437 * WSACancelBlockingCall (WS2_32.113)
5439 INT WINAPI WSACancelBlockingCall(void)
5445 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
5447 FIXME("How was this called?\n");
5452 /***********************************************************************
5453 * WSASetBlockingHook (WS2_32.109)
5455 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
5457 FARPROC prev = blocking_hook;
5458 blocking_hook = lpBlockFunc;
5459 TRACE("hook %p\n", lpBlockFunc);
5464 /***********************************************************************
5465 * WSAUnhookBlockingHook (WS2_32.110)
5467 INT WINAPI WSAUnhookBlockingHook(void)
5469 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
5474 /* ----------------------------------- end of API stuff */
5476 /* ----------------------------------- helper functions -
5478 * TODO: Merge WS_dup_..() stuff into one function that
5479 * would operate with a generic structure containing internal
5480 * pointers (via a template of some kind).
5483 static int list_size(char** l, int item_size)
5488 j += (item_size) ? item_size : strlen(l[i]) + 1;
5489 j += (i + 1) * sizeof(char*); }
5493 static int list_dup(char** l_src, char** l_to, int item_size)
5498 for (i = 0; l_src[i]; i++) ;
5499 p = (char *)(l_to + i + 1);
5500 for (i = 0; l_src[i]; i++)
5502 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
5503 memcpy(p, l_src[i], count);
5508 return p - (char *)l_to;
5513 /* create a hostent entry
5515 * Creates the entry with enough memory for the name, aliases
5516 * addresses, and the address pointers. Also copies the name
5517 * and sets up all the pointers. If "fill_addresses" is set then
5518 * sufficient memory for the addresses is also allocated and the
5519 * address pointers are set to this memory.
5521 * NOTE: The alias and address lists must be allocated with room
5522 * for the NULL item terminating the list. This is true even if
5523 * the list has no items ("aliases" and "addresses" must be
5524 * at least "1", a truly empty list is invalid).
5526 static struct WS_hostent *WS_create_he(char *name, int aliases, int addresses, int fill_addresses)
5528 struct WS_hostent *p_to;
5531 int size = (sizeof(struct WS_hostent) +
5533 sizeof(char *)*aliases +
5534 sizeof(char *)*addresses);
5536 /* Allocate enough memory for the addresses */
5538 size += sizeof(struct in_addr)*addresses;
5540 if (!(p_to = check_buffer_he(size))) return NULL;
5541 memset(p_to, 0, size);
5543 p = (char *)(p_to + 1);
5548 p_to->h_aliases = (char **)p;
5549 p += sizeof(char *)*aliases;
5550 p_to->h_addr_list = (char **)p;
5551 p += sizeof(char *)*addresses;
5556 /* NOTE: h_aliases must be filled in manually, leave these
5557 * pointers NULL (already set to NULL by memset earlier).
5560 /* Fill in the list of address pointers */
5561 for (i = 0; i < addresses; i++)
5562 p_to->h_addr_list[i] = (p += sizeof(struct in_addr));
5563 p += sizeof(struct in_addr);
5568 /* duplicate hostent entry
5569 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
5570 * Ditto for protoent and servent.
5572 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
5574 int addresses = list_size(p_he->h_addr_list, p_he->h_length);
5575 int aliases = list_size(p_he->h_aliases, 0);
5576 struct WS_hostent *p_to;
5578 p_to = WS_create_he(p_he->h_name, aliases, addresses, FALSE);
5580 if (!p_to) return NULL;
5581 p_to->h_addrtype = p_he->h_addrtype;
5582 p_to->h_length = p_he->h_length;
5584 list_dup(p_he->h_aliases, p_to->h_aliases, 0);
5585 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
5589 /* ----- protoent */
5591 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
5594 struct WS_protoent *p_to;
5596 int size = (sizeof(*p_pe) +
5597 strlen(p_pe->p_name) + 1 +
5598 list_size(p_pe->p_aliases, 0));
5600 if (!(p_to = check_buffer_pe(size))) return NULL;
5601 p_to->p_proto = p_pe->p_proto;
5603 p = (char *)(p_to + 1);
5605 strcpy(p, p_pe->p_name);
5608 p_to->p_aliases = (char **)p;
5609 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
5615 static struct WS_servent *WS_dup_se(const struct servent* p_se)
5618 struct WS_servent *p_to;
5620 int size = (sizeof(*p_se) +
5621 strlen(p_se->s_proto) + 1 +
5622 strlen(p_se->s_name) + 1 +
5623 list_size(p_se->s_aliases, 0));
5625 if (!(p_to = check_buffer_se(size))) return NULL;
5626 p_to->s_port = p_se->s_port;
5628 p = (char *)(p_to + 1);
5630 strcpy(p, p_se->s_name);
5634 strcpy(p, p_se->s_proto);
5637 p_to->s_aliases = (char **)p;
5638 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
5643 /***********************************************************************
5644 * WSARecv (WS2_32.67)
5646 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5647 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
5648 LPWSAOVERLAPPED lpOverlapped,
5649 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
5651 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
5652 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
5655 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5656 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
5657 struct WS_sockaddr *lpFrom,
5658 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
5659 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
5660 LPWSABUF lpControlBuffer )
5662 unsigned int i, options;
5664 struct ws2_async *wsa;
5665 DWORD timeout_start = GetTickCount();
5666 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5668 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
5669 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
5670 (lpFromlen ? *lpFromlen : -1),
5671 lpOverlapped, lpCompletionRoutine);
5673 fd = get_sock_fd( s, FILE_READ_DATA, &options );
5674 TRACE( "fd=%d, options=%x\n", fd, options );
5676 if (fd == -1) return SOCKET_ERROR;
5678 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
5684 wsa->hSocket = SOCKET2HANDLE(s);
5685 wsa->flags = *lpFlags;
5686 wsa->lpFlags = lpFlags;
5688 wsa->addrlen.ptr = lpFromlen;
5689 wsa->control = lpControlBuffer;
5690 wsa->n_iovecs = dwBufferCount;
5691 wsa->first_iovec = 0;
5692 for (i = 0; i < dwBufferCount; i++)
5694 /* check buffer first to trigger write watches */
5695 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
5700 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5701 wsa->iovec[i].iov_len = lpBuffers[i].len;
5706 n = WS2_recv( fd, wsa );
5709 if (errno == EINTR) continue;
5710 if (errno != EAGAIN)
5712 int loc_errno = errno;
5714 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
5719 *lpNumberOfBytesRecvd = n;
5721 if ((lpOverlapped || lpCompletionRoutine) &&
5722 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5724 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5726 wsa->user_overlapped = lpOverlapped;
5727 wsa->completion_func = lpCompletionRoutine;
5728 release_sock_fd( s, fd );
5732 iosb->u.Status = STATUS_PENDING;
5733 iosb->Information = 0;
5735 SERVER_START_REQ( register_async )
5737 req->type = ASYNC_TYPE_READ;
5738 req->async.handle = wine_server_obj_handle( wsa->hSocket );
5739 req->async.callback = wine_server_client_ptr( WS2_async_recv );
5740 req->async.iosb = wine_server_client_ptr( iosb );
5741 req->async.arg = wine_server_client_ptr( wsa );
5742 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
5743 req->async.cvalue = cvalue;
5744 err = wine_server_call( req );
5748 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5749 WSASetLastError( NtStatusToWSAError( err ));
5750 return SOCKET_ERROR;
5753 iosb->u.Status = STATUS_SUCCESS;
5754 iosb->Information = n;
5755 if (!wsa->completion_func)
5757 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5758 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5759 HeapFree( GetProcessHeap(), 0, wsa );
5761 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5762 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5763 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5769 if ( _is_blocking(s) )
5772 int timeout = GET_RCVTIMEO(fd);
5775 timeout -= GetTickCount() - timeout_start;
5776 if (timeout < 0) timeout = 0;
5780 pfd.events = POLLIN;
5781 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
5783 if (!timeout || !poll( &pfd, 1, timeout ))
5786 /* a timeout is not fatal */
5787 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5793 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5794 err = WSAEWOULDBLOCK;
5799 TRACE(" -> %i bytes\n", n);
5800 HeapFree( GetProcessHeap(), 0, wsa );
5801 release_sock_fd( s, fd );
5802 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5807 HeapFree( GetProcessHeap(), 0, wsa );
5808 release_sock_fd( s, fd );
5809 WARN(" -> ERROR %d\n", err);
5810 WSASetLastError( err );
5811 return SOCKET_ERROR;
5814 /***********************************************************************
5815 * WSARecvFrom (WS2_32.69)
5817 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5818 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
5819 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
5820 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5823 return WS2_recv_base( s, lpBuffers, dwBufferCount,
5824 lpNumberOfBytesRecvd, lpFlags,
5826 lpOverlapped, lpCompletionRoutine, NULL );
5829 /***********************************************************************
5830 * WSCInstallProvider (WS2_32.88)
5832 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
5833 LPCWSTR lpszProviderDllPath,
5834 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
5835 DWORD dwNumberOfEntries,
5838 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
5839 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
5840 dwNumberOfEntries, lpErrno);
5846 /***********************************************************************
5847 * WSCDeinstallProvider (WS2_32.83)
5849 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
5851 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
5857 /***********************************************************************
5858 * WSAAccept (WS2_32.26)
5860 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
5861 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
5864 int ret = 0, size = 0;
5865 WSABUF CallerId, CallerData, CalleeId, CalleeData;
5866 /* QOS SQOS, GQOS; */
5869 SOCKADDR src_addr, dst_addr;
5871 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %d\n",
5872 s, addr, addrlen, lpfnCondition, dwCallbackData);
5875 size = sizeof(src_addr);
5876 cs = WS_accept(s, &src_addr, &size);
5878 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
5880 if (!lpfnCondition) return cs;
5882 CallerId.buf = (char *)&src_addr;
5883 CallerId.len = sizeof(src_addr);
5885 CallerData.buf = NULL;
5888 WS_getsockname(cs, &dst_addr, &size);
5890 CalleeId.buf = (char *)&dst_addr;
5891 CalleeId.len = sizeof(dst_addr);
5894 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
5895 &CalleeId, &CalleeData, &g, dwCallbackData);
5900 if (addr && addrlen)
5901 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
5904 SERVER_START_REQ( set_socket_deferred )
5906 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5907 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
5908 if ( !wine_server_call_err ( req ) )
5910 SetLastError( WSATRY_AGAIN );
5911 WS_closesocket( cs );
5915 return SOCKET_ERROR;
5918 SetLastError(WSAECONNREFUSED);
5919 return SOCKET_ERROR;
5921 FIXME("Unknown return type from Condition function\n");
5922 SetLastError(WSAENOTSOCK);
5923 return SOCKET_ERROR;
5927 /***********************************************************************
5928 * WSADuplicateSocketA (WS2_32.32)
5930 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
5934 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
5935 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
5936 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
5937 /* I don't know what the real Windoze does next, this is a hack */
5938 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
5939 * the target use the global duplicate, or we could copy a reference to us to the structure
5940 * and let the target duplicate it from us, but let's do it as simple as possible */
5941 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
5942 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
5943 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
5944 0, FALSE, DUPLICATE_SAME_ACCESS);
5945 CloseHandle(hProcess);
5946 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
5950 /***********************************************************************
5951 * WSADuplicateSocketW (WS2_32.33)
5953 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
5957 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
5959 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
5960 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
5961 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
5962 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
5963 0, FALSE, DUPLICATE_SAME_ACCESS);
5964 CloseHandle(hProcess);
5965 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
5969 /***********************************************************************
5970 * WSAInstallServiceClassA (WS2_32.48)
5972 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
5974 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
5975 WSASetLastError(WSAEACCES);
5976 return SOCKET_ERROR;
5979 /***********************************************************************
5980 * WSAInstallServiceClassW (WS2_32.49)
5982 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
5984 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
5985 WSASetLastError(WSAEACCES);
5986 return SOCKET_ERROR;
5989 /***********************************************************************
5990 * WSARemoveServiceClass (WS2_32.70)
5992 int WINAPI WSARemoveServiceClass(LPGUID info)
5994 FIXME("Request to remove service %p\n",info);
5995 WSASetLastError(WSATYPE_NOT_FOUND);
5996 return SOCKET_ERROR;
5999 /***********************************************************************
6000 * inet_ntop (WS2_32.@)
6002 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
6004 #ifdef HAVE_INET_NTOP
6005 struct WS_in6_addr *in6;
6006 struct WS_in_addr *in;
6009 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
6012 WSASetLastError( STATUS_INVALID_PARAMETER );
6021 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
6027 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
6031 WSASetLastError( WSAEAFNOSUPPORT );
6035 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
6038 FIXME( "not supported on this platform\n" );
6039 WSASetLastError( WSAEAFNOSUPPORT );
6044 /***********************************************************************
6045 * WSAStringToAddressA (WS2_32.80)
6047 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
6049 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6050 LPSOCKADDR lpAddress,
6051 LPINT lpAddressLength)
6054 LPSTR workBuffer=NULL,ptrPort;
6056 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
6057 lpProtocolInfo, lpAddress, lpAddressLength );
6059 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6063 WSASetLastError(WSAEINVAL);
6064 return SOCKET_ERROR;
6068 FIXME("ProtocolInfo not implemented.\n");
6070 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
6071 strlen(AddressString) + 1);
6074 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6075 return SOCKET_ERROR;
6078 strcpy(workBuffer, AddressString);
6080 switch(AddressFamily)
6084 struct in_addr inetaddr;
6086 /* If lpAddressLength is too small, tell caller the size we need */
6087 if (*lpAddressLength < sizeof(SOCKADDR_IN))
6089 *lpAddressLength = sizeof(SOCKADDR_IN);
6093 *lpAddressLength = sizeof(SOCKADDR_IN);
6094 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
6096 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
6098 ptrPort = strchr(workBuffer, ':');
6101 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
6106 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
6109 if(inet_aton(workBuffer, &inetaddr) > 0)
6111 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
6122 struct in6_addr inetaddr;
6123 /* If lpAddressLength is too small, tell caller the size we need */
6124 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
6126 *lpAddressLength = sizeof(SOCKADDR_IN6);
6130 #ifdef HAVE_INET_PTON
6131 *lpAddressLength = sizeof(SOCKADDR_IN6);
6132 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
6134 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
6136 /* This one is a bit tricky. An IPv6 address contains colons, so the
6137 * check from IPv4 doesn't work like that. However, IPv6 addresses that
6138 * contain a port are written with braces like [fd12:3456:7890::1]:12345
6139 * so what we will do is to look for ']', check if the next char is a
6140 * colon, and if it is, parse the port as in IPv4. */
6142 ptrPort = strchr(workBuffer, ']');
6143 if(ptrPort && *(++ptrPort) == ':')
6145 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
6150 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
6153 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
6155 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
6156 sizeof(struct in6_addr));
6160 #endif /* HAVE_INET_PTON */
6166 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
6167 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
6171 HeapFree(GetProcessHeap(), 0, workBuffer);
6174 WSASetLastError(res);
6175 return SOCKET_ERROR;
6178 /***********************************************************************
6179 * WSAStringToAddressW (WS2_32.81)
6181 * Does anybody know if this functions allows to use hebrew/arabic/chinese... digits?
6182 * If this should be the case, it would be required to map these digits
6183 * to Unicode digits (0-9) using FoldString first.
6185 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
6187 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6188 LPSOCKADDR lpAddress,
6189 LPINT lpAddressLength)
6192 LPSTR workBuffer=NULL;
6193 WSAPROTOCOL_INFOA infoA;
6194 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
6196 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
6197 lpAddress, lpAddressLength );
6199 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6201 /* if ProtocolInfo is available - convert to ANSI variant */
6204 lpProtoInfoA = &infoA;
6205 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
6207 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6208 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
6210 WSASetLastError( WSAEINVAL);
6211 return SOCKET_ERROR;
6217 /* Translate AddressString to ANSI code page - assumes that only
6218 standard digits 0-9 are used with this API call */
6219 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
6220 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
6224 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
6225 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
6226 lpAddress,lpAddressLength);
6227 HeapFree( GetProcessHeap(), 0, workBuffer );
6231 res = WSA_NOT_ENOUGH_MEMORY;
6236 WSASetLastError(res);
6237 return SOCKET_ERROR;
6240 /***********************************************************************
6241 * WSAAddressToStringA (WS2_32.27)
6243 * See WSAAddressToStringW
6245 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
6246 LPWSAPROTOCOL_INFOA info, LPSTR string,
6250 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6253 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6255 if (!sockaddr) return SOCKET_ERROR;
6256 if (!string || !lenstr) return SOCKET_ERROR;
6258 switch(sockaddr->sa_family)
6261 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
6262 sprintf( buffer, "%u.%u.%u.%u:%u",
6263 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
6264 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
6265 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
6266 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
6267 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
6269 p = strchr( buffer, ':' );
6270 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
6275 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
6278 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
6279 if ((sockaddr6->sin6_port))
6280 strcpy(buffer, "[");
6281 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
6283 WSASetLastError(WSAEINVAL);
6284 return SOCKET_ERROR;
6286 if ((sockaddr6->sin6_scope_id))
6287 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
6288 if ((sockaddr6->sin6_port))
6289 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
6294 WSASetLastError(WSAEINVAL);
6295 return SOCKET_ERROR;
6298 size = strlen( buffer ) + 1;
6303 WSASetLastError(WSAEFAULT);
6304 return SOCKET_ERROR;
6308 strcpy( string, buffer );
6312 /***********************************************************************
6313 * WSAAddressToStringW (WS2_32.28)
6315 * Convert a sockaddr address into a readable address string.
6318 * sockaddr [I] Pointer to a sockaddr structure.
6319 * len [I] Size of the sockaddr structure.
6320 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
6321 * string [I/O] Pointer to a buffer to receive the address string.
6322 * lenstr [I/O] Size of the receive buffer in WCHARs.
6326 * Failure: SOCKET_ERROR
6329 * The 'info' parameter is ignored.
6331 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
6332 LPWSAPROTOCOL_INFOW info, LPWSTR string,
6337 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6340 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6343 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
6345 if (ret) return ret;
6347 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
6352 WSASetLastError(WSAEFAULT);
6353 return SOCKET_ERROR;
6357 lstrcpyW( string, buffer );
6361 /***********************************************************************
6362 * WSAEnumNameSpaceProvidersA (WS2_32.34)
6364 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
6366 FIXME( "(%p %p) Stub!\n", len, buffer );
6370 /***********************************************************************
6371 * WSAEnumNameSpaceProvidersW (WS2_32.35)
6373 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
6375 FIXME( "(%p %p) Stub!\n", len, buffer );
6379 /***********************************************************************
6380 * WSAGetQOSByName (WS2_32.41)
6382 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
6384 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
6388 /***********************************************************************
6389 * WSAGetServiceClassInfoA (WS2_32.42)
6391 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
6392 LPWSASERVICECLASSINFOA info )
6394 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
6396 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6397 return SOCKET_ERROR;
6400 /***********************************************************************
6401 * WSAGetServiceClassInfoW (WS2_32.43)
6403 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
6404 LPWSASERVICECLASSINFOW info )
6406 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
6408 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6409 return SOCKET_ERROR;
6412 /***********************************************************************
6413 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
6415 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
6417 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6418 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6419 return SOCKET_ERROR;
6422 /***********************************************************************
6423 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
6425 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
6427 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6428 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6429 return SOCKET_ERROR;
6432 /***********************************************************************
6433 * WSALookupServiceBeginA (WS2_32.59)
6435 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
6436 DWORD dwControlFlags,
6439 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6441 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6442 return SOCKET_ERROR;
6445 /***********************************************************************
6446 * WSALookupServiceBeginW (WS2_32.60)
6448 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
6449 DWORD dwControlFlags,
6452 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6454 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6455 return SOCKET_ERROR;
6458 /***********************************************************************
6459 * WSALookupServiceBeginW (WS2_32.61)
6461 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
6463 FIXME("(%p) Stub!\n", lookup );
6467 /***********************************************************************
6468 * WSALookupServiceNextA (WS2_32.62)
6470 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
6472 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6473 WSASetLastError(WSA_E_NO_MORE);
6474 return SOCKET_ERROR;
6477 /***********************************************************************
6478 * WSALookupServiceNextW (WS2_32.63)
6480 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
6482 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6483 WSASetLastError(WSA_E_NO_MORE);
6484 return SOCKET_ERROR;
6487 /***********************************************************************
6488 * WSANtohl (WS2_32.64)
6490 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
6492 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
6494 if (!lphostlong) return WSAEFAULT;
6496 *lphostlong = ntohl( netlong );
6500 /***********************************************************************
6501 * WSANtohs (WS2_32.65)
6503 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
6505 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
6507 if (!lphostshort) return WSAEFAULT;
6509 *lphostshort = ntohs( netshort );
6513 /***********************************************************************
6514 * WSAProviderConfigChange (WS2_32.66)
6516 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
6517 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
6519 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
6520 return SOCKET_ERROR;
6523 /***********************************************************************
6524 * WSARecvDisconnect (WS2_32.68)
6526 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
6528 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
6530 return WS_shutdown( s, 0 );
6533 /***********************************************************************
6534 * WSASetServiceA (WS2_32.76)
6536 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
6538 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6542 /***********************************************************************
6543 * WSASetServiceW (WS2_32.77)
6545 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
6547 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6551 /***********************************************************************
6552 * WSCEnableNSProvider (WS2_32.84)
6554 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
6556 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
6560 /***********************************************************************
6561 * WSCGetProviderPath (WS2_32.86)
6563 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
6565 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
6567 if (!errcode || !provider || !len) return WSAEFAULT;
6569 *errcode = WSAEINVAL;
6570 return SOCKET_ERROR;
6573 /***********************************************************************
6574 * WSCInstallNameSpace (WS2_32.87)
6576 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
6577 DWORD version, LPGUID provider )
6579 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
6580 namespace, version, debugstr_guid(provider) );
6584 /***********************************************************************
6585 * WSCUnInstallNameSpace (WS2_32.89)
6587 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
6589 FIXME("(%p) Stub!\n", lpProviderId);
6593 /***********************************************************************
6594 * WSCWriteProviderOrder (WS2_32.91)
6596 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
6598 FIXME("(%p 0x%08x) Stub!\n", entry, number);
6602 /***********************************************************************
6603 * WSANSPIoctl (WS2_32.91)
6605 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
6606 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
6607 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
6609 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
6610 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
6611 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6612 return SOCKET_ERROR;