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 # include <linux/ipx.h>
113 #ifdef HAVE_SYS_POLL_H
114 # include <sys/poll.h>
116 #ifdef HAVE_SYS_TIME_H
117 # include <sys/time.h>
120 #define NONAMELESSUNION
121 #define NONAMELESSSTRUCT
122 #include "ntstatus.h"
123 #define WIN32_NO_STATUS
128 #include "winerror.h"
130 #include "winsock2.h"
132 #include "ws2tcpip.h"
136 #include "iphlpapi.h"
137 #include "wine/server.h"
138 #include "wine/debug.h"
139 #include "wine/unicode.h"
142 # include "wsnwlink.h"
146 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
147 # define sipx_network sipx_addr.x_net
148 # define sipx_node sipx_addr.x_host.c_host
149 #endif /* __FreeBSD__ */
152 #define INADDR_NONE ~0UL
155 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
157 /* critical section to protect some non-reentrant net function */
158 extern CRITICAL_SECTION csWSgetXXXbyYYY;
160 union generic_unix_sockaddr
162 struct sockaddr addr;
163 char data[128]; /* should be big enough for all families */
166 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
168 if (!a) return "(nil)";
169 return wine_dbg_sprintf("{ family %d, address %s, port %d }",
170 ((const struct sockaddr_in *)a)->sin_family,
171 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
172 ntohs(((const struct sockaddr_in *)a)->sin_port));
175 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
176 #define SOCKET2HANDLE(s) ((HANDLE)(s))
177 #define HANDLE2SOCKET(h) ((SOCKET)(h))
179 /****************************************************************
180 * Async IO declarations
181 ****************************************************************/
183 typedef struct ws2_async
187 LPWSAOVERLAPPED user_overlapped;
188 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
189 IO_STATUS_BLOCK local_iosb;
190 struct iovec iovec[WS_MSG_MAXIOVLEN];
192 struct WS_sockaddr *addr;
195 int val; /* for send operations */
196 int *ptr; /* for recv operations */
201 /****************************************************************/
203 /* ----------------------------------- internal data */
205 /* ws_... struct conversion flags */
207 typedef struct /* WSAAsyncSelect() control struct */
209 HANDLE service, event, sock;
215 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
216 #define WS_MAX_UDP_DATAGRAM 1024
217 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
219 /* hostent's, servent's and protent's are stored in one buffer per thread,
220 * as documented on MSDN for the functions that return any of the buffers */
221 struct per_thread_data
224 struct WS_hostent *he_buffer;
225 struct WS_servent *se_buffer;
226 struct WS_protoent *pe_buffer;
232 static INT num_startup; /* reference counter */
233 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
235 /* function prototypes */
236 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
237 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
238 static struct WS_servent *WS_dup_se(const struct servent* p_se);
240 int WSAIOCTL_GetInterfaceCount(void);
241 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
244 UINT wsaHerrno(int errnr);
246 #define MAP_OPTION(opt) { WS_##opt, opt }
248 static const int ws_sock_map[][2] =
250 MAP_OPTION( SO_DEBUG ),
251 MAP_OPTION( SO_ACCEPTCONN ),
252 MAP_OPTION( SO_REUSEADDR ),
253 MAP_OPTION( SO_KEEPALIVE ),
254 MAP_OPTION( SO_DONTROUTE ),
255 MAP_OPTION( SO_BROADCAST ),
256 MAP_OPTION( SO_LINGER ),
257 MAP_OPTION( SO_OOBINLINE ),
258 MAP_OPTION( SO_SNDBUF ),
259 MAP_OPTION( SO_RCVBUF ),
260 MAP_OPTION( SO_ERROR ),
261 MAP_OPTION( SO_TYPE ),
263 MAP_OPTION( SO_RCVTIMEO ),
266 MAP_OPTION( SO_SNDTIMEO ),
270 static const int ws_tcp_map[][2] =
273 MAP_OPTION( TCP_NODELAY ),
277 static const int ws_ip_map[][2] =
279 MAP_OPTION( IP_MULTICAST_IF ),
280 MAP_OPTION( IP_MULTICAST_TTL ),
281 MAP_OPTION( IP_MULTICAST_LOOP ),
282 MAP_OPTION( IP_ADD_MEMBERSHIP ),
283 MAP_OPTION( IP_DROP_MEMBERSHIP ),
284 MAP_OPTION( IP_OPTIONS ),
286 MAP_OPTION( IP_HDRINCL ),
288 MAP_OPTION( IP_TOS ),
289 MAP_OPTION( IP_TTL ),
292 static const int ws_af_map[][2] =
294 MAP_OPTION( AF_UNSPEC ),
295 MAP_OPTION( AF_INET ),
296 MAP_OPTION( AF_INET6 ),
298 MAP_OPTION( AF_IPX ),
300 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
303 static const int ws_socktype_map[][2] =
305 MAP_OPTION( SOCK_DGRAM ),
306 MAP_OPTION( SOCK_STREAM ),
307 MAP_OPTION( SOCK_RAW ),
308 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
311 static const int ws_proto_map[][2] =
313 MAP_OPTION( IPPROTO_IP ),
314 MAP_OPTION( IPPROTO_TCP ),
315 MAP_OPTION( IPPROTO_UDP ),
316 MAP_OPTION( IPPROTO_ICMP ),
317 MAP_OPTION( IPPROTO_IGMP ),
318 MAP_OPTION( IPPROTO_RAW ),
319 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
322 static const int ws_aiflag_map[][2] =
324 MAP_OPTION( AI_PASSIVE ),
325 MAP_OPTION( AI_CANONNAME ),
326 MAP_OPTION( AI_NUMERICHOST ),
327 /* Linux/UNIX knows a lot more. But Windows only
328 * has 3 as far as I could see. -Marcus
332 static const int ws_niflag_map[][2] =
334 MAP_OPTION( NI_NOFQDN ),
335 MAP_OPTION( NI_NUMERICHOST ),
336 MAP_OPTION( NI_NAMEREQD ),
337 MAP_OPTION( NI_NUMERICSERV ),
338 MAP_OPTION( NI_DGRAM ),
341 static const int ws_eai_map[][2] =
343 MAP_OPTION( EAI_AGAIN ),
344 MAP_OPTION( EAI_BADFLAGS ),
345 MAP_OPTION( EAI_FAIL ),
346 MAP_OPTION( EAI_FAMILY ),
347 MAP_OPTION( EAI_MEMORY ),
348 /* Note: EAI_NODATA is deprecated, but still
349 * used by Windows and Linux... We map the newer
350 * EAI_NONAME to EAI_NODATA for now until Windows
354 MAP_OPTION( EAI_NODATA ),
357 { WS_EAI_NODATA, EAI_NONAME },
360 MAP_OPTION( EAI_SERVICE ),
361 MAP_OPTION( EAI_SOCKTYPE ),
365 static const char magic_loopback_addr[] = {127, 12, 34, 56};
367 static inline DWORD NtStatusToWSAError( const DWORD status )
369 /* We only need to cover the status codes set by server async request handling */
373 case STATUS_SUCCESS: wserr = 0; break;
374 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
375 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
376 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
377 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
378 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
379 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
380 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
381 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
383 if ( status >= WSABASEERR && status <= WSABASEERR+1004 )
384 /* It is not an NT status code but a winsock error */
388 wserr = RtlNtStatusToDosError( status );
389 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
395 /* set last error code from NT status without mapping WSA errors */
396 static inline unsigned int set_error( unsigned int err )
400 err = NtStatusToWSAError( err );
406 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
409 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
414 static inline void release_sock_fd( SOCKET s, int fd )
416 wine_server_release_fd( SOCKET2HANDLE(s), fd );
419 static void _enable_event( HANDLE s, unsigned int event,
420 unsigned int sstate, unsigned int cstate )
422 SERVER_START_REQ( enable_socket_event )
426 req->sstate = sstate;
427 req->cstate = cstate;
428 wine_server_call( req );
433 static int _is_blocking(SOCKET s)
436 SERVER_START_REQ( get_socket_event )
438 req->handle = SOCKET2HANDLE(s);
439 req->service = FALSE;
441 wine_server_call( req );
442 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
448 static unsigned int _get_sock_mask(SOCKET s)
451 SERVER_START_REQ( get_socket_event )
453 req->handle = SOCKET2HANDLE(s);
454 req->service = FALSE;
456 wine_server_call( req );
463 static void _sync_sock_state(SOCKET s)
465 /* do a dummy wineserver request in order to let
466 the wineserver run through its select loop once */
467 (void)_is_blocking(s);
470 static int _get_sock_error(SOCKET s, unsigned int bit)
472 int events[FD_MAX_EVENTS];
474 SERVER_START_REQ( get_socket_event )
476 req->handle = SOCKET2HANDLE(s);
477 req->service = FALSE;
479 wine_server_set_reply( req, events, sizeof(events) );
480 wine_server_call( req );
486 static struct per_thread_data *get_per_thread_data(void)
488 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
489 /* lazy initialization */
492 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
493 NtCurrentTeb()->WinSockData = ptb;
498 static void free_per_thread_data(void)
500 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
504 /* delete scratch buffers */
505 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
506 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
507 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
508 ptb->he_buffer = NULL;
509 ptb->se_buffer = NULL;
510 ptb->pe_buffer = NULL;
512 HeapFree( GetProcessHeap(), 0, ptb );
513 NtCurrentTeb()->WinSockData = NULL;
516 /***********************************************************************
517 * DllMain (WS2_32.init)
519 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
521 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
523 case DLL_PROCESS_ATTACH:
525 case DLL_PROCESS_DETACH:
526 free_per_thread_data();
529 case DLL_THREAD_DETACH:
530 free_per_thread_data();
536 /***********************************************************************
539 * Converts socket flags from Windows format.
540 * Return 1 if converted, 0 if not (error).
542 static int convert_sockopt(INT *level, INT *optname)
549 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
550 if( ws_sock_map[i][0] == *optname )
552 *optname = ws_sock_map[i][1];
556 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
559 *level = IPPROTO_TCP;
560 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
561 if ( ws_tcp_map[i][0] == *optname )
563 *optname = ws_tcp_map[i][1];
567 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
571 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
572 if (ws_ip_map[i][0] == *optname )
574 *optname = ws_ip_map[i][1];
578 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
580 default: FIXME("Unimplemented or unknown socket level\n");
585 /* ----------------------------------- Per-thread info (or per-process?) */
587 static char *strdup_lower(const char *str)
590 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
594 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
597 else SetLastError(WSAENOBUFS);
601 static inline int sock_error_p(int s)
603 unsigned int optval, optlen;
605 optlen = sizeof(optval);
606 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
607 if (optval) WARN("\t[%i] error: %d\n", s, optval);
611 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
612 * from an fd and return the value converted to milli seconds
613 * or -1 if there is an infinite time out */
614 static inline int get_rcvsnd_timeo( int fd, int optname)
617 unsigned int len = sizeof(tv);
618 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
620 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
621 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
626 /* macro wrappers for portability */
628 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
630 #define GET_RCVTIMEO(fd) (-1)
634 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
636 #define GET_SNDTIMEO(fd) (-1)
639 /* utility: given an fd, will block until one of the events occurs */
640 static inline int do_block( int fd, int events, int timeout )
648 while ((ret = poll(&pfd, 1, timeout)) < 0)
659 convert_af_w2u(int windowsaf) {
662 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
663 if (ws_af_map[i][0] == windowsaf)
664 return ws_af_map[i][1];
665 FIXME("unhandled Windows address family %d\n", windowsaf);
670 convert_af_u2w(int unixaf) {
673 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
674 if (ws_af_map[i][1] == unixaf)
675 return ws_af_map[i][0];
676 FIXME("unhandled UNIX address family %d\n", unixaf);
681 convert_proto_w2u(int windowsproto) {
684 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
685 if (ws_proto_map[i][0] == windowsproto)
686 return ws_proto_map[i][1];
687 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
692 convert_proto_u2w(int unixproto) {
695 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
696 if (ws_proto_map[i][1] == unixproto)
697 return ws_proto_map[i][0];
698 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
703 convert_socktype_w2u(int windowssocktype) {
706 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
707 if (ws_socktype_map[i][0] == windowssocktype)
708 return ws_socktype_map[i][1];
709 FIXME("unhandled Windows socket type %d\n", windowssocktype);
714 convert_socktype_u2w(int unixsocktype) {
717 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
718 if (ws_socktype_map[i][1] == unixsocktype)
719 return ws_socktype_map[i][0];
720 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
724 /* ----------------------------------- API -----
726 * Init / cleanup / error checking.
729 /***********************************************************************
730 * WSAStartup (WS2_32.115)
732 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
734 TRACE("verReq=%x\n", wVersionRequested);
736 if (LOBYTE(wVersionRequested) < 1)
737 return WSAVERNOTSUPPORTED;
739 if (!lpWSAData) return WSAEINVAL;
743 /* that's the whole of the negotiation for now */
744 lpWSAData->wVersion = wVersionRequested;
745 /* return winsock information */
746 lpWSAData->wHighVersion = 0x0202;
747 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
748 strcpy(lpWSAData->szSystemStatus, "Running" );
749 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
750 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
751 /* don't do anything with lpWSAData->lpVendorInfo */
752 /* (some apps don't allocate the space for this field) */
754 TRACE("succeeded\n");
759 /***********************************************************************
760 * WSACleanup (WS2_32.116)
762 INT WINAPI WSACleanup(void)
768 SetLastError(WSANOTINITIALISED);
773 /***********************************************************************
774 * WSAGetLastError (WINSOCK.111)
775 * WSAGetLastError (WS2_32.111)
777 INT WINAPI WSAGetLastError(void)
779 return GetLastError();
782 /***********************************************************************
783 * WSASetLastError (WS2_32.112)
785 void WINAPI WSASetLastError(INT iError) {
786 SetLastError(iError);
789 static struct WS_hostent *check_buffer_he(int size)
791 struct per_thread_data * ptb = get_per_thread_data();
794 if (ptb->he_len >= size ) return ptb->he_buffer;
795 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
797 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
798 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
799 return ptb->he_buffer;
802 static struct WS_servent *check_buffer_se(int size)
804 struct per_thread_data * ptb = get_per_thread_data();
807 if (ptb->se_len >= size ) return ptb->se_buffer;
808 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
810 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
811 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
812 return ptb->se_buffer;
815 static struct WS_protoent *check_buffer_pe(int size)
817 struct per_thread_data * ptb = get_per_thread_data();
820 if (ptb->pe_len >= size ) return ptb->pe_buffer;
821 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
823 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
824 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
825 return ptb->pe_buffer;
828 /* ----------------------------------- i/o APIs */
831 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf)== WS_AF_IPX || (pf) == WS_AF_INET6)
833 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf) == WS_AF_INET6)
837 /**********************************************************************/
839 /* Returns the length of the converted address if successful, 0 if it was too small to
842 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
843 union generic_unix_sockaddr *uaddr)
845 unsigned int uaddrlen = 0;
847 switch (wsaddr->sa_family)
852 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
853 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
855 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
858 uaddrlen = sizeof(struct sockaddr_ipx);
859 memset( uaddr, 0, uaddrlen );
860 uipx->sipx_family=AF_IPX;
861 uipx->sipx_port=wsipx->sa_socket;
862 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
865 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
866 #ifdef IPX_FRAME_NONE
867 uipx->sipx_type=IPX_FRAME_NONE;
873 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
874 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
876 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
877 * scope_id, one without.
879 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
880 uaddrlen = sizeof(struct sockaddr_in6);
881 memset( uaddr, 0, uaddrlen );
882 uin6->sin6_family = AF_INET6;
883 uin6->sin6_port = win6->sin6_port;
884 uin6->sin6_flowinfo = win6->sin6_flowinfo;
885 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
886 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
888 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
891 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
895 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
896 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
898 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
900 uaddrlen = sizeof(struct sockaddr_in);
901 memset( uaddr, 0, uaddrlen );
902 uin->sin_family = AF_INET;
903 uin->sin_port = win->sin_port;
904 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
908 /* Try to determine the needed space by the passed windows sockaddr space */
910 default: /* likely a ipv4 address */
911 case sizeof(struct WS_sockaddr_in):
912 uaddrlen = sizeof(struct sockaddr_in);
915 case sizeof(struct WS_sockaddr_ipx):
916 uaddrlen = sizeof(struct sockaddr_ipx);
919 case sizeof(struct WS_sockaddr_in6):
920 case sizeof(struct WS_sockaddr_in6_old):
921 uaddrlen = sizeof(struct sockaddr_in6);
924 memset( uaddr, 0, uaddrlen );
928 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
934 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
936 switch (uaddr->sa_family)
940 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
945 static const struct sockaddr_in6 emptyAddr;
946 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
947 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
951 static const struct sockaddr_in emptyAddr;
952 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
953 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
958 FIXME("unknown address family %d\n", uaddr->sa_family);
963 /* Returns 0 if successful, -1 if the buffer is too small */
964 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
968 switch(uaddr->sa_family)
973 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
974 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
977 switch (*wsaddrlen) /* how much can we copy? */
981 *wsaddrlen = sizeof(*wsipx);
982 wsipx->sa_socket=uipx->sipx_port;
986 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
994 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1000 wsipx->sa_family=WS_AF_IPX;
1011 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1012 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1014 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1016 win6old->sin6_family = WS_AF_INET6;
1017 win6old->sin6_port = uin6->sin6_port;
1018 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1019 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1020 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1021 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1022 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1023 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1024 win6->sin6_scope_id = uin6->sin6_scope_id;
1025 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1031 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1032 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1034 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1036 win->sin_family = WS_AF_INET;
1037 win->sin_port = uin->sin_port;
1038 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1039 memset(&win->sin_zero, 0, 8); /* Make sure the null padding is null */
1040 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1044 memset(wsaddr,0,*wsaddrlen);
1048 FIXME("Unknown address family %d\n", uaddr->sa_family);
1054 /**************************************************************************
1055 * Functions for handling overlapped I/O
1056 **************************************************************************/
1058 /* user APC called upon async completion */
1059 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1061 ws2_async *wsa = arg;
1063 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1064 iosb->Information, wsa->user_overlapped,
1066 HeapFree( GetProcessHeap(), 0, wsa );
1069 /***********************************************************************
1070 * WS2_recv (INTERNAL)
1072 * Workhorse for both synchronous and asynchronous recv() operations.
1074 static int WS2_recv( int fd, struct iovec* iov, int count,
1075 struct WS_sockaddr *lpFrom, LPINT lpFromlen,
1079 union generic_unix_sockaddr unix_sockaddr;
1082 hdr.msg_name = NULL;
1086 hdr.msg_namelen = sizeof(unix_sockaddr);
1087 hdr.msg_name = &unix_sockaddr;
1090 hdr.msg_namelen = 0;
1093 hdr.msg_iovlen = count;
1094 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1095 hdr.msg_accrights = NULL;
1096 hdr.msg_accrightslen = 0;
1098 hdr.msg_control = NULL;
1099 hdr.msg_controllen = 0;
1103 if ( (n = recvmsg(fd, &hdr, *lpFlags)) == -1 )
1106 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1107 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1109 * quoting linux 2.6 net/ipv4/tcp.c:
1110 * "According to UNIX98, msg_name/msg_namelen are ignored
1111 * on connected socket. I was just happy when found this 8) --ANK"
1113 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1114 * connection-oriented sockets, so don't try to update lpFrom.
1116 if ( lpFrom && hdr.msg_namelen &&
1117 ws_sockaddr_u2ws( &unix_sockaddr.addr, lpFrom, lpFromlen ) != 0 )
1119 /* The from buffer was too small, but we read the data
1120 * anyway. Is that really bad?
1127 /***********************************************************************
1128 * WS2_async_recv (INTERNAL)
1130 * Handler for overlapped recv() operations.
1132 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, ULONG_PTR *total )
1134 ws2_async* wsa = user;
1139 case STATUS_ALERTED:
1140 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1143 result = WS2_recv( fd, wsa->iovec, wsa->n_iovecs,
1144 wsa->addr, wsa->addrlen.ptr, &wsa->flags );
1145 wine_server_release_fd( wsa->hSocket, fd );
1148 status = STATUS_SUCCESS;
1149 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1153 if (errno == EINTR || errno == EAGAIN)
1155 status = STATUS_PENDING;
1156 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1161 status = wsaErrno(); /* FIXME: is this correct ???? */
1166 if (status != STATUS_PENDING)
1168 iosb->u.Status = status;
1169 iosb->Information = *total = result;
1174 /***********************************************************************
1175 * WS2_send (INTERNAL)
1177 * Workhorse for both synchronous and asynchronous send() operations.
1179 static int WS2_send( int fd, struct iovec* iov, int count,
1180 const struct WS_sockaddr *to, INT tolen, DWORD dwFlags )
1183 union generic_unix_sockaddr unix_addr;
1186 hdr.msg_name = NULL;
1187 hdr.msg_namelen = 0;
1191 hdr.msg_name = &unix_addr;
1192 hdr.msg_namelen = ws_sockaddr_ws2u( to, tolen, &unix_addr );
1193 if ( !hdr.msg_namelen )
1199 #if defined(HAVE_IPX) && defined(SOL_IPX)
1200 if(to->sa_family == WS_AF_IPX)
1202 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1204 unsigned int len=sizeof(int);
1206 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1207 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1208 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1209 * ipx type in the sockaddr_opx structure with the stored value.
1211 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1212 uipx->sipx_type = val;
1218 hdr.msg_iovlen = count;
1219 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1220 hdr.msg_accrights = NULL;
1221 hdr.msg_accrightslen = 0;
1223 hdr.msg_control = NULL;
1224 hdr.msg_controllen = 0;
1228 return sendmsg(fd, &hdr, dwFlags);
1231 /***********************************************************************
1232 * WS2_async_send (INTERNAL)
1234 * Handler for overlapped send() operations.
1236 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, ULONG_PTR *total )
1238 ws2_async* wsa = user;
1243 case STATUS_ALERTED:
1244 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1247 /* check to see if the data is ready (non-blocking) */
1248 result = WS2_send( fd, wsa->iovec, wsa->n_iovecs, wsa->addr, wsa->addrlen.val, wsa->flags );
1249 wine_server_release_fd( wsa->hSocket, fd );
1253 status = STATUS_SUCCESS;
1254 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1258 if (errno == EINTR || errno == EAGAIN)
1260 status = STATUS_PENDING;
1261 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1265 /* We set the status to a winsock error code and check for that
1266 later in NtStatusToWSAError () */
1267 status = wsaErrno();
1273 if (status != STATUS_PENDING)
1275 iosb->u.Status = status;
1276 iosb->Information = *total = result;
1281 /***********************************************************************
1282 * WS2_async_shutdown (INTERNAL)
1284 * Handler for shutdown() operations on overlapped sockets.
1286 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status )
1288 ws2_async* wsa = user;
1293 case STATUS_ALERTED:
1294 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1297 switch ( wsa->type )
1299 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1300 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1302 wine_server_release_fd( wsa->hSocket, fd );
1303 status = err ? wsaErrno() : STATUS_SUCCESS;
1306 iosb->u.Status = status;
1310 /***********************************************************************
1311 * WS2_register_async_shutdown (INTERNAL)
1313 * Helper function for WS_shutdown() on overlapped sockets.
1315 static int WS2_register_async_shutdown( SOCKET s, int type )
1317 struct ws2_async *wsa;
1320 TRACE("s %ld type %d\n", s, type);
1322 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1326 wsa->hSocket = SOCKET2HANDLE(s);
1328 wsa->completion_func = NULL;
1330 SERVER_START_REQ( register_async )
1332 req->handle = wsa->hSocket;
1334 req->async.callback = WS2_async_shutdown;
1335 req->async.iosb = &wsa->local_iosb;
1336 req->async.arg = wsa;
1337 req->async.apc = ws2_async_apc;
1338 req->async.cvalue = 0;
1339 status = wine_server_call( req );
1343 if (status != STATUS_PENDING)
1345 HeapFree( GetProcessHeap(), 0, wsa );
1346 return NtStatusToWSAError( status );
1351 /***********************************************************************
1354 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1360 TRACE("socket %04lx\n", s );
1361 is_blocking = _is_blocking(s);
1366 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1367 if (fd == -1) return INVALID_SOCKET;
1369 do_block(fd, POLLIN, -1);
1370 _sync_sock_state(s); /* let wineserver notice connection */
1371 release_sock_fd( s, fd );
1372 /* retrieve any error codes from it */
1373 SetLastError(_get_sock_error(s, FD_ACCEPT_BIT));
1374 /* FIXME: care about the error? */
1376 SERVER_START_REQ( accept_socket )
1378 req->lhandle = SOCKET2HANDLE(s);
1379 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1380 req->attributes = OBJ_INHERIT;
1381 set_error( wine_server_call( req ) );
1382 as = HANDLE2SOCKET( reply->handle );
1387 if (addr) WS_getpeername(as, addr, addrlen32);
1390 } while (is_blocking);
1391 return INVALID_SOCKET;
1394 /***********************************************************************
1397 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1399 int fd = get_sock_fd( s, 0, NULL );
1400 int res = SOCKET_ERROR;
1402 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1406 if (!name || (name->sa_family && !SUPPORTED_PF(name->sa_family)))
1408 SetLastError(WSAEAFNOSUPPORT);
1412 union generic_unix_sockaddr uaddr;
1413 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1416 SetLastError(WSAEFAULT);
1421 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
1422 if (name->sa_family == WS_AF_INET6 &&
1423 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
1426 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
1428 release_sock_fd( s, fd );
1429 SetLastError(WSAEAFNOSUPPORT);
1430 return INVALID_SOCKET;
1434 if (name->sa_family == WS_AF_INET)
1436 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1437 if (memcmp(&in4->sin_addr, &magic_loopback_addr, 4) == 0)
1439 /* Trying to bind to the default host interface, using
1440 * INADDR_ANY instead*/
1441 WARN("Trying to bind to magic IP address, using "
1442 "INADDR_ANY instead.\n");
1443 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
1446 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
1448 int loc_errno = errno;
1449 WARN("\tfailure - errno = %i\n", errno);
1454 SetLastError(WSAENOTSOCK);
1457 SetLastError(WSAEINVAL);
1460 SetLastError(wsaErrno());
1466 res=0; /* success */
1470 release_sock_fd( s, fd );
1475 /***********************************************************************
1476 * closesocket (WS2_32.3)
1478 int WINAPI WS_closesocket(SOCKET s)
1480 TRACE("socket %04lx\n", s);
1481 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
1482 return SOCKET_ERROR;
1485 /***********************************************************************
1486 * connect (WS2_32.4)
1488 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1490 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1492 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1496 union generic_unix_sockaddr uaddr;
1497 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1501 SetLastError(WSAEFAULT);
1505 if (name->sa_family == WS_AF_INET)
1507 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1508 if (memcmp(&in4->sin_addr, &magic_loopback_addr, 4) == 0)
1510 /* Trying to connect to magic replace-loopback address,
1511 * assuming we really want to connect to localhost */
1512 TRACE("Trying to connect to magic IP address, using "
1513 "INADDR_LOOPBACK instead.\n");
1514 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
1518 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
1519 goto connect_success;
1522 if (errno == EINPROGRESS)
1524 /* tell wineserver that a connection is in progress */
1525 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1526 FD_CONNECT|FD_READ|FD_WRITE,
1527 FD_WINE_CONNECTED|FD_WINE_LISTENING);
1528 if (_is_blocking(s))
1532 do_block(fd, POLLIN | POLLOUT, -1);
1533 _sync_sock_state(s); /* let wineserver notice connection */
1534 /* retrieve any error codes from it */
1535 result = _get_sock_error(s, FD_CONNECT_BIT);
1537 SetLastError(result);
1540 goto connect_success;
1545 SetLastError(WSAEWOULDBLOCK);
1550 SetLastError(wsaErrno());
1552 release_sock_fd( s, fd );
1554 return SOCKET_ERROR;
1557 release_sock_fd( s, fd );
1558 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1559 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1560 FD_CONNECT|FD_WINE_LISTENING);
1564 /***********************************************************************
1565 * WSAConnect (WS2_32.30)
1567 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
1568 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1569 LPQOS lpSQOS, LPQOS lpGQOS )
1571 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1572 FIXME("unsupported parameters!\n");
1573 return WS_connect( s, name, namelen );
1577 /***********************************************************************
1578 * getpeername (WS2_32.5)
1580 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1585 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, *namelen);
1587 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1588 if( (name == NULL) || (namelen == NULL) )
1590 SetLastError( WSAEFAULT );
1591 return SOCKET_ERROR;
1594 fd = get_sock_fd( s, 0, NULL );
1599 union generic_unix_sockaddr uaddr;
1600 unsigned int uaddrlen = sizeof(uaddr);
1602 if (getpeername(fd, &uaddr.addr, &uaddrlen) != 0)
1604 SetLastError(wsaErrno());
1606 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1608 /* The buffer was too small */
1609 SetLastError(WSAEFAULT);
1615 release_sock_fd( s, fd );
1620 /***********************************************************************
1621 * getsockname (WS2_32.6)
1623 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1628 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
1630 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1631 if( (name == NULL) || (namelen == NULL) )
1633 SetLastError( WSAEFAULT );
1634 return SOCKET_ERROR;
1637 fd = get_sock_fd( s, 0, NULL );
1642 union generic_unix_sockaddr uaddr;
1643 unsigned int uaddrlen = sizeof(uaddr);
1645 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
1647 SetLastError(wsaErrno());
1649 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
1651 SetLastError(WSAEINVAL);
1653 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1655 /* The buffer was too small */
1656 SetLastError(WSAEFAULT);
1662 release_sock_fd( s, fd );
1667 /***********************************************************************
1668 * getsockopt (WS2_32.7)
1670 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1671 INT optname, char *optval, INT *optlen)
1676 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
1677 s, level, optname, optval, *optlen);
1685 /* Handle common cases. The special cases are below, sorted
1687 case WS_SO_ACCEPTCONN:
1688 case WS_SO_BROADCAST:
1691 case WS_SO_KEEPALIVE:
1692 case WS_SO_OOBINLINE:
1694 case WS_SO_REUSEADDR:
1697 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1698 return SOCKET_ERROR;
1699 convert_sockopt(&level, &optname);
1700 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1702 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1705 release_sock_fd( s, fd );
1708 case WS_SO_DONTLINGER:
1710 struct linger lingval;
1711 unsigned int len = sizeof(struct linger);
1713 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
1715 SetLastError(WSAEFAULT);
1716 return SOCKET_ERROR;
1718 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1719 return SOCKET_ERROR;
1721 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1723 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1728 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
1729 *optlen = sizeof(BOOL);
1732 release_sock_fd( s, fd );
1736 /* As mentioned in setsockopt, Windows ignores this, so we
1737 * always return true here */
1738 case WS_SO_DONTROUTE:
1739 if (!optlen || *optlen < sizeof(BOOL) || !optval)
1741 SetLastError(WSAEFAULT);
1742 return SOCKET_ERROR;
1744 *(BOOL *)optval = TRUE;
1745 *optlen = sizeof(BOOL);
1750 struct linger lingval;
1751 unsigned int len = sizeof(struct linger);
1753 /* struct linger and LINGER have different sizes */
1754 if (!optlen || *optlen < sizeof(LINGER) || !optval)
1756 SetLastError(WSAEFAULT);
1757 return SOCKET_ERROR;
1759 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1760 return SOCKET_ERROR;
1762 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1764 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1769 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
1770 ((LINGER *)optval)->l_linger = lingval.l_linger;
1771 *optlen = sizeof(struct linger);
1774 release_sock_fd( s, fd );
1778 case WS_SO_MAX_MSG_SIZE:
1779 if (!optlen || *optlen < sizeof(int) || !optval)
1781 SetLastError(WSAEFAULT);
1782 return SOCKET_ERROR;
1784 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
1785 *(int *)optval = 65507;
1786 *optlen = sizeof(int);
1789 /* SO_OPENTYPE does not require a valid socket handle. */
1790 case WS_SO_OPENTYPE:
1791 if (!optlen || *optlen < sizeof(int) || !optval)
1793 SetLastError(WSAEFAULT);
1794 return SOCKET_ERROR;
1796 *(int *)optval = get_per_thread_data()->opentype;
1797 *optlen = sizeof(int);
1798 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
1802 case WS_SO_RCVTIMEO:
1805 case WS_SO_SNDTIMEO:
1807 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
1810 unsigned int len = sizeof(struct timeval);
1812 if (!optlen || *optlen < sizeof(int)|| !optval)
1814 SetLastError(WSAEFAULT);
1815 return SOCKET_ERROR;
1817 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1818 return SOCKET_ERROR;
1820 convert_sockopt(&level, &optname);
1821 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
1823 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1828 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1829 *optlen = sizeof(int);
1832 release_sock_fd( s, fd );
1837 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
1838 SetLastError(WSAENOPROTOOPT);
1839 return SOCKET_ERROR;
1840 } /* end switch(optname) */
1841 }/* end case WS_SOL_SOCKET */
1845 struct WS_sockaddr_ipx addr;
1846 IPX_ADDRESS_DATA *data;
1851 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
1853 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
1860 socklen_t len=sizeof(struct ipx);
1861 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
1864 *optval = (int)val.ipx_pt;
1867 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
1868 release_sock_fd( s, fd );
1873 * On a Win2000 system with one network card there are usually
1874 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
1875 * Using this call you can then retrieve info about this all.
1876 * In case of Linux it is a bit different. Usually you have
1877 * only "one" device active and further it is not possible to
1878 * query things like the linkspeed.
1880 FIXME("IPX_ADDRESS\n");
1881 namelen = sizeof(struct WS_sockaddr_ipx);
1882 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
1883 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
1885 data = (IPX_ADDRESS_DATA*)optval;
1886 memcpy(data->nodenum,&addr.sa_nodenum,sizeof(data->nodenum));
1887 memcpy(data->netnum,&addr.sa_netnum,sizeof(data->netnum));
1888 data->adapternum = 0;
1889 data->wan = FALSE; /* We are not on a wan for now .. */
1890 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
1891 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
1892 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
1893 * note 1MB = 1000kB in this case */
1896 case IPX_MAX_ADAPTER_NUM:
1897 FIXME("IPX_MAX_ADAPTER_NUM\n");
1898 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
1902 FIXME("IPX optname:%x\n", optname);
1903 return SOCKET_ERROR;
1904 }/* end switch(optname) */
1905 } /* end case NSPROTO_IPX */
1907 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
1908 case WS_IPPROTO_TCP:
1911 case WS_TCP_NODELAY:
1912 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1913 return SOCKET_ERROR;
1914 convert_sockopt(&level, &optname);
1915 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1917 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1920 release_sock_fd( s, fd );
1923 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
1924 return SOCKET_ERROR;
1929 case WS_IP_ADD_MEMBERSHIP:
1930 case WS_IP_DROP_MEMBERSHIP:
1934 case WS_IP_MULTICAST_IF:
1935 case WS_IP_MULTICAST_LOOP:
1936 case WS_IP_MULTICAST_TTL:
1940 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1941 return SOCKET_ERROR;
1942 convert_sockopt(&level, &optname);
1943 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1945 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1948 release_sock_fd( s, fd );
1950 case WS_IP_DONTFRAGMENT:
1951 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
1952 *(BOOL*)optval = FALSE;
1955 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
1956 return SOCKET_ERROR;
1959 FIXME("Unknown level: 0x%08x\n", level);
1960 return SOCKET_ERROR;
1961 } /* end switch(level) */
1964 /***********************************************************************
1968 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
1970 return htonl(hostlong);
1974 /***********************************************************************
1978 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
1980 return htons(hostshort);
1983 /***********************************************************************
1984 * WSAHtonl (WS2_32.46)
1985 * From MSDN description of error codes, this function should also
1986 * check if WinSock has been initialized and the socket is a valid
1987 * socket. But why? This function only translates a host byte order
1988 * u_long into a network byte order u_long...
1990 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
1994 *lpnetlong = htonl(hostlong);
1997 WSASetLastError(WSAEFAULT);
1998 return SOCKET_ERROR;
2001 /***********************************************************************
2002 * WSAHtons (WS2_32.47)
2003 * From MSDN description of error codes, this function should also
2004 * check if WinSock has been initialized and the socket is a valid
2005 * socket. But why? This function only translates a host byte order
2006 * u_short into a network byte order u_short...
2008 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2013 *lpnetshort = htons(hostshort);
2016 WSASetLastError(WSAEFAULT);
2017 return SOCKET_ERROR;
2021 /***********************************************************************
2022 * inet_addr (WINSOCK.10)
2023 * inet_addr (WS2_32.11)
2025 WS_u_long WINAPI WS_inet_addr(const char *cp)
2027 if (!cp) return INADDR_NONE;
2028 return inet_addr(cp);
2032 /***********************************************************************
2033 * ntohl (WINSOCK.14)
2036 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2038 return ntohl(netlong);
2042 /***********************************************************************
2043 * ntohs (WINSOCK.15)
2046 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2048 return ntohs(netshort);
2052 /***********************************************************************
2053 * inet_ntoa (WS2_32.12)
2055 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2057 /* use "buffer for dummies" here because some applications have a
2058 * propensity to decode addresses in ws_hostent structure without
2059 * saving them first...
2061 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2063 char* s = inet_ntoa(*((struct in_addr*)&in));
2069 SetLastError(wsaErrno());
2073 /**********************************************************************
2074 * WSAIoctl (WS2_32.50)
2077 INT WINAPI WSAIoctl(SOCKET s,
2078 DWORD dwIoControlCode,
2081 LPVOID lpbOutBuffer,
2083 LPDWORD lpcbBytesReturned,
2084 LPWSAOVERLAPPED lpOverlapped,
2085 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2087 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
2088 s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpbOutBuffer,
2089 cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
2091 switch( dwIoControlCode )
2094 if (cbInBuffer != sizeof(WS_u_long)) {
2095 WSASetLastError(WSAEFAULT);
2096 return SOCKET_ERROR;
2098 return WS_ioctlsocket( s, WS_FIONBIO, lpvInBuffer);
2101 if (cbOutBuffer != sizeof(WS_u_long)) {
2102 WSASetLastError(WSAEFAULT);
2103 return SOCKET_ERROR;
2105 return WS_ioctlsocket( s, WS_FIONREAD, lpbOutBuffer);
2107 case WS_SIO_GET_INTERFACE_LIST:
2109 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
2110 DWORD size, numInt, apiReturn;
2113 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
2117 WSASetLastError(WSAEFAULT);
2118 return SOCKET_ERROR;
2120 if (!lpcbBytesReturned)
2122 WSASetLastError(WSAEFAULT);
2123 return SOCKET_ERROR;
2126 fd = get_sock_fd( s, 0, NULL );
2127 if (fd == -1) return SOCKET_ERROR;
2129 apiReturn = GetAdaptersInfo(NULL, &size);
2130 if (apiReturn == ERROR_NO_DATA)
2134 else if (apiReturn == ERROR_BUFFER_OVERFLOW)
2136 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
2140 if (GetAdaptersInfo(table, &size) == NO_ERROR)
2142 PIP_ADAPTER_INFO ptr;
2144 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > cbOutBuffer)
2146 WARN("Buffer too small = %u, cbOutBuffer = %u\n", size, cbOutBuffer);
2147 HeapFree(GetProcessHeap(),0,table);
2148 release_sock_fd( s, fd );
2149 WSASetLastError(WSAEFAULT);
2150 return SOCKET_ERROR;
2152 for (ptr = table, numInt = 0; ptr;
2153 ptr = ptr->Next, intArray++, numInt++)
2155 unsigned int addr, mask, bcast;
2156 struct ifreq ifInfo;
2158 /* Socket Status Flags */
2159 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
2160 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2162 ERR("Error obtaining status flags for socket!\n");
2163 HeapFree(GetProcessHeap(),0,table);
2164 release_sock_fd( s, fd );
2165 WSASetLastError(WSAEINVAL);
2166 return SOCKET_ERROR;
2170 /* set flags; the values of IFF_* are not the same
2171 under Linux and Windows, therefore must generate
2173 intArray->iiFlags = 0;
2174 if (ifInfo.ifr_flags & IFF_BROADCAST)
2175 intArray->iiFlags |= WS_IFF_BROADCAST;
2176 #ifdef IFF_POINTOPOINT
2177 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
2178 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
2180 if (ifInfo.ifr_flags & IFF_LOOPBACK)
2181 intArray->iiFlags |= WS_IFF_LOOPBACK;
2182 if (ifInfo.ifr_flags & IFF_UP)
2183 intArray->iiFlags |= WS_IFF_UP;
2184 if (ifInfo.ifr_flags & IFF_MULTICAST)
2185 intArray->iiFlags |= WS_IFF_MULTICAST;
2188 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
2189 mask = inet_addr(ptr->IpAddressList.IpMask.String);
2190 bcast = addr | ~mask;
2191 intArray->iiAddress.AddressIn.sin_family = AF_INET;
2192 intArray->iiAddress.AddressIn.sin_port = 0;
2193 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
2195 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2196 intArray->iiNetmask.AddressIn.sin_port = 0;
2197 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
2199 intArray->iiBroadcastAddress.AddressIn.sin_family =
2201 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
2202 intArray->iiBroadcastAddress.AddressIn.sin_addr.
2208 ERR("Unable to get interface table!\n");
2209 release_sock_fd( s, fd );
2210 HeapFree(GetProcessHeap(),0,table);
2211 WSASetLastError(WSAEINVAL);
2212 return SOCKET_ERROR;
2214 HeapFree(GetProcessHeap(),0,table);
2218 release_sock_fd( s, fd );
2219 WSASetLastError(WSAEINVAL);
2220 return SOCKET_ERROR;
2225 ERR("Unable to get interface table!\n");
2226 release_sock_fd( s, fd );
2227 WSASetLastError(WSAEINVAL);
2228 return SOCKET_ERROR;
2230 /* Calculate the size of the array being returned */
2231 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2232 release_sock_fd( s, fd );
2236 case WS_SIO_ADDRESS_LIST_CHANGE:
2237 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
2238 /* FIXME: error and return code depend on whether socket was created
2239 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
2242 case WS_SIO_ADDRESS_LIST_QUERY:
2246 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
2248 if (!lpcbBytesReturned)
2250 WSASetLastError(WSAEFAULT);
2251 return SOCKET_ERROR;
2254 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
2256 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
2259 if (!table || GetAdaptersInfo(table, &size))
2261 HeapFree(GetProcessHeap(), 0, table);
2262 WSASetLastError(WSAEINVAL);
2263 return SOCKET_ERROR;
2266 for (p = table, num = 0; p; p = p->Next)
2267 if (p->IpAddressList.IpAddress.String[0]) num++;
2269 need = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
2270 need += sizeof(SOCKADDR) * num;
2271 *lpcbBytesReturned = need;
2273 if (need > cbOutBuffer)
2275 HeapFree(GetProcessHeap(), 0, table);
2276 WSASetLastError(WSAEFAULT);
2277 return SOCKET_ERROR;
2284 SOCKET_ADDRESS_LIST *sa_list = (SOCKET_ADDRESS_LIST *)lpbOutBuffer;
2285 SOCKADDR_IN *sockaddr;
2287 sa = sa_list->Address;
2288 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
2289 sa_list->iAddressCount = num;
2291 for (p = table, i = 0; p; p = p->Next)
2293 if (!p->IpAddressList.IpAddress.String[0]) continue;
2295 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
2296 sa[i].iSockaddrLength = sizeof(SOCKADDR);
2298 sockaddr[i].sin_family = AF_INET;
2299 sockaddr[i].sin_port = 0;
2300 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
2305 HeapFree(GetProcessHeap(), 0, table);
2310 WARN("unable to get IP address list\n");
2311 WSASetLastError(WSAEINVAL);
2312 return SOCKET_ERROR;
2316 FIXME("SIO_FLUSH: stub.\n");
2319 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
2320 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(lpvInBuffer));
2321 WSASetLastError(WSAEOPNOTSUPP);
2322 return SOCKET_ERROR;
2325 FIXME("unsupported WS_IOCTL cmd (%08x)\n", dwIoControlCode);
2326 WSASetLastError(WSAEOPNOTSUPP);
2327 return SOCKET_ERROR;
2334 /***********************************************************************
2335 * ioctlsocket (WS2_32.10)
2337 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
2342 TRACE("socket %04lx, cmd %08x, ptr %p\n", s, cmd, argp);
2351 if( _get_sock_mask(s) )
2353 /* AsyncSelect()'ed sockets are always nonblocking */
2354 if (*argp) return 0;
2355 SetLastError(WSAEINVAL);
2356 return SOCKET_ERROR;
2358 fd = get_sock_fd( s, 0, NULL );
2364 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
2365 ret = fcntl( fd, F_SETFL, O_NONBLOCK );
2369 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
2370 ret = fcntl( fd, F_SETFL, 0 );
2372 release_sock_fd( s, fd );
2374 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2376 return SOCKET_ERROR;
2383 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2384 SetLastError(WSAEINVAL);
2385 return SOCKET_ERROR;
2387 case SIOCGIFBRDADDR:
2388 case SIOCGIFNETMASK:
2390 /* These don't need any special handling. They are used by
2391 WsControl, and are here to suppress an unnecessary warning. */
2395 /* Netscape tries hard to use bogus ioctl 0x667e */
2396 /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
2397 * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
2399 WARN("\tunknown WS_IOCTL cmd (%08x)\n", cmd);
2403 fd = get_sock_fd( s, 0, NULL );
2406 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2408 release_sock_fd( s, fd );
2411 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2412 release_sock_fd( s, fd );
2414 return SOCKET_ERROR;
2417 /***********************************************************************
2418 * listen (WS2_32.13)
2420 int WINAPI WS_listen(SOCKET s, int backlog)
2422 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2424 TRACE("socket %04lx, backlog %d\n", s, backlog);
2427 if (listen(fd, backlog) == 0)
2429 release_sock_fd( s, fd );
2430 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
2432 FD_CONNECT|FD_WINE_CONNECTED);
2435 SetLastError(wsaErrno());
2436 release_sock_fd( s, fd );
2438 return SOCKET_ERROR;
2441 /***********************************************************************
2444 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2446 DWORD n, dwFlags = flags;
2452 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2453 return SOCKET_ERROR;
2458 /***********************************************************************
2459 * recvfrom (WS2_32.17)
2461 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2462 struct WS_sockaddr *from, int *fromlen)
2464 DWORD n, dwFlags = flags;
2470 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2471 return SOCKET_ERROR;
2476 /* allocate a poll array for the corresponding fd sets */
2477 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
2478 const WS_fd_set *exceptfds, int *count_ptr )
2480 int i, j = 0, count = 0;
2483 if (readfds) count += readfds->fd_count;
2484 if (writefds) count += writefds->fd_count;
2485 if (exceptfds) count += exceptfds->fd_count;
2487 if (!count) return NULL;
2488 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0])))) return NULL;
2490 for (i = 0; i < readfds->fd_count; i++, j++)
2492 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
2493 fds[j].events = POLLIN;
2497 for (i = 0; i < writefds->fd_count; i++, j++)
2499 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
2500 fds[j].events = POLLOUT;
2504 for (i = 0; i < exceptfds->fd_count; i++, j++)
2506 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
2507 fds[j].events = POLLHUP;
2513 /* release the file descriptor obtained in fd_sets_to_poll */
2514 /* must be called with the original fd_set arrays, before calling get_poll_results */
2515 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
2516 const WS_fd_set *exceptfds, struct pollfd *fds )
2522 for (i = 0; i < readfds->fd_count; i++, j++)
2523 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
2527 for (i = 0; i < writefds->fd_count; i++, j++)
2528 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
2532 for (i = 0; i < exceptfds->fd_count; i++, j++)
2533 if (fds[j].fd != -1)
2535 /* make sure we have a real error before releasing the fd */
2536 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
2537 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
2542 /* map the poll results back into the Windows fd sets */
2543 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
2544 const struct pollfd *fds )
2546 int i, j = 0, k, total = 0;
2550 for (i = k = 0; i < readfds->fd_count; i++, j++)
2551 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
2552 readfds->fd_count = k;
2557 for (i = k = 0; i < writefds->fd_count; i++, j++)
2558 if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
2559 writefds->fd_count = k;
2564 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
2565 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
2566 exceptfds->fd_count = k;
2573 /***********************************************************************
2574 * select (WS2_32.18)
2576 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
2577 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
2578 const struct WS_timeval* ws_timeout)
2580 struct pollfd *pollfds;
2581 int count, ret, timeout = -1;
2583 TRACE("read %p, write %p, excp %p timeout %p\n",
2584 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
2586 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )) && count)
2588 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2589 return SOCKET_ERROR;
2592 if (ws_timeout) timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
2594 ret = poll( pollfds, count, timeout );
2595 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2597 if (ret == -1) SetLastError(wsaErrno());
2598 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2599 HeapFree( GetProcessHeap(), 0, pollfds );
2603 /* helper to send completion messages for client-only i/o operation case */
2604 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG_PTR Information )
2608 SERVER_START_REQ( add_fd_completion )
2610 req->handle = SOCKET2HANDLE(sock);
2611 req->cvalue = CompletionValue;
2612 req->status = CompletionStatus;
2613 req->information = Information;
2614 status = wine_server_call( req );
2620 /***********************************************************************
2623 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
2629 wsabuf.buf = (char*) buf;
2631 if ( WSASendTo( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
2632 return SOCKET_ERROR;
2637 /***********************************************************************
2638 * WSASend (WS2_32.72)
2640 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2641 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2642 LPWSAOVERLAPPED lpOverlapped,
2643 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2645 return WSASendTo( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
2646 NULL, 0, lpOverlapped, lpCompletionRoutine );
2649 /***********************************************************************
2650 * WSASendDisconnect (WS2_32.73)
2652 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
2654 return WS_shutdown( s, SD_SEND );
2658 /***********************************************************************
2659 * WSASendTo (WS2_32.74)
2661 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2662 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2663 const struct WS_sockaddr *to, int tolen,
2664 LPWSAOVERLAPPED lpOverlapped,
2665 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2667 unsigned int i, options;
2669 struct iovec iovec[WS_MSG_MAXIOVLEN];
2670 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
2672 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
2673 s, lpBuffers, dwBufferCount, dwFlags,
2674 to, tolen, lpOverlapped, lpCompletionRoutine);
2676 if (dwBufferCount > WS_MSG_MAXIOVLEN)
2678 WSASetLastError( WSAEINVAL );
2679 return SOCKET_ERROR;
2682 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
2683 TRACE( "fd=%d, options=%x\n", fd, options );
2685 if ( fd == -1 ) return SOCKET_ERROR;
2687 if ( !lpNumberOfBytesSent )
2693 for ( i = 0; i < dwBufferCount; i++ )
2695 iovec[i].iov_base = lpBuffers[i].buf;
2696 iovec[i].iov_len = lpBuffers[i].len;
2701 n = WS2_send( fd, iovec, dwBufferCount, to, tolen, dwFlags );
2702 if (n != -1 || errno != EINTR) break;
2704 if (n == -1 && errno != EAGAIN)
2707 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
2711 if ((lpOverlapped || lpCompletionRoutine) &&
2712 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
2714 IO_STATUS_BLOCK *iosb;
2715 struct ws2_async *wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
2722 release_sock_fd( s, fd );
2724 wsa->hSocket = SOCKET2HANDLE(s);
2725 wsa->addr = (struct WS_sockaddr *)to;
2726 wsa->addrlen.val = tolen;
2728 wsa->user_overlapped = lpOverlapped;
2729 wsa->completion_func = lpCompletionRoutine;
2730 wsa->n_iovecs = dwBufferCount;
2731 memcpy( wsa->iovec, iovec, dwBufferCount * sizeof(*iovec) );
2733 iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
2736 iosb->u.Status = STATUS_PENDING;
2737 iosb->Information = 0;
2739 SERVER_START_REQ( register_async )
2741 req->handle = wsa->hSocket;
2742 req->type = ASYNC_TYPE_WRITE;
2743 req->async.callback = WS2_async_send;
2744 req->async.iosb = iosb;
2745 req->async.arg = wsa;
2746 req->async.apc = ws2_async_apc;
2747 req->async.event = lpCompletionRoutine ? 0 : lpOverlapped->hEvent;
2748 req->async.cvalue = cvalue;
2749 err = wine_server_call( req );
2753 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
2754 WSASetLastError( NtStatusToWSAError( err ));
2755 return SOCKET_ERROR;
2758 iosb->u.Status = STATUS_SUCCESS;
2759 iosb->Information = n;
2760 *lpNumberOfBytesSent = n;
2761 if (!wsa->completion_func)
2763 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
2764 SetEvent( lpOverlapped->hEvent );
2765 HeapFree( GetProcessHeap(), 0, wsa );
2767 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
2768 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
2772 if ( _is_blocking(s) )
2774 /* On a blocking non-overlapped stream socket,
2775 * sending blocks until the entire buffer is sent. */
2776 DWORD timeout_start = GetTickCount();
2777 unsigned int first_buff = 0;
2779 *lpNumberOfBytesSent = 0;
2781 while (first_buff < dwBufferCount)
2784 int timeout = GET_SNDTIMEO(fd);
2788 *lpNumberOfBytesSent += n;
2789 while (first_buff < dwBufferCount && iovec[first_buff].iov_len <= n)
2790 n -= iovec[first_buff++].iov_len;
2791 if (first_buff >= dwBufferCount) break;
2792 iovec[first_buff].iov_base = (char*)iovec[first_buff].iov_base + n;
2793 iovec[first_buff].iov_len -= n;
2798 timeout -= GetTickCount() - timeout_start;
2799 if (timeout < 0) timeout = 0;
2803 pfd.events = POLLOUT;
2805 if (!timeout || !poll( &pfd, 1, timeout ))
2808 goto error; /* msdn says a timeout in send is fatal */
2811 n = WS2_send( fd, iovec + first_buff, dwBufferCount - first_buff, to, tolen, dwFlags );
2812 if (n == -1 && errno != EAGAIN && errno != EINTR)
2819 else /* non-blocking */
2821 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
2824 err = WSAEWOULDBLOCK;
2827 *lpNumberOfBytesSent = n;
2830 TRACE(" -> %i bytes\n", *lpNumberOfBytesSent);
2832 release_sock_fd( s, fd );
2836 release_sock_fd( s, fd );
2837 WARN(" -> ERROR %d\n", err);
2838 WSASetLastError(err);
2839 return SOCKET_ERROR;
2842 /***********************************************************************
2843 * sendto (WS2_32.20)
2845 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
2846 const struct WS_sockaddr *to, int tolen)
2852 wsabuf.buf = (char*) buf;
2854 if ( WSASendTo(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
2855 return SOCKET_ERROR;
2860 /***********************************************************************
2861 * setsockopt (WS2_32.21)
2863 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
2864 const char *optval, int optlen)
2868 struct linger linger;
2869 struct timeval tval;
2871 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2872 s, level, optname, optval, optlen);
2874 /* some broken apps pass the value directly instead of a pointer to it */
2875 if(IS_INTRESOURCE(optval))
2877 SetLastError(WSAEFAULT);
2878 return SOCKET_ERROR;
2886 /* Some options need some conversion before they can be sent to
2887 * setsockopt. The conversions are done here, then they will fall though
2888 * to the general case. Special options that are not passed to
2889 * setsockopt follow below that.*/
2891 case WS_SO_DONTLINGER:
2892 linger.l_onoff = *((const int*)optval) ? 0: 1;
2893 linger.l_linger = 0;
2895 optname = SO_LINGER;
2896 optval = (char*)&linger;
2897 optlen = sizeof(struct linger);
2901 linger.l_onoff = ((LINGER*)optval)->l_onoff;
2902 linger.l_linger = ((LINGER*)optval)->l_linger;
2903 /* FIXME: what is documented behavior if SO_LINGER optval
2906 optname = SO_LINGER;
2907 optval = (char*)&linger;
2908 optlen = sizeof(struct linger);
2912 if (*(const int*)optval < 2048)
2914 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
2919 /* The options listed here don't need any special handling. Thanks to
2920 * the conversion happening above, options from there will fall through
2922 case WS_SO_ACCEPTCONN:
2923 case WS_SO_BROADCAST:
2925 case WS_SO_KEEPALIVE:
2926 case WS_SO_OOBINLINE:
2927 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
2928 * however, using it the BSD way fixes bug 8513 and seems to be what
2929 * most programmers assume, anyway */
2930 case WS_SO_REUSEADDR:
2933 convert_sockopt(&level, &optname);
2936 /* SO_DEBUG is a privileged operation, ignore it. */
2938 TRACE("Ignoring SO_DEBUG\n");
2941 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
2942 * socket. According to MSDN, this option is silently ignored.*/
2943 case WS_SO_DONTROUTE:
2944 TRACE("Ignoring SO_DONTROUTE\n");
2947 /* Stops two sockets from being bound to the same port. Always happens
2948 * on unix systems, so just drop it. */
2949 case WS_SO_EXCLUSIVEADDRUSE:
2950 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
2953 /* SO_OPENTYPE does not require a valid socket handle. */
2954 case WS_SO_OPENTYPE:
2955 if (!optlen || optlen < sizeof(int) || !optval)
2957 SetLastError(WSAEFAULT);
2958 return SOCKET_ERROR;
2960 get_per_thread_data()->opentype = *(const int *)optval;
2961 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2965 case WS_SO_RCVTIMEO:
2968 case WS_SO_SNDTIMEO:
2970 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
2971 if (optval && optlen == sizeof(UINT32)) {
2972 /* WinSock passes milliseconds instead of struct timeval */
2973 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
2974 tval.tv_sec = *(const UINT32*)optval / 1000;
2975 /* min of 500 milliseconds */
2976 if (tval.tv_sec == 0 && tval.tv_usec < 500000)
2977 tval.tv_usec = 500000;
2978 optlen = sizeof(struct timeval);
2979 optval = (char*)&tval;
2980 } else if (optlen == sizeof(struct timeval)) {
2981 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
2983 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
2986 convert_sockopt(&level, &optname);
2991 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
2992 SetLastError(WSAENOPROTOOPT);
2993 return SOCKET_ERROR;
2995 break; /* case WS_SOL_SOCKET */
3002 fd = get_sock_fd( s, 0, NULL );
3003 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
3005 /* We try to set the ipx type on ipx socket level. */
3007 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
3009 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
3010 release_sock_fd( s, fd );
3011 return SOCKET_ERROR;
3016 /* Should we retrieve val using a getsockopt call and then
3017 * set the modified one? */
3018 val.ipx_pt = *optval;
3019 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
3022 release_sock_fd( s, fd );
3025 case IPX_FILTERPTYPE:
3026 /* Sets the receive filter packet type, at the moment we don't support it */
3027 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
3028 /* Returning 0 is better for now than returning a SOCKET_ERROR */
3032 FIXME("opt_name:%x\n", optname);
3033 return SOCKET_ERROR;
3035 break; /* case NSPROTO_IPX */
3038 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3039 case WS_IPPROTO_TCP:
3042 case WS_TCP_NODELAY:
3043 convert_sockopt(&level, &optname);
3046 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3047 return SOCKET_ERROR;
3054 case WS_IP_ADD_MEMBERSHIP:
3055 case WS_IP_DROP_MEMBERSHIP:
3059 case WS_IP_MULTICAST_IF:
3060 case WS_IP_MULTICAST_LOOP:
3061 case WS_IP_MULTICAST_TTL:
3065 convert_sockopt(&level, &optname);
3067 case WS_IP_DONTFRAGMENT:
3068 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
3071 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3072 return SOCKET_ERROR;
3077 FIXME("Unknown level: 0x%08x\n", level);
3078 return SOCKET_ERROR;
3079 } /* end switch(level) */
3081 /* avoid endianness issues if argument is a 16-bit int */
3082 if (optval && optlen < sizeof(int))
3084 woptval= *((const INT16 *) optval);
3085 optval= (char*) &woptval;
3088 fd = get_sock_fd( s, 0, NULL );
3089 if (fd == -1) return SOCKET_ERROR;
3091 if (setsockopt(fd, level, optname, optval, optlen) == 0)
3093 release_sock_fd( s, fd );
3096 TRACE("Setting socket error, %d\n", wsaErrno());
3097 SetLastError(wsaErrno());
3098 release_sock_fd( s, fd );
3100 return SOCKET_ERROR;
3103 /***********************************************************************
3104 * shutdown (WS2_32.22)
3106 int WINAPI WS_shutdown(SOCKET s, int how)
3108 int fd, err = WSAENOTSOCK;
3109 unsigned int options, clear_flags = 0;
3111 fd = get_sock_fd( s, 0, &options );
3112 TRACE("socket %04lx, how %i %x\n", s, how, options );
3115 return SOCKET_ERROR;
3119 case 0: /* drop receives */
3120 clear_flags |= FD_READ;
3122 case 1: /* drop sends */
3123 clear_flags |= FD_WRITE;
3125 case 2: /* drop all */
3126 clear_flags |= FD_READ|FD_WRITE;
3128 clear_flags |= FD_WINE_LISTENING;
3131 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3136 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3139 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3143 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3144 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3147 if (err) goto error;
3149 else /* non-overlapped mode */
3151 if ( shutdown( fd, how ) )
3158 release_sock_fd( s, fd );
3159 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3160 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
3164 release_sock_fd( s, fd );
3165 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3166 WSASetLastError( err );
3167 return SOCKET_ERROR;
3170 /***********************************************************************
3171 * socket (WS2_32.23)
3173 SOCKET WINAPI WS_socket(int af, int type, int protocol)
3175 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
3177 return WSASocketA( af, type, protocol, NULL, 0,
3178 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
3182 /***********************************************************************
3183 * gethostbyaddr (WS2_32.51)
3185 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
3187 struct WS_hostent *retval = NULL;
3188 struct hostent* host;
3190 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3193 struct hostent hostentry;
3196 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3198 int res = gethostbyaddr_r(addr, len, type,
3199 &hostentry, extrabuf, ebufsize, &host, &locerr);
3200 if( res != ERANGE) break;
3202 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3204 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3206 EnterCriticalSection( &csWSgetXXXbyYYY );
3207 host = gethostbyaddr(addr, len, type);
3208 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3210 if( host != NULL ) retval = WS_dup_he(host);
3211 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3212 HeapFree(GetProcessHeap(),0,extrabuf);
3214 LeaveCriticalSection( &csWSgetXXXbyYYY );
3216 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
3220 /***********************************************************************
3221 * gethostbyname (WS2_32.52)
3223 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
3225 struct WS_hostent *retval = NULL;
3226 struct hostent* host;
3227 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3230 struct hostent hostentry;
3231 int locerr = ENOBUFS;
3234 if( !name || !name[0]) {
3236 if( gethostname( buf, 100) == -1) {
3237 SetLastError( WSAENOBUFS); /* appropriate ? */
3241 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3243 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3245 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
3246 if( res != ERANGE) break;
3248 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3250 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3252 EnterCriticalSection( &csWSgetXXXbyYYY );
3253 host = gethostbyname(name);
3254 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3256 if (host) retval = WS_dup_he(host);
3257 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3258 HeapFree(GetProcessHeap(),0,extrabuf);
3260 LeaveCriticalSection( &csWSgetXXXbyYYY );
3262 if (retval && retval->h_addr_list[0][0] == 127 &&
3263 strcmp(name, "localhost") != 0)
3265 /* hostname != "localhost" but has loopback address. replace by our
3266 * special address.*/
3267 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
3269 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3274 /***********************************************************************
3275 * getprotobyname (WS2_32.53)
3277 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3279 struct WS_protoent* retval = NULL;
3280 #ifdef HAVE_GETPROTOBYNAME
3281 struct protoent* proto;
3282 EnterCriticalSection( &csWSgetXXXbyYYY );
3283 if( (proto = getprotobyname(name)) != NULL )
3285 retval = WS_dup_pe(proto);
3288 MESSAGE("protocol %s not found; You might want to add "
3289 "this to /etc/protocols\n", debugstr_a(name) );
3290 SetLastError(WSANO_DATA);
3292 LeaveCriticalSection( &csWSgetXXXbyYYY );
3294 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3299 /***********************************************************************
3300 * getprotobynumber (WS2_32.54)
3302 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3304 struct WS_protoent* retval = NULL;
3305 #ifdef HAVE_GETPROTOBYNUMBER
3306 struct protoent* proto;
3307 EnterCriticalSection( &csWSgetXXXbyYYY );
3308 if( (proto = getprotobynumber(number)) != NULL )
3310 retval = WS_dup_pe(proto);
3313 MESSAGE("protocol number %d not found; You might want to add "
3314 "this to /etc/protocols\n", number );
3315 SetLastError(WSANO_DATA);
3317 LeaveCriticalSection( &csWSgetXXXbyYYY );
3319 TRACE("%i ret %p\n", number, retval);
3324 /***********************************************************************
3325 * getservbyname (WS2_32.55)
3327 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3329 struct WS_servent* retval = NULL;
3330 struct servent* serv;
3332 char *proto_str = NULL;
3334 if (!(name_str = strdup_lower(name))) return NULL;
3336 if (proto && *proto)
3338 if (!(proto_str = strdup_lower(proto)))
3340 HeapFree( GetProcessHeap(), 0, name_str );
3345 EnterCriticalSection( &csWSgetXXXbyYYY );
3346 serv = getservbyname(name_str, proto_str);
3349 retval = WS_dup_se(serv);
3351 else SetLastError(WSANO_DATA);
3352 LeaveCriticalSection( &csWSgetXXXbyYYY );
3353 HeapFree( GetProcessHeap(), 0, proto_str );
3354 HeapFree( GetProcessHeap(), 0, name_str );
3355 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
3359 /***********************************************************************
3360 * freeaddrinfo (WS2_32.@)
3362 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
3365 struct WS_addrinfo *next;
3367 HeapFree(GetProcessHeap(),0,res->ai_canonname);
3368 HeapFree(GetProcessHeap(),0,res->ai_addr);
3369 next = res->ai_next;
3370 HeapFree(GetProcessHeap(),0,res);
3375 /* helper functions for getaddrinfo()/getnameinfo() */
3376 static int convert_aiflag_w2u(int winflags) {
3377 int i, unixflags = 0;
3379 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3380 if (ws_aiflag_map[i][0] & winflags) {
3381 unixflags |= ws_aiflag_map[i][1];
3382 winflags &= ~ws_aiflag_map[i][0];
3385 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
3389 static int convert_niflag_w2u(int winflags) {
3390 int i, unixflags = 0;
3392 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
3393 if (ws_niflag_map[i][0] & winflags) {
3394 unixflags |= ws_niflag_map[i][1];
3395 winflags &= ~ws_niflag_map[i][0];
3398 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
3402 static int convert_aiflag_u2w(int unixflags) {
3403 int i, winflags = 0;
3405 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3406 if (ws_aiflag_map[i][1] & unixflags) {
3407 winflags |= ws_aiflag_map[i][0];
3408 unixflags &= ~ws_aiflag_map[i][1];
3410 if (unixflags) /* will warn usually */
3411 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
3415 static int convert_eai_u2w(int unixret) {
3418 for (i=0;ws_eai_map[i][0];i++)
3419 if (ws_eai_map[i][1] == unixret)
3420 return ws_eai_map[i][0];
3424 /***********************************************************************
3425 * getaddrinfo (WS2_32.@)
3427 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
3429 #ifdef HAVE_GETADDRINFO
3430 struct addrinfo *unixaires = NULL;
3432 struct addrinfo unixhints, *punixhints = NULL;
3433 CHAR *node = NULL, *serv = NULL;
3436 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
3439 if (!(serv = strdup_lower(servname))) {
3440 HeapFree(GetProcessHeap(), 0, node);
3441 return WSA_NOT_ENOUGH_MEMORY;
3446 punixhints = &unixhints;
3448 memset(&unixhints, 0, sizeof(unixhints));
3449 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
3450 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
3451 punixhints->ai_family = 0;
3453 punixhints->ai_family = convert_af_w2u(hints->ai_family);
3454 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
3455 punixhints->ai_socktype = 0;
3457 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
3458 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
3459 punixhints->ai_protocol = 0;
3461 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
3464 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
3465 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
3467 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
3469 HeapFree(GetProcessHeap(), 0, node);
3470 HeapFree(GetProcessHeap(), 0, serv);
3473 struct addrinfo *xuai = unixaires;
3474 struct WS_addrinfo **xai = res;
3478 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
3484 *xai = ai;xai = &ai->ai_next;
3485 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
3486 ai->ai_family = convert_af_u2w(xuai->ai_family);
3487 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
3488 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
3489 if (xuai->ai_canonname) {
3490 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
3491 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
3492 if (!ai->ai_canonname)
3494 strcpy(ai->ai_canonname,xuai->ai_canonname);
3496 len = xuai->ai_addrlen;
3497 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
3500 ai->ai_addrlen = len;
3502 int winlen = ai->ai_addrlen;
3504 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
3505 ai->ai_addrlen = winlen;
3509 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
3512 ai->ai_addrlen = len;
3514 xuai = xuai->ai_next;
3516 freeaddrinfo(unixaires);
3518 result = convert_eai_u2w(result);
3524 if (*res) WS_freeaddrinfo(*res);
3525 if (unixaires) freeaddrinfo(unixaires);
3527 return WSA_NOT_ENOUGH_MEMORY;
3529 FIXME("getaddrinfo() failed, not found during buildtime.\n");
3534 /***********************************************************************
3535 * GetAddrInfoW (WS2_32.@)
3537 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
3539 FIXME("empty stub!\n");
3543 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
3544 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
3546 #ifdef HAVE_GETNAMEINFO
3548 union generic_unix_sockaddr sa_u;
3551 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
3552 serv, servlen, flags);
3554 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
3557 WSASetLastError(WSAEFAULT);
3558 return WSA_NOT_ENOUGH_MEMORY;
3560 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
3561 return convert_eai_u2w(ret);
3563 FIXME("getnameinfo() failed, not found during buildtime.\n");
3568 /***********************************************************************
3569 * getservbyport (WS2_32.56)
3571 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
3573 struct WS_servent* retval = NULL;
3574 #ifdef HAVE_GETSERVBYPORT
3575 struct servent* serv;
3576 char *proto_str = NULL;
3578 if (proto && *proto)
3580 if (!(proto_str = strdup_lower(proto))) return NULL;
3582 EnterCriticalSection( &csWSgetXXXbyYYY );
3583 if( (serv = getservbyport(port, proto_str)) != NULL ) {
3584 retval = WS_dup_se(serv);
3586 else SetLastError(WSANO_DATA);
3587 LeaveCriticalSection( &csWSgetXXXbyYYY );
3588 HeapFree( GetProcessHeap(), 0, proto_str );
3590 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
3595 /***********************************************************************
3596 * gethostname (WS2_32.57)
3598 int WINAPI WS_gethostname(char *name, int namelen)
3600 TRACE("name %p, len %d\n", name, namelen);
3602 if (gethostname(name, namelen) == 0)
3604 TRACE("<- '%s'\n", name);
3607 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
3608 TRACE("<- ERROR !\n");
3609 return SOCKET_ERROR;
3613 /* ------------------------------------- Windows sockets extensions -- *
3615 * ------------------------------------------------------------------- */
3617 /***********************************************************************
3618 * WSAEnumNetworkEvents (WS2_32.36)
3620 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
3624 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
3626 SERVER_START_REQ( get_socket_event )
3628 req->handle = SOCKET2HANDLE(s);
3629 req->service = TRUE;
3630 req->c_event = hEvent;
3631 wine_server_set_reply( req, lpEvent->iErrorCode, sizeof(lpEvent->iErrorCode) );
3632 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
3636 SetLastError(WSAEINVAL);
3637 return SOCKET_ERROR;
3640 /***********************************************************************
3641 * WSAEventSelect (WS2_32.39)
3643 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
3647 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
3649 SERVER_START_REQ( set_socket_event )
3651 req->handle = SOCKET2HANDLE(s);
3653 req->event = hEvent;
3656 ret = wine_server_call( req );
3660 SetLastError(WSAEINVAL);
3661 return SOCKET_ERROR;
3664 /**********************************************************************
3665 * WSAGetOverlappedResult (WS2_32.40)
3667 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
3668 LPDWORD lpcbTransfer, BOOL fWait,
3673 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
3674 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
3676 if ( lpOverlapped == NULL )
3678 ERR( "Invalid pointer\n" );
3679 WSASetLastError(WSA_INVALID_PARAMETER);
3683 status = lpOverlapped->Internal;
3684 if (status == STATUS_PENDING)
3688 SetLastError( WSA_IO_INCOMPLETE );
3692 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
3693 INFINITE ) == WAIT_FAILED)
3695 status = lpOverlapped->Internal;
3699 *lpcbTransfer = lpOverlapped->InternalHigh;
3702 *lpdwFlags = lpOverlapped->u.s.Offset;
3704 if (status) SetLastError( RtlNtStatusToDosError(status) );
3709 /***********************************************************************
3710 * WSAAsyncSelect (WS2_32.101)
3712 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
3716 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
3718 SERVER_START_REQ( set_socket_event )
3720 req->handle = SOCKET2HANDLE(s);
3725 ret = wine_server_call( req );
3729 SetLastError(WSAEINVAL);
3730 return SOCKET_ERROR;
3733 /***********************************************************************
3734 * WSACreateEvent (WS2_32.31)
3737 WSAEVENT WINAPI WSACreateEvent(void)
3739 /* Create a manual-reset event, with initial state: unsignaled */
3742 return CreateEventW(NULL, TRUE, FALSE, NULL);
3745 /***********************************************************************
3746 * WSACloseEvent (WS2_32.29)
3749 BOOL WINAPI WSACloseEvent(WSAEVENT event)
3751 TRACE ("event=%p\n", event);
3753 return CloseHandle(event);
3756 /***********************************************************************
3757 * WSASocketA (WS2_32.78)
3760 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
3761 LPWSAPROTOCOL_INFOA lpProtocolInfo,
3762 GROUP g, DWORD dwFlags)
3765 WSAPROTOCOL_INFOW info;
3767 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
3768 af, type, protocol, lpProtocolInfo, g, dwFlags);
3770 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
3772 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
3773 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
3774 info.szProtocol, WSAPROTOCOL_LEN + 1);
3778 WSASetLastError( WSAEINVAL);
3779 return SOCKET_ERROR;
3782 return WSASocketW(af, type, protocol, &info, g, dwFlags);
3785 /***********************************************************************
3786 * WSASocketW (WS2_32.79)
3789 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
3790 LPWSAPROTOCOL_INFOW lpProtocolInfo,
3791 GROUP g, DWORD dwFlags)
3796 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
3797 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
3800 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
3801 af, type, protocol, lpProtocolInfo, g, dwFlags );
3803 /* hack for WSADuplicateSocket */
3804 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
3805 ret = lpProtocolInfo->dwCatalogEntryId;
3806 TRACE("\tgot duplicate %04lx\n", ret);
3810 /* convert the socket family and type */
3811 af = convert_af_w2u(af);
3812 type = convert_socktype_w2u(type);
3816 if (af == FROM_PROTOCOL_INFO)
3817 af = lpProtocolInfo->iAddressFamily;
3818 if (type == FROM_PROTOCOL_INFO)
3819 type = lpProtocolInfo->iSocketType;
3820 if (protocol == FROM_PROTOCOL_INFO)
3821 protocol = lpProtocolInfo->iProtocol;
3824 if ( af == AF_UNSPEC) /* did they not specify the address family? */
3828 if (type == SOCK_STREAM) { af = AF_INET; break; }
3830 if (type == SOCK_DGRAM) { af = AF_INET; break; }
3831 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
3834 SERVER_START_REQ( create_socket )
3838 req->protocol = protocol;
3839 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
3840 req->attributes = OBJ_INHERIT;
3841 req->flags = dwFlags;
3842 set_error( wine_server_call( req ) );
3843 ret = HANDLE2SOCKET( reply->handle );
3848 TRACE("\tcreated %04lx\n", ret );
3852 if (GetLastError() == WSAEACCES) /* raw socket denied */
3854 if (type == SOCK_RAW)
3855 MESSAGE("WARNING: Trying to create a socket of type SOCK_RAW, this"
3856 " will fail unless you have special permissions.\n");
3858 MESSAGE("WS_SOCKET: Failed to create socket, this requires"
3859 " special permissions.\n");
3860 SetLastError(WSAESOCKTNOSUPPORT);
3863 WARN("\t\tfailed!\n");
3864 return INVALID_SOCKET;
3867 /***********************************************************************
3868 * WSAJoinLeaf (WS2_32.58)
3871 SOCKET WINAPI WSAJoinLeaf(
3873 const struct WS_sockaddr *addr,
3875 LPWSABUF lpCallerData,
3876 LPWSABUF lpCalleeData,
3882 return INVALID_SOCKET;
3885 /***********************************************************************
3886 * __WSAFDIsSet (WS2_32.151)
3888 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
3890 int i = set->fd_count;
3892 TRACE("(%ld,%p(%i))\n", s, set, i);
3895 if (set->fd_array[i] == s) return 1;
3899 /***********************************************************************
3900 * WSAIsBlocking (WINSOCK.114)
3901 * WSAIsBlocking (WS2_32.114)
3903 BOOL WINAPI WSAIsBlocking(void)
3905 /* By default WinSock should set all its sockets to non-blocking mode
3906 * and poll in PeekMessage loop when processing "blocking" ones. This
3907 * function is supposed to tell if the program is in this loop. Our
3908 * blocking calls are truly blocking so we always return FALSE.
3910 * Note: It is allowed to call this function without prior WSAStartup().
3917 /***********************************************************************
3918 * WSACancelBlockingCall (WINSOCK.113)
3919 * WSACancelBlockingCall (WS2_32.113)
3921 INT WINAPI WSACancelBlockingCall(void)
3927 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
3929 FIXME("How was this called?\n");
3934 /***********************************************************************
3935 * WSASetBlockingHook (WS2_32.109)
3937 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
3939 FARPROC prev = blocking_hook;
3940 blocking_hook = lpBlockFunc;
3941 TRACE("hook %p\n", lpBlockFunc);
3946 /***********************************************************************
3947 * WSAUnhookBlockingHook (WS2_32.110)
3949 INT WINAPI WSAUnhookBlockingHook(void)
3951 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
3956 /* ----------------------------------- end of API stuff */
3958 /* ----------------------------------- helper functions -
3960 * TODO: Merge WS_dup_..() stuff into one function that
3961 * would operate with a generic structure containing internal
3962 * pointers (via a template of some kind).
3965 static int list_size(char** l, int item_size)
3970 j += (item_size) ? item_size : strlen(l[i]) + 1;
3971 j += (i + 1) * sizeof(char*); }
3975 static int list_dup(char** l_src, char** l_to, int item_size)
3980 for (i = 0; l_src[i]; i++) ;
3981 p = (char *)(l_to + i + 1);
3982 for (i = 0; l_src[i]; i++)
3984 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
3985 memcpy(p, l_src[i], count);
3990 return p - (char *)l_to;
3995 /* duplicate hostent entry
3996 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
3997 * Ditto for protoent and servent.
3999 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
4002 struct WS_hostent *p_to;
4004 int size = (sizeof(*p_he) +
4005 strlen(p_he->h_name) + 1 +
4006 list_size(p_he->h_aliases, 0) +
4007 list_size(p_he->h_addr_list, p_he->h_length));
4009 if (!(p_to = check_buffer_he(size))) return NULL;
4010 p_to->h_addrtype = p_he->h_addrtype;
4011 p_to->h_length = p_he->h_length;
4013 p = (char *)(p_to + 1);
4015 strcpy(p, p_he->h_name);
4018 p_to->h_aliases = (char **)p;
4019 p += list_dup(p_he->h_aliases, p_to->h_aliases, 0);
4021 p_to->h_addr_list = (char **)p;
4022 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
4026 /* ----- protoent */
4028 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
4031 struct WS_protoent *p_to;
4033 int size = (sizeof(*p_pe) +
4034 strlen(p_pe->p_name) + 1 +
4035 list_size(p_pe->p_aliases, 0));
4037 if (!(p_to = check_buffer_pe(size))) return NULL;
4038 p_to->p_proto = p_pe->p_proto;
4040 p = (char *)(p_to + 1);
4042 strcpy(p, p_pe->p_name);
4045 p_to->p_aliases = (char **)p;
4046 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
4052 static struct WS_servent *WS_dup_se(const struct servent* p_se)
4055 struct WS_servent *p_to;
4057 int size = (sizeof(*p_se) +
4058 strlen(p_se->s_proto) + 1 +
4059 strlen(p_se->s_name) + 1 +
4060 list_size(p_se->s_aliases, 0));
4062 if (!(p_to = check_buffer_se(size))) return NULL;
4063 p_to->s_port = p_se->s_port;
4065 p = (char *)(p_to + 1);
4067 strcpy(p, p_se->s_name);
4071 strcpy(p, p_se->s_proto);
4074 p_to->s_aliases = (char **)p;
4075 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
4079 /* ----------------------------------- error handling */
4083 int loc_errno = errno;
4084 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
4088 case EINTR: return WSAEINTR;
4089 case EBADF: return WSAEBADF;
4091 case EACCES: return WSAEACCES;
4092 case EFAULT: return WSAEFAULT;
4093 case EINVAL: return WSAEINVAL;
4094 case EMFILE: return WSAEMFILE;
4095 case EWOULDBLOCK: return WSAEWOULDBLOCK;
4096 case EINPROGRESS: return WSAEINPROGRESS;
4097 case EALREADY: return WSAEALREADY;
4098 case ENOTSOCK: return WSAENOTSOCK;
4099 case EDESTADDRREQ: return WSAEDESTADDRREQ;
4100 case EMSGSIZE: return WSAEMSGSIZE;
4101 case EPROTOTYPE: return WSAEPROTOTYPE;
4102 case ENOPROTOOPT: return WSAENOPROTOOPT;
4103 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
4104 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
4105 case EOPNOTSUPP: return WSAEOPNOTSUPP;
4106 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
4107 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
4108 case EADDRINUSE: return WSAEADDRINUSE;
4109 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
4110 case ENETDOWN: return WSAENETDOWN;
4111 case ENETUNREACH: return WSAENETUNREACH;
4112 case ENETRESET: return WSAENETRESET;
4113 case ECONNABORTED: return WSAECONNABORTED;
4115 case ECONNRESET: return WSAECONNRESET;
4116 case ENOBUFS: return WSAENOBUFS;
4117 case EISCONN: return WSAEISCONN;
4118 case ENOTCONN: return WSAENOTCONN;
4119 case ESHUTDOWN: return WSAESHUTDOWN;
4120 case ETOOMANYREFS: return WSAETOOMANYREFS;
4121 case ETIMEDOUT: return WSAETIMEDOUT;
4122 case ECONNREFUSED: return WSAECONNREFUSED;
4123 case ELOOP: return WSAELOOP;
4124 case ENAMETOOLONG: return WSAENAMETOOLONG;
4125 case EHOSTDOWN: return WSAEHOSTDOWN;
4126 case EHOSTUNREACH: return WSAEHOSTUNREACH;
4127 case ENOTEMPTY: return WSAENOTEMPTY;
4129 case EPROCLIM: return WSAEPROCLIM;
4132 case EUSERS: return WSAEUSERS;
4135 case EDQUOT: return WSAEDQUOT;
4138 case ESTALE: return WSAESTALE;
4141 case EREMOTE: return WSAEREMOTE;
4144 /* just in case we ever get here and there are no problems */
4147 WARN("Unknown errno %d!\n", loc_errno);
4148 return WSAEOPNOTSUPP;
4152 UINT wsaHerrno(int loc_errno)
4155 WARN("h_errno %d.\n", loc_errno);
4159 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
4160 case TRY_AGAIN: return WSATRY_AGAIN;
4161 case NO_RECOVERY: return WSANO_RECOVERY;
4162 case NO_DATA: return WSANO_DATA;
4163 case ENOBUFS: return WSAENOBUFS;
4167 WARN("Unknown h_errno %d!\n", loc_errno);
4168 return WSAEOPNOTSUPP;
4173 /***********************************************************************
4174 * WSARecv (WS2_32.67)
4176 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4177 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
4178 LPWSAOVERLAPPED lpOverlapped,
4179 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
4181 return WSARecvFrom(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
4182 NULL, NULL, lpOverlapped, lpCompletionRoutine);
4185 /***********************************************************************
4186 * WSARecvFrom (WS2_32.69)
4188 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4189 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
4190 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
4191 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4194 unsigned int i, options;
4196 DWORD timeout_start = GetTickCount();
4197 struct iovec iovec[WS_MSG_MAXIOVLEN];
4198 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4200 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
4201 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
4202 (lpFromlen ? *lpFromlen : -1),
4203 lpOverlapped, lpCompletionRoutine);
4205 if (dwBufferCount > WS_MSG_MAXIOVLEN)
4207 WSASetLastError( WSAEINVAL );
4208 return SOCKET_ERROR;
4211 fd = get_sock_fd( s, FILE_READ_DATA, &options );
4212 TRACE( "fd=%d, options=%x\n", fd, options );
4214 if (fd == -1) return SOCKET_ERROR;
4216 for (i = 0; i < dwBufferCount; i++)
4218 iovec[i].iov_base = lpBuffers[i].buf;
4219 iovec[i].iov_len = lpBuffers[i].len;
4224 n = WS2_recv( fd, iovec, dwBufferCount, lpFrom, lpFromlen, lpFlags );
4227 if (errno == EINTR) continue;
4228 if (errno != EAGAIN)
4231 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
4236 *lpNumberOfBytesRecvd = n;
4238 if ((lpOverlapped || lpCompletionRoutine) &&
4239 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4241 IO_STATUS_BLOCK *iosb;
4242 struct ws2_async *wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
4249 release_sock_fd( s, fd );
4251 wsa->hSocket = SOCKET2HANDLE(s);
4252 wsa->flags = *lpFlags;
4254 wsa->addrlen.ptr = lpFromlen;
4255 wsa->user_overlapped = lpOverlapped;
4256 wsa->completion_func = lpCompletionRoutine;
4257 wsa->n_iovecs = dwBufferCount;
4258 memcpy( wsa->iovec, iovec, dwBufferCount * sizeof(*iovec) );
4260 iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4264 iosb->u.Status = STATUS_PENDING;
4265 iosb->Information = 0;
4267 SERVER_START_REQ( register_async )
4269 req->handle = wsa->hSocket;
4270 req->type = ASYNC_TYPE_READ;
4271 req->async.callback = WS2_async_recv;
4272 req->async.iosb = iosb;
4273 req->async.arg = wsa;
4274 req->async.apc = ws2_async_apc;
4275 req->async.event = lpCompletionRoutine ? 0 : lpOverlapped->hEvent;
4276 req->async.cvalue = cvalue;
4277 err = wine_server_call( req );
4281 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4282 WSASetLastError( NtStatusToWSAError( err ));
4283 return SOCKET_ERROR;
4286 iosb->u.Status = STATUS_SUCCESS;
4287 iosb->Information = n;
4288 if (!wsa->completion_func)
4290 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4291 SetEvent( lpOverlapped->hEvent );
4292 HeapFree( GetProcessHeap(), 0, wsa );
4294 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4295 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4296 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4302 if ( _is_blocking(s) )
4305 int timeout = GET_RCVTIMEO(fd);
4308 timeout -= GetTickCount() - timeout_start;
4309 if (timeout < 0) timeout = 0;
4313 pfd.events = POLLIN;
4314 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
4316 if (!timeout || !poll( &pfd, 1, timeout ))
4319 /* a timeout is not fatal */
4320 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4326 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4327 err = WSAEWOULDBLOCK;
4332 TRACE(" -> %i bytes\n", n);
4333 release_sock_fd( s, fd );
4334 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4339 release_sock_fd( s, fd );
4340 WARN(" -> ERROR %d\n", err);
4341 WSASetLastError( err );
4342 return SOCKET_ERROR;
4345 /***********************************************************************
4346 * WSCInstallProvider (WS2_32.88)
4348 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
4349 LPCWSTR lpszProviderDllPath,
4350 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
4351 DWORD dwNumberOfEntries,
4354 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
4355 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
4356 dwNumberOfEntries, lpErrno);
4362 /***********************************************************************
4363 * WSCDeinstallProvider (WS2_32.83)
4365 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
4367 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
4373 /***********************************************************************
4374 * WSAAccept (WS2_32.26)
4376 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
4377 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
4380 int ret = 0, size = 0;
4381 WSABUF CallerId, CallerData, CalleeId, CalleeData;
4382 /* QOS SQOS, GQOS; */
4385 SOCKADDR src_addr, dst_addr;
4387 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %d\n",
4388 s, addr, addrlen, lpfnCondition, dwCallbackData);
4391 size = sizeof(src_addr);
4392 cs = WS_accept(s, &src_addr, &size);
4394 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
4396 CallerId.buf = (char *)&src_addr;
4397 CallerId.len = sizeof(src_addr);
4399 CallerData.buf = NULL;
4400 CallerData.len = (ULONG)NULL;
4402 WS_getsockname(cs, &dst_addr, &size);
4404 CalleeId.buf = (char *)&dst_addr;
4405 CalleeId.len = sizeof(dst_addr);
4408 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
4409 &CalleeId, &CalleeData, &g, dwCallbackData);
4414 if (addr && addrlen)
4415 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
4418 SERVER_START_REQ( set_socket_deferred )
4420 req->handle = SOCKET2HANDLE(s);
4421 req->deferred = SOCKET2HANDLE(cs);
4422 if ( !wine_server_call_err ( req ) )
4424 SetLastError( WSATRY_AGAIN );
4425 WS_closesocket( cs );
4429 return SOCKET_ERROR;
4432 SetLastError(WSAECONNREFUSED);
4433 return SOCKET_ERROR;
4435 FIXME("Unknown return type from Condition function\n");
4436 SetLastError(WSAENOTSOCK);
4437 return SOCKET_ERROR;
4441 /***********************************************************************
4442 * WSADuplicateSocketA (WS2_32.32)
4444 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
4448 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4449 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4450 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
4451 /* I don't know what the real Windoze does next, this is a hack */
4452 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
4453 * the target use the global duplicate, or we could copy a reference to us to the structure
4454 * and let the target duplicate it from us, but let's do it as simple as possible */
4455 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4456 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4457 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4458 0, FALSE, DUPLICATE_SAME_ACCESS);
4459 CloseHandle(hProcess);
4460 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4464 /***********************************************************************
4465 * WSADuplicateSocketW (WS2_32.33)
4467 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
4471 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4473 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4474 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4475 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4476 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4477 0, FALSE, DUPLICATE_SAME_ACCESS);
4478 CloseHandle(hProcess);
4479 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4483 /***********************************************************************
4484 * WSAInstallServiceClassA (WS2_32.48)
4486 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
4488 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
4489 WSASetLastError(WSAEACCES);
4490 return SOCKET_ERROR;
4493 /***********************************************************************
4494 * WSAInstallServiceClassW (WS2_32.49)
4496 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
4498 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
4499 WSASetLastError(WSAEACCES);
4500 return SOCKET_ERROR;
4503 /***********************************************************************
4504 * WSARemoveServiceClass (WS2_32.70)
4506 int WINAPI WSARemoveServiceClass(LPGUID info)
4508 FIXME("Request to remove service %p\n",info);
4509 WSASetLastError(WSATYPE_NOT_FOUND);
4510 return SOCKET_ERROR;
4513 /***********************************************************************
4514 * WSAStringToAddressA (WS2_32.80)
4516 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
4518 LPWSAPROTOCOL_INFOA lpProtocolInfo,
4519 LPSOCKADDR lpAddress,
4520 LPINT lpAddressLength)
4523 LPSTR workBuffer=NULL,ptrPort;
4525 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
4526 lpProtocolInfo, lpAddress, lpAddressLength );
4528 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
4532 WSASetLastError(WSAEINVAL);
4533 return SOCKET_ERROR;
4537 FIXME("ProtocolInfo not implemented.\n");
4539 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
4540 strlen(AddressString) + 1);
4543 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4544 return SOCKET_ERROR;
4547 strcpy(workBuffer, AddressString);
4549 switch(AddressFamily)
4553 struct in_addr inetaddr;
4555 /* If lpAddressLength is too small, tell caller the size we need */
4556 if (*lpAddressLength < sizeof(SOCKADDR_IN))
4558 *lpAddressLength = sizeof(SOCKADDR_IN);
4562 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
4564 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
4566 ptrPort = strchr(workBuffer, ':');
4569 ((LPSOCKADDR_IN)lpAddress)->sin_port = (WS_u_short)atoi(ptrPort+1);
4574 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
4577 if(inet_aton(workBuffer, &inetaddr) > 0)
4579 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
4590 struct in6_addr inetaddr;
4591 /* If lpAddressLength is too small, tell caller the size we need */
4592 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
4594 *lpAddressLength = sizeof(SOCKADDR_IN6);
4598 #ifdef HAVE_INET_PTON
4599 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
4601 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
4603 /* This one is a bit tricky. An IPv6 address contains colons, so the
4604 * check from IPv4 doesn't work like that. However, IPv6 addresses that
4605 * contain a port are written with braces like [fd12:3456:7890::1]:12345
4606 * so what we will do is to look for ']', check if the next char is a
4607 * colon, and if it is, parse the port as in IPv4. */
4609 ptrPort = strchr(workBuffer, ']');
4610 if(ptrPort && *(++ptrPort) == ':')
4612 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = (WS_u_short)atoi(ptrPort+1);
4617 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
4620 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
4622 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
4623 sizeof(struct in6_addr));
4627 #endif /* HAVE_INET_PTON */
4633 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
4634 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
4638 HeapFree(GetProcessHeap(), 0, workBuffer);
4641 WSASetLastError(res);
4642 return SOCKET_ERROR;
4645 /***********************************************************************
4646 * WSAStringToAddressW (WS2_32.81)
4648 * Does anybody know if this functions allows to use hebrew/arabic/chinese... digits?
4649 * If this should be the case, it would be required to map these digits
4650 * to Unicode digits (0-9) using FoldString first.
4652 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
4654 LPWSAPROTOCOL_INFOW lpProtocolInfo,
4655 LPSOCKADDR lpAddress,
4656 LPINT lpAddressLength)
4659 LPSTR workBuffer=NULL;
4660 WSAPROTOCOL_INFOA infoA;
4661 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
4663 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
4664 lpAddress, lpAddressLength );
4666 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
4668 /* if ProtocolInfo is available - convert to ANSI variant */
4671 lpProtoInfoA = &infoA;
4672 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
4674 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
4675 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
4677 WSASetLastError( WSAEINVAL);
4678 return SOCKET_ERROR;
4684 /* Translate AddressString to ANSI code page - assumes that only
4685 standard digits 0-9 are used with this API call */
4686 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
4687 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
4691 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
4692 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
4693 lpAddress,lpAddressLength);
4694 HeapFree( GetProcessHeap(), 0, workBuffer );
4698 res = WSA_NOT_ENOUGH_MEMORY;
4703 WSASetLastError(res);
4704 return SOCKET_ERROR;
4707 /***********************************************************************
4708 * WSAAddressToStringA (WS2_32.27)
4710 * See WSAAddressToStringW
4712 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
4713 LPWSAPROTOCOL_INFOA info, LPSTR string,
4717 CHAR buffer[22]; /* 12 digits + 3 dots + ':' + 5 digits + '\0' */
4720 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
4722 if (!sockaddr || len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
4723 if (!string || !lenstr) return SOCKET_ERROR;
4725 /* sin_family is guaranteed to be the first u_short */
4726 if (((SOCKADDR_IN *)sockaddr)->sin_family != AF_INET) return SOCKET_ERROR;
4728 sprintf( buffer, "%u.%u.%u.%u:%u",
4729 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
4730 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
4731 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
4732 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
4733 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
4735 p = strchr( buffer, ':' );
4736 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
4738 size = strlen( buffer );
4743 WSASetLastError(WSAEFAULT);
4744 return SOCKET_ERROR;
4747 strcpy( string, buffer );
4751 /***********************************************************************
4752 * WSAAddressToStringW (WS2_32.28)
4754 * Convert a sockaddr address into a readable address string.
4757 * sockaddr [I] Pointer to a sockaddr structure.
4758 * len [I] Size of the sockaddr structure.
4759 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
4760 * string [I/O] Pointer to a buffer to receive the address string.
4761 * lenstr [I/O] Size of the receive buffer in WCHARs.
4765 * Failure: SOCKET_ERROR
4768 * The 'info' parameter is ignored.
4771 * Only supports AF_INET addresses.
4773 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
4774 LPWSAPROTOCOL_INFOW info, LPWSTR string,
4778 WCHAR buffer[22]; /* 12 digits + 3 dots + ':' + 5 digits + '\0' */
4779 static const WCHAR format[] = { '%','u','.','%','u','.','%','u','.','%','u',':','%','u',0 };
4782 TRACE( "(%p, %x, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
4784 if (!sockaddr || len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
4785 if (!string || !lenstr) return SOCKET_ERROR;
4787 /* sin_family is guaranteed to be the first u_short */
4788 if (((SOCKADDR_IN *)sockaddr)->sin_family != AF_INET) return SOCKET_ERROR;
4790 sprintfW( buffer, format,
4791 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
4792 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
4793 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
4794 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
4795 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
4797 p = strchrW( buffer, ':' );
4798 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
4800 size = lstrlenW( buffer );
4805 return SOCKET_ERROR;
4808 lstrcpyW( string, buffer );
4812 /***********************************************************************
4813 * WSAEnumNameSpaceProvidersA (WS2_32.34)
4815 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
4817 FIXME( "(%p %p) Stub!\n", len, buffer );
4821 /***********************************************************************
4822 * WSAEnumNameSpaceProvidersW (WS2_32.35)
4824 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
4826 FIXME( "(%p %p) Stub!\n", len, buffer );
4830 /***********************************************************************
4831 * WSAGetQOSByName (WS2_32.41)
4833 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
4835 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
4839 /***********************************************************************
4840 * WSAGetServiceClassInfoA (WS2_32.42)
4842 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
4843 LPWSASERVICECLASSINFOA info )
4845 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
4847 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4848 return SOCKET_ERROR;
4851 /***********************************************************************
4852 * WSAGetServiceClassInfoW (WS2_32.43)
4854 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
4855 LPWSASERVICECLASSINFOW info )
4857 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
4859 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4860 return SOCKET_ERROR;
4863 /***********************************************************************
4864 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
4866 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
4868 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
4869 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4870 return SOCKET_ERROR;
4873 /***********************************************************************
4874 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
4876 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
4878 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
4879 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4880 return SOCKET_ERROR;
4883 /***********************************************************************
4884 * WSALookupServiceBeginA (WS2_32.59)
4886 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
4887 DWORD dwControlFlags,
4890 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
4892 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4893 return SOCKET_ERROR;
4896 /***********************************************************************
4897 * WSALookupServiceBeginW (WS2_32.60)
4899 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
4900 DWORD dwControlFlags,
4903 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
4905 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4906 return SOCKET_ERROR;
4909 /***********************************************************************
4910 * WSALookupServiceBeginW (WS2_32.61)
4912 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
4914 FIXME("(%p) Stub!\n", lookup );
4918 /***********************************************************************
4919 * WSALookupServiceNextA (WS2_32.62)
4921 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
4923 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
4927 /***********************************************************************
4928 * WSALookupServiceNextW (WS2_32.63)
4930 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
4932 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
4936 /***********************************************************************
4937 * WSANtohl (WS2_32.64)
4939 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
4941 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
4943 if (!lphostlong) return WSAEFAULT;
4945 *lphostlong = ntohl( netlong );
4949 /***********************************************************************
4950 * WSANtohs (WS2_32.65)
4952 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
4954 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
4956 if (!lphostshort) return WSAEFAULT;
4958 *lphostshort = ntohs( netshort );
4962 /***********************************************************************
4963 * WSAProviderConfigChange (WS2_32.66)
4965 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
4966 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4968 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
4969 return SOCKET_ERROR;
4972 /***********************************************************************
4973 * WSARecvDisconnect (WS2_32.68)
4975 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
4977 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
4979 return WS_shutdown( s, 0 );
4982 /***********************************************************************
4983 * WSASetServiceA (WS2_32.76)
4985 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
4987 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
4991 /***********************************************************************
4992 * WSASetServiceW (WS2_32.77)
4994 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
4996 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5000 /***********************************************************************
5001 * WSCEnableNSProvider (WS2_32.84)
5003 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
5005 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
5009 /***********************************************************************
5010 * WSCGetProviderPath (WS2_32.86)
5012 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
5014 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
5016 if (!errcode || !provider || !len) return WSAEFAULT;
5018 *errcode = WSAEINVAL;
5019 return SOCKET_ERROR;
5022 /***********************************************************************
5023 * WSCInstallNameSpace (WS2_32.87)
5025 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
5026 DWORD version, LPGUID provider )
5028 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
5029 namespace, version, debugstr_guid(provider) );
5033 /***********************************************************************
5034 * WSCUnInstallNameSpace (WS2_32.89)
5036 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
5038 FIXME("(%p) Stub!\n", lpProviderId);
5042 /***********************************************************************
5043 * WSCWriteProviderOrder (WS2_32.91)
5045 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
5047 FIXME("(%p 0x%08x) Stub!\n", entry, number);