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>
116 #ifdef HAVE_SYS_POLL_H
117 # include <sys/poll.h>
119 #ifdef HAVE_SYS_TIME_H
120 # include <sys/time.h>
123 #define NONAMELESSUNION
124 #define NONAMELESSSTRUCT
125 #include "ntstatus.h"
126 #define WIN32_NO_STATUS
131 #include "winerror.h"
133 #include "winsock2.h"
135 #include "ws2tcpip.h"
140 #include "iphlpapi.h"
141 #include "wine/server.h"
142 #include "wine/debug.h"
143 #include "wine/unicode.h"
146 # include "wsnwlink.h"
150 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
151 # define sipx_network sipx_addr.x_net
152 # define sipx_node sipx_addr.x_host.c_host
153 #endif /* __FreeBSD__ */
156 #define INADDR_NONE ~0UL
159 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
161 /* critical section to protect some non-reentrant net function */
162 extern CRITICAL_SECTION csWSgetXXXbyYYY;
164 union generic_unix_sockaddr
166 struct sockaddr addr;
167 char data[128]; /* should be big enough for all families */
170 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
172 if (!a) return "(nil)";
173 return wine_dbg_sprintf("{ family %d, address %s, port %d }",
174 ((const struct sockaddr_in *)a)->sin_family,
175 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
176 ntohs(((const struct sockaddr_in *)a)->sin_port));
179 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
180 #define SOCKET2HANDLE(s) ((HANDLE)(s))
181 #define HANDLE2SOCKET(h) ((SOCKET)(h))
183 /****************************************************************
184 * Async IO declarations
185 ****************************************************************/
187 typedef struct ws2_async
191 LPWSAOVERLAPPED user_overlapped;
192 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
193 IO_STATUS_BLOCK local_iosb;
194 struct WS_sockaddr *addr;
197 int val; /* for send operations */
198 int *ptr; /* for recv operations */
201 unsigned int n_iovecs;
202 unsigned int first_iovec;
203 struct iovec iovec[1];
206 /****************************************************************/
208 /* ----------------------------------- internal data */
210 /* ws_... struct conversion flags */
212 typedef struct /* WSAAsyncSelect() control struct */
214 HANDLE service, event, sock;
220 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
221 #define WS_MAX_UDP_DATAGRAM 1024
222 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
224 /* hostent's, servent's and protent's are stored in one buffer per thread,
225 * as documented on MSDN for the functions that return any of the buffers */
226 struct per_thread_data
229 struct WS_hostent *he_buffer;
230 struct WS_servent *se_buffer;
231 struct WS_protoent *pe_buffer;
237 static INT num_startup; /* reference counter */
238 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
240 /* function prototypes */
241 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
242 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
243 static struct WS_servent *WS_dup_se(const struct servent* p_se);
245 int WSAIOCTL_GetInterfaceCount(void);
246 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
249 UINT wsaHerrno(int errnr);
251 #define MAP_OPTION(opt) { WS_##opt, opt }
253 static const int ws_sock_map[][2] =
255 MAP_OPTION( SO_DEBUG ),
256 MAP_OPTION( SO_ACCEPTCONN ),
257 MAP_OPTION( SO_REUSEADDR ),
258 MAP_OPTION( SO_KEEPALIVE ),
259 MAP_OPTION( SO_DONTROUTE ),
260 MAP_OPTION( SO_BROADCAST ),
261 MAP_OPTION( SO_LINGER ),
262 MAP_OPTION( SO_OOBINLINE ),
263 MAP_OPTION( SO_SNDBUF ),
264 MAP_OPTION( SO_RCVBUF ),
265 MAP_OPTION( SO_ERROR ),
266 MAP_OPTION( SO_TYPE ),
268 MAP_OPTION( SO_RCVTIMEO ),
271 MAP_OPTION( SO_SNDTIMEO ),
275 static const int ws_tcp_map[][2] =
278 MAP_OPTION( TCP_NODELAY ),
282 static const int ws_ip_map[][2] =
284 MAP_OPTION( IP_MULTICAST_IF ),
285 MAP_OPTION( IP_MULTICAST_TTL ),
286 MAP_OPTION( IP_MULTICAST_LOOP ),
287 MAP_OPTION( IP_ADD_MEMBERSHIP ),
288 MAP_OPTION( IP_DROP_MEMBERSHIP ),
289 MAP_OPTION( IP_OPTIONS ),
291 MAP_OPTION( IP_HDRINCL ),
293 MAP_OPTION( IP_TOS ),
294 MAP_OPTION( IP_TTL ),
297 static const int ws_af_map[][2] =
299 MAP_OPTION( AF_UNSPEC ),
300 MAP_OPTION( AF_INET ),
301 MAP_OPTION( AF_INET6 ),
303 MAP_OPTION( AF_IPX ),
305 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
308 static const int ws_socktype_map[][2] =
310 MAP_OPTION( SOCK_DGRAM ),
311 MAP_OPTION( SOCK_STREAM ),
312 MAP_OPTION( SOCK_RAW ),
313 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
316 static const int ws_proto_map[][2] =
318 MAP_OPTION( IPPROTO_IP ),
319 MAP_OPTION( IPPROTO_TCP ),
320 MAP_OPTION( IPPROTO_UDP ),
321 MAP_OPTION( IPPROTO_ICMP ),
322 MAP_OPTION( IPPROTO_IGMP ),
323 MAP_OPTION( IPPROTO_RAW ),
324 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
327 static const int ws_aiflag_map[][2] =
329 MAP_OPTION( AI_PASSIVE ),
330 MAP_OPTION( AI_CANONNAME ),
331 MAP_OPTION( AI_NUMERICHOST ),
332 /* Linux/UNIX knows a lot more. But Windows only
333 * has 3 as far as I could see. -Marcus
337 static const int ws_niflag_map[][2] =
339 MAP_OPTION( NI_NOFQDN ),
340 MAP_OPTION( NI_NUMERICHOST ),
341 MAP_OPTION( NI_NAMEREQD ),
342 MAP_OPTION( NI_NUMERICSERV ),
343 MAP_OPTION( NI_DGRAM ),
346 static const int ws_eai_map[][2] =
348 MAP_OPTION( EAI_AGAIN ),
349 MAP_OPTION( EAI_BADFLAGS ),
350 MAP_OPTION( EAI_FAIL ),
351 MAP_OPTION( EAI_FAMILY ),
352 MAP_OPTION( EAI_MEMORY ),
353 /* Note: EAI_NODATA is deprecated, but still
354 * used by Windows and Linux... We map the newer
355 * EAI_NONAME to EAI_NODATA for now until Windows
359 MAP_OPTION( EAI_NODATA ),
362 { WS_EAI_NODATA, EAI_NONAME },
365 MAP_OPTION( EAI_SERVICE ),
366 MAP_OPTION( EAI_SOCKTYPE ),
370 static const char magic_loopback_addr[] = {127, 12, 34, 56};
372 static inline DWORD NtStatusToWSAError( const DWORD status )
374 /* We only need to cover the status codes set by server async request handling */
378 case STATUS_SUCCESS: wserr = 0; break;
379 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
380 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
381 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
382 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
383 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
384 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
385 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
386 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
388 if ( status >= WSABASEERR && status <= WSABASEERR+1004 )
389 /* It is not an NT status code but a winsock error */
393 wserr = RtlNtStatusToDosError( status );
394 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
400 /* set last error code from NT status without mapping WSA errors */
401 static inline unsigned int set_error( unsigned int err )
405 err = NtStatusToWSAError( err );
411 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
414 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
419 static inline void release_sock_fd( SOCKET s, int fd )
421 wine_server_release_fd( SOCKET2HANDLE(s), fd );
424 static void _enable_event( HANDLE s, unsigned int event,
425 unsigned int sstate, unsigned int cstate )
427 SERVER_START_REQ( enable_socket_event )
429 req->handle = wine_server_obj_handle( s );
431 req->sstate = sstate;
432 req->cstate = cstate;
433 wine_server_call( req );
438 static int _is_blocking(SOCKET s)
441 SERVER_START_REQ( get_socket_event )
443 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
444 req->service = FALSE;
446 wine_server_call( req );
447 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
453 static unsigned int _get_sock_mask(SOCKET s)
456 SERVER_START_REQ( get_socket_event )
458 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
459 req->service = FALSE;
461 wine_server_call( req );
468 static void _sync_sock_state(SOCKET s)
470 /* do a dummy wineserver request in order to let
471 the wineserver run through its select loop once */
472 (void)_is_blocking(s);
475 static int _get_sock_error(SOCKET s, unsigned int bit)
477 int events[FD_MAX_EVENTS];
479 SERVER_START_REQ( get_socket_event )
481 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
482 req->service = FALSE;
484 wine_server_set_reply( req, events, sizeof(events) );
485 wine_server_call( req );
491 static struct per_thread_data *get_per_thread_data(void)
493 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
494 /* lazy initialization */
497 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
498 NtCurrentTeb()->WinSockData = ptb;
503 static void free_per_thread_data(void)
505 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
509 /* delete scratch buffers */
510 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
511 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
512 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
513 ptb->he_buffer = NULL;
514 ptb->se_buffer = NULL;
515 ptb->pe_buffer = NULL;
517 HeapFree( GetProcessHeap(), 0, ptb );
518 NtCurrentTeb()->WinSockData = NULL;
521 /***********************************************************************
522 * DllMain (WS2_32.init)
524 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
526 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
528 case DLL_PROCESS_ATTACH:
530 case DLL_PROCESS_DETACH:
531 free_per_thread_data();
534 case DLL_THREAD_DETACH:
535 free_per_thread_data();
541 /***********************************************************************
544 * Converts socket flags from Windows format.
545 * Return 1 if converted, 0 if not (error).
547 static int convert_sockopt(INT *level, INT *optname)
554 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
555 if( ws_sock_map[i][0] == *optname )
557 *optname = ws_sock_map[i][1];
561 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
564 *level = IPPROTO_TCP;
565 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
566 if ( ws_tcp_map[i][0] == *optname )
568 *optname = ws_tcp_map[i][1];
572 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
576 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
577 if (ws_ip_map[i][0] == *optname )
579 *optname = ws_ip_map[i][1];
583 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
585 default: FIXME("Unimplemented or unknown socket level\n");
590 /* ----------------------------------- Per-thread info (or per-process?) */
592 static char *strdup_lower(const char *str)
595 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
599 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
602 else SetLastError(WSAENOBUFS);
606 static inline int sock_error_p(int s)
608 unsigned int optval, optlen;
610 optlen = sizeof(optval);
611 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
612 if (optval) WARN("\t[%i] error: %d\n", s, optval);
616 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
617 * from an fd and return the value converted to milli seconds
618 * or -1 if there is an infinite time out */
619 static inline int get_rcvsnd_timeo( int fd, int optname)
622 unsigned int len = sizeof(tv);
623 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
625 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
626 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
631 /* macro wrappers for portability */
633 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
635 #define GET_RCVTIMEO(fd) (-1)
639 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
641 #define GET_SNDTIMEO(fd) (-1)
644 /* utility: given an fd, will block until one of the events occurs */
645 static inline int do_block( int fd, int events, int timeout )
653 while ((ret = poll(&pfd, 1, timeout)) < 0)
664 convert_af_w2u(int windowsaf) {
667 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
668 if (ws_af_map[i][0] == windowsaf)
669 return ws_af_map[i][1];
670 FIXME("unhandled Windows address family %d\n", windowsaf);
675 convert_af_u2w(int unixaf) {
678 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
679 if (ws_af_map[i][1] == unixaf)
680 return ws_af_map[i][0];
681 FIXME("unhandled UNIX address family %d\n", unixaf);
686 convert_proto_w2u(int windowsproto) {
689 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
690 if (ws_proto_map[i][0] == windowsproto)
691 return ws_proto_map[i][1];
692 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
697 convert_proto_u2w(int unixproto) {
700 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
701 if (ws_proto_map[i][1] == unixproto)
702 return ws_proto_map[i][0];
703 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
708 convert_socktype_w2u(int windowssocktype) {
711 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
712 if (ws_socktype_map[i][0] == windowssocktype)
713 return ws_socktype_map[i][1];
714 FIXME("unhandled Windows socket type %d\n", windowssocktype);
719 convert_socktype_u2w(int unixsocktype) {
722 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
723 if (ws_socktype_map[i][1] == unixsocktype)
724 return ws_socktype_map[i][0];
725 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
729 /* ----------------------------------- API -----
731 * Init / cleanup / error checking.
734 /***********************************************************************
735 * WSAStartup (WS2_32.115)
737 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
739 TRACE("verReq=%x\n", wVersionRequested);
741 if (LOBYTE(wVersionRequested) < 1)
742 return WSAVERNOTSUPPORTED;
744 if (!lpWSAData) return WSAEINVAL;
748 /* that's the whole of the negotiation for now */
749 lpWSAData->wVersion = wVersionRequested;
750 /* return winsock information */
751 lpWSAData->wHighVersion = 0x0202;
752 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
753 strcpy(lpWSAData->szSystemStatus, "Running" );
754 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
755 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
756 /* don't do anything with lpWSAData->lpVendorInfo */
757 /* (some apps don't allocate the space for this field) */
759 TRACE("succeeded\n");
764 /***********************************************************************
765 * WSACleanup (WS2_32.116)
767 INT WINAPI WSACleanup(void)
773 SetLastError(WSANOTINITIALISED);
778 /***********************************************************************
779 * WSAGetLastError (WINSOCK.111)
780 * WSAGetLastError (WS2_32.111)
782 INT WINAPI WSAGetLastError(void)
784 return GetLastError();
787 /***********************************************************************
788 * WSASetLastError (WS2_32.112)
790 void WINAPI WSASetLastError(INT iError) {
791 SetLastError(iError);
794 static struct WS_hostent *check_buffer_he(int size)
796 struct per_thread_data * ptb = get_per_thread_data();
799 if (ptb->he_len >= size ) return ptb->he_buffer;
800 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
802 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
803 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
804 return ptb->he_buffer;
807 static struct WS_servent *check_buffer_se(int size)
809 struct per_thread_data * ptb = get_per_thread_data();
812 if (ptb->se_len >= size ) return ptb->se_buffer;
813 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
815 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
816 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
817 return ptb->se_buffer;
820 static struct WS_protoent *check_buffer_pe(int size)
822 struct per_thread_data * ptb = get_per_thread_data();
825 if (ptb->pe_len >= size ) return ptb->pe_buffer;
826 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
828 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
829 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
830 return ptb->pe_buffer;
833 /* ----------------------------------- i/o APIs */
836 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf)== WS_AF_IPX || (pf) == WS_AF_INET6)
838 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf) == WS_AF_INET6)
842 /**********************************************************************/
844 /* Returns the length of the converted address if successful, 0 if it was too small to
847 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
848 union generic_unix_sockaddr *uaddr)
850 unsigned int uaddrlen = 0;
852 switch (wsaddr->sa_family)
857 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
858 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
860 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
863 uaddrlen = sizeof(struct sockaddr_ipx);
864 memset( uaddr, 0, uaddrlen );
865 uipx->sipx_family=AF_IPX;
866 uipx->sipx_port=wsipx->sa_socket;
867 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
870 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
871 #ifdef IPX_FRAME_NONE
872 uipx->sipx_type=IPX_FRAME_NONE;
878 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
879 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
881 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
882 * scope_id, one without.
884 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
885 uaddrlen = sizeof(struct sockaddr_in6);
886 memset( uaddr, 0, uaddrlen );
887 uin6->sin6_family = AF_INET6;
888 uin6->sin6_port = win6->sin6_port;
889 uin6->sin6_flowinfo = win6->sin6_flowinfo;
890 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
891 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
893 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
896 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
900 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
901 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
903 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
905 uaddrlen = sizeof(struct sockaddr_in);
906 memset( uaddr, 0, uaddrlen );
907 uin->sin_family = AF_INET;
908 uin->sin_port = win->sin_port;
909 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
913 /* Try to determine the needed space by the passed windows sockaddr space */
915 default: /* likely a ipv4 address */
916 case sizeof(struct WS_sockaddr_in):
917 uaddrlen = sizeof(struct sockaddr_in);
920 case sizeof(struct WS_sockaddr_ipx):
921 uaddrlen = sizeof(struct sockaddr_ipx);
924 case sizeof(struct WS_sockaddr_in6):
925 case sizeof(struct WS_sockaddr_in6_old):
926 uaddrlen = sizeof(struct sockaddr_in6);
929 memset( uaddr, 0, uaddrlen );
933 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
939 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
941 switch (uaddr->sa_family)
945 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
950 static const struct sockaddr_in6 emptyAddr;
951 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
952 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
956 static const struct sockaddr_in emptyAddr;
957 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
958 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
963 FIXME("unknown address family %d\n", uaddr->sa_family);
968 /* Returns 0 if successful, -1 if the buffer is too small */
969 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
973 switch(uaddr->sa_family)
978 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
979 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
982 switch (*wsaddrlen) /* how much can we copy? */
986 *wsaddrlen = sizeof(*wsipx);
987 wsipx->sa_socket=uipx->sipx_port;
991 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
999 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1005 wsipx->sa_family=WS_AF_IPX;
1016 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1017 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1019 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1021 win6old->sin6_family = WS_AF_INET6;
1022 win6old->sin6_port = uin6->sin6_port;
1023 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1024 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1025 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1026 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1027 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1028 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1029 win6->sin6_scope_id = uin6->sin6_scope_id;
1030 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1036 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1037 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1039 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1041 win->sin_family = WS_AF_INET;
1042 win->sin_port = uin->sin_port;
1043 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1044 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1045 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1049 memset(wsaddr,0,*wsaddrlen);
1053 FIXME("Unknown address family %d\n", uaddr->sa_family);
1059 /**************************************************************************
1060 * Functions for handling overlapped I/O
1061 **************************************************************************/
1063 /* user APC called upon async completion */
1064 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1066 ws2_async *wsa = arg;
1068 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1069 iosb->Information, wsa->user_overlapped,
1071 HeapFree( GetProcessHeap(), 0, wsa );
1074 /***********************************************************************
1075 * WS2_recv (INTERNAL)
1077 * Workhorse for both synchronous and asynchronous recv() operations.
1079 static int WS2_recv( int fd, struct ws2_async *wsa )
1082 union generic_unix_sockaddr unix_sockaddr;
1085 hdr.msg_name = NULL;
1089 hdr.msg_namelen = sizeof(unix_sockaddr);
1090 hdr.msg_name = &unix_sockaddr;
1093 hdr.msg_namelen = 0;
1095 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1096 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1097 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1098 hdr.msg_accrights = NULL;
1099 hdr.msg_accrightslen = 0;
1101 hdr.msg_control = NULL;
1102 hdr.msg_controllen = 0;
1106 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1109 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1110 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1112 * quoting linux 2.6 net/ipv4/tcp.c:
1113 * "According to UNIX98, msg_name/msg_namelen are ignored
1114 * on connected socket. I was just happy when found this 8) --ANK"
1116 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1117 * connection-oriented sockets, so don't try to update lpFrom.
1119 if (wsa->addr && hdr.msg_namelen)
1120 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1125 /***********************************************************************
1126 * WS2_async_recv (INTERNAL)
1128 * Handler for overlapped recv() operations.
1130 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1132 ws2_async* wsa = user;
1137 case STATUS_ALERTED:
1138 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1141 result = WS2_recv( fd, wsa );
1142 wine_server_release_fd( wsa->hSocket, fd );
1145 status = STATUS_SUCCESS;
1146 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1150 if (errno == EINTR || errno == EAGAIN)
1152 status = STATUS_PENDING;
1153 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1158 status = wsaErrno(); /* FIXME: is this correct ???? */
1163 if (status != STATUS_PENDING)
1165 iosb->u.Status = status;
1166 iosb->Information = result;
1167 *apc = ws2_async_apc;
1172 /***********************************************************************
1173 * WS2_send (INTERNAL)
1175 * Workhorse for both synchronous and asynchronous send() operations.
1177 static int WS2_send( int fd, struct ws2_async *wsa )
1180 union generic_unix_sockaddr unix_addr;
1182 hdr.msg_name = NULL;
1183 hdr.msg_namelen = 0;
1187 hdr.msg_name = &unix_addr;
1188 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
1189 if ( !hdr.msg_namelen )
1195 #if defined(HAVE_IPX) && defined(SOL_IPX)
1196 if(wsa->addr->sa_family == WS_AF_IPX)
1198 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1200 unsigned int len=sizeof(int);
1202 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1203 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1204 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1205 * ipx type in the sockaddr_opx structure with the stored value.
1207 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1208 uipx->sipx_type = val;
1213 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1214 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1215 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1216 hdr.msg_accrights = NULL;
1217 hdr.msg_accrightslen = 0;
1219 hdr.msg_control = NULL;
1220 hdr.msg_controllen = 0;
1224 return sendmsg(fd, &hdr, wsa->flags);
1227 /***********************************************************************
1228 * WS2_async_send (INTERNAL)
1230 * Handler for overlapped send() operations.
1232 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1234 ws2_async* wsa = user;
1239 case STATUS_ALERTED:
1240 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1243 /* check to see if the data is ready (non-blocking) */
1244 result = WS2_send( fd, wsa );
1245 wine_server_release_fd( wsa->hSocket, fd );
1249 int totalLength = 0;
1251 status = STATUS_SUCCESS;
1252 for (i = 0; i < wsa->n_iovecs; i++)
1253 totalLength += wsa->iovec[i].iov_len;
1254 if (result < totalLength)
1255 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1259 if (errno == EINTR || errno == EAGAIN)
1261 status = STATUS_PENDING;
1262 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1266 /* We set the status to a winsock error code and check for that
1267 later in NtStatusToWSAError () */
1268 status = wsaErrno();
1274 if (status != STATUS_PENDING)
1276 iosb->u.Status = status;
1277 iosb->Information = result;
1278 *apc = ws2_async_apc;
1283 /***********************************************************************
1284 * WS2_async_shutdown (INTERNAL)
1286 * Handler for shutdown() operations on overlapped sockets.
1288 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
1290 ws2_async* wsa = user;
1295 case STATUS_ALERTED:
1296 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1299 switch ( wsa->type )
1301 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1302 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1304 wine_server_release_fd( wsa->hSocket, fd );
1305 status = err ? wsaErrno() : STATUS_SUCCESS;
1308 iosb->u.Status = status;
1309 *apc = ws2_async_apc;
1313 /***********************************************************************
1314 * WS2_register_async_shutdown (INTERNAL)
1316 * Helper function for WS_shutdown() on overlapped sockets.
1318 static int WS2_register_async_shutdown( SOCKET s, int type )
1320 struct ws2_async *wsa;
1323 TRACE("s %ld type %d\n", s, type);
1325 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1329 wsa->hSocket = SOCKET2HANDLE(s);
1331 wsa->completion_func = NULL;
1333 SERVER_START_REQ( register_async )
1336 req->async.handle = wine_server_obj_handle( wsa->hSocket );
1337 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
1338 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
1339 req->async.arg = wine_server_client_ptr( wsa );
1340 req->async.cvalue = 0;
1341 status = wine_server_call( req );
1345 if (status != STATUS_PENDING)
1347 HeapFree( GetProcessHeap(), 0, wsa );
1348 return NtStatusToWSAError( status );
1353 /***********************************************************************
1356 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1362 TRACE("socket %04lx\n", s );
1363 is_blocking = _is_blocking(s);
1368 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1369 if (fd == -1) return INVALID_SOCKET;
1371 do_block(fd, POLLIN, -1);
1372 _sync_sock_state(s); /* let wineserver notice connection */
1373 release_sock_fd( s, fd );
1374 /* retrieve any error codes from it */
1375 SetLastError(_get_sock_error(s, FD_ACCEPT_BIT));
1376 /* FIXME: care about the error? */
1378 SERVER_START_REQ( accept_socket )
1380 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1381 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1382 req->attributes = OBJ_INHERIT;
1383 set_error( wine_server_call( req ) );
1384 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
1389 if (addr) WS_getpeername(as, addr, addrlen32);
1392 } while (is_blocking);
1393 return INVALID_SOCKET;
1396 /***********************************************************************
1399 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1401 int fd = get_sock_fd( s, 0, NULL );
1402 int res = SOCKET_ERROR;
1404 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1408 if (!name || (name->sa_family && !SUPPORTED_PF(name->sa_family)))
1410 SetLastError(WSAEAFNOSUPPORT);
1414 union generic_unix_sockaddr uaddr;
1415 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1418 SetLastError(WSAEFAULT);
1423 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
1424 if (name->sa_family == WS_AF_INET6 &&
1425 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
1428 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
1430 release_sock_fd( s, fd );
1431 SetLastError(WSAEAFNOSUPPORT);
1432 return SOCKET_ERROR;
1436 if (name->sa_family == WS_AF_INET)
1438 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1439 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1441 /* Trying to bind to the default host interface, using
1442 * INADDR_ANY instead*/
1443 WARN("Trying to bind to magic IP address, using "
1444 "INADDR_ANY instead.\n");
1445 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
1448 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
1450 int loc_errno = errno;
1451 WARN("\tfailure - errno = %i\n", errno);
1456 SetLastError(WSAENOTSOCK);
1459 SetLastError(WSAEINVAL);
1462 SetLastError(wsaErrno());
1468 res=0; /* success */
1472 release_sock_fd( s, fd );
1477 /***********************************************************************
1478 * closesocket (WS2_32.3)
1480 int WINAPI WS_closesocket(SOCKET s)
1482 TRACE("socket %04lx\n", s);
1483 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
1484 return SOCKET_ERROR;
1487 /***********************************************************************
1488 * connect (WS2_32.4)
1490 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1492 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1494 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1498 union generic_unix_sockaddr uaddr;
1499 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1503 SetLastError(WSAEFAULT);
1507 if (name->sa_family == WS_AF_INET)
1509 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1510 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1512 /* Trying to connect to magic replace-loopback address,
1513 * assuming we really want to connect to localhost */
1514 TRACE("Trying to connect to magic IP address, using "
1515 "INADDR_LOOPBACK instead.\n");
1516 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
1520 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
1521 goto connect_success;
1524 if (errno == EINPROGRESS)
1526 /* tell wineserver that a connection is in progress */
1527 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1528 FD_CONNECT|FD_READ|FD_WRITE,
1529 FD_WINE_CONNECTED|FD_WINE_LISTENING);
1530 if (_is_blocking(s))
1534 do_block(fd, POLLIN | POLLOUT, -1);
1535 _sync_sock_state(s); /* let wineserver notice connection */
1536 /* retrieve any error codes from it */
1537 result = _get_sock_error(s, FD_CONNECT_BIT);
1539 SetLastError(result);
1542 goto connect_success;
1547 SetLastError(WSAEWOULDBLOCK);
1552 SetLastError(wsaErrno());
1554 release_sock_fd( s, fd );
1556 return SOCKET_ERROR;
1559 release_sock_fd( s, fd );
1560 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1561 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1562 FD_CONNECT|FD_WINE_LISTENING);
1566 /***********************************************************************
1567 * WSAConnect (WS2_32.30)
1569 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
1570 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1571 LPQOS lpSQOS, LPQOS lpGQOS )
1573 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1574 FIXME("unsupported parameters!\n");
1575 return WS_connect( s, name, namelen );
1579 /***********************************************************************
1580 * getpeername (WS2_32.5)
1582 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1587 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, *namelen);
1589 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1590 if( (name == NULL) || (namelen == NULL) )
1592 SetLastError( WSAEFAULT );
1593 return SOCKET_ERROR;
1596 fd = get_sock_fd( s, 0, NULL );
1601 union generic_unix_sockaddr uaddr;
1602 unsigned int uaddrlen = sizeof(uaddr);
1604 if (getpeername(fd, &uaddr.addr, &uaddrlen) != 0)
1606 SetLastError(wsaErrno());
1608 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1610 /* The buffer was too small */
1611 SetLastError(WSAEFAULT);
1617 release_sock_fd( s, fd );
1622 /***********************************************************************
1623 * getsockname (WS2_32.6)
1625 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1630 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
1632 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1633 if( (name == NULL) || (namelen == NULL) )
1635 SetLastError( WSAEFAULT );
1636 return SOCKET_ERROR;
1639 fd = get_sock_fd( s, 0, NULL );
1644 union generic_unix_sockaddr uaddr;
1645 unsigned int uaddrlen = sizeof(uaddr);
1647 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
1649 SetLastError(wsaErrno());
1651 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
1653 SetLastError(WSAEINVAL);
1655 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1657 /* The buffer was too small */
1658 SetLastError(WSAEFAULT);
1664 release_sock_fd( s, fd );
1669 /***********************************************************************
1670 * getsockopt (WS2_32.7)
1672 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1673 INT optname, char *optval, INT *optlen)
1678 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
1679 s, level, optname, optval, *optlen);
1687 /* Handle common cases. The special cases are below, sorted
1689 case WS_SO_ACCEPTCONN:
1690 case WS_SO_BROADCAST:
1693 case WS_SO_KEEPALIVE:
1694 case WS_SO_OOBINLINE:
1696 case WS_SO_REUSEADDR:
1699 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1700 return SOCKET_ERROR;
1701 convert_sockopt(&level, &optname);
1702 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1704 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1707 release_sock_fd( s, fd );
1710 case WS_SO_DONTLINGER:
1712 struct linger lingval;
1713 unsigned int len = sizeof(struct linger);
1715 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
1717 SetLastError(WSAEFAULT);
1718 return SOCKET_ERROR;
1720 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1721 return SOCKET_ERROR;
1723 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1725 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1730 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
1731 *optlen = sizeof(BOOL);
1734 release_sock_fd( s, fd );
1738 /* As mentioned in setsockopt, Windows ignores this, so we
1739 * always return true here */
1740 case WS_SO_DONTROUTE:
1741 if (!optlen || *optlen < sizeof(BOOL) || !optval)
1743 SetLastError(WSAEFAULT);
1744 return SOCKET_ERROR;
1746 *(BOOL *)optval = TRUE;
1747 *optlen = sizeof(BOOL);
1752 struct linger lingval;
1753 unsigned int len = sizeof(struct linger);
1755 /* struct linger and LINGER have different sizes */
1756 if (!optlen || *optlen < sizeof(LINGER) || !optval)
1758 SetLastError(WSAEFAULT);
1759 return SOCKET_ERROR;
1761 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1762 return SOCKET_ERROR;
1764 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1766 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1771 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
1772 ((LINGER *)optval)->l_linger = lingval.l_linger;
1773 *optlen = sizeof(struct linger);
1776 release_sock_fd( s, fd );
1780 case WS_SO_MAX_MSG_SIZE:
1781 if (!optlen || *optlen < sizeof(int) || !optval)
1783 SetLastError(WSAEFAULT);
1784 return SOCKET_ERROR;
1786 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
1787 *(int *)optval = 65507;
1788 *optlen = sizeof(int);
1791 /* SO_OPENTYPE does not require a valid socket handle. */
1792 case WS_SO_OPENTYPE:
1793 if (!optlen || *optlen < sizeof(int) || !optval)
1795 SetLastError(WSAEFAULT);
1796 return SOCKET_ERROR;
1798 *(int *)optval = get_per_thread_data()->opentype;
1799 *optlen = sizeof(int);
1800 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
1804 case WS_SO_RCVTIMEO:
1807 case WS_SO_SNDTIMEO:
1809 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
1812 unsigned int len = sizeof(struct timeval);
1814 if (!optlen || *optlen < sizeof(int)|| !optval)
1816 SetLastError(WSAEFAULT);
1817 return SOCKET_ERROR;
1819 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1820 return SOCKET_ERROR;
1822 convert_sockopt(&level, &optname);
1823 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
1825 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1830 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1831 *optlen = sizeof(int);
1834 release_sock_fd( s, fd );
1839 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
1840 SetLastError(WSAENOPROTOOPT);
1841 return SOCKET_ERROR;
1842 } /* end switch(optname) */
1843 }/* end case WS_SOL_SOCKET */
1847 struct WS_sockaddr_ipx addr;
1848 IPX_ADDRESS_DATA *data;
1853 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
1855 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
1862 socklen_t len=sizeof(struct ipx);
1863 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
1866 *optval = (int)val.ipx_pt;
1869 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
1870 release_sock_fd( s, fd );
1875 * On a Win2000 system with one network card there are usually
1876 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
1877 * Using this call you can then retrieve info about this all.
1878 * In case of Linux it is a bit different. Usually you have
1879 * only "one" device active and further it is not possible to
1880 * query things like the linkspeed.
1882 FIXME("IPX_ADDRESS\n");
1883 namelen = sizeof(struct WS_sockaddr_ipx);
1884 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
1885 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
1887 data = (IPX_ADDRESS_DATA*)optval;
1888 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
1889 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
1890 data->adapternum = 0;
1891 data->wan = FALSE; /* We are not on a wan for now .. */
1892 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
1893 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
1894 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
1895 * note 1MB = 1000kB in this case */
1898 case IPX_MAX_ADAPTER_NUM:
1899 FIXME("IPX_MAX_ADAPTER_NUM\n");
1900 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
1904 FIXME("IPX optname:%x\n", optname);
1905 return SOCKET_ERROR;
1906 }/* end switch(optname) */
1907 } /* end case NSPROTO_IPX */
1909 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
1910 case WS_IPPROTO_TCP:
1913 case WS_TCP_NODELAY:
1914 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1915 return SOCKET_ERROR;
1916 convert_sockopt(&level, &optname);
1917 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1919 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1922 release_sock_fd( s, fd );
1925 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
1926 return SOCKET_ERROR;
1931 case WS_IP_ADD_MEMBERSHIP:
1932 case WS_IP_DROP_MEMBERSHIP:
1936 case WS_IP_MULTICAST_IF:
1937 case WS_IP_MULTICAST_LOOP:
1938 case WS_IP_MULTICAST_TTL:
1942 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1943 return SOCKET_ERROR;
1944 convert_sockopt(&level, &optname);
1945 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1947 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1950 release_sock_fd( s, fd );
1952 case WS_IP_DONTFRAGMENT:
1953 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
1954 *(BOOL*)optval = FALSE;
1957 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
1958 return SOCKET_ERROR;
1961 FIXME("Unknown level: 0x%08x\n", level);
1962 return SOCKET_ERROR;
1963 } /* end switch(level) */
1966 /***********************************************************************
1970 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
1972 return htonl(hostlong);
1976 /***********************************************************************
1980 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
1982 return htons(hostshort);
1985 /***********************************************************************
1986 * WSAHtonl (WS2_32.46)
1987 * From MSDN description of error codes, this function should also
1988 * check if WinSock has been initialized and the socket is a valid
1989 * socket. But why? This function only translates a host byte order
1990 * u_long into a network byte order u_long...
1992 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
1996 *lpnetlong = htonl(hostlong);
1999 WSASetLastError(WSAEFAULT);
2000 return SOCKET_ERROR;
2003 /***********************************************************************
2004 * WSAHtons (WS2_32.47)
2005 * From MSDN description of error codes, this function should also
2006 * check if WinSock has been initialized and the socket is a valid
2007 * socket. But why? This function only translates a host byte order
2008 * u_short into a network byte order u_short...
2010 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2015 *lpnetshort = htons(hostshort);
2018 WSASetLastError(WSAEFAULT);
2019 return SOCKET_ERROR;
2023 /***********************************************************************
2024 * inet_addr (WINSOCK.10)
2025 * inet_addr (WS2_32.11)
2027 WS_u_long WINAPI WS_inet_addr(const char *cp)
2029 if (!cp) return INADDR_NONE;
2030 return inet_addr(cp);
2034 /***********************************************************************
2035 * ntohl (WINSOCK.14)
2038 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2040 return ntohl(netlong);
2044 /***********************************************************************
2045 * ntohs (WINSOCK.15)
2048 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2050 return ntohs(netshort);
2054 /***********************************************************************
2055 * inet_ntoa (WS2_32.12)
2057 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2059 /* use "buffer for dummies" here because some applications have a
2060 * propensity to decode addresses in ws_hostent structure without
2061 * saving them first...
2063 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2065 char* s = inet_ntoa(*((struct in_addr*)&in));
2071 SetLastError(wsaErrno());
2075 /**********************************************************************
2076 * WSAIoctl (WS2_32.50)
2079 INT WINAPI WSAIoctl(SOCKET s,
2080 DWORD dwIoControlCode,
2083 LPVOID lpbOutBuffer,
2085 LPDWORD lpcbBytesReturned,
2086 LPWSAOVERLAPPED lpOverlapped,
2087 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2089 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
2090 s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpbOutBuffer,
2091 cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
2093 switch( dwIoControlCode )
2096 if (cbInBuffer != sizeof(WS_u_long)) {
2097 WSASetLastError(WSAEFAULT);
2098 return SOCKET_ERROR;
2100 return WS_ioctlsocket( s, WS_FIONBIO, lpvInBuffer);
2103 if (cbOutBuffer != sizeof(WS_u_long)) {
2104 WSASetLastError(WSAEFAULT);
2105 return SOCKET_ERROR;
2107 return WS_ioctlsocket( s, WS_FIONREAD, lpbOutBuffer);
2109 case WS_SIO_GET_INTERFACE_LIST:
2111 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
2112 DWORD size, numInt, apiReturn;
2115 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
2119 WSASetLastError(WSAEFAULT);
2120 return SOCKET_ERROR;
2122 if (!lpcbBytesReturned)
2124 WSASetLastError(WSAEFAULT);
2125 return SOCKET_ERROR;
2128 fd = get_sock_fd( s, 0, NULL );
2129 if (fd == -1) return SOCKET_ERROR;
2131 apiReturn = GetAdaptersInfo(NULL, &size);
2132 if (apiReturn == ERROR_NO_DATA)
2136 else if (apiReturn == ERROR_BUFFER_OVERFLOW)
2138 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
2142 if (GetAdaptersInfo(table, &size) == NO_ERROR)
2144 PIP_ADAPTER_INFO ptr;
2146 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > cbOutBuffer)
2148 WARN("Buffer too small = %u, cbOutBuffer = %u\n", size, cbOutBuffer);
2149 HeapFree(GetProcessHeap(),0,table);
2150 release_sock_fd( s, fd );
2151 WSASetLastError(WSAEFAULT);
2152 return SOCKET_ERROR;
2154 for (ptr = table, numInt = 0; ptr;
2155 ptr = ptr->Next, intArray++, numInt++)
2157 unsigned int addr, mask, bcast;
2158 struct ifreq ifInfo;
2160 /* Socket Status Flags */
2161 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
2162 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2164 ERR("Error obtaining status flags for socket!\n");
2165 HeapFree(GetProcessHeap(),0,table);
2166 release_sock_fd( s, fd );
2167 WSASetLastError(WSAEINVAL);
2168 return SOCKET_ERROR;
2172 /* set flags; the values of IFF_* are not the same
2173 under Linux and Windows, therefore must generate
2175 intArray->iiFlags = 0;
2176 if (ifInfo.ifr_flags & IFF_BROADCAST)
2177 intArray->iiFlags |= WS_IFF_BROADCAST;
2178 #ifdef IFF_POINTOPOINT
2179 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
2180 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
2182 if (ifInfo.ifr_flags & IFF_LOOPBACK)
2183 intArray->iiFlags |= WS_IFF_LOOPBACK;
2184 if (ifInfo.ifr_flags & IFF_UP)
2185 intArray->iiFlags |= WS_IFF_UP;
2186 if (ifInfo.ifr_flags & IFF_MULTICAST)
2187 intArray->iiFlags |= WS_IFF_MULTICAST;
2190 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
2191 mask = inet_addr(ptr->IpAddressList.IpMask.String);
2192 bcast = addr | ~mask;
2193 intArray->iiAddress.AddressIn.sin_family = AF_INET;
2194 intArray->iiAddress.AddressIn.sin_port = 0;
2195 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
2197 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2198 intArray->iiNetmask.AddressIn.sin_port = 0;
2199 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
2201 intArray->iiBroadcastAddress.AddressIn.sin_family =
2203 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
2204 intArray->iiBroadcastAddress.AddressIn.sin_addr.
2210 ERR("Unable to get interface table!\n");
2211 release_sock_fd( s, fd );
2212 HeapFree(GetProcessHeap(),0,table);
2213 WSASetLastError(WSAEINVAL);
2214 return SOCKET_ERROR;
2216 HeapFree(GetProcessHeap(),0,table);
2220 release_sock_fd( s, fd );
2221 WSASetLastError(WSAEINVAL);
2222 return SOCKET_ERROR;
2227 ERR("Unable to get interface table!\n");
2228 release_sock_fd( s, fd );
2229 WSASetLastError(WSAEINVAL);
2230 return SOCKET_ERROR;
2232 /* Calculate the size of the array being returned */
2233 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2234 release_sock_fd( s, fd );
2238 case WS_SIO_ADDRESS_LIST_CHANGE:
2239 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
2240 /* FIXME: error and return code depend on whether socket was created
2241 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
2244 case WS_SIO_ADDRESS_LIST_QUERY:
2248 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
2250 if (!lpcbBytesReturned)
2252 WSASetLastError(WSAEFAULT);
2253 return SOCKET_ERROR;
2256 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
2258 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
2261 if (!table || GetAdaptersInfo(table, &size))
2263 HeapFree(GetProcessHeap(), 0, table);
2264 WSASetLastError(WSAEINVAL);
2265 return SOCKET_ERROR;
2268 for (p = table, num = 0; p; p = p->Next)
2269 if (p->IpAddressList.IpAddress.String[0]) num++;
2271 need = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
2272 need += sizeof(SOCKADDR) * num;
2273 *lpcbBytesReturned = need;
2275 if (need > cbOutBuffer)
2277 HeapFree(GetProcessHeap(), 0, table);
2278 WSASetLastError(WSAEFAULT);
2279 return SOCKET_ERROR;
2286 SOCKET_ADDRESS_LIST *sa_list = (SOCKET_ADDRESS_LIST *)lpbOutBuffer;
2287 SOCKADDR_IN *sockaddr;
2289 sa = sa_list->Address;
2290 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
2291 sa_list->iAddressCount = num;
2293 for (p = table, i = 0; p; p = p->Next)
2295 if (!p->IpAddressList.IpAddress.String[0]) continue;
2297 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
2298 sa[i].iSockaddrLength = sizeof(SOCKADDR);
2300 sockaddr[i].sin_family = AF_INET;
2301 sockaddr[i].sin_port = 0;
2302 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
2307 HeapFree(GetProcessHeap(), 0, table);
2312 WARN("unable to get IP address list\n");
2313 WSASetLastError(WSAEINVAL);
2314 return SOCKET_ERROR;
2318 FIXME("SIO_FLUSH: stub.\n");
2321 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
2322 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(lpvInBuffer));
2323 WSASetLastError(WSAEOPNOTSUPP);
2324 return SOCKET_ERROR;
2326 case WS_SIO_KEEPALIVE_VALS:
2329 struct tcp_keepalive *k = lpvInBuffer;
2330 int keepalive = k->onoff ? 1 : 0;
2331 int keepidle = k->keepalivetime / 1000;
2332 int keepintvl = k->keepaliveinterval / 1000;
2336 WSASetLastError(WSAEINVAL);
2337 return SOCKET_ERROR;
2340 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
2342 fd = get_sock_fd(s, 0, NULL);
2343 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
2345 release_sock_fd(s, fd);
2346 WSASetLastError(WSAEINVAL);
2347 return SOCKET_ERROR;
2349 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
2350 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
2352 release_sock_fd(s, fd);
2353 WSASetLastError(WSAEINVAL);
2354 return SOCKET_ERROR;
2356 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
2358 release_sock_fd(s, fd);
2359 WSASetLastError(WSAEINVAL);
2360 return SOCKET_ERROR;
2363 FIXME("ignoring keepalive interval and timeout\n");
2366 release_sock_fd(s, fd);
2370 FIXME("unsupported WS_IOCTL cmd (%08x)\n", dwIoControlCode);
2371 WSASetLastError(WSAEOPNOTSUPP);
2372 return SOCKET_ERROR;
2379 /***********************************************************************
2380 * ioctlsocket (WS2_32.10)
2382 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
2387 TRACE("socket %04lx, cmd %08x, ptr %p\n", s, cmd, argp);
2388 /* broken apps like defcon pass the argp value directly instead of a pointer to it */
2389 if(IS_INTRESOURCE(argp))
2391 SetLastError(WSAEFAULT);
2392 return SOCKET_ERROR;
2402 if( _get_sock_mask(s) )
2404 /* AsyncSelect()'ed sockets are always nonblocking */
2405 if (*argp) return 0;
2406 SetLastError(WSAEINVAL);
2407 return SOCKET_ERROR;
2409 fd = get_sock_fd( s, 0, NULL );
2415 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
2416 ret = fcntl( fd, F_SETFL, O_NONBLOCK );
2420 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
2421 ret = fcntl( fd, F_SETFL, 0 );
2423 release_sock_fd( s, fd );
2425 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2427 return SOCKET_ERROR;
2434 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2435 SetLastError(WSAEINVAL);
2436 return SOCKET_ERROR;
2438 case SIOCGIFBRDADDR:
2439 case SIOCGIFNETMASK:
2441 /* These don't need any special handling. They are used by
2442 WsControl, and are here to suppress an unnecessary warning. */
2446 /* Netscape tries hard to use bogus ioctl 0x667e */
2447 /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
2448 * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
2450 WARN("\tunknown WS_IOCTL cmd (%08x)\n", cmd);
2454 fd = get_sock_fd( s, 0, NULL );
2457 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2459 release_sock_fd( s, fd );
2462 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2463 release_sock_fd( s, fd );
2465 return SOCKET_ERROR;
2468 /***********************************************************************
2469 * listen (WS2_32.13)
2471 int WINAPI WS_listen(SOCKET s, int backlog)
2473 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2475 TRACE("socket %04lx, backlog %d\n", s, backlog);
2478 if (listen(fd, backlog) == 0)
2480 release_sock_fd( s, fd );
2481 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
2483 FD_CONNECT|FD_WINE_CONNECTED);
2486 SetLastError(wsaErrno());
2487 release_sock_fd( s, fd );
2489 return SOCKET_ERROR;
2492 /***********************************************************************
2495 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2497 DWORD n, dwFlags = flags;
2503 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2504 return SOCKET_ERROR;
2509 /***********************************************************************
2510 * recvfrom (WS2_32.17)
2512 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2513 struct WS_sockaddr *from, int *fromlen)
2515 DWORD n, dwFlags = flags;
2521 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2522 return SOCKET_ERROR;
2527 /* allocate a poll array for the corresponding fd sets */
2528 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
2529 const WS_fd_set *exceptfds, int *count_ptr )
2531 unsigned int i, j = 0, count = 0;
2534 if (readfds) count += readfds->fd_count;
2535 if (writefds) count += writefds->fd_count;
2536 if (exceptfds) count += exceptfds->fd_count;
2538 if (!count) return NULL;
2539 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0])))) return NULL;
2541 for (i = 0; i < readfds->fd_count; i++, j++)
2543 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
2544 fds[j].events = POLLIN;
2548 for (i = 0; i < writefds->fd_count; i++, j++)
2550 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
2551 fds[j].events = POLLOUT;
2555 for (i = 0; i < exceptfds->fd_count; i++, j++)
2557 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
2558 fds[j].events = POLLHUP;
2564 /* release the file descriptor obtained in fd_sets_to_poll */
2565 /* must be called with the original fd_set arrays, before calling get_poll_results */
2566 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
2567 const WS_fd_set *exceptfds, struct pollfd *fds )
2569 unsigned int i, j = 0;
2573 for (i = 0; i < readfds->fd_count; i++, j++)
2574 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
2578 for (i = 0; i < writefds->fd_count; i++, j++)
2579 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
2583 for (i = 0; i < exceptfds->fd_count; i++, j++)
2584 if (fds[j].fd != -1)
2586 /* make sure we have a real error before releasing the fd */
2587 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
2588 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
2593 /* map the poll results back into the Windows fd sets */
2594 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
2595 const struct pollfd *fds )
2597 unsigned int i, j = 0, k, total = 0;
2601 for (i = k = 0; i < readfds->fd_count; i++, j++)
2602 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
2603 readfds->fd_count = k;
2608 for (i = k = 0; i < writefds->fd_count; i++, j++)
2609 if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
2610 writefds->fd_count = k;
2615 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
2616 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
2617 exceptfds->fd_count = k;
2624 /***********************************************************************
2625 * select (WS2_32.18)
2627 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
2628 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
2629 const struct WS_timeval* ws_timeout)
2631 struct pollfd *pollfds;
2632 int count, ret, timeout = -1;
2634 TRACE("read %p, write %p, excp %p timeout %p\n",
2635 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
2637 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )) && count)
2639 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2640 return SOCKET_ERROR;
2643 if (ws_timeout) timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
2645 ret = poll( pollfds, count, timeout );
2646 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2648 if (ret == -1) SetLastError(wsaErrno());
2649 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2650 HeapFree( GetProcessHeap(), 0, pollfds );
2654 /* helper to send completion messages for client-only i/o operation case */
2655 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
2660 SERVER_START_REQ( add_fd_completion )
2662 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
2663 req->cvalue = CompletionValue;
2664 req->status = CompletionStatus;
2665 req->information = Information;
2666 status = wine_server_call( req );
2672 /***********************************************************************
2675 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
2681 wsabuf.buf = (char*) buf;
2683 if ( WSASendTo( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
2684 return SOCKET_ERROR;
2689 /***********************************************************************
2690 * WSASend (WS2_32.72)
2692 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2693 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2694 LPWSAOVERLAPPED lpOverlapped,
2695 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2697 return WSASendTo( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
2698 NULL, 0, lpOverlapped, lpCompletionRoutine );
2701 /***********************************************************************
2702 * WSASendDisconnect (WS2_32.73)
2704 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
2706 return WS_shutdown( s, SD_SEND );
2710 /***********************************************************************
2711 * WSASendTo (WS2_32.74)
2713 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2714 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2715 const struct WS_sockaddr *to, int tolen,
2716 LPWSAOVERLAPPED lpOverlapped,
2717 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2719 unsigned int i, options;
2721 struct ws2_async *wsa;
2722 int totalLength = 0;
2723 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
2725 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
2726 s, lpBuffers, dwBufferCount, dwFlags,
2727 to, tolen, lpOverlapped, lpCompletionRoutine);
2729 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
2730 TRACE( "fd=%d, options=%x\n", fd, options );
2732 if ( fd == -1 ) return SOCKET_ERROR;
2734 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
2740 wsa->hSocket = SOCKET2HANDLE(s);
2741 wsa->addr = (struct WS_sockaddr *)to;
2742 wsa->addrlen.val = tolen;
2743 wsa->flags = dwFlags;
2744 wsa->n_iovecs = dwBufferCount;
2745 wsa->first_iovec = 0;
2746 for ( i = 0; i < dwBufferCount; i++ )
2748 wsa->iovec[i].iov_base = lpBuffers[i].buf;
2749 wsa->iovec[i].iov_len = lpBuffers[i].len;
2750 totalLength += lpBuffers[i].len;
2753 if (!lpNumberOfBytesSent)
2761 n = WS2_send( fd, wsa );
2762 if (n != -1 || errno != EINTR) break;
2764 if (n == -1 && errno != EAGAIN)
2767 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
2771 if ((lpOverlapped || lpCompletionRoutine) &&
2772 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
2774 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
2776 wsa->user_overlapped = lpOverlapped;
2777 wsa->completion_func = lpCompletionRoutine;
2778 release_sock_fd( s, fd );
2782 iosb->u.Status = STATUS_PENDING;
2783 iosb->Information = 0;
2785 SERVER_START_REQ( register_async )
2787 req->type = ASYNC_TYPE_WRITE;
2788 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2789 req->async.callback = wine_server_client_ptr( WS2_async_send );
2790 req->async.iosb = wine_server_client_ptr( iosb );
2791 req->async.arg = wine_server_client_ptr( wsa );
2792 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
2793 req->async.cvalue = cvalue;
2794 err = wine_server_call( req );
2798 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
2799 WSASetLastError( NtStatusToWSAError( err ));
2800 return SOCKET_ERROR;
2803 iosb->u.Status = STATUS_SUCCESS;
2804 iosb->Information = n;
2805 *lpNumberOfBytesSent = n;
2806 if (!wsa->completion_func)
2808 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
2809 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
2810 HeapFree( GetProcessHeap(), 0, wsa );
2812 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
2813 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
2818 if ( _is_blocking(s) )
2820 /* On a blocking non-overlapped stream socket,
2821 * sending blocks until the entire buffer is sent. */
2822 DWORD timeout_start = GetTickCount();
2824 *lpNumberOfBytesSent = 0;
2826 while (wsa->first_iovec < dwBufferCount)
2829 int timeout = GET_SNDTIMEO(fd);
2833 *lpNumberOfBytesSent += n;
2834 while (wsa->first_iovec < dwBufferCount && wsa->iovec[wsa->first_iovec].iov_len <= n)
2835 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2836 if (wsa->first_iovec >= dwBufferCount) break;
2837 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2838 wsa->iovec[wsa->first_iovec].iov_len -= n;
2843 timeout -= GetTickCount() - timeout_start;
2844 if (timeout < 0) timeout = 0;
2848 pfd.events = POLLOUT;
2850 if (!timeout || !poll( &pfd, 1, timeout ))
2853 goto error; /* msdn says a timeout in send is fatal */
2856 n = WS2_send( fd, wsa );
2857 if (n == -1 && errno != EAGAIN && errno != EINTR)
2864 else /* non-blocking */
2866 if (n < totalLength)
2867 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
2870 err = WSAEWOULDBLOCK;
2873 *lpNumberOfBytesSent = n;
2876 TRACE(" -> %i bytes\n", *lpNumberOfBytesSent);
2878 HeapFree( GetProcessHeap(), 0, wsa );
2879 release_sock_fd( s, fd );
2884 HeapFree( GetProcessHeap(), 0, wsa );
2885 release_sock_fd( s, fd );
2886 WARN(" -> ERROR %d\n", err);
2887 WSASetLastError(err);
2888 return SOCKET_ERROR;
2891 /***********************************************************************
2892 * sendto (WS2_32.20)
2894 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
2895 const struct WS_sockaddr *to, int tolen)
2901 wsabuf.buf = (char*) buf;
2903 if ( WSASendTo(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
2904 return SOCKET_ERROR;
2909 /***********************************************************************
2910 * setsockopt (WS2_32.21)
2912 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
2913 const char *optval, int optlen)
2917 struct linger linger;
2918 struct timeval tval;
2920 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2921 s, level, optname, optval, optlen);
2923 /* some broken apps pass the value directly instead of a pointer to it */
2924 if(IS_INTRESOURCE(optval))
2926 SetLastError(WSAEFAULT);
2927 return SOCKET_ERROR;
2935 /* Some options need some conversion before they can be sent to
2936 * setsockopt. The conversions are done here, then they will fall though
2937 * to the general case. Special options that are not passed to
2938 * setsockopt follow below that.*/
2940 case WS_SO_DONTLINGER:
2941 linger.l_onoff = *((const int*)optval) ? 0: 1;
2942 linger.l_linger = 0;
2944 optname = SO_LINGER;
2945 optval = (char*)&linger;
2946 optlen = sizeof(struct linger);
2950 linger.l_onoff = ((LINGER*)optval)->l_onoff;
2951 linger.l_linger = ((LINGER*)optval)->l_linger;
2952 /* FIXME: what is documented behavior if SO_LINGER optval
2955 optname = SO_LINGER;
2956 optval = (char*)&linger;
2957 optlen = sizeof(struct linger);
2961 if (*(const int*)optval < 2048)
2963 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
2968 /* The options listed here don't need any special handling. Thanks to
2969 * the conversion happening above, options from there will fall through
2971 case WS_SO_ACCEPTCONN:
2972 case WS_SO_BROADCAST:
2974 case WS_SO_KEEPALIVE:
2975 case WS_SO_OOBINLINE:
2976 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
2977 * however, using it the BSD way fixes bug 8513 and seems to be what
2978 * most programmers assume, anyway */
2979 case WS_SO_REUSEADDR:
2982 convert_sockopt(&level, &optname);
2985 /* SO_DEBUG is a privileged operation, ignore it. */
2987 TRACE("Ignoring SO_DEBUG\n");
2990 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
2991 * socket. According to MSDN, this option is silently ignored.*/
2992 case WS_SO_DONTROUTE:
2993 TRACE("Ignoring SO_DONTROUTE\n");
2996 /* Stops two sockets from being bound to the same port. Always happens
2997 * on unix systems, so just drop it. */
2998 case WS_SO_EXCLUSIVEADDRUSE:
2999 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
3002 /* SO_OPENTYPE does not require a valid socket handle. */
3003 case WS_SO_OPENTYPE:
3004 if (!optlen || optlen < sizeof(int) || !optval)
3006 SetLastError(WSAEFAULT);
3007 return SOCKET_ERROR;
3009 get_per_thread_data()->opentype = *(const int *)optval;
3010 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3014 case WS_SO_RCVTIMEO:
3017 case WS_SO_SNDTIMEO:
3019 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3020 if (optval && optlen == sizeof(UINT32)) {
3021 /* WinSock passes milliseconds instead of struct timeval */
3022 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
3023 tval.tv_sec = *(const UINT32*)optval / 1000;
3024 /* min of 500 milliseconds */
3025 if (tval.tv_sec == 0 && tval.tv_usec < 500000)
3026 tval.tv_usec = 500000;
3027 optlen = sizeof(struct timeval);
3028 optval = (char*)&tval;
3029 } else if (optlen == sizeof(struct timeval)) {
3030 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
3032 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
3035 convert_sockopt(&level, &optname);
3040 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3041 SetLastError(WSAENOPROTOOPT);
3042 return SOCKET_ERROR;
3044 break; /* case WS_SOL_SOCKET */
3051 fd = get_sock_fd( s, 0, NULL );
3052 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
3054 /* We try to set the ipx type on ipx socket level. */
3056 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
3058 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
3059 release_sock_fd( s, fd );
3060 return SOCKET_ERROR;
3065 /* Should we retrieve val using a getsockopt call and then
3066 * set the modified one? */
3067 val.ipx_pt = *optval;
3068 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
3071 release_sock_fd( s, fd );
3074 case IPX_FILTERPTYPE:
3075 /* Sets the receive filter packet type, at the moment we don't support it */
3076 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
3077 /* Returning 0 is better for now than returning a SOCKET_ERROR */
3081 FIXME("opt_name:%x\n", optname);
3082 return SOCKET_ERROR;
3084 break; /* case NSPROTO_IPX */
3087 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3088 case WS_IPPROTO_TCP:
3091 case WS_TCP_NODELAY:
3092 convert_sockopt(&level, &optname);
3095 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3096 return SOCKET_ERROR;
3103 case WS_IP_ADD_MEMBERSHIP:
3104 case WS_IP_DROP_MEMBERSHIP:
3108 case WS_IP_MULTICAST_IF:
3109 case WS_IP_MULTICAST_LOOP:
3110 case WS_IP_MULTICAST_TTL:
3114 convert_sockopt(&level, &optname);
3116 case WS_IP_DONTFRAGMENT:
3117 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
3120 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3121 return SOCKET_ERROR;
3126 FIXME("Unknown level: 0x%08x\n", level);
3127 return SOCKET_ERROR;
3128 } /* end switch(level) */
3130 /* avoid endianness issues if argument is a 16-bit int */
3131 if (optval && optlen < sizeof(int))
3133 woptval= *((const INT16 *) optval);
3134 optval= (char*) &woptval;
3137 fd = get_sock_fd( s, 0, NULL );
3138 if (fd == -1) return SOCKET_ERROR;
3140 if (setsockopt(fd, level, optname, optval, optlen) == 0)
3142 release_sock_fd( s, fd );
3145 TRACE("Setting socket error, %d\n", wsaErrno());
3146 SetLastError(wsaErrno());
3147 release_sock_fd( s, fd );
3149 return SOCKET_ERROR;
3152 /***********************************************************************
3153 * shutdown (WS2_32.22)
3155 int WINAPI WS_shutdown(SOCKET s, int how)
3157 int fd, err = WSAENOTSOCK;
3158 unsigned int options, clear_flags = 0;
3160 fd = get_sock_fd( s, 0, &options );
3161 TRACE("socket %04lx, how %i %x\n", s, how, options );
3164 return SOCKET_ERROR;
3168 case 0: /* drop receives */
3169 clear_flags |= FD_READ;
3171 case 1: /* drop sends */
3172 clear_flags |= FD_WRITE;
3174 case 2: /* drop all */
3175 clear_flags |= FD_READ|FD_WRITE;
3177 clear_flags |= FD_WINE_LISTENING;
3180 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3185 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3188 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3192 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3193 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3196 if (err) goto error;
3198 else /* non-overlapped mode */
3200 if ( shutdown( fd, how ) )
3207 release_sock_fd( s, fd );
3208 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3209 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
3213 release_sock_fd( s, fd );
3214 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3215 WSASetLastError( err );
3216 return SOCKET_ERROR;
3219 /***********************************************************************
3220 * socket (WS2_32.23)
3222 SOCKET WINAPI WS_socket(int af, int type, int protocol)
3224 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
3226 return WSASocketA( af, type, protocol, NULL, 0,
3227 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
3231 /***********************************************************************
3232 * gethostbyaddr (WS2_32.51)
3234 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
3236 struct WS_hostent *retval = NULL;
3237 struct hostent* host;
3239 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3242 struct hostent hostentry;
3245 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3247 int res = gethostbyaddr_r(addr, len, type,
3248 &hostentry, extrabuf, ebufsize, &host, &locerr);
3249 if( res != ERANGE) break;
3251 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3253 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3255 EnterCriticalSection( &csWSgetXXXbyYYY );
3256 host = gethostbyaddr(addr, len, type);
3257 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3259 if( host != NULL ) retval = WS_dup_he(host);
3260 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3261 HeapFree(GetProcessHeap(),0,extrabuf);
3263 LeaveCriticalSection( &csWSgetXXXbyYYY );
3265 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
3269 /***********************************************************************
3270 * gethostbyname (WS2_32.52)
3272 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
3274 struct WS_hostent *retval = NULL;
3275 struct hostent* host;
3276 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3279 struct hostent hostentry;
3280 int locerr = ENOBUFS;
3283 if( !name || !name[0]) {
3285 if( gethostname( buf, 100) == -1) {
3286 SetLastError( WSAENOBUFS); /* appropriate ? */
3290 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3292 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3294 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
3295 if( res != ERANGE) break;
3297 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3299 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3301 EnterCriticalSection( &csWSgetXXXbyYYY );
3302 host = gethostbyname(name);
3303 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3305 if (host) retval = WS_dup_he(host);
3306 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3307 HeapFree(GetProcessHeap(),0,extrabuf);
3309 LeaveCriticalSection( &csWSgetXXXbyYYY );
3311 if (retval && retval->h_addr_list[0][0] == 127 &&
3312 strcmp(name, "localhost") != 0)
3314 /* hostname != "localhost" but has loopback address. replace by our
3315 * special address.*/
3316 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
3318 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3323 /***********************************************************************
3324 * getprotobyname (WS2_32.53)
3326 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3328 struct WS_protoent* retval = NULL;
3329 #ifdef HAVE_GETPROTOBYNAME
3330 struct protoent* proto;
3331 EnterCriticalSection( &csWSgetXXXbyYYY );
3332 if( (proto = getprotobyname(name)) != NULL )
3334 retval = WS_dup_pe(proto);
3337 MESSAGE("protocol %s not found; You might want to add "
3338 "this to /etc/protocols\n", debugstr_a(name) );
3339 SetLastError(WSANO_DATA);
3341 LeaveCriticalSection( &csWSgetXXXbyYYY );
3343 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3348 /***********************************************************************
3349 * getprotobynumber (WS2_32.54)
3351 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3353 struct WS_protoent* retval = NULL;
3354 #ifdef HAVE_GETPROTOBYNUMBER
3355 struct protoent* proto;
3356 EnterCriticalSection( &csWSgetXXXbyYYY );
3357 if( (proto = getprotobynumber(number)) != NULL )
3359 retval = WS_dup_pe(proto);
3362 MESSAGE("protocol number %d not found; You might want to add "
3363 "this to /etc/protocols\n", number );
3364 SetLastError(WSANO_DATA);
3366 LeaveCriticalSection( &csWSgetXXXbyYYY );
3368 TRACE("%i ret %p\n", number, retval);
3373 /***********************************************************************
3374 * getservbyname (WS2_32.55)
3376 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3378 struct WS_servent* retval = NULL;
3379 struct servent* serv;
3381 char *proto_str = NULL;
3383 if (!(name_str = strdup_lower(name))) return NULL;
3385 if (proto && *proto)
3387 if (!(proto_str = strdup_lower(proto)))
3389 HeapFree( GetProcessHeap(), 0, name_str );
3394 EnterCriticalSection( &csWSgetXXXbyYYY );
3395 serv = getservbyname(name_str, proto_str);
3398 retval = WS_dup_se(serv);
3400 else SetLastError(WSANO_DATA);
3401 LeaveCriticalSection( &csWSgetXXXbyYYY );
3402 HeapFree( GetProcessHeap(), 0, proto_str );
3403 HeapFree( GetProcessHeap(), 0, name_str );
3404 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
3408 /***********************************************************************
3409 * freeaddrinfo (WS2_32.@)
3411 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
3414 struct WS_addrinfo *next;
3416 HeapFree(GetProcessHeap(),0,res->ai_canonname);
3417 HeapFree(GetProcessHeap(),0,res->ai_addr);
3418 next = res->ai_next;
3419 HeapFree(GetProcessHeap(),0,res);
3424 /* helper functions for getaddrinfo()/getnameinfo() */
3425 static int convert_aiflag_w2u(int winflags) {
3429 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3430 if (ws_aiflag_map[i][0] & winflags) {
3431 unixflags |= ws_aiflag_map[i][1];
3432 winflags &= ~ws_aiflag_map[i][0];
3435 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
3439 static int convert_niflag_w2u(int winflags) {
3443 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
3444 if (ws_niflag_map[i][0] & winflags) {
3445 unixflags |= ws_niflag_map[i][1];
3446 winflags &= ~ws_niflag_map[i][0];
3449 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
3453 static int convert_aiflag_u2w(int unixflags) {
3457 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3458 if (ws_aiflag_map[i][1] & unixflags) {
3459 winflags |= ws_aiflag_map[i][0];
3460 unixflags &= ~ws_aiflag_map[i][1];
3462 if (unixflags) /* will warn usually */
3463 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
3467 static int convert_eai_u2w(int unixret) {
3470 for (i=0;ws_eai_map[i][0];i++)
3471 if (ws_eai_map[i][1] == unixret)
3472 return ws_eai_map[i][0];
3476 /***********************************************************************
3477 * getaddrinfo (WS2_32.@)
3479 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
3481 #ifdef HAVE_GETADDRINFO
3482 struct addrinfo *unixaires = NULL;
3484 struct addrinfo unixhints, *punixhints = NULL;
3485 CHAR *node = NULL, *serv = NULL;
3488 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
3491 if (!(serv = strdup_lower(servname))) {
3492 HeapFree(GetProcessHeap(), 0, node);
3493 return WSA_NOT_ENOUGH_MEMORY;
3498 punixhints = &unixhints;
3500 memset(&unixhints, 0, sizeof(unixhints));
3501 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
3502 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
3503 punixhints->ai_family = 0;
3505 punixhints->ai_family = convert_af_w2u(hints->ai_family);
3506 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
3507 punixhints->ai_socktype = 0;
3509 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
3510 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
3511 punixhints->ai_protocol = 0;
3513 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
3516 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
3517 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
3519 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
3521 HeapFree(GetProcessHeap(), 0, node);
3522 HeapFree(GetProcessHeap(), 0, serv);
3525 struct addrinfo *xuai = unixaires;
3526 struct WS_addrinfo **xai = res;
3530 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
3536 *xai = ai;xai = &ai->ai_next;
3537 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
3538 ai->ai_family = convert_af_u2w(xuai->ai_family);
3539 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
3540 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
3541 if (xuai->ai_canonname) {
3542 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
3543 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
3544 if (!ai->ai_canonname)
3546 strcpy(ai->ai_canonname,xuai->ai_canonname);
3548 len = xuai->ai_addrlen;
3549 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
3552 ai->ai_addrlen = len;
3554 int winlen = ai->ai_addrlen;
3556 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
3557 ai->ai_addrlen = winlen;
3561 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
3564 ai->ai_addrlen = len;
3566 xuai = xuai->ai_next;
3568 freeaddrinfo(unixaires);
3570 result = convert_eai_u2w(result);
3576 if (*res) WS_freeaddrinfo(*res);
3577 if (unixaires) freeaddrinfo(unixaires);
3579 return WSA_NOT_ENOUGH_MEMORY;
3581 FIXME("getaddrinfo() failed, not found during buildtime.\n");
3586 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
3588 struct WS_addrinfoW *ret;
3590 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
3591 ret->ai_flags = ai->ai_flags;
3592 ret->ai_family = ai->ai_family;
3593 ret->ai_socktype = ai->ai_socktype;
3594 ret->ai_protocol = ai->ai_protocol;
3595 ret->ai_addrlen = ai->ai_addrlen;
3596 ret->ai_canonname = NULL;
3597 ret->ai_addr = NULL;
3598 ret->ai_next = NULL;
3599 if (ai->ai_canonname)
3601 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
3602 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
3604 HeapFree(GetProcessHeap(), 0, ret);
3607 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
3611 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
3613 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
3614 HeapFree(GetProcessHeap(), 0, ret);
3617 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
3622 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
3624 struct WS_addrinfoW *ret, *infoW;
3626 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
3627 while (info->ai_next)
3629 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
3634 infoW = infoW->ai_next;
3635 info = info->ai_next;
3640 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
3642 struct WS_addrinfo *ret;
3644 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
3645 ret->ai_flags = ai->ai_flags;
3646 ret->ai_family = ai->ai_family;
3647 ret->ai_socktype = ai->ai_socktype;
3648 ret->ai_protocol = ai->ai_protocol;
3649 ret->ai_addrlen = ai->ai_addrlen;
3650 ret->ai_canonname = NULL;
3651 ret->ai_addr = NULL;
3652 ret->ai_next = NULL;
3653 if (ai->ai_canonname)
3655 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
3656 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
3658 HeapFree(GetProcessHeap(), 0, ret);
3661 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
3665 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
3667 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
3668 HeapFree(GetProcessHeap(), 0, ret);
3671 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
3676 /***********************************************************************
3677 * GetAddrInfoW (WS2_32.@)
3679 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
3682 char *nodenameA, *servnameA = NULL;
3683 struct WS_addrinfo *resA, *hintsA = NULL;
3685 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
3686 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
3687 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
3691 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
3692 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
3694 HeapFree(GetProcessHeap(), 0, nodenameA);
3697 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
3700 if (hints) hintsA = addrinfo_WtoA(hints);
3701 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
3702 WS_freeaddrinfo(hintsA);
3706 *res = addrinfo_list_AtoW(resA);
3707 WS_freeaddrinfo(resA);
3710 HeapFree(GetProcessHeap(), 0, nodenameA);
3711 HeapFree(GetProcessHeap(), 0, servnameA);
3715 /***********************************************************************
3716 * FreeAddrInfoW (WS2_32.@)
3718 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
3723 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
3724 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
3726 HeapFree(GetProcessHeap(), 0, ai);
3731 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
3732 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
3734 #ifdef HAVE_GETNAMEINFO
3736 union generic_unix_sockaddr sa_u;
3739 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
3740 serv, servlen, flags);
3742 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
3745 WSASetLastError(WSAEFAULT);
3746 return WSA_NOT_ENOUGH_MEMORY;
3748 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
3749 return convert_eai_u2w(ret);
3751 FIXME("getnameinfo() failed, not found during buildtime.\n");
3756 /***********************************************************************
3757 * getservbyport (WS2_32.56)
3759 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
3761 struct WS_servent* retval = NULL;
3762 #ifdef HAVE_GETSERVBYPORT
3763 struct servent* serv;
3764 char *proto_str = NULL;
3766 if (proto && *proto)
3768 if (!(proto_str = strdup_lower(proto))) return NULL;
3770 EnterCriticalSection( &csWSgetXXXbyYYY );
3771 if( (serv = getservbyport(port, proto_str)) != NULL ) {
3772 retval = WS_dup_se(serv);
3774 else SetLastError(WSANO_DATA);
3775 LeaveCriticalSection( &csWSgetXXXbyYYY );
3776 HeapFree( GetProcessHeap(), 0, proto_str );
3778 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
3783 /***********************************************************************
3784 * gethostname (WS2_32.57)
3786 int WINAPI WS_gethostname(char *name, int namelen)
3788 TRACE("name %p, len %d\n", name, namelen);
3790 if (gethostname(name, namelen) == 0)
3792 TRACE("<- '%s'\n", name);
3795 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
3796 TRACE("<- ERROR !\n");
3797 return SOCKET_ERROR;
3801 /* ------------------------------------- Windows sockets extensions -- *
3803 * ------------------------------------------------------------------- */
3805 /***********************************************************************
3806 * WSAEnumNetworkEvents (WS2_32.36)
3808 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
3812 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
3814 SERVER_START_REQ( get_socket_event )
3816 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
3817 req->service = TRUE;
3818 req->c_event = wine_server_obj_handle( hEvent );
3819 wine_server_set_reply( req, lpEvent->iErrorCode, sizeof(lpEvent->iErrorCode) );
3820 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
3824 SetLastError(WSAEINVAL);
3825 return SOCKET_ERROR;
3828 /***********************************************************************
3829 * WSAEventSelect (WS2_32.39)
3831 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
3835 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
3837 SERVER_START_REQ( set_socket_event )
3839 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
3841 req->event = wine_server_obj_handle( hEvent );
3844 ret = wine_server_call( req );
3848 SetLastError(WSAEINVAL);
3849 return SOCKET_ERROR;
3852 /**********************************************************************
3853 * WSAGetOverlappedResult (WS2_32.40)
3855 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
3856 LPDWORD lpcbTransfer, BOOL fWait,
3861 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
3862 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
3864 if ( lpOverlapped == NULL )
3866 ERR( "Invalid pointer\n" );
3867 WSASetLastError(WSA_INVALID_PARAMETER);
3871 status = lpOverlapped->Internal;
3872 if (status == STATUS_PENDING)
3876 SetLastError( WSA_IO_INCOMPLETE );
3880 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
3881 INFINITE ) == WAIT_FAILED)
3883 status = lpOverlapped->Internal;
3887 *lpcbTransfer = lpOverlapped->InternalHigh;
3890 *lpdwFlags = lpOverlapped->u.s.Offset;
3892 if (status) SetLastError( RtlNtStatusToDosError(status) );
3897 /***********************************************************************
3898 * WSAAsyncSelect (WS2_32.101)
3900 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
3904 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
3906 SERVER_START_REQ( set_socket_event )
3908 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
3911 req->window = wine_server_user_handle( hWnd );
3913 ret = wine_server_call( req );
3917 SetLastError(WSAEINVAL);
3918 return SOCKET_ERROR;
3921 /***********************************************************************
3922 * WSACreateEvent (WS2_32.31)
3925 WSAEVENT WINAPI WSACreateEvent(void)
3927 /* Create a manual-reset event, with initial state: unsignaled */
3930 return CreateEventW(NULL, TRUE, FALSE, NULL);
3933 /***********************************************************************
3934 * WSACloseEvent (WS2_32.29)
3937 BOOL WINAPI WSACloseEvent(WSAEVENT event)
3939 TRACE ("event=%p\n", event);
3941 return CloseHandle(event);
3944 /***********************************************************************
3945 * WSASocketA (WS2_32.78)
3948 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
3949 LPWSAPROTOCOL_INFOA lpProtocolInfo,
3950 GROUP g, DWORD dwFlags)
3953 WSAPROTOCOL_INFOW info;
3955 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
3956 af, type, protocol, lpProtocolInfo, g, dwFlags);
3958 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
3960 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
3961 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
3962 info.szProtocol, WSAPROTOCOL_LEN + 1);
3966 WSASetLastError( WSAEINVAL);
3967 return SOCKET_ERROR;
3970 return WSASocketW(af, type, protocol, &info, g, dwFlags);
3973 /***********************************************************************
3974 * WSASocketW (WS2_32.79)
3977 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
3978 LPWSAPROTOCOL_INFOW lpProtocolInfo,
3979 GROUP g, DWORD dwFlags)
3984 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
3985 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
3988 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
3989 af, type, protocol, lpProtocolInfo, g, dwFlags );
3991 /* hack for WSADuplicateSocket */
3992 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
3993 ret = lpProtocolInfo->dwCatalogEntryId;
3994 TRACE("\tgot duplicate %04lx\n", ret);
3998 /* convert the socket family and type */
3999 af = convert_af_w2u(af);
4000 type = convert_socktype_w2u(type);
4004 if (af == FROM_PROTOCOL_INFO)
4005 af = lpProtocolInfo->iAddressFamily;
4006 if (type == FROM_PROTOCOL_INFO)
4007 type = lpProtocolInfo->iSocketType;
4008 if (protocol == FROM_PROTOCOL_INFO)
4009 protocol = lpProtocolInfo->iProtocol;
4012 if ( af == AF_UNSPEC) /* did they not specify the address family? */
4016 if (type == SOCK_STREAM) { af = AF_INET; break; }
4018 if (type == SOCK_DGRAM) { af = AF_INET; break; }
4019 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
4022 SERVER_START_REQ( create_socket )
4026 req->protocol = protocol;
4027 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
4028 req->attributes = OBJ_INHERIT;
4029 req->flags = dwFlags;
4030 set_error( wine_server_call( req ) );
4031 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
4036 TRACE("\tcreated %04lx\n", ret );
4040 if (GetLastError() == WSAEACCES) /* raw socket denied */
4042 if (type == SOCK_RAW)
4043 MESSAGE("WARNING: Trying to create a socket of type SOCK_RAW, this"
4044 " will fail unless you have special permissions.\n");
4046 MESSAGE("WS_SOCKET: Failed to create socket, this requires"
4047 " special permissions.\n");
4048 SetLastError(WSAESOCKTNOSUPPORT);
4051 WARN("\t\tfailed!\n");
4052 return INVALID_SOCKET;
4055 /***********************************************************************
4056 * WSAJoinLeaf (WS2_32.58)
4059 SOCKET WINAPI WSAJoinLeaf(
4061 const struct WS_sockaddr *addr,
4063 LPWSABUF lpCallerData,
4064 LPWSABUF lpCalleeData,
4070 return INVALID_SOCKET;
4073 /***********************************************************************
4074 * __WSAFDIsSet (WS2_32.151)
4076 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
4078 int i = set->fd_count;
4080 TRACE("(%ld,%p(%i))\n", s, set, i);
4083 if (set->fd_array[i] == s) return 1;
4087 /***********************************************************************
4088 * WSAIsBlocking (WINSOCK.114)
4089 * WSAIsBlocking (WS2_32.114)
4091 BOOL WINAPI WSAIsBlocking(void)
4093 /* By default WinSock should set all its sockets to non-blocking mode
4094 * and poll in PeekMessage loop when processing "blocking" ones. This
4095 * function is supposed to tell if the program is in this loop. Our
4096 * blocking calls are truly blocking so we always return FALSE.
4098 * Note: It is allowed to call this function without prior WSAStartup().
4105 /***********************************************************************
4106 * WSACancelBlockingCall (WINSOCK.113)
4107 * WSACancelBlockingCall (WS2_32.113)
4109 INT WINAPI WSACancelBlockingCall(void)
4115 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
4117 FIXME("How was this called?\n");
4122 /***********************************************************************
4123 * WSASetBlockingHook (WS2_32.109)
4125 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
4127 FARPROC prev = blocking_hook;
4128 blocking_hook = lpBlockFunc;
4129 TRACE("hook %p\n", lpBlockFunc);
4134 /***********************************************************************
4135 * WSAUnhookBlockingHook (WS2_32.110)
4137 INT WINAPI WSAUnhookBlockingHook(void)
4139 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
4144 /* ----------------------------------- end of API stuff */
4146 /* ----------------------------------- helper functions -
4148 * TODO: Merge WS_dup_..() stuff into one function that
4149 * would operate with a generic structure containing internal
4150 * pointers (via a template of some kind).
4153 static int list_size(char** l, int item_size)
4158 j += (item_size) ? item_size : strlen(l[i]) + 1;
4159 j += (i + 1) * sizeof(char*); }
4163 static int list_dup(char** l_src, char** l_to, int item_size)
4168 for (i = 0; l_src[i]; i++) ;
4169 p = (char *)(l_to + i + 1);
4170 for (i = 0; l_src[i]; i++)
4172 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
4173 memcpy(p, l_src[i], count);
4178 return p - (char *)l_to;
4183 /* duplicate hostent entry
4184 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
4185 * Ditto for protoent and servent.
4187 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
4190 struct WS_hostent *p_to;
4192 int size = (sizeof(*p_he) +
4193 strlen(p_he->h_name) + 1 +
4194 list_size(p_he->h_aliases, 0) +
4195 list_size(p_he->h_addr_list, p_he->h_length));
4197 if (!(p_to = check_buffer_he(size))) return NULL;
4198 p_to->h_addrtype = p_he->h_addrtype;
4199 p_to->h_length = p_he->h_length;
4201 p = (char *)(p_to + 1);
4203 strcpy(p, p_he->h_name);
4206 p_to->h_aliases = (char **)p;
4207 p += list_dup(p_he->h_aliases, p_to->h_aliases, 0);
4209 p_to->h_addr_list = (char **)p;
4210 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
4214 /* ----- protoent */
4216 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
4219 struct WS_protoent *p_to;
4221 int size = (sizeof(*p_pe) +
4222 strlen(p_pe->p_name) + 1 +
4223 list_size(p_pe->p_aliases, 0));
4225 if (!(p_to = check_buffer_pe(size))) return NULL;
4226 p_to->p_proto = p_pe->p_proto;
4228 p = (char *)(p_to + 1);
4230 strcpy(p, p_pe->p_name);
4233 p_to->p_aliases = (char **)p;
4234 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
4240 static struct WS_servent *WS_dup_se(const struct servent* p_se)
4243 struct WS_servent *p_to;
4245 int size = (sizeof(*p_se) +
4246 strlen(p_se->s_proto) + 1 +
4247 strlen(p_se->s_name) + 1 +
4248 list_size(p_se->s_aliases, 0));
4250 if (!(p_to = check_buffer_se(size))) return NULL;
4251 p_to->s_port = p_se->s_port;
4253 p = (char *)(p_to + 1);
4255 strcpy(p, p_se->s_name);
4259 strcpy(p, p_se->s_proto);
4262 p_to->s_aliases = (char **)p;
4263 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
4267 /* ----------------------------------- error handling */
4271 int loc_errno = errno;
4272 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
4276 case EINTR: return WSAEINTR;
4277 case EBADF: return WSAEBADF;
4279 case EACCES: return WSAEACCES;
4280 case EFAULT: return WSAEFAULT;
4281 case EINVAL: return WSAEINVAL;
4282 case EMFILE: return WSAEMFILE;
4283 case EWOULDBLOCK: return WSAEWOULDBLOCK;
4284 case EINPROGRESS: return WSAEINPROGRESS;
4285 case EALREADY: return WSAEALREADY;
4286 case ENOTSOCK: return WSAENOTSOCK;
4287 case EDESTADDRREQ: return WSAEDESTADDRREQ;
4288 case EMSGSIZE: return WSAEMSGSIZE;
4289 case EPROTOTYPE: return WSAEPROTOTYPE;
4290 case ENOPROTOOPT: return WSAENOPROTOOPT;
4291 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
4292 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
4293 case EOPNOTSUPP: return WSAEOPNOTSUPP;
4294 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
4295 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
4296 case EADDRINUSE: return WSAEADDRINUSE;
4297 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
4298 case ENETDOWN: return WSAENETDOWN;
4299 case ENETUNREACH: return WSAENETUNREACH;
4300 case ENETRESET: return WSAENETRESET;
4301 case ECONNABORTED: return WSAECONNABORTED;
4303 case ECONNRESET: return WSAECONNRESET;
4304 case ENOBUFS: return WSAENOBUFS;
4305 case EISCONN: return WSAEISCONN;
4306 case ENOTCONN: return WSAENOTCONN;
4307 case ESHUTDOWN: return WSAESHUTDOWN;
4308 case ETOOMANYREFS: return WSAETOOMANYREFS;
4309 case ETIMEDOUT: return WSAETIMEDOUT;
4310 case ECONNREFUSED: return WSAECONNREFUSED;
4311 case ELOOP: return WSAELOOP;
4312 case ENAMETOOLONG: return WSAENAMETOOLONG;
4313 case EHOSTDOWN: return WSAEHOSTDOWN;
4314 case EHOSTUNREACH: return WSAEHOSTUNREACH;
4315 case ENOTEMPTY: return WSAENOTEMPTY;
4317 case EPROCLIM: return WSAEPROCLIM;
4320 case EUSERS: return WSAEUSERS;
4323 case EDQUOT: return WSAEDQUOT;
4326 case ESTALE: return WSAESTALE;
4329 case EREMOTE: return WSAEREMOTE;
4332 /* just in case we ever get here and there are no problems */
4335 WARN("Unknown errno %d!\n", loc_errno);
4336 return WSAEOPNOTSUPP;
4340 UINT wsaHerrno(int loc_errno)
4343 WARN("h_errno %d.\n", loc_errno);
4347 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
4348 case TRY_AGAIN: return WSATRY_AGAIN;
4349 case NO_RECOVERY: return WSANO_RECOVERY;
4350 case NO_DATA: return WSANO_DATA;
4351 case ENOBUFS: return WSAENOBUFS;
4355 WARN("Unknown h_errno %d!\n", loc_errno);
4356 return WSAEOPNOTSUPP;
4361 /***********************************************************************
4362 * WSARecv (WS2_32.67)
4364 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4365 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
4366 LPWSAOVERLAPPED lpOverlapped,
4367 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
4369 return WSARecvFrom(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
4370 NULL, NULL, lpOverlapped, lpCompletionRoutine);
4373 /***********************************************************************
4374 * WSARecvFrom (WS2_32.69)
4376 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4377 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
4378 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
4379 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4382 unsigned int i, options;
4384 struct ws2_async *wsa;
4385 DWORD timeout_start = GetTickCount();
4386 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4388 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
4389 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
4390 (lpFromlen ? *lpFromlen : -1),
4391 lpOverlapped, lpCompletionRoutine);
4393 fd = get_sock_fd( s, FILE_READ_DATA, &options );
4394 TRACE( "fd=%d, options=%x\n", fd, options );
4396 if (fd == -1) return SOCKET_ERROR;
4398 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
4404 wsa->hSocket = SOCKET2HANDLE(s);
4405 wsa->flags = *lpFlags;
4407 wsa->addrlen.ptr = lpFromlen;
4408 wsa->n_iovecs = dwBufferCount;
4409 wsa->first_iovec = 0;
4410 for (i = 0; i < dwBufferCount; i++)
4412 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4413 wsa->iovec[i].iov_len = lpBuffers[i].len;
4418 n = WS2_recv( fd, wsa );
4421 if (errno == EINTR) continue;
4422 if (errno != EAGAIN)
4425 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
4430 *lpNumberOfBytesRecvd = n;
4432 if ((lpOverlapped || lpCompletionRoutine) &&
4433 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4435 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4437 wsa->user_overlapped = lpOverlapped;
4438 wsa->completion_func = lpCompletionRoutine;
4439 release_sock_fd( s, fd );
4443 iosb->u.Status = STATUS_PENDING;
4444 iosb->Information = 0;
4446 SERVER_START_REQ( register_async )
4448 req->type = ASYNC_TYPE_READ;
4449 req->async.handle = wine_server_obj_handle( wsa->hSocket );
4450 req->async.callback = wine_server_client_ptr( WS2_async_recv );
4451 req->async.iosb = wine_server_client_ptr( iosb );
4452 req->async.arg = wine_server_client_ptr( wsa );
4453 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
4454 req->async.cvalue = cvalue;
4455 err = wine_server_call( req );
4459 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4460 WSASetLastError( NtStatusToWSAError( err ));
4461 return SOCKET_ERROR;
4464 iosb->u.Status = STATUS_SUCCESS;
4465 iosb->Information = n;
4466 if (!wsa->completion_func)
4468 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4469 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
4470 HeapFree( GetProcessHeap(), 0, wsa );
4472 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4473 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4474 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4480 if ( _is_blocking(s) )
4483 int timeout = GET_RCVTIMEO(fd);
4486 timeout -= GetTickCount() - timeout_start;
4487 if (timeout < 0) timeout = 0;
4491 pfd.events = POLLIN;
4492 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
4494 if (!timeout || !poll( &pfd, 1, timeout ))
4497 /* a timeout is not fatal */
4498 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4504 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4505 err = WSAEWOULDBLOCK;
4510 TRACE(" -> %i bytes\n", n);
4511 HeapFree( GetProcessHeap(), 0, wsa );
4512 release_sock_fd( s, fd );
4513 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4518 HeapFree( GetProcessHeap(), 0, wsa );
4519 release_sock_fd( s, fd );
4520 WARN(" -> ERROR %d\n", err);
4521 WSASetLastError( err );
4522 return SOCKET_ERROR;
4525 /***********************************************************************
4526 * WSCInstallProvider (WS2_32.88)
4528 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
4529 LPCWSTR lpszProviderDllPath,
4530 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
4531 DWORD dwNumberOfEntries,
4534 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
4535 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
4536 dwNumberOfEntries, lpErrno);
4542 /***********************************************************************
4543 * WSCDeinstallProvider (WS2_32.83)
4545 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
4547 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
4553 /***********************************************************************
4554 * WSAAccept (WS2_32.26)
4556 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
4557 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
4560 int ret = 0, size = 0;
4561 WSABUF CallerId, CallerData, CalleeId, CalleeData;
4562 /* QOS SQOS, GQOS; */
4565 SOCKADDR src_addr, dst_addr;
4567 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %d\n",
4568 s, addr, addrlen, lpfnCondition, dwCallbackData);
4571 size = sizeof(src_addr);
4572 cs = WS_accept(s, &src_addr, &size);
4574 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
4576 if (!lpfnCondition) return cs;
4578 CallerId.buf = (char *)&src_addr;
4579 CallerId.len = sizeof(src_addr);
4581 CallerData.buf = NULL;
4584 WS_getsockname(cs, &dst_addr, &size);
4586 CalleeId.buf = (char *)&dst_addr;
4587 CalleeId.len = sizeof(dst_addr);
4590 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
4591 &CalleeId, &CalleeData, &g, dwCallbackData);
4596 if (addr && addrlen)
4597 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
4600 SERVER_START_REQ( set_socket_deferred )
4602 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4603 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
4604 if ( !wine_server_call_err ( req ) )
4606 SetLastError( WSATRY_AGAIN );
4607 WS_closesocket( cs );
4611 return SOCKET_ERROR;
4614 SetLastError(WSAECONNREFUSED);
4615 return SOCKET_ERROR;
4617 FIXME("Unknown return type from Condition function\n");
4618 SetLastError(WSAENOTSOCK);
4619 return SOCKET_ERROR;
4623 /***********************************************************************
4624 * WSADuplicateSocketA (WS2_32.32)
4626 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
4630 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4631 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4632 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
4633 /* I don't know what the real Windoze does next, this is a hack */
4634 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
4635 * the target use the global duplicate, or we could copy a reference to us to the structure
4636 * and let the target duplicate it from us, but let's do it as simple as possible */
4637 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4638 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4639 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4640 0, FALSE, DUPLICATE_SAME_ACCESS);
4641 CloseHandle(hProcess);
4642 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4646 /***********************************************************************
4647 * WSADuplicateSocketW (WS2_32.33)
4649 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
4653 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4655 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4656 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4657 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4658 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4659 0, FALSE, DUPLICATE_SAME_ACCESS);
4660 CloseHandle(hProcess);
4661 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4665 /***********************************************************************
4666 * WSAInstallServiceClassA (WS2_32.48)
4668 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
4670 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
4671 WSASetLastError(WSAEACCES);
4672 return SOCKET_ERROR;
4675 /***********************************************************************
4676 * WSAInstallServiceClassW (WS2_32.49)
4678 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
4680 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
4681 WSASetLastError(WSAEACCES);
4682 return SOCKET_ERROR;
4685 /***********************************************************************
4686 * WSARemoveServiceClass (WS2_32.70)
4688 int WINAPI WSARemoveServiceClass(LPGUID info)
4690 FIXME("Request to remove service %p\n",info);
4691 WSASetLastError(WSATYPE_NOT_FOUND);
4692 return SOCKET_ERROR;
4695 /***********************************************************************
4696 * inet_ntop (WS2_32.@)
4698 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
4700 #ifdef HAVE_INET_NTOP
4701 struct WS_in6_addr *in6;
4702 struct WS_in_addr *in;
4704 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
4709 return inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
4712 return inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
4715 FIXME( "not supported on this platform\n" );
4717 WSASetLastError( WSAEAFNOSUPPORT );
4721 /***********************************************************************
4722 * WSAStringToAddressA (WS2_32.80)
4724 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
4726 LPWSAPROTOCOL_INFOA lpProtocolInfo,
4727 LPSOCKADDR lpAddress,
4728 LPINT lpAddressLength)
4731 LPSTR workBuffer=NULL,ptrPort;
4733 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
4734 lpProtocolInfo, lpAddress, lpAddressLength );
4736 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
4740 WSASetLastError(WSAEINVAL);
4741 return SOCKET_ERROR;
4745 FIXME("ProtocolInfo not implemented.\n");
4747 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
4748 strlen(AddressString) + 1);
4751 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4752 return SOCKET_ERROR;
4755 strcpy(workBuffer, AddressString);
4757 switch(AddressFamily)
4761 struct in_addr inetaddr;
4763 /* If lpAddressLength is too small, tell caller the size we need */
4764 if (*lpAddressLength < sizeof(SOCKADDR_IN))
4766 *lpAddressLength = sizeof(SOCKADDR_IN);
4770 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
4772 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
4774 ptrPort = strchr(workBuffer, ':');
4777 ((LPSOCKADDR_IN)lpAddress)->sin_port = (WS_u_short)atoi(ptrPort+1);
4782 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
4785 if(inet_aton(workBuffer, &inetaddr) > 0)
4787 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
4798 struct in6_addr inetaddr;
4799 /* If lpAddressLength is too small, tell caller the size we need */
4800 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
4802 *lpAddressLength = sizeof(SOCKADDR_IN6);
4806 #ifdef HAVE_INET_PTON
4807 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
4809 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
4811 /* This one is a bit tricky. An IPv6 address contains colons, so the
4812 * check from IPv4 doesn't work like that. However, IPv6 addresses that
4813 * contain a port are written with braces like [fd12:3456:7890::1]:12345
4814 * so what we will do is to look for ']', check if the next char is a
4815 * colon, and if it is, parse the port as in IPv4. */
4817 ptrPort = strchr(workBuffer, ']');
4818 if(ptrPort && *(++ptrPort) == ':')
4820 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = (WS_u_short)atoi(ptrPort+1);
4825 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
4828 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
4830 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
4831 sizeof(struct in6_addr));
4835 #endif /* HAVE_INET_PTON */
4841 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
4842 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
4846 HeapFree(GetProcessHeap(), 0, workBuffer);
4849 WSASetLastError(res);
4850 return SOCKET_ERROR;
4853 /***********************************************************************
4854 * WSAStringToAddressW (WS2_32.81)
4856 * Does anybody know if this functions allows to use hebrew/arabic/chinese... digits?
4857 * If this should be the case, it would be required to map these digits
4858 * to Unicode digits (0-9) using FoldString first.
4860 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
4862 LPWSAPROTOCOL_INFOW lpProtocolInfo,
4863 LPSOCKADDR lpAddress,
4864 LPINT lpAddressLength)
4867 LPSTR workBuffer=NULL;
4868 WSAPROTOCOL_INFOA infoA;
4869 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
4871 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
4872 lpAddress, lpAddressLength );
4874 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
4876 /* if ProtocolInfo is available - convert to ANSI variant */
4879 lpProtoInfoA = &infoA;
4880 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
4882 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
4883 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
4885 WSASetLastError( WSAEINVAL);
4886 return SOCKET_ERROR;
4892 /* Translate AddressString to ANSI code page - assumes that only
4893 standard digits 0-9 are used with this API call */
4894 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
4895 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
4899 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
4900 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
4901 lpAddress,lpAddressLength);
4902 HeapFree( GetProcessHeap(), 0, workBuffer );
4906 res = WSA_NOT_ENOUGH_MEMORY;
4911 WSASetLastError(res);
4912 return SOCKET_ERROR;
4915 /***********************************************************************
4916 * WSAAddressToStringA (WS2_32.27)
4918 * See WSAAddressToStringW
4920 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
4921 LPWSAPROTOCOL_INFOA info, LPSTR string,
4925 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
4928 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
4930 if (!sockaddr || len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
4931 if (!string || !lenstr) return SOCKET_ERROR;
4933 /* sin_family is guaranteed to be the first u_short */
4934 switch(((SOCKADDR_IN *)sockaddr)->sin_family)
4937 sprintf( buffer, "%u.%u.%u.%u:%u",
4938 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
4939 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
4940 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
4941 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
4942 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
4944 p = strchr( buffer, ':' );
4945 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
4950 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
4952 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer, sizeof(buffer)))
4954 WSASetLastError(WSAEINVAL);
4955 return SOCKET_ERROR;
4961 WSASetLastError(WSAEINVAL);
4962 return SOCKET_ERROR;
4965 size = strlen( buffer ) + 1;
4970 WSASetLastError(WSAEFAULT);
4971 return SOCKET_ERROR;
4975 strcpy( string, buffer );
4979 /***********************************************************************
4980 * WSAAddressToStringW (WS2_32.28)
4982 * Convert a sockaddr address into a readable address string.
4985 * sockaddr [I] Pointer to a sockaddr structure.
4986 * len [I] Size of the sockaddr structure.
4987 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
4988 * string [I/O] Pointer to a buffer to receive the address string.
4989 * lenstr [I/O] Size of the receive buffer in WCHARs.
4993 * Failure: SOCKET_ERROR
4996 * The 'info' parameter is ignored.
4999 * Only supports AF_INET addresses.
5001 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
5002 LPWSAPROTOCOL_INFOW info, LPWSTR string,
5006 WCHAR buffer[22]; /* 12 digits + 3 dots + ':' + 5 digits + '\0' */
5007 static const WCHAR format[] = { '%','u','.','%','u','.','%','u','.','%','u',':','%','u',0 };
5010 TRACE( "(%p, %x, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
5012 if (!sockaddr || len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
5013 if (!string || !lenstr) return SOCKET_ERROR;
5015 /* sin_family is guaranteed to be the first u_short */
5016 if (((SOCKADDR_IN *)sockaddr)->sin_family != AF_INET) return SOCKET_ERROR;
5018 sprintfW( buffer, format,
5019 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
5020 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
5021 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
5022 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
5023 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
5025 p = strchrW( buffer, ':' );
5026 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
5028 size = strlenW( buffer ) + 1;
5033 return SOCKET_ERROR;
5037 lstrcpyW( string, buffer );
5041 /***********************************************************************
5042 * WSAEnumNameSpaceProvidersA (WS2_32.34)
5044 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
5046 FIXME( "(%p %p) Stub!\n", len, buffer );
5050 /***********************************************************************
5051 * WSAEnumNameSpaceProvidersW (WS2_32.35)
5053 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
5055 FIXME( "(%p %p) Stub!\n", len, buffer );
5059 /***********************************************************************
5060 * WSAGetQOSByName (WS2_32.41)
5062 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
5064 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
5068 /***********************************************************************
5069 * WSAGetServiceClassInfoA (WS2_32.42)
5071 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
5072 LPWSASERVICECLASSINFOA info )
5074 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
5076 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5077 return SOCKET_ERROR;
5080 /***********************************************************************
5081 * WSAGetServiceClassInfoW (WS2_32.43)
5083 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
5084 LPWSASERVICECLASSINFOW info )
5086 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
5088 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5089 return SOCKET_ERROR;
5092 /***********************************************************************
5093 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
5095 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
5097 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
5098 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5099 return SOCKET_ERROR;
5102 /***********************************************************************
5103 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
5105 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
5107 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
5108 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5109 return SOCKET_ERROR;
5112 /***********************************************************************
5113 * WSALookupServiceBeginA (WS2_32.59)
5115 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
5116 DWORD dwControlFlags,
5119 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
5121 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5122 return SOCKET_ERROR;
5125 /***********************************************************************
5126 * WSALookupServiceBeginW (WS2_32.60)
5128 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
5129 DWORD dwControlFlags,
5132 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
5134 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5135 return SOCKET_ERROR;
5138 /***********************************************************************
5139 * WSALookupServiceBeginW (WS2_32.61)
5141 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
5143 FIXME("(%p) Stub!\n", lookup );
5147 /***********************************************************************
5148 * WSALookupServiceNextA (WS2_32.62)
5150 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
5152 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
5156 /***********************************************************************
5157 * WSALookupServiceNextW (WS2_32.63)
5159 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
5161 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
5165 /***********************************************************************
5166 * WSANtohl (WS2_32.64)
5168 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
5170 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
5172 if (!lphostlong) return WSAEFAULT;
5174 *lphostlong = ntohl( netlong );
5178 /***********************************************************************
5179 * WSANtohs (WS2_32.65)
5181 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
5183 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
5185 if (!lphostshort) return WSAEFAULT;
5187 *lphostshort = ntohs( netshort );
5191 /***********************************************************************
5192 * WSAProviderConfigChange (WS2_32.66)
5194 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
5195 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
5197 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
5198 return SOCKET_ERROR;
5201 /***********************************************************************
5202 * WSARecvDisconnect (WS2_32.68)
5204 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
5206 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
5208 return WS_shutdown( s, 0 );
5211 /***********************************************************************
5212 * WSASetServiceA (WS2_32.76)
5214 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
5216 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5220 /***********************************************************************
5221 * WSASetServiceW (WS2_32.77)
5223 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
5225 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5229 /***********************************************************************
5230 * WSCEnableNSProvider (WS2_32.84)
5232 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
5234 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
5238 /***********************************************************************
5239 * WSCGetProviderPath (WS2_32.86)
5241 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
5243 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
5245 if (!errcode || !provider || !len) return WSAEFAULT;
5247 *errcode = WSAEINVAL;
5248 return SOCKET_ERROR;
5251 /***********************************************************************
5252 * WSCInstallNameSpace (WS2_32.87)
5254 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
5255 DWORD version, LPGUID provider )
5257 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
5258 namespace, version, debugstr_guid(provider) );
5262 /***********************************************************************
5263 * WSCUnInstallNameSpace (WS2_32.89)
5265 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
5267 FIXME("(%p) Stub!\n", lpProviderId);
5271 /***********************************************************************
5272 * WSCWriteProviderOrder (WS2_32.91)
5274 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
5276 FIXME("(%p 0x%08x) Stub!\n", entry, number);