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/unicode.h"
155 # include "wsnwlink.h"
159 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
160 # define sipx_network sipx_addr.x_net
161 # define sipx_node sipx_addr.x_host.c_host
162 #endif /* __FreeBSD__ */
165 #define INADDR_NONE ~0UL
168 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
170 /* critical section to protect some non-reentrant net function */
171 extern CRITICAL_SECTION csWSgetXXXbyYYY;
173 union generic_unix_sockaddr
175 struct sockaddr addr;
176 char data[128]; /* should be big enough for all families */
179 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
181 if (!a) return "(nil)";
182 switch (a->sa_family)
185 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
186 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
187 ntohs(((const struct sockaddr_in *)a)->sin_port));
192 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
194 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
196 p = "(unknown IPv6 address)";
197 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
198 p, ntohs(sin->sin6_port));
204 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
205 addr = ntohl( addr );
206 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
208 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
211 return wine_dbg_sprintf("{ family %d }", a->sa_family);
215 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
216 #define SOCKET2HANDLE(s) ((HANDLE)(s))
217 #define HANDLE2SOCKET(h) ((SOCKET)(h))
219 /****************************************************************
220 * Async IO declarations
221 ****************************************************************/
223 typedef struct ws2_async
227 LPWSAOVERLAPPED user_overlapped;
228 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
229 IO_STATUS_BLOCK local_iosb;
230 struct WS_sockaddr *addr;
233 int val; /* for send operations */
234 int *ptr; /* for recv operations */
237 unsigned int n_iovecs;
238 unsigned int first_iovec;
239 struct iovec iovec[1];
242 /****************************************************************/
244 /* ----------------------------------- internal data */
246 /* ws_... struct conversion flags */
248 typedef struct /* WSAAsyncSelect() control struct */
250 HANDLE service, event, sock;
256 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
257 #define WS_MAX_UDP_DATAGRAM 1024
258 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
260 /* hostent's, servent's and protent's are stored in one buffer per thread,
261 * as documented on MSDN for the functions that return any of the buffers */
262 struct per_thread_data
265 struct WS_hostent *he_buffer;
266 struct WS_servent *se_buffer;
267 struct WS_protoent *pe_buffer;
273 static INT num_startup; /* reference counter */
274 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
276 /* function prototypes */
277 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
278 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
279 static struct WS_servent *WS_dup_se(const struct servent* p_se);
281 int WSAIOCTL_GetInterfaceCount(void);
282 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
285 UINT wsaHerrno(int errnr);
287 #define MAP_OPTION(opt) { WS_##opt, opt }
289 static const int ws_sock_map[][2] =
291 MAP_OPTION( SO_DEBUG ),
292 MAP_OPTION( SO_ACCEPTCONN ),
293 MAP_OPTION( SO_REUSEADDR ),
294 MAP_OPTION( SO_KEEPALIVE ),
295 MAP_OPTION( SO_DONTROUTE ),
296 MAP_OPTION( SO_BROADCAST ),
297 MAP_OPTION( SO_LINGER ),
298 MAP_OPTION( SO_OOBINLINE ),
299 MAP_OPTION( SO_SNDBUF ),
300 MAP_OPTION( SO_RCVBUF ),
301 MAP_OPTION( SO_ERROR ),
302 MAP_OPTION( SO_TYPE ),
304 MAP_OPTION( SO_RCVTIMEO ),
307 MAP_OPTION( SO_SNDTIMEO ),
311 static const int ws_tcp_map[][2] =
314 MAP_OPTION( TCP_NODELAY ),
318 static const int ws_ip_map[][2] =
320 MAP_OPTION( IP_MULTICAST_IF ),
321 MAP_OPTION( IP_MULTICAST_TTL ),
322 MAP_OPTION( IP_MULTICAST_LOOP ),
323 MAP_OPTION( IP_ADD_MEMBERSHIP ),
324 MAP_OPTION( IP_DROP_MEMBERSHIP ),
325 MAP_OPTION( IP_OPTIONS ),
327 MAP_OPTION( IP_HDRINCL ),
329 MAP_OPTION( IP_TOS ),
330 MAP_OPTION( IP_TTL ),
333 static const int ws_af_map[][2] =
335 MAP_OPTION( AF_UNSPEC ),
336 MAP_OPTION( AF_INET ),
337 MAP_OPTION( AF_INET6 ),
339 MAP_OPTION( AF_IPX ),
342 MAP_OPTION( AF_IRDA ),
344 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
347 static const int ws_socktype_map[][2] =
349 MAP_OPTION( SOCK_DGRAM ),
350 MAP_OPTION( SOCK_STREAM ),
351 MAP_OPTION( SOCK_RAW ),
352 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
355 static const int ws_proto_map[][2] =
357 MAP_OPTION( IPPROTO_IP ),
358 MAP_OPTION( IPPROTO_TCP ),
359 MAP_OPTION( IPPROTO_UDP ),
360 MAP_OPTION( IPPROTO_ICMP ),
361 MAP_OPTION( IPPROTO_IGMP ),
362 MAP_OPTION( IPPROTO_RAW ),
363 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
366 static const int ws_aiflag_map[][2] =
368 MAP_OPTION( AI_PASSIVE ),
369 MAP_OPTION( AI_CANONNAME ),
370 MAP_OPTION( AI_NUMERICHOST ),
371 /* Linux/UNIX knows a lot more. But Windows only
372 * has 3 as far as I could see. -Marcus
376 static const int ws_niflag_map[][2] =
378 MAP_OPTION( NI_NOFQDN ),
379 MAP_OPTION( NI_NUMERICHOST ),
380 MAP_OPTION( NI_NAMEREQD ),
381 MAP_OPTION( NI_NUMERICSERV ),
382 MAP_OPTION( NI_DGRAM ),
385 static const int ws_eai_map[][2] =
387 MAP_OPTION( EAI_AGAIN ),
388 MAP_OPTION( EAI_BADFLAGS ),
389 MAP_OPTION( EAI_FAIL ),
390 MAP_OPTION( EAI_FAMILY ),
391 MAP_OPTION( EAI_MEMORY ),
392 /* Note: EAI_NODATA is deprecated, but still
393 * used by Windows and Linux... We map the newer
394 * EAI_NONAME to EAI_NODATA for now until Windows
398 MAP_OPTION( EAI_NODATA ),
401 { WS_EAI_NODATA, EAI_NONAME },
404 MAP_OPTION( EAI_SERVICE ),
405 MAP_OPTION( EAI_SOCKTYPE ),
409 static const char magic_loopback_addr[] = {127, 12, 34, 56};
411 static inline DWORD NtStatusToWSAError( const DWORD status )
413 /* We only need to cover the status codes set by server async request handling */
417 case STATUS_SUCCESS: wserr = 0; break;
418 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
419 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
420 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
421 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
422 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
423 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
424 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
425 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
427 if ( status >= WSABASEERR && status <= WSABASEERR+1004 )
428 /* It is not an NT status code but a winsock error */
432 wserr = RtlNtStatusToDosError( status );
433 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
439 /* set last error code from NT status without mapping WSA errors */
440 static inline unsigned int set_error( unsigned int err )
444 err = NtStatusToWSAError( err );
450 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
453 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
458 static inline void release_sock_fd( SOCKET s, int fd )
460 wine_server_release_fd( SOCKET2HANDLE(s), fd );
463 static void _enable_event( HANDLE s, unsigned int event,
464 unsigned int sstate, unsigned int cstate )
466 SERVER_START_REQ( enable_socket_event )
468 req->handle = wine_server_obj_handle( s );
470 req->sstate = sstate;
471 req->cstate = cstate;
472 wine_server_call( req );
477 static int _is_blocking(SOCKET s)
480 SERVER_START_REQ( get_socket_event )
482 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
483 req->service = FALSE;
485 wine_server_call( req );
486 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
492 static unsigned int _get_sock_mask(SOCKET s)
495 SERVER_START_REQ( get_socket_event )
497 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
498 req->service = FALSE;
500 wine_server_call( req );
507 static void _sync_sock_state(SOCKET s)
509 /* do a dummy wineserver request in order to let
510 the wineserver run through its select loop once */
511 (void)_is_blocking(s);
514 static int _get_sock_error(SOCKET s, unsigned int bit)
516 int events[FD_MAX_EVENTS];
518 SERVER_START_REQ( get_socket_event )
520 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
521 req->service = FALSE;
523 wine_server_set_reply( req, events, sizeof(events) );
524 wine_server_call( req );
530 static struct per_thread_data *get_per_thread_data(void)
532 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
533 /* lazy initialization */
536 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
537 NtCurrentTeb()->WinSockData = ptb;
542 static void free_per_thread_data(void)
544 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
548 /* delete scratch buffers */
549 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
550 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
551 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
552 ptb->he_buffer = NULL;
553 ptb->se_buffer = NULL;
554 ptb->pe_buffer = NULL;
556 HeapFree( GetProcessHeap(), 0, ptb );
557 NtCurrentTeb()->WinSockData = NULL;
560 /***********************************************************************
561 * DllMain (WS2_32.init)
563 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
565 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
567 case DLL_PROCESS_ATTACH:
569 case DLL_PROCESS_DETACH:
570 free_per_thread_data();
573 case DLL_THREAD_DETACH:
574 free_per_thread_data();
580 /***********************************************************************
583 * Converts socket flags from Windows format.
584 * Return 1 if converted, 0 if not (error).
586 static int convert_sockopt(INT *level, INT *optname)
593 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
594 if( ws_sock_map[i][0] == *optname )
596 *optname = ws_sock_map[i][1];
600 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
603 *level = IPPROTO_TCP;
604 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
605 if ( ws_tcp_map[i][0] == *optname )
607 *optname = ws_tcp_map[i][1];
611 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
615 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
616 if (ws_ip_map[i][0] == *optname )
618 *optname = ws_ip_map[i][1];
622 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
624 default: FIXME("Unimplemented or unknown socket level\n");
629 /* ----------------------------------- Per-thread info (or per-process?) */
631 static char *strdup_lower(const char *str)
634 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
638 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
641 else SetLastError(WSAENOBUFS);
645 static inline int sock_error_p(int s)
647 unsigned int optval, optlen;
649 optlen = sizeof(optval);
650 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
651 if (optval) WARN("\t[%i] error: %d\n", s, optval);
655 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
656 * from an fd and return the value converted to milli seconds
657 * or -1 if there is an infinite time out */
658 static inline int get_rcvsnd_timeo( int fd, int optname)
661 unsigned int len = sizeof(tv);
662 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
664 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
665 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
670 /* macro wrappers for portability */
672 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
674 #define GET_RCVTIMEO(fd) (-1)
678 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
680 #define GET_SNDTIMEO(fd) (-1)
683 /* utility: given an fd, will block until one of the events occurs */
684 static inline int do_block( int fd, int events, int timeout )
692 while ((ret = poll(&pfd, 1, timeout)) < 0)
703 convert_af_w2u(int windowsaf) {
706 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
707 if (ws_af_map[i][0] == windowsaf)
708 return ws_af_map[i][1];
709 FIXME("unhandled Windows address family %d\n", windowsaf);
714 convert_af_u2w(int unixaf) {
717 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
718 if (ws_af_map[i][1] == unixaf)
719 return ws_af_map[i][0];
720 FIXME("unhandled UNIX address family %d\n", unixaf);
725 convert_proto_w2u(int windowsproto) {
728 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
729 if (ws_proto_map[i][0] == windowsproto)
730 return ws_proto_map[i][1];
731 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
736 convert_proto_u2w(int unixproto) {
739 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
740 if (ws_proto_map[i][1] == unixproto)
741 return ws_proto_map[i][0];
742 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
747 convert_socktype_w2u(int windowssocktype) {
750 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
751 if (ws_socktype_map[i][0] == windowssocktype)
752 return ws_socktype_map[i][1];
753 FIXME("unhandled Windows socket type %d\n", windowssocktype);
758 convert_socktype_u2w(int unixsocktype) {
761 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
762 if (ws_socktype_map[i][1] == unixsocktype)
763 return ws_socktype_map[i][0];
764 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
768 /* ----------------------------------- API -----
770 * Init / cleanup / error checking.
773 /***********************************************************************
774 * WSAStartup (WS2_32.115)
776 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
778 TRACE("verReq=%x\n", wVersionRequested);
780 if (LOBYTE(wVersionRequested) < 1)
781 return WSAVERNOTSUPPORTED;
783 if (!lpWSAData) return WSAEINVAL;
787 /* that's the whole of the negotiation for now */
788 lpWSAData->wVersion = wVersionRequested;
789 /* return winsock information */
790 lpWSAData->wHighVersion = 0x0202;
791 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
792 strcpy(lpWSAData->szSystemStatus, "Running" );
793 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
794 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
795 /* don't do anything with lpWSAData->lpVendorInfo */
796 /* (some apps don't allocate the space for this field) */
798 TRACE("succeeded\n");
803 /***********************************************************************
804 * WSACleanup (WS2_32.116)
806 INT WINAPI WSACleanup(void)
812 SetLastError(WSANOTINITIALISED);
817 /***********************************************************************
818 * WSAGetLastError (WINSOCK.111)
819 * WSAGetLastError (WS2_32.111)
821 INT WINAPI WSAGetLastError(void)
823 return GetLastError();
826 /***********************************************************************
827 * WSASetLastError (WS2_32.112)
829 void WINAPI WSASetLastError(INT iError) {
830 SetLastError(iError);
833 static struct WS_hostent *check_buffer_he(int size)
835 struct per_thread_data * ptb = get_per_thread_data();
838 if (ptb->he_len >= size ) return ptb->he_buffer;
839 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
841 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
842 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
843 return ptb->he_buffer;
846 static struct WS_servent *check_buffer_se(int size)
848 struct per_thread_data * ptb = get_per_thread_data();
851 if (ptb->se_len >= size ) return ptb->se_buffer;
852 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
854 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
855 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
856 return ptb->se_buffer;
859 static struct WS_protoent *check_buffer_pe(int size)
861 struct per_thread_data * ptb = get_per_thread_data();
864 if (ptb->pe_len >= size ) return ptb->pe_buffer;
865 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
867 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
868 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
869 return ptb->pe_buffer;
872 /* ----------------------------------- i/o APIs */
874 static inline BOOL supported_pf(int pf)
895 /**********************************************************************/
897 /* Returns the length of the converted address if successful, 0 if it was too small to
900 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
901 union generic_unix_sockaddr *uaddr)
903 unsigned int uaddrlen = 0;
905 switch (wsaddr->sa_family)
910 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
911 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
913 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
916 uaddrlen = sizeof(struct sockaddr_ipx);
917 memset( uaddr, 0, uaddrlen );
918 uipx->sipx_family=AF_IPX;
919 uipx->sipx_port=wsipx->sa_socket;
920 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
923 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
924 #ifdef IPX_FRAME_NONE
925 uipx->sipx_type=IPX_FRAME_NONE;
931 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
932 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
934 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
935 * scope_id, one without.
937 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
938 uaddrlen = sizeof(struct sockaddr_in6);
939 memset( uaddr, 0, uaddrlen );
940 uin6->sin6_family = AF_INET6;
941 uin6->sin6_port = win6->sin6_port;
942 uin6->sin6_flowinfo = win6->sin6_flowinfo;
943 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
944 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
946 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
949 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
953 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
954 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
956 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
958 uaddrlen = sizeof(struct sockaddr_in);
959 memset( uaddr, 0, uaddrlen );
960 uin->sin_family = AF_INET;
961 uin->sin_port = win->sin_port;
962 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
967 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
968 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
970 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
972 uaddrlen = sizeof(struct sockaddr_irda);
973 memset( uaddr, 0, uaddrlen );
974 uin->sir_family = AF_IRDA;
975 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
977 unsigned int lsap_sel;
979 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
980 uin->sir_lsap_sel = lsap_sel;
984 uin->sir_lsap_sel = LSAP_ANY;
985 memcpy( uin->sir_name, win->irdaServiceName, 25 );
987 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
992 /* Try to determine the needed space by the passed windows sockaddr space */
994 default: /* likely a ipv4 address */
995 case sizeof(struct WS_sockaddr_in):
996 uaddrlen = sizeof(struct sockaddr_in);
999 case sizeof(struct WS_sockaddr_ipx):
1000 uaddrlen = sizeof(struct sockaddr_ipx);
1004 case sizeof(SOCKADDR_IRDA):
1005 uaddrlen = sizeof(struct sockaddr_irda);
1008 case sizeof(struct WS_sockaddr_in6):
1009 case sizeof(struct WS_sockaddr_in6_old):
1010 uaddrlen = sizeof(struct sockaddr_in6);
1013 memset( uaddr, 0, uaddrlen );
1017 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1023 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1025 switch (uaddr->sa_family)
1029 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
1034 static const struct sockaddr_in6 emptyAddr;
1035 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1036 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1040 static const struct sockaddr_in emptyAddr;
1041 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1042 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1047 FIXME("unknown address family %d\n", uaddr->sa_family);
1052 /* Returns 0 if successful, -1 if the buffer is too small */
1053 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1057 switch(uaddr->sa_family)
1062 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1063 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1066 switch (*wsaddrlen) /* how much can we copy? */
1070 *wsaddrlen = sizeof(*wsipx);
1071 wsipx->sa_socket=uipx->sipx_port;
1075 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1083 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1089 wsipx->sa_family=WS_AF_IPX;
1101 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1102 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1104 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1106 win->irdaAddressFamily = WS_AF_IRDA;
1107 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1108 if (uin->sir_lsap_sel != LSAP_ANY)
1109 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1111 memcpy( win->irdaServiceName, uin->sir_name,
1112 sizeof(win->irdaServiceName) );
1117 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1118 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1120 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1122 win6old->sin6_family = WS_AF_INET6;
1123 win6old->sin6_port = uin6->sin6_port;
1124 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1125 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1126 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1127 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1128 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1129 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1130 win6->sin6_scope_id = uin6->sin6_scope_id;
1131 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1137 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1138 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1140 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1142 win->sin_family = WS_AF_INET;
1143 win->sin_port = uin->sin_port;
1144 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1145 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1146 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1150 memset(wsaddr,0,*wsaddrlen);
1154 FIXME("Unknown address family %d\n", uaddr->sa_family);
1160 /**************************************************************************
1161 * Functions for handling overlapped I/O
1162 **************************************************************************/
1164 /* user APC called upon async completion */
1165 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1167 ws2_async *wsa = arg;
1169 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1170 iosb->Information, wsa->user_overlapped,
1172 HeapFree( GetProcessHeap(), 0, wsa );
1175 /***********************************************************************
1176 * WS2_recv (INTERNAL)
1178 * Workhorse for both synchronous and asynchronous recv() operations.
1180 static int WS2_recv( int fd, struct ws2_async *wsa )
1183 union generic_unix_sockaddr unix_sockaddr;
1186 hdr.msg_name = NULL;
1190 hdr.msg_namelen = sizeof(unix_sockaddr);
1191 hdr.msg_name = &unix_sockaddr;
1194 hdr.msg_namelen = 0;
1196 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1197 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1198 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1199 hdr.msg_accrights = NULL;
1200 hdr.msg_accrightslen = 0;
1202 hdr.msg_control = NULL;
1203 hdr.msg_controllen = 0;
1207 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1210 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1211 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1213 * quoting linux 2.6 net/ipv4/tcp.c:
1214 * "According to UNIX98, msg_name/msg_namelen are ignored
1215 * on connected socket. I was just happy when found this 8) --ANK"
1217 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1218 * connection-oriented sockets, so don't try to update lpFrom.
1220 if (wsa->addr && hdr.msg_namelen)
1221 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1226 /***********************************************************************
1227 * WS2_async_recv (INTERNAL)
1229 * Handler for overlapped recv() operations.
1231 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1233 ws2_async* wsa = user;
1238 case STATUS_ALERTED:
1239 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1242 result = WS2_recv( fd, wsa );
1243 wine_server_release_fd( wsa->hSocket, fd );
1246 status = STATUS_SUCCESS;
1247 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1251 if (errno == EINTR || errno == EAGAIN)
1253 status = STATUS_PENDING;
1254 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1259 status = wsaErrno(); /* FIXME: is this correct ???? */
1264 if (status != STATUS_PENDING)
1266 iosb->u.Status = status;
1267 iosb->Information = result;
1268 *apc = ws2_async_apc;
1273 /***********************************************************************
1274 * WS2_send (INTERNAL)
1276 * Workhorse for both synchronous and asynchronous send() operations.
1278 static int WS2_send( int fd, struct ws2_async *wsa )
1281 union generic_unix_sockaddr unix_addr;
1283 hdr.msg_name = NULL;
1284 hdr.msg_namelen = 0;
1288 hdr.msg_name = &unix_addr;
1289 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
1290 if ( !hdr.msg_namelen )
1296 #if defined(HAVE_IPX) && defined(SOL_IPX)
1297 if(wsa->addr->sa_family == WS_AF_IPX)
1299 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1301 unsigned int len=sizeof(int);
1303 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1304 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1305 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1306 * ipx type in the sockaddr_opx structure with the stored value.
1308 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1309 uipx->sipx_type = val;
1314 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1315 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1316 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1317 hdr.msg_accrights = NULL;
1318 hdr.msg_accrightslen = 0;
1320 hdr.msg_control = NULL;
1321 hdr.msg_controllen = 0;
1325 return sendmsg(fd, &hdr, wsa->flags);
1328 /***********************************************************************
1329 * WS2_async_send (INTERNAL)
1331 * Handler for overlapped send() operations.
1333 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1335 ws2_async* wsa = user;
1340 case STATUS_ALERTED:
1341 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1344 /* check to see if the data is ready (non-blocking) */
1345 result = WS2_send( fd, wsa );
1346 wine_server_release_fd( wsa->hSocket, fd );
1350 int totalLength = 0;
1352 status = STATUS_SUCCESS;
1353 for (i = 0; i < wsa->n_iovecs; i++)
1354 totalLength += wsa->iovec[i].iov_len;
1355 if (result < totalLength)
1356 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1360 if (errno == EINTR || errno == EAGAIN)
1362 status = STATUS_PENDING;
1363 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1367 /* We set the status to a winsock error code and check for that
1368 later in NtStatusToWSAError () */
1369 status = wsaErrno();
1375 if (status != STATUS_PENDING)
1377 iosb->u.Status = status;
1378 iosb->Information = result;
1379 *apc = ws2_async_apc;
1384 /***********************************************************************
1385 * WS2_async_shutdown (INTERNAL)
1387 * Handler for shutdown() operations on overlapped sockets.
1389 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
1391 ws2_async* wsa = user;
1396 case STATUS_ALERTED:
1397 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1400 switch ( wsa->type )
1402 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1403 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1405 wine_server_release_fd( wsa->hSocket, fd );
1406 status = err ? wsaErrno() : STATUS_SUCCESS;
1409 iosb->u.Status = status;
1410 *apc = ws2_async_apc;
1414 /***********************************************************************
1415 * WS2_register_async_shutdown (INTERNAL)
1417 * Helper function for WS_shutdown() on overlapped sockets.
1419 static int WS2_register_async_shutdown( SOCKET s, int type )
1421 struct ws2_async *wsa;
1424 TRACE("s %ld type %d\n", s, type);
1426 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1430 wsa->hSocket = SOCKET2HANDLE(s);
1432 wsa->completion_func = NULL;
1434 SERVER_START_REQ( register_async )
1437 req->async.handle = wine_server_obj_handle( wsa->hSocket );
1438 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
1439 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
1440 req->async.arg = wine_server_client_ptr( wsa );
1441 req->async.cvalue = 0;
1442 status = wine_server_call( req );
1446 if (status != STATUS_PENDING)
1448 HeapFree( GetProcessHeap(), 0, wsa );
1449 return NtStatusToWSAError( status );
1454 /***********************************************************************
1457 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1463 TRACE("socket %04lx\n", s );
1464 is_blocking = _is_blocking(s);
1469 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1470 if (fd == -1) return INVALID_SOCKET;
1472 do_block(fd, POLLIN, -1);
1473 _sync_sock_state(s); /* let wineserver notice connection */
1474 release_sock_fd( s, fd );
1475 /* retrieve any error codes from it */
1476 SetLastError(_get_sock_error(s, FD_ACCEPT_BIT));
1477 /* FIXME: care about the error? */
1479 SERVER_START_REQ( accept_socket )
1481 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1482 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1483 req->attributes = OBJ_INHERIT;
1484 set_error( wine_server_call( req ) );
1485 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
1490 if (addr) WS_getpeername(as, addr, addrlen32);
1493 } while (is_blocking);
1494 return INVALID_SOCKET;
1497 /***********************************************************************
1500 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1502 int fd = get_sock_fd( s, 0, NULL );
1503 int res = SOCKET_ERROR;
1505 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1509 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
1511 SetLastError(WSAEAFNOSUPPORT);
1515 union generic_unix_sockaddr uaddr;
1516 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1519 SetLastError(WSAEFAULT);
1524 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
1525 if (name->sa_family == WS_AF_INET6 &&
1526 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
1529 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
1531 release_sock_fd( s, fd );
1532 SetLastError(WSAEAFNOSUPPORT);
1533 return SOCKET_ERROR;
1537 if (name->sa_family == WS_AF_INET)
1539 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1540 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1542 /* Trying to bind to the default host interface, using
1543 * INADDR_ANY instead*/
1544 WARN("Trying to bind to magic IP address, using "
1545 "INADDR_ANY instead.\n");
1546 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
1549 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
1551 int loc_errno = errno;
1552 WARN("\tfailure - errno = %i\n", errno);
1557 SetLastError(WSAENOTSOCK);
1560 SetLastError(WSAEINVAL);
1563 SetLastError(wsaErrno());
1569 res=0; /* success */
1573 release_sock_fd( s, fd );
1578 /***********************************************************************
1579 * closesocket (WS2_32.3)
1581 int WINAPI WS_closesocket(SOCKET s)
1583 TRACE("socket %04lx\n", s);
1584 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
1585 return SOCKET_ERROR;
1588 /***********************************************************************
1589 * connect (WS2_32.4)
1591 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1593 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1595 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1599 union generic_unix_sockaddr uaddr;
1600 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1604 SetLastError(WSAEFAULT);
1608 if (name->sa_family == WS_AF_INET)
1610 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1611 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1613 /* Trying to connect to magic replace-loopback address,
1614 * assuming we really want to connect to localhost */
1615 TRACE("Trying to connect to magic IP address, using "
1616 "INADDR_LOOPBACK instead.\n");
1617 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
1621 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
1622 goto connect_success;
1625 if (errno == EINPROGRESS)
1627 /* tell wineserver that a connection is in progress */
1628 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1629 FD_CONNECT|FD_READ|FD_WRITE,
1630 FD_WINE_CONNECTED|FD_WINE_LISTENING);
1631 if (_is_blocking(s))
1635 do_block(fd, POLLIN | POLLOUT, -1);
1636 _sync_sock_state(s); /* let wineserver notice connection */
1637 /* retrieve any error codes from it */
1638 result = _get_sock_error(s, FD_CONNECT_BIT);
1640 SetLastError(result);
1643 goto connect_success;
1648 SetLastError(WSAEWOULDBLOCK);
1653 SetLastError(wsaErrno());
1655 release_sock_fd( s, fd );
1657 return SOCKET_ERROR;
1660 release_sock_fd( s, fd );
1661 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1662 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1663 FD_CONNECT|FD_WINE_LISTENING);
1667 /***********************************************************************
1668 * WSAConnect (WS2_32.30)
1670 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
1671 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1672 LPQOS lpSQOS, LPQOS lpGQOS )
1674 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1675 FIXME("unsupported parameters!\n");
1676 return WS_connect( s, name, namelen );
1680 /***********************************************************************
1681 * getpeername (WS2_32.5)
1683 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1688 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, *namelen);
1690 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1691 if( (name == NULL) || (namelen == NULL) )
1693 SetLastError( WSAEFAULT );
1694 return SOCKET_ERROR;
1697 fd = get_sock_fd( s, 0, NULL );
1702 union generic_unix_sockaddr uaddr;
1703 unsigned int uaddrlen = sizeof(uaddr);
1705 if (getpeername(fd, &uaddr.addr, &uaddrlen) != 0)
1707 SetLastError(wsaErrno());
1709 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1711 /* The buffer was too small */
1712 SetLastError(WSAEFAULT);
1718 release_sock_fd( s, fd );
1723 /***********************************************************************
1724 * getsockname (WS2_32.6)
1726 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1731 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
1733 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1734 if( (name == NULL) || (namelen == NULL) )
1736 SetLastError( WSAEFAULT );
1737 return SOCKET_ERROR;
1740 fd = get_sock_fd( s, 0, NULL );
1745 union generic_unix_sockaddr uaddr;
1746 unsigned int uaddrlen = sizeof(uaddr);
1748 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
1750 SetLastError(wsaErrno());
1752 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
1754 SetLastError(WSAEINVAL);
1756 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1758 /* The buffer was too small */
1759 SetLastError(WSAEFAULT);
1765 release_sock_fd( s, fd );
1770 /***********************************************************************
1771 * getsockopt (WS2_32.7)
1773 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1774 INT optname, char *optval, INT *optlen)
1779 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
1780 s, level, optname, optval, *optlen);
1788 /* Handle common cases. The special cases are below, sorted
1790 case WS_SO_ACCEPTCONN:
1791 case WS_SO_BROADCAST:
1794 case WS_SO_KEEPALIVE:
1795 case WS_SO_OOBINLINE:
1797 case WS_SO_REUSEADDR:
1800 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1801 return SOCKET_ERROR;
1802 convert_sockopt(&level, &optname);
1803 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1805 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1808 release_sock_fd( s, fd );
1811 case WS_SO_DONTLINGER:
1813 struct linger lingval;
1814 unsigned int len = sizeof(struct linger);
1816 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
1818 SetLastError(WSAEFAULT);
1819 return SOCKET_ERROR;
1821 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1822 return SOCKET_ERROR;
1824 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1826 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1831 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
1832 *optlen = sizeof(BOOL);
1835 release_sock_fd( s, fd );
1839 /* As mentioned in setsockopt, Windows ignores this, so we
1840 * always return true here */
1841 case WS_SO_DONTROUTE:
1842 if (!optlen || *optlen < sizeof(BOOL) || !optval)
1844 SetLastError(WSAEFAULT);
1845 return SOCKET_ERROR;
1847 *(BOOL *)optval = TRUE;
1848 *optlen = sizeof(BOOL);
1853 struct linger lingval;
1854 unsigned int len = sizeof(struct linger);
1856 /* struct linger and LINGER have different sizes */
1857 if (!optlen || *optlen < sizeof(LINGER) || !optval)
1859 SetLastError(WSAEFAULT);
1860 return SOCKET_ERROR;
1862 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1863 return SOCKET_ERROR;
1865 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1867 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1872 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
1873 ((LINGER *)optval)->l_linger = lingval.l_linger;
1874 *optlen = sizeof(struct linger);
1877 release_sock_fd( s, fd );
1881 case WS_SO_MAX_MSG_SIZE:
1882 if (!optlen || *optlen < sizeof(int) || !optval)
1884 SetLastError(WSAEFAULT);
1885 return SOCKET_ERROR;
1887 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
1888 *(int *)optval = 65507;
1889 *optlen = sizeof(int);
1892 /* SO_OPENTYPE does not require a valid socket handle. */
1893 case WS_SO_OPENTYPE:
1894 if (!optlen || *optlen < sizeof(int) || !optval)
1896 SetLastError(WSAEFAULT);
1897 return SOCKET_ERROR;
1899 *(int *)optval = get_per_thread_data()->opentype;
1900 *optlen = sizeof(int);
1901 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
1905 case WS_SO_RCVTIMEO:
1908 case WS_SO_SNDTIMEO:
1910 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
1913 unsigned int len = sizeof(struct timeval);
1915 if (!optlen || *optlen < sizeof(int)|| !optval)
1917 SetLastError(WSAEFAULT);
1918 return SOCKET_ERROR;
1920 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1921 return SOCKET_ERROR;
1923 convert_sockopt(&level, &optname);
1924 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
1926 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1931 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1932 *optlen = sizeof(int);
1935 release_sock_fd( s, fd );
1940 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
1941 SetLastError(WSAENOPROTOOPT);
1942 return SOCKET_ERROR;
1943 } /* end switch(optname) */
1944 }/* end case WS_SOL_SOCKET */
1948 struct WS_sockaddr_ipx addr;
1949 IPX_ADDRESS_DATA *data;
1954 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
1956 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
1963 socklen_t len=sizeof(struct ipx);
1964 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
1967 *optval = (int)val.ipx_pt;
1970 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
1971 release_sock_fd( s, fd );
1976 * On a Win2000 system with one network card there are usually
1977 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
1978 * Using this call you can then retrieve info about this all.
1979 * In case of Linux it is a bit different. Usually you have
1980 * only "one" device active and further it is not possible to
1981 * query things like the linkspeed.
1983 FIXME("IPX_ADDRESS\n");
1984 namelen = sizeof(struct WS_sockaddr_ipx);
1985 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
1986 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
1988 data = (IPX_ADDRESS_DATA*)optval;
1989 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
1990 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
1991 data->adapternum = 0;
1992 data->wan = FALSE; /* We are not on a wan for now .. */
1993 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
1994 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
1995 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
1996 * note 1MB = 1000kB in this case */
1999 case IPX_MAX_ADAPTER_NUM:
2000 FIXME("IPX_MAX_ADAPTER_NUM\n");
2001 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
2005 FIXME("IPX optname:%x\n", optname);
2006 return SOCKET_ERROR;
2007 }/* end switch(optname) */
2008 } /* end case NSPROTO_IPX */
2015 case WS_IRLMP_ENUMDEVICES:
2017 static const int MAX_IRDA_DEVICES = 10;
2018 char buf[sizeof(struct irda_device_list) +
2019 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
2021 socklen_t len = sizeof(buf);
2023 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2024 return SOCKET_ERROR;
2025 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
2028 SetLastError(wsaErrno());
2029 return SOCKET_ERROR;
2033 struct irda_device_list *src = (struct irda_device_list *)buf;
2034 DEVICELIST *dst = (DEVICELIST *)optval;
2035 INT needed = sizeof(DEVICELIST), i;
2038 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
2039 if (*optlen < needed)
2041 SetLastError(WSAEFAULT);
2042 return SOCKET_ERROR;
2045 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
2046 dst->numDevice = src->len;
2047 for (i = 0; i < src->len; i++)
2049 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
2050 src->dev[i].saddr, src->dev[i].daddr,
2051 src->dev[i].info, src->dev[i].hints[0],
2052 src->dev[i].hints[1]);
2053 memcpy( dst->Device[i].irdaDeviceID,
2055 sizeof(dst->Device[i].irdaDeviceID) ) ;
2056 memcpy( dst->Device[i].irdaDeviceName,
2058 sizeof(dst->Device[i].irdaDeviceName) ) ;
2059 memcpy( &dst->Device[i].irdaDeviceHints1,
2060 &src->dev[i].hints[0],
2061 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
2062 memcpy( &dst->Device[i].irdaDeviceHints2,
2063 &src->dev[i].hints[1],
2064 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
2065 dst->Device[i].irdaCharSet = src->dev[i].charset;
2071 FIXME("IrDA optname:0x%x\n", optname);
2072 return SOCKET_ERROR;
2074 break; /* case WS_SOL_IRLMP */
2077 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
2078 case WS_IPPROTO_TCP:
2081 case WS_TCP_NODELAY:
2082 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2083 return SOCKET_ERROR;
2084 convert_sockopt(&level, &optname);
2085 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2087 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2090 release_sock_fd( s, fd );
2093 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
2094 return SOCKET_ERROR;
2099 case WS_IP_ADD_MEMBERSHIP:
2100 case WS_IP_DROP_MEMBERSHIP:
2104 case WS_IP_MULTICAST_IF:
2105 case WS_IP_MULTICAST_LOOP:
2106 case WS_IP_MULTICAST_TTL:
2110 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2111 return SOCKET_ERROR;
2112 convert_sockopt(&level, &optname);
2113 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2115 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2118 release_sock_fd( s, fd );
2120 case WS_IP_DONTFRAGMENT:
2121 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
2122 *(BOOL*)optval = FALSE;
2125 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
2126 return SOCKET_ERROR;
2129 WARN("Unknown level: 0x%08x\n", level);
2130 SetLastError(WSAEINVAL);
2131 return SOCKET_ERROR;
2132 } /* end switch(level) */
2135 /***********************************************************************
2139 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
2141 return htonl(hostlong);
2145 /***********************************************************************
2149 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
2151 return htons(hostshort);
2154 /***********************************************************************
2155 * WSAHtonl (WS2_32.46)
2156 * From MSDN description of error codes, this function should also
2157 * check if WinSock has been initialized and the socket is a valid
2158 * socket. But why? This function only translates a host byte order
2159 * u_long into a network byte order u_long...
2161 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
2165 *lpnetlong = htonl(hostlong);
2168 WSASetLastError(WSAEFAULT);
2169 return SOCKET_ERROR;
2172 /***********************************************************************
2173 * WSAHtons (WS2_32.47)
2174 * From MSDN description of error codes, this function should also
2175 * check if WinSock has been initialized and the socket is a valid
2176 * socket. But why? This function only translates a host byte order
2177 * u_short into a network byte order u_short...
2179 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2184 *lpnetshort = htons(hostshort);
2187 WSASetLastError(WSAEFAULT);
2188 return SOCKET_ERROR;
2192 /***********************************************************************
2193 * inet_addr (WINSOCK.10)
2194 * inet_addr (WS2_32.11)
2196 WS_u_long WINAPI WS_inet_addr(const char *cp)
2198 if (!cp) return INADDR_NONE;
2199 return inet_addr(cp);
2203 /***********************************************************************
2204 * ntohl (WINSOCK.14)
2207 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2209 return ntohl(netlong);
2213 /***********************************************************************
2214 * ntohs (WINSOCK.15)
2217 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2219 return ntohs(netshort);
2223 /***********************************************************************
2224 * inet_ntoa (WS2_32.12)
2226 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2228 /* use "buffer for dummies" here because some applications have a
2229 * propensity to decode addresses in ws_hostent structure without
2230 * saving them first...
2232 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2234 char* s = inet_ntoa(*((struct in_addr*)&in));
2240 SetLastError(wsaErrno());
2244 /**********************************************************************
2245 * WSAIoctl (WS2_32.50)
2248 INT WINAPI WSAIoctl(SOCKET s,
2249 DWORD dwIoControlCode,
2252 LPVOID lpbOutBuffer,
2254 LPDWORD lpcbBytesReturned,
2255 LPWSAOVERLAPPED lpOverlapped,
2256 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2258 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
2259 s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpbOutBuffer,
2260 cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
2262 switch( dwIoControlCode )
2265 if (cbInBuffer != sizeof(WS_u_long)) {
2266 WSASetLastError(WSAEFAULT);
2267 return SOCKET_ERROR;
2269 return WS_ioctlsocket( s, WS_FIONBIO, lpvInBuffer);
2272 if (cbOutBuffer != sizeof(WS_u_long)) {
2273 WSASetLastError(WSAEFAULT);
2274 return SOCKET_ERROR;
2276 return WS_ioctlsocket( s, WS_FIONREAD, lpbOutBuffer);
2278 case WS_SIO_GET_INTERFACE_LIST:
2280 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
2281 DWORD size, numInt, apiReturn;
2284 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
2288 WSASetLastError(WSAEFAULT);
2289 return SOCKET_ERROR;
2291 if (!lpcbBytesReturned)
2293 WSASetLastError(WSAEFAULT);
2294 return SOCKET_ERROR;
2297 fd = get_sock_fd( s, 0, NULL );
2298 if (fd == -1) return SOCKET_ERROR;
2300 apiReturn = GetAdaptersInfo(NULL, &size);
2301 if (apiReturn == ERROR_NO_DATA)
2305 else if (apiReturn == ERROR_BUFFER_OVERFLOW)
2307 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
2311 if (GetAdaptersInfo(table, &size) == NO_ERROR)
2313 PIP_ADAPTER_INFO ptr;
2315 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > cbOutBuffer)
2317 WARN("Buffer too small = %u, cbOutBuffer = %u\n", size, cbOutBuffer);
2318 HeapFree(GetProcessHeap(),0,table);
2319 release_sock_fd( s, fd );
2320 WSASetLastError(WSAEFAULT);
2321 return SOCKET_ERROR;
2323 for (ptr = table, numInt = 0; ptr;
2324 ptr = ptr->Next, intArray++, numInt++)
2326 unsigned int addr, mask, bcast;
2327 struct ifreq ifInfo;
2329 /* Socket Status Flags */
2330 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
2331 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2333 ERR("Error obtaining status flags for socket!\n");
2334 HeapFree(GetProcessHeap(),0,table);
2335 release_sock_fd( s, fd );
2336 WSASetLastError(WSAEINVAL);
2337 return SOCKET_ERROR;
2341 /* set flags; the values of IFF_* are not the same
2342 under Linux and Windows, therefore must generate
2344 intArray->iiFlags = 0;
2345 if (ifInfo.ifr_flags & IFF_BROADCAST)
2346 intArray->iiFlags |= WS_IFF_BROADCAST;
2347 #ifdef IFF_POINTOPOINT
2348 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
2349 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
2351 if (ifInfo.ifr_flags & IFF_LOOPBACK)
2352 intArray->iiFlags |= WS_IFF_LOOPBACK;
2353 if (ifInfo.ifr_flags & IFF_UP)
2354 intArray->iiFlags |= WS_IFF_UP;
2355 if (ifInfo.ifr_flags & IFF_MULTICAST)
2356 intArray->iiFlags |= WS_IFF_MULTICAST;
2359 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
2360 mask = inet_addr(ptr->IpAddressList.IpMask.String);
2361 bcast = addr | ~mask;
2362 intArray->iiAddress.AddressIn.sin_family = AF_INET;
2363 intArray->iiAddress.AddressIn.sin_port = 0;
2364 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
2366 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2367 intArray->iiNetmask.AddressIn.sin_port = 0;
2368 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
2370 intArray->iiBroadcastAddress.AddressIn.sin_family =
2372 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
2373 intArray->iiBroadcastAddress.AddressIn.sin_addr.
2379 ERR("Unable to get interface table!\n");
2380 release_sock_fd( s, fd );
2381 HeapFree(GetProcessHeap(),0,table);
2382 WSASetLastError(WSAEINVAL);
2383 return SOCKET_ERROR;
2385 HeapFree(GetProcessHeap(),0,table);
2389 release_sock_fd( s, fd );
2390 WSASetLastError(WSAEINVAL);
2391 return SOCKET_ERROR;
2396 ERR("Unable to get interface table!\n");
2397 release_sock_fd( s, fd );
2398 WSASetLastError(WSAEINVAL);
2399 return SOCKET_ERROR;
2401 /* Calculate the size of the array being returned */
2402 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2403 release_sock_fd( s, fd );
2407 case WS_SIO_ADDRESS_LIST_CHANGE:
2408 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
2409 /* FIXME: error and return code depend on whether socket was created
2410 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
2413 case WS_SIO_ADDRESS_LIST_QUERY:
2417 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
2419 if (!lpcbBytesReturned)
2421 WSASetLastError(WSAEFAULT);
2422 return SOCKET_ERROR;
2425 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
2427 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
2430 if (!table || GetAdaptersInfo(table, &size))
2432 HeapFree(GetProcessHeap(), 0, table);
2433 WSASetLastError(WSAEINVAL);
2434 return SOCKET_ERROR;
2437 for (p = table, num = 0; p; p = p->Next)
2438 if (p->IpAddressList.IpAddress.String[0]) num++;
2440 need = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
2441 need += sizeof(SOCKADDR) * num;
2442 *lpcbBytesReturned = need;
2444 if (need > cbOutBuffer)
2446 HeapFree(GetProcessHeap(), 0, table);
2447 WSASetLastError(WSAEFAULT);
2448 return SOCKET_ERROR;
2455 SOCKET_ADDRESS_LIST *sa_list = (SOCKET_ADDRESS_LIST *)lpbOutBuffer;
2456 SOCKADDR_IN *sockaddr;
2458 sa = sa_list->Address;
2459 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
2460 sa_list->iAddressCount = num;
2462 for (p = table, i = 0; p; p = p->Next)
2464 if (!p->IpAddressList.IpAddress.String[0]) continue;
2466 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
2467 sa[i].iSockaddrLength = sizeof(SOCKADDR);
2469 sockaddr[i].sin_family = AF_INET;
2470 sockaddr[i].sin_port = 0;
2471 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
2476 HeapFree(GetProcessHeap(), 0, table);
2481 WARN("unable to get IP address list\n");
2482 WSASetLastError(WSAEINVAL);
2483 return SOCKET_ERROR;
2487 FIXME("SIO_FLUSH: stub.\n");
2490 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
2491 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(lpvInBuffer));
2492 WSASetLastError(WSAEOPNOTSUPP);
2493 return SOCKET_ERROR;
2495 case WS_SIO_KEEPALIVE_VALS:
2498 struct tcp_keepalive *k = lpvInBuffer;
2499 int keepalive = k->onoff ? 1 : 0;
2500 int keepidle = k->keepalivetime / 1000;
2501 int keepintvl = k->keepaliveinterval / 1000;
2505 WSASetLastError(WSAEINVAL);
2506 return SOCKET_ERROR;
2509 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
2511 fd = get_sock_fd(s, 0, NULL);
2512 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
2514 release_sock_fd(s, fd);
2515 WSASetLastError(WSAEINVAL);
2516 return SOCKET_ERROR;
2518 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
2519 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
2521 release_sock_fd(s, fd);
2522 WSASetLastError(WSAEINVAL);
2523 return SOCKET_ERROR;
2525 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
2527 release_sock_fd(s, fd);
2528 WSASetLastError(WSAEINVAL);
2529 return SOCKET_ERROR;
2532 FIXME("ignoring keepalive interval and timeout\n");
2535 release_sock_fd(s, fd);
2539 FIXME("unsupported WS_IOCTL cmd (%08x)\n", dwIoControlCode);
2540 WSASetLastError(WSAEOPNOTSUPP);
2541 return SOCKET_ERROR;
2548 /***********************************************************************
2549 * ioctlsocket (WS2_32.10)
2551 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
2556 TRACE("socket %04lx, cmd %08x, ptr %p\n", s, cmd, argp);
2557 /* broken apps like defcon pass the argp value directly instead of a pointer to it */
2558 if(IS_INTRESOURCE(argp))
2560 SetLastError(WSAEFAULT);
2561 return SOCKET_ERROR;
2571 if( _get_sock_mask(s) )
2573 /* AsyncSelect()'ed sockets are always nonblocking */
2574 if (*argp) return 0;
2575 SetLastError(WSAEINVAL);
2576 return SOCKET_ERROR;
2579 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
2581 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
2589 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2590 SetLastError(WSAEINVAL);
2591 return SOCKET_ERROR;
2593 case SIOCGIFBRDADDR:
2594 case SIOCGIFNETMASK:
2596 /* These don't need any special handling. They are used by
2597 WsControl, and are here to suppress an unnecessary warning. */
2601 /* Netscape tries hard to use bogus ioctl 0x667e */
2602 /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
2603 * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
2605 WARN("\tunknown WS_IOCTL cmd (%08x)\n", cmd);
2609 fd = get_sock_fd( s, 0, NULL );
2612 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2614 release_sock_fd( s, fd );
2617 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2618 release_sock_fd( s, fd );
2620 return SOCKET_ERROR;
2623 /***********************************************************************
2624 * listen (WS2_32.13)
2626 int WINAPI WS_listen(SOCKET s, int backlog)
2628 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2630 TRACE("socket %04lx, backlog %d\n", s, backlog);
2633 if (listen(fd, backlog) == 0)
2635 release_sock_fd( s, fd );
2636 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
2638 FD_CONNECT|FD_WINE_CONNECTED);
2641 SetLastError(wsaErrno());
2642 release_sock_fd( s, fd );
2644 return SOCKET_ERROR;
2647 /***********************************************************************
2650 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2652 DWORD n, dwFlags = flags;
2658 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2659 return SOCKET_ERROR;
2664 /***********************************************************************
2665 * recvfrom (WS2_32.17)
2667 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2668 struct WS_sockaddr *from, int *fromlen)
2670 DWORD n, dwFlags = flags;
2676 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2677 return SOCKET_ERROR;
2682 /* allocate a poll array for the corresponding fd sets */
2683 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
2684 const WS_fd_set *exceptfds, int *count_ptr )
2686 unsigned int i, j = 0, count = 0;
2689 if (readfds) count += readfds->fd_count;
2690 if (writefds) count += writefds->fd_count;
2691 if (exceptfds) count += exceptfds->fd_count;
2693 if (!count) return NULL;
2694 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0])))) return NULL;
2696 for (i = 0; i < readfds->fd_count; i++, j++)
2698 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
2699 fds[j].events = POLLIN;
2703 for (i = 0; i < writefds->fd_count; i++, j++)
2705 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
2706 fds[j].events = POLLOUT;
2710 for (i = 0; i < exceptfds->fd_count; i++, j++)
2712 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
2713 fds[j].events = POLLHUP;
2719 /* release the file descriptor obtained in fd_sets_to_poll */
2720 /* must be called with the original fd_set arrays, before calling get_poll_results */
2721 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
2722 const WS_fd_set *exceptfds, struct pollfd *fds )
2724 unsigned int i, j = 0;
2728 for (i = 0; i < readfds->fd_count; i++, j++)
2729 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
2733 for (i = 0; i < writefds->fd_count; i++, j++)
2734 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
2738 for (i = 0; i < exceptfds->fd_count; i++, j++)
2739 if (fds[j].fd != -1)
2741 /* make sure we have a real error before releasing the fd */
2742 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
2743 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
2748 /* map the poll results back into the Windows fd sets */
2749 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
2750 const struct pollfd *fds )
2752 unsigned int i, j = 0, k, total = 0;
2756 for (i = k = 0; i < readfds->fd_count; i++, j++)
2757 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
2758 readfds->fd_count = k;
2763 for (i = k = 0; i < writefds->fd_count; i++, j++)
2764 if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
2765 writefds->fd_count = k;
2770 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
2771 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
2772 exceptfds->fd_count = k;
2779 /***********************************************************************
2780 * select (WS2_32.18)
2782 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
2783 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
2784 const struct WS_timeval* ws_timeout)
2786 struct pollfd *pollfds;
2787 int count, ret, timeout = -1;
2789 TRACE("read %p, write %p, excp %p timeout %p\n",
2790 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
2792 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )) && count)
2794 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2795 return SOCKET_ERROR;
2798 if (ws_timeout) timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
2800 ret = poll( pollfds, count, timeout );
2801 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2803 if (ret == -1) SetLastError(wsaErrno());
2804 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2805 HeapFree( GetProcessHeap(), 0, pollfds );
2809 /* helper to send completion messages for client-only i/o operation case */
2810 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
2815 SERVER_START_REQ( add_fd_completion )
2817 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
2818 req->cvalue = CompletionValue;
2819 req->status = CompletionStatus;
2820 req->information = Information;
2821 status = wine_server_call( req );
2827 /***********************************************************************
2830 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
2836 wsabuf.buf = (char*) buf;
2838 if ( WSASendTo( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
2839 return SOCKET_ERROR;
2844 /***********************************************************************
2845 * WSASend (WS2_32.72)
2847 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2848 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2849 LPWSAOVERLAPPED lpOverlapped,
2850 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2852 return WSASendTo( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
2853 NULL, 0, lpOverlapped, lpCompletionRoutine );
2856 /***********************************************************************
2857 * WSASendDisconnect (WS2_32.73)
2859 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
2861 return WS_shutdown( s, SD_SEND );
2865 /***********************************************************************
2866 * WSASendTo (WS2_32.74)
2868 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2869 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2870 const struct WS_sockaddr *to, int tolen,
2871 LPWSAOVERLAPPED lpOverlapped,
2872 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2874 unsigned int i, options;
2876 struct ws2_async *wsa;
2877 int totalLength = 0;
2878 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
2880 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
2881 s, lpBuffers, dwBufferCount, dwFlags,
2882 to, tolen, lpOverlapped, lpCompletionRoutine);
2884 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
2885 TRACE( "fd=%d, options=%x\n", fd, options );
2887 if ( fd == -1 ) return SOCKET_ERROR;
2889 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
2895 wsa->hSocket = SOCKET2HANDLE(s);
2896 wsa->addr = (struct WS_sockaddr *)to;
2897 wsa->addrlen.val = tolen;
2898 wsa->flags = dwFlags;
2899 wsa->n_iovecs = dwBufferCount;
2900 wsa->first_iovec = 0;
2901 for ( i = 0; i < dwBufferCount; i++ )
2903 wsa->iovec[i].iov_base = lpBuffers[i].buf;
2904 wsa->iovec[i].iov_len = lpBuffers[i].len;
2905 totalLength += lpBuffers[i].len;
2908 if (!lpNumberOfBytesSent)
2916 n = WS2_send( fd, wsa );
2917 if (n != -1 || errno != EINTR) break;
2919 if (n == -1 && errno != EAGAIN)
2922 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
2926 if ((lpOverlapped || lpCompletionRoutine) &&
2927 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
2929 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
2931 wsa->user_overlapped = lpOverlapped;
2932 wsa->completion_func = lpCompletionRoutine;
2933 release_sock_fd( s, fd );
2937 iosb->u.Status = STATUS_PENDING;
2938 iosb->Information = 0;
2940 SERVER_START_REQ( register_async )
2942 req->type = ASYNC_TYPE_WRITE;
2943 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2944 req->async.callback = wine_server_client_ptr( WS2_async_send );
2945 req->async.iosb = wine_server_client_ptr( iosb );
2946 req->async.arg = wine_server_client_ptr( wsa );
2947 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
2948 req->async.cvalue = cvalue;
2949 err = wine_server_call( req );
2953 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
2954 WSASetLastError( NtStatusToWSAError( err ));
2955 return SOCKET_ERROR;
2958 iosb->u.Status = STATUS_SUCCESS;
2959 iosb->Information = n;
2960 *lpNumberOfBytesSent = n;
2961 if (!wsa->completion_func)
2963 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
2964 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
2965 HeapFree( GetProcessHeap(), 0, wsa );
2967 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
2968 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
2973 if ( _is_blocking(s) )
2975 /* On a blocking non-overlapped stream socket,
2976 * sending blocks until the entire buffer is sent. */
2977 DWORD timeout_start = GetTickCount();
2979 *lpNumberOfBytesSent = 0;
2981 while (wsa->first_iovec < dwBufferCount)
2984 int timeout = GET_SNDTIMEO(fd);
2988 *lpNumberOfBytesSent += n;
2989 while (wsa->first_iovec < dwBufferCount && wsa->iovec[wsa->first_iovec].iov_len <= n)
2990 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2991 if (wsa->first_iovec >= dwBufferCount) break;
2992 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2993 wsa->iovec[wsa->first_iovec].iov_len -= n;
2998 timeout -= GetTickCount() - timeout_start;
2999 if (timeout < 0) timeout = 0;
3003 pfd.events = POLLOUT;
3005 if (!timeout || !poll( &pfd, 1, timeout ))
3008 goto error; /* msdn says a timeout in send is fatal */
3011 n = WS2_send( fd, wsa );
3012 if (n == -1 && errno != EAGAIN && errno != EINTR)
3019 else /* non-blocking */
3021 if (n < totalLength)
3022 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
3025 err = WSAEWOULDBLOCK;
3028 *lpNumberOfBytesSent = n;
3031 TRACE(" -> %i bytes\n", *lpNumberOfBytesSent);
3033 HeapFree( GetProcessHeap(), 0, wsa );
3034 release_sock_fd( s, fd );
3039 HeapFree( GetProcessHeap(), 0, wsa );
3040 release_sock_fd( s, fd );
3041 WARN(" -> ERROR %d\n", err);
3042 WSASetLastError(err);
3043 return SOCKET_ERROR;
3046 /***********************************************************************
3047 * sendto (WS2_32.20)
3049 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
3050 const struct WS_sockaddr *to, int tolen)
3056 wsabuf.buf = (char*) buf;
3058 if ( WSASendTo(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
3059 return SOCKET_ERROR;
3064 /***********************************************************************
3065 * setsockopt (WS2_32.21)
3067 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
3068 const char *optval, int optlen)
3072 struct linger linger;
3073 struct timeval tval;
3075 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
3076 s, level, optname, optval, optlen);
3078 /* some broken apps pass the value directly instead of a pointer to it */
3079 if(IS_INTRESOURCE(optval))
3081 SetLastError(WSAEFAULT);
3082 return SOCKET_ERROR;
3090 /* Some options need some conversion before they can be sent to
3091 * setsockopt. The conversions are done here, then they will fall though
3092 * to the general case. Special options that are not passed to
3093 * setsockopt follow below that.*/
3095 case WS_SO_DONTLINGER:
3096 linger.l_onoff = *((const int*)optval) ? 0: 1;
3097 linger.l_linger = 0;
3099 optname = SO_LINGER;
3100 optval = (char*)&linger;
3101 optlen = sizeof(struct linger);
3105 linger.l_onoff = ((LINGER*)optval)->l_onoff;
3106 linger.l_linger = ((LINGER*)optval)->l_linger;
3107 /* FIXME: what is documented behavior if SO_LINGER optval
3110 optname = SO_LINGER;
3111 optval = (char*)&linger;
3112 optlen = sizeof(struct linger);
3116 if (*(const int*)optval < 2048)
3118 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
3123 /* The options listed here don't need any special handling. Thanks to
3124 * the conversion happening above, options from there will fall through
3126 case WS_SO_ACCEPTCONN:
3127 case WS_SO_BROADCAST:
3129 case WS_SO_KEEPALIVE:
3130 case WS_SO_OOBINLINE:
3131 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
3132 * however, using it the BSD way fixes bug 8513 and seems to be what
3133 * most programmers assume, anyway */
3134 case WS_SO_REUSEADDR:
3137 convert_sockopt(&level, &optname);
3140 /* SO_DEBUG is a privileged operation, ignore it. */
3142 TRACE("Ignoring SO_DEBUG\n");
3145 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
3146 * socket. According to MSDN, this option is silently ignored.*/
3147 case WS_SO_DONTROUTE:
3148 TRACE("Ignoring SO_DONTROUTE\n");
3151 /* Stops two sockets from being bound to the same port. Always happens
3152 * on unix systems, so just drop it. */
3153 case WS_SO_EXCLUSIVEADDRUSE:
3154 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
3157 /* SO_OPENTYPE does not require a valid socket handle. */
3158 case WS_SO_OPENTYPE:
3159 if (!optlen || optlen < sizeof(int) || !optval)
3161 SetLastError(WSAEFAULT);
3162 return SOCKET_ERROR;
3164 get_per_thread_data()->opentype = *(const int *)optval;
3165 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3169 case WS_SO_RCVTIMEO:
3172 case WS_SO_SNDTIMEO:
3174 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3175 if (optval && optlen == sizeof(UINT32)) {
3176 /* WinSock passes milliseconds instead of struct timeval */
3177 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
3178 tval.tv_sec = *(const UINT32*)optval / 1000;
3179 /* min of 500 milliseconds */
3180 if (tval.tv_sec == 0 && tval.tv_usec < 500000)
3181 tval.tv_usec = 500000;
3182 optlen = sizeof(struct timeval);
3183 optval = (char*)&tval;
3184 } else if (optlen == sizeof(struct timeval)) {
3185 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
3187 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
3190 convert_sockopt(&level, &optname);
3195 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3196 SetLastError(WSAENOPROTOOPT);
3197 return SOCKET_ERROR;
3199 break; /* case WS_SOL_SOCKET */
3206 fd = get_sock_fd( s, 0, NULL );
3207 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
3209 /* We try to set the ipx type on ipx socket level. */
3211 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
3213 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
3214 release_sock_fd( s, fd );
3215 return SOCKET_ERROR;
3220 /* Should we retrieve val using a getsockopt call and then
3221 * set the modified one? */
3222 val.ipx_pt = *optval;
3223 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
3226 release_sock_fd( s, fd );
3229 case IPX_FILTERPTYPE:
3230 /* Sets the receive filter packet type, at the moment we don't support it */
3231 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
3232 /* Returning 0 is better for now than returning a SOCKET_ERROR */
3236 FIXME("opt_name:%x\n", optname);
3237 return SOCKET_ERROR;
3239 break; /* case NSPROTO_IPX */
3242 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3243 case WS_IPPROTO_TCP:
3246 case WS_TCP_NODELAY:
3247 convert_sockopt(&level, &optname);
3250 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3251 return SOCKET_ERROR;
3258 case WS_IP_ADD_MEMBERSHIP:
3259 case WS_IP_DROP_MEMBERSHIP:
3263 case WS_IP_MULTICAST_IF:
3264 case WS_IP_MULTICAST_LOOP:
3265 case WS_IP_MULTICAST_TTL:
3269 convert_sockopt(&level, &optname);
3271 case WS_IP_DONTFRAGMENT:
3272 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
3275 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3276 return SOCKET_ERROR;
3281 WARN("Unknown level: 0x%08x\n", level);
3282 SetLastError(WSAEINVAL);
3283 return SOCKET_ERROR;
3284 } /* end switch(level) */
3286 /* avoid endianness issues if argument is a 16-bit int */
3287 if (optval && optlen < sizeof(int))
3289 woptval= *((const INT16 *) optval);
3290 optval= (char*) &woptval;
3293 fd = get_sock_fd( s, 0, NULL );
3294 if (fd == -1) return SOCKET_ERROR;
3296 if (setsockopt(fd, level, optname, optval, optlen) == 0)
3298 release_sock_fd( s, fd );
3301 TRACE("Setting socket error, %d\n", wsaErrno());
3302 SetLastError(wsaErrno());
3303 release_sock_fd( s, fd );
3305 return SOCKET_ERROR;
3308 /***********************************************************************
3309 * shutdown (WS2_32.22)
3311 int WINAPI WS_shutdown(SOCKET s, int how)
3313 int fd, err = WSAENOTSOCK;
3314 unsigned int options, clear_flags = 0;
3316 fd = get_sock_fd( s, 0, &options );
3317 TRACE("socket %04lx, how %i %x\n", s, how, options );
3320 return SOCKET_ERROR;
3324 case 0: /* drop receives */
3325 clear_flags |= FD_READ;
3327 case 1: /* drop sends */
3328 clear_flags |= FD_WRITE;
3330 case 2: /* drop all */
3331 clear_flags |= FD_READ|FD_WRITE;
3333 clear_flags |= FD_WINE_LISTENING;
3336 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3341 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3344 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3348 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3349 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3352 if (err) goto error;
3354 else /* non-overlapped mode */
3356 if ( shutdown( fd, how ) )
3363 release_sock_fd( s, fd );
3364 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3365 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
3369 release_sock_fd( s, fd );
3370 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3371 WSASetLastError( err );
3372 return SOCKET_ERROR;
3375 /***********************************************************************
3376 * socket (WS2_32.23)
3378 SOCKET WINAPI WS_socket(int af, int type, int protocol)
3380 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
3382 return WSASocketA( af, type, protocol, NULL, 0,
3383 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
3387 /***********************************************************************
3388 * gethostbyaddr (WS2_32.51)
3390 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
3392 struct WS_hostent *retval = NULL;
3393 struct hostent* host;
3395 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3398 struct hostent hostentry;
3401 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3403 int res = gethostbyaddr_r(addr, len, type,
3404 &hostentry, extrabuf, ebufsize, &host, &locerr);
3405 if( res != ERANGE) break;
3407 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3409 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3411 EnterCriticalSection( &csWSgetXXXbyYYY );
3412 host = gethostbyaddr(addr, len, type);
3413 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3415 if( host != NULL ) retval = WS_dup_he(host);
3416 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3417 HeapFree(GetProcessHeap(),0,extrabuf);
3419 LeaveCriticalSection( &csWSgetXXXbyYYY );
3421 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
3425 /***********************************************************************
3426 * gethostbyname (WS2_32.52)
3428 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
3430 struct WS_hostent *retval = NULL;
3431 struct hostent* host;
3432 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3435 struct hostent hostentry;
3436 int locerr = ENOBUFS;
3439 if( !name || !name[0]) {
3441 if( gethostname( buf, 100) == -1) {
3442 SetLastError( WSAENOBUFS); /* appropriate ? */
3446 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3448 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3450 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
3451 if( res != ERANGE) break;
3453 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3455 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3457 EnterCriticalSection( &csWSgetXXXbyYYY );
3458 host = gethostbyname(name);
3459 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3461 if (host) retval = WS_dup_he(host);
3462 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3463 HeapFree(GetProcessHeap(),0,extrabuf);
3465 LeaveCriticalSection( &csWSgetXXXbyYYY );
3467 if (retval && retval->h_addr_list[0][0] == 127 &&
3468 strcmp(name, "localhost") != 0)
3470 /* hostname != "localhost" but has loopback address. replace by our
3471 * special address.*/
3472 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
3474 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3479 /***********************************************************************
3480 * getprotobyname (WS2_32.53)
3482 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3484 struct WS_protoent* retval = NULL;
3485 #ifdef HAVE_GETPROTOBYNAME
3486 struct protoent* proto;
3487 EnterCriticalSection( &csWSgetXXXbyYYY );
3488 if( (proto = getprotobyname(name)) != NULL )
3490 retval = WS_dup_pe(proto);
3493 MESSAGE("protocol %s not found; You might want to add "
3494 "this to /etc/protocols\n", debugstr_a(name) );
3495 SetLastError(WSANO_DATA);
3497 LeaveCriticalSection( &csWSgetXXXbyYYY );
3499 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3504 /***********************************************************************
3505 * getprotobynumber (WS2_32.54)
3507 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3509 struct WS_protoent* retval = NULL;
3510 #ifdef HAVE_GETPROTOBYNUMBER
3511 struct protoent* proto;
3512 EnterCriticalSection( &csWSgetXXXbyYYY );
3513 if( (proto = getprotobynumber(number)) != NULL )
3515 retval = WS_dup_pe(proto);
3518 MESSAGE("protocol number %d not found; You might want to add "
3519 "this to /etc/protocols\n", number );
3520 SetLastError(WSANO_DATA);
3522 LeaveCriticalSection( &csWSgetXXXbyYYY );
3524 TRACE("%i ret %p\n", number, retval);
3529 /***********************************************************************
3530 * getservbyname (WS2_32.55)
3532 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3534 struct WS_servent* retval = NULL;
3535 struct servent* serv;
3537 char *proto_str = NULL;
3539 if (!(name_str = strdup_lower(name))) return NULL;
3541 if (proto && *proto)
3543 if (!(proto_str = strdup_lower(proto)))
3545 HeapFree( GetProcessHeap(), 0, name_str );
3550 EnterCriticalSection( &csWSgetXXXbyYYY );
3551 serv = getservbyname(name_str, proto_str);
3554 retval = WS_dup_se(serv);
3556 else SetLastError(WSANO_DATA);
3557 LeaveCriticalSection( &csWSgetXXXbyYYY );
3558 HeapFree( GetProcessHeap(), 0, proto_str );
3559 HeapFree( GetProcessHeap(), 0, name_str );
3560 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
3564 /***********************************************************************
3565 * freeaddrinfo (WS2_32.@)
3567 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
3570 struct WS_addrinfo *next;
3572 HeapFree(GetProcessHeap(),0,res->ai_canonname);
3573 HeapFree(GetProcessHeap(),0,res->ai_addr);
3574 next = res->ai_next;
3575 HeapFree(GetProcessHeap(),0,res);
3580 /* helper functions for getaddrinfo()/getnameinfo() */
3581 static int convert_aiflag_w2u(int winflags) {
3585 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3586 if (ws_aiflag_map[i][0] & winflags) {
3587 unixflags |= ws_aiflag_map[i][1];
3588 winflags &= ~ws_aiflag_map[i][0];
3591 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
3595 static int convert_niflag_w2u(int winflags) {
3599 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
3600 if (ws_niflag_map[i][0] & winflags) {
3601 unixflags |= ws_niflag_map[i][1];
3602 winflags &= ~ws_niflag_map[i][0];
3605 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
3609 static int convert_aiflag_u2w(int unixflags) {
3613 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3614 if (ws_aiflag_map[i][1] & unixflags) {
3615 winflags |= ws_aiflag_map[i][0];
3616 unixflags &= ~ws_aiflag_map[i][1];
3618 if (unixflags) /* will warn usually */
3619 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
3623 static int convert_eai_u2w(int unixret) {
3626 for (i=0;ws_eai_map[i][0];i++)
3627 if (ws_eai_map[i][1] == unixret)
3628 return ws_eai_map[i][0];
3632 /***********************************************************************
3633 * getaddrinfo (WS2_32.@)
3635 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
3637 #ifdef HAVE_GETADDRINFO
3638 struct addrinfo *unixaires = NULL;
3640 struct addrinfo unixhints, *punixhints = NULL;
3641 CHAR *node = NULL, *serv = NULL;
3644 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
3647 if (!(serv = strdup_lower(servname))) {
3648 HeapFree(GetProcessHeap(), 0, node);
3649 return WSA_NOT_ENOUGH_MEMORY;
3654 punixhints = &unixhints;
3656 memset(&unixhints, 0, sizeof(unixhints));
3657 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
3658 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
3659 punixhints->ai_family = 0;
3661 punixhints->ai_family = convert_af_w2u(hints->ai_family);
3662 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
3663 punixhints->ai_socktype = 0;
3665 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
3666 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
3667 punixhints->ai_protocol = 0;
3669 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
3672 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
3673 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
3675 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
3677 HeapFree(GetProcessHeap(), 0, node);
3678 HeapFree(GetProcessHeap(), 0, serv);
3681 struct addrinfo *xuai = unixaires;
3682 struct WS_addrinfo **xai = res;
3686 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
3692 *xai = ai;xai = &ai->ai_next;
3693 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
3694 ai->ai_family = convert_af_u2w(xuai->ai_family);
3695 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
3696 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
3697 if (xuai->ai_canonname) {
3698 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
3699 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
3700 if (!ai->ai_canonname)
3702 strcpy(ai->ai_canonname,xuai->ai_canonname);
3704 len = xuai->ai_addrlen;
3705 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
3708 ai->ai_addrlen = len;
3710 int winlen = ai->ai_addrlen;
3712 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
3713 ai->ai_addrlen = winlen;
3717 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
3720 ai->ai_addrlen = len;
3722 xuai = xuai->ai_next;
3724 freeaddrinfo(unixaires);
3726 result = convert_eai_u2w(result);
3732 if (*res) WS_freeaddrinfo(*res);
3733 if (unixaires) freeaddrinfo(unixaires);
3735 return WSA_NOT_ENOUGH_MEMORY;
3737 FIXME("getaddrinfo() failed, not found during buildtime.\n");
3742 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
3744 struct WS_addrinfoW *ret;
3746 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
3747 ret->ai_flags = ai->ai_flags;
3748 ret->ai_family = ai->ai_family;
3749 ret->ai_socktype = ai->ai_socktype;
3750 ret->ai_protocol = ai->ai_protocol;
3751 ret->ai_addrlen = ai->ai_addrlen;
3752 ret->ai_canonname = NULL;
3753 ret->ai_addr = NULL;
3754 ret->ai_next = NULL;
3755 if (ai->ai_canonname)
3757 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
3758 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
3760 HeapFree(GetProcessHeap(), 0, ret);
3763 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
3767 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
3769 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
3770 HeapFree(GetProcessHeap(), 0, ret);
3773 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
3778 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
3780 struct WS_addrinfoW *ret, *infoW;
3782 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
3783 while (info->ai_next)
3785 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
3790 infoW = infoW->ai_next;
3791 info = info->ai_next;
3796 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
3798 struct WS_addrinfo *ret;
3800 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
3801 ret->ai_flags = ai->ai_flags;
3802 ret->ai_family = ai->ai_family;
3803 ret->ai_socktype = ai->ai_socktype;
3804 ret->ai_protocol = ai->ai_protocol;
3805 ret->ai_addrlen = ai->ai_addrlen;
3806 ret->ai_canonname = NULL;
3807 ret->ai_addr = NULL;
3808 ret->ai_next = NULL;
3809 if (ai->ai_canonname)
3811 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
3812 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
3814 HeapFree(GetProcessHeap(), 0, ret);
3817 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
3821 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
3823 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
3824 HeapFree(GetProcessHeap(), 0, ret);
3827 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
3832 /***********************************************************************
3833 * GetAddrInfoW (WS2_32.@)
3835 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
3838 char *nodenameA, *servnameA = NULL;
3839 struct WS_addrinfo *resA, *hintsA = NULL;
3841 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
3842 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
3843 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
3847 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
3848 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
3850 HeapFree(GetProcessHeap(), 0, nodenameA);
3853 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
3856 if (hints) hintsA = addrinfo_WtoA(hints);
3857 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
3858 WS_freeaddrinfo(hintsA);
3862 *res = addrinfo_list_AtoW(resA);
3863 WS_freeaddrinfo(resA);
3866 HeapFree(GetProcessHeap(), 0, nodenameA);
3867 HeapFree(GetProcessHeap(), 0, servnameA);
3871 /***********************************************************************
3872 * FreeAddrInfoW (WS2_32.@)
3874 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
3879 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
3880 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
3882 HeapFree(GetProcessHeap(), 0, ai);
3887 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
3888 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
3890 #ifdef HAVE_GETNAMEINFO
3892 union generic_unix_sockaddr sa_u;
3895 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
3896 serv, servlen, flags);
3898 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
3901 WSASetLastError(WSAEFAULT);
3902 return WSA_NOT_ENOUGH_MEMORY;
3904 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
3905 return convert_eai_u2w(ret);
3907 FIXME("getnameinfo() failed, not found during buildtime.\n");
3912 /***********************************************************************
3913 * getservbyport (WS2_32.56)
3915 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
3917 struct WS_servent* retval = NULL;
3918 #ifdef HAVE_GETSERVBYPORT
3919 struct servent* serv;
3920 char *proto_str = NULL;
3922 if (proto && *proto)
3924 if (!(proto_str = strdup_lower(proto))) return NULL;
3926 EnterCriticalSection( &csWSgetXXXbyYYY );
3927 if( (serv = getservbyport(port, proto_str)) != NULL ) {
3928 retval = WS_dup_se(serv);
3930 else SetLastError(WSANO_DATA);
3931 LeaveCriticalSection( &csWSgetXXXbyYYY );
3932 HeapFree( GetProcessHeap(), 0, proto_str );
3934 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
3939 /***********************************************************************
3940 * gethostname (WS2_32.57)
3942 int WINAPI WS_gethostname(char *name, int namelen)
3944 TRACE("name %p, len %d\n", name, namelen);
3946 if (gethostname(name, namelen) == 0)
3948 TRACE("<- '%s'\n", name);
3951 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
3952 TRACE("<- ERROR !\n");
3953 return SOCKET_ERROR;
3957 /* ------------------------------------- Windows sockets extensions -- *
3959 * ------------------------------------------------------------------- */
3961 /***********************************************************************
3962 * WSAEnumNetworkEvents (WS2_32.36)
3964 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
3968 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
3970 SERVER_START_REQ( get_socket_event )
3972 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
3973 req->service = TRUE;
3974 req->c_event = wine_server_obj_handle( hEvent );
3975 wine_server_set_reply( req, lpEvent->iErrorCode, sizeof(lpEvent->iErrorCode) );
3976 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
3980 SetLastError(WSAEINVAL);
3981 return SOCKET_ERROR;
3984 /***********************************************************************
3985 * WSAEventSelect (WS2_32.39)
3987 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
3991 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
3993 SERVER_START_REQ( set_socket_event )
3995 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
3997 req->event = wine_server_obj_handle( hEvent );
4000 ret = wine_server_call( req );
4004 SetLastError(WSAEINVAL);
4005 return SOCKET_ERROR;
4008 /**********************************************************************
4009 * WSAGetOverlappedResult (WS2_32.40)
4011 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
4012 LPDWORD lpcbTransfer, BOOL fWait,
4017 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
4018 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
4020 if ( lpOverlapped == NULL )
4022 ERR( "Invalid pointer\n" );
4023 WSASetLastError(WSA_INVALID_PARAMETER);
4027 status = lpOverlapped->Internal;
4028 if (status == STATUS_PENDING)
4032 SetLastError( WSA_IO_INCOMPLETE );
4036 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
4037 INFINITE ) == WAIT_FAILED)
4039 status = lpOverlapped->Internal;
4043 *lpcbTransfer = lpOverlapped->InternalHigh;
4046 *lpdwFlags = lpOverlapped->u.s.Offset;
4048 if (status) SetLastError( RtlNtStatusToDosError(status) );
4053 /***********************************************************************
4054 * WSAAsyncSelect (WS2_32.101)
4056 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
4060 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
4062 SERVER_START_REQ( set_socket_event )
4064 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4067 req->window = wine_server_user_handle( hWnd );
4069 ret = wine_server_call( req );
4073 SetLastError(WSAEINVAL);
4074 return SOCKET_ERROR;
4077 /***********************************************************************
4078 * WSACreateEvent (WS2_32.31)
4081 WSAEVENT WINAPI WSACreateEvent(void)
4083 /* Create a manual-reset event, with initial state: unsignaled */
4086 return CreateEventW(NULL, TRUE, FALSE, NULL);
4089 /***********************************************************************
4090 * WSACloseEvent (WS2_32.29)
4093 BOOL WINAPI WSACloseEvent(WSAEVENT event)
4095 TRACE ("event=%p\n", event);
4097 return CloseHandle(event);
4100 /***********************************************************************
4101 * WSASocketA (WS2_32.78)
4104 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
4105 LPWSAPROTOCOL_INFOA lpProtocolInfo,
4106 GROUP g, DWORD dwFlags)
4109 WSAPROTOCOL_INFOW info;
4111 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
4112 af, type, protocol, lpProtocolInfo, g, dwFlags);
4114 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
4116 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
4117 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
4118 info.szProtocol, WSAPROTOCOL_LEN + 1);
4122 WSASetLastError( WSAEINVAL);
4123 return SOCKET_ERROR;
4126 return WSASocketW(af, type, protocol, &info, g, dwFlags);
4129 /***********************************************************************
4130 * WSASocketW (WS2_32.79)
4133 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
4134 LPWSAPROTOCOL_INFOW lpProtocolInfo,
4135 GROUP g, DWORD dwFlags)
4140 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
4141 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
4144 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
4145 af, type, protocol, lpProtocolInfo, g, dwFlags );
4147 /* hack for WSADuplicateSocket */
4148 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
4149 ret = lpProtocolInfo->dwCatalogEntryId;
4150 TRACE("\tgot duplicate %04lx\n", ret);
4154 /* convert the socket family and type */
4155 af = convert_af_w2u(af);
4156 type = convert_socktype_w2u(type);
4160 if (af == FROM_PROTOCOL_INFO)
4161 af = lpProtocolInfo->iAddressFamily;
4162 if (type == FROM_PROTOCOL_INFO)
4163 type = lpProtocolInfo->iSocketType;
4164 if (protocol == FROM_PROTOCOL_INFO)
4165 protocol = lpProtocolInfo->iProtocol;
4168 if ( af == AF_UNSPEC) /* did they not specify the address family? */
4172 if (type == SOCK_STREAM) { af = AF_INET; break; }
4174 if (type == SOCK_DGRAM) { af = AF_INET; break; }
4175 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
4178 SERVER_START_REQ( create_socket )
4182 req->protocol = protocol;
4183 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
4184 req->attributes = OBJ_INHERIT;
4185 req->flags = dwFlags;
4186 set_error( wine_server_call( req ) );
4187 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
4192 TRACE("\tcreated %04lx\n", ret );
4196 if (GetLastError() == WSAEACCES) /* raw socket denied */
4198 if (type == SOCK_RAW)
4199 MESSAGE("WARNING: Trying to create a socket of type SOCK_RAW, this"
4200 " will fail unless you have special permissions.\n");
4202 MESSAGE("WS_SOCKET: Failed to create socket, this requires"
4203 " special permissions.\n");
4204 SetLastError(WSAESOCKTNOSUPPORT);
4207 WARN("\t\tfailed!\n");
4208 return INVALID_SOCKET;
4211 /***********************************************************************
4212 * WSAJoinLeaf (WS2_32.58)
4215 SOCKET WINAPI WSAJoinLeaf(
4217 const struct WS_sockaddr *addr,
4219 LPWSABUF lpCallerData,
4220 LPWSABUF lpCalleeData,
4226 return INVALID_SOCKET;
4229 /***********************************************************************
4230 * __WSAFDIsSet (WS2_32.151)
4232 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
4234 int i = set->fd_count;
4236 TRACE("(%ld,%p(%i))\n", s, set, i);
4239 if (set->fd_array[i] == s) return 1;
4243 /***********************************************************************
4244 * WSAIsBlocking (WINSOCK.114)
4245 * WSAIsBlocking (WS2_32.114)
4247 BOOL WINAPI WSAIsBlocking(void)
4249 /* By default WinSock should set all its sockets to non-blocking mode
4250 * and poll in PeekMessage loop when processing "blocking" ones. This
4251 * function is supposed to tell if the program is in this loop. Our
4252 * blocking calls are truly blocking so we always return FALSE.
4254 * Note: It is allowed to call this function without prior WSAStartup().
4261 /***********************************************************************
4262 * WSACancelBlockingCall (WINSOCK.113)
4263 * WSACancelBlockingCall (WS2_32.113)
4265 INT WINAPI WSACancelBlockingCall(void)
4271 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
4273 FIXME("How was this called?\n");
4278 /***********************************************************************
4279 * WSASetBlockingHook (WS2_32.109)
4281 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
4283 FARPROC prev = blocking_hook;
4284 blocking_hook = lpBlockFunc;
4285 TRACE("hook %p\n", lpBlockFunc);
4290 /***********************************************************************
4291 * WSAUnhookBlockingHook (WS2_32.110)
4293 INT WINAPI WSAUnhookBlockingHook(void)
4295 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
4300 /* ----------------------------------- end of API stuff */
4302 /* ----------------------------------- helper functions -
4304 * TODO: Merge WS_dup_..() stuff into one function that
4305 * would operate with a generic structure containing internal
4306 * pointers (via a template of some kind).
4309 static int list_size(char** l, int item_size)
4314 j += (item_size) ? item_size : strlen(l[i]) + 1;
4315 j += (i + 1) * sizeof(char*); }
4319 static int list_dup(char** l_src, char** l_to, int item_size)
4324 for (i = 0; l_src[i]; i++) ;
4325 p = (char *)(l_to + i + 1);
4326 for (i = 0; l_src[i]; i++)
4328 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
4329 memcpy(p, l_src[i], count);
4334 return p - (char *)l_to;
4339 /* duplicate hostent entry
4340 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
4341 * Ditto for protoent and servent.
4343 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
4346 struct WS_hostent *p_to;
4348 int size = (sizeof(*p_he) +
4349 strlen(p_he->h_name) + 1 +
4350 list_size(p_he->h_aliases, 0) +
4351 list_size(p_he->h_addr_list, p_he->h_length));
4353 if (!(p_to = check_buffer_he(size))) return NULL;
4354 p_to->h_addrtype = p_he->h_addrtype;
4355 p_to->h_length = p_he->h_length;
4357 p = (char *)(p_to + 1);
4359 strcpy(p, p_he->h_name);
4362 p_to->h_aliases = (char **)p;
4363 p += list_dup(p_he->h_aliases, p_to->h_aliases, 0);
4365 p_to->h_addr_list = (char **)p;
4366 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
4370 /* ----- protoent */
4372 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
4375 struct WS_protoent *p_to;
4377 int size = (sizeof(*p_pe) +
4378 strlen(p_pe->p_name) + 1 +
4379 list_size(p_pe->p_aliases, 0));
4381 if (!(p_to = check_buffer_pe(size))) return NULL;
4382 p_to->p_proto = p_pe->p_proto;
4384 p = (char *)(p_to + 1);
4386 strcpy(p, p_pe->p_name);
4389 p_to->p_aliases = (char **)p;
4390 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
4396 static struct WS_servent *WS_dup_se(const struct servent* p_se)
4399 struct WS_servent *p_to;
4401 int size = (sizeof(*p_se) +
4402 strlen(p_se->s_proto) + 1 +
4403 strlen(p_se->s_name) + 1 +
4404 list_size(p_se->s_aliases, 0));
4406 if (!(p_to = check_buffer_se(size))) return NULL;
4407 p_to->s_port = p_se->s_port;
4409 p = (char *)(p_to + 1);
4411 strcpy(p, p_se->s_name);
4415 strcpy(p, p_se->s_proto);
4418 p_to->s_aliases = (char **)p;
4419 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
4423 /* ----------------------------------- error handling */
4427 int loc_errno = errno;
4428 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
4432 case EINTR: return WSAEINTR;
4433 case EBADF: return WSAEBADF;
4435 case EACCES: return WSAEACCES;
4436 case EFAULT: return WSAEFAULT;
4437 case EINVAL: return WSAEINVAL;
4438 case EMFILE: return WSAEMFILE;
4439 case EWOULDBLOCK: return WSAEWOULDBLOCK;
4440 case EINPROGRESS: return WSAEINPROGRESS;
4441 case EALREADY: return WSAEALREADY;
4442 case ENOTSOCK: return WSAENOTSOCK;
4443 case EDESTADDRREQ: return WSAEDESTADDRREQ;
4444 case EMSGSIZE: return WSAEMSGSIZE;
4445 case EPROTOTYPE: return WSAEPROTOTYPE;
4446 case ENOPROTOOPT: return WSAENOPROTOOPT;
4447 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
4448 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
4449 case EOPNOTSUPP: return WSAEOPNOTSUPP;
4450 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
4451 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
4452 case EADDRINUSE: return WSAEADDRINUSE;
4453 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
4454 case ENETDOWN: return WSAENETDOWN;
4455 case ENETUNREACH: return WSAENETUNREACH;
4456 case ENETRESET: return WSAENETRESET;
4457 case ECONNABORTED: return WSAECONNABORTED;
4459 case ECONNRESET: return WSAECONNRESET;
4460 case ENOBUFS: return WSAENOBUFS;
4461 case EISCONN: return WSAEISCONN;
4462 case ENOTCONN: return WSAENOTCONN;
4463 case ESHUTDOWN: return WSAESHUTDOWN;
4464 case ETOOMANYREFS: return WSAETOOMANYREFS;
4465 case ETIMEDOUT: return WSAETIMEDOUT;
4466 case ECONNREFUSED: return WSAECONNREFUSED;
4467 case ELOOP: return WSAELOOP;
4468 case ENAMETOOLONG: return WSAENAMETOOLONG;
4469 case EHOSTDOWN: return WSAEHOSTDOWN;
4470 case EHOSTUNREACH: return WSAEHOSTUNREACH;
4471 case ENOTEMPTY: return WSAENOTEMPTY;
4473 case EPROCLIM: return WSAEPROCLIM;
4476 case EUSERS: return WSAEUSERS;
4479 case EDQUOT: return WSAEDQUOT;
4482 case ESTALE: return WSAESTALE;
4485 case EREMOTE: return WSAEREMOTE;
4488 /* just in case we ever get here and there are no problems */
4491 WARN("Unknown errno %d!\n", loc_errno);
4492 return WSAEOPNOTSUPP;
4496 UINT wsaHerrno(int loc_errno)
4499 WARN("h_errno %d.\n", loc_errno);
4503 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
4504 case TRY_AGAIN: return WSATRY_AGAIN;
4505 case NO_RECOVERY: return WSANO_RECOVERY;
4506 case NO_DATA: return WSANO_DATA;
4507 case ENOBUFS: return WSAENOBUFS;
4511 WARN("Unknown h_errno %d!\n", loc_errno);
4512 return WSAEOPNOTSUPP;
4517 /***********************************************************************
4518 * WSARecv (WS2_32.67)
4520 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4521 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
4522 LPWSAOVERLAPPED lpOverlapped,
4523 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
4525 return WSARecvFrom(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
4526 NULL, NULL, lpOverlapped, lpCompletionRoutine);
4529 /***********************************************************************
4530 * WSARecvFrom (WS2_32.69)
4532 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4533 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
4534 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
4535 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4538 unsigned int i, options;
4540 struct ws2_async *wsa;
4541 DWORD timeout_start = GetTickCount();
4542 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4544 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
4545 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
4546 (lpFromlen ? *lpFromlen : -1),
4547 lpOverlapped, lpCompletionRoutine);
4549 fd = get_sock_fd( s, FILE_READ_DATA, &options );
4550 TRACE( "fd=%d, options=%x\n", fd, options );
4552 if (fd == -1) return SOCKET_ERROR;
4554 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
4560 wsa->hSocket = SOCKET2HANDLE(s);
4561 wsa->flags = *lpFlags;
4563 wsa->addrlen.ptr = lpFromlen;
4564 wsa->n_iovecs = dwBufferCount;
4565 wsa->first_iovec = 0;
4566 for (i = 0; i < dwBufferCount; i++)
4568 /* check buffer first to trigger write watches */
4569 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
4574 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4575 wsa->iovec[i].iov_len = lpBuffers[i].len;
4580 n = WS2_recv( fd, wsa );
4583 if (errno == EINTR) continue;
4584 if (errno != EAGAIN)
4587 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
4592 *lpNumberOfBytesRecvd = n;
4594 if ((lpOverlapped || lpCompletionRoutine) &&
4595 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4597 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4599 wsa->user_overlapped = lpOverlapped;
4600 wsa->completion_func = lpCompletionRoutine;
4601 release_sock_fd( s, fd );
4605 iosb->u.Status = STATUS_PENDING;
4606 iosb->Information = 0;
4608 SERVER_START_REQ( register_async )
4610 req->type = ASYNC_TYPE_READ;
4611 req->async.handle = wine_server_obj_handle( wsa->hSocket );
4612 req->async.callback = wine_server_client_ptr( WS2_async_recv );
4613 req->async.iosb = wine_server_client_ptr( iosb );
4614 req->async.arg = wine_server_client_ptr( wsa );
4615 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
4616 req->async.cvalue = cvalue;
4617 err = wine_server_call( req );
4621 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4622 WSASetLastError( NtStatusToWSAError( err ));
4623 return SOCKET_ERROR;
4626 iosb->u.Status = STATUS_SUCCESS;
4627 iosb->Information = n;
4628 if (!wsa->completion_func)
4630 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4631 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
4632 HeapFree( GetProcessHeap(), 0, wsa );
4634 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4635 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4636 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4642 if ( _is_blocking(s) )
4645 int timeout = GET_RCVTIMEO(fd);
4648 timeout -= GetTickCount() - timeout_start;
4649 if (timeout < 0) timeout = 0;
4653 pfd.events = POLLIN;
4654 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
4656 if (!timeout || !poll( &pfd, 1, timeout ))
4659 /* a timeout is not fatal */
4660 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4666 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4667 err = WSAEWOULDBLOCK;
4672 TRACE(" -> %i bytes\n", n);
4673 HeapFree( GetProcessHeap(), 0, wsa );
4674 release_sock_fd( s, fd );
4675 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4680 HeapFree( GetProcessHeap(), 0, wsa );
4681 release_sock_fd( s, fd );
4682 WARN(" -> ERROR %d\n", err);
4683 WSASetLastError( err );
4684 return SOCKET_ERROR;
4687 /***********************************************************************
4688 * WSCInstallProvider (WS2_32.88)
4690 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
4691 LPCWSTR lpszProviderDllPath,
4692 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
4693 DWORD dwNumberOfEntries,
4696 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
4697 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
4698 dwNumberOfEntries, lpErrno);
4704 /***********************************************************************
4705 * WSCDeinstallProvider (WS2_32.83)
4707 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
4709 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
4715 /***********************************************************************
4716 * WSAAccept (WS2_32.26)
4718 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
4719 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
4722 int ret = 0, size = 0;
4723 WSABUF CallerId, CallerData, CalleeId, CalleeData;
4724 /* QOS SQOS, GQOS; */
4727 SOCKADDR src_addr, dst_addr;
4729 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %d\n",
4730 s, addr, addrlen, lpfnCondition, dwCallbackData);
4733 size = sizeof(src_addr);
4734 cs = WS_accept(s, &src_addr, &size);
4736 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
4738 if (!lpfnCondition) return cs;
4740 CallerId.buf = (char *)&src_addr;
4741 CallerId.len = sizeof(src_addr);
4743 CallerData.buf = NULL;
4746 WS_getsockname(cs, &dst_addr, &size);
4748 CalleeId.buf = (char *)&dst_addr;
4749 CalleeId.len = sizeof(dst_addr);
4752 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
4753 &CalleeId, &CalleeData, &g, dwCallbackData);
4758 if (addr && addrlen)
4759 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
4762 SERVER_START_REQ( set_socket_deferred )
4764 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4765 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
4766 if ( !wine_server_call_err ( req ) )
4768 SetLastError( WSATRY_AGAIN );
4769 WS_closesocket( cs );
4773 return SOCKET_ERROR;
4776 SetLastError(WSAECONNREFUSED);
4777 return SOCKET_ERROR;
4779 FIXME("Unknown return type from Condition function\n");
4780 SetLastError(WSAENOTSOCK);
4781 return SOCKET_ERROR;
4785 /***********************************************************************
4786 * WSADuplicateSocketA (WS2_32.32)
4788 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
4792 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4793 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4794 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
4795 /* I don't know what the real Windoze does next, this is a hack */
4796 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
4797 * the target use the global duplicate, or we could copy a reference to us to the structure
4798 * and let the target duplicate it from us, but let's do it as simple as possible */
4799 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4800 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4801 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4802 0, FALSE, DUPLICATE_SAME_ACCESS);
4803 CloseHandle(hProcess);
4804 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4808 /***********************************************************************
4809 * WSADuplicateSocketW (WS2_32.33)
4811 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
4815 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4817 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4818 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4819 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4820 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4821 0, FALSE, DUPLICATE_SAME_ACCESS);
4822 CloseHandle(hProcess);
4823 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4827 /***********************************************************************
4828 * WSAInstallServiceClassA (WS2_32.48)
4830 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
4832 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
4833 WSASetLastError(WSAEACCES);
4834 return SOCKET_ERROR;
4837 /***********************************************************************
4838 * WSAInstallServiceClassW (WS2_32.49)
4840 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
4842 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
4843 WSASetLastError(WSAEACCES);
4844 return SOCKET_ERROR;
4847 /***********************************************************************
4848 * WSARemoveServiceClass (WS2_32.70)
4850 int WINAPI WSARemoveServiceClass(LPGUID info)
4852 FIXME("Request to remove service %p\n",info);
4853 WSASetLastError(WSATYPE_NOT_FOUND);
4854 return SOCKET_ERROR;
4857 /***********************************************************************
4858 * inet_ntop (WS2_32.@)
4860 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
4862 #ifdef HAVE_INET_NTOP
4863 struct WS_in6_addr *in6;
4864 struct WS_in_addr *in;
4867 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
4870 WSASetLastError( STATUS_INVALID_PARAMETER );
4879 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
4885 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
4889 WSASetLastError( WSAEAFNOSUPPORT );
4893 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
4896 FIXME( "not supported on this platform\n" );
4897 WSASetLastError( WSAEAFNOSUPPORT );
4902 /***********************************************************************
4903 * WSAStringToAddressA (WS2_32.80)
4905 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
4907 LPWSAPROTOCOL_INFOA lpProtocolInfo,
4908 LPSOCKADDR lpAddress,
4909 LPINT lpAddressLength)
4912 LPSTR workBuffer=NULL,ptrPort;
4914 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
4915 lpProtocolInfo, lpAddress, lpAddressLength );
4917 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
4921 WSASetLastError(WSAEINVAL);
4922 return SOCKET_ERROR;
4926 FIXME("ProtocolInfo not implemented.\n");
4928 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
4929 strlen(AddressString) + 1);
4932 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4933 return SOCKET_ERROR;
4936 strcpy(workBuffer, AddressString);
4938 switch(AddressFamily)
4942 struct in_addr inetaddr;
4944 /* If lpAddressLength is too small, tell caller the size we need */
4945 if (*lpAddressLength < sizeof(SOCKADDR_IN))
4947 *lpAddressLength = sizeof(SOCKADDR_IN);
4951 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
4953 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
4955 ptrPort = strchr(workBuffer, ':');
4958 ((LPSOCKADDR_IN)lpAddress)->sin_port = (WS_u_short)atoi(ptrPort+1);
4963 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
4966 if(inet_aton(workBuffer, &inetaddr) > 0)
4968 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
4979 struct in6_addr inetaddr;
4980 /* If lpAddressLength is too small, tell caller the size we need */
4981 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
4983 *lpAddressLength = sizeof(SOCKADDR_IN6);
4987 #ifdef HAVE_INET_PTON
4988 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
4990 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
4992 /* This one is a bit tricky. An IPv6 address contains colons, so the
4993 * check from IPv4 doesn't work like that. However, IPv6 addresses that
4994 * contain a port are written with braces like [fd12:3456:7890::1]:12345
4995 * so what we will do is to look for ']', check if the next char is a
4996 * colon, and if it is, parse the port as in IPv4. */
4998 ptrPort = strchr(workBuffer, ']');
4999 if(ptrPort && *(++ptrPort) == ':')
5001 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = (WS_u_short)atoi(ptrPort+1);
5006 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
5009 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
5011 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
5012 sizeof(struct in6_addr));
5016 #endif /* HAVE_INET_PTON */
5022 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
5023 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
5027 HeapFree(GetProcessHeap(), 0, workBuffer);
5030 WSASetLastError(res);
5031 return SOCKET_ERROR;
5034 /***********************************************************************
5035 * WSAStringToAddressW (WS2_32.81)
5037 * Does anybody know if this functions allows to use hebrew/arabic/chinese... digits?
5038 * If this should be the case, it would be required to map these digits
5039 * to Unicode digits (0-9) using FoldString first.
5041 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
5043 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5044 LPSOCKADDR lpAddress,
5045 LPINT lpAddressLength)
5048 LPSTR workBuffer=NULL;
5049 WSAPROTOCOL_INFOA infoA;
5050 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
5052 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
5053 lpAddress, lpAddressLength );
5055 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
5057 /* if ProtocolInfo is available - convert to ANSI variant */
5060 lpProtoInfoA = &infoA;
5061 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
5063 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5064 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
5066 WSASetLastError( WSAEINVAL);
5067 return SOCKET_ERROR;
5073 /* Translate AddressString to ANSI code page - assumes that only
5074 standard digits 0-9 are used with this API call */
5075 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
5076 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
5080 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
5081 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
5082 lpAddress,lpAddressLength);
5083 HeapFree( GetProcessHeap(), 0, workBuffer );
5087 res = WSA_NOT_ENOUGH_MEMORY;
5092 WSASetLastError(res);
5093 return SOCKET_ERROR;
5096 /***********************************************************************
5097 * WSAAddressToStringA (WS2_32.27)
5099 * See WSAAddressToStringW
5101 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
5102 LPWSAPROTOCOL_INFOA info, LPSTR string,
5106 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
5109 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
5111 if (!sockaddr) return SOCKET_ERROR;
5112 if (!string || !lenstr) return SOCKET_ERROR;
5114 switch(sockaddr->sa_family)
5117 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
5118 sprintf( buffer, "%u.%u.%u.%u:%u",
5119 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
5120 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
5121 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
5122 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
5123 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
5125 p = strchr( buffer, ':' );
5126 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
5131 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
5134 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
5135 if ((sockaddr6->sin6_port))
5136 strcpy(buffer, "[");
5137 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
5139 WSASetLastError(WSAEINVAL);
5140 return SOCKET_ERROR;
5142 if ((sockaddr6->sin6_scope_id))
5143 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
5144 if ((sockaddr6->sin6_port))
5145 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
5150 WSASetLastError(WSAEINVAL);
5151 return SOCKET_ERROR;
5154 size = strlen( buffer ) + 1;
5159 WSASetLastError(WSAEFAULT);
5160 return SOCKET_ERROR;
5164 strcpy( string, buffer );
5168 /***********************************************************************
5169 * WSAAddressToStringW (WS2_32.28)
5171 * Convert a sockaddr address into a readable address string.
5174 * sockaddr [I] Pointer to a sockaddr structure.
5175 * len [I] Size of the sockaddr structure.
5176 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
5177 * string [I/O] Pointer to a buffer to receive the address string.
5178 * lenstr [I/O] Size of the receive buffer in WCHARs.
5182 * Failure: SOCKET_ERROR
5185 * The 'info' parameter is ignored.
5187 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
5188 LPWSAPROTOCOL_INFOW info, LPWSTR string,
5193 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
5196 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
5199 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
5201 if (ret) return ret;
5203 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
5208 WSASetLastError(WSAEFAULT);
5209 return SOCKET_ERROR;
5213 lstrcpyW( string, buffer );
5217 /***********************************************************************
5218 * WSAEnumNameSpaceProvidersA (WS2_32.34)
5220 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
5222 FIXME( "(%p %p) Stub!\n", len, buffer );
5226 /***********************************************************************
5227 * WSAEnumNameSpaceProvidersW (WS2_32.35)
5229 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
5231 FIXME( "(%p %p) Stub!\n", len, buffer );
5235 /***********************************************************************
5236 * WSAGetQOSByName (WS2_32.41)
5238 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
5240 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
5244 /***********************************************************************
5245 * WSAGetServiceClassInfoA (WS2_32.42)
5247 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
5248 LPWSASERVICECLASSINFOA info )
5250 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
5252 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5253 return SOCKET_ERROR;
5256 /***********************************************************************
5257 * WSAGetServiceClassInfoW (WS2_32.43)
5259 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
5260 LPWSASERVICECLASSINFOW info )
5262 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
5264 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5265 return SOCKET_ERROR;
5268 /***********************************************************************
5269 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
5271 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
5273 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
5274 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5275 return SOCKET_ERROR;
5278 /***********************************************************************
5279 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
5281 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
5283 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
5284 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5285 return SOCKET_ERROR;
5288 /***********************************************************************
5289 * WSALookupServiceBeginA (WS2_32.59)
5291 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
5292 DWORD dwControlFlags,
5295 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
5297 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5298 return SOCKET_ERROR;
5301 /***********************************************************************
5302 * WSALookupServiceBeginW (WS2_32.60)
5304 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
5305 DWORD dwControlFlags,
5308 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
5310 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5311 return SOCKET_ERROR;
5314 /***********************************************************************
5315 * WSALookupServiceBeginW (WS2_32.61)
5317 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
5319 FIXME("(%p) Stub!\n", lookup );
5323 /***********************************************************************
5324 * WSALookupServiceNextA (WS2_32.62)
5326 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
5328 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
5332 /***********************************************************************
5333 * WSALookupServiceNextW (WS2_32.63)
5335 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
5337 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
5341 /***********************************************************************
5342 * WSANtohl (WS2_32.64)
5344 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
5346 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
5348 if (!lphostlong) return WSAEFAULT;
5350 *lphostlong = ntohl( netlong );
5354 /***********************************************************************
5355 * WSANtohs (WS2_32.65)
5357 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
5359 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
5361 if (!lphostshort) return WSAEFAULT;
5363 *lphostshort = ntohs( netshort );
5367 /***********************************************************************
5368 * WSAProviderConfigChange (WS2_32.66)
5370 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
5371 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
5373 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
5374 return SOCKET_ERROR;
5377 /***********************************************************************
5378 * WSARecvDisconnect (WS2_32.68)
5380 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
5382 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
5384 return WS_shutdown( s, 0 );
5387 /***********************************************************************
5388 * WSASetServiceA (WS2_32.76)
5390 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
5392 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5396 /***********************************************************************
5397 * WSASetServiceW (WS2_32.77)
5399 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
5401 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5405 /***********************************************************************
5406 * WSCEnableNSProvider (WS2_32.84)
5408 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
5410 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
5414 /***********************************************************************
5415 * WSCGetProviderPath (WS2_32.86)
5417 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
5419 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
5421 if (!errcode || !provider || !len) return WSAEFAULT;
5423 *errcode = WSAEINVAL;
5424 return SOCKET_ERROR;
5427 /***********************************************************************
5428 * WSCInstallNameSpace (WS2_32.87)
5430 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
5431 DWORD version, LPGUID provider )
5433 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
5434 namespace, version, debugstr_guid(provider) );
5438 /***********************************************************************
5439 * WSCUnInstallNameSpace (WS2_32.89)
5441 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
5443 FIXME("(%p) Stub!\n", lpProviderId);
5447 /***********************************************************************
5448 * WSCWriteProviderOrder (WS2_32.91)
5450 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
5452 FIXME("(%p 0x%08x) Stub!\n", entry, number);