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 ),
302 static const int ws_socktype_map[][2] =
304 MAP_OPTION( SOCK_DGRAM ),
305 MAP_OPTION( SOCK_STREAM ),
306 MAP_OPTION( SOCK_RAW ),
309 static const int ws_proto_map[][2] =
311 MAP_OPTION( IPPROTO_IP ),
312 MAP_OPTION( IPPROTO_TCP ),
313 MAP_OPTION( IPPROTO_UDP ),
314 MAP_OPTION( IPPROTO_ICMP ),
315 MAP_OPTION( IPPROTO_IGMP ),
316 MAP_OPTION( IPPROTO_RAW ),
319 static const int ws_aiflag_map[][2] =
321 MAP_OPTION( AI_PASSIVE ),
322 MAP_OPTION( AI_CANONNAME ),
323 MAP_OPTION( AI_NUMERICHOST ),
324 /* Linux/UNIX knows a lot more. But Windows only
325 * has 3 as far as I could see. -Marcus
329 static const int ws_niflag_map[][2] =
331 MAP_OPTION( NI_NOFQDN ),
332 MAP_OPTION( NI_NUMERICHOST ),
333 MAP_OPTION( NI_NAMEREQD ),
334 MAP_OPTION( NI_NUMERICSERV ),
335 MAP_OPTION( NI_DGRAM ),
338 static const int ws_eai_map[][2] =
340 MAP_OPTION( EAI_AGAIN ),
341 MAP_OPTION( EAI_BADFLAGS ),
342 MAP_OPTION( EAI_FAIL ),
343 MAP_OPTION( EAI_FAMILY ),
344 MAP_OPTION( EAI_MEMORY ),
345 /* Note: EAI_NODATA is deprecated, but still
346 * used by Windows and Linux... We map the newer
347 * EAI_NONAME to EAI_NODATA for now until Windows
351 MAP_OPTION( EAI_NODATA ),
354 { WS_EAI_NODATA, EAI_NONAME },
357 MAP_OPTION( EAI_SERVICE ),
358 MAP_OPTION( EAI_SOCKTYPE ),
362 static const char magic_loopback_addr[] = {127, 12, 34, 56};
364 static inline DWORD NtStatusToWSAError( const DWORD status )
366 /* We only need to cover the status codes set by server async request handling */
370 case STATUS_SUCCESS: wserr = 0; break;
371 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
372 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
373 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
374 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
375 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
376 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
377 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
378 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
380 if ( status >= WSABASEERR && status <= WSABASEERR+1004 )
381 /* It is not an NT status code but a winsock error */
385 wserr = RtlNtStatusToDosError( status );
386 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
392 /* set last error code from NT status without mapping WSA errors */
393 static inline unsigned int set_error( unsigned int err )
397 err = NtStatusToWSAError( err );
403 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
406 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
411 static inline void release_sock_fd( SOCKET s, int fd )
413 wine_server_release_fd( SOCKET2HANDLE(s), fd );
416 static void _enable_event( HANDLE s, unsigned int event,
417 unsigned int sstate, unsigned int cstate )
419 SERVER_START_REQ( enable_socket_event )
423 req->sstate = sstate;
424 req->cstate = cstate;
425 wine_server_call( req );
430 static int _is_blocking(SOCKET s)
433 SERVER_START_REQ( get_socket_event )
435 req->handle = SOCKET2HANDLE(s);
436 req->service = FALSE;
438 wine_server_call( req );
439 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
445 static unsigned int _get_sock_mask(SOCKET s)
448 SERVER_START_REQ( get_socket_event )
450 req->handle = SOCKET2HANDLE(s);
451 req->service = FALSE;
453 wine_server_call( req );
460 static void _sync_sock_state(SOCKET s)
462 /* do a dummy wineserver request in order to let
463 the wineserver run through its select loop once */
464 (void)_is_blocking(s);
467 static int _get_sock_error(SOCKET s, unsigned int bit)
469 int events[FD_MAX_EVENTS];
471 SERVER_START_REQ( get_socket_event )
473 req->handle = SOCKET2HANDLE(s);
474 req->service = FALSE;
476 wine_server_set_reply( req, events, sizeof(events) );
477 wine_server_call( req );
483 static struct per_thread_data *get_per_thread_data(void)
485 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
486 /* lazy initialization */
489 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
490 NtCurrentTeb()->WinSockData = ptb;
495 static void free_per_thread_data(void)
497 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
501 /* delete scratch buffers */
502 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
503 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
504 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
505 ptb->he_buffer = NULL;
506 ptb->se_buffer = NULL;
507 ptb->pe_buffer = NULL;
509 HeapFree( GetProcessHeap(), 0, ptb );
510 NtCurrentTeb()->WinSockData = NULL;
513 /***********************************************************************
514 * DllMain (WS2_32.init)
516 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
518 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
520 case DLL_PROCESS_ATTACH:
522 case DLL_PROCESS_DETACH:
523 free_per_thread_data();
526 case DLL_THREAD_DETACH:
527 free_per_thread_data();
533 /***********************************************************************
536 * Converts socket flags from Windows format.
537 * Return 1 if converted, 0 if not (error).
539 static int convert_sockopt(INT *level, INT *optname)
546 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
547 if( ws_sock_map[i][0] == *optname )
549 *optname = ws_sock_map[i][1];
553 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
556 *level = IPPROTO_TCP;
557 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
558 if ( ws_tcp_map[i][0] == *optname )
560 *optname = ws_tcp_map[i][1];
564 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
568 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
569 if (ws_ip_map[i][0] == *optname )
571 *optname = ws_ip_map[i][1];
575 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
577 default: FIXME("Unimplemented or unknown socket level\n");
582 /* ----------------------------------- Per-thread info (or per-process?) */
584 static char *strdup_lower(const char *str)
587 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
591 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
594 else SetLastError(WSAENOBUFS);
598 static inline int sock_error_p(int s)
600 unsigned int optval, optlen;
602 optlen = sizeof(optval);
603 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
604 if (optval) WARN("\t[%i] error: %d\n", s, optval);
608 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
609 * from an fd and return the value converted to milli seconds
610 * or -1 if there is an infinite time out */
611 static inline int get_rcvsnd_timeo( int fd, int optname)
614 unsigned int len = sizeof(tv);
615 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
617 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
618 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
623 /* macro wrappers for portability */
625 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
627 #define GET_RCVTIMEO(fd) (-1)
631 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
633 #define GET_SNDTIMEO(fd) (-1)
636 /* utility: given an fd, will block until one of the events occurs */
637 static inline int do_block( int fd, int events, int timeout )
645 while ((ret = poll(&pfd, 1, timeout)) < 0)
656 convert_af_w2u(int windowsaf) {
659 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
660 if (ws_af_map[i][0] == windowsaf)
661 return ws_af_map[i][1];
662 FIXME("unhandled Windows address family %d\n", windowsaf);
667 convert_af_u2w(int unixaf) {
670 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
671 if (ws_af_map[i][1] == unixaf)
672 return ws_af_map[i][0];
673 FIXME("unhandled UNIX address family %d\n", unixaf);
678 convert_proto_w2u(int windowsproto) {
681 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
682 if (ws_proto_map[i][0] == windowsproto)
683 return ws_proto_map[i][1];
684 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
689 convert_proto_u2w(int unixproto) {
692 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
693 if (ws_proto_map[i][1] == unixproto)
694 return ws_proto_map[i][0];
695 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
700 convert_socktype_w2u(int windowssocktype) {
703 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
704 if (ws_socktype_map[i][0] == windowssocktype)
705 return ws_socktype_map[i][1];
706 FIXME("unhandled Windows socket type %d\n", windowssocktype);
711 convert_socktype_u2w(int unixsocktype) {
714 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
715 if (ws_socktype_map[i][1] == unixsocktype)
716 return ws_socktype_map[i][0];
717 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
721 /* ----------------------------------- API -----
723 * Init / cleanup / error checking.
726 /***********************************************************************
727 * WSAStartup (WS2_32.115)
729 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
731 TRACE("verReq=%x\n", wVersionRequested);
733 if (LOBYTE(wVersionRequested) < 1)
734 return WSAVERNOTSUPPORTED;
736 if (!lpWSAData) return WSAEINVAL;
740 /* that's the whole of the negotiation for now */
741 lpWSAData->wVersion = wVersionRequested;
742 /* return winsock information */
743 lpWSAData->wHighVersion = 0x0202;
744 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
745 strcpy(lpWSAData->szSystemStatus, "Running" );
746 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
747 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
748 /* don't do anything with lpWSAData->lpVendorInfo */
749 /* (some apps don't allocate the space for this field) */
751 TRACE("succeeded\n");
756 /***********************************************************************
757 * WSACleanup (WS2_32.116)
759 INT WINAPI WSACleanup(void)
765 SetLastError(WSANOTINITIALISED);
770 /***********************************************************************
771 * WSAGetLastError (WINSOCK.111)
772 * WSAGetLastError (WS2_32.111)
774 INT WINAPI WSAGetLastError(void)
776 return GetLastError();
779 /***********************************************************************
780 * WSASetLastError (WS2_32.112)
782 void WINAPI WSASetLastError(INT iError) {
783 SetLastError(iError);
786 static struct WS_hostent *check_buffer_he(int size)
788 struct per_thread_data * ptb = get_per_thread_data();
791 if (ptb->he_len >= size ) return ptb->he_buffer;
792 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
794 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
795 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
796 return ptb->he_buffer;
799 static struct WS_servent *check_buffer_se(int size)
801 struct per_thread_data * ptb = get_per_thread_data();
804 if (ptb->se_len >= size ) return ptb->se_buffer;
805 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
807 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
808 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
809 return ptb->se_buffer;
812 static struct WS_protoent *check_buffer_pe(int size)
814 struct per_thread_data * ptb = get_per_thread_data();
817 if (ptb->pe_len >= size ) return ptb->pe_buffer;
818 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
820 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
821 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
822 return ptb->pe_buffer;
825 /* ----------------------------------- i/o APIs */
828 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf)== WS_AF_IPX || (pf) == WS_AF_INET6)
830 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf) == WS_AF_INET6)
834 /**********************************************************************/
836 /* Returns the length of the converted address if successful, 0 if it was too small to
839 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
840 union generic_unix_sockaddr *uaddr)
842 unsigned int uaddrlen = 0;
844 switch (wsaddr->sa_family)
849 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
850 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
852 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
855 uaddrlen = sizeof(struct sockaddr_ipx);
856 memset( uaddr, 0, uaddrlen );
857 uipx->sipx_family=AF_IPX;
858 uipx->sipx_port=wsipx->sa_socket;
859 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
862 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
863 #ifdef IPX_FRAME_NONE
864 uipx->sipx_type=IPX_FRAME_NONE;
870 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
871 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
873 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
874 * scope_id, one without.
876 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
877 uaddrlen = sizeof(struct sockaddr_in6);
878 memset( uaddr, 0, uaddrlen );
879 uin6->sin6_family = AF_INET6;
880 uin6->sin6_port = win6->sin6_port;
881 uin6->sin6_flowinfo = win6->sin6_flowinfo;
882 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
883 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
885 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
888 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
892 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
893 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
895 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
897 uaddrlen = sizeof(struct sockaddr_in);
898 memset( uaddr, 0, uaddrlen );
899 uin->sin_family = AF_INET;
900 uin->sin_port = win->sin_port;
901 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
905 /* Try to determine the needed space by the passed windows sockaddr space */
907 default: /* likely a ipv4 address */
908 case sizeof(struct WS_sockaddr_in):
909 uaddrlen = sizeof(struct sockaddr_in);
912 case sizeof(struct WS_sockaddr_ipx):
913 uaddrlen = sizeof(struct sockaddr_ipx);
916 case sizeof(struct WS_sockaddr_in6):
917 case sizeof(struct WS_sockaddr_in6_old):
918 uaddrlen = sizeof(struct sockaddr_in6);
921 memset( uaddr, 0, uaddrlen );
925 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
931 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
933 switch (uaddr->sa_family)
937 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
942 static const struct sockaddr_in6 emptyAddr;
943 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
944 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
948 static const struct sockaddr_in emptyAddr;
949 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
950 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
955 FIXME("unknown address family %d\n", uaddr->sa_family);
960 /* Returns 0 if successful, -1 if the buffer is too small */
961 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
965 switch(uaddr->sa_family)
970 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
971 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
974 switch (*wsaddrlen) /* how much can we copy? */
978 *wsaddrlen = sizeof(*wsipx);
979 wsipx->sa_socket=uipx->sipx_port;
983 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
991 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
997 wsipx->sa_family=WS_AF_IPX;
1008 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1009 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1011 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1013 win6old->sin6_family = WS_AF_INET6;
1014 win6old->sin6_port = uin6->sin6_port;
1015 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1016 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1017 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1018 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1019 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1020 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1021 win6->sin6_scope_id = uin6->sin6_scope_id;
1022 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1028 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1029 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1031 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1033 win->sin_family = WS_AF_INET;
1034 win->sin_port = uin->sin_port;
1035 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1036 memset(&win->sin_zero, 0, 8); /* Make sure the null padding is null */
1037 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1041 memset(wsaddr,0,*wsaddrlen);
1045 FIXME("Unknown address family %d\n", uaddr->sa_family);
1051 /**************************************************************************
1052 * Functions for handling overlapped I/O
1053 **************************************************************************/
1055 /* user APC called upon async completion */
1056 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1058 ws2_async *wsa = arg;
1060 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1061 iosb->Information, wsa->user_overlapped,
1063 HeapFree( GetProcessHeap(), 0, wsa );
1066 /***********************************************************************
1067 * WS2_recv (INTERNAL)
1069 * Workhorse for both synchronous and asynchronous recv() operations.
1071 static int WS2_recv( int fd, struct iovec* iov, int count,
1072 struct WS_sockaddr *lpFrom, LPINT lpFromlen,
1076 union generic_unix_sockaddr unix_sockaddr;
1079 hdr.msg_name = NULL;
1083 hdr.msg_namelen = sizeof(unix_sockaddr);
1084 hdr.msg_name = &unix_sockaddr;
1087 hdr.msg_namelen = 0;
1090 hdr.msg_iovlen = count;
1091 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1092 hdr.msg_accrights = NULL;
1093 hdr.msg_accrightslen = 0;
1095 hdr.msg_control = NULL;
1096 hdr.msg_controllen = 0;
1100 if ( (n = recvmsg(fd, &hdr, *lpFlags)) == -1 )
1104 ws_sockaddr_u2ws( &unix_sockaddr.addr, lpFrom, lpFromlen ) != 0 )
1106 /* The from buffer was too small, but we read the data
1107 * anyway. Is that really bad?
1114 /***********************************************************************
1115 * WS2_async_recv (INTERNAL)
1117 * Handler for overlapped recv() operations.
1119 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, ULONG_PTR *total )
1121 ws2_async* wsa = user;
1126 case STATUS_ALERTED:
1127 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1130 result = WS2_recv( fd, wsa->iovec, wsa->n_iovecs,
1131 wsa->addr, wsa->addrlen.ptr, &wsa->flags );
1132 wine_server_release_fd( wsa->hSocket, fd );
1135 status = STATUS_SUCCESS;
1136 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1140 if (errno == EINTR || errno == EAGAIN)
1142 status = STATUS_PENDING;
1143 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1148 status = wsaErrno(); /* FIXME: is this correct ???? */
1153 if (status != STATUS_PENDING)
1155 iosb->u.Status = status;
1156 iosb->Information = *total = result;
1161 /***********************************************************************
1162 * WS2_send (INTERNAL)
1164 * Workhorse for both synchronous and asynchronous send() operations.
1166 static int WS2_send( int fd, struct iovec* iov, int count,
1167 const struct WS_sockaddr *to, INT tolen, DWORD dwFlags )
1170 union generic_unix_sockaddr unix_addr;
1173 hdr.msg_name = NULL;
1174 hdr.msg_namelen = 0;
1178 hdr.msg_name = &unix_addr;
1179 hdr.msg_namelen = ws_sockaddr_ws2u( to, tolen, &unix_addr );
1180 if ( !hdr.msg_namelen )
1186 #if defined(HAVE_IPX) && defined(SOL_IPX)
1187 if(to->sa_family == WS_AF_IPX)
1189 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1191 unsigned int len=sizeof(int);
1193 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1194 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1195 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1196 * ipx type in the sockaddr_opx structure with the stored value.
1198 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1199 uipx->sipx_type = val;
1205 hdr.msg_iovlen = count;
1206 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1207 hdr.msg_accrights = NULL;
1208 hdr.msg_accrightslen = 0;
1210 hdr.msg_control = NULL;
1211 hdr.msg_controllen = 0;
1215 return sendmsg(fd, &hdr, dwFlags);
1218 /***********************************************************************
1219 * WS2_async_send (INTERNAL)
1221 * Handler for overlapped send() operations.
1223 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, ULONG_PTR *total )
1225 ws2_async* wsa = user;
1230 case STATUS_ALERTED:
1231 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1234 /* check to see if the data is ready (non-blocking) */
1235 result = WS2_send( fd, wsa->iovec, wsa->n_iovecs, wsa->addr, wsa->addrlen.val, wsa->flags );
1236 wine_server_release_fd( wsa->hSocket, fd );
1240 status = STATUS_SUCCESS;
1241 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1245 if (errno == EINTR || errno == EAGAIN)
1247 status = STATUS_PENDING;
1248 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1252 /* We set the status to a winsock error code and check for that
1253 later in NtStatusToWSAError () */
1254 status = wsaErrno();
1260 if (status != STATUS_PENDING)
1262 iosb->u.Status = status;
1263 iosb->Information = *total = result;
1268 /***********************************************************************
1269 * WS2_async_shutdown (INTERNAL)
1271 * Handler for shutdown() operations on overlapped sockets.
1273 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status )
1275 ws2_async* wsa = user;
1280 case STATUS_ALERTED:
1281 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1284 switch ( wsa->type )
1286 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1287 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1289 wine_server_release_fd( wsa->hSocket, fd );
1290 status = err ? wsaErrno() : STATUS_SUCCESS;
1293 iosb->u.Status = status;
1297 /***********************************************************************
1298 * WS2_register_async_shutdown (INTERNAL)
1300 * Helper function for WS_shutdown() on overlapped sockets.
1302 static int WS2_register_async_shutdown( SOCKET s, int type )
1304 struct ws2_async *wsa;
1307 TRACE("s %ld type %d\n", s, type);
1309 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1313 wsa->hSocket = SOCKET2HANDLE(s);
1315 wsa->completion_func = NULL;
1317 SERVER_START_REQ( register_async )
1319 req->handle = wsa->hSocket;
1321 req->async.callback = WS2_async_shutdown;
1322 req->async.iosb = &wsa->local_iosb;
1323 req->async.arg = wsa;
1324 req->async.apc = ws2_async_apc;
1325 req->async.cvalue = 0;
1326 status = wine_server_call( req );
1330 if (status != STATUS_PENDING)
1332 HeapFree( GetProcessHeap(), 0, wsa );
1333 return NtStatusToWSAError( status );
1338 /***********************************************************************
1341 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1347 TRACE("socket %04lx\n", s );
1348 is_blocking = _is_blocking(s);
1353 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1354 if (fd == -1) return INVALID_SOCKET;
1356 do_block(fd, POLLIN, -1);
1357 _sync_sock_state(s); /* let wineserver notice connection */
1358 release_sock_fd( s, fd );
1359 /* retrieve any error codes from it */
1360 SetLastError(_get_sock_error(s, FD_ACCEPT_BIT));
1361 /* FIXME: care about the error? */
1363 SERVER_START_REQ( accept_socket )
1365 req->lhandle = SOCKET2HANDLE(s);
1366 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1367 req->attributes = OBJ_INHERIT;
1368 set_error( wine_server_call( req ) );
1369 as = HANDLE2SOCKET( reply->handle );
1374 if (addr) WS_getpeername(as, addr, addrlen32);
1377 } while (is_blocking);
1378 return INVALID_SOCKET;
1381 /***********************************************************************
1384 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1386 int fd = get_sock_fd( s, 0, NULL );
1387 int res = SOCKET_ERROR;
1389 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1393 if (!name || (name->sa_family && !SUPPORTED_PF(name->sa_family)))
1395 SetLastError(WSAEAFNOSUPPORT);
1399 union generic_unix_sockaddr uaddr;
1400 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1403 SetLastError(WSAEFAULT);
1408 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
1409 if (name->sa_family == WS_AF_INET6 &&
1410 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
1413 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
1415 release_sock_fd( s, fd );
1416 SetLastError(WSAEAFNOSUPPORT);
1417 return INVALID_SOCKET;
1421 if (name->sa_family == WS_AF_INET)
1423 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1424 if (memcmp(&in4->sin_addr, &magic_loopback_addr, 4) == 0)
1426 /* Trying to bind to the default host interface, using
1427 * INADDR_ANY instead*/
1428 WARN("Trying to bind to magic IP address, using "
1429 "INADDR_ANY instead.\n");
1430 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
1433 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
1435 int loc_errno = errno;
1436 WARN("\tfailure - errno = %i\n", errno);
1441 SetLastError(WSAENOTSOCK);
1444 SetLastError(WSAEINVAL);
1447 SetLastError(wsaErrno());
1453 res=0; /* success */
1457 release_sock_fd( s, fd );
1462 /***********************************************************************
1463 * closesocket (WS2_32.3)
1465 int WINAPI WS_closesocket(SOCKET s)
1467 TRACE("socket %04lx\n", s);
1468 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
1469 return SOCKET_ERROR;
1472 /***********************************************************************
1473 * connect (WS2_32.4)
1475 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1477 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1479 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1483 union generic_unix_sockaddr uaddr;
1484 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1488 SetLastError(WSAEFAULT);
1492 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
1493 goto connect_success;
1496 if (errno == EINPROGRESS)
1498 /* tell wineserver that a connection is in progress */
1499 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1500 FD_CONNECT|FD_READ|FD_WRITE,
1501 FD_WINE_CONNECTED|FD_WINE_LISTENING);
1502 if (_is_blocking(s))
1506 do_block(fd, POLLIN | POLLOUT, -1);
1507 _sync_sock_state(s); /* let wineserver notice connection */
1508 /* retrieve any error codes from it */
1509 result = _get_sock_error(s, FD_CONNECT_BIT);
1511 SetLastError(result);
1514 goto connect_success;
1519 SetLastError(WSAEWOULDBLOCK);
1524 SetLastError(wsaErrno());
1526 release_sock_fd( s, fd );
1528 return SOCKET_ERROR;
1531 release_sock_fd( s, fd );
1532 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1533 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1534 FD_CONNECT|FD_WINE_LISTENING);
1538 /***********************************************************************
1539 * WSAConnect (WS2_32.30)
1541 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
1542 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1543 LPQOS lpSQOS, LPQOS lpGQOS )
1545 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1546 FIXME("unsupported parameters!\n");
1547 return WS_connect( s, name, namelen );
1551 /***********************************************************************
1552 * getpeername (WS2_32.5)
1554 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1559 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, *namelen);
1561 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1562 if( (name == NULL) || (namelen == NULL) )
1564 SetLastError( WSAEFAULT );
1565 return SOCKET_ERROR;
1568 fd = get_sock_fd( s, 0, NULL );
1573 union generic_unix_sockaddr uaddr;
1574 unsigned int uaddrlen = sizeof(uaddr);
1576 if (getpeername(fd, &uaddr.addr, &uaddrlen) != 0)
1578 SetLastError(wsaErrno());
1580 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1582 /* The buffer was too small */
1583 SetLastError(WSAEFAULT);
1589 release_sock_fd( s, fd );
1594 /***********************************************************************
1595 * getsockname (WS2_32.6)
1597 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1602 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
1604 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1605 if( (name == NULL) || (namelen == NULL) )
1607 SetLastError( WSAEFAULT );
1608 return SOCKET_ERROR;
1611 fd = get_sock_fd( s, 0, NULL );
1616 union generic_unix_sockaddr uaddr;
1617 unsigned int uaddrlen = sizeof(uaddr);
1619 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
1621 SetLastError(wsaErrno());
1623 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
1625 SetLastError(WSAEINVAL);
1627 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1629 /* The buffer was too small */
1630 SetLastError(WSAEFAULT);
1636 release_sock_fd( s, fd );
1641 /***********************************************************************
1642 * getsockopt (WS2_32.7)
1644 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1645 INT optname, char *optval, INT *optlen)
1650 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
1651 s, level, optname, optval, *optlen);
1659 /* Handle common cases. The special cases are below, sorted
1661 case WS_SO_ACCEPTCONN:
1662 case WS_SO_BROADCAST:
1665 case WS_SO_KEEPALIVE:
1666 case WS_SO_OOBINLINE:
1668 case WS_SO_REUSEADDR:
1671 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1672 return SOCKET_ERROR;
1673 convert_sockopt(&level, &optname);
1674 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1676 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1679 release_sock_fd( s, fd );
1682 case WS_SO_DONTLINGER:
1684 struct linger lingval;
1685 unsigned int len = sizeof(struct linger);
1687 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
1689 SetLastError(WSAEFAULT);
1690 return SOCKET_ERROR;
1692 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1693 return SOCKET_ERROR;
1695 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1697 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1702 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
1703 *optlen = sizeof(BOOL);
1706 release_sock_fd( s, fd );
1710 /* As mentioned in setsockopt, Windows ignores this, so we
1711 * always return true here */
1712 case WS_SO_DONTROUTE:
1713 if (!optlen || *optlen < sizeof(BOOL) || !optval)
1715 SetLastError(WSAEFAULT);
1716 return SOCKET_ERROR;
1718 *(BOOL *)optval = TRUE;
1719 *optlen = sizeof(BOOL);
1724 struct linger lingval;
1725 unsigned int len = sizeof(struct linger);
1727 /* struct linger and LINGER have different sizes */
1728 if (!optlen || *optlen < sizeof(LINGER) || !optval)
1730 SetLastError(WSAEFAULT);
1731 return SOCKET_ERROR;
1733 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1734 return SOCKET_ERROR;
1736 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1738 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1743 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
1744 ((LINGER *)optval)->l_linger = lingval.l_linger;
1745 *optlen = sizeof(struct linger);
1748 release_sock_fd( s, fd );
1752 case WS_SO_MAX_MSG_SIZE:
1753 if (!optlen || *optlen < sizeof(int) || !optval)
1755 SetLastError(WSAEFAULT);
1756 return SOCKET_ERROR;
1758 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
1759 *(int *)optval = 65507;
1760 *optlen = sizeof(int);
1763 /* SO_OPENTYPE does not require a valid socket handle. */
1764 case WS_SO_OPENTYPE:
1765 if (!optlen || *optlen < sizeof(int) || !optval)
1767 SetLastError(WSAEFAULT);
1768 return SOCKET_ERROR;
1770 *(int *)optval = get_per_thread_data()->opentype;
1771 *optlen = sizeof(int);
1772 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
1776 case WS_SO_RCVTIMEO:
1779 case WS_SO_SNDTIMEO:
1781 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
1784 unsigned int len = sizeof(struct timeval);
1786 if (!optlen || *optlen < sizeof(int)|| !optval)
1788 SetLastError(WSAEFAULT);
1789 return SOCKET_ERROR;
1791 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1792 return SOCKET_ERROR;
1794 convert_sockopt(&level, &optname);
1795 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
1797 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1802 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1803 *optlen = sizeof(int);
1806 release_sock_fd( s, fd );
1811 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
1812 SetLastError(WSAENOPROTOOPT);
1813 return SOCKET_ERROR;
1814 } /* end switch(optname) */
1815 }/* end case WS_SOL_SOCKET */
1819 struct WS_sockaddr_ipx addr;
1820 IPX_ADDRESS_DATA *data;
1825 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
1827 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
1834 socklen_t len=sizeof(struct ipx);
1835 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
1838 *optval = (int)val.ipx_pt;
1841 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
1842 release_sock_fd( s, fd );
1847 * On a Win2000 system with one network card there are usually
1848 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
1849 * Using this call you can then retrieve info about this all.
1850 * In case of Linux it is a bit different. Usually you have
1851 * only "one" device active and further it is not possible to
1852 * query things like the linkspeed.
1854 FIXME("IPX_ADDRESS\n");
1855 namelen = sizeof(struct WS_sockaddr_ipx);
1856 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
1857 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
1859 data = (IPX_ADDRESS_DATA*)optval;
1860 memcpy(data->nodenum,&addr.sa_nodenum,sizeof(data->nodenum));
1861 memcpy(data->netnum,&addr.sa_netnum,sizeof(data->netnum));
1862 data->adapternum = 0;
1863 data->wan = FALSE; /* We are not on a wan for now .. */
1864 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
1865 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
1866 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
1867 * note 1MB = 1000kB in this case */
1870 case IPX_MAX_ADAPTER_NUM:
1871 FIXME("IPX_MAX_ADAPTER_NUM\n");
1872 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
1876 FIXME("IPX optname:%x\n", optname);
1877 return SOCKET_ERROR;
1878 }/* end switch(optname) */
1879 } /* end case NSPROTO_IPX */
1881 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
1882 case WS_IPPROTO_TCP:
1885 case WS_TCP_NODELAY:
1886 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1887 return SOCKET_ERROR;
1888 convert_sockopt(&level, &optname);
1889 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1891 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1894 release_sock_fd( s, fd );
1897 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
1898 return SOCKET_ERROR;
1903 case WS_IP_ADD_MEMBERSHIP:
1904 case WS_IP_DROP_MEMBERSHIP:
1908 case WS_IP_MULTICAST_IF:
1909 case WS_IP_MULTICAST_LOOP:
1910 case WS_IP_MULTICAST_TTL:
1914 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1915 return SOCKET_ERROR;
1916 convert_sockopt(&level, &optname);
1917 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1919 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1922 release_sock_fd( s, fd );
1924 case WS_IP_DONTFRAGMENT:
1925 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
1926 *(BOOL*)optval = FALSE;
1929 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
1930 return SOCKET_ERROR;
1933 FIXME("Unknown level: 0x%08x\n", level);
1934 return SOCKET_ERROR;
1935 } /* end switch(level) */
1938 /***********************************************************************
1942 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
1944 return htonl(hostlong);
1948 /***********************************************************************
1952 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
1954 return htons(hostshort);
1957 /***********************************************************************
1958 * WSAHtonl (WS2_32.46)
1959 * From MSDN description of error codes, this function should also
1960 * check if WinSock has been initialized and the socket is a valid
1961 * socket. But why? This function only translates a host byte order
1962 * u_long into a network byte order u_long...
1964 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
1968 *lpnetlong = htonl(hostlong);
1971 WSASetLastError(WSAEFAULT);
1972 return SOCKET_ERROR;
1975 /***********************************************************************
1976 * WSAHtons (WS2_32.47)
1977 * From MSDN description of error codes, this function should also
1978 * check if WinSock has been initialized and the socket is a valid
1979 * socket. But why? This function only translates a host byte order
1980 * u_short into a network byte order u_short...
1982 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
1987 *lpnetshort = htons(hostshort);
1990 WSASetLastError(WSAEFAULT);
1991 return SOCKET_ERROR;
1995 /***********************************************************************
1996 * inet_addr (WINSOCK.10)
1997 * inet_addr (WS2_32.11)
1999 WS_u_long WINAPI WS_inet_addr(const char *cp)
2001 if (!cp) return INADDR_NONE;
2002 return inet_addr(cp);
2006 /***********************************************************************
2007 * ntohl (WINSOCK.14)
2010 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2012 return ntohl(netlong);
2016 /***********************************************************************
2017 * ntohs (WINSOCK.15)
2020 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2022 return ntohs(netshort);
2026 /***********************************************************************
2027 * inet_ntoa (WS2_32.12)
2029 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2031 /* use "buffer for dummies" here because some applications have a
2032 * propensity to decode addresses in ws_hostent structure without
2033 * saving them first...
2035 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2037 char* s = inet_ntoa(*((struct in_addr*)&in));
2043 SetLastError(wsaErrno());
2047 /**********************************************************************
2048 * WSAIoctl (WS2_32.50)
2051 INT WINAPI WSAIoctl(SOCKET s,
2052 DWORD dwIoControlCode,
2055 LPVOID lpbOutBuffer,
2057 LPDWORD lpcbBytesReturned,
2058 LPWSAOVERLAPPED lpOverlapped,
2059 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2061 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
2062 s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpbOutBuffer,
2063 cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
2065 switch( dwIoControlCode )
2068 if (cbInBuffer != sizeof(WS_u_long)) {
2069 WSASetLastError(WSAEFAULT);
2070 return SOCKET_ERROR;
2072 return WS_ioctlsocket( s, WS_FIONBIO, lpvInBuffer);
2075 if (cbOutBuffer != sizeof(WS_u_long)) {
2076 WSASetLastError(WSAEFAULT);
2077 return SOCKET_ERROR;
2079 return WS_ioctlsocket( s, WS_FIONREAD, lpbOutBuffer);
2081 case WS_SIO_GET_INTERFACE_LIST:
2083 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
2084 DWORD size, numInt, apiReturn;
2087 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
2091 WSASetLastError(WSAEFAULT);
2092 return SOCKET_ERROR;
2094 if (!lpcbBytesReturned)
2096 WSASetLastError(WSAEFAULT);
2097 return SOCKET_ERROR;
2100 fd = get_sock_fd( s, 0, NULL );
2101 if (fd == -1) return SOCKET_ERROR;
2103 apiReturn = GetAdaptersInfo(NULL, &size);
2104 if (apiReturn == ERROR_NO_DATA)
2108 else if (apiReturn == ERROR_BUFFER_OVERFLOW)
2110 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
2114 if (GetAdaptersInfo(table, &size) == NO_ERROR)
2116 PIP_ADAPTER_INFO ptr;
2118 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > cbOutBuffer)
2120 WARN("Buffer too small = %u, cbOutBuffer = %u\n", size, cbOutBuffer);
2121 HeapFree(GetProcessHeap(),0,table);
2122 release_sock_fd( s, fd );
2123 WSASetLastError(WSAEFAULT);
2124 return SOCKET_ERROR;
2126 for (ptr = table, numInt = 0; ptr;
2127 ptr = ptr->Next, intArray++, numInt++)
2129 unsigned int addr, mask, bcast;
2130 struct ifreq ifInfo;
2132 /* Socket Status Flags */
2133 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
2134 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2136 ERR("Error obtaining status flags for socket!\n");
2137 HeapFree(GetProcessHeap(),0,table);
2138 release_sock_fd( s, fd );
2139 WSASetLastError(WSAEINVAL);
2140 return SOCKET_ERROR;
2144 /* set flags; the values of IFF_* are not the same
2145 under Linux and Windows, therefore must generate
2147 intArray->iiFlags = 0;
2148 if (ifInfo.ifr_flags & IFF_BROADCAST)
2149 intArray->iiFlags |= WS_IFF_BROADCAST;
2150 #ifdef IFF_POINTOPOINT
2151 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
2152 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
2154 if (ifInfo.ifr_flags & IFF_LOOPBACK)
2155 intArray->iiFlags |= WS_IFF_LOOPBACK;
2156 if (ifInfo.ifr_flags & IFF_UP)
2157 intArray->iiFlags |= WS_IFF_UP;
2158 if (ifInfo.ifr_flags & IFF_MULTICAST)
2159 intArray->iiFlags |= WS_IFF_MULTICAST;
2162 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
2163 mask = inet_addr(ptr->IpAddressList.IpMask.String);
2164 bcast = addr | ~mask;
2165 intArray->iiAddress.AddressIn.sin_family = AF_INET;
2166 intArray->iiAddress.AddressIn.sin_port = 0;
2167 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
2169 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2170 intArray->iiNetmask.AddressIn.sin_port = 0;
2171 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
2173 intArray->iiBroadcastAddress.AddressIn.sin_family =
2175 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
2176 intArray->iiBroadcastAddress.AddressIn.sin_addr.
2182 ERR("Unable to get interface table!\n");
2183 release_sock_fd( s, fd );
2184 HeapFree(GetProcessHeap(),0,table);
2185 WSASetLastError(WSAEINVAL);
2186 return SOCKET_ERROR;
2188 HeapFree(GetProcessHeap(),0,table);
2192 release_sock_fd( s, fd );
2193 WSASetLastError(WSAEINVAL);
2194 return SOCKET_ERROR;
2199 ERR("Unable to get interface table!\n");
2200 release_sock_fd( s, fd );
2201 WSASetLastError(WSAEINVAL);
2202 return SOCKET_ERROR;
2204 /* Calculate the size of the array being returned */
2205 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2206 release_sock_fd( s, fd );
2210 case WS_SIO_ADDRESS_LIST_CHANGE:
2211 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
2212 /* FIXME: error and return code depend on whether socket was created
2213 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
2216 case WS_SIO_ADDRESS_LIST_QUERY:
2220 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
2222 if (!lpcbBytesReturned)
2224 WSASetLastError(WSAEFAULT);
2225 return SOCKET_ERROR;
2228 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
2230 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
2233 if (!table || GetAdaptersInfo(table, &size))
2235 HeapFree(GetProcessHeap(), 0, table);
2236 WSASetLastError(WSAEINVAL);
2237 return SOCKET_ERROR;
2240 for (p = table, num = 0; p; p = p->Next)
2241 if (p->IpAddressList.IpAddress.String[0]) num++;
2243 need = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
2244 need += sizeof(SOCKADDR) * num;
2245 *lpcbBytesReturned = need;
2247 if (need > cbOutBuffer)
2249 HeapFree(GetProcessHeap(), 0, table);
2250 WSASetLastError(WSAEFAULT);
2251 return SOCKET_ERROR;
2258 SOCKET_ADDRESS_LIST *sa_list = (SOCKET_ADDRESS_LIST *)lpbOutBuffer;
2259 SOCKADDR_IN *sockaddr;
2261 sa = sa_list->Address;
2262 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
2263 sa_list->iAddressCount = num;
2265 for (p = table, i = 0; p; p = p->Next)
2267 if (!p->IpAddressList.IpAddress.String[0]) continue;
2269 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
2270 sa[i].iSockaddrLength = sizeof(SOCKADDR);
2272 sockaddr[i].sin_family = AF_INET;
2273 sockaddr[i].sin_port = 0;
2274 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
2279 HeapFree(GetProcessHeap(), 0, table);
2284 WARN("unable to get IP address list\n");
2285 WSASetLastError(WSAEINVAL);
2286 return SOCKET_ERROR;
2290 FIXME("SIO_FLUSH: stub.\n");
2293 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
2294 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(lpvInBuffer));
2295 WSASetLastError(WSAEOPNOTSUPP);
2296 return SOCKET_ERROR;
2299 FIXME("unsupported WS_IOCTL cmd (%08x)\n", dwIoControlCode);
2300 WSASetLastError(WSAEOPNOTSUPP);
2301 return SOCKET_ERROR;
2308 /***********************************************************************
2309 * ioctlsocket (WS2_32.10)
2311 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
2316 TRACE("socket %04lx, cmd %08x, ptr %p\n", s, cmd, argp);
2325 if( _get_sock_mask(s) )
2327 /* AsyncSelect()'ed sockets are always nonblocking */
2328 if (*argp) return 0;
2329 SetLastError(WSAEINVAL);
2330 return SOCKET_ERROR;
2332 fd = get_sock_fd( s, 0, NULL );
2338 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
2339 ret = fcntl( fd, F_SETFL, O_NONBLOCK );
2343 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
2344 ret = fcntl( fd, F_SETFL, 0 );
2346 release_sock_fd( s, fd );
2348 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2350 return SOCKET_ERROR;
2357 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2358 SetLastError(WSAEINVAL);
2359 return SOCKET_ERROR;
2361 case SIOCGIFBRDADDR:
2362 case SIOCGIFNETMASK:
2364 /* These don't need any special handling. They are used by
2365 WsControl, and are here to suppress an unnecessary warning. */
2369 /* Netscape tries hard to use bogus ioctl 0x667e */
2370 /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
2371 * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
2373 WARN("\tunknown WS_IOCTL cmd (%08x)\n", cmd);
2377 fd = get_sock_fd( s, 0, NULL );
2380 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2382 release_sock_fd( s, fd );
2385 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2386 release_sock_fd( s, fd );
2388 return SOCKET_ERROR;
2391 /***********************************************************************
2392 * listen (WS2_32.13)
2394 int WINAPI WS_listen(SOCKET s, int backlog)
2396 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2398 TRACE("socket %04lx, backlog %d\n", s, backlog);
2401 if (listen(fd, backlog) == 0)
2403 release_sock_fd( s, fd );
2404 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
2406 FD_CONNECT|FD_WINE_CONNECTED);
2409 SetLastError(wsaErrno());
2410 release_sock_fd( s, fd );
2412 return SOCKET_ERROR;
2415 /***********************************************************************
2418 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2420 DWORD n, dwFlags = flags;
2426 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2427 return SOCKET_ERROR;
2432 /***********************************************************************
2433 * recvfrom (WS2_32.17)
2435 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2436 struct WS_sockaddr *from, int *fromlen)
2438 DWORD n, dwFlags = flags;
2444 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2445 return SOCKET_ERROR;
2450 /* allocate a poll array for the corresponding fd sets */
2451 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
2452 const WS_fd_set *exceptfds, int *count_ptr )
2454 int i, j = 0, count = 0;
2457 if (readfds) count += readfds->fd_count;
2458 if (writefds) count += writefds->fd_count;
2459 if (exceptfds) count += exceptfds->fd_count;
2461 if (!count) return NULL;
2462 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0])))) return NULL;
2464 for (i = 0; i < readfds->fd_count; i++, j++)
2466 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
2467 fds[j].events = POLLIN;
2471 for (i = 0; i < writefds->fd_count; i++, j++)
2473 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
2474 fds[j].events = POLLOUT;
2478 for (i = 0; i < exceptfds->fd_count; i++, j++)
2480 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
2481 fds[j].events = POLLHUP;
2487 /* release the file descriptor obtained in fd_sets_to_poll */
2488 /* must be called with the original fd_set arrays, before calling get_poll_results */
2489 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
2490 const WS_fd_set *exceptfds, struct pollfd *fds )
2496 for (i = 0; i < readfds->fd_count; i++, j++)
2497 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
2501 for (i = 0; i < writefds->fd_count; i++, j++)
2502 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
2506 for (i = 0; i < exceptfds->fd_count; i++, j++)
2507 if (fds[j].fd != -1)
2509 /* make sure we have a real error before releasing the fd */
2510 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
2511 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
2516 /* map the poll results back into the Windows fd sets */
2517 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
2518 const struct pollfd *fds )
2520 int i, j = 0, k, total = 0;
2524 for (i = k = 0; i < readfds->fd_count; i++, j++)
2525 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
2526 readfds->fd_count = k;
2531 for (i = k = 0; i < writefds->fd_count; i++, j++)
2532 if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
2533 writefds->fd_count = k;
2538 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
2539 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
2540 exceptfds->fd_count = k;
2547 /***********************************************************************
2548 * select (WS2_32.18)
2550 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
2551 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
2552 const struct WS_timeval* ws_timeout)
2554 struct pollfd *pollfds;
2555 int count, ret, timeout = -1;
2557 TRACE("read %p, write %p, excp %p timeout %p\n",
2558 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
2560 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )) && count)
2562 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2563 return SOCKET_ERROR;
2566 if (ws_timeout) timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
2568 ret = poll( pollfds, count, timeout );
2569 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2571 if (ret == -1) SetLastError(wsaErrno());
2572 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2573 HeapFree( GetProcessHeap(), 0, pollfds );
2577 /* helper to send completion messages for client-only i/o operation case */
2578 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG_PTR Information )
2582 SERVER_START_REQ( add_fd_completion )
2584 req->handle = SOCKET2HANDLE(sock);
2585 req->cvalue = CompletionValue;
2586 req->status = CompletionStatus;
2587 req->information = Information;
2588 status = wine_server_call( req );
2594 /***********************************************************************
2597 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
2603 wsabuf.buf = (char*) buf;
2605 if ( WSASendTo( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
2606 return SOCKET_ERROR;
2611 /***********************************************************************
2612 * WSASend (WS2_32.72)
2614 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2615 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2616 LPWSAOVERLAPPED lpOverlapped,
2617 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2619 return WSASendTo( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
2620 NULL, 0, lpOverlapped, lpCompletionRoutine );
2623 /***********************************************************************
2624 * WSASendDisconnect (WS2_32.73)
2626 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
2628 return WS_shutdown( s, SD_SEND );
2632 /***********************************************************************
2633 * WSASendTo (WS2_32.74)
2635 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2636 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2637 const struct WS_sockaddr *to, int tolen,
2638 LPWSAOVERLAPPED lpOverlapped,
2639 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2641 unsigned int i, options;
2643 struct iovec iovec[WS_MSG_MAXIOVLEN];
2644 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
2646 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
2647 s, lpBuffers, dwBufferCount, dwFlags,
2648 to, tolen, lpOverlapped, lpCompletionRoutine);
2650 if (dwBufferCount > WS_MSG_MAXIOVLEN)
2652 WSASetLastError( WSAEINVAL );
2653 return SOCKET_ERROR;
2656 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
2657 TRACE( "fd=%d, options=%x\n", fd, options );
2659 if ( fd == -1 ) return SOCKET_ERROR;
2661 if ( !lpNumberOfBytesSent )
2667 for ( i = 0; i < dwBufferCount; i++ )
2669 iovec[i].iov_base = lpBuffers[i].buf;
2670 iovec[i].iov_len = lpBuffers[i].len;
2675 n = WS2_send( fd, iovec, dwBufferCount, to, tolen, dwFlags );
2676 if (n != -1 || errno != EINTR) break;
2678 if (n == -1 && errno != EAGAIN)
2681 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
2685 if ((lpOverlapped || lpCompletionRoutine) &&
2686 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
2688 IO_STATUS_BLOCK *iosb;
2689 struct ws2_async *wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
2696 release_sock_fd( s, fd );
2698 wsa->hSocket = SOCKET2HANDLE(s);
2699 wsa->addr = (struct WS_sockaddr *)to;
2700 wsa->addrlen.val = tolen;
2702 wsa->user_overlapped = lpOverlapped;
2703 wsa->completion_func = lpCompletionRoutine;
2704 wsa->n_iovecs = dwBufferCount;
2705 memcpy( wsa->iovec, iovec, dwBufferCount * sizeof(*iovec) );
2707 iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
2710 iosb->u.Status = STATUS_PENDING;
2711 iosb->Information = 0;
2713 SERVER_START_REQ( register_async )
2715 req->handle = wsa->hSocket;
2716 req->type = ASYNC_TYPE_WRITE;
2717 req->async.callback = WS2_async_send;
2718 req->async.iosb = iosb;
2719 req->async.arg = wsa;
2720 req->async.apc = ws2_async_apc;
2721 req->async.event = lpCompletionRoutine ? 0 : lpOverlapped->hEvent;
2722 req->async.cvalue = cvalue;
2723 err = wine_server_call( req );
2727 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
2728 WSASetLastError( NtStatusToWSAError( err ));
2729 return SOCKET_ERROR;
2732 iosb->u.Status = STATUS_SUCCESS;
2733 iosb->Information = n;
2734 *lpNumberOfBytesSent = n;
2735 if (!wsa->completion_func)
2737 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
2738 SetEvent( lpOverlapped->hEvent );
2739 HeapFree( GetProcessHeap(), 0, wsa );
2741 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
2742 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
2746 if ( _is_blocking(s) )
2748 /* On a blocking non-overlapped stream socket,
2749 * sending blocks until the entire buffer is sent. */
2750 DWORD timeout_start = GetTickCount();
2751 unsigned int first_buff = 0;
2753 *lpNumberOfBytesSent = 0;
2755 while (first_buff < dwBufferCount)
2758 int timeout = GET_SNDTIMEO(fd);
2762 *lpNumberOfBytesSent += n;
2763 while (first_buff < dwBufferCount && iovec[first_buff].iov_len <= n)
2764 n -= iovec[first_buff++].iov_len;
2765 if (first_buff >= dwBufferCount) break;
2766 iovec[first_buff].iov_base = (char*)iovec[first_buff].iov_base + n;
2767 iovec[first_buff].iov_len -= n;
2772 timeout -= GetTickCount() - timeout_start;
2773 if (timeout < 0) timeout = 0;
2777 pfd.events = POLLOUT;
2779 if (!timeout || !poll( &pfd, 1, timeout ))
2782 goto error; /* msdn says a timeout in send is fatal */
2785 n = WS2_send( fd, iovec + first_buff, dwBufferCount - first_buff, to, tolen, dwFlags );
2786 if (n == -1 && errno != EAGAIN && errno != EINTR)
2793 else /* non-blocking */
2795 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
2798 err = WSAEWOULDBLOCK;
2801 *lpNumberOfBytesSent = n;
2804 TRACE(" -> %i bytes\n", *lpNumberOfBytesSent);
2806 release_sock_fd( s, fd );
2810 release_sock_fd( s, fd );
2811 WARN(" -> ERROR %d\n", err);
2812 WSASetLastError(err);
2813 return SOCKET_ERROR;
2816 /***********************************************************************
2817 * sendto (WS2_32.20)
2819 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
2820 const struct WS_sockaddr *to, int tolen)
2826 wsabuf.buf = (char*) buf;
2828 if ( WSASendTo(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
2829 return SOCKET_ERROR;
2834 /***********************************************************************
2835 * setsockopt (WS2_32.21)
2837 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
2838 const char *optval, int optlen)
2842 struct linger linger;
2843 struct timeval tval;
2845 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2846 s, level, optname, optval, optlen);
2848 /* some broken apps pass the value directly instead of a pointer to it */
2849 if(IS_INTRESOURCE(optval))
2851 SetLastError(WSAEFAULT);
2852 return SOCKET_ERROR;
2860 /* Some options need some conversion before they can be sent to
2861 * setsockopt. The conversions are done here, then they will fall though
2862 * to the general case. Special options that are not passed to
2863 * setsockopt follow below that.*/
2865 case WS_SO_DONTLINGER:
2866 linger.l_onoff = *((const int*)optval) ? 0: 1;
2867 linger.l_linger = 0;
2869 optname = SO_LINGER;
2870 optval = (char*)&linger;
2871 optlen = sizeof(struct linger);
2875 linger.l_onoff = ((LINGER*)optval)->l_onoff;
2876 linger.l_linger = ((LINGER*)optval)->l_linger;
2877 /* FIXME: what is documented behavior if SO_LINGER optval
2880 optname = SO_LINGER;
2881 optval = (char*)&linger;
2882 optlen = sizeof(struct linger);
2886 if (*(const int*)optval < 2048)
2888 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
2893 /* The options listed here don't need any special handling. Thanks to
2894 * the conversion happening above, options from there will fall through
2896 case WS_SO_ACCEPTCONN:
2897 case WS_SO_BROADCAST:
2899 case WS_SO_KEEPALIVE:
2900 case WS_SO_OOBINLINE:
2901 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
2902 * however, using it the BSD way fixes bug 8513 and seems to be what
2903 * most programmers assume, anyway */
2904 case WS_SO_REUSEADDR:
2907 convert_sockopt(&level, &optname);
2910 /* SO_DEBUG is a privileged operation, ignore it. */
2912 TRACE("Ignoring SO_DEBUG\n");
2915 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
2916 * socket. According to MSDN, this option is silently ignored.*/
2917 case WS_SO_DONTROUTE:
2918 TRACE("Ignoring SO_DONTROUTE\n");
2921 /* Stops two sockets from being bound to the same port. Always happens
2922 * on unix systems, so just drop it. */
2923 case WS_SO_EXCLUSIVEADDRUSE:
2924 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
2927 /* SO_OPENTYPE does not require a valid socket handle. */
2928 case WS_SO_OPENTYPE:
2929 if (!optlen || optlen < sizeof(int) || !optval)
2931 SetLastError(WSAEFAULT);
2932 return SOCKET_ERROR;
2934 get_per_thread_data()->opentype = *(const int *)optval;
2935 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2939 case WS_SO_RCVTIMEO:
2942 case WS_SO_SNDTIMEO:
2944 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
2945 if (optval && optlen == sizeof(UINT32)) {
2946 /* WinSock passes milliseconds instead of struct timeval */
2947 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
2948 tval.tv_sec = *(const UINT32*)optval / 1000;
2949 /* min of 500 milliseconds */
2950 if (tval.tv_sec == 0 && tval.tv_usec < 500000)
2951 tval.tv_usec = 500000;
2952 optlen = sizeof(struct timeval);
2953 optval = (char*)&tval;
2954 } else if (optlen == sizeof(struct timeval)) {
2955 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
2957 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
2960 convert_sockopt(&level, &optname);
2965 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
2966 SetLastError(WSAENOPROTOOPT);
2967 return SOCKET_ERROR;
2969 break; /* case WS_SOL_SOCKET */
2976 fd = get_sock_fd( s, 0, NULL );
2977 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
2979 /* We try to set the ipx type on ipx socket level. */
2981 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
2983 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
2984 release_sock_fd( s, fd );
2985 return SOCKET_ERROR;
2990 /* Should we retrieve val using a getsockopt call and then
2991 * set the modified one? */
2992 val.ipx_pt = *optval;
2993 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
2996 release_sock_fd( s, fd );
2999 case IPX_FILTERPTYPE:
3000 /* Sets the receive filter packet type, at the moment we don't support it */
3001 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
3002 /* Returning 0 is better for now than returning a SOCKET_ERROR */
3006 FIXME("opt_name:%x\n", optname);
3007 return SOCKET_ERROR;
3009 break; /* case NSPROTO_IPX */
3012 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3013 case WS_IPPROTO_TCP:
3016 case WS_TCP_NODELAY:
3017 convert_sockopt(&level, &optname);
3020 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3021 return SOCKET_ERROR;
3028 case WS_IP_ADD_MEMBERSHIP:
3029 case WS_IP_DROP_MEMBERSHIP:
3033 case WS_IP_MULTICAST_IF:
3034 case WS_IP_MULTICAST_LOOP:
3035 case WS_IP_MULTICAST_TTL:
3039 convert_sockopt(&level, &optname);
3041 case WS_IP_DONTFRAGMENT:
3042 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
3045 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3046 return SOCKET_ERROR;
3051 FIXME("Unknown level: 0x%08x\n", level);
3052 return SOCKET_ERROR;
3053 } /* end switch(level) */
3055 /* avoid endianness issues if argument is a 16-bit int */
3056 if (optval && optlen < sizeof(int))
3058 woptval= *((const INT16 *) optval);
3059 optval= (char*) &woptval;
3062 fd = get_sock_fd( s, 0, NULL );
3063 if (fd == -1) return SOCKET_ERROR;
3065 if (setsockopt(fd, level, optname, optval, optlen) == 0)
3067 release_sock_fd( s, fd );
3070 TRACE("Setting socket error, %d\n", wsaErrno());
3071 SetLastError(wsaErrno());
3072 release_sock_fd( s, fd );
3074 return SOCKET_ERROR;
3077 /***********************************************************************
3078 * shutdown (WS2_32.22)
3080 int WINAPI WS_shutdown(SOCKET s, int how)
3082 int fd, err = WSAENOTSOCK;
3083 unsigned int options, clear_flags = 0;
3085 fd = get_sock_fd( s, 0, &options );
3086 TRACE("socket %04lx, how %i %x\n", s, how, options );
3089 return SOCKET_ERROR;
3093 case 0: /* drop receives */
3094 clear_flags |= FD_READ;
3096 case 1: /* drop sends */
3097 clear_flags |= FD_WRITE;
3099 case 2: /* drop all */
3100 clear_flags |= FD_READ|FD_WRITE;
3102 clear_flags |= FD_WINE_LISTENING;
3105 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3110 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3113 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3117 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3118 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3121 if (err) goto error;
3123 else /* non-overlapped mode */
3125 if ( shutdown( fd, how ) )
3132 release_sock_fd( s, fd );
3133 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3134 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
3138 release_sock_fd( s, fd );
3139 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3140 WSASetLastError( err );
3141 return SOCKET_ERROR;
3144 /***********************************************************************
3145 * socket (WS2_32.23)
3147 SOCKET WINAPI WS_socket(int af, int type, int protocol)
3149 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
3151 return WSASocketA( af, type, protocol, NULL, 0,
3152 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
3156 /***********************************************************************
3157 * gethostbyaddr (WS2_32.51)
3159 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
3161 struct WS_hostent *retval = NULL;
3162 struct hostent* host;
3164 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3167 struct hostent hostentry;
3170 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3172 int res = gethostbyaddr_r(addr, len, type,
3173 &hostentry, extrabuf, ebufsize, &host, &locerr);
3174 if( res != ERANGE) break;
3176 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3178 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3180 EnterCriticalSection( &csWSgetXXXbyYYY );
3181 host = gethostbyaddr(addr, len, type);
3182 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3184 if( host != NULL ) retval = WS_dup_he(host);
3185 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3186 HeapFree(GetProcessHeap(),0,extrabuf);
3188 LeaveCriticalSection( &csWSgetXXXbyYYY );
3190 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
3194 /***********************************************************************
3195 * gethostbyname (WS2_32.52)
3197 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
3199 struct WS_hostent *retval = NULL;
3200 struct hostent* host;
3201 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3204 struct hostent hostentry;
3205 int locerr = ENOBUFS;
3208 if( !name || !name[0]) {
3210 if( gethostname( buf, 100) == -1) {
3211 SetLastError( WSAENOBUFS); /* appropriate ? */
3215 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3217 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3219 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
3220 if( res != ERANGE) break;
3222 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3224 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3226 EnterCriticalSection( &csWSgetXXXbyYYY );
3227 host = gethostbyname(name);
3228 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3230 if (host) retval = WS_dup_he(host);
3231 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3232 HeapFree(GetProcessHeap(),0,extrabuf);
3234 LeaveCriticalSection( &csWSgetXXXbyYYY );
3236 if (retval && retval->h_addr_list[0][0] == 127 &&
3237 strcmp(name, "localhost") != 0)
3239 /* hostname != "localhost" but has loopback address. replace by our
3240 * special address.*/
3241 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
3243 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3248 /***********************************************************************
3249 * getprotobyname (WS2_32.53)
3251 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3253 struct WS_protoent* retval = NULL;
3254 #ifdef HAVE_GETPROTOBYNAME
3255 struct protoent* proto;
3256 EnterCriticalSection( &csWSgetXXXbyYYY );
3257 if( (proto = getprotobyname(name)) != NULL )
3259 retval = WS_dup_pe(proto);
3262 MESSAGE("protocol %s not found; You might want to add "
3263 "this to /etc/protocols\n", debugstr_a(name) );
3264 SetLastError(WSANO_DATA);
3266 LeaveCriticalSection( &csWSgetXXXbyYYY );
3268 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3273 /***********************************************************************
3274 * getprotobynumber (WS2_32.54)
3276 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3278 struct WS_protoent* retval = NULL;
3279 #ifdef HAVE_GETPROTOBYNUMBER
3280 struct protoent* proto;
3281 EnterCriticalSection( &csWSgetXXXbyYYY );
3282 if( (proto = getprotobynumber(number)) != NULL )
3284 retval = WS_dup_pe(proto);
3287 MESSAGE("protocol number %d not found; You might want to add "
3288 "this to /etc/protocols\n", number );
3289 SetLastError(WSANO_DATA);
3291 LeaveCriticalSection( &csWSgetXXXbyYYY );
3293 TRACE("%i ret %p\n", number, retval);
3298 /***********************************************************************
3299 * getservbyname (WS2_32.55)
3301 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3303 struct WS_servent* retval = NULL;
3304 struct servent* serv;
3306 char *proto_str = NULL;
3308 if (!(name_str = strdup_lower(name))) return NULL;
3310 if (proto && *proto)
3312 if (!(proto_str = strdup_lower(proto)))
3314 HeapFree( GetProcessHeap(), 0, name_str );
3319 EnterCriticalSection( &csWSgetXXXbyYYY );
3320 serv = getservbyname(name_str, proto_str);
3323 retval = WS_dup_se(serv);
3325 else SetLastError(WSANO_DATA);
3326 LeaveCriticalSection( &csWSgetXXXbyYYY );
3327 HeapFree( GetProcessHeap(), 0, proto_str );
3328 HeapFree( GetProcessHeap(), 0, name_str );
3329 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
3333 /***********************************************************************
3334 * freeaddrinfo (WS2_32.@)
3336 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
3339 struct WS_addrinfo *next;
3341 HeapFree(GetProcessHeap(),0,res->ai_canonname);
3342 HeapFree(GetProcessHeap(),0,res->ai_addr);
3343 next = res->ai_next;
3344 HeapFree(GetProcessHeap(),0,res);
3349 /* helper functions for getaddrinfo()/getnameinfo() */
3350 static int convert_aiflag_w2u(int winflags) {
3351 int i, unixflags = 0;
3353 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3354 if (ws_aiflag_map[i][0] & winflags) {
3355 unixflags |= ws_aiflag_map[i][1];
3356 winflags &= ~ws_aiflag_map[i][0];
3359 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
3363 static int convert_niflag_w2u(int winflags) {
3364 int i, unixflags = 0;
3366 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
3367 if (ws_niflag_map[i][0] & winflags) {
3368 unixflags |= ws_niflag_map[i][1];
3369 winflags &= ~ws_niflag_map[i][0];
3372 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
3376 static int convert_aiflag_u2w(int unixflags) {
3377 int i, winflags = 0;
3379 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3380 if (ws_aiflag_map[i][1] & unixflags) {
3381 winflags |= ws_aiflag_map[i][0];
3382 unixflags &= ~ws_aiflag_map[i][1];
3384 if (unixflags) /* will warn usually */
3385 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
3389 static int convert_eai_u2w(int unixret) {
3392 for (i=0;ws_eai_map[i][0];i++)
3393 if (ws_eai_map[i][1] == unixret)
3394 return ws_eai_map[i][0];
3398 /***********************************************************************
3399 * getaddrinfo (WS2_32.@)
3401 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
3403 #ifdef HAVE_GETADDRINFO
3404 struct addrinfo *unixaires = NULL;
3406 struct addrinfo unixhints, *punixhints = NULL;
3407 CHAR *node = NULL, *serv = NULL;
3410 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
3413 if (!(serv = strdup_lower(servname))) {
3414 HeapFree(GetProcessHeap(), 0, node);
3415 return WSA_NOT_ENOUGH_MEMORY;
3420 punixhints = &unixhints;
3422 memset(&unixhints, 0, sizeof(unixhints));
3423 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
3424 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
3425 punixhints->ai_family = 0;
3427 punixhints->ai_family = convert_af_w2u(hints->ai_family);
3428 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
3429 punixhints->ai_socktype = 0;
3431 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
3432 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
3433 punixhints->ai_protocol = 0;
3435 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
3438 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
3439 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
3441 TRACE("%s, %s %p -> %p %d\n", nodename, servname, hints, res, result);
3443 HeapFree(GetProcessHeap(), 0, node);
3444 HeapFree(GetProcessHeap(), 0, serv);
3447 struct addrinfo *xuai = unixaires;
3448 struct WS_addrinfo **xai = res;
3452 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
3458 *xai = ai;xai = &ai->ai_next;
3459 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
3460 ai->ai_family = convert_af_u2w(xuai->ai_family);
3461 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
3462 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
3463 if (xuai->ai_canonname) {
3464 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
3465 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
3466 if (!ai->ai_canonname)
3468 strcpy(ai->ai_canonname,xuai->ai_canonname);
3470 len = xuai->ai_addrlen;
3471 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
3474 ai->ai_addrlen = len;
3476 int winlen = ai->ai_addrlen;
3478 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
3479 ai->ai_addrlen = winlen;
3483 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
3486 ai->ai_addrlen = len;
3488 xuai = xuai->ai_next;
3490 freeaddrinfo(unixaires);
3492 result = convert_eai_u2w(result);
3498 if (*res) WS_freeaddrinfo(*res);
3499 if (unixaires) freeaddrinfo(unixaires);
3501 return WSA_NOT_ENOUGH_MEMORY;
3503 FIXME("getaddrinfo() failed, not found during buildtime.\n");
3508 /***********************************************************************
3509 * GetAddrInfoW (WS2_32.@)
3511 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
3513 FIXME("empty stub!\n");
3517 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
3518 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
3520 #ifdef HAVE_GETNAMEINFO
3522 union generic_unix_sockaddr sa_u;
3525 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
3526 serv, servlen, flags);
3528 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
3531 WSASetLastError(WSAEFAULT);
3532 return WSA_NOT_ENOUGH_MEMORY;
3534 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
3535 return convert_eai_u2w(ret);
3537 FIXME("getnameinfo() failed, not found during buildtime.\n");
3542 /***********************************************************************
3543 * getservbyport (WS2_32.56)
3545 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
3547 struct WS_servent* retval = NULL;
3548 #ifdef HAVE_GETSERVBYPORT
3549 struct servent* serv;
3550 char *proto_str = NULL;
3552 if (proto && *proto)
3554 if (!(proto_str = strdup_lower(proto))) return NULL;
3556 EnterCriticalSection( &csWSgetXXXbyYYY );
3557 if( (serv = getservbyport(port, proto_str)) != NULL ) {
3558 retval = WS_dup_se(serv);
3560 else SetLastError(WSANO_DATA);
3561 LeaveCriticalSection( &csWSgetXXXbyYYY );
3562 HeapFree( GetProcessHeap(), 0, proto_str );
3564 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
3569 /***********************************************************************
3570 * gethostname (WS2_32.57)
3572 int WINAPI WS_gethostname(char *name, int namelen)
3574 TRACE("name %p, len %d\n", name, namelen);
3576 if (gethostname(name, namelen) == 0)
3578 TRACE("<- '%s'\n", name);
3581 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
3582 TRACE("<- ERROR !\n");
3583 return SOCKET_ERROR;
3587 /* ------------------------------------- Windows sockets extensions -- *
3589 * ------------------------------------------------------------------- */
3591 /***********************************************************************
3592 * WSAEnumNetworkEvents (WS2_32.36)
3594 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
3598 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
3600 SERVER_START_REQ( get_socket_event )
3602 req->handle = SOCKET2HANDLE(s);
3603 req->service = TRUE;
3604 req->c_event = hEvent;
3605 wine_server_set_reply( req, lpEvent->iErrorCode, sizeof(lpEvent->iErrorCode) );
3606 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
3610 SetLastError(WSAEINVAL);
3611 return SOCKET_ERROR;
3614 /***********************************************************************
3615 * WSAEventSelect (WS2_32.39)
3617 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
3621 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
3623 SERVER_START_REQ( set_socket_event )
3625 req->handle = SOCKET2HANDLE(s);
3627 req->event = hEvent;
3630 ret = wine_server_call( req );
3634 SetLastError(WSAEINVAL);
3635 return SOCKET_ERROR;
3638 /**********************************************************************
3639 * WSAGetOverlappedResult (WS2_32.40)
3641 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
3642 LPDWORD lpcbTransfer, BOOL fWait,
3647 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
3648 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
3650 if ( lpOverlapped == NULL )
3652 ERR( "Invalid pointer\n" );
3653 WSASetLastError(WSA_INVALID_PARAMETER);
3657 status = lpOverlapped->Internal;
3658 if (status == STATUS_PENDING)
3662 SetLastError( WSA_IO_INCOMPLETE );
3666 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
3667 INFINITE ) == WAIT_FAILED)
3669 status = lpOverlapped->Internal;
3673 *lpcbTransfer = lpOverlapped->InternalHigh;
3676 *lpdwFlags = lpOverlapped->u.s.Offset;
3678 if (status) SetLastError( RtlNtStatusToDosError(status) );
3683 /***********************************************************************
3684 * WSAAsyncSelect (WS2_32.101)
3686 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
3690 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
3692 SERVER_START_REQ( set_socket_event )
3694 req->handle = SOCKET2HANDLE(s);
3699 ret = wine_server_call( req );
3703 SetLastError(WSAEINVAL);
3704 return SOCKET_ERROR;
3707 /***********************************************************************
3708 * WSACreateEvent (WS2_32.31)
3711 WSAEVENT WINAPI WSACreateEvent(void)
3713 /* Create a manual-reset event, with initial state: unsignaled */
3716 return CreateEventW(NULL, TRUE, FALSE, NULL);
3719 /***********************************************************************
3720 * WSACloseEvent (WS2_32.29)
3723 BOOL WINAPI WSACloseEvent(WSAEVENT event)
3725 TRACE ("event=%p\n", event);
3727 return CloseHandle(event);
3730 /***********************************************************************
3731 * WSASocketA (WS2_32.78)
3734 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
3735 LPWSAPROTOCOL_INFOA lpProtocolInfo,
3736 GROUP g, DWORD dwFlags)
3739 WSAPROTOCOL_INFOW info;
3741 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
3742 af, type, protocol, lpProtocolInfo, g, dwFlags);
3744 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
3746 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
3747 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
3748 info.szProtocol, WSAPROTOCOL_LEN + 1);
3752 WSASetLastError( WSAEINVAL);
3753 return SOCKET_ERROR;
3756 return WSASocketW(af, type, protocol, &info, g, dwFlags);
3759 /***********************************************************************
3760 * WSASocketW (WS2_32.79)
3763 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
3764 LPWSAPROTOCOL_INFOW lpProtocolInfo,
3765 GROUP g, DWORD dwFlags)
3770 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
3771 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
3774 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
3775 af, type, protocol, lpProtocolInfo, g, dwFlags );
3777 /* hack for WSADuplicateSocket */
3778 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
3779 ret = lpProtocolInfo->dwCatalogEntryId;
3780 TRACE("\tgot duplicate %04lx\n", ret);
3784 /* check and convert the socket family */
3785 af = convert_af_w2u(af);
3788 FIXME("Unsupported socket family %d!\n", af);
3789 SetLastError(WSAEAFNOSUPPORT);
3790 return INVALID_SOCKET;
3793 /* check the socket type */
3794 type = convert_socktype_w2u(type);
3797 SetLastError(WSAESOCKTNOSUPPORT);
3798 return INVALID_SOCKET;
3801 /* check the protocol type */
3802 if ( protocol < 0 ) /* don't support negative values */
3804 SetLastError(WSAEPROTONOSUPPORT);
3805 return INVALID_SOCKET;
3808 if ( af == AF_UNSPEC) /* did they not specify the address family? */
3812 if (type == SOCK_STREAM) { af = AF_INET; break; }
3814 if (type == SOCK_DGRAM) { af = AF_INET; break; }
3815 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
3818 SERVER_START_REQ( create_socket )
3822 req->protocol = protocol;
3823 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
3824 req->attributes = OBJ_INHERIT;
3825 req->flags = dwFlags;
3826 set_error( wine_server_call( req ) );
3827 ret = HANDLE2SOCKET( reply->handle );
3832 TRACE("\tcreated %04lx\n", ret );
3836 if (GetLastError() == WSAEACCES) /* raw socket denied */
3838 if (type == SOCK_RAW)
3839 MESSAGE("WARNING: Trying to create a socket of type SOCK_RAW, this"
3840 " will fail unless you have special permissions.\n");
3842 MESSAGE("WS_SOCKET: Failed to create socket, this requires"
3843 " special permissions.\n");
3844 SetLastError(WSAESOCKTNOSUPPORT);
3847 WARN("\t\tfailed!\n");
3848 return INVALID_SOCKET;
3851 /***********************************************************************
3852 * WSAJoinLeaf (WS2_32.58)
3855 SOCKET WINAPI WSAJoinLeaf(
3857 const struct WS_sockaddr *addr,
3859 LPWSABUF lpCallerData,
3860 LPWSABUF lpCalleeData,
3866 return INVALID_SOCKET;
3869 /***********************************************************************
3870 * __WSAFDIsSet (WS2_32.151)
3872 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
3874 int i = set->fd_count;
3876 TRACE("(%ld,%p(%i))\n", s, set, i);
3879 if (set->fd_array[i] == s) return 1;
3883 /***********************************************************************
3884 * WSAIsBlocking (WINSOCK.114)
3885 * WSAIsBlocking (WS2_32.114)
3887 BOOL WINAPI WSAIsBlocking(void)
3889 /* By default WinSock should set all its sockets to non-blocking mode
3890 * and poll in PeekMessage loop when processing "blocking" ones. This
3891 * function is supposed to tell if the program is in this loop. Our
3892 * blocking calls are truly blocking so we always return FALSE.
3894 * Note: It is allowed to call this function without prior WSAStartup().
3901 /***********************************************************************
3902 * WSACancelBlockingCall (WINSOCK.113)
3903 * WSACancelBlockingCall (WS2_32.113)
3905 INT WINAPI WSACancelBlockingCall(void)
3911 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
3913 FIXME("How was this called?\n");
3918 /***********************************************************************
3919 * WSASetBlockingHook (WS2_32.109)
3921 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
3923 FARPROC prev = blocking_hook;
3924 blocking_hook = lpBlockFunc;
3925 TRACE("hook %p\n", lpBlockFunc);
3930 /***********************************************************************
3931 * WSAUnhookBlockingHook (WS2_32.110)
3933 INT WINAPI WSAUnhookBlockingHook(void)
3935 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
3940 /* ----------------------------------- end of API stuff */
3942 /* ----------------------------------- helper functions -
3944 * TODO: Merge WS_dup_..() stuff into one function that
3945 * would operate with a generic structure containing internal
3946 * pointers (via a template of some kind).
3949 static int list_size(char** l, int item_size)
3954 j += (item_size) ? item_size : strlen(l[i]) + 1;
3955 j += (i + 1) * sizeof(char*); }
3959 static int list_dup(char** l_src, char** l_to, int item_size)
3964 for (i = 0; l_src[i]; i++) ;
3965 p = (char *)(l_to + i + 1);
3966 for (i = 0; l_src[i]; i++)
3968 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
3969 memcpy(p, l_src[i], count);
3974 return p - (char *)l_to;
3979 /* duplicate hostent entry
3980 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
3981 * Ditto for protoent and servent.
3983 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
3986 struct WS_hostent *p_to;
3988 int size = (sizeof(*p_he) +
3989 strlen(p_he->h_name) + 1 +
3990 list_size(p_he->h_aliases, 0) +
3991 list_size(p_he->h_addr_list, p_he->h_length));
3993 if (!(p_to = check_buffer_he(size))) return NULL;
3994 p_to->h_addrtype = p_he->h_addrtype;
3995 p_to->h_length = p_he->h_length;
3997 p = (char *)(p_to + 1);
3999 strcpy(p, p_he->h_name);
4002 p_to->h_aliases = (char **)p;
4003 p += list_dup(p_he->h_aliases, p_to->h_aliases, 0);
4005 p_to->h_addr_list = (char **)p;
4006 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
4010 /* ----- protoent */
4012 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
4015 struct WS_protoent *p_to;
4017 int size = (sizeof(*p_pe) +
4018 strlen(p_pe->p_name) + 1 +
4019 list_size(p_pe->p_aliases, 0));
4021 if (!(p_to = check_buffer_pe(size))) return NULL;
4022 p_to->p_proto = p_pe->p_proto;
4024 p = (char *)(p_to + 1);
4026 strcpy(p, p_pe->p_name);
4029 p_to->p_aliases = (char **)p;
4030 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
4036 static struct WS_servent *WS_dup_se(const struct servent* p_se)
4039 struct WS_servent *p_to;
4041 int size = (sizeof(*p_se) +
4042 strlen(p_se->s_proto) + 1 +
4043 strlen(p_se->s_name) + 1 +
4044 list_size(p_se->s_aliases, 0));
4046 if (!(p_to = check_buffer_se(size))) return NULL;
4047 p_to->s_port = p_se->s_port;
4049 p = (char *)(p_to + 1);
4051 strcpy(p, p_se->s_name);
4055 strcpy(p, p_se->s_proto);
4058 p_to->s_aliases = (char **)p;
4059 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
4063 /* ----------------------------------- error handling */
4067 int loc_errno = errno;
4068 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
4072 case EINTR: return WSAEINTR;
4073 case EBADF: return WSAEBADF;
4075 case EACCES: return WSAEACCES;
4076 case EFAULT: return WSAEFAULT;
4077 case EINVAL: return WSAEINVAL;
4078 case EMFILE: return WSAEMFILE;
4079 case EWOULDBLOCK: return WSAEWOULDBLOCK;
4080 case EINPROGRESS: return WSAEINPROGRESS;
4081 case EALREADY: return WSAEALREADY;
4082 case ENOTSOCK: return WSAENOTSOCK;
4083 case EDESTADDRREQ: return WSAEDESTADDRREQ;
4084 case EMSGSIZE: return WSAEMSGSIZE;
4085 case EPROTOTYPE: return WSAEPROTOTYPE;
4086 case ENOPROTOOPT: return WSAENOPROTOOPT;
4087 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
4088 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
4089 case EOPNOTSUPP: return WSAEOPNOTSUPP;
4090 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
4091 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
4092 case EADDRINUSE: return WSAEADDRINUSE;
4093 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
4094 case ENETDOWN: return WSAENETDOWN;
4095 case ENETUNREACH: return WSAENETUNREACH;
4096 case ENETRESET: return WSAENETRESET;
4097 case ECONNABORTED: return WSAECONNABORTED;
4099 case ECONNRESET: return WSAECONNRESET;
4100 case ENOBUFS: return WSAENOBUFS;
4101 case EISCONN: return WSAEISCONN;
4102 case ENOTCONN: return WSAENOTCONN;
4103 case ESHUTDOWN: return WSAESHUTDOWN;
4104 case ETOOMANYREFS: return WSAETOOMANYREFS;
4105 case ETIMEDOUT: return WSAETIMEDOUT;
4106 case ECONNREFUSED: return WSAECONNREFUSED;
4107 case ELOOP: return WSAELOOP;
4108 case ENAMETOOLONG: return WSAENAMETOOLONG;
4109 case EHOSTDOWN: return WSAEHOSTDOWN;
4110 case EHOSTUNREACH: return WSAEHOSTUNREACH;
4111 case ENOTEMPTY: return WSAENOTEMPTY;
4113 case EPROCLIM: return WSAEPROCLIM;
4116 case EUSERS: return WSAEUSERS;
4119 case EDQUOT: return WSAEDQUOT;
4122 case ESTALE: return WSAESTALE;
4125 case EREMOTE: return WSAEREMOTE;
4128 /* just in case we ever get here and there are no problems */
4131 WARN("Unknown errno %d!\n", loc_errno);
4132 return WSAEOPNOTSUPP;
4136 UINT wsaHerrno(int loc_errno)
4139 WARN("h_errno %d.\n", loc_errno);
4143 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
4144 case TRY_AGAIN: return WSATRY_AGAIN;
4145 case NO_RECOVERY: return WSANO_RECOVERY;
4146 case NO_DATA: return WSANO_DATA;
4147 case ENOBUFS: return WSAENOBUFS;
4151 WARN("Unknown h_errno %d!\n", loc_errno);
4152 return WSAEOPNOTSUPP;
4157 /***********************************************************************
4158 * WSARecv (WS2_32.67)
4160 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4161 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
4162 LPWSAOVERLAPPED lpOverlapped,
4163 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
4165 return WSARecvFrom(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
4166 NULL, NULL, lpOverlapped, lpCompletionRoutine);
4169 /***********************************************************************
4170 * WSARecvFrom (WS2_32.69)
4172 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4173 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
4174 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
4175 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4178 unsigned int i, options;
4180 DWORD timeout_start = GetTickCount();
4181 struct iovec iovec[WS_MSG_MAXIOVLEN];
4182 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4184 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
4185 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
4186 (lpFromlen ? *lpFromlen : -1),
4187 lpOverlapped, lpCompletionRoutine);
4189 if (dwBufferCount > WS_MSG_MAXIOVLEN)
4191 WSASetLastError( WSAEINVAL );
4192 return SOCKET_ERROR;
4195 fd = get_sock_fd( s, FILE_READ_DATA, &options );
4196 TRACE( "fd=%d, options=%x\n", fd, options );
4198 if (fd == -1) return SOCKET_ERROR;
4200 for (i = 0; i < dwBufferCount; i++)
4202 iovec[i].iov_base = lpBuffers[i].buf;
4203 iovec[i].iov_len = lpBuffers[i].len;
4208 n = WS2_recv( fd, iovec, dwBufferCount, lpFrom, lpFromlen, lpFlags );
4211 if (errno == EINTR) continue;
4212 if (errno != EAGAIN)
4215 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
4220 *lpNumberOfBytesRecvd = n;
4222 if ((lpOverlapped || lpCompletionRoutine) &&
4223 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4225 IO_STATUS_BLOCK *iosb;
4226 struct ws2_async *wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
4233 release_sock_fd( s, fd );
4235 wsa->hSocket = SOCKET2HANDLE(s);
4236 wsa->flags = *lpFlags;
4238 wsa->addrlen.ptr = lpFromlen;
4239 wsa->user_overlapped = lpOverlapped;
4240 wsa->completion_func = lpCompletionRoutine;
4241 wsa->n_iovecs = dwBufferCount;
4242 memcpy( wsa->iovec, iovec, dwBufferCount * sizeof(*iovec) );
4244 iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4248 iosb->u.Status = STATUS_PENDING;
4249 iosb->Information = 0;
4251 SERVER_START_REQ( register_async )
4253 req->handle = wsa->hSocket;
4254 req->type = ASYNC_TYPE_READ;
4255 req->async.callback = WS2_async_recv;
4256 req->async.iosb = iosb;
4257 req->async.arg = wsa;
4258 req->async.apc = ws2_async_apc;
4259 req->async.event = lpCompletionRoutine ? 0 : lpOverlapped->hEvent;
4260 req->async.cvalue = cvalue;
4261 err = wine_server_call( req );
4265 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4266 WSASetLastError( NtStatusToWSAError( err ));
4267 return SOCKET_ERROR;
4270 iosb->u.Status = STATUS_SUCCESS;
4271 iosb->Information = n;
4272 if (!wsa->completion_func)
4274 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4275 SetEvent( lpOverlapped->hEvent );
4276 HeapFree( GetProcessHeap(), 0, wsa );
4278 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4279 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4280 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4286 if ( _is_blocking(s) )
4289 int timeout = GET_RCVTIMEO(fd);
4292 timeout -= GetTickCount() - timeout_start;
4293 if (timeout < 0) timeout = 0;
4297 pfd.events = POLLIN;
4298 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
4300 if (!timeout || !poll( &pfd, 1, timeout ))
4303 /* a timeout is not fatal */
4304 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4310 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4311 err = WSAEWOULDBLOCK;
4316 TRACE(" -> %i bytes\n", n);
4317 release_sock_fd( s, fd );
4318 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4323 release_sock_fd( s, fd );
4324 WARN(" -> ERROR %d\n", err);
4325 WSASetLastError( err );
4326 return SOCKET_ERROR;
4329 /***********************************************************************
4330 * WSCInstallProvider (WS2_32.88)
4332 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
4333 LPCWSTR lpszProviderDllPath,
4334 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
4335 DWORD dwNumberOfEntries,
4338 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
4339 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
4340 dwNumberOfEntries, lpErrno);
4346 /***********************************************************************
4347 * WSCDeinstallProvider (WS2_32.83)
4349 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
4351 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
4357 /***********************************************************************
4358 * WSAAccept (WS2_32.26)
4360 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
4361 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
4364 int ret = 0, size = 0;
4365 WSABUF CallerId, CallerData, CalleeId, CalleeData;
4366 /* QOS SQOS, GQOS; */
4369 SOCKADDR src_addr, dst_addr;
4371 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %d\n",
4372 s, addr, addrlen, lpfnCondition, dwCallbackData);
4375 size = sizeof(src_addr);
4376 cs = WS_accept(s, &src_addr, &size);
4378 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
4380 CallerId.buf = (char *)&src_addr;
4381 CallerId.len = sizeof(src_addr);
4383 CallerData.buf = NULL;
4384 CallerData.len = (ULONG)NULL;
4386 WS_getsockname(cs, &dst_addr, &size);
4388 CalleeId.buf = (char *)&dst_addr;
4389 CalleeId.len = sizeof(dst_addr);
4392 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
4393 &CalleeId, &CalleeData, &g, dwCallbackData);
4398 if (addr && addrlen)
4399 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
4402 SERVER_START_REQ( set_socket_deferred )
4404 req->handle = SOCKET2HANDLE(s);
4405 req->deferred = SOCKET2HANDLE(cs);
4406 if ( !wine_server_call_err ( req ) )
4408 SetLastError( WSATRY_AGAIN );
4409 WS_closesocket( cs );
4413 return SOCKET_ERROR;
4416 SetLastError(WSAECONNREFUSED);
4417 return SOCKET_ERROR;
4419 FIXME("Unknown return type from Condition function\n");
4420 SetLastError(WSAENOTSOCK);
4421 return SOCKET_ERROR;
4425 /***********************************************************************
4426 * WSADuplicateSocketA (WS2_32.32)
4428 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
4432 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4433 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4434 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
4435 /* I don't know what the real Windoze does next, this is a hack */
4436 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
4437 * the target use the global duplicate, or we could copy a reference to us to the structure
4438 * and let the target duplicate it from us, but let's do it as simple as possible */
4439 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4440 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4441 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4442 0, FALSE, DUPLICATE_SAME_ACCESS);
4443 CloseHandle(hProcess);
4444 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4448 /***********************************************************************
4449 * WSADuplicateSocketW (WS2_32.33)
4451 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
4455 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4457 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4458 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4459 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4460 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4461 0, FALSE, DUPLICATE_SAME_ACCESS);
4462 CloseHandle(hProcess);
4463 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4467 /***********************************************************************
4468 * WSAInstallServiceClassA (WS2_32.48)
4470 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
4472 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
4473 WSASetLastError(WSAEACCES);
4474 return SOCKET_ERROR;
4477 /***********************************************************************
4478 * WSAInstallServiceClassW (WS2_32.49)
4480 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
4482 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
4483 WSASetLastError(WSAEACCES);
4484 return SOCKET_ERROR;
4487 /***********************************************************************
4488 * WSARemoveServiceClass (WS2_32.70)
4490 int WINAPI WSARemoveServiceClass(LPGUID info)
4492 FIXME("Request to remove service %p\n",info);
4493 WSASetLastError(WSATYPE_NOT_FOUND);
4494 return SOCKET_ERROR;
4497 /***********************************************************************
4498 * WSAStringToAddressA (WS2_32.80)
4500 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
4502 LPWSAPROTOCOL_INFOA lpProtocolInfo,
4503 LPSOCKADDR lpAddress,
4504 LPINT lpAddressLength)
4507 LPSTR workBuffer=NULL,ptrPort;
4509 TRACE( "(%s, %x, %p, %p, %p)\n", AddressString, AddressFamily, lpProtocolInfo,
4510 lpAddress, lpAddressLength );
4512 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
4516 WSASetLastError(WSAEINVAL);
4517 return SOCKET_ERROR;
4521 FIXME("ProtocolInfo not implemented.\n");
4523 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
4524 strlen(AddressString) + 1);
4527 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4528 return SOCKET_ERROR;
4531 strcpy(workBuffer, AddressString);
4533 switch(AddressFamily)
4537 struct in_addr inetaddr;
4539 /* If lpAddressLength is too small, tell caller the size we need */
4540 if (*lpAddressLength < sizeof(SOCKADDR_IN))
4542 *lpAddressLength = sizeof(SOCKADDR_IN);
4546 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
4548 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
4550 ptrPort = strchr(workBuffer, ':');
4553 ((LPSOCKADDR_IN)lpAddress)->sin_port = (WS_u_short)atoi(ptrPort+1);
4558 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
4561 if(inet_aton(workBuffer, &inetaddr) > 0)
4563 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
4574 struct in6_addr inetaddr;
4575 /* If lpAddressLength is too small, tell caller the size we need */
4576 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
4578 *lpAddressLength = sizeof(SOCKADDR_IN6);
4582 #ifdef HAVE_INET_PTON
4583 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
4585 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
4587 /* This one is a bit tricky. An IPv6 address contains colons, so the
4588 * check from IPv4 doesn't work like that. However, IPv6 addresses that
4589 * contain a port are written with braces like [fd12:3456:7890::1]:12345
4590 * so what we will do is to look for ']', check if the next char is a
4591 * colon, and if it is, parse the port as in IPv4. */
4593 ptrPort = strchr(workBuffer, ']');
4594 if(ptrPort && *(++ptrPort) == ':')
4596 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = (WS_u_short)atoi(ptrPort+1);
4601 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
4604 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
4606 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
4607 sizeof(struct in6_addr));
4611 #endif /* HAVE_INET_PTON */
4617 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
4618 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
4622 HeapFree(GetProcessHeap(), 0, workBuffer);
4625 WSASetLastError(res);
4626 return SOCKET_ERROR;
4629 /***********************************************************************
4630 * WSAStringToAddressW (WS2_32.81)
4632 * Does anybody know if this functions allows to use hebrew/arabic/chinese... digits?
4633 * If this should be the case, it would be required to map these digits
4634 * to Unicode digits (0-9) using FoldString first.
4636 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
4638 LPWSAPROTOCOL_INFOW lpProtocolInfo,
4639 LPSOCKADDR lpAddress,
4640 LPINT lpAddressLength)
4643 LPSTR workBuffer=NULL;
4644 WSAPROTOCOL_INFOA infoA;
4645 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
4647 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
4648 lpAddress, lpAddressLength );
4650 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
4652 /* if ProtocolInfo is available - convert to ANSI variant */
4655 lpProtoInfoA = &infoA;
4656 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
4658 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
4659 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
4661 WSASetLastError( WSAEINVAL);
4662 return SOCKET_ERROR;
4668 /* Translate AddressString to ANSI code page - assumes that only
4669 standard digits 0-9 are used with this API call */
4670 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
4671 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
4675 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
4676 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
4677 lpAddress,lpAddressLength);
4678 HeapFree( GetProcessHeap(), 0, workBuffer );
4682 res = WSA_NOT_ENOUGH_MEMORY;
4687 WSASetLastError(res);
4688 return SOCKET_ERROR;
4691 /***********************************************************************
4692 * WSAAddressToStringA (WS2_32.27)
4694 * See WSAAddressToStringW
4696 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
4697 LPWSAPROTOCOL_INFOA info, LPSTR string,
4701 CHAR buffer[22]; /* 12 digits + 3 dots + ':' + 5 digits + '\0' */
4704 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
4706 if (!sockaddr || len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
4707 if (!string || !lenstr) return SOCKET_ERROR;
4709 /* sin_family is guaranteed to be the first u_short */
4710 if (((SOCKADDR_IN *)sockaddr)->sin_family != AF_INET) return SOCKET_ERROR;
4712 sprintf( buffer, "%u.%u.%u.%u:%u",
4713 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
4714 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
4715 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
4716 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
4717 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
4719 p = strchr( buffer, ':' );
4720 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
4722 size = strlen( buffer );
4727 WSASetLastError(WSAEFAULT);
4728 return SOCKET_ERROR;
4731 strcpy( string, buffer );
4735 /***********************************************************************
4736 * WSAAddressToStringW (WS2_32.28)
4738 * Convert a sockaddr address into a readable address string.
4741 * sockaddr [I] Pointer to a sockaddr structure.
4742 * len [I] Size of the sockaddr structure.
4743 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
4744 * string [I/O] Pointer to a buffer to receive the address string.
4745 * lenstr [I/O] Size of the receive buffer in WCHARs.
4749 * Failure: SOCKET_ERROR
4752 * The 'info' parameter is ignored.
4755 * Only supports AF_INET addresses.
4757 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
4758 LPWSAPROTOCOL_INFOW info, LPWSTR string,
4762 WCHAR buffer[22]; /* 12 digits + 3 dots + ':' + 5 digits + '\0' */
4763 static const WCHAR format[] = { '%','u','.','%','u','.','%','u','.','%','u',':','%','u',0 };
4766 TRACE( "(%p, %x, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
4768 if (!sockaddr || len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
4769 if (!string || !lenstr) return SOCKET_ERROR;
4771 /* sin_family is guaranteed to be the first u_short */
4772 if (((SOCKADDR_IN *)sockaddr)->sin_family != AF_INET) return SOCKET_ERROR;
4774 sprintfW( buffer, format,
4775 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
4776 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
4777 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
4778 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
4779 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
4781 p = strchrW( buffer, ':' );
4782 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
4784 size = lstrlenW( buffer );
4789 return SOCKET_ERROR;
4792 lstrcpyW( string, buffer );
4796 /***********************************************************************
4797 * WSAEnumNameSpaceProvidersA (WS2_32.34)
4799 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
4801 FIXME( "(%p %p) Stub!\n", len, buffer );
4805 /***********************************************************************
4806 * WSAEnumNameSpaceProvidersW (WS2_32.35)
4808 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
4810 FIXME( "(%p %p) Stub!\n", len, buffer );
4814 /***********************************************************************
4815 * WSAGetQOSByName (WS2_32.41)
4817 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
4819 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
4823 /***********************************************************************
4824 * WSAGetServiceClassInfoA (WS2_32.42)
4826 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
4827 LPWSASERVICECLASSINFOA info )
4829 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
4831 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4832 return SOCKET_ERROR;
4835 /***********************************************************************
4836 * WSAGetServiceClassInfoW (WS2_32.43)
4838 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
4839 LPWSASERVICECLASSINFOW info )
4841 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
4843 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4844 return SOCKET_ERROR;
4847 /***********************************************************************
4848 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
4850 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
4852 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
4853 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4854 return SOCKET_ERROR;
4857 /***********************************************************************
4858 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
4860 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
4862 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
4863 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4864 return SOCKET_ERROR;
4867 /***********************************************************************
4868 * WSALookupServiceBeginA (WS2_32.59)
4870 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
4871 DWORD dwControlFlags,
4874 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
4876 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4877 return SOCKET_ERROR;
4880 /***********************************************************************
4881 * WSALookupServiceBeginW (WS2_32.60)
4883 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
4884 DWORD dwControlFlags,
4887 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
4889 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4890 return SOCKET_ERROR;
4893 /***********************************************************************
4894 * WSALookupServiceBeginW (WS2_32.61)
4896 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
4898 FIXME("(%p) Stub!\n", lookup );
4902 /***********************************************************************
4903 * WSALookupServiceNextA (WS2_32.62)
4905 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
4907 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
4911 /***********************************************************************
4912 * WSALookupServiceNextW (WS2_32.63)
4914 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
4916 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
4920 /***********************************************************************
4921 * WSANtohl (WS2_32.64)
4923 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
4925 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
4927 if (!lphostlong) return WSAEFAULT;
4929 *lphostlong = ntohl( netlong );
4933 /***********************************************************************
4934 * WSANtohs (WS2_32.65)
4936 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
4938 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
4940 if (!lphostshort) return WSAEFAULT;
4942 *lphostshort = ntohs( netshort );
4946 /***********************************************************************
4947 * WSAProviderConfigChange (WS2_32.66)
4949 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
4950 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4952 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
4953 return SOCKET_ERROR;
4956 /***********************************************************************
4957 * WSARecvDisconnect (WS2_32.68)
4959 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
4961 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
4963 return WS_shutdown( s, 0 );
4966 /***********************************************************************
4967 * WSASetServiceA (WS2_32.76)
4969 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
4971 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
4975 /***********************************************************************
4976 * WSASetServiceW (WS2_32.77)
4978 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
4980 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
4984 /***********************************************************************
4985 * WSCEnableNSProvider (WS2_32.84)
4987 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
4989 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
4993 /***********************************************************************
4994 * WSCGetProviderPath (WS2_32.86)
4996 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
4998 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
5000 if (!errcode || !provider || !len) return WSAEFAULT;
5002 *errcode = WSAEINVAL;
5003 return SOCKET_ERROR;
5006 /***********************************************************************
5007 * WSCInstallNameSpace (WS2_32.87)
5009 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
5010 DWORD version, LPGUID provider )
5012 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
5013 namespace, version, debugstr_guid(provider) );
5017 /***********************************************************************
5018 * WSCUnInstallNameSpace (WS2_32.89)
5020 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
5022 FIXME("(%p) Stub!\n", lpProviderId);
5026 /***********************************************************************
5027 * WSCWriteProviderOrder (WS2_32.91)
5029 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
5031 FIXME("(%p 0x%08x) Stub!\n", entry, number);