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 switch (a->sa_family)
176 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
177 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
178 ntohs(((const struct sockaddr_in *)a)->sin_port));
183 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
185 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
187 p = "(unknown IPv6 address)";
188 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
189 p, ntohs(sin->sin6_port));
192 return wine_dbg_sprintf("{ family %d }", a->sa_family);
196 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
197 #define SOCKET2HANDLE(s) ((HANDLE)(s))
198 #define HANDLE2SOCKET(h) ((SOCKET)(h))
200 /****************************************************************
201 * Async IO declarations
202 ****************************************************************/
204 typedef struct ws2_async
208 LPWSAOVERLAPPED user_overlapped;
209 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
210 IO_STATUS_BLOCK local_iosb;
211 struct WS_sockaddr *addr;
214 int val; /* for send operations */
215 int *ptr; /* for recv operations */
218 unsigned int n_iovecs;
219 unsigned int first_iovec;
220 struct iovec iovec[1];
223 /****************************************************************/
225 /* ----------------------------------- internal data */
227 /* ws_... struct conversion flags */
229 typedef struct /* WSAAsyncSelect() control struct */
231 HANDLE service, event, sock;
237 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
238 #define WS_MAX_UDP_DATAGRAM 1024
239 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
241 /* hostent's, servent's and protent's are stored in one buffer per thread,
242 * as documented on MSDN for the functions that return any of the buffers */
243 struct per_thread_data
246 struct WS_hostent *he_buffer;
247 struct WS_servent *se_buffer;
248 struct WS_protoent *pe_buffer;
254 static INT num_startup; /* reference counter */
255 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
257 /* function prototypes */
258 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
259 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
260 static struct WS_servent *WS_dup_se(const struct servent* p_se);
262 int WSAIOCTL_GetInterfaceCount(void);
263 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
266 UINT wsaHerrno(int errnr);
268 #define MAP_OPTION(opt) { WS_##opt, opt }
270 static const int ws_sock_map[][2] =
272 MAP_OPTION( SO_DEBUG ),
273 MAP_OPTION( SO_ACCEPTCONN ),
274 MAP_OPTION( SO_REUSEADDR ),
275 MAP_OPTION( SO_KEEPALIVE ),
276 MAP_OPTION( SO_DONTROUTE ),
277 MAP_OPTION( SO_BROADCAST ),
278 MAP_OPTION( SO_LINGER ),
279 MAP_OPTION( SO_OOBINLINE ),
280 MAP_OPTION( SO_SNDBUF ),
281 MAP_OPTION( SO_RCVBUF ),
282 MAP_OPTION( SO_ERROR ),
283 MAP_OPTION( SO_TYPE ),
285 MAP_OPTION( SO_RCVTIMEO ),
288 MAP_OPTION( SO_SNDTIMEO ),
292 static const int ws_tcp_map[][2] =
295 MAP_OPTION( TCP_NODELAY ),
299 static const int ws_ip_map[][2] =
301 MAP_OPTION( IP_MULTICAST_IF ),
302 MAP_OPTION( IP_MULTICAST_TTL ),
303 MAP_OPTION( IP_MULTICAST_LOOP ),
304 MAP_OPTION( IP_ADD_MEMBERSHIP ),
305 MAP_OPTION( IP_DROP_MEMBERSHIP ),
306 MAP_OPTION( IP_OPTIONS ),
308 MAP_OPTION( IP_HDRINCL ),
310 MAP_OPTION( IP_TOS ),
311 MAP_OPTION( IP_TTL ),
314 static const int ws_af_map[][2] =
316 MAP_OPTION( AF_UNSPEC ),
317 MAP_OPTION( AF_INET ),
318 MAP_OPTION( AF_INET6 ),
320 MAP_OPTION( AF_IPX ),
322 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
325 static const int ws_socktype_map[][2] =
327 MAP_OPTION( SOCK_DGRAM ),
328 MAP_OPTION( SOCK_STREAM ),
329 MAP_OPTION( SOCK_RAW ),
330 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
333 static const int ws_proto_map[][2] =
335 MAP_OPTION( IPPROTO_IP ),
336 MAP_OPTION( IPPROTO_TCP ),
337 MAP_OPTION( IPPROTO_UDP ),
338 MAP_OPTION( IPPROTO_ICMP ),
339 MAP_OPTION( IPPROTO_IGMP ),
340 MAP_OPTION( IPPROTO_RAW ),
341 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
344 static const int ws_aiflag_map[][2] =
346 MAP_OPTION( AI_PASSIVE ),
347 MAP_OPTION( AI_CANONNAME ),
348 MAP_OPTION( AI_NUMERICHOST ),
349 /* Linux/UNIX knows a lot more. But Windows only
350 * has 3 as far as I could see. -Marcus
354 static const int ws_niflag_map[][2] =
356 MAP_OPTION( NI_NOFQDN ),
357 MAP_OPTION( NI_NUMERICHOST ),
358 MAP_OPTION( NI_NAMEREQD ),
359 MAP_OPTION( NI_NUMERICSERV ),
360 MAP_OPTION( NI_DGRAM ),
363 static const int ws_eai_map[][2] =
365 MAP_OPTION( EAI_AGAIN ),
366 MAP_OPTION( EAI_BADFLAGS ),
367 MAP_OPTION( EAI_FAIL ),
368 MAP_OPTION( EAI_FAMILY ),
369 MAP_OPTION( EAI_MEMORY ),
370 /* Note: EAI_NODATA is deprecated, but still
371 * used by Windows and Linux... We map the newer
372 * EAI_NONAME to EAI_NODATA for now until Windows
376 MAP_OPTION( EAI_NODATA ),
379 { WS_EAI_NODATA, EAI_NONAME },
382 MAP_OPTION( EAI_SERVICE ),
383 MAP_OPTION( EAI_SOCKTYPE ),
387 static const char magic_loopback_addr[] = {127, 12, 34, 56};
389 static inline DWORD NtStatusToWSAError( const DWORD status )
391 /* We only need to cover the status codes set by server async request handling */
395 case STATUS_SUCCESS: wserr = 0; break;
396 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
397 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
398 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
399 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
400 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
401 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
402 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
403 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
405 if ( status >= WSABASEERR && status <= WSABASEERR+1004 )
406 /* It is not an NT status code but a winsock error */
410 wserr = RtlNtStatusToDosError( status );
411 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
417 /* set last error code from NT status without mapping WSA errors */
418 static inline unsigned int set_error( unsigned int err )
422 err = NtStatusToWSAError( err );
428 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
431 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
436 static inline void release_sock_fd( SOCKET s, int fd )
438 wine_server_release_fd( SOCKET2HANDLE(s), fd );
441 static void _enable_event( HANDLE s, unsigned int event,
442 unsigned int sstate, unsigned int cstate )
444 SERVER_START_REQ( enable_socket_event )
446 req->handle = wine_server_obj_handle( s );
448 req->sstate = sstate;
449 req->cstate = cstate;
450 wine_server_call( req );
455 static int _is_blocking(SOCKET s)
458 SERVER_START_REQ( get_socket_event )
460 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
461 req->service = FALSE;
463 wine_server_call( req );
464 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
470 static unsigned int _get_sock_mask(SOCKET s)
473 SERVER_START_REQ( get_socket_event )
475 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
476 req->service = FALSE;
478 wine_server_call( req );
485 static void _sync_sock_state(SOCKET s)
487 /* do a dummy wineserver request in order to let
488 the wineserver run through its select loop once */
489 (void)_is_blocking(s);
492 static int _get_sock_error(SOCKET s, unsigned int bit)
494 int events[FD_MAX_EVENTS];
496 SERVER_START_REQ( get_socket_event )
498 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
499 req->service = FALSE;
501 wine_server_set_reply( req, events, sizeof(events) );
502 wine_server_call( req );
508 static struct per_thread_data *get_per_thread_data(void)
510 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
511 /* lazy initialization */
514 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
515 NtCurrentTeb()->WinSockData = ptb;
520 static void free_per_thread_data(void)
522 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
526 /* delete scratch buffers */
527 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
528 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
529 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
530 ptb->he_buffer = NULL;
531 ptb->se_buffer = NULL;
532 ptb->pe_buffer = NULL;
534 HeapFree( GetProcessHeap(), 0, ptb );
535 NtCurrentTeb()->WinSockData = NULL;
538 /***********************************************************************
539 * DllMain (WS2_32.init)
541 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
543 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
545 case DLL_PROCESS_ATTACH:
547 case DLL_PROCESS_DETACH:
548 free_per_thread_data();
551 case DLL_THREAD_DETACH:
552 free_per_thread_data();
558 /***********************************************************************
561 * Converts socket flags from Windows format.
562 * Return 1 if converted, 0 if not (error).
564 static int convert_sockopt(INT *level, INT *optname)
571 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
572 if( ws_sock_map[i][0] == *optname )
574 *optname = ws_sock_map[i][1];
578 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
581 *level = IPPROTO_TCP;
582 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
583 if ( ws_tcp_map[i][0] == *optname )
585 *optname = ws_tcp_map[i][1];
589 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
593 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
594 if (ws_ip_map[i][0] == *optname )
596 *optname = ws_ip_map[i][1];
600 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
602 default: FIXME("Unimplemented or unknown socket level\n");
607 /* ----------------------------------- Per-thread info (or per-process?) */
609 static char *strdup_lower(const char *str)
612 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
616 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
619 else SetLastError(WSAENOBUFS);
623 static inline int sock_error_p(int s)
625 unsigned int optval, optlen;
627 optlen = sizeof(optval);
628 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
629 if (optval) WARN("\t[%i] error: %d\n", s, optval);
633 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
634 * from an fd and return the value converted to milli seconds
635 * or -1 if there is an infinite time out */
636 static inline int get_rcvsnd_timeo( int fd, int optname)
639 unsigned int len = sizeof(tv);
640 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
642 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
643 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
648 /* macro wrappers for portability */
650 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
652 #define GET_RCVTIMEO(fd) (-1)
656 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
658 #define GET_SNDTIMEO(fd) (-1)
661 /* utility: given an fd, will block until one of the events occurs */
662 static inline int do_block( int fd, int events, int timeout )
670 while ((ret = poll(&pfd, 1, timeout)) < 0)
681 convert_af_w2u(int windowsaf) {
684 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
685 if (ws_af_map[i][0] == windowsaf)
686 return ws_af_map[i][1];
687 FIXME("unhandled Windows address family %d\n", windowsaf);
692 convert_af_u2w(int unixaf) {
695 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
696 if (ws_af_map[i][1] == unixaf)
697 return ws_af_map[i][0];
698 FIXME("unhandled UNIX address family %d\n", unixaf);
703 convert_proto_w2u(int windowsproto) {
706 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
707 if (ws_proto_map[i][0] == windowsproto)
708 return ws_proto_map[i][1];
709 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
714 convert_proto_u2w(int unixproto) {
717 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
718 if (ws_proto_map[i][1] == unixproto)
719 return ws_proto_map[i][0];
720 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
725 convert_socktype_w2u(int windowssocktype) {
728 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
729 if (ws_socktype_map[i][0] == windowssocktype)
730 return ws_socktype_map[i][1];
731 FIXME("unhandled Windows socket type %d\n", windowssocktype);
736 convert_socktype_u2w(int unixsocktype) {
739 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
740 if (ws_socktype_map[i][1] == unixsocktype)
741 return ws_socktype_map[i][0];
742 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
746 /* ----------------------------------- API -----
748 * Init / cleanup / error checking.
751 /***********************************************************************
752 * WSAStartup (WS2_32.115)
754 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
756 TRACE("verReq=%x\n", wVersionRequested);
758 if (LOBYTE(wVersionRequested) < 1)
759 return WSAVERNOTSUPPORTED;
761 if (!lpWSAData) return WSAEINVAL;
765 /* that's the whole of the negotiation for now */
766 lpWSAData->wVersion = wVersionRequested;
767 /* return winsock information */
768 lpWSAData->wHighVersion = 0x0202;
769 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
770 strcpy(lpWSAData->szSystemStatus, "Running" );
771 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
772 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
773 /* don't do anything with lpWSAData->lpVendorInfo */
774 /* (some apps don't allocate the space for this field) */
776 TRACE("succeeded\n");
781 /***********************************************************************
782 * WSACleanup (WS2_32.116)
784 INT WINAPI WSACleanup(void)
790 SetLastError(WSANOTINITIALISED);
795 /***********************************************************************
796 * WSAGetLastError (WINSOCK.111)
797 * WSAGetLastError (WS2_32.111)
799 INT WINAPI WSAGetLastError(void)
801 return GetLastError();
804 /***********************************************************************
805 * WSASetLastError (WS2_32.112)
807 void WINAPI WSASetLastError(INT iError) {
808 SetLastError(iError);
811 static struct WS_hostent *check_buffer_he(int size)
813 struct per_thread_data * ptb = get_per_thread_data();
816 if (ptb->he_len >= size ) return ptb->he_buffer;
817 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
819 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
820 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
821 return ptb->he_buffer;
824 static struct WS_servent *check_buffer_se(int size)
826 struct per_thread_data * ptb = get_per_thread_data();
829 if (ptb->se_len >= size ) return ptb->se_buffer;
830 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
832 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
833 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
834 return ptb->se_buffer;
837 static struct WS_protoent *check_buffer_pe(int size)
839 struct per_thread_data * ptb = get_per_thread_data();
842 if (ptb->pe_len >= size ) return ptb->pe_buffer;
843 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
845 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
846 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
847 return ptb->pe_buffer;
850 /* ----------------------------------- i/o APIs */
853 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf)== WS_AF_IPX || (pf) == WS_AF_INET6)
855 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf) == WS_AF_INET6)
859 /**********************************************************************/
861 /* Returns the length of the converted address if successful, 0 if it was too small to
864 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
865 union generic_unix_sockaddr *uaddr)
867 unsigned int uaddrlen = 0;
869 switch (wsaddr->sa_family)
874 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
875 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
877 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
880 uaddrlen = sizeof(struct sockaddr_ipx);
881 memset( uaddr, 0, uaddrlen );
882 uipx->sipx_family=AF_IPX;
883 uipx->sipx_port=wsipx->sa_socket;
884 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
887 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
888 #ifdef IPX_FRAME_NONE
889 uipx->sipx_type=IPX_FRAME_NONE;
895 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
896 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
898 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
899 * scope_id, one without.
901 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
902 uaddrlen = sizeof(struct sockaddr_in6);
903 memset( uaddr, 0, uaddrlen );
904 uin6->sin6_family = AF_INET6;
905 uin6->sin6_port = win6->sin6_port;
906 uin6->sin6_flowinfo = win6->sin6_flowinfo;
907 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
908 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
910 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
913 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
917 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
918 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
920 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
922 uaddrlen = sizeof(struct sockaddr_in);
923 memset( uaddr, 0, uaddrlen );
924 uin->sin_family = AF_INET;
925 uin->sin_port = win->sin_port;
926 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
930 /* Try to determine the needed space by the passed windows sockaddr space */
932 default: /* likely a ipv4 address */
933 case sizeof(struct WS_sockaddr_in):
934 uaddrlen = sizeof(struct sockaddr_in);
937 case sizeof(struct WS_sockaddr_ipx):
938 uaddrlen = sizeof(struct sockaddr_ipx);
941 case sizeof(struct WS_sockaddr_in6):
942 case sizeof(struct WS_sockaddr_in6_old):
943 uaddrlen = sizeof(struct sockaddr_in6);
946 memset( uaddr, 0, uaddrlen );
950 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
956 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
958 switch (uaddr->sa_family)
962 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
967 static const struct sockaddr_in6 emptyAddr;
968 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
969 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
973 static const struct sockaddr_in emptyAddr;
974 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
975 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
980 FIXME("unknown address family %d\n", uaddr->sa_family);
985 /* Returns 0 if successful, -1 if the buffer is too small */
986 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
990 switch(uaddr->sa_family)
995 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
996 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
999 switch (*wsaddrlen) /* how much can we copy? */
1003 *wsaddrlen = sizeof(*wsipx);
1004 wsipx->sa_socket=uipx->sipx_port;
1008 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1016 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1022 wsipx->sa_family=WS_AF_IPX;
1033 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1034 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1036 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1038 win6old->sin6_family = WS_AF_INET6;
1039 win6old->sin6_port = uin6->sin6_port;
1040 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1041 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1042 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1043 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1044 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1045 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1046 win6->sin6_scope_id = uin6->sin6_scope_id;
1047 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1053 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1054 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1056 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1058 win->sin_family = WS_AF_INET;
1059 win->sin_port = uin->sin_port;
1060 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1061 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1062 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1066 memset(wsaddr,0,*wsaddrlen);
1070 FIXME("Unknown address family %d\n", uaddr->sa_family);
1076 /**************************************************************************
1077 * Functions for handling overlapped I/O
1078 **************************************************************************/
1080 /* user APC called upon async completion */
1081 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1083 ws2_async *wsa = arg;
1085 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1086 iosb->Information, wsa->user_overlapped,
1088 HeapFree( GetProcessHeap(), 0, wsa );
1091 /***********************************************************************
1092 * WS2_recv (INTERNAL)
1094 * Workhorse for both synchronous and asynchronous recv() operations.
1096 static int WS2_recv( int fd, struct ws2_async *wsa )
1099 union generic_unix_sockaddr unix_sockaddr;
1102 hdr.msg_name = NULL;
1106 hdr.msg_namelen = sizeof(unix_sockaddr);
1107 hdr.msg_name = &unix_sockaddr;
1110 hdr.msg_namelen = 0;
1112 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1113 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1114 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1115 hdr.msg_accrights = NULL;
1116 hdr.msg_accrightslen = 0;
1118 hdr.msg_control = NULL;
1119 hdr.msg_controllen = 0;
1123 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1126 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1127 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1129 * quoting linux 2.6 net/ipv4/tcp.c:
1130 * "According to UNIX98, msg_name/msg_namelen are ignored
1131 * on connected socket. I was just happy when found this 8) --ANK"
1133 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1134 * connection-oriented sockets, so don't try to update lpFrom.
1136 if (wsa->addr && hdr.msg_namelen)
1137 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1142 /***********************************************************************
1143 * WS2_async_recv (INTERNAL)
1145 * Handler for overlapped recv() operations.
1147 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1149 ws2_async* wsa = user;
1154 case STATUS_ALERTED:
1155 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1158 result = WS2_recv( fd, wsa );
1159 wine_server_release_fd( wsa->hSocket, fd );
1162 status = STATUS_SUCCESS;
1163 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1167 if (errno == EINTR || errno == EAGAIN)
1169 status = STATUS_PENDING;
1170 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1175 status = wsaErrno(); /* FIXME: is this correct ???? */
1180 if (status != STATUS_PENDING)
1182 iosb->u.Status = status;
1183 iosb->Information = result;
1184 *apc = ws2_async_apc;
1189 /***********************************************************************
1190 * WS2_send (INTERNAL)
1192 * Workhorse for both synchronous and asynchronous send() operations.
1194 static int WS2_send( int fd, struct ws2_async *wsa )
1197 union generic_unix_sockaddr unix_addr;
1199 hdr.msg_name = NULL;
1200 hdr.msg_namelen = 0;
1204 hdr.msg_name = &unix_addr;
1205 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
1206 if ( !hdr.msg_namelen )
1212 #if defined(HAVE_IPX) && defined(SOL_IPX)
1213 if(wsa->addr->sa_family == WS_AF_IPX)
1215 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1217 unsigned int len=sizeof(int);
1219 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1220 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1221 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1222 * ipx type in the sockaddr_opx structure with the stored value.
1224 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1225 uipx->sipx_type = val;
1230 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1231 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1232 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1233 hdr.msg_accrights = NULL;
1234 hdr.msg_accrightslen = 0;
1236 hdr.msg_control = NULL;
1237 hdr.msg_controllen = 0;
1241 return sendmsg(fd, &hdr, wsa->flags);
1244 /***********************************************************************
1245 * WS2_async_send (INTERNAL)
1247 * Handler for overlapped send() operations.
1249 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1251 ws2_async* wsa = user;
1256 case STATUS_ALERTED:
1257 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1260 /* check to see if the data is ready (non-blocking) */
1261 result = WS2_send( fd, wsa );
1262 wine_server_release_fd( wsa->hSocket, fd );
1266 int totalLength = 0;
1268 status = STATUS_SUCCESS;
1269 for (i = 0; i < wsa->n_iovecs; i++)
1270 totalLength += wsa->iovec[i].iov_len;
1271 if (result < totalLength)
1272 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1276 if (errno == EINTR || errno == EAGAIN)
1278 status = STATUS_PENDING;
1279 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1283 /* We set the status to a winsock error code and check for that
1284 later in NtStatusToWSAError () */
1285 status = wsaErrno();
1291 if (status != STATUS_PENDING)
1293 iosb->u.Status = status;
1294 iosb->Information = result;
1295 *apc = ws2_async_apc;
1300 /***********************************************************************
1301 * WS2_async_shutdown (INTERNAL)
1303 * Handler for shutdown() operations on overlapped sockets.
1305 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
1307 ws2_async* wsa = user;
1312 case STATUS_ALERTED:
1313 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1316 switch ( wsa->type )
1318 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1319 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1321 wine_server_release_fd( wsa->hSocket, fd );
1322 status = err ? wsaErrno() : STATUS_SUCCESS;
1325 iosb->u.Status = status;
1326 *apc = ws2_async_apc;
1330 /***********************************************************************
1331 * WS2_register_async_shutdown (INTERNAL)
1333 * Helper function for WS_shutdown() on overlapped sockets.
1335 static int WS2_register_async_shutdown( SOCKET s, int type )
1337 struct ws2_async *wsa;
1340 TRACE("s %ld type %d\n", s, type);
1342 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1346 wsa->hSocket = SOCKET2HANDLE(s);
1348 wsa->completion_func = NULL;
1350 SERVER_START_REQ( register_async )
1353 req->async.handle = wine_server_obj_handle( wsa->hSocket );
1354 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
1355 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
1356 req->async.arg = wine_server_client_ptr( wsa );
1357 req->async.cvalue = 0;
1358 status = wine_server_call( req );
1362 if (status != STATUS_PENDING)
1364 HeapFree( GetProcessHeap(), 0, wsa );
1365 return NtStatusToWSAError( status );
1370 /***********************************************************************
1373 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1379 TRACE("socket %04lx\n", s );
1380 is_blocking = _is_blocking(s);
1385 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1386 if (fd == -1) return INVALID_SOCKET;
1388 do_block(fd, POLLIN, -1);
1389 _sync_sock_state(s); /* let wineserver notice connection */
1390 release_sock_fd( s, fd );
1391 /* retrieve any error codes from it */
1392 SetLastError(_get_sock_error(s, FD_ACCEPT_BIT));
1393 /* FIXME: care about the error? */
1395 SERVER_START_REQ( accept_socket )
1397 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1398 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1399 req->attributes = OBJ_INHERIT;
1400 set_error( wine_server_call( req ) );
1401 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
1406 if (addr) WS_getpeername(as, addr, addrlen32);
1409 } while (is_blocking);
1410 return INVALID_SOCKET;
1413 /***********************************************************************
1416 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1418 int fd = get_sock_fd( s, 0, NULL );
1419 int res = SOCKET_ERROR;
1421 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1425 if (!name || (name->sa_family && !SUPPORTED_PF(name->sa_family)))
1427 SetLastError(WSAEAFNOSUPPORT);
1431 union generic_unix_sockaddr uaddr;
1432 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1435 SetLastError(WSAEFAULT);
1440 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
1441 if (name->sa_family == WS_AF_INET6 &&
1442 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
1445 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
1447 release_sock_fd( s, fd );
1448 SetLastError(WSAEAFNOSUPPORT);
1449 return SOCKET_ERROR;
1453 if (name->sa_family == WS_AF_INET)
1455 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1456 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1458 /* Trying to bind to the default host interface, using
1459 * INADDR_ANY instead*/
1460 WARN("Trying to bind to magic IP address, using "
1461 "INADDR_ANY instead.\n");
1462 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
1465 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
1467 int loc_errno = errno;
1468 WARN("\tfailure - errno = %i\n", errno);
1473 SetLastError(WSAENOTSOCK);
1476 SetLastError(WSAEINVAL);
1479 SetLastError(wsaErrno());
1485 res=0; /* success */
1489 release_sock_fd( s, fd );
1494 /***********************************************************************
1495 * closesocket (WS2_32.3)
1497 int WINAPI WS_closesocket(SOCKET s)
1499 TRACE("socket %04lx\n", s);
1500 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
1501 return SOCKET_ERROR;
1504 /***********************************************************************
1505 * connect (WS2_32.4)
1507 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1509 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1511 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1515 union generic_unix_sockaddr uaddr;
1516 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1520 SetLastError(WSAEFAULT);
1524 if (name->sa_family == WS_AF_INET)
1526 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1527 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1529 /* Trying to connect to magic replace-loopback address,
1530 * assuming we really want to connect to localhost */
1531 TRACE("Trying to connect to magic IP address, using "
1532 "INADDR_LOOPBACK instead.\n");
1533 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
1537 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
1538 goto connect_success;
1541 if (errno == EINPROGRESS)
1543 /* tell wineserver that a connection is in progress */
1544 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1545 FD_CONNECT|FD_READ|FD_WRITE,
1546 FD_WINE_CONNECTED|FD_WINE_LISTENING);
1547 if (_is_blocking(s))
1551 do_block(fd, POLLIN | POLLOUT, -1);
1552 _sync_sock_state(s); /* let wineserver notice connection */
1553 /* retrieve any error codes from it */
1554 result = _get_sock_error(s, FD_CONNECT_BIT);
1556 SetLastError(result);
1559 goto connect_success;
1564 SetLastError(WSAEWOULDBLOCK);
1569 SetLastError(wsaErrno());
1571 release_sock_fd( s, fd );
1573 return SOCKET_ERROR;
1576 release_sock_fd( s, fd );
1577 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1578 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1579 FD_CONNECT|FD_WINE_LISTENING);
1583 /***********************************************************************
1584 * WSAConnect (WS2_32.30)
1586 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
1587 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1588 LPQOS lpSQOS, LPQOS lpGQOS )
1590 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1591 FIXME("unsupported parameters!\n");
1592 return WS_connect( s, name, namelen );
1596 /***********************************************************************
1597 * getpeername (WS2_32.5)
1599 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1604 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, *namelen);
1606 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1607 if( (name == NULL) || (namelen == NULL) )
1609 SetLastError( WSAEFAULT );
1610 return SOCKET_ERROR;
1613 fd = get_sock_fd( s, 0, NULL );
1618 union generic_unix_sockaddr uaddr;
1619 unsigned int uaddrlen = sizeof(uaddr);
1621 if (getpeername(fd, &uaddr.addr, &uaddrlen) != 0)
1623 SetLastError(wsaErrno());
1625 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1627 /* The buffer was too small */
1628 SetLastError(WSAEFAULT);
1634 release_sock_fd( s, fd );
1639 /***********************************************************************
1640 * getsockname (WS2_32.6)
1642 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1647 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
1649 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1650 if( (name == NULL) || (namelen == NULL) )
1652 SetLastError( WSAEFAULT );
1653 return SOCKET_ERROR;
1656 fd = get_sock_fd( s, 0, NULL );
1661 union generic_unix_sockaddr uaddr;
1662 unsigned int uaddrlen = sizeof(uaddr);
1664 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
1666 SetLastError(wsaErrno());
1668 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
1670 SetLastError(WSAEINVAL);
1672 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1674 /* The buffer was too small */
1675 SetLastError(WSAEFAULT);
1681 release_sock_fd( s, fd );
1686 /***********************************************************************
1687 * getsockopt (WS2_32.7)
1689 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1690 INT optname, char *optval, INT *optlen)
1695 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
1696 s, level, optname, optval, *optlen);
1704 /* Handle common cases. The special cases are below, sorted
1706 case WS_SO_ACCEPTCONN:
1707 case WS_SO_BROADCAST:
1710 case WS_SO_KEEPALIVE:
1711 case WS_SO_OOBINLINE:
1713 case WS_SO_REUSEADDR:
1716 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1717 return SOCKET_ERROR;
1718 convert_sockopt(&level, &optname);
1719 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1721 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1724 release_sock_fd( s, fd );
1727 case WS_SO_DONTLINGER:
1729 struct linger lingval;
1730 unsigned int len = sizeof(struct linger);
1732 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
1734 SetLastError(WSAEFAULT);
1735 return SOCKET_ERROR;
1737 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1738 return SOCKET_ERROR;
1740 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1742 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1747 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
1748 *optlen = sizeof(BOOL);
1751 release_sock_fd( s, fd );
1755 /* As mentioned in setsockopt, Windows ignores this, so we
1756 * always return true here */
1757 case WS_SO_DONTROUTE:
1758 if (!optlen || *optlen < sizeof(BOOL) || !optval)
1760 SetLastError(WSAEFAULT);
1761 return SOCKET_ERROR;
1763 *(BOOL *)optval = TRUE;
1764 *optlen = sizeof(BOOL);
1769 struct linger lingval;
1770 unsigned int len = sizeof(struct linger);
1772 /* struct linger and LINGER have different sizes */
1773 if (!optlen || *optlen < sizeof(LINGER) || !optval)
1775 SetLastError(WSAEFAULT);
1776 return SOCKET_ERROR;
1778 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1779 return SOCKET_ERROR;
1781 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1783 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1788 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
1789 ((LINGER *)optval)->l_linger = lingval.l_linger;
1790 *optlen = sizeof(struct linger);
1793 release_sock_fd( s, fd );
1797 case WS_SO_MAX_MSG_SIZE:
1798 if (!optlen || *optlen < sizeof(int) || !optval)
1800 SetLastError(WSAEFAULT);
1801 return SOCKET_ERROR;
1803 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
1804 *(int *)optval = 65507;
1805 *optlen = sizeof(int);
1808 /* SO_OPENTYPE does not require a valid socket handle. */
1809 case WS_SO_OPENTYPE:
1810 if (!optlen || *optlen < sizeof(int) || !optval)
1812 SetLastError(WSAEFAULT);
1813 return SOCKET_ERROR;
1815 *(int *)optval = get_per_thread_data()->opentype;
1816 *optlen = sizeof(int);
1817 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
1821 case WS_SO_RCVTIMEO:
1824 case WS_SO_SNDTIMEO:
1826 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
1829 unsigned int len = sizeof(struct timeval);
1831 if (!optlen || *optlen < sizeof(int)|| !optval)
1833 SetLastError(WSAEFAULT);
1834 return SOCKET_ERROR;
1836 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1837 return SOCKET_ERROR;
1839 convert_sockopt(&level, &optname);
1840 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
1842 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1847 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1848 *optlen = sizeof(int);
1851 release_sock_fd( s, fd );
1856 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
1857 SetLastError(WSAENOPROTOOPT);
1858 return SOCKET_ERROR;
1859 } /* end switch(optname) */
1860 }/* end case WS_SOL_SOCKET */
1864 struct WS_sockaddr_ipx addr;
1865 IPX_ADDRESS_DATA *data;
1870 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
1872 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
1879 socklen_t len=sizeof(struct ipx);
1880 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
1883 *optval = (int)val.ipx_pt;
1886 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
1887 release_sock_fd( s, fd );
1892 * On a Win2000 system with one network card there are usually
1893 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
1894 * Using this call you can then retrieve info about this all.
1895 * In case of Linux it is a bit different. Usually you have
1896 * only "one" device active and further it is not possible to
1897 * query things like the linkspeed.
1899 FIXME("IPX_ADDRESS\n");
1900 namelen = sizeof(struct WS_sockaddr_ipx);
1901 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
1902 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
1904 data = (IPX_ADDRESS_DATA*)optval;
1905 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
1906 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
1907 data->adapternum = 0;
1908 data->wan = FALSE; /* We are not on a wan for now .. */
1909 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
1910 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
1911 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
1912 * note 1MB = 1000kB in this case */
1915 case IPX_MAX_ADAPTER_NUM:
1916 FIXME("IPX_MAX_ADAPTER_NUM\n");
1917 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
1921 FIXME("IPX optname:%x\n", optname);
1922 return SOCKET_ERROR;
1923 }/* end switch(optname) */
1924 } /* end case NSPROTO_IPX */
1926 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
1927 case WS_IPPROTO_TCP:
1930 case WS_TCP_NODELAY:
1931 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1932 return SOCKET_ERROR;
1933 convert_sockopt(&level, &optname);
1934 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1936 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1939 release_sock_fd( s, fd );
1942 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
1943 return SOCKET_ERROR;
1948 case WS_IP_ADD_MEMBERSHIP:
1949 case WS_IP_DROP_MEMBERSHIP:
1953 case WS_IP_MULTICAST_IF:
1954 case WS_IP_MULTICAST_LOOP:
1955 case WS_IP_MULTICAST_TTL:
1959 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1960 return SOCKET_ERROR;
1961 convert_sockopt(&level, &optname);
1962 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1964 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1967 release_sock_fd( s, fd );
1969 case WS_IP_DONTFRAGMENT:
1970 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
1971 *(BOOL*)optval = FALSE;
1974 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
1975 return SOCKET_ERROR;
1978 FIXME("Unknown level: 0x%08x\n", level);
1979 return SOCKET_ERROR;
1980 } /* end switch(level) */
1983 /***********************************************************************
1987 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
1989 return htonl(hostlong);
1993 /***********************************************************************
1997 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
1999 return htons(hostshort);
2002 /***********************************************************************
2003 * WSAHtonl (WS2_32.46)
2004 * From MSDN description of error codes, this function should also
2005 * check if WinSock has been initialized and the socket is a valid
2006 * socket. But why? This function only translates a host byte order
2007 * u_long into a network byte order u_long...
2009 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
2013 *lpnetlong = htonl(hostlong);
2016 WSASetLastError(WSAEFAULT);
2017 return SOCKET_ERROR;
2020 /***********************************************************************
2021 * WSAHtons (WS2_32.47)
2022 * From MSDN description of error codes, this function should also
2023 * check if WinSock has been initialized and the socket is a valid
2024 * socket. But why? This function only translates a host byte order
2025 * u_short into a network byte order u_short...
2027 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2032 *lpnetshort = htons(hostshort);
2035 WSASetLastError(WSAEFAULT);
2036 return SOCKET_ERROR;
2040 /***********************************************************************
2041 * inet_addr (WINSOCK.10)
2042 * inet_addr (WS2_32.11)
2044 WS_u_long WINAPI WS_inet_addr(const char *cp)
2046 if (!cp) return INADDR_NONE;
2047 return inet_addr(cp);
2051 /***********************************************************************
2052 * ntohl (WINSOCK.14)
2055 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2057 return ntohl(netlong);
2061 /***********************************************************************
2062 * ntohs (WINSOCK.15)
2065 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2067 return ntohs(netshort);
2071 /***********************************************************************
2072 * inet_ntoa (WS2_32.12)
2074 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2076 /* use "buffer for dummies" here because some applications have a
2077 * propensity to decode addresses in ws_hostent structure without
2078 * saving them first...
2080 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2082 char* s = inet_ntoa(*((struct in_addr*)&in));
2088 SetLastError(wsaErrno());
2092 /**********************************************************************
2093 * WSAIoctl (WS2_32.50)
2096 INT WINAPI WSAIoctl(SOCKET s,
2097 DWORD dwIoControlCode,
2100 LPVOID lpbOutBuffer,
2102 LPDWORD lpcbBytesReturned,
2103 LPWSAOVERLAPPED lpOverlapped,
2104 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2106 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
2107 s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpbOutBuffer,
2108 cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
2110 switch( dwIoControlCode )
2113 if (cbInBuffer != sizeof(WS_u_long)) {
2114 WSASetLastError(WSAEFAULT);
2115 return SOCKET_ERROR;
2117 return WS_ioctlsocket( s, WS_FIONBIO, lpvInBuffer);
2120 if (cbOutBuffer != sizeof(WS_u_long)) {
2121 WSASetLastError(WSAEFAULT);
2122 return SOCKET_ERROR;
2124 return WS_ioctlsocket( s, WS_FIONREAD, lpbOutBuffer);
2126 case WS_SIO_GET_INTERFACE_LIST:
2128 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
2129 DWORD size, numInt, apiReturn;
2132 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
2136 WSASetLastError(WSAEFAULT);
2137 return SOCKET_ERROR;
2139 if (!lpcbBytesReturned)
2141 WSASetLastError(WSAEFAULT);
2142 return SOCKET_ERROR;
2145 fd = get_sock_fd( s, 0, NULL );
2146 if (fd == -1) return SOCKET_ERROR;
2148 apiReturn = GetAdaptersInfo(NULL, &size);
2149 if (apiReturn == ERROR_NO_DATA)
2153 else if (apiReturn == ERROR_BUFFER_OVERFLOW)
2155 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
2159 if (GetAdaptersInfo(table, &size) == NO_ERROR)
2161 PIP_ADAPTER_INFO ptr;
2163 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > cbOutBuffer)
2165 WARN("Buffer too small = %u, cbOutBuffer = %u\n", size, cbOutBuffer);
2166 HeapFree(GetProcessHeap(),0,table);
2167 release_sock_fd( s, fd );
2168 WSASetLastError(WSAEFAULT);
2169 return SOCKET_ERROR;
2171 for (ptr = table, numInt = 0; ptr;
2172 ptr = ptr->Next, intArray++, numInt++)
2174 unsigned int addr, mask, bcast;
2175 struct ifreq ifInfo;
2177 /* Socket Status Flags */
2178 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
2179 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2181 ERR("Error obtaining status flags for socket!\n");
2182 HeapFree(GetProcessHeap(),0,table);
2183 release_sock_fd( s, fd );
2184 WSASetLastError(WSAEINVAL);
2185 return SOCKET_ERROR;
2189 /* set flags; the values of IFF_* are not the same
2190 under Linux and Windows, therefore must generate
2192 intArray->iiFlags = 0;
2193 if (ifInfo.ifr_flags & IFF_BROADCAST)
2194 intArray->iiFlags |= WS_IFF_BROADCAST;
2195 #ifdef IFF_POINTOPOINT
2196 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
2197 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
2199 if (ifInfo.ifr_flags & IFF_LOOPBACK)
2200 intArray->iiFlags |= WS_IFF_LOOPBACK;
2201 if (ifInfo.ifr_flags & IFF_UP)
2202 intArray->iiFlags |= WS_IFF_UP;
2203 if (ifInfo.ifr_flags & IFF_MULTICAST)
2204 intArray->iiFlags |= WS_IFF_MULTICAST;
2207 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
2208 mask = inet_addr(ptr->IpAddressList.IpMask.String);
2209 bcast = addr | ~mask;
2210 intArray->iiAddress.AddressIn.sin_family = AF_INET;
2211 intArray->iiAddress.AddressIn.sin_port = 0;
2212 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
2214 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2215 intArray->iiNetmask.AddressIn.sin_port = 0;
2216 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
2218 intArray->iiBroadcastAddress.AddressIn.sin_family =
2220 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
2221 intArray->iiBroadcastAddress.AddressIn.sin_addr.
2227 ERR("Unable to get interface table!\n");
2228 release_sock_fd( s, fd );
2229 HeapFree(GetProcessHeap(),0,table);
2230 WSASetLastError(WSAEINVAL);
2231 return SOCKET_ERROR;
2233 HeapFree(GetProcessHeap(),0,table);
2237 release_sock_fd( s, fd );
2238 WSASetLastError(WSAEINVAL);
2239 return SOCKET_ERROR;
2244 ERR("Unable to get interface table!\n");
2245 release_sock_fd( s, fd );
2246 WSASetLastError(WSAEINVAL);
2247 return SOCKET_ERROR;
2249 /* Calculate the size of the array being returned */
2250 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2251 release_sock_fd( s, fd );
2255 case WS_SIO_ADDRESS_LIST_CHANGE:
2256 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
2257 /* FIXME: error and return code depend on whether socket was created
2258 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
2261 case WS_SIO_ADDRESS_LIST_QUERY:
2265 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
2267 if (!lpcbBytesReturned)
2269 WSASetLastError(WSAEFAULT);
2270 return SOCKET_ERROR;
2273 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
2275 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
2278 if (!table || GetAdaptersInfo(table, &size))
2280 HeapFree(GetProcessHeap(), 0, table);
2281 WSASetLastError(WSAEINVAL);
2282 return SOCKET_ERROR;
2285 for (p = table, num = 0; p; p = p->Next)
2286 if (p->IpAddressList.IpAddress.String[0]) num++;
2288 need = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
2289 need += sizeof(SOCKADDR) * num;
2290 *lpcbBytesReturned = need;
2292 if (need > cbOutBuffer)
2294 HeapFree(GetProcessHeap(), 0, table);
2295 WSASetLastError(WSAEFAULT);
2296 return SOCKET_ERROR;
2303 SOCKET_ADDRESS_LIST *sa_list = (SOCKET_ADDRESS_LIST *)lpbOutBuffer;
2304 SOCKADDR_IN *sockaddr;
2306 sa = sa_list->Address;
2307 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
2308 sa_list->iAddressCount = num;
2310 for (p = table, i = 0; p; p = p->Next)
2312 if (!p->IpAddressList.IpAddress.String[0]) continue;
2314 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
2315 sa[i].iSockaddrLength = sizeof(SOCKADDR);
2317 sockaddr[i].sin_family = AF_INET;
2318 sockaddr[i].sin_port = 0;
2319 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
2324 HeapFree(GetProcessHeap(), 0, table);
2329 WARN("unable to get IP address list\n");
2330 WSASetLastError(WSAEINVAL);
2331 return SOCKET_ERROR;
2335 FIXME("SIO_FLUSH: stub.\n");
2338 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
2339 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(lpvInBuffer));
2340 WSASetLastError(WSAEOPNOTSUPP);
2341 return SOCKET_ERROR;
2343 case WS_SIO_KEEPALIVE_VALS:
2346 struct tcp_keepalive *k = lpvInBuffer;
2347 int keepalive = k->onoff ? 1 : 0;
2348 int keepidle = k->keepalivetime / 1000;
2349 int keepintvl = k->keepaliveinterval / 1000;
2353 WSASetLastError(WSAEINVAL);
2354 return SOCKET_ERROR;
2357 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
2359 fd = get_sock_fd(s, 0, NULL);
2360 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
2362 release_sock_fd(s, fd);
2363 WSASetLastError(WSAEINVAL);
2364 return SOCKET_ERROR;
2366 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
2367 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
2369 release_sock_fd(s, fd);
2370 WSASetLastError(WSAEINVAL);
2371 return SOCKET_ERROR;
2373 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
2375 release_sock_fd(s, fd);
2376 WSASetLastError(WSAEINVAL);
2377 return SOCKET_ERROR;
2380 FIXME("ignoring keepalive interval and timeout\n");
2383 release_sock_fd(s, fd);
2387 FIXME("unsupported WS_IOCTL cmd (%08x)\n", dwIoControlCode);
2388 WSASetLastError(WSAEOPNOTSUPP);
2389 return SOCKET_ERROR;
2396 /***********************************************************************
2397 * ioctlsocket (WS2_32.10)
2399 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
2404 TRACE("socket %04lx, cmd %08x, ptr %p\n", s, cmd, argp);
2405 /* broken apps like defcon pass the argp value directly instead of a pointer to it */
2406 if(IS_INTRESOURCE(argp))
2408 SetLastError(WSAEFAULT);
2409 return SOCKET_ERROR;
2419 if( _get_sock_mask(s) )
2421 /* AsyncSelect()'ed sockets are always nonblocking */
2422 if (*argp) return 0;
2423 SetLastError(WSAEINVAL);
2424 return SOCKET_ERROR;
2427 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
2429 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
2437 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2438 SetLastError(WSAEINVAL);
2439 return SOCKET_ERROR;
2441 case SIOCGIFBRDADDR:
2442 case SIOCGIFNETMASK:
2444 /* These don't need any special handling. They are used by
2445 WsControl, and are here to suppress an unnecessary warning. */
2449 /* Netscape tries hard to use bogus ioctl 0x667e */
2450 /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
2451 * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
2453 WARN("\tunknown WS_IOCTL cmd (%08x)\n", cmd);
2457 fd = get_sock_fd( s, 0, NULL );
2460 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2462 release_sock_fd( s, fd );
2465 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2466 release_sock_fd( s, fd );
2468 return SOCKET_ERROR;
2471 /***********************************************************************
2472 * listen (WS2_32.13)
2474 int WINAPI WS_listen(SOCKET s, int backlog)
2476 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2478 TRACE("socket %04lx, backlog %d\n", s, backlog);
2481 if (listen(fd, backlog) == 0)
2483 release_sock_fd( s, fd );
2484 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
2486 FD_CONNECT|FD_WINE_CONNECTED);
2489 SetLastError(wsaErrno());
2490 release_sock_fd( s, fd );
2492 return SOCKET_ERROR;
2495 /***********************************************************************
2498 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2500 DWORD n, dwFlags = flags;
2506 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2507 return SOCKET_ERROR;
2512 /***********************************************************************
2513 * recvfrom (WS2_32.17)
2515 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2516 struct WS_sockaddr *from, int *fromlen)
2518 DWORD n, dwFlags = flags;
2524 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2525 return SOCKET_ERROR;
2530 /* allocate a poll array for the corresponding fd sets */
2531 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
2532 const WS_fd_set *exceptfds, int *count_ptr )
2534 unsigned int i, j = 0, count = 0;
2537 if (readfds) count += readfds->fd_count;
2538 if (writefds) count += writefds->fd_count;
2539 if (exceptfds) count += exceptfds->fd_count;
2541 if (!count) return NULL;
2542 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0])))) return NULL;
2544 for (i = 0; i < readfds->fd_count; i++, j++)
2546 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
2547 fds[j].events = POLLIN;
2551 for (i = 0; i < writefds->fd_count; i++, j++)
2553 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
2554 fds[j].events = POLLOUT;
2558 for (i = 0; i < exceptfds->fd_count; i++, j++)
2560 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
2561 fds[j].events = POLLHUP;
2567 /* release the file descriptor obtained in fd_sets_to_poll */
2568 /* must be called with the original fd_set arrays, before calling get_poll_results */
2569 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
2570 const WS_fd_set *exceptfds, struct pollfd *fds )
2572 unsigned int i, j = 0;
2576 for (i = 0; i < readfds->fd_count; i++, j++)
2577 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
2581 for (i = 0; i < writefds->fd_count; i++, j++)
2582 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
2586 for (i = 0; i < exceptfds->fd_count; i++, j++)
2587 if (fds[j].fd != -1)
2589 /* make sure we have a real error before releasing the fd */
2590 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
2591 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
2596 /* map the poll results back into the Windows fd sets */
2597 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
2598 const struct pollfd *fds )
2600 unsigned int i, j = 0, k, total = 0;
2604 for (i = k = 0; i < readfds->fd_count; i++, j++)
2605 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
2606 readfds->fd_count = k;
2611 for (i = k = 0; i < writefds->fd_count; i++, j++)
2612 if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
2613 writefds->fd_count = k;
2618 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
2619 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
2620 exceptfds->fd_count = k;
2627 /***********************************************************************
2628 * select (WS2_32.18)
2630 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
2631 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
2632 const struct WS_timeval* ws_timeout)
2634 struct pollfd *pollfds;
2635 int count, ret, timeout = -1;
2637 TRACE("read %p, write %p, excp %p timeout %p\n",
2638 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
2640 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )) && count)
2642 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2643 return SOCKET_ERROR;
2646 if (ws_timeout) timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
2648 ret = poll( pollfds, count, timeout );
2649 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2651 if (ret == -1) SetLastError(wsaErrno());
2652 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2653 HeapFree( GetProcessHeap(), 0, pollfds );
2657 /* helper to send completion messages for client-only i/o operation case */
2658 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
2663 SERVER_START_REQ( add_fd_completion )
2665 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
2666 req->cvalue = CompletionValue;
2667 req->status = CompletionStatus;
2668 req->information = Information;
2669 status = wine_server_call( req );
2675 /***********************************************************************
2678 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
2684 wsabuf.buf = (char*) buf;
2686 if ( WSASendTo( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
2687 return SOCKET_ERROR;
2692 /***********************************************************************
2693 * WSASend (WS2_32.72)
2695 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2696 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2697 LPWSAOVERLAPPED lpOverlapped,
2698 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2700 return WSASendTo( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
2701 NULL, 0, lpOverlapped, lpCompletionRoutine );
2704 /***********************************************************************
2705 * WSASendDisconnect (WS2_32.73)
2707 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
2709 return WS_shutdown( s, SD_SEND );
2713 /***********************************************************************
2714 * WSASendTo (WS2_32.74)
2716 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2717 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2718 const struct WS_sockaddr *to, int tolen,
2719 LPWSAOVERLAPPED lpOverlapped,
2720 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2722 unsigned int i, options;
2724 struct ws2_async *wsa;
2725 int totalLength = 0;
2726 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
2728 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
2729 s, lpBuffers, dwBufferCount, dwFlags,
2730 to, tolen, lpOverlapped, lpCompletionRoutine);
2732 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
2733 TRACE( "fd=%d, options=%x\n", fd, options );
2735 if ( fd == -1 ) return SOCKET_ERROR;
2737 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
2743 wsa->hSocket = SOCKET2HANDLE(s);
2744 wsa->addr = (struct WS_sockaddr *)to;
2745 wsa->addrlen.val = tolen;
2746 wsa->flags = dwFlags;
2747 wsa->n_iovecs = dwBufferCount;
2748 wsa->first_iovec = 0;
2749 for ( i = 0; i < dwBufferCount; i++ )
2751 wsa->iovec[i].iov_base = lpBuffers[i].buf;
2752 wsa->iovec[i].iov_len = lpBuffers[i].len;
2753 totalLength += lpBuffers[i].len;
2756 if (!lpNumberOfBytesSent)
2764 n = WS2_send( fd, wsa );
2765 if (n != -1 || errno != EINTR) break;
2767 if (n == -1 && errno != EAGAIN)
2770 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
2774 if ((lpOverlapped || lpCompletionRoutine) &&
2775 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
2777 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
2779 wsa->user_overlapped = lpOverlapped;
2780 wsa->completion_func = lpCompletionRoutine;
2781 release_sock_fd( s, fd );
2785 iosb->u.Status = STATUS_PENDING;
2786 iosb->Information = 0;
2788 SERVER_START_REQ( register_async )
2790 req->type = ASYNC_TYPE_WRITE;
2791 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2792 req->async.callback = wine_server_client_ptr( WS2_async_send );
2793 req->async.iosb = wine_server_client_ptr( iosb );
2794 req->async.arg = wine_server_client_ptr( wsa );
2795 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
2796 req->async.cvalue = cvalue;
2797 err = wine_server_call( req );
2801 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
2802 WSASetLastError( NtStatusToWSAError( err ));
2803 return SOCKET_ERROR;
2806 iosb->u.Status = STATUS_SUCCESS;
2807 iosb->Information = n;
2808 *lpNumberOfBytesSent = n;
2809 if (!wsa->completion_func)
2811 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
2812 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
2813 HeapFree( GetProcessHeap(), 0, wsa );
2815 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
2816 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
2821 if ( _is_blocking(s) )
2823 /* On a blocking non-overlapped stream socket,
2824 * sending blocks until the entire buffer is sent. */
2825 DWORD timeout_start = GetTickCount();
2827 *lpNumberOfBytesSent = 0;
2829 while (wsa->first_iovec < dwBufferCount)
2832 int timeout = GET_SNDTIMEO(fd);
2836 *lpNumberOfBytesSent += n;
2837 while (wsa->first_iovec < dwBufferCount && wsa->iovec[wsa->first_iovec].iov_len <= n)
2838 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2839 if (wsa->first_iovec >= dwBufferCount) break;
2840 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2841 wsa->iovec[wsa->first_iovec].iov_len -= n;
2846 timeout -= GetTickCount() - timeout_start;
2847 if (timeout < 0) timeout = 0;
2851 pfd.events = POLLOUT;
2853 if (!timeout || !poll( &pfd, 1, timeout ))
2856 goto error; /* msdn says a timeout in send is fatal */
2859 n = WS2_send( fd, wsa );
2860 if (n == -1 && errno != EAGAIN && errno != EINTR)
2867 else /* non-blocking */
2869 if (n < totalLength)
2870 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
2873 err = WSAEWOULDBLOCK;
2876 *lpNumberOfBytesSent = n;
2879 TRACE(" -> %i bytes\n", *lpNumberOfBytesSent);
2881 HeapFree( GetProcessHeap(), 0, wsa );
2882 release_sock_fd( s, fd );
2887 HeapFree( GetProcessHeap(), 0, wsa );
2888 release_sock_fd( s, fd );
2889 WARN(" -> ERROR %d\n", err);
2890 WSASetLastError(err);
2891 return SOCKET_ERROR;
2894 /***********************************************************************
2895 * sendto (WS2_32.20)
2897 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
2898 const struct WS_sockaddr *to, int tolen)
2904 wsabuf.buf = (char*) buf;
2906 if ( WSASendTo(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
2907 return SOCKET_ERROR;
2912 /***********************************************************************
2913 * setsockopt (WS2_32.21)
2915 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
2916 const char *optval, int optlen)
2920 struct linger linger;
2921 struct timeval tval;
2923 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2924 s, level, optname, optval, optlen);
2926 /* some broken apps pass the value directly instead of a pointer to it */
2927 if(IS_INTRESOURCE(optval))
2929 SetLastError(WSAEFAULT);
2930 return SOCKET_ERROR;
2938 /* Some options need some conversion before they can be sent to
2939 * setsockopt. The conversions are done here, then they will fall though
2940 * to the general case. Special options that are not passed to
2941 * setsockopt follow below that.*/
2943 case WS_SO_DONTLINGER:
2944 linger.l_onoff = *((const int*)optval) ? 0: 1;
2945 linger.l_linger = 0;
2947 optname = SO_LINGER;
2948 optval = (char*)&linger;
2949 optlen = sizeof(struct linger);
2953 linger.l_onoff = ((LINGER*)optval)->l_onoff;
2954 linger.l_linger = ((LINGER*)optval)->l_linger;
2955 /* FIXME: what is documented behavior if SO_LINGER optval
2958 optname = SO_LINGER;
2959 optval = (char*)&linger;
2960 optlen = sizeof(struct linger);
2964 if (*(const int*)optval < 2048)
2966 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
2971 /* The options listed here don't need any special handling. Thanks to
2972 * the conversion happening above, options from there will fall through
2974 case WS_SO_ACCEPTCONN:
2975 case WS_SO_BROADCAST:
2977 case WS_SO_KEEPALIVE:
2978 case WS_SO_OOBINLINE:
2979 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
2980 * however, using it the BSD way fixes bug 8513 and seems to be what
2981 * most programmers assume, anyway */
2982 case WS_SO_REUSEADDR:
2985 convert_sockopt(&level, &optname);
2988 /* SO_DEBUG is a privileged operation, ignore it. */
2990 TRACE("Ignoring SO_DEBUG\n");
2993 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
2994 * socket. According to MSDN, this option is silently ignored.*/
2995 case WS_SO_DONTROUTE:
2996 TRACE("Ignoring SO_DONTROUTE\n");
2999 /* Stops two sockets from being bound to the same port. Always happens
3000 * on unix systems, so just drop it. */
3001 case WS_SO_EXCLUSIVEADDRUSE:
3002 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
3005 /* SO_OPENTYPE does not require a valid socket handle. */
3006 case WS_SO_OPENTYPE:
3007 if (!optlen || optlen < sizeof(int) || !optval)
3009 SetLastError(WSAEFAULT);
3010 return SOCKET_ERROR;
3012 get_per_thread_data()->opentype = *(const int *)optval;
3013 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3017 case WS_SO_RCVTIMEO:
3020 case WS_SO_SNDTIMEO:
3022 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3023 if (optval && optlen == sizeof(UINT32)) {
3024 /* WinSock passes milliseconds instead of struct timeval */
3025 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
3026 tval.tv_sec = *(const UINT32*)optval / 1000;
3027 /* min of 500 milliseconds */
3028 if (tval.tv_sec == 0 && tval.tv_usec < 500000)
3029 tval.tv_usec = 500000;
3030 optlen = sizeof(struct timeval);
3031 optval = (char*)&tval;
3032 } else if (optlen == sizeof(struct timeval)) {
3033 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
3035 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
3038 convert_sockopt(&level, &optname);
3043 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3044 SetLastError(WSAENOPROTOOPT);
3045 return SOCKET_ERROR;
3047 break; /* case WS_SOL_SOCKET */
3054 fd = get_sock_fd( s, 0, NULL );
3055 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
3057 /* We try to set the ipx type on ipx socket level. */
3059 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
3061 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
3062 release_sock_fd( s, fd );
3063 return SOCKET_ERROR;
3068 /* Should we retrieve val using a getsockopt call and then
3069 * set the modified one? */
3070 val.ipx_pt = *optval;
3071 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
3074 release_sock_fd( s, fd );
3077 case IPX_FILTERPTYPE:
3078 /* Sets the receive filter packet type, at the moment we don't support it */
3079 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
3080 /* Returning 0 is better for now than returning a SOCKET_ERROR */
3084 FIXME("opt_name:%x\n", optname);
3085 return SOCKET_ERROR;
3087 break; /* case NSPROTO_IPX */
3090 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3091 case WS_IPPROTO_TCP:
3094 case WS_TCP_NODELAY:
3095 convert_sockopt(&level, &optname);
3098 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3099 return SOCKET_ERROR;
3106 case WS_IP_ADD_MEMBERSHIP:
3107 case WS_IP_DROP_MEMBERSHIP:
3111 case WS_IP_MULTICAST_IF:
3112 case WS_IP_MULTICAST_LOOP:
3113 case WS_IP_MULTICAST_TTL:
3117 convert_sockopt(&level, &optname);
3119 case WS_IP_DONTFRAGMENT:
3120 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
3123 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3124 return SOCKET_ERROR;
3129 FIXME("Unknown level: 0x%08x\n", level);
3130 return SOCKET_ERROR;
3131 } /* end switch(level) */
3133 /* avoid endianness issues if argument is a 16-bit int */
3134 if (optval && optlen < sizeof(int))
3136 woptval= *((const INT16 *) optval);
3137 optval= (char*) &woptval;
3140 fd = get_sock_fd( s, 0, NULL );
3141 if (fd == -1) return SOCKET_ERROR;
3143 if (setsockopt(fd, level, optname, optval, optlen) == 0)
3145 release_sock_fd( s, fd );
3148 TRACE("Setting socket error, %d\n", wsaErrno());
3149 SetLastError(wsaErrno());
3150 release_sock_fd( s, fd );
3152 return SOCKET_ERROR;
3155 /***********************************************************************
3156 * shutdown (WS2_32.22)
3158 int WINAPI WS_shutdown(SOCKET s, int how)
3160 int fd, err = WSAENOTSOCK;
3161 unsigned int options, clear_flags = 0;
3163 fd = get_sock_fd( s, 0, &options );
3164 TRACE("socket %04lx, how %i %x\n", s, how, options );
3167 return SOCKET_ERROR;
3171 case 0: /* drop receives */
3172 clear_flags |= FD_READ;
3174 case 1: /* drop sends */
3175 clear_flags |= FD_WRITE;
3177 case 2: /* drop all */
3178 clear_flags |= FD_READ|FD_WRITE;
3180 clear_flags |= FD_WINE_LISTENING;
3183 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3188 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3191 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3195 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3196 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3199 if (err) goto error;
3201 else /* non-overlapped mode */
3203 if ( shutdown( fd, how ) )
3210 release_sock_fd( s, fd );
3211 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3212 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
3216 release_sock_fd( s, fd );
3217 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3218 WSASetLastError( err );
3219 return SOCKET_ERROR;
3222 /***********************************************************************
3223 * socket (WS2_32.23)
3225 SOCKET WINAPI WS_socket(int af, int type, int protocol)
3227 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
3229 return WSASocketA( af, type, protocol, NULL, 0,
3230 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
3234 /***********************************************************************
3235 * gethostbyaddr (WS2_32.51)
3237 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
3239 struct WS_hostent *retval = NULL;
3240 struct hostent* host;
3242 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3245 struct hostent hostentry;
3248 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3250 int res = gethostbyaddr_r(addr, len, type,
3251 &hostentry, extrabuf, ebufsize, &host, &locerr);
3252 if( res != ERANGE) break;
3254 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3256 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3258 EnterCriticalSection( &csWSgetXXXbyYYY );
3259 host = gethostbyaddr(addr, len, type);
3260 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3262 if( host != NULL ) retval = WS_dup_he(host);
3263 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3264 HeapFree(GetProcessHeap(),0,extrabuf);
3266 LeaveCriticalSection( &csWSgetXXXbyYYY );
3268 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
3272 /***********************************************************************
3273 * gethostbyname (WS2_32.52)
3275 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
3277 struct WS_hostent *retval = NULL;
3278 struct hostent* host;
3279 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3282 struct hostent hostentry;
3283 int locerr = ENOBUFS;
3286 if( !name || !name[0]) {
3288 if( gethostname( buf, 100) == -1) {
3289 SetLastError( WSAENOBUFS); /* appropriate ? */
3293 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3295 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3297 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
3298 if( res != ERANGE) break;
3300 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3302 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3304 EnterCriticalSection( &csWSgetXXXbyYYY );
3305 host = gethostbyname(name);
3306 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3308 if (host) retval = WS_dup_he(host);
3309 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3310 HeapFree(GetProcessHeap(),0,extrabuf);
3312 LeaveCriticalSection( &csWSgetXXXbyYYY );
3314 if (retval && retval->h_addr_list[0][0] == 127 &&
3315 strcmp(name, "localhost") != 0)
3317 /* hostname != "localhost" but has loopback address. replace by our
3318 * special address.*/
3319 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
3321 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3326 /***********************************************************************
3327 * getprotobyname (WS2_32.53)
3329 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3331 struct WS_protoent* retval = NULL;
3332 #ifdef HAVE_GETPROTOBYNAME
3333 struct protoent* proto;
3334 EnterCriticalSection( &csWSgetXXXbyYYY );
3335 if( (proto = getprotobyname(name)) != NULL )
3337 retval = WS_dup_pe(proto);
3340 MESSAGE("protocol %s not found; You might want to add "
3341 "this to /etc/protocols\n", debugstr_a(name) );
3342 SetLastError(WSANO_DATA);
3344 LeaveCriticalSection( &csWSgetXXXbyYYY );
3346 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3351 /***********************************************************************
3352 * getprotobynumber (WS2_32.54)
3354 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3356 struct WS_protoent* retval = NULL;
3357 #ifdef HAVE_GETPROTOBYNUMBER
3358 struct protoent* proto;
3359 EnterCriticalSection( &csWSgetXXXbyYYY );
3360 if( (proto = getprotobynumber(number)) != NULL )
3362 retval = WS_dup_pe(proto);
3365 MESSAGE("protocol number %d not found; You might want to add "
3366 "this to /etc/protocols\n", number );
3367 SetLastError(WSANO_DATA);
3369 LeaveCriticalSection( &csWSgetXXXbyYYY );
3371 TRACE("%i ret %p\n", number, retval);
3376 /***********************************************************************
3377 * getservbyname (WS2_32.55)
3379 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3381 struct WS_servent* retval = NULL;
3382 struct servent* serv;
3384 char *proto_str = NULL;
3386 if (!(name_str = strdup_lower(name))) return NULL;
3388 if (proto && *proto)
3390 if (!(proto_str = strdup_lower(proto)))
3392 HeapFree( GetProcessHeap(), 0, name_str );
3397 EnterCriticalSection( &csWSgetXXXbyYYY );
3398 serv = getservbyname(name_str, proto_str);
3401 retval = WS_dup_se(serv);
3403 else SetLastError(WSANO_DATA);
3404 LeaveCriticalSection( &csWSgetXXXbyYYY );
3405 HeapFree( GetProcessHeap(), 0, proto_str );
3406 HeapFree( GetProcessHeap(), 0, name_str );
3407 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
3411 /***********************************************************************
3412 * freeaddrinfo (WS2_32.@)
3414 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
3417 struct WS_addrinfo *next;
3419 HeapFree(GetProcessHeap(),0,res->ai_canonname);
3420 HeapFree(GetProcessHeap(),0,res->ai_addr);
3421 next = res->ai_next;
3422 HeapFree(GetProcessHeap(),0,res);
3427 /* helper functions for getaddrinfo()/getnameinfo() */
3428 static int convert_aiflag_w2u(int winflags) {
3432 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3433 if (ws_aiflag_map[i][0] & winflags) {
3434 unixflags |= ws_aiflag_map[i][1];
3435 winflags &= ~ws_aiflag_map[i][0];
3438 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
3442 static int convert_niflag_w2u(int winflags) {
3446 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
3447 if (ws_niflag_map[i][0] & winflags) {
3448 unixflags |= ws_niflag_map[i][1];
3449 winflags &= ~ws_niflag_map[i][0];
3452 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
3456 static int convert_aiflag_u2w(int unixflags) {
3460 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3461 if (ws_aiflag_map[i][1] & unixflags) {
3462 winflags |= ws_aiflag_map[i][0];
3463 unixflags &= ~ws_aiflag_map[i][1];
3465 if (unixflags) /* will warn usually */
3466 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
3470 static int convert_eai_u2w(int unixret) {
3473 for (i=0;ws_eai_map[i][0];i++)
3474 if (ws_eai_map[i][1] == unixret)
3475 return ws_eai_map[i][0];
3479 /***********************************************************************
3480 * getaddrinfo (WS2_32.@)
3482 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
3484 #ifdef HAVE_GETADDRINFO
3485 struct addrinfo *unixaires = NULL;
3487 struct addrinfo unixhints, *punixhints = NULL;
3488 CHAR *node = NULL, *serv = NULL;
3491 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
3494 if (!(serv = strdup_lower(servname))) {
3495 HeapFree(GetProcessHeap(), 0, node);
3496 return WSA_NOT_ENOUGH_MEMORY;
3501 punixhints = &unixhints;
3503 memset(&unixhints, 0, sizeof(unixhints));
3504 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
3505 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
3506 punixhints->ai_family = 0;
3508 punixhints->ai_family = convert_af_w2u(hints->ai_family);
3509 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
3510 punixhints->ai_socktype = 0;
3512 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
3513 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
3514 punixhints->ai_protocol = 0;
3516 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
3519 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
3520 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
3522 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
3524 HeapFree(GetProcessHeap(), 0, node);
3525 HeapFree(GetProcessHeap(), 0, serv);
3528 struct addrinfo *xuai = unixaires;
3529 struct WS_addrinfo **xai = res;
3533 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
3539 *xai = ai;xai = &ai->ai_next;
3540 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
3541 ai->ai_family = convert_af_u2w(xuai->ai_family);
3542 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
3543 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
3544 if (xuai->ai_canonname) {
3545 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
3546 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
3547 if (!ai->ai_canonname)
3549 strcpy(ai->ai_canonname,xuai->ai_canonname);
3551 len = xuai->ai_addrlen;
3552 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
3555 ai->ai_addrlen = len;
3557 int winlen = ai->ai_addrlen;
3559 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
3560 ai->ai_addrlen = winlen;
3564 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
3567 ai->ai_addrlen = len;
3569 xuai = xuai->ai_next;
3571 freeaddrinfo(unixaires);
3573 result = convert_eai_u2w(result);
3579 if (*res) WS_freeaddrinfo(*res);
3580 if (unixaires) freeaddrinfo(unixaires);
3582 return WSA_NOT_ENOUGH_MEMORY;
3584 FIXME("getaddrinfo() failed, not found during buildtime.\n");
3589 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
3591 struct WS_addrinfoW *ret;
3593 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
3594 ret->ai_flags = ai->ai_flags;
3595 ret->ai_family = ai->ai_family;
3596 ret->ai_socktype = ai->ai_socktype;
3597 ret->ai_protocol = ai->ai_protocol;
3598 ret->ai_addrlen = ai->ai_addrlen;
3599 ret->ai_canonname = NULL;
3600 ret->ai_addr = NULL;
3601 ret->ai_next = NULL;
3602 if (ai->ai_canonname)
3604 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
3605 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
3607 HeapFree(GetProcessHeap(), 0, ret);
3610 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
3614 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
3616 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
3617 HeapFree(GetProcessHeap(), 0, ret);
3620 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
3625 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
3627 struct WS_addrinfoW *ret, *infoW;
3629 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
3630 while (info->ai_next)
3632 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
3637 infoW = infoW->ai_next;
3638 info = info->ai_next;
3643 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
3645 struct WS_addrinfo *ret;
3647 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
3648 ret->ai_flags = ai->ai_flags;
3649 ret->ai_family = ai->ai_family;
3650 ret->ai_socktype = ai->ai_socktype;
3651 ret->ai_protocol = ai->ai_protocol;
3652 ret->ai_addrlen = ai->ai_addrlen;
3653 ret->ai_canonname = NULL;
3654 ret->ai_addr = NULL;
3655 ret->ai_next = NULL;
3656 if (ai->ai_canonname)
3658 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
3659 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
3661 HeapFree(GetProcessHeap(), 0, ret);
3664 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
3668 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
3670 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
3671 HeapFree(GetProcessHeap(), 0, ret);
3674 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
3679 /***********************************************************************
3680 * GetAddrInfoW (WS2_32.@)
3682 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
3685 char *nodenameA, *servnameA = NULL;
3686 struct WS_addrinfo *resA, *hintsA = NULL;
3688 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
3689 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
3690 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
3694 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
3695 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
3697 HeapFree(GetProcessHeap(), 0, nodenameA);
3700 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
3703 if (hints) hintsA = addrinfo_WtoA(hints);
3704 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
3705 WS_freeaddrinfo(hintsA);
3709 *res = addrinfo_list_AtoW(resA);
3710 WS_freeaddrinfo(resA);
3713 HeapFree(GetProcessHeap(), 0, nodenameA);
3714 HeapFree(GetProcessHeap(), 0, servnameA);
3718 /***********************************************************************
3719 * FreeAddrInfoW (WS2_32.@)
3721 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
3726 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
3727 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
3729 HeapFree(GetProcessHeap(), 0, ai);
3734 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
3735 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
3737 #ifdef HAVE_GETNAMEINFO
3739 union generic_unix_sockaddr sa_u;
3742 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
3743 serv, servlen, flags);
3745 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
3748 WSASetLastError(WSAEFAULT);
3749 return WSA_NOT_ENOUGH_MEMORY;
3751 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
3752 return convert_eai_u2w(ret);
3754 FIXME("getnameinfo() failed, not found during buildtime.\n");
3759 /***********************************************************************
3760 * getservbyport (WS2_32.56)
3762 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
3764 struct WS_servent* retval = NULL;
3765 #ifdef HAVE_GETSERVBYPORT
3766 struct servent* serv;
3767 char *proto_str = NULL;
3769 if (proto && *proto)
3771 if (!(proto_str = strdup_lower(proto))) return NULL;
3773 EnterCriticalSection( &csWSgetXXXbyYYY );
3774 if( (serv = getservbyport(port, proto_str)) != NULL ) {
3775 retval = WS_dup_se(serv);
3777 else SetLastError(WSANO_DATA);
3778 LeaveCriticalSection( &csWSgetXXXbyYYY );
3779 HeapFree( GetProcessHeap(), 0, proto_str );
3781 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
3786 /***********************************************************************
3787 * gethostname (WS2_32.57)
3789 int WINAPI WS_gethostname(char *name, int namelen)
3791 TRACE("name %p, len %d\n", name, namelen);
3793 if (gethostname(name, namelen) == 0)
3795 TRACE("<- '%s'\n", name);
3798 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
3799 TRACE("<- ERROR !\n");
3800 return SOCKET_ERROR;
3804 /* ------------------------------------- Windows sockets extensions -- *
3806 * ------------------------------------------------------------------- */
3808 /***********************************************************************
3809 * WSAEnumNetworkEvents (WS2_32.36)
3811 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
3815 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
3817 SERVER_START_REQ( get_socket_event )
3819 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
3820 req->service = TRUE;
3821 req->c_event = wine_server_obj_handle( hEvent );
3822 wine_server_set_reply( req, lpEvent->iErrorCode, sizeof(lpEvent->iErrorCode) );
3823 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
3827 SetLastError(WSAEINVAL);
3828 return SOCKET_ERROR;
3831 /***********************************************************************
3832 * WSAEventSelect (WS2_32.39)
3834 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
3838 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
3840 SERVER_START_REQ( set_socket_event )
3842 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
3844 req->event = wine_server_obj_handle( hEvent );
3847 ret = wine_server_call( req );
3851 SetLastError(WSAEINVAL);
3852 return SOCKET_ERROR;
3855 /**********************************************************************
3856 * WSAGetOverlappedResult (WS2_32.40)
3858 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
3859 LPDWORD lpcbTransfer, BOOL fWait,
3864 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
3865 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
3867 if ( lpOverlapped == NULL )
3869 ERR( "Invalid pointer\n" );
3870 WSASetLastError(WSA_INVALID_PARAMETER);
3874 status = lpOverlapped->Internal;
3875 if (status == STATUS_PENDING)
3879 SetLastError( WSA_IO_INCOMPLETE );
3883 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
3884 INFINITE ) == WAIT_FAILED)
3886 status = lpOverlapped->Internal;
3890 *lpcbTransfer = lpOverlapped->InternalHigh;
3893 *lpdwFlags = lpOverlapped->u.s.Offset;
3895 if (status) SetLastError( RtlNtStatusToDosError(status) );
3900 /***********************************************************************
3901 * WSAAsyncSelect (WS2_32.101)
3903 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
3907 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
3909 SERVER_START_REQ( set_socket_event )
3911 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
3914 req->window = wine_server_user_handle( hWnd );
3916 ret = wine_server_call( req );
3920 SetLastError(WSAEINVAL);
3921 return SOCKET_ERROR;
3924 /***********************************************************************
3925 * WSACreateEvent (WS2_32.31)
3928 WSAEVENT WINAPI WSACreateEvent(void)
3930 /* Create a manual-reset event, with initial state: unsignaled */
3933 return CreateEventW(NULL, TRUE, FALSE, NULL);
3936 /***********************************************************************
3937 * WSACloseEvent (WS2_32.29)
3940 BOOL WINAPI WSACloseEvent(WSAEVENT event)
3942 TRACE ("event=%p\n", event);
3944 return CloseHandle(event);
3947 /***********************************************************************
3948 * WSASocketA (WS2_32.78)
3951 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
3952 LPWSAPROTOCOL_INFOA lpProtocolInfo,
3953 GROUP g, DWORD dwFlags)
3956 WSAPROTOCOL_INFOW info;
3958 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
3959 af, type, protocol, lpProtocolInfo, g, dwFlags);
3961 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
3963 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
3964 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
3965 info.szProtocol, WSAPROTOCOL_LEN + 1);
3969 WSASetLastError( WSAEINVAL);
3970 return SOCKET_ERROR;
3973 return WSASocketW(af, type, protocol, &info, g, dwFlags);
3976 /***********************************************************************
3977 * WSASocketW (WS2_32.79)
3980 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
3981 LPWSAPROTOCOL_INFOW lpProtocolInfo,
3982 GROUP g, DWORD dwFlags)
3987 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
3988 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
3991 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
3992 af, type, protocol, lpProtocolInfo, g, dwFlags );
3994 /* hack for WSADuplicateSocket */
3995 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
3996 ret = lpProtocolInfo->dwCatalogEntryId;
3997 TRACE("\tgot duplicate %04lx\n", ret);
4001 /* convert the socket family and type */
4002 af = convert_af_w2u(af);
4003 type = convert_socktype_w2u(type);
4007 if (af == FROM_PROTOCOL_INFO)
4008 af = lpProtocolInfo->iAddressFamily;
4009 if (type == FROM_PROTOCOL_INFO)
4010 type = lpProtocolInfo->iSocketType;
4011 if (protocol == FROM_PROTOCOL_INFO)
4012 protocol = lpProtocolInfo->iProtocol;
4015 if ( af == AF_UNSPEC) /* did they not specify the address family? */
4019 if (type == SOCK_STREAM) { af = AF_INET; break; }
4021 if (type == SOCK_DGRAM) { af = AF_INET; break; }
4022 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
4025 SERVER_START_REQ( create_socket )
4029 req->protocol = protocol;
4030 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
4031 req->attributes = OBJ_INHERIT;
4032 req->flags = dwFlags;
4033 set_error( wine_server_call( req ) );
4034 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
4039 TRACE("\tcreated %04lx\n", ret );
4043 if (GetLastError() == WSAEACCES) /* raw socket denied */
4045 if (type == SOCK_RAW)
4046 MESSAGE("WARNING: Trying to create a socket of type SOCK_RAW, this"
4047 " will fail unless you have special permissions.\n");
4049 MESSAGE("WS_SOCKET: Failed to create socket, this requires"
4050 " special permissions.\n");
4051 SetLastError(WSAESOCKTNOSUPPORT);
4054 WARN("\t\tfailed!\n");
4055 return INVALID_SOCKET;
4058 /***********************************************************************
4059 * WSAJoinLeaf (WS2_32.58)
4062 SOCKET WINAPI WSAJoinLeaf(
4064 const struct WS_sockaddr *addr,
4066 LPWSABUF lpCallerData,
4067 LPWSABUF lpCalleeData,
4073 return INVALID_SOCKET;
4076 /***********************************************************************
4077 * __WSAFDIsSet (WS2_32.151)
4079 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
4081 int i = set->fd_count;
4083 TRACE("(%ld,%p(%i))\n", s, set, i);
4086 if (set->fd_array[i] == s) return 1;
4090 /***********************************************************************
4091 * WSAIsBlocking (WINSOCK.114)
4092 * WSAIsBlocking (WS2_32.114)
4094 BOOL WINAPI WSAIsBlocking(void)
4096 /* By default WinSock should set all its sockets to non-blocking mode
4097 * and poll in PeekMessage loop when processing "blocking" ones. This
4098 * function is supposed to tell if the program is in this loop. Our
4099 * blocking calls are truly blocking so we always return FALSE.
4101 * Note: It is allowed to call this function without prior WSAStartup().
4108 /***********************************************************************
4109 * WSACancelBlockingCall (WINSOCK.113)
4110 * WSACancelBlockingCall (WS2_32.113)
4112 INT WINAPI WSACancelBlockingCall(void)
4118 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
4120 FIXME("How was this called?\n");
4125 /***********************************************************************
4126 * WSASetBlockingHook (WS2_32.109)
4128 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
4130 FARPROC prev = blocking_hook;
4131 blocking_hook = lpBlockFunc;
4132 TRACE("hook %p\n", lpBlockFunc);
4137 /***********************************************************************
4138 * WSAUnhookBlockingHook (WS2_32.110)
4140 INT WINAPI WSAUnhookBlockingHook(void)
4142 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
4147 /* ----------------------------------- end of API stuff */
4149 /* ----------------------------------- helper functions -
4151 * TODO: Merge WS_dup_..() stuff into one function that
4152 * would operate with a generic structure containing internal
4153 * pointers (via a template of some kind).
4156 static int list_size(char** l, int item_size)
4161 j += (item_size) ? item_size : strlen(l[i]) + 1;
4162 j += (i + 1) * sizeof(char*); }
4166 static int list_dup(char** l_src, char** l_to, int item_size)
4171 for (i = 0; l_src[i]; i++) ;
4172 p = (char *)(l_to + i + 1);
4173 for (i = 0; l_src[i]; i++)
4175 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
4176 memcpy(p, l_src[i], count);
4181 return p - (char *)l_to;
4186 /* duplicate hostent entry
4187 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
4188 * Ditto for protoent and servent.
4190 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
4193 struct WS_hostent *p_to;
4195 int size = (sizeof(*p_he) +
4196 strlen(p_he->h_name) + 1 +
4197 list_size(p_he->h_aliases, 0) +
4198 list_size(p_he->h_addr_list, p_he->h_length));
4200 if (!(p_to = check_buffer_he(size))) return NULL;
4201 p_to->h_addrtype = p_he->h_addrtype;
4202 p_to->h_length = p_he->h_length;
4204 p = (char *)(p_to + 1);
4206 strcpy(p, p_he->h_name);
4209 p_to->h_aliases = (char **)p;
4210 p += list_dup(p_he->h_aliases, p_to->h_aliases, 0);
4212 p_to->h_addr_list = (char **)p;
4213 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
4217 /* ----- protoent */
4219 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
4222 struct WS_protoent *p_to;
4224 int size = (sizeof(*p_pe) +
4225 strlen(p_pe->p_name) + 1 +
4226 list_size(p_pe->p_aliases, 0));
4228 if (!(p_to = check_buffer_pe(size))) return NULL;
4229 p_to->p_proto = p_pe->p_proto;
4231 p = (char *)(p_to + 1);
4233 strcpy(p, p_pe->p_name);
4236 p_to->p_aliases = (char **)p;
4237 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
4243 static struct WS_servent *WS_dup_se(const struct servent* p_se)
4246 struct WS_servent *p_to;
4248 int size = (sizeof(*p_se) +
4249 strlen(p_se->s_proto) + 1 +
4250 strlen(p_se->s_name) + 1 +
4251 list_size(p_se->s_aliases, 0));
4253 if (!(p_to = check_buffer_se(size))) return NULL;
4254 p_to->s_port = p_se->s_port;
4256 p = (char *)(p_to + 1);
4258 strcpy(p, p_se->s_name);
4262 strcpy(p, p_se->s_proto);
4265 p_to->s_aliases = (char **)p;
4266 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
4270 /* ----------------------------------- error handling */
4274 int loc_errno = errno;
4275 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
4279 case EINTR: return WSAEINTR;
4280 case EBADF: return WSAEBADF;
4282 case EACCES: return WSAEACCES;
4283 case EFAULT: return WSAEFAULT;
4284 case EINVAL: return WSAEINVAL;
4285 case EMFILE: return WSAEMFILE;
4286 case EWOULDBLOCK: return WSAEWOULDBLOCK;
4287 case EINPROGRESS: return WSAEINPROGRESS;
4288 case EALREADY: return WSAEALREADY;
4289 case ENOTSOCK: return WSAENOTSOCK;
4290 case EDESTADDRREQ: return WSAEDESTADDRREQ;
4291 case EMSGSIZE: return WSAEMSGSIZE;
4292 case EPROTOTYPE: return WSAEPROTOTYPE;
4293 case ENOPROTOOPT: return WSAENOPROTOOPT;
4294 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
4295 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
4296 case EOPNOTSUPP: return WSAEOPNOTSUPP;
4297 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
4298 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
4299 case EADDRINUSE: return WSAEADDRINUSE;
4300 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
4301 case ENETDOWN: return WSAENETDOWN;
4302 case ENETUNREACH: return WSAENETUNREACH;
4303 case ENETRESET: return WSAENETRESET;
4304 case ECONNABORTED: return WSAECONNABORTED;
4306 case ECONNRESET: return WSAECONNRESET;
4307 case ENOBUFS: return WSAENOBUFS;
4308 case EISCONN: return WSAEISCONN;
4309 case ENOTCONN: return WSAENOTCONN;
4310 case ESHUTDOWN: return WSAESHUTDOWN;
4311 case ETOOMANYREFS: return WSAETOOMANYREFS;
4312 case ETIMEDOUT: return WSAETIMEDOUT;
4313 case ECONNREFUSED: return WSAECONNREFUSED;
4314 case ELOOP: return WSAELOOP;
4315 case ENAMETOOLONG: return WSAENAMETOOLONG;
4316 case EHOSTDOWN: return WSAEHOSTDOWN;
4317 case EHOSTUNREACH: return WSAEHOSTUNREACH;
4318 case ENOTEMPTY: return WSAENOTEMPTY;
4320 case EPROCLIM: return WSAEPROCLIM;
4323 case EUSERS: return WSAEUSERS;
4326 case EDQUOT: return WSAEDQUOT;
4329 case ESTALE: return WSAESTALE;
4332 case EREMOTE: return WSAEREMOTE;
4335 /* just in case we ever get here and there are no problems */
4338 WARN("Unknown errno %d!\n", loc_errno);
4339 return WSAEOPNOTSUPP;
4343 UINT wsaHerrno(int loc_errno)
4346 WARN("h_errno %d.\n", loc_errno);
4350 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
4351 case TRY_AGAIN: return WSATRY_AGAIN;
4352 case NO_RECOVERY: return WSANO_RECOVERY;
4353 case NO_DATA: return WSANO_DATA;
4354 case ENOBUFS: return WSAENOBUFS;
4358 WARN("Unknown h_errno %d!\n", loc_errno);
4359 return WSAEOPNOTSUPP;
4364 /***********************************************************************
4365 * WSARecv (WS2_32.67)
4367 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4368 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
4369 LPWSAOVERLAPPED lpOverlapped,
4370 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
4372 return WSARecvFrom(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
4373 NULL, NULL, lpOverlapped, lpCompletionRoutine);
4376 /***********************************************************************
4377 * WSARecvFrom (WS2_32.69)
4379 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4380 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
4381 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
4382 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4385 unsigned int i, options;
4387 struct ws2_async *wsa;
4388 DWORD timeout_start = GetTickCount();
4389 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4391 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
4392 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
4393 (lpFromlen ? *lpFromlen : -1),
4394 lpOverlapped, lpCompletionRoutine);
4396 fd = get_sock_fd( s, FILE_READ_DATA, &options );
4397 TRACE( "fd=%d, options=%x\n", fd, options );
4399 if (fd == -1) return SOCKET_ERROR;
4401 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
4407 wsa->hSocket = SOCKET2HANDLE(s);
4408 wsa->flags = *lpFlags;
4410 wsa->addrlen.ptr = lpFromlen;
4411 wsa->n_iovecs = dwBufferCount;
4412 wsa->first_iovec = 0;
4413 for (i = 0; i < dwBufferCount; i++)
4415 /* check buffer first to trigger write watches */
4416 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
4421 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4422 wsa->iovec[i].iov_len = lpBuffers[i].len;
4427 n = WS2_recv( fd, wsa );
4430 if (errno == EINTR) continue;
4431 if (errno != EAGAIN)
4434 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
4439 *lpNumberOfBytesRecvd = n;
4441 if ((lpOverlapped || lpCompletionRoutine) &&
4442 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4444 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4446 wsa->user_overlapped = lpOverlapped;
4447 wsa->completion_func = lpCompletionRoutine;
4448 release_sock_fd( s, fd );
4452 iosb->u.Status = STATUS_PENDING;
4453 iosb->Information = 0;
4455 SERVER_START_REQ( register_async )
4457 req->type = ASYNC_TYPE_READ;
4458 req->async.handle = wine_server_obj_handle( wsa->hSocket );
4459 req->async.callback = wine_server_client_ptr( WS2_async_recv );
4460 req->async.iosb = wine_server_client_ptr( iosb );
4461 req->async.arg = wine_server_client_ptr( wsa );
4462 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
4463 req->async.cvalue = cvalue;
4464 err = wine_server_call( req );
4468 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4469 WSASetLastError( NtStatusToWSAError( err ));
4470 return SOCKET_ERROR;
4473 iosb->u.Status = STATUS_SUCCESS;
4474 iosb->Information = n;
4475 if (!wsa->completion_func)
4477 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4478 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
4479 HeapFree( GetProcessHeap(), 0, wsa );
4481 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4482 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4483 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4489 if ( _is_blocking(s) )
4492 int timeout = GET_RCVTIMEO(fd);
4495 timeout -= GetTickCount() - timeout_start;
4496 if (timeout < 0) timeout = 0;
4500 pfd.events = POLLIN;
4501 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
4503 if (!timeout || !poll( &pfd, 1, timeout ))
4506 /* a timeout is not fatal */
4507 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4513 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4514 err = WSAEWOULDBLOCK;
4519 TRACE(" -> %i bytes\n", n);
4520 HeapFree( GetProcessHeap(), 0, wsa );
4521 release_sock_fd( s, fd );
4522 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4527 HeapFree( GetProcessHeap(), 0, wsa );
4528 release_sock_fd( s, fd );
4529 WARN(" -> ERROR %d\n", err);
4530 WSASetLastError( err );
4531 return SOCKET_ERROR;
4534 /***********************************************************************
4535 * WSCInstallProvider (WS2_32.88)
4537 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
4538 LPCWSTR lpszProviderDllPath,
4539 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
4540 DWORD dwNumberOfEntries,
4543 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
4544 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
4545 dwNumberOfEntries, lpErrno);
4551 /***********************************************************************
4552 * WSCDeinstallProvider (WS2_32.83)
4554 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
4556 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
4562 /***********************************************************************
4563 * WSAAccept (WS2_32.26)
4565 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
4566 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
4569 int ret = 0, size = 0;
4570 WSABUF CallerId, CallerData, CalleeId, CalleeData;
4571 /* QOS SQOS, GQOS; */
4574 SOCKADDR src_addr, dst_addr;
4576 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %d\n",
4577 s, addr, addrlen, lpfnCondition, dwCallbackData);
4580 size = sizeof(src_addr);
4581 cs = WS_accept(s, &src_addr, &size);
4583 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
4585 if (!lpfnCondition) return cs;
4587 CallerId.buf = (char *)&src_addr;
4588 CallerId.len = sizeof(src_addr);
4590 CallerData.buf = NULL;
4593 WS_getsockname(cs, &dst_addr, &size);
4595 CalleeId.buf = (char *)&dst_addr;
4596 CalleeId.len = sizeof(dst_addr);
4599 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
4600 &CalleeId, &CalleeData, &g, dwCallbackData);
4605 if (addr && addrlen)
4606 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
4609 SERVER_START_REQ( set_socket_deferred )
4611 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4612 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
4613 if ( !wine_server_call_err ( req ) )
4615 SetLastError( WSATRY_AGAIN );
4616 WS_closesocket( cs );
4620 return SOCKET_ERROR;
4623 SetLastError(WSAECONNREFUSED);
4624 return SOCKET_ERROR;
4626 FIXME("Unknown return type from Condition function\n");
4627 SetLastError(WSAENOTSOCK);
4628 return SOCKET_ERROR;
4632 /***********************************************************************
4633 * WSADuplicateSocketA (WS2_32.32)
4635 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
4639 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4640 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4641 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
4642 /* I don't know what the real Windoze does next, this is a hack */
4643 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
4644 * the target use the global duplicate, or we could copy a reference to us to the structure
4645 * and let the target duplicate it from us, but let's do it as simple as possible */
4646 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4647 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4648 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4649 0, FALSE, DUPLICATE_SAME_ACCESS);
4650 CloseHandle(hProcess);
4651 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4655 /***********************************************************************
4656 * WSADuplicateSocketW (WS2_32.33)
4658 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
4662 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4664 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4665 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4666 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4667 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4668 0, FALSE, DUPLICATE_SAME_ACCESS);
4669 CloseHandle(hProcess);
4670 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4674 /***********************************************************************
4675 * WSAInstallServiceClassA (WS2_32.48)
4677 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
4679 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
4680 WSASetLastError(WSAEACCES);
4681 return SOCKET_ERROR;
4684 /***********************************************************************
4685 * WSAInstallServiceClassW (WS2_32.49)
4687 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
4689 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
4690 WSASetLastError(WSAEACCES);
4691 return SOCKET_ERROR;
4694 /***********************************************************************
4695 * WSARemoveServiceClass (WS2_32.70)
4697 int WINAPI WSARemoveServiceClass(LPGUID info)
4699 FIXME("Request to remove service %p\n",info);
4700 WSASetLastError(WSATYPE_NOT_FOUND);
4701 return SOCKET_ERROR;
4704 /***********************************************************************
4705 * inet_ntop (WS2_32.@)
4707 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
4709 #ifdef HAVE_INET_NTOP
4710 struct WS_in6_addr *in6;
4711 struct WS_in_addr *in;
4713 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
4718 return inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
4721 return inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
4724 FIXME( "not supported on this platform\n" );
4726 WSASetLastError( WSAEAFNOSUPPORT );
4730 /***********************************************************************
4731 * WSAStringToAddressA (WS2_32.80)
4733 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
4735 LPWSAPROTOCOL_INFOA lpProtocolInfo,
4736 LPSOCKADDR lpAddress,
4737 LPINT lpAddressLength)
4740 LPSTR workBuffer=NULL,ptrPort;
4742 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
4743 lpProtocolInfo, lpAddress, lpAddressLength );
4745 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
4749 WSASetLastError(WSAEINVAL);
4750 return SOCKET_ERROR;
4754 FIXME("ProtocolInfo not implemented.\n");
4756 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
4757 strlen(AddressString) + 1);
4760 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4761 return SOCKET_ERROR;
4764 strcpy(workBuffer, AddressString);
4766 switch(AddressFamily)
4770 struct in_addr inetaddr;
4772 /* If lpAddressLength is too small, tell caller the size we need */
4773 if (*lpAddressLength < sizeof(SOCKADDR_IN))
4775 *lpAddressLength = sizeof(SOCKADDR_IN);
4779 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
4781 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
4783 ptrPort = strchr(workBuffer, ':');
4786 ((LPSOCKADDR_IN)lpAddress)->sin_port = (WS_u_short)atoi(ptrPort+1);
4791 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
4794 if(inet_aton(workBuffer, &inetaddr) > 0)
4796 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
4807 struct in6_addr inetaddr;
4808 /* If lpAddressLength is too small, tell caller the size we need */
4809 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
4811 *lpAddressLength = sizeof(SOCKADDR_IN6);
4815 #ifdef HAVE_INET_PTON
4816 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
4818 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
4820 /* This one is a bit tricky. An IPv6 address contains colons, so the
4821 * check from IPv4 doesn't work like that. However, IPv6 addresses that
4822 * contain a port are written with braces like [fd12:3456:7890::1]:12345
4823 * so what we will do is to look for ']', check if the next char is a
4824 * colon, and if it is, parse the port as in IPv4. */
4826 ptrPort = strchr(workBuffer, ']');
4827 if(ptrPort && *(++ptrPort) == ':')
4829 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = (WS_u_short)atoi(ptrPort+1);
4834 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
4837 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
4839 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
4840 sizeof(struct in6_addr));
4844 #endif /* HAVE_INET_PTON */
4850 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
4851 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
4855 HeapFree(GetProcessHeap(), 0, workBuffer);
4858 WSASetLastError(res);
4859 return SOCKET_ERROR;
4862 /***********************************************************************
4863 * WSAStringToAddressW (WS2_32.81)
4865 * Does anybody know if this functions allows to use hebrew/arabic/chinese... digits?
4866 * If this should be the case, it would be required to map these digits
4867 * to Unicode digits (0-9) using FoldString first.
4869 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
4871 LPWSAPROTOCOL_INFOW lpProtocolInfo,
4872 LPSOCKADDR lpAddress,
4873 LPINT lpAddressLength)
4876 LPSTR workBuffer=NULL;
4877 WSAPROTOCOL_INFOA infoA;
4878 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
4880 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
4881 lpAddress, lpAddressLength );
4883 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
4885 /* if ProtocolInfo is available - convert to ANSI variant */
4888 lpProtoInfoA = &infoA;
4889 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
4891 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
4892 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
4894 WSASetLastError( WSAEINVAL);
4895 return SOCKET_ERROR;
4901 /* Translate AddressString to ANSI code page - assumes that only
4902 standard digits 0-9 are used with this API call */
4903 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
4904 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
4908 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
4909 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
4910 lpAddress,lpAddressLength);
4911 HeapFree( GetProcessHeap(), 0, workBuffer );
4915 res = WSA_NOT_ENOUGH_MEMORY;
4920 WSASetLastError(res);
4921 return SOCKET_ERROR;
4924 /***********************************************************************
4925 * WSAAddressToStringA (WS2_32.27)
4927 * See WSAAddressToStringW
4929 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
4930 LPWSAPROTOCOL_INFOA info, LPSTR string,
4934 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
4937 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
4939 if (!sockaddr) return SOCKET_ERROR;
4940 if (!string || !lenstr) return SOCKET_ERROR;
4942 switch(sockaddr->sa_family)
4945 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
4946 sprintf( buffer, "%u.%u.%u.%u:%u",
4947 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
4948 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
4949 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
4950 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
4951 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
4953 p = strchr( buffer, ':' );
4954 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
4959 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
4962 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
4963 if ((sockaddr6->sin6_port))
4964 strcpy(buffer, "[");
4965 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
4967 WSASetLastError(WSAEINVAL);
4968 return SOCKET_ERROR;
4970 if ((sockaddr6->sin6_scope_id))
4971 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
4972 if ((sockaddr6->sin6_port))
4973 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
4978 WSASetLastError(WSAEINVAL);
4979 return SOCKET_ERROR;
4982 size = strlen( buffer ) + 1;
4987 WSASetLastError(WSAEFAULT);
4988 return SOCKET_ERROR;
4992 strcpy( string, buffer );
4996 /***********************************************************************
4997 * WSAAddressToStringW (WS2_32.28)
4999 * Convert a sockaddr address into a readable address string.
5002 * sockaddr [I] Pointer to a sockaddr structure.
5003 * len [I] Size of the sockaddr structure.
5004 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
5005 * string [I/O] Pointer to a buffer to receive the address string.
5006 * lenstr [I/O] Size of the receive buffer in WCHARs.
5010 * Failure: SOCKET_ERROR
5013 * The 'info' parameter is ignored.
5015 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
5016 LPWSAPROTOCOL_INFOW info, LPWSTR string,
5021 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
5024 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
5027 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
5029 if (ret) return ret;
5031 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
5036 WSASetLastError(WSAEFAULT);
5037 return SOCKET_ERROR;
5041 lstrcpyW( string, buffer );
5045 /***********************************************************************
5046 * WSAEnumNameSpaceProvidersA (WS2_32.34)
5048 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
5050 FIXME( "(%p %p) Stub!\n", len, buffer );
5054 /***********************************************************************
5055 * WSAEnumNameSpaceProvidersW (WS2_32.35)
5057 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
5059 FIXME( "(%p %p) Stub!\n", len, buffer );
5063 /***********************************************************************
5064 * WSAGetQOSByName (WS2_32.41)
5066 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
5068 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
5072 /***********************************************************************
5073 * WSAGetServiceClassInfoA (WS2_32.42)
5075 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
5076 LPWSASERVICECLASSINFOA info )
5078 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
5080 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5081 return SOCKET_ERROR;
5084 /***********************************************************************
5085 * WSAGetServiceClassInfoW (WS2_32.43)
5087 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
5088 LPWSASERVICECLASSINFOW info )
5090 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
5092 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5093 return SOCKET_ERROR;
5096 /***********************************************************************
5097 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
5099 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
5101 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
5102 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5103 return SOCKET_ERROR;
5106 /***********************************************************************
5107 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
5109 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
5111 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
5112 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5113 return SOCKET_ERROR;
5116 /***********************************************************************
5117 * WSALookupServiceBeginA (WS2_32.59)
5119 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
5120 DWORD dwControlFlags,
5123 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
5125 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5126 return SOCKET_ERROR;
5129 /***********************************************************************
5130 * WSALookupServiceBeginW (WS2_32.60)
5132 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
5133 DWORD dwControlFlags,
5136 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
5138 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5139 return SOCKET_ERROR;
5142 /***********************************************************************
5143 * WSALookupServiceBeginW (WS2_32.61)
5145 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
5147 FIXME("(%p) Stub!\n", lookup );
5151 /***********************************************************************
5152 * WSALookupServiceNextA (WS2_32.62)
5154 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
5156 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
5160 /***********************************************************************
5161 * WSALookupServiceNextW (WS2_32.63)
5163 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
5165 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
5169 /***********************************************************************
5170 * WSANtohl (WS2_32.64)
5172 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
5174 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
5176 if (!lphostlong) return WSAEFAULT;
5178 *lphostlong = ntohl( netlong );
5182 /***********************************************************************
5183 * WSANtohs (WS2_32.65)
5185 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
5187 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
5189 if (!lphostshort) return WSAEFAULT;
5191 *lphostshort = ntohs( netshort );
5195 /***********************************************************************
5196 * WSAProviderConfigChange (WS2_32.66)
5198 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
5199 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
5201 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
5202 return SOCKET_ERROR;
5205 /***********************************************************************
5206 * WSARecvDisconnect (WS2_32.68)
5208 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
5210 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
5212 return WS_shutdown( s, 0 );
5215 /***********************************************************************
5216 * WSASetServiceA (WS2_32.76)
5218 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
5220 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5224 /***********************************************************************
5225 * WSASetServiceW (WS2_32.77)
5227 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
5229 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5233 /***********************************************************************
5234 * WSCEnableNSProvider (WS2_32.84)
5236 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
5238 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
5242 /***********************************************************************
5243 * WSCGetProviderPath (WS2_32.86)
5245 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
5247 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
5249 if (!errcode || !provider || !len) return WSAEFAULT;
5251 *errcode = WSAEINVAL;
5252 return SOCKET_ERROR;
5255 /***********************************************************************
5256 * WSCInstallNameSpace (WS2_32.87)
5258 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
5259 DWORD version, LPGUID provider )
5261 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
5262 namespace, version, debugstr_guid(provider) );
5266 /***********************************************************************
5267 * WSCUnInstallNameSpace (WS2_32.89)
5269 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
5271 FIXME("(%p) Stub!\n", lpProviderId);
5275 /***********************************************************************
5276 * WSCWriteProviderOrder (WS2_32.91)
5278 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
5280 FIXME("(%p 0x%08x) Stub!\n", entry, number);