2 * based on Windows Sockets 1.1 specs
4 * Copyright (C) 1993,1994,1996,1997 John Brezak, Erik Bos, Alex Korobka.
5 * Copyright (C) 2005 Marcus Meissner
6 * Copyright (C) 2006-2008 Kai Blin
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 * NOTE: If you make any changes to fix a particular app, make sure
23 * they don't break something else like Netscape or telnet and ftp
24 * clients and servers (www.winsite.com got a lot of those).
28 #include "wine/port.h"
33 #include <sys/types.h>
37 #ifdef HAVE_SYS_IOCTL_H
38 # include <sys/ioctl.h>
40 #ifdef HAVE_SYS_FILIO_H
41 # include <sys/filio.h>
43 #ifdef HAVE_SYS_SOCKIO_H
44 # include <sys/sockio.h>
48 # include <sys/so_ioctl.h>
51 #ifdef HAVE_SYS_PARAM_H
52 # include <sys/param.h>
58 #ifdef HAVE_SYS_WAIT_H
59 # include <sys/wait.h>
64 #ifdef HAVE_SYS_SOCKET_H
65 #include <sys/socket.h>
67 #ifdef HAVE_NETINET_IN_H
68 # include <netinet/in.h>
70 #ifdef HAVE_NETINET_TCP_H
71 # include <netinet/tcp.h>
73 #ifdef HAVE_ARPA_INET_H
74 # include <arpa/inet.h>
79 #ifdef HAVE_SYS_ERRNO_H
80 #include <sys/errno.h>
89 #ifdef HAVE_ARPA_NAMESER_H
90 # include <arpa/nameser.h>
99 #ifdef HAVE_NETIPX_IPX_H
100 # include <netipx/ipx.h>
102 #elif defined(HAVE_LINUX_IPX_H)
103 # ifdef HAVE_ASM_TYPES_H
104 # include <asm/types.h>
106 # include <linux/ipx.h>
113 #ifdef HAVE_SYS_POLL_H
114 # include <sys/poll.h>
116 #ifdef HAVE_SYS_TIME_H
117 # include <sys/time.h>
120 #define NONAMELESSUNION
121 #define NONAMELESSSTRUCT
122 #include "ntstatus.h"
123 #define WIN32_NO_STATUS
128 #include "winerror.h"
130 #include "winsock2.h"
132 #include "ws2tcpip.h"
136 #include "iphlpapi.h"
137 #include "wine/server.h"
138 #include "wine/debug.h"
139 #include "wine/unicode.h"
142 # include "wsnwlink.h"
146 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
147 # define sipx_network sipx_addr.x_net
148 # define sipx_node sipx_addr.x_host.c_host
149 #endif /* __FreeBSD__ */
152 #define INADDR_NONE ~0UL
155 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
157 /* critical section to protect some non-reentrant net function */
158 extern CRITICAL_SECTION csWSgetXXXbyYYY;
160 union generic_unix_sockaddr
162 struct sockaddr addr;
163 char data[128]; /* should be big enough for all families */
166 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
168 if (!a) return "(nil)";
169 return wine_dbg_sprintf("{ family %d, address %s, port %d }",
170 ((const struct sockaddr_in *)a)->sin_family,
171 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
172 ntohs(((const struct sockaddr_in *)a)->sin_port));
175 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
176 #define SOCKET2HANDLE(s) ((HANDLE)(s))
177 #define HANDLE2SOCKET(h) ((SOCKET)(h))
179 /****************************************************************
180 * Async IO declarations
181 ****************************************************************/
183 typedef struct ws2_async
187 LPWSAOVERLAPPED user_overlapped;
188 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
189 IO_STATUS_BLOCK local_iosb;
190 struct iovec iovec[WS_MSG_MAXIOVLEN];
192 struct WS_sockaddr *addr;
195 int val; /* for send operations */
196 int *ptr; /* for recv operations */
201 /****************************************************************/
203 /* ----------------------------------- internal data */
205 /* ws_... struct conversion flags */
207 typedef struct /* WSAAsyncSelect() control struct */
209 HANDLE service, event, sock;
215 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
216 #define WS_MAX_UDP_DATAGRAM 1024
217 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
219 /* hostent's, servent's and protent's are stored in one buffer per thread,
220 * as documented on MSDN for the functions that return any of the buffers */
221 struct per_thread_data
224 struct WS_hostent *he_buffer;
225 struct WS_servent *se_buffer;
226 struct WS_protoent *pe_buffer;
232 static INT num_startup; /* reference counter */
233 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
235 /* function prototypes */
236 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
237 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
238 static struct WS_servent *WS_dup_se(const struct servent* p_se);
240 int WSAIOCTL_GetInterfaceCount(void);
241 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
244 UINT wsaHerrno(int errnr);
246 #define MAP_OPTION(opt) { WS_##opt, opt }
248 static const int ws_sock_map[][2] =
250 MAP_OPTION( SO_DEBUG ),
251 MAP_OPTION( SO_ACCEPTCONN ),
252 MAP_OPTION( SO_REUSEADDR ),
253 MAP_OPTION( SO_KEEPALIVE ),
254 MAP_OPTION( SO_DONTROUTE ),
255 MAP_OPTION( SO_BROADCAST ),
256 MAP_OPTION( SO_LINGER ),
257 MAP_OPTION( SO_OOBINLINE ),
258 MAP_OPTION( SO_SNDBUF ),
259 MAP_OPTION( SO_RCVBUF ),
260 MAP_OPTION( SO_ERROR ),
261 MAP_OPTION( SO_TYPE ),
263 MAP_OPTION( SO_RCVTIMEO ),
266 MAP_OPTION( SO_SNDTIMEO ),
270 static const int ws_tcp_map[][2] =
273 MAP_OPTION( TCP_NODELAY ),
277 static const int ws_ip_map[][2] =
279 MAP_OPTION( IP_MULTICAST_IF ),
280 MAP_OPTION( IP_MULTICAST_TTL ),
281 MAP_OPTION( IP_MULTICAST_LOOP ),
282 MAP_OPTION( IP_ADD_MEMBERSHIP ),
283 MAP_OPTION( IP_DROP_MEMBERSHIP ),
284 MAP_OPTION( IP_OPTIONS ),
286 MAP_OPTION( IP_HDRINCL ),
288 MAP_OPTION( IP_TOS ),
289 MAP_OPTION( IP_TTL ),
292 static const int ws_af_map[][2] =
294 MAP_OPTION( AF_UNSPEC ),
295 MAP_OPTION( AF_INET ),
296 MAP_OPTION( AF_INET6 ),
298 MAP_OPTION( AF_IPX ),
300 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
303 static const int ws_socktype_map[][2] =
305 MAP_OPTION( SOCK_DGRAM ),
306 MAP_OPTION( SOCK_STREAM ),
307 MAP_OPTION( SOCK_RAW ),
308 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
311 static const int ws_proto_map[][2] =
313 MAP_OPTION( IPPROTO_IP ),
314 MAP_OPTION( IPPROTO_TCP ),
315 MAP_OPTION( IPPROTO_UDP ),
316 MAP_OPTION( IPPROTO_ICMP ),
317 MAP_OPTION( IPPROTO_IGMP ),
318 MAP_OPTION( IPPROTO_RAW ),
319 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
322 static const int ws_aiflag_map[][2] =
324 MAP_OPTION( AI_PASSIVE ),
325 MAP_OPTION( AI_CANONNAME ),
326 MAP_OPTION( AI_NUMERICHOST ),
327 /* Linux/UNIX knows a lot more. But Windows only
328 * has 3 as far as I could see. -Marcus
332 static const int ws_niflag_map[][2] =
334 MAP_OPTION( NI_NOFQDN ),
335 MAP_OPTION( NI_NUMERICHOST ),
336 MAP_OPTION( NI_NAMEREQD ),
337 MAP_OPTION( NI_NUMERICSERV ),
338 MAP_OPTION( NI_DGRAM ),
341 static const int ws_eai_map[][2] =
343 MAP_OPTION( EAI_AGAIN ),
344 MAP_OPTION( EAI_BADFLAGS ),
345 MAP_OPTION( EAI_FAIL ),
346 MAP_OPTION( EAI_FAMILY ),
347 MAP_OPTION( EAI_MEMORY ),
348 /* Note: EAI_NODATA is deprecated, but still
349 * used by Windows and Linux... We map the newer
350 * EAI_NONAME to EAI_NODATA for now until Windows
354 MAP_OPTION( EAI_NODATA ),
357 { WS_EAI_NODATA, EAI_NONAME },
360 MAP_OPTION( EAI_SERVICE ),
361 MAP_OPTION( EAI_SOCKTYPE ),
365 static const char magic_loopback_addr[] = {127, 12, 34, 56};
367 static inline DWORD NtStatusToWSAError( const DWORD status )
369 /* We only need to cover the status codes set by server async request handling */
373 case STATUS_SUCCESS: wserr = 0; break;
374 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
375 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
376 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
377 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
378 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
379 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
380 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
381 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
383 if ( status >= WSABASEERR && status <= WSABASEERR+1004 )
384 /* It is not an NT status code but a winsock error */
388 wserr = RtlNtStatusToDosError( status );
389 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
395 /* set last error code from NT status without mapping WSA errors */
396 static inline unsigned int set_error( unsigned int err )
400 err = NtStatusToWSAError( err );
406 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
409 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
414 static inline void release_sock_fd( SOCKET s, int fd )
416 wine_server_release_fd( SOCKET2HANDLE(s), fd );
419 static void _enable_event( HANDLE s, unsigned int event,
420 unsigned int sstate, unsigned int cstate )
422 SERVER_START_REQ( enable_socket_event )
426 req->sstate = sstate;
427 req->cstate = cstate;
428 wine_server_call( req );
433 static int _is_blocking(SOCKET s)
436 SERVER_START_REQ( get_socket_event )
438 req->handle = SOCKET2HANDLE(s);
439 req->service = FALSE;
441 wine_server_call( req );
442 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
448 static unsigned int _get_sock_mask(SOCKET s)
451 SERVER_START_REQ( get_socket_event )
453 req->handle = SOCKET2HANDLE(s);
454 req->service = FALSE;
456 wine_server_call( req );
463 static void _sync_sock_state(SOCKET s)
465 /* do a dummy wineserver request in order to let
466 the wineserver run through its select loop once */
467 (void)_is_blocking(s);
470 static int _get_sock_error(SOCKET s, unsigned int bit)
472 int events[FD_MAX_EVENTS];
474 SERVER_START_REQ( get_socket_event )
476 req->handle = SOCKET2HANDLE(s);
477 req->service = FALSE;
479 wine_server_set_reply( req, events, sizeof(events) );
480 wine_server_call( req );
486 static struct per_thread_data *get_per_thread_data(void)
488 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
489 /* lazy initialization */
492 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
493 NtCurrentTeb()->WinSockData = ptb;
498 static void free_per_thread_data(void)
500 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
504 /* delete scratch buffers */
505 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
506 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
507 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
508 ptb->he_buffer = NULL;
509 ptb->se_buffer = NULL;
510 ptb->pe_buffer = NULL;
512 HeapFree( GetProcessHeap(), 0, ptb );
513 NtCurrentTeb()->WinSockData = NULL;
516 /***********************************************************************
517 * DllMain (WS2_32.init)
519 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
521 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
523 case DLL_PROCESS_ATTACH:
525 case DLL_PROCESS_DETACH:
526 free_per_thread_data();
529 case DLL_THREAD_DETACH:
530 free_per_thread_data();
536 /***********************************************************************
539 * Converts socket flags from Windows format.
540 * Return 1 if converted, 0 if not (error).
542 static int convert_sockopt(INT *level, INT *optname)
549 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
550 if( ws_sock_map[i][0] == *optname )
552 *optname = ws_sock_map[i][1];
556 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
559 *level = IPPROTO_TCP;
560 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
561 if ( ws_tcp_map[i][0] == *optname )
563 *optname = ws_tcp_map[i][1];
567 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
571 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
572 if (ws_ip_map[i][0] == *optname )
574 *optname = ws_ip_map[i][1];
578 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
580 default: FIXME("Unimplemented or unknown socket level\n");
585 /* ----------------------------------- Per-thread info (or per-process?) */
587 static char *strdup_lower(const char *str)
590 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
594 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
597 else SetLastError(WSAENOBUFS);
601 static inline int sock_error_p(int s)
603 unsigned int optval, optlen;
605 optlen = sizeof(optval);
606 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
607 if (optval) WARN("\t[%i] error: %d\n", s, optval);
611 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
612 * from an fd and return the value converted to milli seconds
613 * or -1 if there is an infinite time out */
614 static inline int get_rcvsnd_timeo( int fd, int optname)
617 unsigned int len = sizeof(tv);
618 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
620 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
621 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
626 /* macro wrappers for portability */
628 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
630 #define GET_RCVTIMEO(fd) (-1)
634 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
636 #define GET_SNDTIMEO(fd) (-1)
639 /* utility: given an fd, will block until one of the events occurs */
640 static inline int do_block( int fd, int events, int timeout )
648 while ((ret = poll(&pfd, 1, timeout)) < 0)
659 convert_af_w2u(int windowsaf) {
662 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
663 if (ws_af_map[i][0] == windowsaf)
664 return ws_af_map[i][1];
665 FIXME("unhandled Windows address family %d\n", windowsaf);
670 convert_af_u2w(int unixaf) {
673 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
674 if (ws_af_map[i][1] == unixaf)
675 return ws_af_map[i][0];
676 FIXME("unhandled UNIX address family %d\n", unixaf);
681 convert_proto_w2u(int windowsproto) {
684 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
685 if (ws_proto_map[i][0] == windowsproto)
686 return ws_proto_map[i][1];
687 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
692 convert_proto_u2w(int unixproto) {
695 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
696 if (ws_proto_map[i][1] == unixproto)
697 return ws_proto_map[i][0];
698 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
703 convert_socktype_w2u(int windowssocktype) {
706 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
707 if (ws_socktype_map[i][0] == windowssocktype)
708 return ws_socktype_map[i][1];
709 FIXME("unhandled Windows socket type %d\n", windowssocktype);
714 convert_socktype_u2w(int unixsocktype) {
717 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
718 if (ws_socktype_map[i][1] == unixsocktype)
719 return ws_socktype_map[i][0];
720 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
724 /* ----------------------------------- API -----
726 * Init / cleanup / error checking.
729 /***********************************************************************
730 * WSAStartup (WS2_32.115)
732 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
734 TRACE("verReq=%x\n", wVersionRequested);
736 if (LOBYTE(wVersionRequested) < 1)
737 return WSAVERNOTSUPPORTED;
739 if (!lpWSAData) return WSAEINVAL;
743 /* that's the whole of the negotiation for now */
744 lpWSAData->wVersion = wVersionRequested;
745 /* return winsock information */
746 lpWSAData->wHighVersion = 0x0202;
747 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
748 strcpy(lpWSAData->szSystemStatus, "Running" );
749 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
750 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
751 /* don't do anything with lpWSAData->lpVendorInfo */
752 /* (some apps don't allocate the space for this field) */
754 TRACE("succeeded\n");
759 /***********************************************************************
760 * WSACleanup (WS2_32.116)
762 INT WINAPI WSACleanup(void)
768 SetLastError(WSANOTINITIALISED);
773 /***********************************************************************
774 * WSAGetLastError (WINSOCK.111)
775 * WSAGetLastError (WS2_32.111)
777 INT WINAPI WSAGetLastError(void)
779 return GetLastError();
782 /***********************************************************************
783 * WSASetLastError (WS2_32.112)
785 void WINAPI WSASetLastError(INT iError) {
786 SetLastError(iError);
789 static struct WS_hostent *check_buffer_he(int size)
791 struct per_thread_data * ptb = get_per_thread_data();
794 if (ptb->he_len >= size ) return ptb->he_buffer;
795 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
797 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
798 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
799 return ptb->he_buffer;
802 static struct WS_servent *check_buffer_se(int size)
804 struct per_thread_data * ptb = get_per_thread_data();
807 if (ptb->se_len >= size ) return ptb->se_buffer;
808 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
810 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
811 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
812 return ptb->se_buffer;
815 static struct WS_protoent *check_buffer_pe(int size)
817 struct per_thread_data * ptb = get_per_thread_data();
820 if (ptb->pe_len >= size ) return ptb->pe_buffer;
821 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
823 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
824 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
825 return ptb->pe_buffer;
828 /* ----------------------------------- i/o APIs */
831 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf)== WS_AF_IPX || (pf) == WS_AF_INET6)
833 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf) == WS_AF_INET6)
837 /**********************************************************************/
839 /* Returns the length of the converted address if successful, 0 if it was too small to
842 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
843 union generic_unix_sockaddr *uaddr)
845 unsigned int uaddrlen = 0;
847 switch (wsaddr->sa_family)
852 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
853 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
855 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
858 uaddrlen = sizeof(struct sockaddr_ipx);
859 memset( uaddr, 0, uaddrlen );
860 uipx->sipx_family=AF_IPX;
861 uipx->sipx_port=wsipx->sa_socket;
862 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
865 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
866 #ifdef IPX_FRAME_NONE
867 uipx->sipx_type=IPX_FRAME_NONE;
873 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
874 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
876 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
877 * scope_id, one without.
879 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
880 uaddrlen = sizeof(struct sockaddr_in6);
881 memset( uaddr, 0, uaddrlen );
882 uin6->sin6_family = AF_INET6;
883 uin6->sin6_port = win6->sin6_port;
884 uin6->sin6_flowinfo = win6->sin6_flowinfo;
885 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
886 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
888 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
891 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
895 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
896 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
898 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
900 uaddrlen = sizeof(struct sockaddr_in);
901 memset( uaddr, 0, uaddrlen );
902 uin->sin_family = AF_INET;
903 uin->sin_port = win->sin_port;
904 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
908 /* Try to determine the needed space by the passed windows sockaddr space */
910 default: /* likely a ipv4 address */
911 case sizeof(struct WS_sockaddr_in):
912 uaddrlen = sizeof(struct sockaddr_in);
915 case sizeof(struct WS_sockaddr_ipx):
916 uaddrlen = sizeof(struct sockaddr_ipx);
919 case sizeof(struct WS_sockaddr_in6):
920 case sizeof(struct WS_sockaddr_in6_old):
921 uaddrlen = sizeof(struct sockaddr_in6);
924 memset( uaddr, 0, uaddrlen );
928 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
934 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
936 switch (uaddr->sa_family)
940 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
945 static const struct sockaddr_in6 emptyAddr;
946 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
947 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
951 static const struct sockaddr_in emptyAddr;
952 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
953 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
958 FIXME("unknown address family %d\n", uaddr->sa_family);
963 /* Returns 0 if successful, -1 if the buffer is too small */
964 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
968 switch(uaddr->sa_family)
973 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
974 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
977 switch (*wsaddrlen) /* how much can we copy? */
981 *wsaddrlen = sizeof(*wsipx);
982 wsipx->sa_socket=uipx->sipx_port;
986 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
994 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1000 wsipx->sa_family=WS_AF_IPX;
1011 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1012 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1014 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1016 win6old->sin6_family = WS_AF_INET6;
1017 win6old->sin6_port = uin6->sin6_port;
1018 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1019 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1020 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1021 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1022 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1023 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1024 win6->sin6_scope_id = uin6->sin6_scope_id;
1025 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1031 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1032 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1034 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1036 win->sin_family = WS_AF_INET;
1037 win->sin_port = uin->sin_port;
1038 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1039 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1040 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1044 memset(wsaddr,0,*wsaddrlen);
1048 FIXME("Unknown address family %d\n", uaddr->sa_family);
1054 /**************************************************************************
1055 * Functions for handling overlapped I/O
1056 **************************************************************************/
1058 /* user APC called upon async completion */
1059 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1061 ws2_async *wsa = arg;
1063 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1064 iosb->Information, wsa->user_overlapped,
1066 HeapFree( GetProcessHeap(), 0, wsa );
1069 /***********************************************************************
1070 * WS2_recv (INTERNAL)
1072 * Workhorse for both synchronous and asynchronous recv() operations.
1074 static int WS2_recv( int fd, struct iovec* iov, int count,
1075 struct WS_sockaddr *lpFrom, LPINT lpFromlen,
1079 union generic_unix_sockaddr unix_sockaddr;
1082 hdr.msg_name = NULL;
1086 hdr.msg_namelen = sizeof(unix_sockaddr);
1087 hdr.msg_name = &unix_sockaddr;
1090 hdr.msg_namelen = 0;
1093 hdr.msg_iovlen = count;
1094 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1095 hdr.msg_accrights = NULL;
1096 hdr.msg_accrightslen = 0;
1098 hdr.msg_control = NULL;
1099 hdr.msg_controllen = 0;
1103 if ( (n = recvmsg(fd, &hdr, *lpFlags)) == -1 )
1106 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1107 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1109 * quoting linux 2.6 net/ipv4/tcp.c:
1110 * "According to UNIX98, msg_name/msg_namelen are ignored
1111 * on connected socket. I was just happy when found this 8) --ANK"
1113 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1114 * connection-oriented sockets, so don't try to update lpFrom.
1116 if ( lpFrom && hdr.msg_namelen &&
1117 ws_sockaddr_u2ws( &unix_sockaddr.addr, lpFrom, lpFromlen ) != 0 )
1119 /* The from buffer was too small, but we read the data
1120 * anyway. Is that really bad?
1127 /***********************************************************************
1128 * WS2_async_recv (INTERNAL)
1130 * Handler for overlapped recv() operations.
1132 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, ULONG_PTR *total )
1134 ws2_async* wsa = user;
1139 case STATUS_ALERTED:
1140 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1143 result = WS2_recv( fd, wsa->iovec, wsa->n_iovecs,
1144 wsa->addr, wsa->addrlen.ptr, &wsa->flags );
1145 wine_server_release_fd( wsa->hSocket, fd );
1148 status = STATUS_SUCCESS;
1149 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1153 if (errno == EINTR || errno == EAGAIN)
1155 status = STATUS_PENDING;
1156 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1161 status = wsaErrno(); /* FIXME: is this correct ???? */
1166 if (status != STATUS_PENDING)
1168 iosb->u.Status = status;
1169 iosb->Information = *total = result;
1174 /***********************************************************************
1175 * WS2_send (INTERNAL)
1177 * Workhorse for both synchronous and asynchronous send() operations.
1179 static int WS2_send( int fd, struct iovec* iov, int count,
1180 const struct WS_sockaddr *to, INT tolen, DWORD dwFlags )
1183 union generic_unix_sockaddr unix_addr;
1186 hdr.msg_name = NULL;
1187 hdr.msg_namelen = 0;
1191 hdr.msg_name = &unix_addr;
1192 hdr.msg_namelen = ws_sockaddr_ws2u( to, tolen, &unix_addr );
1193 if ( !hdr.msg_namelen )
1199 #if defined(HAVE_IPX) && defined(SOL_IPX)
1200 if(to->sa_family == WS_AF_IPX)
1202 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1204 unsigned int len=sizeof(int);
1206 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1207 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1208 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1209 * ipx type in the sockaddr_opx structure with the stored value.
1211 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1212 uipx->sipx_type = val;
1218 hdr.msg_iovlen = count;
1219 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1220 hdr.msg_accrights = NULL;
1221 hdr.msg_accrightslen = 0;
1223 hdr.msg_control = NULL;
1224 hdr.msg_controllen = 0;
1228 return sendmsg(fd, &hdr, dwFlags);
1231 /***********************************************************************
1232 * WS2_async_send (INTERNAL)
1234 * Handler for overlapped send() operations.
1236 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, ULONG_PTR *total )
1238 ws2_async* wsa = user;
1243 case STATUS_ALERTED:
1244 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1247 /* check to see if the data is ready (non-blocking) */
1248 result = WS2_send( fd, wsa->iovec, wsa->n_iovecs, wsa->addr, wsa->addrlen.val, wsa->flags );
1249 wine_server_release_fd( wsa->hSocket, fd );
1253 int totalLength = 0;
1255 status = STATUS_SUCCESS;
1256 for (i = 0; i < wsa->n_iovecs; i++)
1257 totalLength += wsa->iovec[i].iov_len;
1258 if (result < totalLength)
1259 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1263 if (errno == EINTR || errno == EAGAIN)
1265 status = STATUS_PENDING;
1266 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1270 /* We set the status to a winsock error code and check for that
1271 later in NtStatusToWSAError () */
1272 status = wsaErrno();
1278 if (status != STATUS_PENDING)
1280 iosb->u.Status = status;
1281 iosb->Information = *total = result;
1286 /***********************************************************************
1287 * WS2_async_shutdown (INTERNAL)
1289 * Handler for shutdown() operations on overlapped sockets.
1291 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status )
1293 ws2_async* wsa = user;
1298 case STATUS_ALERTED:
1299 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1302 switch ( wsa->type )
1304 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1305 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1307 wine_server_release_fd( wsa->hSocket, fd );
1308 status = err ? wsaErrno() : STATUS_SUCCESS;
1311 iosb->u.Status = status;
1315 /***********************************************************************
1316 * WS2_register_async_shutdown (INTERNAL)
1318 * Helper function for WS_shutdown() on overlapped sockets.
1320 static int WS2_register_async_shutdown( SOCKET s, int type )
1322 struct ws2_async *wsa;
1325 TRACE("s %ld type %d\n", s, type);
1327 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1331 wsa->hSocket = SOCKET2HANDLE(s);
1333 wsa->completion_func = NULL;
1335 SERVER_START_REQ( register_async )
1337 req->handle = wsa->hSocket;
1339 req->async.callback = WS2_async_shutdown;
1340 req->async.iosb = &wsa->local_iosb;
1341 req->async.arg = wsa;
1342 req->async.apc = ws2_async_apc;
1343 req->async.cvalue = 0;
1344 status = wine_server_call( req );
1348 if (status != STATUS_PENDING)
1350 HeapFree( GetProcessHeap(), 0, wsa );
1351 return NtStatusToWSAError( status );
1356 /***********************************************************************
1359 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1365 TRACE("socket %04lx\n", s );
1366 is_blocking = _is_blocking(s);
1371 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1372 if (fd == -1) return INVALID_SOCKET;
1374 do_block(fd, POLLIN, -1);
1375 _sync_sock_state(s); /* let wineserver notice connection */
1376 release_sock_fd( s, fd );
1377 /* retrieve any error codes from it */
1378 SetLastError(_get_sock_error(s, FD_ACCEPT_BIT));
1379 /* FIXME: care about the error? */
1381 SERVER_START_REQ( accept_socket )
1383 req->lhandle = SOCKET2HANDLE(s);
1384 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1385 req->attributes = OBJ_INHERIT;
1386 set_error( wine_server_call( req ) );
1387 as = HANDLE2SOCKET( reply->handle );
1392 if (addr) WS_getpeername(as, addr, addrlen32);
1395 } while (is_blocking);
1396 return INVALID_SOCKET;
1399 /***********************************************************************
1402 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1404 int fd = get_sock_fd( s, 0, NULL );
1405 int res = SOCKET_ERROR;
1407 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1411 if (!name || (name->sa_family && !SUPPORTED_PF(name->sa_family)))
1413 SetLastError(WSAEAFNOSUPPORT);
1417 union generic_unix_sockaddr uaddr;
1418 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1421 SetLastError(WSAEFAULT);
1426 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
1427 if (name->sa_family == WS_AF_INET6 &&
1428 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
1431 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
1433 release_sock_fd( s, fd );
1434 SetLastError(WSAEAFNOSUPPORT);
1435 return INVALID_SOCKET;
1439 if (name->sa_family == WS_AF_INET)
1441 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1442 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1444 /* Trying to bind to the default host interface, using
1445 * INADDR_ANY instead*/
1446 WARN("Trying to bind to magic IP address, using "
1447 "INADDR_ANY instead.\n");
1448 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
1451 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
1453 int loc_errno = errno;
1454 WARN("\tfailure - errno = %i\n", errno);
1459 SetLastError(WSAENOTSOCK);
1462 SetLastError(WSAEINVAL);
1465 SetLastError(wsaErrno());
1471 res=0; /* success */
1475 release_sock_fd( s, fd );
1480 /***********************************************************************
1481 * closesocket (WS2_32.3)
1483 int WINAPI WS_closesocket(SOCKET s)
1485 TRACE("socket %04lx\n", s);
1486 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
1487 return SOCKET_ERROR;
1490 /***********************************************************************
1491 * connect (WS2_32.4)
1493 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1495 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1497 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1501 union generic_unix_sockaddr uaddr;
1502 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1506 SetLastError(WSAEFAULT);
1510 if (name->sa_family == WS_AF_INET)
1512 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1513 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1515 /* Trying to connect to magic replace-loopback address,
1516 * assuming we really want to connect to localhost */
1517 TRACE("Trying to connect to magic IP address, using "
1518 "INADDR_LOOPBACK instead.\n");
1519 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
1523 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
1524 goto connect_success;
1527 if (errno == EINPROGRESS)
1529 /* tell wineserver that a connection is in progress */
1530 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1531 FD_CONNECT|FD_READ|FD_WRITE,
1532 FD_WINE_CONNECTED|FD_WINE_LISTENING);
1533 if (_is_blocking(s))
1537 do_block(fd, POLLIN | POLLOUT, -1);
1538 _sync_sock_state(s); /* let wineserver notice connection */
1539 /* retrieve any error codes from it */
1540 result = _get_sock_error(s, FD_CONNECT_BIT);
1542 SetLastError(result);
1545 goto connect_success;
1550 SetLastError(WSAEWOULDBLOCK);
1555 SetLastError(wsaErrno());
1557 release_sock_fd( s, fd );
1559 return SOCKET_ERROR;
1562 release_sock_fd( s, fd );
1563 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1564 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1565 FD_CONNECT|FD_WINE_LISTENING);
1569 /***********************************************************************
1570 * WSAConnect (WS2_32.30)
1572 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
1573 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1574 LPQOS lpSQOS, LPQOS lpGQOS )
1576 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1577 FIXME("unsupported parameters!\n");
1578 return WS_connect( s, name, namelen );
1582 /***********************************************************************
1583 * getpeername (WS2_32.5)
1585 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1590 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, *namelen);
1592 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1593 if( (name == NULL) || (namelen == NULL) )
1595 SetLastError( WSAEFAULT );
1596 return SOCKET_ERROR;
1599 fd = get_sock_fd( s, 0, NULL );
1604 union generic_unix_sockaddr uaddr;
1605 unsigned int uaddrlen = sizeof(uaddr);
1607 if (getpeername(fd, &uaddr.addr, &uaddrlen) != 0)
1609 SetLastError(wsaErrno());
1611 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1613 /* The buffer was too small */
1614 SetLastError(WSAEFAULT);
1620 release_sock_fd( s, fd );
1625 /***********************************************************************
1626 * getsockname (WS2_32.6)
1628 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1633 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
1635 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1636 if( (name == NULL) || (namelen == NULL) )
1638 SetLastError( WSAEFAULT );
1639 return SOCKET_ERROR;
1642 fd = get_sock_fd( s, 0, NULL );
1647 union generic_unix_sockaddr uaddr;
1648 unsigned int uaddrlen = sizeof(uaddr);
1650 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
1652 SetLastError(wsaErrno());
1654 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
1656 SetLastError(WSAEINVAL);
1658 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1660 /* The buffer was too small */
1661 SetLastError(WSAEFAULT);
1667 release_sock_fd( s, fd );
1672 /***********************************************************************
1673 * getsockopt (WS2_32.7)
1675 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1676 INT optname, char *optval, INT *optlen)
1681 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
1682 s, level, optname, optval, *optlen);
1690 /* Handle common cases. The special cases are below, sorted
1692 case WS_SO_ACCEPTCONN:
1693 case WS_SO_BROADCAST:
1696 case WS_SO_KEEPALIVE:
1697 case WS_SO_OOBINLINE:
1699 case WS_SO_REUSEADDR:
1702 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1703 return SOCKET_ERROR;
1704 convert_sockopt(&level, &optname);
1705 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1707 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1710 release_sock_fd( s, fd );
1713 case WS_SO_DONTLINGER:
1715 struct linger lingval;
1716 unsigned int len = sizeof(struct linger);
1718 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
1720 SetLastError(WSAEFAULT);
1721 return SOCKET_ERROR;
1723 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1724 return SOCKET_ERROR;
1726 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1728 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1733 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
1734 *optlen = sizeof(BOOL);
1737 release_sock_fd( s, fd );
1741 /* As mentioned in setsockopt, Windows ignores this, so we
1742 * always return true here */
1743 case WS_SO_DONTROUTE:
1744 if (!optlen || *optlen < sizeof(BOOL) || !optval)
1746 SetLastError(WSAEFAULT);
1747 return SOCKET_ERROR;
1749 *(BOOL *)optval = TRUE;
1750 *optlen = sizeof(BOOL);
1755 struct linger lingval;
1756 unsigned int len = sizeof(struct linger);
1758 /* struct linger and LINGER have different sizes */
1759 if (!optlen || *optlen < sizeof(LINGER) || !optval)
1761 SetLastError(WSAEFAULT);
1762 return SOCKET_ERROR;
1764 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1765 return SOCKET_ERROR;
1767 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1769 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1774 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
1775 ((LINGER *)optval)->l_linger = lingval.l_linger;
1776 *optlen = sizeof(struct linger);
1779 release_sock_fd( s, fd );
1783 case WS_SO_MAX_MSG_SIZE:
1784 if (!optlen || *optlen < sizeof(int) || !optval)
1786 SetLastError(WSAEFAULT);
1787 return SOCKET_ERROR;
1789 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
1790 *(int *)optval = 65507;
1791 *optlen = sizeof(int);
1794 /* SO_OPENTYPE does not require a valid socket handle. */
1795 case WS_SO_OPENTYPE:
1796 if (!optlen || *optlen < sizeof(int) || !optval)
1798 SetLastError(WSAEFAULT);
1799 return SOCKET_ERROR;
1801 *(int *)optval = get_per_thread_data()->opentype;
1802 *optlen = sizeof(int);
1803 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
1807 case WS_SO_RCVTIMEO:
1810 case WS_SO_SNDTIMEO:
1812 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
1815 unsigned int len = sizeof(struct timeval);
1817 if (!optlen || *optlen < sizeof(int)|| !optval)
1819 SetLastError(WSAEFAULT);
1820 return SOCKET_ERROR;
1822 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1823 return SOCKET_ERROR;
1825 convert_sockopt(&level, &optname);
1826 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
1828 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1833 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1834 *optlen = sizeof(int);
1837 release_sock_fd( s, fd );
1842 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
1843 SetLastError(WSAENOPROTOOPT);
1844 return SOCKET_ERROR;
1845 } /* end switch(optname) */
1846 }/* end case WS_SOL_SOCKET */
1850 struct WS_sockaddr_ipx addr;
1851 IPX_ADDRESS_DATA *data;
1856 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
1858 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
1865 socklen_t len=sizeof(struct ipx);
1866 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
1869 *optval = (int)val.ipx_pt;
1872 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
1873 release_sock_fd( s, fd );
1878 * On a Win2000 system with one network card there are usually
1879 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
1880 * Using this call you can then retrieve info about this all.
1881 * In case of Linux it is a bit different. Usually you have
1882 * only "one" device active and further it is not possible to
1883 * query things like the linkspeed.
1885 FIXME("IPX_ADDRESS\n");
1886 namelen = sizeof(struct WS_sockaddr_ipx);
1887 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
1888 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
1890 data = (IPX_ADDRESS_DATA*)optval;
1891 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
1892 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
1893 data->adapternum = 0;
1894 data->wan = FALSE; /* We are not on a wan for now .. */
1895 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
1896 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
1897 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
1898 * note 1MB = 1000kB in this case */
1901 case IPX_MAX_ADAPTER_NUM:
1902 FIXME("IPX_MAX_ADAPTER_NUM\n");
1903 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
1907 FIXME("IPX optname:%x\n", optname);
1908 return SOCKET_ERROR;
1909 }/* end switch(optname) */
1910 } /* end case NSPROTO_IPX */
1912 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
1913 case WS_IPPROTO_TCP:
1916 case WS_TCP_NODELAY:
1917 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1918 return SOCKET_ERROR;
1919 convert_sockopt(&level, &optname);
1920 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1922 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1925 release_sock_fd( s, fd );
1928 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
1929 return SOCKET_ERROR;
1934 case WS_IP_ADD_MEMBERSHIP:
1935 case WS_IP_DROP_MEMBERSHIP:
1939 case WS_IP_MULTICAST_IF:
1940 case WS_IP_MULTICAST_LOOP:
1941 case WS_IP_MULTICAST_TTL:
1945 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1946 return SOCKET_ERROR;
1947 convert_sockopt(&level, &optname);
1948 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1950 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1953 release_sock_fd( s, fd );
1955 case WS_IP_DONTFRAGMENT:
1956 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
1957 *(BOOL*)optval = FALSE;
1960 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
1961 return SOCKET_ERROR;
1964 FIXME("Unknown level: 0x%08x\n", level);
1965 return SOCKET_ERROR;
1966 } /* end switch(level) */
1969 /***********************************************************************
1973 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
1975 return htonl(hostlong);
1979 /***********************************************************************
1983 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
1985 return htons(hostshort);
1988 /***********************************************************************
1989 * WSAHtonl (WS2_32.46)
1990 * From MSDN description of error codes, this function should also
1991 * check if WinSock has been initialized and the socket is a valid
1992 * socket. But why? This function only translates a host byte order
1993 * u_long into a network byte order u_long...
1995 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
1999 *lpnetlong = htonl(hostlong);
2002 WSASetLastError(WSAEFAULT);
2003 return SOCKET_ERROR;
2006 /***********************************************************************
2007 * WSAHtons (WS2_32.47)
2008 * From MSDN description of error codes, this function should also
2009 * check if WinSock has been initialized and the socket is a valid
2010 * socket. But why? This function only translates a host byte order
2011 * u_short into a network byte order u_short...
2013 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2018 *lpnetshort = htons(hostshort);
2021 WSASetLastError(WSAEFAULT);
2022 return SOCKET_ERROR;
2026 /***********************************************************************
2027 * inet_addr (WINSOCK.10)
2028 * inet_addr (WS2_32.11)
2030 WS_u_long WINAPI WS_inet_addr(const char *cp)
2032 if (!cp) return INADDR_NONE;
2033 return inet_addr(cp);
2037 /***********************************************************************
2038 * ntohl (WINSOCK.14)
2041 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2043 return ntohl(netlong);
2047 /***********************************************************************
2048 * ntohs (WINSOCK.15)
2051 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2053 return ntohs(netshort);
2057 /***********************************************************************
2058 * inet_ntoa (WS2_32.12)
2060 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2062 /* use "buffer for dummies" here because some applications have a
2063 * propensity to decode addresses in ws_hostent structure without
2064 * saving them first...
2066 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2068 char* s = inet_ntoa(*((struct in_addr*)&in));
2074 SetLastError(wsaErrno());
2078 /**********************************************************************
2079 * WSAIoctl (WS2_32.50)
2082 INT WINAPI WSAIoctl(SOCKET s,
2083 DWORD dwIoControlCode,
2086 LPVOID lpbOutBuffer,
2088 LPDWORD lpcbBytesReturned,
2089 LPWSAOVERLAPPED lpOverlapped,
2090 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2092 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
2093 s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpbOutBuffer,
2094 cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
2096 switch( dwIoControlCode )
2099 if (cbInBuffer != sizeof(WS_u_long)) {
2100 WSASetLastError(WSAEFAULT);
2101 return SOCKET_ERROR;
2103 return WS_ioctlsocket( s, WS_FIONBIO, lpvInBuffer);
2106 if (cbOutBuffer != sizeof(WS_u_long)) {
2107 WSASetLastError(WSAEFAULT);
2108 return SOCKET_ERROR;
2110 return WS_ioctlsocket( s, WS_FIONREAD, lpbOutBuffer);
2112 case WS_SIO_GET_INTERFACE_LIST:
2114 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
2115 DWORD size, numInt, apiReturn;
2118 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
2122 WSASetLastError(WSAEFAULT);
2123 return SOCKET_ERROR;
2125 if (!lpcbBytesReturned)
2127 WSASetLastError(WSAEFAULT);
2128 return SOCKET_ERROR;
2131 fd = get_sock_fd( s, 0, NULL );
2132 if (fd == -1) return SOCKET_ERROR;
2134 apiReturn = GetAdaptersInfo(NULL, &size);
2135 if (apiReturn == ERROR_NO_DATA)
2139 else if (apiReturn == ERROR_BUFFER_OVERFLOW)
2141 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
2145 if (GetAdaptersInfo(table, &size) == NO_ERROR)
2147 PIP_ADAPTER_INFO ptr;
2149 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > cbOutBuffer)
2151 WARN("Buffer too small = %u, cbOutBuffer = %u\n", size, cbOutBuffer);
2152 HeapFree(GetProcessHeap(),0,table);
2153 release_sock_fd( s, fd );
2154 WSASetLastError(WSAEFAULT);
2155 return SOCKET_ERROR;
2157 for (ptr = table, numInt = 0; ptr;
2158 ptr = ptr->Next, intArray++, numInt++)
2160 unsigned int addr, mask, bcast;
2161 struct ifreq ifInfo;
2163 /* Socket Status Flags */
2164 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
2165 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2167 ERR("Error obtaining status flags for socket!\n");
2168 HeapFree(GetProcessHeap(),0,table);
2169 release_sock_fd( s, fd );
2170 WSASetLastError(WSAEINVAL);
2171 return SOCKET_ERROR;
2175 /* set flags; the values of IFF_* are not the same
2176 under Linux and Windows, therefore must generate
2178 intArray->iiFlags = 0;
2179 if (ifInfo.ifr_flags & IFF_BROADCAST)
2180 intArray->iiFlags |= WS_IFF_BROADCAST;
2181 #ifdef IFF_POINTOPOINT
2182 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
2183 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
2185 if (ifInfo.ifr_flags & IFF_LOOPBACK)
2186 intArray->iiFlags |= WS_IFF_LOOPBACK;
2187 if (ifInfo.ifr_flags & IFF_UP)
2188 intArray->iiFlags |= WS_IFF_UP;
2189 if (ifInfo.ifr_flags & IFF_MULTICAST)
2190 intArray->iiFlags |= WS_IFF_MULTICAST;
2193 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
2194 mask = inet_addr(ptr->IpAddressList.IpMask.String);
2195 bcast = addr | ~mask;
2196 intArray->iiAddress.AddressIn.sin_family = AF_INET;
2197 intArray->iiAddress.AddressIn.sin_port = 0;
2198 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
2200 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2201 intArray->iiNetmask.AddressIn.sin_port = 0;
2202 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
2204 intArray->iiBroadcastAddress.AddressIn.sin_family =
2206 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
2207 intArray->iiBroadcastAddress.AddressIn.sin_addr.
2213 ERR("Unable to get interface table!\n");
2214 release_sock_fd( s, fd );
2215 HeapFree(GetProcessHeap(),0,table);
2216 WSASetLastError(WSAEINVAL);
2217 return SOCKET_ERROR;
2219 HeapFree(GetProcessHeap(),0,table);
2223 release_sock_fd( s, fd );
2224 WSASetLastError(WSAEINVAL);
2225 return SOCKET_ERROR;
2230 ERR("Unable to get interface table!\n");
2231 release_sock_fd( s, fd );
2232 WSASetLastError(WSAEINVAL);
2233 return SOCKET_ERROR;
2235 /* Calculate the size of the array being returned */
2236 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2237 release_sock_fd( s, fd );
2241 case WS_SIO_ADDRESS_LIST_CHANGE:
2242 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
2243 /* FIXME: error and return code depend on whether socket was created
2244 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
2247 case WS_SIO_ADDRESS_LIST_QUERY:
2251 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
2253 if (!lpcbBytesReturned)
2255 WSASetLastError(WSAEFAULT);
2256 return SOCKET_ERROR;
2259 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
2261 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
2264 if (!table || GetAdaptersInfo(table, &size))
2266 HeapFree(GetProcessHeap(), 0, table);
2267 WSASetLastError(WSAEINVAL);
2268 return SOCKET_ERROR;
2271 for (p = table, num = 0; p; p = p->Next)
2272 if (p->IpAddressList.IpAddress.String[0]) num++;
2274 need = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
2275 need += sizeof(SOCKADDR) * num;
2276 *lpcbBytesReturned = need;
2278 if (need > cbOutBuffer)
2280 HeapFree(GetProcessHeap(), 0, table);
2281 WSASetLastError(WSAEFAULT);
2282 return SOCKET_ERROR;
2289 SOCKET_ADDRESS_LIST *sa_list = (SOCKET_ADDRESS_LIST *)lpbOutBuffer;
2290 SOCKADDR_IN *sockaddr;
2292 sa = sa_list->Address;
2293 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
2294 sa_list->iAddressCount = num;
2296 for (p = table, i = 0; p; p = p->Next)
2298 if (!p->IpAddressList.IpAddress.String[0]) continue;
2300 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
2301 sa[i].iSockaddrLength = sizeof(SOCKADDR);
2303 sockaddr[i].sin_family = AF_INET;
2304 sockaddr[i].sin_port = 0;
2305 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
2310 HeapFree(GetProcessHeap(), 0, table);
2315 WARN("unable to get IP address list\n");
2316 WSASetLastError(WSAEINVAL);
2317 return SOCKET_ERROR;
2321 FIXME("SIO_FLUSH: stub.\n");
2324 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
2325 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(lpvInBuffer));
2326 WSASetLastError(WSAEOPNOTSUPP);
2327 return SOCKET_ERROR;
2330 FIXME("unsupported WS_IOCTL cmd (%08x)\n", dwIoControlCode);
2331 WSASetLastError(WSAEOPNOTSUPP);
2332 return SOCKET_ERROR;
2339 /***********************************************************************
2340 * ioctlsocket (WS2_32.10)
2342 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
2347 TRACE("socket %04lx, cmd %08x, ptr %p\n", s, cmd, argp);
2348 /* broken apps like defcon pass the argp value directly instead of a pointer to it */
2349 if(IS_INTRESOURCE(argp))
2351 SetLastError(WSAEFAULT);
2352 return SOCKET_ERROR;
2362 if( _get_sock_mask(s) )
2364 /* AsyncSelect()'ed sockets are always nonblocking */
2365 if (*argp) return 0;
2366 SetLastError(WSAEINVAL);
2367 return SOCKET_ERROR;
2369 fd = get_sock_fd( s, 0, NULL );
2375 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
2376 ret = fcntl( fd, F_SETFL, O_NONBLOCK );
2380 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
2381 ret = fcntl( fd, F_SETFL, 0 );
2383 release_sock_fd( s, fd );
2385 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2387 return SOCKET_ERROR;
2394 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2395 SetLastError(WSAEINVAL);
2396 return SOCKET_ERROR;
2398 case SIOCGIFBRDADDR:
2399 case SIOCGIFNETMASK:
2401 /* These don't need any special handling. They are used by
2402 WsControl, and are here to suppress an unnecessary warning. */
2406 /* Netscape tries hard to use bogus ioctl 0x667e */
2407 /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
2408 * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
2410 WARN("\tunknown WS_IOCTL cmd (%08x)\n", cmd);
2414 fd = get_sock_fd( s, 0, NULL );
2417 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2419 release_sock_fd( s, fd );
2422 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2423 release_sock_fd( s, fd );
2425 return SOCKET_ERROR;
2428 /***********************************************************************
2429 * listen (WS2_32.13)
2431 int WINAPI WS_listen(SOCKET s, int backlog)
2433 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2435 TRACE("socket %04lx, backlog %d\n", s, backlog);
2438 if (listen(fd, backlog) == 0)
2440 release_sock_fd( s, fd );
2441 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
2443 FD_CONNECT|FD_WINE_CONNECTED);
2446 SetLastError(wsaErrno());
2447 release_sock_fd( s, fd );
2449 return SOCKET_ERROR;
2452 /***********************************************************************
2455 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2457 DWORD n, dwFlags = flags;
2463 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2464 return SOCKET_ERROR;
2469 /***********************************************************************
2470 * recvfrom (WS2_32.17)
2472 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2473 struct WS_sockaddr *from, int *fromlen)
2475 DWORD n, dwFlags = flags;
2481 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2482 return SOCKET_ERROR;
2487 /* allocate a poll array for the corresponding fd sets */
2488 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
2489 const WS_fd_set *exceptfds, int *count_ptr )
2491 int i, j = 0, count = 0;
2494 if (readfds) count += readfds->fd_count;
2495 if (writefds) count += writefds->fd_count;
2496 if (exceptfds) count += exceptfds->fd_count;
2498 if (!count) return NULL;
2499 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0])))) return NULL;
2501 for (i = 0; i < readfds->fd_count; i++, j++)
2503 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
2504 fds[j].events = POLLIN;
2508 for (i = 0; i < writefds->fd_count; i++, j++)
2510 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
2511 fds[j].events = POLLOUT;
2515 for (i = 0; i < exceptfds->fd_count; i++, j++)
2517 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
2518 fds[j].events = POLLHUP;
2524 /* release the file descriptor obtained in fd_sets_to_poll */
2525 /* must be called with the original fd_set arrays, before calling get_poll_results */
2526 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
2527 const WS_fd_set *exceptfds, struct pollfd *fds )
2533 for (i = 0; i < readfds->fd_count; i++, j++)
2534 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
2538 for (i = 0; i < writefds->fd_count; i++, j++)
2539 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
2543 for (i = 0; i < exceptfds->fd_count; i++, j++)
2544 if (fds[j].fd != -1)
2546 /* make sure we have a real error before releasing the fd */
2547 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
2548 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
2553 /* map the poll results back into the Windows fd sets */
2554 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
2555 const struct pollfd *fds )
2557 int i, j = 0, k, total = 0;
2561 for (i = k = 0; i < readfds->fd_count; i++, j++)
2562 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
2563 readfds->fd_count = k;
2568 for (i = k = 0; i < writefds->fd_count; i++, j++)
2569 if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
2570 writefds->fd_count = k;
2575 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
2576 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
2577 exceptfds->fd_count = k;
2584 /***********************************************************************
2585 * select (WS2_32.18)
2587 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
2588 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
2589 const struct WS_timeval* ws_timeout)
2591 struct pollfd *pollfds;
2592 int count, ret, timeout = -1;
2594 TRACE("read %p, write %p, excp %p timeout %p\n",
2595 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
2597 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )) && count)
2599 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2600 return SOCKET_ERROR;
2603 if (ws_timeout) timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
2605 ret = poll( pollfds, count, timeout );
2606 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2608 if (ret == -1) SetLastError(wsaErrno());
2609 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2610 HeapFree( GetProcessHeap(), 0, pollfds );
2614 /* helper to send completion messages for client-only i/o operation case */
2615 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG_PTR Information )
2619 SERVER_START_REQ( add_fd_completion )
2621 req->handle = SOCKET2HANDLE(sock);
2622 req->cvalue = CompletionValue;
2623 req->status = CompletionStatus;
2624 req->information = Information;
2625 status = wine_server_call( req );
2631 /***********************************************************************
2634 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
2640 wsabuf.buf = (char*) buf;
2642 if ( WSASendTo( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
2643 return SOCKET_ERROR;
2648 /***********************************************************************
2649 * WSASend (WS2_32.72)
2651 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2652 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2653 LPWSAOVERLAPPED lpOverlapped,
2654 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2656 return WSASendTo( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
2657 NULL, 0, lpOverlapped, lpCompletionRoutine );
2660 /***********************************************************************
2661 * WSASendDisconnect (WS2_32.73)
2663 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
2665 return WS_shutdown( s, SD_SEND );
2669 /***********************************************************************
2670 * WSASendTo (WS2_32.74)
2672 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2673 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2674 const struct WS_sockaddr *to, int tolen,
2675 LPWSAOVERLAPPED lpOverlapped,
2676 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2678 unsigned int i, options;
2680 struct iovec iovec[WS_MSG_MAXIOVLEN];
2681 int totalLength = 0;
2682 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
2684 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
2685 s, lpBuffers, dwBufferCount, dwFlags,
2686 to, tolen, lpOverlapped, lpCompletionRoutine);
2688 if (dwBufferCount > WS_MSG_MAXIOVLEN)
2690 WSASetLastError( WSAEINVAL );
2691 return SOCKET_ERROR;
2694 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
2695 TRACE( "fd=%d, options=%x\n", fd, options );
2697 if ( fd == -1 ) return SOCKET_ERROR;
2699 if ( !lpNumberOfBytesSent )
2705 for ( i = 0; i < dwBufferCount; i++ )
2707 iovec[i].iov_base = lpBuffers[i].buf;
2708 iovec[i].iov_len = lpBuffers[i].len;
2709 totalLength += lpBuffers[i].len;
2714 n = WS2_send( fd, iovec, dwBufferCount, to, tolen, dwFlags );
2715 if (n != -1 || errno != EINTR) break;
2717 if (n == -1 && errno != EAGAIN)
2720 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
2724 if ((lpOverlapped || lpCompletionRoutine) &&
2725 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
2727 IO_STATUS_BLOCK *iosb;
2728 struct ws2_async *wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
2735 release_sock_fd( s, fd );
2737 wsa->hSocket = SOCKET2HANDLE(s);
2738 wsa->addr = (struct WS_sockaddr *)to;
2739 wsa->addrlen.val = tolen;
2741 wsa->user_overlapped = lpOverlapped;
2742 wsa->completion_func = lpCompletionRoutine;
2743 wsa->n_iovecs = dwBufferCount;
2744 memcpy( wsa->iovec, iovec, dwBufferCount * sizeof(*iovec) );
2746 iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
2749 iosb->u.Status = STATUS_PENDING;
2750 iosb->Information = 0;
2752 SERVER_START_REQ( register_async )
2754 req->handle = wsa->hSocket;
2755 req->type = ASYNC_TYPE_WRITE;
2756 req->async.callback = WS2_async_send;
2757 req->async.iosb = iosb;
2758 req->async.arg = wsa;
2759 req->async.apc = ws2_async_apc;
2760 req->async.event = lpCompletionRoutine ? 0 : lpOverlapped->hEvent;
2761 req->async.cvalue = cvalue;
2762 err = wine_server_call( req );
2766 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
2767 WSASetLastError( NtStatusToWSAError( err ));
2768 return SOCKET_ERROR;
2771 iosb->u.Status = STATUS_SUCCESS;
2772 iosb->Information = n;
2773 *lpNumberOfBytesSent = n;
2774 if (!wsa->completion_func)
2776 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
2777 SetEvent( lpOverlapped->hEvent );
2778 HeapFree( GetProcessHeap(), 0, wsa );
2780 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
2781 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
2786 if ( _is_blocking(s) )
2788 /* On a blocking non-overlapped stream socket,
2789 * sending blocks until the entire buffer is sent. */
2790 DWORD timeout_start = GetTickCount();
2791 unsigned int first_buff = 0;
2793 *lpNumberOfBytesSent = 0;
2795 while (first_buff < dwBufferCount)
2798 int timeout = GET_SNDTIMEO(fd);
2802 *lpNumberOfBytesSent += n;
2803 while (first_buff < dwBufferCount && iovec[first_buff].iov_len <= n)
2804 n -= iovec[first_buff++].iov_len;
2805 if (first_buff >= dwBufferCount) break;
2806 iovec[first_buff].iov_base = (char*)iovec[first_buff].iov_base + n;
2807 iovec[first_buff].iov_len -= n;
2812 timeout -= GetTickCount() - timeout_start;
2813 if (timeout < 0) timeout = 0;
2817 pfd.events = POLLOUT;
2819 if (!timeout || !poll( &pfd, 1, timeout ))
2822 goto error; /* msdn says a timeout in send is fatal */
2825 n = WS2_send( fd, iovec + first_buff, dwBufferCount - first_buff, to, tolen, dwFlags );
2826 if (n == -1 && errno != EAGAIN && errno != EINTR)
2833 else /* non-blocking */
2835 if (n < totalLength)
2836 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
2839 err = WSAEWOULDBLOCK;
2842 *lpNumberOfBytesSent = n;
2845 TRACE(" -> %i bytes\n", *lpNumberOfBytesSent);
2847 release_sock_fd( s, fd );
2852 release_sock_fd( s, fd );
2853 WARN(" -> ERROR %d\n", err);
2854 WSASetLastError(err);
2855 return SOCKET_ERROR;
2858 /***********************************************************************
2859 * sendto (WS2_32.20)
2861 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
2862 const struct WS_sockaddr *to, int tolen)
2868 wsabuf.buf = (char*) buf;
2870 if ( WSASendTo(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
2871 return SOCKET_ERROR;
2876 /***********************************************************************
2877 * setsockopt (WS2_32.21)
2879 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
2880 const char *optval, int optlen)
2884 struct linger linger;
2885 struct timeval tval;
2887 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2888 s, level, optname, optval, optlen);
2890 /* some broken apps pass the value directly instead of a pointer to it */
2891 if(IS_INTRESOURCE(optval))
2893 SetLastError(WSAEFAULT);
2894 return SOCKET_ERROR;
2902 /* Some options need some conversion before they can be sent to
2903 * setsockopt. The conversions are done here, then they will fall though
2904 * to the general case. Special options that are not passed to
2905 * setsockopt follow below that.*/
2907 case WS_SO_DONTLINGER:
2908 linger.l_onoff = *((const int*)optval) ? 0: 1;
2909 linger.l_linger = 0;
2911 optname = SO_LINGER;
2912 optval = (char*)&linger;
2913 optlen = sizeof(struct linger);
2917 linger.l_onoff = ((LINGER*)optval)->l_onoff;
2918 linger.l_linger = ((LINGER*)optval)->l_linger;
2919 /* FIXME: what is documented behavior if SO_LINGER optval
2922 optname = SO_LINGER;
2923 optval = (char*)&linger;
2924 optlen = sizeof(struct linger);
2928 if (*(const int*)optval < 2048)
2930 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
2935 /* The options listed here don't need any special handling. Thanks to
2936 * the conversion happening above, options from there will fall through
2938 case WS_SO_ACCEPTCONN:
2939 case WS_SO_BROADCAST:
2941 case WS_SO_KEEPALIVE:
2942 case WS_SO_OOBINLINE:
2943 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
2944 * however, using it the BSD way fixes bug 8513 and seems to be what
2945 * most programmers assume, anyway */
2946 case WS_SO_REUSEADDR:
2949 convert_sockopt(&level, &optname);
2952 /* SO_DEBUG is a privileged operation, ignore it. */
2954 TRACE("Ignoring SO_DEBUG\n");
2957 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
2958 * socket. According to MSDN, this option is silently ignored.*/
2959 case WS_SO_DONTROUTE:
2960 TRACE("Ignoring SO_DONTROUTE\n");
2963 /* Stops two sockets from being bound to the same port. Always happens
2964 * on unix systems, so just drop it. */
2965 case WS_SO_EXCLUSIVEADDRUSE:
2966 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
2969 /* SO_OPENTYPE does not require a valid socket handle. */
2970 case WS_SO_OPENTYPE:
2971 if (!optlen || optlen < sizeof(int) || !optval)
2973 SetLastError(WSAEFAULT);
2974 return SOCKET_ERROR;
2976 get_per_thread_data()->opentype = *(const int *)optval;
2977 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2981 case WS_SO_RCVTIMEO:
2984 case WS_SO_SNDTIMEO:
2986 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
2987 if (optval && optlen == sizeof(UINT32)) {
2988 /* WinSock passes milliseconds instead of struct timeval */
2989 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
2990 tval.tv_sec = *(const UINT32*)optval / 1000;
2991 /* min of 500 milliseconds */
2992 if (tval.tv_sec == 0 && tval.tv_usec < 500000)
2993 tval.tv_usec = 500000;
2994 optlen = sizeof(struct timeval);
2995 optval = (char*)&tval;
2996 } else if (optlen == sizeof(struct timeval)) {
2997 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
2999 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
3002 convert_sockopt(&level, &optname);
3007 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3008 SetLastError(WSAENOPROTOOPT);
3009 return SOCKET_ERROR;
3011 break; /* case WS_SOL_SOCKET */
3018 fd = get_sock_fd( s, 0, NULL );
3019 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
3021 /* We try to set the ipx type on ipx socket level. */
3023 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
3025 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
3026 release_sock_fd( s, fd );
3027 return SOCKET_ERROR;
3032 /* Should we retrieve val using a getsockopt call and then
3033 * set the modified one? */
3034 val.ipx_pt = *optval;
3035 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
3038 release_sock_fd( s, fd );
3041 case IPX_FILTERPTYPE:
3042 /* Sets the receive filter packet type, at the moment we don't support it */
3043 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
3044 /* Returning 0 is better for now than returning a SOCKET_ERROR */
3048 FIXME("opt_name:%x\n", optname);
3049 return SOCKET_ERROR;
3051 break; /* case NSPROTO_IPX */
3054 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3055 case WS_IPPROTO_TCP:
3058 case WS_TCP_NODELAY:
3059 convert_sockopt(&level, &optname);
3062 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3063 return SOCKET_ERROR;
3070 case WS_IP_ADD_MEMBERSHIP:
3071 case WS_IP_DROP_MEMBERSHIP:
3075 case WS_IP_MULTICAST_IF:
3076 case WS_IP_MULTICAST_LOOP:
3077 case WS_IP_MULTICAST_TTL:
3081 convert_sockopt(&level, &optname);
3083 case WS_IP_DONTFRAGMENT:
3084 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
3087 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3088 return SOCKET_ERROR;
3093 FIXME("Unknown level: 0x%08x\n", level);
3094 return SOCKET_ERROR;
3095 } /* end switch(level) */
3097 /* avoid endianness issues if argument is a 16-bit int */
3098 if (optval && optlen < sizeof(int))
3100 woptval= *((const INT16 *) optval);
3101 optval= (char*) &woptval;
3104 fd = get_sock_fd( s, 0, NULL );
3105 if (fd == -1) return SOCKET_ERROR;
3107 if (setsockopt(fd, level, optname, optval, optlen) == 0)
3109 release_sock_fd( s, fd );
3112 TRACE("Setting socket error, %d\n", wsaErrno());
3113 SetLastError(wsaErrno());
3114 release_sock_fd( s, fd );
3116 return SOCKET_ERROR;
3119 /***********************************************************************
3120 * shutdown (WS2_32.22)
3122 int WINAPI WS_shutdown(SOCKET s, int how)
3124 int fd, err = WSAENOTSOCK;
3125 unsigned int options, clear_flags = 0;
3127 fd = get_sock_fd( s, 0, &options );
3128 TRACE("socket %04lx, how %i %x\n", s, how, options );
3131 return SOCKET_ERROR;
3135 case 0: /* drop receives */
3136 clear_flags |= FD_READ;
3138 case 1: /* drop sends */
3139 clear_flags |= FD_WRITE;
3141 case 2: /* drop all */
3142 clear_flags |= FD_READ|FD_WRITE;
3144 clear_flags |= FD_WINE_LISTENING;
3147 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3152 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3155 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3159 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3160 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3163 if (err) goto error;
3165 else /* non-overlapped mode */
3167 if ( shutdown( fd, how ) )
3174 release_sock_fd( s, fd );
3175 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3176 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
3180 release_sock_fd( s, fd );
3181 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3182 WSASetLastError( err );
3183 return SOCKET_ERROR;
3186 /***********************************************************************
3187 * socket (WS2_32.23)
3189 SOCKET WINAPI WS_socket(int af, int type, int protocol)
3191 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
3193 return WSASocketA( af, type, protocol, NULL, 0,
3194 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
3198 /***********************************************************************
3199 * gethostbyaddr (WS2_32.51)
3201 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
3203 struct WS_hostent *retval = NULL;
3204 struct hostent* host;
3206 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3209 struct hostent hostentry;
3212 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3214 int res = gethostbyaddr_r(addr, len, type,
3215 &hostentry, extrabuf, ebufsize, &host, &locerr);
3216 if( res != ERANGE) break;
3218 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3220 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3222 EnterCriticalSection( &csWSgetXXXbyYYY );
3223 host = gethostbyaddr(addr, len, type);
3224 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3226 if( host != NULL ) retval = WS_dup_he(host);
3227 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3228 HeapFree(GetProcessHeap(),0,extrabuf);
3230 LeaveCriticalSection( &csWSgetXXXbyYYY );
3232 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
3236 /***********************************************************************
3237 * gethostbyname (WS2_32.52)
3239 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
3241 struct WS_hostent *retval = NULL;
3242 struct hostent* host;
3243 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3246 struct hostent hostentry;
3247 int locerr = ENOBUFS;
3250 if( !name || !name[0]) {
3252 if( gethostname( buf, 100) == -1) {
3253 SetLastError( WSAENOBUFS); /* appropriate ? */
3257 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3259 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3261 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
3262 if( res != ERANGE) break;
3264 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3266 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3268 EnterCriticalSection( &csWSgetXXXbyYYY );
3269 host = gethostbyname(name);
3270 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3272 if (host) retval = WS_dup_he(host);
3273 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3274 HeapFree(GetProcessHeap(),0,extrabuf);
3276 LeaveCriticalSection( &csWSgetXXXbyYYY );
3278 if (retval && retval->h_addr_list[0][0] == 127 &&
3279 strcmp(name, "localhost") != 0)
3281 /* hostname != "localhost" but has loopback address. replace by our
3282 * special address.*/
3283 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
3285 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3290 /***********************************************************************
3291 * getprotobyname (WS2_32.53)
3293 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3295 struct WS_protoent* retval = NULL;
3296 #ifdef HAVE_GETPROTOBYNAME
3297 struct protoent* proto;
3298 EnterCriticalSection( &csWSgetXXXbyYYY );
3299 if( (proto = getprotobyname(name)) != NULL )
3301 retval = WS_dup_pe(proto);
3304 MESSAGE("protocol %s not found; You might want to add "
3305 "this to /etc/protocols\n", debugstr_a(name) );
3306 SetLastError(WSANO_DATA);
3308 LeaveCriticalSection( &csWSgetXXXbyYYY );
3310 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3315 /***********************************************************************
3316 * getprotobynumber (WS2_32.54)
3318 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3320 struct WS_protoent* retval = NULL;
3321 #ifdef HAVE_GETPROTOBYNUMBER
3322 struct protoent* proto;
3323 EnterCriticalSection( &csWSgetXXXbyYYY );
3324 if( (proto = getprotobynumber(number)) != NULL )
3326 retval = WS_dup_pe(proto);
3329 MESSAGE("protocol number %d not found; You might want to add "
3330 "this to /etc/protocols\n", number );
3331 SetLastError(WSANO_DATA);
3333 LeaveCriticalSection( &csWSgetXXXbyYYY );
3335 TRACE("%i ret %p\n", number, retval);
3340 /***********************************************************************
3341 * getservbyname (WS2_32.55)
3343 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3345 struct WS_servent* retval = NULL;
3346 struct servent* serv;
3348 char *proto_str = NULL;
3350 if (!(name_str = strdup_lower(name))) return NULL;
3352 if (proto && *proto)
3354 if (!(proto_str = strdup_lower(proto)))
3356 HeapFree( GetProcessHeap(), 0, name_str );
3361 EnterCriticalSection( &csWSgetXXXbyYYY );
3362 serv = getservbyname(name_str, proto_str);
3365 retval = WS_dup_se(serv);
3367 else SetLastError(WSANO_DATA);
3368 LeaveCriticalSection( &csWSgetXXXbyYYY );
3369 HeapFree( GetProcessHeap(), 0, proto_str );
3370 HeapFree( GetProcessHeap(), 0, name_str );
3371 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
3375 /***********************************************************************
3376 * freeaddrinfo (WS2_32.@)
3378 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
3381 struct WS_addrinfo *next;
3383 HeapFree(GetProcessHeap(),0,res->ai_canonname);
3384 HeapFree(GetProcessHeap(),0,res->ai_addr);
3385 next = res->ai_next;
3386 HeapFree(GetProcessHeap(),0,res);
3391 /* helper functions for getaddrinfo()/getnameinfo() */
3392 static int convert_aiflag_w2u(int winflags) {
3393 int i, unixflags = 0;
3395 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3396 if (ws_aiflag_map[i][0] & winflags) {
3397 unixflags |= ws_aiflag_map[i][1];
3398 winflags &= ~ws_aiflag_map[i][0];
3401 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
3405 static int convert_niflag_w2u(int winflags) {
3406 int i, unixflags = 0;
3408 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
3409 if (ws_niflag_map[i][0] & winflags) {
3410 unixflags |= ws_niflag_map[i][1];
3411 winflags &= ~ws_niflag_map[i][0];
3414 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
3418 static int convert_aiflag_u2w(int unixflags) {
3419 int i, winflags = 0;
3421 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3422 if (ws_aiflag_map[i][1] & unixflags) {
3423 winflags |= ws_aiflag_map[i][0];
3424 unixflags &= ~ws_aiflag_map[i][1];
3426 if (unixflags) /* will warn usually */
3427 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
3431 static int convert_eai_u2w(int unixret) {
3434 for (i=0;ws_eai_map[i][0];i++)
3435 if (ws_eai_map[i][1] == unixret)
3436 return ws_eai_map[i][0];
3440 /***********************************************************************
3441 * getaddrinfo (WS2_32.@)
3443 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
3445 #ifdef HAVE_GETADDRINFO
3446 struct addrinfo *unixaires = NULL;
3448 struct addrinfo unixhints, *punixhints = NULL;
3449 CHAR *node = NULL, *serv = NULL;
3452 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
3455 if (!(serv = strdup_lower(servname))) {
3456 HeapFree(GetProcessHeap(), 0, node);
3457 return WSA_NOT_ENOUGH_MEMORY;
3462 punixhints = &unixhints;
3464 memset(&unixhints, 0, sizeof(unixhints));
3465 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
3466 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
3467 punixhints->ai_family = 0;
3469 punixhints->ai_family = convert_af_w2u(hints->ai_family);
3470 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
3471 punixhints->ai_socktype = 0;
3473 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
3474 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
3475 punixhints->ai_protocol = 0;
3477 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
3480 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
3481 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
3483 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
3485 HeapFree(GetProcessHeap(), 0, node);
3486 HeapFree(GetProcessHeap(), 0, serv);
3489 struct addrinfo *xuai = unixaires;
3490 struct WS_addrinfo **xai = res;
3494 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
3500 *xai = ai;xai = &ai->ai_next;
3501 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
3502 ai->ai_family = convert_af_u2w(xuai->ai_family);
3503 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
3504 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
3505 if (xuai->ai_canonname) {
3506 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
3507 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
3508 if (!ai->ai_canonname)
3510 strcpy(ai->ai_canonname,xuai->ai_canonname);
3512 len = xuai->ai_addrlen;
3513 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
3516 ai->ai_addrlen = len;
3518 int winlen = ai->ai_addrlen;
3520 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
3521 ai->ai_addrlen = winlen;
3525 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
3528 ai->ai_addrlen = len;
3530 xuai = xuai->ai_next;
3532 freeaddrinfo(unixaires);
3534 result = convert_eai_u2w(result);
3540 if (*res) WS_freeaddrinfo(*res);
3541 if (unixaires) freeaddrinfo(unixaires);
3543 return WSA_NOT_ENOUGH_MEMORY;
3545 FIXME("getaddrinfo() failed, not found during buildtime.\n");
3550 /***********************************************************************
3551 * GetAddrInfoW (WS2_32.@)
3553 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
3555 FIXME("empty stub!\n");
3559 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
3560 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
3562 #ifdef HAVE_GETNAMEINFO
3564 union generic_unix_sockaddr sa_u;
3567 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
3568 serv, servlen, flags);
3570 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
3573 WSASetLastError(WSAEFAULT);
3574 return WSA_NOT_ENOUGH_MEMORY;
3576 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
3577 return convert_eai_u2w(ret);
3579 FIXME("getnameinfo() failed, not found during buildtime.\n");
3584 /***********************************************************************
3585 * getservbyport (WS2_32.56)
3587 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
3589 struct WS_servent* retval = NULL;
3590 #ifdef HAVE_GETSERVBYPORT
3591 struct servent* serv;
3592 char *proto_str = NULL;
3594 if (proto && *proto)
3596 if (!(proto_str = strdup_lower(proto))) return NULL;
3598 EnterCriticalSection( &csWSgetXXXbyYYY );
3599 if( (serv = getservbyport(port, proto_str)) != NULL ) {
3600 retval = WS_dup_se(serv);
3602 else SetLastError(WSANO_DATA);
3603 LeaveCriticalSection( &csWSgetXXXbyYYY );
3604 HeapFree( GetProcessHeap(), 0, proto_str );
3606 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
3611 /***********************************************************************
3612 * gethostname (WS2_32.57)
3614 int WINAPI WS_gethostname(char *name, int namelen)
3616 TRACE("name %p, len %d\n", name, namelen);
3618 if (gethostname(name, namelen) == 0)
3620 TRACE("<- '%s'\n", name);
3623 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
3624 TRACE("<- ERROR !\n");
3625 return SOCKET_ERROR;
3629 /* ------------------------------------- Windows sockets extensions -- *
3631 * ------------------------------------------------------------------- */
3633 /***********************************************************************
3634 * WSAEnumNetworkEvents (WS2_32.36)
3636 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
3640 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
3642 SERVER_START_REQ( get_socket_event )
3644 req->handle = SOCKET2HANDLE(s);
3645 req->service = TRUE;
3646 req->c_event = hEvent;
3647 wine_server_set_reply( req, lpEvent->iErrorCode, sizeof(lpEvent->iErrorCode) );
3648 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
3652 SetLastError(WSAEINVAL);
3653 return SOCKET_ERROR;
3656 /***********************************************************************
3657 * WSAEventSelect (WS2_32.39)
3659 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
3663 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
3665 SERVER_START_REQ( set_socket_event )
3667 req->handle = SOCKET2HANDLE(s);
3669 req->event = hEvent;
3672 ret = wine_server_call( req );
3676 SetLastError(WSAEINVAL);
3677 return SOCKET_ERROR;
3680 /**********************************************************************
3681 * WSAGetOverlappedResult (WS2_32.40)
3683 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
3684 LPDWORD lpcbTransfer, BOOL fWait,
3689 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
3690 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
3692 if ( lpOverlapped == NULL )
3694 ERR( "Invalid pointer\n" );
3695 WSASetLastError(WSA_INVALID_PARAMETER);
3699 status = lpOverlapped->Internal;
3700 if (status == STATUS_PENDING)
3704 SetLastError( WSA_IO_INCOMPLETE );
3708 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
3709 INFINITE ) == WAIT_FAILED)
3711 status = lpOverlapped->Internal;
3715 *lpcbTransfer = lpOverlapped->InternalHigh;
3718 *lpdwFlags = lpOverlapped->u.s.Offset;
3720 if (status) SetLastError( RtlNtStatusToDosError(status) );
3725 /***********************************************************************
3726 * WSAAsyncSelect (WS2_32.101)
3728 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
3732 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
3734 SERVER_START_REQ( set_socket_event )
3736 req->handle = SOCKET2HANDLE(s);
3741 ret = wine_server_call( req );
3745 SetLastError(WSAEINVAL);
3746 return SOCKET_ERROR;
3749 /***********************************************************************
3750 * WSACreateEvent (WS2_32.31)
3753 WSAEVENT WINAPI WSACreateEvent(void)
3755 /* Create a manual-reset event, with initial state: unsignaled */
3758 return CreateEventW(NULL, TRUE, FALSE, NULL);
3761 /***********************************************************************
3762 * WSACloseEvent (WS2_32.29)
3765 BOOL WINAPI WSACloseEvent(WSAEVENT event)
3767 TRACE ("event=%p\n", event);
3769 return CloseHandle(event);
3772 /***********************************************************************
3773 * WSASocketA (WS2_32.78)
3776 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
3777 LPWSAPROTOCOL_INFOA lpProtocolInfo,
3778 GROUP g, DWORD dwFlags)
3781 WSAPROTOCOL_INFOW info;
3783 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
3784 af, type, protocol, lpProtocolInfo, g, dwFlags);
3786 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
3788 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
3789 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
3790 info.szProtocol, WSAPROTOCOL_LEN + 1);
3794 WSASetLastError( WSAEINVAL);
3795 return SOCKET_ERROR;
3798 return WSASocketW(af, type, protocol, &info, g, dwFlags);
3801 /***********************************************************************
3802 * WSASocketW (WS2_32.79)
3805 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
3806 LPWSAPROTOCOL_INFOW lpProtocolInfo,
3807 GROUP g, DWORD dwFlags)
3812 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
3813 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
3816 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
3817 af, type, protocol, lpProtocolInfo, g, dwFlags );
3819 /* hack for WSADuplicateSocket */
3820 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
3821 ret = lpProtocolInfo->dwCatalogEntryId;
3822 TRACE("\tgot duplicate %04lx\n", ret);
3826 /* convert the socket family and type */
3827 af = convert_af_w2u(af);
3828 type = convert_socktype_w2u(type);
3832 if (af == FROM_PROTOCOL_INFO)
3833 af = lpProtocolInfo->iAddressFamily;
3834 if (type == FROM_PROTOCOL_INFO)
3835 type = lpProtocolInfo->iSocketType;
3836 if (protocol == FROM_PROTOCOL_INFO)
3837 protocol = lpProtocolInfo->iProtocol;
3840 if ( af == AF_UNSPEC) /* did they not specify the address family? */
3844 if (type == SOCK_STREAM) { af = AF_INET; break; }
3846 if (type == SOCK_DGRAM) { af = AF_INET; break; }
3847 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
3850 SERVER_START_REQ( create_socket )
3854 req->protocol = protocol;
3855 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
3856 req->attributes = OBJ_INHERIT;
3857 req->flags = dwFlags;
3858 set_error( wine_server_call( req ) );
3859 ret = HANDLE2SOCKET( reply->handle );
3864 TRACE("\tcreated %04lx\n", ret );
3868 if (GetLastError() == WSAEACCES) /* raw socket denied */
3870 if (type == SOCK_RAW)
3871 MESSAGE("WARNING: Trying to create a socket of type SOCK_RAW, this"
3872 " will fail unless you have special permissions.\n");
3874 MESSAGE("WS_SOCKET: Failed to create socket, this requires"
3875 " special permissions.\n");
3876 SetLastError(WSAESOCKTNOSUPPORT);
3879 WARN("\t\tfailed!\n");
3880 return INVALID_SOCKET;
3883 /***********************************************************************
3884 * WSAJoinLeaf (WS2_32.58)
3887 SOCKET WINAPI WSAJoinLeaf(
3889 const struct WS_sockaddr *addr,
3891 LPWSABUF lpCallerData,
3892 LPWSABUF lpCalleeData,
3898 return INVALID_SOCKET;
3901 /***********************************************************************
3902 * __WSAFDIsSet (WS2_32.151)
3904 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
3906 int i = set->fd_count;
3908 TRACE("(%ld,%p(%i))\n", s, set, i);
3911 if (set->fd_array[i] == s) return 1;
3915 /***********************************************************************
3916 * WSAIsBlocking (WINSOCK.114)
3917 * WSAIsBlocking (WS2_32.114)
3919 BOOL WINAPI WSAIsBlocking(void)
3921 /* By default WinSock should set all its sockets to non-blocking mode
3922 * and poll in PeekMessage loop when processing "blocking" ones. This
3923 * function is supposed to tell if the program is in this loop. Our
3924 * blocking calls are truly blocking so we always return FALSE.
3926 * Note: It is allowed to call this function without prior WSAStartup().
3933 /***********************************************************************
3934 * WSACancelBlockingCall (WINSOCK.113)
3935 * WSACancelBlockingCall (WS2_32.113)
3937 INT WINAPI WSACancelBlockingCall(void)
3943 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
3945 FIXME("How was this called?\n");
3950 /***********************************************************************
3951 * WSASetBlockingHook (WS2_32.109)
3953 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
3955 FARPROC prev = blocking_hook;
3956 blocking_hook = lpBlockFunc;
3957 TRACE("hook %p\n", lpBlockFunc);
3962 /***********************************************************************
3963 * WSAUnhookBlockingHook (WS2_32.110)
3965 INT WINAPI WSAUnhookBlockingHook(void)
3967 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
3972 /* ----------------------------------- end of API stuff */
3974 /* ----------------------------------- helper functions -
3976 * TODO: Merge WS_dup_..() stuff into one function that
3977 * would operate with a generic structure containing internal
3978 * pointers (via a template of some kind).
3981 static int list_size(char** l, int item_size)
3986 j += (item_size) ? item_size : strlen(l[i]) + 1;
3987 j += (i + 1) * sizeof(char*); }
3991 static int list_dup(char** l_src, char** l_to, int item_size)
3996 for (i = 0; l_src[i]; i++) ;
3997 p = (char *)(l_to + i + 1);
3998 for (i = 0; l_src[i]; i++)
4000 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
4001 memcpy(p, l_src[i], count);
4006 return p - (char *)l_to;
4011 /* duplicate hostent entry
4012 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
4013 * Ditto for protoent and servent.
4015 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
4018 struct WS_hostent *p_to;
4020 int size = (sizeof(*p_he) +
4021 strlen(p_he->h_name) + 1 +
4022 list_size(p_he->h_aliases, 0) +
4023 list_size(p_he->h_addr_list, p_he->h_length));
4025 if (!(p_to = check_buffer_he(size))) return NULL;
4026 p_to->h_addrtype = p_he->h_addrtype;
4027 p_to->h_length = p_he->h_length;
4029 p = (char *)(p_to + 1);
4031 strcpy(p, p_he->h_name);
4034 p_to->h_aliases = (char **)p;
4035 p += list_dup(p_he->h_aliases, p_to->h_aliases, 0);
4037 p_to->h_addr_list = (char **)p;
4038 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
4042 /* ----- protoent */
4044 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
4047 struct WS_protoent *p_to;
4049 int size = (sizeof(*p_pe) +
4050 strlen(p_pe->p_name) + 1 +
4051 list_size(p_pe->p_aliases, 0));
4053 if (!(p_to = check_buffer_pe(size))) return NULL;
4054 p_to->p_proto = p_pe->p_proto;
4056 p = (char *)(p_to + 1);
4058 strcpy(p, p_pe->p_name);
4061 p_to->p_aliases = (char **)p;
4062 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
4068 static struct WS_servent *WS_dup_se(const struct servent* p_se)
4071 struct WS_servent *p_to;
4073 int size = (sizeof(*p_se) +
4074 strlen(p_se->s_proto) + 1 +
4075 strlen(p_se->s_name) + 1 +
4076 list_size(p_se->s_aliases, 0));
4078 if (!(p_to = check_buffer_se(size))) return NULL;
4079 p_to->s_port = p_se->s_port;
4081 p = (char *)(p_to + 1);
4083 strcpy(p, p_se->s_name);
4087 strcpy(p, p_se->s_proto);
4090 p_to->s_aliases = (char **)p;
4091 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
4095 /* ----------------------------------- error handling */
4099 int loc_errno = errno;
4100 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
4104 case EINTR: return WSAEINTR;
4105 case EBADF: return WSAEBADF;
4107 case EACCES: return WSAEACCES;
4108 case EFAULT: return WSAEFAULT;
4109 case EINVAL: return WSAEINVAL;
4110 case EMFILE: return WSAEMFILE;
4111 case EWOULDBLOCK: return WSAEWOULDBLOCK;
4112 case EINPROGRESS: return WSAEINPROGRESS;
4113 case EALREADY: return WSAEALREADY;
4114 case ENOTSOCK: return WSAENOTSOCK;
4115 case EDESTADDRREQ: return WSAEDESTADDRREQ;
4116 case EMSGSIZE: return WSAEMSGSIZE;
4117 case EPROTOTYPE: return WSAEPROTOTYPE;
4118 case ENOPROTOOPT: return WSAENOPROTOOPT;
4119 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
4120 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
4121 case EOPNOTSUPP: return WSAEOPNOTSUPP;
4122 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
4123 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
4124 case EADDRINUSE: return WSAEADDRINUSE;
4125 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
4126 case ENETDOWN: return WSAENETDOWN;
4127 case ENETUNREACH: return WSAENETUNREACH;
4128 case ENETRESET: return WSAENETRESET;
4129 case ECONNABORTED: return WSAECONNABORTED;
4131 case ECONNRESET: return WSAECONNRESET;
4132 case ENOBUFS: return WSAENOBUFS;
4133 case EISCONN: return WSAEISCONN;
4134 case ENOTCONN: return WSAENOTCONN;
4135 case ESHUTDOWN: return WSAESHUTDOWN;
4136 case ETOOMANYREFS: return WSAETOOMANYREFS;
4137 case ETIMEDOUT: return WSAETIMEDOUT;
4138 case ECONNREFUSED: return WSAECONNREFUSED;
4139 case ELOOP: return WSAELOOP;
4140 case ENAMETOOLONG: return WSAENAMETOOLONG;
4141 case EHOSTDOWN: return WSAEHOSTDOWN;
4142 case EHOSTUNREACH: return WSAEHOSTUNREACH;
4143 case ENOTEMPTY: return WSAENOTEMPTY;
4145 case EPROCLIM: return WSAEPROCLIM;
4148 case EUSERS: return WSAEUSERS;
4151 case EDQUOT: return WSAEDQUOT;
4154 case ESTALE: return WSAESTALE;
4157 case EREMOTE: return WSAEREMOTE;
4160 /* just in case we ever get here and there are no problems */
4163 WARN("Unknown errno %d!\n", loc_errno);
4164 return WSAEOPNOTSUPP;
4168 UINT wsaHerrno(int loc_errno)
4171 WARN("h_errno %d.\n", loc_errno);
4175 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
4176 case TRY_AGAIN: return WSATRY_AGAIN;
4177 case NO_RECOVERY: return WSANO_RECOVERY;
4178 case NO_DATA: return WSANO_DATA;
4179 case ENOBUFS: return WSAENOBUFS;
4183 WARN("Unknown h_errno %d!\n", loc_errno);
4184 return WSAEOPNOTSUPP;
4189 /***********************************************************************
4190 * WSARecv (WS2_32.67)
4192 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4193 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
4194 LPWSAOVERLAPPED lpOverlapped,
4195 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
4197 return WSARecvFrom(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
4198 NULL, NULL, lpOverlapped, lpCompletionRoutine);
4201 /***********************************************************************
4202 * WSARecvFrom (WS2_32.69)
4204 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4205 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
4206 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
4207 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4210 unsigned int i, options;
4212 DWORD timeout_start = GetTickCount();
4213 struct iovec iovec[WS_MSG_MAXIOVLEN];
4214 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4216 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
4217 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
4218 (lpFromlen ? *lpFromlen : -1),
4219 lpOverlapped, lpCompletionRoutine);
4221 if (dwBufferCount > WS_MSG_MAXIOVLEN)
4223 WSASetLastError( WSAEINVAL );
4224 return SOCKET_ERROR;
4227 fd = get_sock_fd( s, FILE_READ_DATA, &options );
4228 TRACE( "fd=%d, options=%x\n", fd, options );
4230 if (fd == -1) return SOCKET_ERROR;
4232 for (i = 0; i < dwBufferCount; i++)
4234 iovec[i].iov_base = lpBuffers[i].buf;
4235 iovec[i].iov_len = lpBuffers[i].len;
4240 n = WS2_recv( fd, iovec, dwBufferCount, lpFrom, lpFromlen, lpFlags );
4243 if (errno == EINTR) continue;
4244 if (errno != EAGAIN)
4247 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
4252 *lpNumberOfBytesRecvd = n;
4254 if ((lpOverlapped || lpCompletionRoutine) &&
4255 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4257 IO_STATUS_BLOCK *iosb;
4258 struct ws2_async *wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
4265 release_sock_fd( s, fd );
4267 wsa->hSocket = SOCKET2HANDLE(s);
4268 wsa->flags = *lpFlags;
4270 wsa->addrlen.ptr = lpFromlen;
4271 wsa->user_overlapped = lpOverlapped;
4272 wsa->completion_func = lpCompletionRoutine;
4273 wsa->n_iovecs = dwBufferCount;
4274 memcpy( wsa->iovec, iovec, dwBufferCount * sizeof(*iovec) );
4276 iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4280 iosb->u.Status = STATUS_PENDING;
4281 iosb->Information = 0;
4283 SERVER_START_REQ( register_async )
4285 req->handle = wsa->hSocket;
4286 req->type = ASYNC_TYPE_READ;
4287 req->async.callback = WS2_async_recv;
4288 req->async.iosb = iosb;
4289 req->async.arg = wsa;
4290 req->async.apc = ws2_async_apc;
4291 req->async.event = lpCompletionRoutine ? 0 : lpOverlapped->hEvent;
4292 req->async.cvalue = cvalue;
4293 err = wine_server_call( req );
4297 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4298 WSASetLastError( NtStatusToWSAError( err ));
4299 return SOCKET_ERROR;
4302 iosb->u.Status = STATUS_SUCCESS;
4303 iosb->Information = n;
4304 if (!wsa->completion_func)
4306 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4307 SetEvent( lpOverlapped->hEvent );
4308 HeapFree( GetProcessHeap(), 0, wsa );
4310 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4311 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4312 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4318 if ( _is_blocking(s) )
4321 int timeout = GET_RCVTIMEO(fd);
4324 timeout -= GetTickCount() - timeout_start;
4325 if (timeout < 0) timeout = 0;
4329 pfd.events = POLLIN;
4330 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
4332 if (!timeout || !poll( &pfd, 1, timeout ))
4335 /* a timeout is not fatal */
4336 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4342 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4343 err = WSAEWOULDBLOCK;
4348 TRACE(" -> %i bytes\n", n);
4349 release_sock_fd( s, fd );
4350 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4355 release_sock_fd( s, fd );
4356 WARN(" -> ERROR %d\n", err);
4357 WSASetLastError( err );
4358 return SOCKET_ERROR;
4361 /***********************************************************************
4362 * WSCInstallProvider (WS2_32.88)
4364 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
4365 LPCWSTR lpszProviderDllPath,
4366 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
4367 DWORD dwNumberOfEntries,
4370 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
4371 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
4372 dwNumberOfEntries, lpErrno);
4378 /***********************************************************************
4379 * WSCDeinstallProvider (WS2_32.83)
4381 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
4383 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
4389 /***********************************************************************
4390 * WSAAccept (WS2_32.26)
4392 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
4393 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
4396 int ret = 0, size = 0;
4397 WSABUF CallerId, CallerData, CalleeId, CalleeData;
4398 /* QOS SQOS, GQOS; */
4401 SOCKADDR src_addr, dst_addr;
4403 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %d\n",
4404 s, addr, addrlen, lpfnCondition, dwCallbackData);
4407 size = sizeof(src_addr);
4408 cs = WS_accept(s, &src_addr, &size);
4410 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
4412 CallerId.buf = (char *)&src_addr;
4413 CallerId.len = sizeof(src_addr);
4415 CallerData.buf = NULL;
4416 CallerData.len = (ULONG)NULL;
4418 WS_getsockname(cs, &dst_addr, &size);
4420 CalleeId.buf = (char *)&dst_addr;
4421 CalleeId.len = sizeof(dst_addr);
4424 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
4425 &CalleeId, &CalleeData, &g, dwCallbackData);
4430 if (addr && addrlen)
4431 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
4434 SERVER_START_REQ( set_socket_deferred )
4436 req->handle = SOCKET2HANDLE(s);
4437 req->deferred = SOCKET2HANDLE(cs);
4438 if ( !wine_server_call_err ( req ) )
4440 SetLastError( WSATRY_AGAIN );
4441 WS_closesocket( cs );
4445 return SOCKET_ERROR;
4448 SetLastError(WSAECONNREFUSED);
4449 return SOCKET_ERROR;
4451 FIXME("Unknown return type from Condition function\n");
4452 SetLastError(WSAENOTSOCK);
4453 return SOCKET_ERROR;
4457 /***********************************************************************
4458 * WSADuplicateSocketA (WS2_32.32)
4460 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
4464 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4465 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4466 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
4467 /* I don't know what the real Windoze does next, this is a hack */
4468 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
4469 * the target use the global duplicate, or we could copy a reference to us to the structure
4470 * and let the target duplicate it from us, but let's do it as simple as possible */
4471 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4472 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4473 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4474 0, FALSE, DUPLICATE_SAME_ACCESS);
4475 CloseHandle(hProcess);
4476 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4480 /***********************************************************************
4481 * WSADuplicateSocketW (WS2_32.33)
4483 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
4487 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4489 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4490 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4491 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4492 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4493 0, FALSE, DUPLICATE_SAME_ACCESS);
4494 CloseHandle(hProcess);
4495 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4499 /***********************************************************************
4500 * WSAInstallServiceClassA (WS2_32.48)
4502 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
4504 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
4505 WSASetLastError(WSAEACCES);
4506 return SOCKET_ERROR;
4509 /***********************************************************************
4510 * WSAInstallServiceClassW (WS2_32.49)
4512 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
4514 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
4515 WSASetLastError(WSAEACCES);
4516 return SOCKET_ERROR;
4519 /***********************************************************************
4520 * WSARemoveServiceClass (WS2_32.70)
4522 int WINAPI WSARemoveServiceClass(LPGUID info)
4524 FIXME("Request to remove service %p\n",info);
4525 WSASetLastError(WSATYPE_NOT_FOUND);
4526 return SOCKET_ERROR;
4529 /***********************************************************************
4530 * WSAStringToAddressA (WS2_32.80)
4532 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
4534 LPWSAPROTOCOL_INFOA lpProtocolInfo,
4535 LPSOCKADDR lpAddress,
4536 LPINT lpAddressLength)
4539 LPSTR workBuffer=NULL,ptrPort;
4541 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
4542 lpProtocolInfo, lpAddress, lpAddressLength );
4544 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
4548 WSASetLastError(WSAEINVAL);
4549 return SOCKET_ERROR;
4553 FIXME("ProtocolInfo not implemented.\n");
4555 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
4556 strlen(AddressString) + 1);
4559 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4560 return SOCKET_ERROR;
4563 strcpy(workBuffer, AddressString);
4565 switch(AddressFamily)
4569 struct in_addr inetaddr;
4571 /* If lpAddressLength is too small, tell caller the size we need */
4572 if (*lpAddressLength < sizeof(SOCKADDR_IN))
4574 *lpAddressLength = sizeof(SOCKADDR_IN);
4578 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
4580 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
4582 ptrPort = strchr(workBuffer, ':');
4585 ((LPSOCKADDR_IN)lpAddress)->sin_port = (WS_u_short)atoi(ptrPort+1);
4590 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
4593 if(inet_aton(workBuffer, &inetaddr) > 0)
4595 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
4606 struct in6_addr inetaddr;
4607 /* If lpAddressLength is too small, tell caller the size we need */
4608 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
4610 *lpAddressLength = sizeof(SOCKADDR_IN6);
4614 #ifdef HAVE_INET_PTON
4615 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
4617 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
4619 /* This one is a bit tricky. An IPv6 address contains colons, so the
4620 * check from IPv4 doesn't work like that. However, IPv6 addresses that
4621 * contain a port are written with braces like [fd12:3456:7890::1]:12345
4622 * so what we will do is to look for ']', check if the next char is a
4623 * colon, and if it is, parse the port as in IPv4. */
4625 ptrPort = strchr(workBuffer, ']');
4626 if(ptrPort && *(++ptrPort) == ':')
4628 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = (WS_u_short)atoi(ptrPort+1);
4633 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
4636 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
4638 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
4639 sizeof(struct in6_addr));
4643 #endif /* HAVE_INET_PTON */
4649 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
4650 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
4654 HeapFree(GetProcessHeap(), 0, workBuffer);
4657 WSASetLastError(res);
4658 return SOCKET_ERROR;
4661 /***********************************************************************
4662 * WSAStringToAddressW (WS2_32.81)
4664 * Does anybody know if this functions allows to use hebrew/arabic/chinese... digits?
4665 * If this should be the case, it would be required to map these digits
4666 * to Unicode digits (0-9) using FoldString first.
4668 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
4670 LPWSAPROTOCOL_INFOW lpProtocolInfo,
4671 LPSOCKADDR lpAddress,
4672 LPINT lpAddressLength)
4675 LPSTR workBuffer=NULL;
4676 WSAPROTOCOL_INFOA infoA;
4677 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
4679 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
4680 lpAddress, lpAddressLength );
4682 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
4684 /* if ProtocolInfo is available - convert to ANSI variant */
4687 lpProtoInfoA = &infoA;
4688 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
4690 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
4691 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
4693 WSASetLastError( WSAEINVAL);
4694 return SOCKET_ERROR;
4700 /* Translate AddressString to ANSI code page - assumes that only
4701 standard digits 0-9 are used with this API call */
4702 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
4703 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
4707 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
4708 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
4709 lpAddress,lpAddressLength);
4710 HeapFree( GetProcessHeap(), 0, workBuffer );
4714 res = WSA_NOT_ENOUGH_MEMORY;
4719 WSASetLastError(res);
4720 return SOCKET_ERROR;
4723 /***********************************************************************
4724 * WSAAddressToStringA (WS2_32.27)
4726 * See WSAAddressToStringW
4728 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
4729 LPWSAPROTOCOL_INFOA info, LPSTR string,
4733 CHAR buffer[22]; /* 12 digits + 3 dots + ':' + 5 digits + '\0' */
4736 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
4738 if (!sockaddr || len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
4739 if (!string || !lenstr) return SOCKET_ERROR;
4741 /* sin_family is guaranteed to be the first u_short */
4742 if (((SOCKADDR_IN *)sockaddr)->sin_family != AF_INET) return SOCKET_ERROR;
4744 sprintf( buffer, "%u.%u.%u.%u:%u",
4745 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
4746 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
4747 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
4748 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
4749 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
4751 p = strchr( buffer, ':' );
4752 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
4754 size = strlen( buffer );
4759 WSASetLastError(WSAEFAULT);
4760 return SOCKET_ERROR;
4763 strcpy( string, buffer );
4767 /***********************************************************************
4768 * WSAAddressToStringW (WS2_32.28)
4770 * Convert a sockaddr address into a readable address string.
4773 * sockaddr [I] Pointer to a sockaddr structure.
4774 * len [I] Size of the sockaddr structure.
4775 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
4776 * string [I/O] Pointer to a buffer to receive the address string.
4777 * lenstr [I/O] Size of the receive buffer in WCHARs.
4781 * Failure: SOCKET_ERROR
4784 * The 'info' parameter is ignored.
4787 * Only supports AF_INET addresses.
4789 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
4790 LPWSAPROTOCOL_INFOW info, LPWSTR string,
4794 WCHAR buffer[22]; /* 12 digits + 3 dots + ':' + 5 digits + '\0' */
4795 static const WCHAR format[] = { '%','u','.','%','u','.','%','u','.','%','u',':','%','u',0 };
4798 TRACE( "(%p, %x, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
4800 if (!sockaddr || len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
4801 if (!string || !lenstr) return SOCKET_ERROR;
4803 /* sin_family is guaranteed to be the first u_short */
4804 if (((SOCKADDR_IN *)sockaddr)->sin_family != AF_INET) return SOCKET_ERROR;
4806 sprintfW( buffer, format,
4807 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
4808 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
4809 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
4810 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
4811 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
4813 p = strchrW( buffer, ':' );
4814 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
4816 size = lstrlenW( buffer );
4821 return SOCKET_ERROR;
4824 lstrcpyW( string, buffer );
4828 /***********************************************************************
4829 * WSAEnumNameSpaceProvidersA (WS2_32.34)
4831 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
4833 FIXME( "(%p %p) Stub!\n", len, buffer );
4837 /***********************************************************************
4838 * WSAEnumNameSpaceProvidersW (WS2_32.35)
4840 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
4842 FIXME( "(%p %p) Stub!\n", len, buffer );
4846 /***********************************************************************
4847 * WSAGetQOSByName (WS2_32.41)
4849 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
4851 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
4855 /***********************************************************************
4856 * WSAGetServiceClassInfoA (WS2_32.42)
4858 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
4859 LPWSASERVICECLASSINFOA info )
4861 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
4863 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4864 return SOCKET_ERROR;
4867 /***********************************************************************
4868 * WSAGetServiceClassInfoW (WS2_32.43)
4870 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
4871 LPWSASERVICECLASSINFOW info )
4873 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
4875 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4876 return SOCKET_ERROR;
4879 /***********************************************************************
4880 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
4882 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
4884 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
4885 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4886 return SOCKET_ERROR;
4889 /***********************************************************************
4890 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
4892 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
4894 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
4895 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4896 return SOCKET_ERROR;
4899 /***********************************************************************
4900 * WSALookupServiceBeginA (WS2_32.59)
4902 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
4903 DWORD dwControlFlags,
4906 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
4908 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4909 return SOCKET_ERROR;
4912 /***********************************************************************
4913 * WSALookupServiceBeginW (WS2_32.60)
4915 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
4916 DWORD dwControlFlags,
4919 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
4921 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4922 return SOCKET_ERROR;
4925 /***********************************************************************
4926 * WSALookupServiceBeginW (WS2_32.61)
4928 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
4930 FIXME("(%p) Stub!\n", lookup );
4934 /***********************************************************************
4935 * WSALookupServiceNextA (WS2_32.62)
4937 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
4939 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
4943 /***********************************************************************
4944 * WSALookupServiceNextW (WS2_32.63)
4946 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
4948 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
4952 /***********************************************************************
4953 * WSANtohl (WS2_32.64)
4955 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
4957 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
4959 if (!lphostlong) return WSAEFAULT;
4961 *lphostlong = ntohl( netlong );
4965 /***********************************************************************
4966 * WSANtohs (WS2_32.65)
4968 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
4970 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
4972 if (!lphostshort) return WSAEFAULT;
4974 *lphostshort = ntohs( netshort );
4978 /***********************************************************************
4979 * WSAProviderConfigChange (WS2_32.66)
4981 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
4982 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4984 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
4985 return SOCKET_ERROR;
4988 /***********************************************************************
4989 * WSARecvDisconnect (WS2_32.68)
4991 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
4993 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
4995 return WS_shutdown( s, 0 );
4998 /***********************************************************************
4999 * WSASetServiceA (WS2_32.76)
5001 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
5003 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5007 /***********************************************************************
5008 * WSASetServiceW (WS2_32.77)
5010 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
5012 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5016 /***********************************************************************
5017 * WSCEnableNSProvider (WS2_32.84)
5019 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
5021 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
5025 /***********************************************************************
5026 * WSCGetProviderPath (WS2_32.86)
5028 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
5030 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
5032 if (!errcode || !provider || !len) return WSAEFAULT;
5034 *errcode = WSAEINVAL;
5035 return SOCKET_ERROR;
5038 /***********************************************************************
5039 * WSCInstallNameSpace (WS2_32.87)
5041 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
5042 DWORD version, LPGUID provider )
5044 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
5045 namespace, version, debugstr_guid(provider) );
5049 /***********************************************************************
5050 * WSCUnInstallNameSpace (WS2_32.89)
5052 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
5054 FIXME("(%p) Stub!\n", lpProviderId);
5058 /***********************************************************************
5059 * WSCWriteProviderOrder (WS2_32.91)
5061 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
5063 FIXME("(%p 0x%08x) Stub!\n", entry, number);