2 * based on Windows Sockets 1.1 specs
3 * (ftp.microsoft.com:/Advsys/winsock/spec11/WINSOCK.TXT)
5 * Copyright (C) 1993,1994,1996,1997 John Brezak, Erik Bos, Alex Korobka.
6 * Copyright (C) 2005 Marcus Meissner
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"
138 #include "wine/server.h"
139 #include "wine/debug.h"
140 #include "wine/unicode.h"
143 # include "wsnwlink.h"
147 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
148 # define sipx_network sipx_addr.x_net
149 # define sipx_node sipx_addr.x_host.c_host
150 #endif /* __FreeBSD__ */
153 #define INADDR_NONE ~0UL
156 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
158 /* critical section to protect some non-rentrant net function */
159 extern CRITICAL_SECTION csWSgetXXXbyYYY;
161 inline static const char *debugstr_sockaddr( const struct WS_sockaddr *a )
163 if (!a) return "(nil)";
164 return wine_dbg_sprintf("{ family %d, address %s, port %d }",
165 ((const struct sockaddr_in *)a)->sin_family,
166 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
167 ntohs(((const struct sockaddr_in *)a)->sin_port));
170 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
171 #define SOCKET2HANDLE(s) ((HANDLE)(s))
172 #define HANDLE2SOCKET(h) ((SOCKET)(h))
174 /****************************************************************
175 * Async IO declarations
176 ****************************************************************/
178 typedef struct ws2_async
181 enum ws2_mode {ws2m_read, ws2m_write, ws2m_sd_read, ws2m_sd_write} mode;
182 LPWSAOVERLAPPED user_overlapped;
183 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
186 struct WS_sockaddr *addr;
189 int val; /* for send operations */
190 int *ptr; /* for recv operations */
196 /****************************************************************/
198 /* ----------------------------------- internal data */
200 /* ws_... struct conversion flags */
202 typedef struct /* WSAAsyncSelect() control struct */
204 HANDLE service, event, sock;
210 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
211 #define WS_MAX_UDP_DATAGRAM 1024
212 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
214 /* hostent's, servent's and protent's are stored in one buffer per thread,
215 * as documented on MSDN for the functions that return any of the buffers */
216 struct per_thread_data
219 struct WS_hostent *he_buffer;
220 struct WS_servent *se_buffer;
221 struct WS_protoent *pe_buffer;
227 static INT num_startup; /* reference counter */
228 static FARPROC blocking_hook = WSA_DefaultBlockingHook;
230 /* function prototypes */
231 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
232 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
233 static struct WS_servent *WS_dup_se(const struct servent* p_se);
235 int WSAIOCTL_GetInterfaceCount(void);
236 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
239 UINT wsaHerrno(int errnr);
241 #define MAP_OPTION(opt) { WS_##opt, opt }
243 static const int ws_sock_map[][2] =
245 MAP_OPTION( SO_DEBUG ),
246 MAP_OPTION( SO_ACCEPTCONN ),
247 MAP_OPTION( SO_REUSEADDR ),
248 MAP_OPTION( SO_KEEPALIVE ),
249 MAP_OPTION( SO_DONTROUTE ),
250 MAP_OPTION( SO_BROADCAST ),
251 MAP_OPTION( SO_LINGER ),
252 MAP_OPTION( SO_OOBINLINE ),
253 MAP_OPTION( SO_SNDBUF ),
254 MAP_OPTION( SO_RCVBUF ),
255 MAP_OPTION( SO_ERROR ),
256 MAP_OPTION( SO_TYPE ),
258 MAP_OPTION( SO_RCVTIMEO ),
261 MAP_OPTION( SO_SNDTIMEO ),
265 static const int ws_tcp_map[][2] =
268 MAP_OPTION( TCP_NODELAY ),
272 static const int ws_ip_map[][2] =
274 MAP_OPTION( IP_MULTICAST_IF ),
275 MAP_OPTION( IP_MULTICAST_TTL ),
276 MAP_OPTION( IP_MULTICAST_LOOP ),
277 MAP_OPTION( IP_ADD_MEMBERSHIP ),
278 MAP_OPTION( IP_DROP_MEMBERSHIP ),
279 MAP_OPTION( IP_OPTIONS ),
281 MAP_OPTION( IP_HDRINCL ),
283 MAP_OPTION( IP_TOS ),
284 MAP_OPTION( IP_TTL ),
287 static const int ws_af_map[][2] =
289 MAP_OPTION( AF_UNSPEC ),
290 MAP_OPTION( AF_INET ),
291 MAP_OPTION( AF_INET6 ),
293 MAP_OPTION( AF_IPX ),
297 static const int ws_socktype_map[][2] =
299 MAP_OPTION( SOCK_DGRAM ),
300 MAP_OPTION( SOCK_STREAM ),
301 MAP_OPTION( SOCK_RAW ),
304 static const int ws_proto_map[][2] =
306 MAP_OPTION( IPPROTO_IP ),
307 MAP_OPTION( IPPROTO_TCP ),
308 MAP_OPTION( IPPROTO_UDP ),
309 MAP_OPTION( IPPROTO_ICMP ),
310 MAP_OPTION( IPPROTO_IGMP ),
311 MAP_OPTION( IPPROTO_RAW ),
314 static const int ws_aiflag_map[][2] =
316 MAP_OPTION( AI_PASSIVE ),
317 MAP_OPTION( AI_CANONNAME ),
318 MAP_OPTION( AI_NUMERICHOST ),
319 /* Linux/UNIX knows a lot more. But Windows only
320 * has 3 as far as I could see. -Marcus
324 static const int ws_eai_map[][2] =
326 MAP_OPTION( EAI_AGAIN ),
327 MAP_OPTION( EAI_BADFLAGS ),
328 MAP_OPTION( EAI_FAIL ),
329 MAP_OPTION( EAI_FAMILY ),
330 MAP_OPTION( EAI_MEMORY ),
331 /* Note: EAI_NODATA is deprecated, but still
332 * used by Windows and Linux... We map the newer
333 * EAI_NONAME to EAI_NODATA for now until Windows
337 MAP_OPTION( EAI_NODATA ),
340 { WS_EAI_NODATA, EAI_NONAME },
343 MAP_OPTION( EAI_SERVICE ),
344 MAP_OPTION( EAI_SOCKTYPE ),
348 inline static DWORD NtStatusToWSAError( const DWORD status )
350 /* We only need to cover the status codes set by server async request handling */
354 case STATUS_SUCCESS: wserr = 0; break;
355 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
356 case STATUS_INVALID_HANDLE: wserr = WSAENOTSOCK; break; /* WSAEBADF ? */
357 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
358 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
359 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
360 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
361 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
363 if ( status >= WSABASEERR && status <= WSABASEERR+1004 )
364 /* It is not a NT status code but a winsock error */
368 wserr = RtlNtStatusToDosError( status );
369 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
375 /* set last error code from NT status without mapping WSA errors */
376 inline static unsigned int set_error( unsigned int err )
380 err = NtStatusToWSAError( err );
386 inline static int get_sock_fd( SOCKET s, DWORD access, int *flags )
389 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, flags ) ))
394 inline static void release_sock_fd( SOCKET s, int fd )
396 wine_server_release_fd( SOCKET2HANDLE(s), fd );
399 static void _enable_event( HANDLE s, unsigned int event,
400 unsigned int sstate, unsigned int cstate )
402 SERVER_START_REQ( enable_socket_event )
406 req->sstate = sstate;
407 req->cstate = cstate;
408 wine_server_call( req );
413 static int _is_blocking(SOCKET s)
416 SERVER_START_REQ( get_socket_event )
418 req->handle = SOCKET2HANDLE(s);
419 req->service = FALSE;
421 wine_server_call( req );
422 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
428 static unsigned int _get_sock_mask(SOCKET s)
431 SERVER_START_REQ( get_socket_event )
433 req->handle = SOCKET2HANDLE(s);
434 req->service = FALSE;
436 wine_server_call( req );
443 static void _sync_sock_state(SOCKET s)
445 /* do a dummy wineserver request in order to let
446 the wineserver run through its select loop once */
447 (void)_is_blocking(s);
450 static int _get_sock_error(SOCKET s, unsigned int bit)
452 int events[FD_MAX_EVENTS];
454 SERVER_START_REQ( get_socket_event )
456 req->handle = SOCKET2HANDLE(s);
457 req->service = FALSE;
459 wine_server_set_reply( req, events, sizeof(events) );
460 wine_server_call( req );
466 static struct per_thread_data *get_per_thread_data(void)
468 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
469 /* lazy initialization */
472 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
473 NtCurrentTeb()->WinSockData = ptb;
478 static void free_per_thread_data(void)
480 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
484 /* delete scratch buffers */
485 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
486 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
487 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
488 ptb->he_buffer = NULL;
489 ptb->se_buffer = NULL;
490 ptb->pe_buffer = NULL;
492 HeapFree( GetProcessHeap(), 0, ptb );
493 NtCurrentTeb()->WinSockData = NULL;
496 /***********************************************************************
497 * DllMain (WS2_32.init)
499 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
501 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
503 case DLL_PROCESS_ATTACH:
505 case DLL_PROCESS_DETACH:
506 free_per_thread_data();
509 case DLL_THREAD_DETACH:
510 free_per_thread_data();
516 /***********************************************************************
519 * Converts socket flags from Windows format.
520 * Return 1 if converted, 0 if not (error).
522 static int convert_sockopt(INT *level, INT *optname)
529 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
530 if( ws_sock_map[i][0] == *optname )
532 *optname = ws_sock_map[i][1];
536 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
539 *level = IPPROTO_TCP;
540 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
541 if ( ws_tcp_map[i][0] == *optname )
543 *optname = ws_tcp_map[i][1];
547 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
551 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
552 if (ws_ip_map[i][0] == *optname )
554 *optname = ws_ip_map[i][1];
558 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
560 default: FIXME("Unimplemented or unknown socket level\n");
565 static inline BOOL is_timeout_option( int optname )
568 if (optname == SO_RCVTIMEO) return TRUE;
571 if (optname == SO_SNDTIMEO) return TRUE;
576 /* ----------------------------------- Per-thread info (or per-process?) */
578 static char *strdup_lower(const char *str)
581 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
585 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
588 else SetLastError(WSAENOBUFS);
592 inline static int sock_error_p(int s)
594 unsigned int optval, optlen;
596 optlen = sizeof(optval);
597 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
598 if (optval) WARN("\t[%i] error: %d\n", s, optval);
602 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
603 * from an fd and return the value converted to milli seconds
604 * or -1 if there is an infinite time out */
605 static inline int get_rcvsnd_timeo( int fd, int optname)
608 unsigned int len = sizeof(tv);
609 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
611 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
612 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
617 /* macro wrappers for portability */
619 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
621 #define GET_RCVTIMEO(fd) (-1)
625 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
627 #define GET_SNDTIMEO(fd) (-1)
630 /* utility: given an fd, will block until one of the events occurs */
631 static inline int do_block( int fd, int events, int timeout )
639 while ((ret = poll(&pfd, 1, timeout)) < 0)
650 convert_af_w2u(int windowsaf) {
653 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
654 if (ws_af_map[i][0] == windowsaf)
655 return ws_af_map[i][1];
656 FIXME("unhandled Windows address family %d\n", windowsaf);
661 convert_af_u2w(int unixaf) {
664 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
665 if (ws_af_map[i][1] == unixaf)
666 return ws_af_map[i][0];
667 FIXME("unhandled UNIX address family %d\n", unixaf);
672 convert_proto_w2u(int windowsproto) {
675 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
676 if (ws_proto_map[i][0] == windowsproto)
677 return ws_proto_map[i][1];
678 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
683 convert_proto_u2w(int unixproto) {
686 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
687 if (ws_proto_map[i][1] == unixproto)
688 return ws_proto_map[i][0];
689 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
694 convert_socktype_w2u(int windowssocktype) {
697 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
698 if (ws_socktype_map[i][0] == windowssocktype)
699 return ws_socktype_map[i][1];
700 FIXME("unhandled Windows socket type %d\n", windowssocktype);
705 convert_socktype_u2w(int unixsocktype) {
708 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
709 if (ws_socktype_map[i][1] == unixsocktype)
710 return ws_socktype_map[i][0];
711 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
715 /* ----------------------------------- API -----
717 * Init / cleanup / error checking.
720 /***********************************************************************
721 * WSAStartup (WS2_32.115)
723 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
725 TRACE("verReq=%x\n", wVersionRequested);
727 if (LOBYTE(wVersionRequested) < 1)
728 return WSAVERNOTSUPPORTED;
730 if (!lpWSAData) return WSAEINVAL;
734 /* that's the whole of the negotiation for now */
735 lpWSAData->wVersion = wVersionRequested;
736 /* return winsock information */
737 lpWSAData->wHighVersion = 0x0202;
738 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
739 strcpy(lpWSAData->szSystemStatus, "Running" );
740 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
741 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
742 /* don't do anything with lpWSAData->lpVendorInfo */
743 /* (some apps don't allocate the space for this field) */
745 TRACE("succeeded\n");
750 /***********************************************************************
751 * WSACleanup (WS2_32.116)
753 INT WINAPI WSACleanup(void)
759 SetLastError(WSANOTINITIALISED);
764 /***********************************************************************
765 * WSAGetLastError (WINSOCK.111)
766 * WSAGetLastError (WS2_32.111)
768 INT WINAPI WSAGetLastError(void)
770 return GetLastError();
773 /***********************************************************************
774 * WSASetLastError (WS2_32.112)
776 void WINAPI WSASetLastError(INT iError) {
777 SetLastError(iError);
780 static struct WS_hostent *check_buffer_he(int size)
782 struct per_thread_data * ptb = get_per_thread_data();
785 if (ptb->he_len >= size ) return ptb->he_buffer;
786 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
788 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
789 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
790 return ptb->he_buffer;
793 static struct WS_servent *check_buffer_se(int size)
795 struct per_thread_data * ptb = get_per_thread_data();
798 if (ptb->se_len >= size ) return ptb->se_buffer;
799 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
801 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
802 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
803 return ptb->se_buffer;
806 static struct WS_protoent *check_buffer_pe(int size)
808 struct per_thread_data * ptb = get_per_thread_data();
811 if (ptb->pe_len >= size ) return ptb->pe_buffer;
812 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
814 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
815 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
816 return ptb->pe_buffer;
819 /* ----------------------------------- i/o APIs */
822 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf)== WS_AF_IPX || (pf) == WS_AF_INET6)
824 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf) == WS_AF_INET6)
828 /**********************************************************************/
830 /* Returns the converted address if successful, NULL if it was too small to
831 * start with. Note that the returned pointer may be the original pointer
832 * if no conversion is necessary.
834 static struct sockaddr* ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen, unsigned int *uaddrlen)
836 switch (wsaddr->sa_family)
841 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
842 struct sockaddr_ipx* uipx;
844 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
847 *uaddrlen=sizeof(struct sockaddr_ipx);
848 uipx=HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *uaddrlen);
849 uipx->sipx_family=AF_IPX;
850 uipx->sipx_port=wsipx->sa_socket;
851 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
854 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
855 #ifdef IPX_FRAME_NONE
856 uipx->sipx_type=IPX_FRAME_NONE;
858 return (struct sockaddr*)uipx;
862 struct sockaddr_in6* uin6;
863 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
865 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
866 * scope_id, one without. Check:
867 * http://msdn.microsoft.com/library/en-us/winsock/winsock/sockaddr_2.asp
869 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
870 *uaddrlen=sizeof(struct sockaddr_in6);
871 uin6=HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *uaddrlen);
872 uin6->sin6_family = AF_INET6;
873 uin6->sin6_port = win6->sin6_port;
874 uin6->sin6_flowinfo = win6->sin6_flowinfo;
875 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
876 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
878 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
879 return (struct sockaddr*)uin6;
881 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
885 struct sockaddr_in* uin;
886 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
888 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
890 *uaddrlen=sizeof(struct sockaddr_in);
891 uin = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *uaddrlen);
892 uin->sin_family = AF_INET;
893 uin->sin_port = win->sin_port;
894 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
895 return (struct sockaddr*)uin;
898 /* Try to determine the needed space by the passed windows sockaddr space */
900 default: /* likely a ipv4 address */
901 case sizeof(struct WS_sockaddr_in):
902 *uaddrlen = sizeof(struct sockaddr_in);
905 case sizeof(struct WS_sockaddr_ipx):
906 *uaddrlen = sizeof(struct sockaddr_ipx);
909 case sizeof(struct WS_sockaddr_in6):
910 case sizeof(struct WS_sockaddr_in6_old):
911 *uaddrlen = sizeof(struct sockaddr_in6);
914 return HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,*uaddrlen);
917 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
922 /* Allocates a Unix sockaddr structure to receive the data */
923 static inline struct sockaddr* ws_sockaddr_alloc(const struct WS_sockaddr* wsaddr, int* wsaddrlen, unsigned int* uaddrlen)
927 ERR( "WINE shouldn't pass a NULL wsaddr! Attempting to continue\n" );
929 /* This is not strictly the right thing to do. Hope it works however */
938 *uaddrlen=max(sizeof(struct sockaddr),*wsaddrlen);
940 return HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *uaddrlen);
943 /* Returns 0 if successful, -1 if the buffer is too small */
944 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, int uaddrlen, struct WS_sockaddr* wsaddr, int* wsaddrlen)
948 switch(uaddr->sa_family)
953 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
954 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
957 switch (*wsaddrlen) /* how much can we copy? */
962 wsipx->sa_socket=uipx->sipx_port;
966 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
974 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
980 wsipx->sa_family=WS_AF_IPX;
991 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
992 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
994 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
996 win6old->sin6_family = WS_AF_INET6;
997 win6old->sin6_port = uin6->sin6_port;
998 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
999 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1000 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1001 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1002 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1003 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1004 win6->sin6_scope_id = uin6->sin6_scope_id;
1005 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1011 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1012 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1014 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1016 win->sin_family = WS_AF_INET;
1017 win->sin_port = uin->sin_port;
1018 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1019 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1023 memset(wsaddr,0,*wsaddrlen);
1027 FIXME("Unknown address family %d\n", uaddr->sa_family);
1033 /* to be called to free the memory allocated by ws_sockaddr_ws2u or
1036 static inline void ws_sockaddr_free(const struct sockaddr* uaddr, const struct WS_sockaddr* wsaddr)
1038 if (uaddr!=(const struct sockaddr*)wsaddr)
1039 HeapFree(GetProcessHeap(), 0, (void *)uaddr);
1042 /**************************************************************************
1043 * Functions for handling overlapped I/O
1044 **************************************************************************/
1046 static void CALLBACK ws2_async_terminate(ws2_async* as, IO_STATUS_BLOCK* iosb)
1048 TRACE( "as: %p uovl %p ovl %p\n", as, as->user_overlapped, iosb );
1050 if (as->event) NtSetEvent( as->event, NULL );
1052 if (as->completion_func)
1053 as->completion_func( NtStatusToWSAError (iosb->u.Status),
1054 iosb->Information, as->user_overlapped, as->flags );
1055 if ( !as->user_overlapped )
1058 /* FIXME: I don't think this is really used */
1059 if ( as->overlapped->hEvent != INVALID_HANDLE_VALUE )
1060 WSACloseEvent( as->overlapped->hEvent );
1062 HeapFree( GetProcessHeap(), 0, iosb );
1065 HeapFree( GetProcessHeap(), 0, as->iovec );
1066 HeapFree( GetProcessHeap(), 0, as );
1069 /***********************************************************************
1070 * WS2_make_async (INTERNAL)
1073 static void WINAPI WS2_async_recv(void*, IO_STATUS_BLOCK*, ULONG);
1074 static void WINAPI WS2_async_send(void*, IO_STATUS_BLOCK*, ULONG);
1075 static void WINAPI WS2_async_shutdown( void*, IO_STATUS_BLOCK*, ULONG);
1077 inline static struct ws2_async*
1078 WS2_make_async(SOCKET s, enum ws2_mode mode, struct iovec *iovec, DWORD dwBufferCount,
1079 LPDWORD lpFlags, struct WS_sockaddr *addr,
1080 LPINT addrlen, LPWSAOVERLAPPED lpOverlapped,
1081 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
1082 IO_STATUS_BLOCK **piosb)
1084 struct ws2_async *wsa = HeapAlloc( GetProcessHeap(), 0, sizeof( ws2_async ) );
1086 TRACE( "wsa %p\n", wsa );
1091 wsa->hSocket = (HANDLE) s;
1097 wsa->flags = *lpFlags;
1098 wsa->addrlen.ptr = addrlen;
1103 wsa->addrlen.val = *addrlen;
1106 ERR("Invalid async mode: %d\n", mode);
1108 wsa->user_overlapped = lpOverlapped;
1109 wsa->completion_func = lpCompletionRoutine;
1111 wsa->n_iovecs = dwBufferCount;
1117 *piosb = (IO_STATUS_BLOCK*)lpOverlapped;
1118 if (!lpCompletionRoutine)
1120 wsa->event = lpOverlapped->hEvent;
1121 NtResetEvent(wsa->event, NULL);
1124 else if (!(*piosb = HeapAlloc( GetProcessHeap(), 0, sizeof(IO_STATUS_BLOCK))))
1127 (*piosb)->Information = 0;
1128 (*piosb)->u.Status = STATUS_PENDING;
1129 TRACE( "wsa %p, h %p, ev %p, iosb %p, uov %p, cfunc %p\n",
1130 wsa, wsa->hSocket, wsa->event,
1131 *piosb, wsa->user_overlapped, wsa->completion_func );
1137 HeapFree( GetProcessHeap(), 0, wsa );
1141 static ULONG ws2_queue_async(struct ws2_async* wsa, IO_STATUS_BLOCK* iosb)
1143 PIO_APC_ROUTINE apc;
1149 case ws2m_read: apc = WS2_async_recv; type = ASYNC_TYPE_READ; break;
1150 case ws2m_write: apc = WS2_async_send; type = ASYNC_TYPE_WRITE; break;
1151 case ws2m_sd_read: apc = WS2_async_shutdown; type = ASYNC_TYPE_READ; break;
1152 case ws2m_sd_write: apc = WS2_async_shutdown; type = ASYNC_TYPE_WRITE; break;
1153 default: FIXME("Unknown internal mode (%d)\n", wsa->mode); return STATUS_INVALID_PARAMETER;
1156 SERVER_START_REQ( register_async )
1158 req->handle = wsa->hSocket;
1163 req->count = iosb->Information;
1164 status = wine_server_call( req );
1168 if ( status ) iosb->u.Status = status;
1169 if ( iosb->u.Status != STATUS_PENDING )
1171 /* Note: we get here a non zero status when we couldn't queue the async
1172 * in the server. Therefore, we simply terminate the async.
1174 status = iosb->u.Status;
1175 ws2_async_terminate(wsa, iosb);
1178 NtCurrentTeb()->num_async_io++;
1179 return STATUS_SUCCESS;
1182 /***********************************************************************
1183 * WS2_recv (INTERNAL)
1185 * Workhorse for both synchronous and asynchronous recv() operations.
1187 static int WS2_recv( int fd, struct iovec* iov, int count,
1188 struct WS_sockaddr *lpFrom, LPINT lpFromlen,
1193 TRACE( "fd %d, iovec %p, count %d addr %s, len %p, flags %x\n",
1194 fd, iov, count, debugstr_sockaddr(lpFrom), lpFromlen, *lpFlags);
1196 hdr.msg_name = NULL;
1200 hdr.msg_namelen = *lpFromlen;
1201 hdr.msg_name = ws_sockaddr_alloc( lpFrom, lpFromlen, &hdr.msg_namelen );
1202 if ( !hdr.msg_name )
1204 WSASetLastError( WSAEFAULT );
1210 hdr.msg_namelen = 0;
1213 hdr.msg_iovlen = count;
1214 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1215 hdr.msg_accrights = NULL;
1216 hdr.msg_accrightslen = 0;
1218 hdr.msg_control = NULL;
1219 hdr.msg_controllen = 0;
1223 if ( (n = recvmsg(fd, &hdr, *lpFlags)) == -1 )
1225 TRACE( "recvmsg error %d\n", errno);
1230 ws_sockaddr_u2ws( hdr.msg_name, hdr.msg_namelen,
1231 lpFrom, lpFromlen ) != 0 )
1233 /* The from buffer was too small, but we read the data
1234 * anyway. Is that really bad?
1236 WSASetLastError( WSAEFAULT );
1237 WARN( "Address buffer too small\n" );
1242 ws_sockaddr_free( hdr.msg_name, lpFrom );
1243 TRACE("-> %d\n", n);
1247 /***********************************************************************
1248 * WS2_async_recv (INTERNAL)
1250 * Handler for overlapped recv() operations.
1252 static void WINAPI WS2_async_recv( void* ovp, IO_STATUS_BLOCK* iosb, ULONG status)
1254 ws2_async* wsa = (ws2_async*) ovp;
1255 int result, fd, err;
1257 TRACE( "(%p %p %x)\n", wsa, iosb, status );
1261 case STATUS_ALERTED:
1262 if ((iosb->u.Status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1264 ws2_async_terminate(wsa, iosb);
1267 result = WS2_recv( fd, wsa->iovec, wsa->n_iovecs,
1268 wsa->addr, wsa->addrlen.ptr, &wsa->flags );
1269 wine_server_release_fd( wsa->hSocket, fd );
1272 iosb->u.Status = STATUS_SUCCESS;
1273 iosb->Information = result;
1274 TRACE( "received %d bytes\n", result );
1275 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1280 if ( err == WSAEINTR || err == WSAEWOULDBLOCK ) /* errno: EINTR / EAGAIN */
1282 iosb->u.Status = STATUS_PENDING;
1283 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1284 TRACE( "still pending\n" );
1288 iosb->u.Status = err; /* FIXME: is this correct ???? */
1289 TRACE( "Error: %x\n", err );
1292 if (iosb->u.Status == STATUS_PENDING)
1293 ws2_queue_async(wsa, iosb);
1295 ws2_async_terminate(wsa, iosb);
1298 FIXME( "status: %d\n", status );
1299 iosb->u.Status = status;
1300 ws2_async_terminate(wsa, iosb);
1305 /***********************************************************************
1306 * WS2_send (INTERNAL)
1308 * Workhorse for both synchronous and asynchronous send() operations.
1310 static int WS2_send( int fd, struct iovec* iov, int count,
1311 const struct WS_sockaddr *to, INT tolen, DWORD dwFlags )
1315 TRACE( "fd %d, iovec %p, count %d addr %s, len %d, flags %x\n",
1316 fd, iov, count, debugstr_sockaddr(to), tolen, dwFlags);
1318 hdr.msg_name = NULL;
1322 hdr.msg_name = (struct sockaddr*) ws_sockaddr_ws2u( to, tolen, &hdr.msg_namelen );
1323 if ( !hdr.msg_name )
1325 WSASetLastError( WSAEFAULT );
1330 if(to->sa_family == WS_AF_IPX)
1333 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1335 unsigned int len=sizeof(int);
1337 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1338 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1339 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1340 * ipx type in the sockaddr_opx structure with the stored value.
1342 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1344 TRACE("ptype: %d (fd:%d)\n", val, fd);
1345 uipx->sipx_type = val;
1353 hdr.msg_namelen = 0;
1356 hdr.msg_iovlen = count;
1357 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1358 hdr.msg_accrights = NULL;
1359 hdr.msg_accrightslen = 0;
1361 hdr.msg_control = NULL;
1362 hdr.msg_controllen = 0;
1366 n = sendmsg(fd, &hdr, dwFlags);
1369 ws_sockaddr_free( hdr.msg_name, to );
1373 /***********************************************************************
1374 * WS2_async_send (INTERNAL)
1376 * Handler for overlapped send() operations.
1378 static void WINAPI WS2_async_send(void* as, IO_STATUS_BLOCK* iosb, ULONG status)
1380 ws2_async* wsa = (ws2_async*) as;
1383 TRACE( "(%p %p %x)\n", wsa, iosb, status );
1387 case STATUS_ALERTED:
1388 if (iosb->u.Status != STATUS_PENDING) FIXME("wrong %08x\n", iosb->u.Status);
1389 if ((iosb->u.Status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1391 ws2_async_terminate(wsa, iosb);
1394 /* check to see if the data is ready (non-blocking) */
1395 result = WS2_send( fd, wsa->iovec, wsa->n_iovecs, wsa->addr, wsa->addrlen.val, wsa->flags );
1396 wine_server_release_fd( wsa->hSocket, fd );
1400 iosb->u.Status = STATUS_SUCCESS;
1401 iosb->Information = result;
1402 TRACE( "sent %d bytes\n", result );
1403 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1407 int err = wsaErrno();
1408 if ( err == WSAEINTR )
1410 iosb->u.Status = STATUS_PENDING;
1411 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1412 TRACE( "still pending\n" );
1416 /* We set the status to a winsock error code and check for that
1417 later in NtStatusToWSAError () */
1418 iosb->u.Status = err;
1419 TRACE( "Error: %x\n", err );
1422 if (iosb->u.Status == STATUS_PENDING)
1423 ws2_queue_async(wsa, iosb);
1425 ws2_async_terminate(wsa, iosb);
1428 FIXME( "status: %d\n", status );
1429 iosb->u.Status = status;
1430 ws2_async_terminate(wsa, iosb);
1436 /***********************************************************************
1437 * WS2_async_shutdown (INTERNAL)
1439 * Handler for shutdown() operations on overlapped sockets.
1441 static void WINAPI WS2_async_shutdown( void* as, PIO_STATUS_BLOCK iosb, ULONG status )
1443 ws2_async* wsa = (ws2_async*) as;
1446 TRACE( "async %p %d\n", wsa, wsa->mode );
1449 case STATUS_ALERTED:
1450 if ((iosb->u.Status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1452 ws2_async_terminate(wsa, iosb);
1455 switch ( wsa->mode )
1457 case ws2m_sd_read: err = shutdown( fd, 0 ); break;
1458 case ws2m_sd_write: err = shutdown( fd, 1 ); break;
1459 default: ERR("invalid mode: %d\n", wsa->mode );
1461 wine_server_release_fd( wsa->hSocket, fd );
1462 iosb->u.Status = err ? wsaErrno() : STATUS_SUCCESS;
1463 if (iosb->u.Status == STATUS_PENDING)
1464 ws2_queue_async(wsa, iosb);
1466 ws2_async_terminate(wsa, iosb);
1469 iosb->u.Status = status;
1470 ws2_async_terminate(wsa, iosb);
1476 /***********************************************************************
1477 * WS2_register_async_shutdown (INTERNAL)
1479 * Helper function for WS_shutdown() on overlapped sockets.
1481 static int WS2_register_async_shutdown( SOCKET s, enum ws2_mode mode )
1483 struct ws2_async *wsa;
1484 int ret, err = WSAEFAULT;
1487 LPWSAOVERLAPPED ovl = HeapAlloc(GetProcessHeap(), 0, sizeof( WSAOVERLAPPED ));
1488 IO_STATUS_BLOCK *iosb = NULL;
1490 TRACE("s %d mode %d\n", s, mode);
1494 ovl->hEvent = WSACreateEvent();
1495 if ( ovl->hEvent == WSA_INVALID_EVENT )
1498 wsa = WS2_make_async( s, mode, NULL, 0, &dwflags, NULL, &len, ovl, NULL, &iosb );
1502 /* Hack: this will cause ws2_async_terminate() to free the overlapped structure */
1503 wsa->user_overlapped = NULL;
1504 if ( (ret = ws2_queue_async( wsa, iosb )) )
1506 err = NtStatusToWSAError( ret );
1509 /* Try immediate completion */
1510 while ( WaitForSingleObjectEx( ovl->hEvent, 0, TRUE ) == STATUS_USER_APC );
1514 WSACloseEvent( ovl->hEvent );
1516 HeapFree( GetProcessHeap(), 0, ovl );
1521 /***********************************************************************
1524 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1530 TRACE("socket %04x\n", s );
1531 is_blocking = _is_blocking(s);
1536 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1537 if (fd == -1) return INVALID_SOCKET;
1539 do_block(fd, POLLIN, -1);
1540 _sync_sock_state(s); /* let wineserver notice connection */
1541 release_sock_fd( s, fd );
1542 /* retrieve any error codes from it */
1543 SetLastError(_get_sock_error(s, FD_ACCEPT_BIT));
1544 /* FIXME: care about the error? */
1546 SERVER_START_REQ( accept_socket )
1548 req->lhandle = SOCKET2HANDLE(s);
1549 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1550 req->attributes = OBJ_INHERIT;
1551 set_error( wine_server_call( req ) );
1552 as = HANDLE2SOCKET( reply->handle );
1557 if (addr) WS_getpeername(as, addr, addrlen32);
1560 } while (is_blocking);
1561 return INVALID_SOCKET;
1564 /***********************************************************************
1567 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1569 int fd = get_sock_fd( s, 0, NULL );
1570 int res = SOCKET_ERROR;
1572 TRACE("socket %04x, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1576 if (!name || (name->sa_family && !SUPPORTED_PF(name->sa_family)))
1578 SetLastError(WSAEAFNOSUPPORT);
1582 const struct sockaddr* uaddr;
1583 unsigned int uaddrlen;
1585 uaddr=ws_sockaddr_ws2u(name,namelen,&uaddrlen);
1588 SetLastError(WSAEFAULT);
1592 if (bind(fd, uaddr, uaddrlen) < 0)
1594 int loc_errno = errno;
1595 WARN("\tfailure - errno = %i\n", errno);
1600 SetLastError(WSAENOTSOCK);
1603 SetLastError(WSAEINVAL);
1606 SetLastError(wsaErrno());
1612 res=0; /* success */
1614 ws_sockaddr_free(uaddr,name);
1617 release_sock_fd( s, fd );
1622 /***********************************************************************
1623 * closesocket (WS2_32.3)
1625 int WINAPI WS_closesocket(SOCKET s)
1627 TRACE("socket %04x\n", s);
1628 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
1629 return SOCKET_ERROR;
1632 /***********************************************************************
1633 * connect (WS2_32.4)
1635 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1637 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1639 TRACE("socket %04x, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1643 const struct sockaddr* uaddr;
1644 unsigned int uaddrlen;
1646 uaddr=ws_sockaddr_ws2u(name,namelen,&uaddrlen);
1649 SetLastError(WSAEFAULT);
1655 rc=connect(fd, uaddr, uaddrlen);
1656 ws_sockaddr_free(uaddr,name);
1658 goto connect_success;
1661 if (errno == EINPROGRESS)
1663 /* tell wineserver that a connection is in progress */
1664 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1665 FD_CONNECT|FD_READ|FD_WRITE,
1666 FD_WINE_CONNECTED|FD_WINE_LISTENING);
1667 if (_is_blocking(s))
1671 do_block(fd, POLLIN | POLLOUT, -1);
1672 _sync_sock_state(s); /* let wineserver notice connection */
1673 /* retrieve any error codes from it */
1674 result = _get_sock_error(s, FD_CONNECT_BIT);
1676 SetLastError(result);
1679 goto connect_success;
1684 SetLastError(WSAEWOULDBLOCK);
1689 SetLastError(wsaErrno());
1691 release_sock_fd( s, fd );
1693 return SOCKET_ERROR;
1696 release_sock_fd( s, fd );
1697 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1698 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1699 FD_CONNECT|FD_WINE_LISTENING);
1703 /***********************************************************************
1704 * WSAConnect (WS2_32.30)
1706 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
1707 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1708 LPQOS lpSQOS, LPQOS lpGQOS )
1710 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1711 FIXME("unsupported parameters!\n");
1712 return WS_connect( s, name, namelen );
1716 /***********************************************************************
1717 * getpeername (WS2_32.5)
1719 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1724 TRACE("socket: %04x, ptr %p, len %08x\n", s, name, *namelen);
1726 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1727 if( (name == NULL) || (namelen == NULL) )
1729 SetLastError( WSAEFAULT );
1730 return SOCKET_ERROR;
1733 fd = get_sock_fd( s, 0, NULL );
1738 struct sockaddr* uaddr;
1739 unsigned int uaddrlen;
1741 uaddr=ws_sockaddr_alloc(name,namelen,&uaddrlen);
1742 if (getpeername(fd, uaddr, &uaddrlen) != 0)
1744 SetLastError(wsaErrno());
1746 else if (ws_sockaddr_u2ws(uaddr,uaddrlen,name,namelen) != 0)
1748 /* The buffer was too small */
1749 SetLastError(WSAEFAULT);
1755 ws_sockaddr_free(uaddr,name);
1756 release_sock_fd( s, fd );
1761 /***********************************************************************
1762 * getsockname (WS2_32.6)
1764 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1769 TRACE("socket: %04x, ptr %p, len %8x\n", s, name, *namelen);
1771 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1772 if( (name == NULL) || (namelen == NULL) )
1774 SetLastError( WSAEFAULT );
1775 return SOCKET_ERROR;
1778 fd = get_sock_fd( s, 0, NULL );
1783 struct sockaddr* uaddr;
1784 unsigned int uaddrlen;
1786 uaddr=ws_sockaddr_alloc(name,namelen,&uaddrlen);
1787 if (getsockname(fd, uaddr, &uaddrlen) != 0)
1789 SetLastError(wsaErrno());
1791 else if (ws_sockaddr_u2ws(uaddr,uaddrlen,name,namelen) != 0)
1793 /* The buffer was too small */
1794 SetLastError(WSAEFAULT);
1800 ws_sockaddr_free(uaddr,name);
1801 release_sock_fd( s, fd );
1806 /***********************************************************************
1807 * getsockopt (WS2_32.7)
1809 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1810 INT optname, char *optval, INT *optlen)
1815 TRACE("socket: %04x, level 0x%x, name 0x%x, ptr %p, len %d\n",
1816 s, level, optname, optval, *optlen);
1817 /* SO_OPENTYPE does not require a valid socket handle. */
1818 if (level == WS_SOL_SOCKET && optname == WS_SO_OPENTYPE)
1820 if (!optlen || *optlen < sizeof(int) || !optval)
1822 SetLastError(WSAEFAULT);
1823 return SOCKET_ERROR;
1825 *(int *)optval = get_per_thread_data()->opentype;
1826 *optlen = sizeof(int);
1827 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
1832 if(level == NSPROTO_IPX)
1834 struct WS_sockaddr_ipx addr;
1835 IPX_ADDRESS_DATA *data;
1840 fd = get_sock_fd( s, 0, NULL );
1842 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
1844 return SOCKET_ERROR;
1849 socklen_t len=sizeof(struct ipx);
1851 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
1852 return SOCKET_ERROR;
1853 *optval = (int)val.ipx_pt;
1856 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
1857 release_sock_fd( s, fd );
1862 * On a Win2000 system with one network card there are usually three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
1863 * Using this call you can then retrieve info about this all. In case of Linux it is a bit different. Usually you have
1864 * only "one" device active and further it is not possible to query things like the linkspeed.
1866 FIXME("IPX_ADDRESS\n");
1867 namelen = sizeof(struct WS_sockaddr_ipx);
1868 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
1869 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
1871 data = (IPX_ADDRESS_DATA*)optval;
1872 memcpy(data->nodenum,&addr.sa_nodenum,sizeof(data->nodenum));
1873 memcpy(data->netnum,&addr.sa_netnum,sizeof(data->netnum));
1874 data->adapternum = 0;
1875 data->wan = FALSE; /* We are not on a wan for now .. */
1876 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
1877 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
1878 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit; note 1MB = 1000kB in this case */
1880 case IPX_MAX_ADAPTER_NUM:
1881 FIXME("IPX_MAX_ADAPTER_NUM\n");
1882 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
1886 FIXME("IPX optname:%x\n", optname);
1887 return SOCKET_ERROR;
1892 if( (fd = get_sock_fd( s, 0, NULL )) == -1)
1893 return SOCKET_ERROR;
1895 if (!convert_sockopt(&level, &optname)) {
1896 SetLastError(WSAENOPROTOOPT); /* Unknown option */
1900 struct linger lingval;
1901 unsigned int len, *plen = (unsigned int*)optlen;
1902 char *pval = optval;
1903 if(level == SOL_SOCKET && is_timeout_option(optname)) {
1906 pval = (char *) &tv;
1907 } else if( level == SOL_SOCKET && optname == SO_LINGER) {
1908 len = sizeof(lingval);
1910 pval = (char *) &lingval;
1912 if (getsockopt(fd, (int) level, optname, pval, plen) != 0 ) {
1913 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1915 } else if(level == SOL_SOCKET && is_timeout_option(optname)) {
1916 if( *optlen >= sizeof(INT) ) {
1917 *optlen = sizeof(INT);
1918 *(INT*)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1920 SetLastError(WSAEFAULT);
1923 } else if( level == SOL_SOCKET && optname == SO_LINGER) {
1924 if( *optlen >= sizeof( LINGER) ) {
1925 (( LINGER *) optval)->l_onoff = lingval.l_onoff;
1926 (( LINGER *) optval)->l_linger = lingval.l_linger;
1928 SetLastError(WSAEFAULT);
1933 release_sock_fd( s, fd );
1938 /***********************************************************************
1942 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
1944 return htonl(hostlong);
1948 /***********************************************************************
1952 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
1954 return htons(hostshort);
1957 /***********************************************************************
1958 * WSAHtonl (WS2_32.46)
1959 * From MSDN decription of error codes, this function should also
1960 * check if WinSock has been initialized and the socket is a valid
1961 * socket. But why? This function only translates a host byte order
1962 * u_long into a network byte order u_long...
1964 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
1968 *lpnetlong = htonl(hostlong);
1971 WSASetLastError(WSAEFAULT);
1972 return SOCKET_ERROR;
1975 /***********************************************************************
1976 * WSAHtons (WS2_32.47)
1977 * From MSDN decription of error codes, this function should also
1978 * check if WinSock has been initialized and the socket is a valid
1979 * socket. But why? This function only translates a host byte order
1980 * u_short into a network byte order u_short...
1982 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
1987 *lpnetshort = htons(hostshort);
1990 WSASetLastError(WSAEFAULT);
1991 return SOCKET_ERROR;
1995 /***********************************************************************
1996 * inet_addr (WINSOCK.10)
1997 * inet_addr (WS2_32.11)
1999 WS_u_long WINAPI WS_inet_addr(const char *cp)
2001 return inet_addr(cp);
2005 /***********************************************************************
2006 * ntohl (WINSOCK.14)
2009 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2011 return ntohl(netlong);
2015 /***********************************************************************
2016 * ntohs (WINSOCK.15)
2019 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2021 return ntohs(netshort);
2025 /***********************************************************************
2026 * inet_ntoa (WS2_32.12)
2028 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2030 /* use "buffer for dummies" here because some applications have a
2031 * propensity to decode addresses in ws_hostent structure without
2032 * saving them first...
2034 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2036 char* s = inet_ntoa(*((struct in_addr*)&in));
2042 SetLastError(wsaErrno());
2046 /**********************************************************************
2047 * WSAIoctl (WS2_32.50)
2050 INT WINAPI WSAIoctl(SOCKET s,
2051 DWORD dwIoControlCode,
2054 LPVOID lpbOutBuffer,
2056 LPDWORD lpcbBytesReturned,
2057 LPWSAOVERLAPPED lpOverlapped,
2058 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2060 TRACE("%d, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
2061 s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpbOutBuffer,
2062 cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
2064 switch( dwIoControlCode )
2067 if (cbInBuffer != sizeof(WS_u_long)) {
2068 WSASetLastError(WSAEFAULT);
2069 return SOCKET_ERROR;
2071 return WS_ioctlsocket( s, WS_FIONBIO, lpvInBuffer);
2074 if (cbOutBuffer != sizeof(WS_u_long)) {
2075 WSASetLastError(WSAEFAULT);
2076 return SOCKET_ERROR;
2078 return WS_ioctlsocket( s, WS_FIONREAD, lpbOutBuffer);
2080 case SIO_GET_INTERFACE_LIST:
2082 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
2083 DWORD size, numInt, apiReturn;
2086 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
2090 WSASetLastError(WSAEFAULT);
2091 return SOCKET_ERROR;
2093 if (!lpcbBytesReturned)
2095 WSASetLastError(WSAEFAULT);
2096 return SOCKET_ERROR;
2099 fd = get_sock_fd( s, 0, NULL );
2100 if (fd == -1) return SOCKET_ERROR;
2102 apiReturn = GetAdaptersInfo(NULL, &size);
2103 if (apiReturn == ERROR_NO_DATA)
2107 else if (apiReturn == ERROR_BUFFER_OVERFLOW)
2109 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
2113 if (GetAdaptersInfo(table, &size) == NO_ERROR)
2115 PIP_ADAPTER_INFO ptr;
2117 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > cbOutBuffer)
2119 WARN("Buffer too small = %u, cbOutBuffer = %u\n", size, cbOutBuffer);
2120 HeapFree(GetProcessHeap(),0,table);
2121 release_sock_fd( s, fd );
2122 WSASetLastError(WSAEFAULT);
2123 return SOCKET_ERROR;
2125 for (ptr = table, numInt = 0; ptr;
2126 ptr = ptr->Next, intArray++, numInt++)
2128 unsigned int addr, mask, bcast;
2129 struct ifreq ifInfo;
2131 /* Socket Status Flags */
2132 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
2133 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2135 ERR("Error obtaining status flags for socket!\n");
2136 HeapFree(GetProcessHeap(),0,table);
2137 release_sock_fd( s, fd );
2138 WSASetLastError(WSAEINVAL);
2139 return SOCKET_ERROR;
2143 /* set flags; the values of IFF_* are not the same
2144 under Linux and Windows, therefore must generate
2146 intArray->iiFlags = 0;
2147 if (ifInfo.ifr_flags & IFF_BROADCAST)
2148 intArray->iiFlags |= WS_IFF_BROADCAST;
2149 #ifdef IFF_POINTOPOINT
2150 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
2151 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
2153 if (ifInfo.ifr_flags & IFF_LOOPBACK)
2154 intArray->iiFlags |= WS_IFF_LOOPBACK;
2155 if (ifInfo.ifr_flags & IFF_UP)
2156 intArray->iiFlags |= WS_IFF_UP;
2157 if (ifInfo.ifr_flags & IFF_MULTICAST)
2158 intArray->iiFlags |= WS_IFF_MULTICAST;
2161 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
2162 mask = inet_addr(ptr->IpAddressList.IpMask.String);
2163 bcast = addr | (addr & !mask);
2164 intArray->iiAddress.AddressIn.sin_family = AF_INET;
2165 intArray->iiAddress.AddressIn.sin_port = 0;
2166 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
2168 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2169 intArray->iiNetmask.AddressIn.sin_port = 0;
2170 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
2172 intArray->iiBroadcastAddress.AddressIn.sin_family =
2174 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
2175 intArray->iiBroadcastAddress.AddressIn.sin_addr.
2181 ERR("Unable to get interface table!\n");
2182 release_sock_fd( s, fd );
2183 HeapFree(GetProcessHeap(),0,table);
2184 WSASetLastError(WSAEINVAL);
2185 return SOCKET_ERROR;
2187 HeapFree(GetProcessHeap(),0,table);
2191 release_sock_fd( s, fd );
2192 WSASetLastError(WSAEINVAL);
2193 return SOCKET_ERROR;
2198 ERR("Unable to get interface table!\n");
2199 release_sock_fd( s, fd );
2200 WSASetLastError(WSAEINVAL);
2201 return SOCKET_ERROR;
2203 /* Calculate the size of the array being returned */
2204 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2205 release_sock_fd( s, fd );
2209 case SIO_ADDRESS_LIST_CHANGE:
2210 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
2211 /* FIXME: error and return code depend on whether socket was created
2212 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
2216 FIXME("SIO_FLUSH: stub.\n");
2220 FIXME("unsupported WS_IOCTL cmd (%08x)\n", dwIoControlCode);
2221 WSASetLastError(WSAEOPNOTSUPP);
2222 return SOCKET_ERROR;
2229 /***********************************************************************
2230 * ioctlsocket (WS2_32.10)
2232 int WINAPI WS_ioctlsocket(SOCKET s, long cmd, WS_u_long *argp)
2237 TRACE("socket %04x, cmd %08lx, ptr %p\n", s, cmd, argp);
2246 if( _get_sock_mask(s) )
2248 /* AsyncSelect()'ed sockets are always nonblocking */
2249 if (*argp) return 0;
2250 SetLastError(WSAEINVAL);
2251 return SOCKET_ERROR;
2253 fd = get_sock_fd( s, 0, NULL );
2259 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
2260 ret = fcntl( fd, F_SETFL, O_NONBLOCK );
2264 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
2265 ret = fcntl( fd, F_SETFL, 0 );
2267 release_sock_fd( s, fd );
2269 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2271 return SOCKET_ERROR;
2278 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2279 SetLastError(WSAEINVAL);
2280 return SOCKET_ERROR;
2282 case SIOCGIFBRDADDR:
2283 case SIOCGIFNETMASK:
2285 /* These don't need any special handling. They are used by
2286 WsControl, and are here to suppress an unnecessary warning. */
2290 /* Netscape tries hard to use bogus ioctl 0x667e */
2291 /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
2292 * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
2294 WARN("\tunknown WS_IOCTL cmd (%08lx)\n", cmd);
2298 fd = get_sock_fd( s, 0, NULL );
2301 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2303 release_sock_fd( s, fd );
2306 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2307 release_sock_fd( s, fd );
2309 return SOCKET_ERROR;
2312 /***********************************************************************
2313 * listen (WS2_32.13)
2315 int WINAPI WS_listen(SOCKET s, int backlog)
2317 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2319 TRACE("socket %04x, backlog %d\n", s, backlog);
2322 if (listen(fd, backlog) == 0)
2324 release_sock_fd( s, fd );
2325 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
2327 FD_CONNECT|FD_WINE_CONNECTED);
2330 SetLastError(wsaErrno());
2331 release_sock_fd( s, fd );
2333 return SOCKET_ERROR;
2336 /***********************************************************************
2339 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2341 DWORD n, dwFlags = flags;
2347 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2348 return SOCKET_ERROR;
2353 /***********************************************************************
2354 * recvfrom (WS2_32.17)
2356 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2357 struct WS_sockaddr *from, int *fromlen)
2359 DWORD n, dwFlags = flags;
2365 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2366 return SOCKET_ERROR;
2371 /* allocate a poll array for the corresponding fd sets */
2372 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
2373 const WS_fd_set *exceptfds, int *count_ptr )
2375 int i, j = 0, count = 0;
2378 if (readfds) count += readfds->fd_count;
2379 if (writefds) count += writefds->fd_count;
2380 if (exceptfds) count += exceptfds->fd_count;
2382 if (!count) return NULL;
2383 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0])))) return NULL;
2385 for (i = 0; i < readfds->fd_count; i++, j++)
2387 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
2388 fds[j].events = POLLIN;
2392 for (i = 0; i < writefds->fd_count; i++, j++)
2394 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
2395 fds[j].events = POLLOUT;
2399 for (i = 0; i < exceptfds->fd_count; i++, j++)
2401 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
2402 fds[j].events = POLLHUP;
2408 /* release the file descriptor obtained in fd_sets_to_poll */
2409 /* must be called with the original fd_set arrays, before calling get_poll_results */
2410 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
2411 const WS_fd_set *exceptfds, struct pollfd *fds )
2417 for (i = 0; i < readfds->fd_count; i++, j++)
2418 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
2422 for (i = 0; i < writefds->fd_count; i++, j++)
2423 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
2427 for (i = 0; i < exceptfds->fd_count; i++, j++)
2428 if (fds[j].fd != -1)
2430 /* make sure we have a real error before releasing the fd */
2431 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
2432 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
2437 /* map the poll results back into the Windows fd sets */
2438 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
2439 const struct pollfd *fds )
2441 int i, j = 0, k, total = 0;
2445 for (i = k = 0; i < readfds->fd_count; i++, j++)
2446 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
2447 readfds->fd_count = k;
2452 for (i = k = 0; i < writefds->fd_count; i++, j++)
2453 if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
2454 writefds->fd_count = k;
2459 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
2460 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
2461 exceptfds->fd_count = k;
2468 /***********************************************************************
2469 * select (WS2_32.18)
2471 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
2472 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
2473 const struct WS_timeval* ws_timeout)
2475 struct pollfd *pollfds;
2476 int count, ret, timeout = -1;
2478 TRACE("read %p, write %p, excp %p timeout %p\n",
2479 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
2481 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )) && count)
2483 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2487 if (ws_timeout) timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
2489 ret = poll( pollfds, count, timeout );
2490 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2492 if (ret == -1) SetLastError(wsaErrno());
2493 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2494 HeapFree( GetProcessHeap(), 0, pollfds );
2499 /***********************************************************************
2502 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
2508 wsabuf.buf = (char*) buf;
2510 if ( WSASendTo( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
2511 return SOCKET_ERROR;
2516 /***********************************************************************
2517 * WSASend (WS2_32.72)
2519 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2520 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2521 LPWSAOVERLAPPED lpOverlapped,
2522 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2524 return WSASendTo( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
2525 NULL, 0, lpOverlapped, lpCompletionRoutine );
2528 /***********************************************************************
2529 * WSASendDisconnect (WS2_32.73)
2531 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
2533 return WS_shutdown( s, SD_SEND );
2537 /***********************************************************************
2538 * WSASendTo (WS2_32.74)
2540 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2541 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2542 const struct WS_sockaddr *to, int tolen,
2543 LPWSAOVERLAPPED lpOverlapped,
2544 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2547 int n, fd, err = WSAENOTSOCK, flags, ret;
2548 struct iovec* iovec;
2549 struct ws2_async *wsa;
2550 IO_STATUS_BLOCK* iosb;
2552 TRACE("socket %04x, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
2553 s, lpBuffers, dwBufferCount, dwFlags,
2554 to, tolen, lpOverlapped, lpCompletionRoutine);
2556 fd = get_sock_fd( s, FILE_WRITE_DATA, &flags );
2557 TRACE( "fd=%d, flags=%x\n", fd, flags );
2559 if ( fd == -1 ) return SOCKET_ERROR;
2561 if (flags & FD_FLAG_SEND_SHUTDOWN)
2563 WSASetLastError( WSAESHUTDOWN );
2567 if ( !lpNumberOfBytesSent )
2573 iovec = HeapAlloc(GetProcessHeap(), 0, dwBufferCount * sizeof(struct iovec) );
2581 for ( i = 0; i < dwBufferCount; i++ )
2583 iovec[i].iov_base = lpBuffers[i].buf;
2584 iovec[i].iov_len = lpBuffers[i].len;
2587 if ( (lpOverlapped || lpCompletionRoutine) && flags & FD_FLAG_OVERLAPPED )
2589 wsa = WS2_make_async( s, ws2m_write, iovec, dwBufferCount,
2590 &dwFlags, (struct WS_sockaddr*) to, &tolen,
2591 lpOverlapped, lpCompletionRoutine, &iosb );
2598 if ( ( ret = ws2_queue_async( wsa, iosb ) ) )
2600 err = NtStatusToWSAError( ret );
2602 if ( !lpOverlapped )
2603 HeapFree( GetProcessHeap(), 0, iosb );
2604 HeapFree( GetProcessHeap(), 0, wsa );
2607 release_sock_fd( s, fd );
2609 /* Try immediate completion */
2612 if ( WSAGetOverlappedResult( s, lpOverlapped,
2613 lpNumberOfBytesSent, FALSE, &dwFlags) )
2616 if ( (err = WSAGetLastError()) != WSA_IO_INCOMPLETE )
2620 WSASetLastError( WSA_IO_PENDING );
2621 return SOCKET_ERROR;
2624 if (_is_blocking(s))
2626 /* FIXME: exceptfds? */
2627 int timeout = GET_SNDTIMEO(fd);
2628 if( !do_block(fd, POLLOUT, timeout)) {
2630 goto err_free; /* msdn says a timeout in send is fatal */
2634 n = WS2_send( fd, iovec, dwBufferCount, to, tolen, dwFlags );
2638 if ( err == WSAEWOULDBLOCK )
2639 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
2643 TRACE(" -> %i bytes\n", n);
2644 *lpNumberOfBytesSent = n;
2646 HeapFree( GetProcessHeap(), 0, iovec );
2647 release_sock_fd( s, fd );
2651 HeapFree( GetProcessHeap(), 0, iovec );
2654 release_sock_fd( s, fd );
2657 WARN(" -> ERROR %d\n", err);
2658 WSASetLastError(err);
2659 return SOCKET_ERROR;
2662 /***********************************************************************
2663 * sendto (WS2_32.20)
2665 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
2666 const struct WS_sockaddr *to, int tolen)
2672 wsabuf.buf = (char*) buf;
2674 if ( WSASendTo(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
2675 return SOCKET_ERROR;
2680 /***********************************************************************
2681 * setsockopt (WS2_32.21)
2683 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
2684 const char *optval, int optlen)
2688 struct linger linger;
2689 struct timeval tval;
2691 TRACE("socket: %04x, level %d, name %d, ptr %p, len %d\n",
2692 s, level, optname, optval, optlen);
2694 /* SO_OPENTYPE does not require a valid socket handle. */
2695 if (level == WS_SOL_SOCKET && optname == WS_SO_OPENTYPE)
2697 if (optlen < sizeof(int) || !optval)
2699 SetLastError(WSAEFAULT);
2700 return SOCKET_ERROR;
2702 get_per_thread_data()->opentype = *(const int *)optval;
2703 TRACE("setting global SO_OPENTYPE to 0x%x\n", *(const int *)optval );
2707 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
2708 * socket. This will either not happen under windows or it is ignored in
2709 * windows (but it works in linux and therefore prevents the game from
2710 * finding games outside the current network) */
2711 if ( level==WS_SOL_SOCKET && optname==WS_SO_DONTROUTE )
2713 FIXME("Does windows ignore SO_DONTROUTE?\n");
2718 if(level == NSPROTO_IPX)
2723 fd = get_sock_fd( s, 0, NULL );
2724 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
2726 /* We try to set the ipx type on ipx socket level. */
2728 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
2730 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
2731 return SOCKET_ERROR;
2736 /* Should we retrieve val using a getsockopt call and then
2737 * set the modified one? */
2738 val.ipx_pt = *optval;
2739 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
2742 release_sock_fd( s, fd );
2744 case IPX_FILTERPTYPE:
2745 /* Sets the receive filter packet type, at the moment we don't support it */
2746 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
2748 /* Returning 0 is better for now than returning a SOCKET_ERROR */
2751 FIXME("opt_name:%x\n", optname);
2752 return SOCKET_ERROR;
2758 /* Is a privileged and useless operation, so we don't. */
2759 if ((optname == WS_SO_DEBUG) && (level == WS_SOL_SOCKET))
2761 FIXME("(%d,SOL_SOCKET,SO_DEBUG,%p(%d)) attempted (is privileged). Ignoring.\n",s,optval,*(const DWORD*)optval);
2765 if(optname == WS_SO_DONTLINGER && level == WS_SOL_SOCKET) {
2766 /* This is unique to WinSock and takes special conversion */
2767 linger.l_onoff = *((const int*)optval) ? 0: 1;
2768 linger.l_linger = 0;
2770 optval = (char*)&linger;
2771 optlen = sizeof(struct linger);
2776 if (!convert_sockopt(&level, &optname)) {
2777 ERR("Invalid level (%d) or optname (%d)\n", level, optname);
2778 SetLastError(WSAENOPROTOOPT);
2779 return SOCKET_ERROR;
2781 if (optname == SO_LINGER && optval) {
2782 linger.l_onoff = ((LINGER*)optval)->l_onoff;
2783 linger.l_linger = ((LINGER*)optval)->l_linger;
2784 /* FIXME: what is documented behavior if SO_LINGER optval
2786 optval = (char*)&linger;
2787 optlen = sizeof(struct linger);
2789 else if (optval && optlen < sizeof(int))
2791 woptval= *((const INT16 *) optval);
2792 optval= (char*) &woptval;
2795 if (level == SOL_SOCKET && is_timeout_option(optname))
2797 if (optlen == sizeof(UINT32)) {
2798 /* WinSock passes miliseconds instead of struct timeval */
2799 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
2800 tval.tv_sec = *(const UINT32*)optval / 1000;
2801 /* min of 500 milisec */
2802 if (tval.tv_sec == 0 && tval.tv_usec < 500000)
2803 tval.tv_usec = 500000;
2804 optlen = sizeof(struct timeval);
2805 optval = (char*)&tval;
2806 } else if (optlen == sizeof(struct timeval)) {
2807 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
2809 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
2813 if (level == SOL_SOCKET && optname == SO_RCVBUF && *(const int*)optval < 2048)
2815 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
2821 fd = get_sock_fd( s, 0, NULL );
2822 if (fd == -1) return SOCKET_ERROR;
2824 if (setsockopt(fd, level, optname, optval, optlen) == 0)
2826 release_sock_fd( s, fd );
2829 TRACE("Setting socket error, %d\n", wsaErrno());
2830 SetLastError(wsaErrno());
2831 release_sock_fd( s, fd );
2832 return SOCKET_ERROR;
2835 /***********************************************************************
2836 * shutdown (WS2_32.22)
2838 int WINAPI WS_shutdown(SOCKET s, int how)
2840 int fd, flags, err = WSAENOTSOCK;
2841 unsigned int clear_flags = 0;
2843 fd = get_sock_fd( s, 0, &flags );
2844 TRACE("socket %04x, how %i %x\n", s, how, flags );
2847 return SOCKET_ERROR;
2851 case 0: /* drop receives */
2852 clear_flags |= FD_READ;
2854 case 1: /* drop sends */
2855 clear_flags |= FD_WRITE;
2857 case 2: /* drop all */
2858 clear_flags |= FD_READ|FD_WRITE;
2860 clear_flags |= FD_WINE_LISTENING;
2863 if ( flags & FD_FLAG_OVERLAPPED ) {
2868 err = WS2_register_async_shutdown( s, ws2m_sd_read );
2871 err = WS2_register_async_shutdown( s, ws2m_sd_write );
2875 err = WS2_register_async_shutdown( s, ws2m_sd_read );
2876 if (!err) err = WS2_register_async_shutdown( s, ws2m_sd_write );
2879 if (err) goto error;
2881 else /* non-overlapped mode */
2883 if ( shutdown( fd, how ) )
2890 release_sock_fd( s, fd );
2891 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
2892 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
2896 release_sock_fd( s, fd );
2897 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
2898 WSASetLastError( err );
2899 return SOCKET_ERROR;
2902 /***********************************************************************
2903 * socket (WS2_32.23)
2905 SOCKET WINAPI WS_socket(int af, int type, int protocol)
2907 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
2909 return WSASocketA( af, type, protocol, NULL, 0,
2910 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
2914 /***********************************************************************
2915 * gethostbyaddr (WS2_32.51)
2917 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
2919 struct WS_hostent *retval = NULL;
2920 struct hostent* host;
2922 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
2925 struct hostent hostentry;
2928 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
2930 int res = gethostbyaddr_r(addr, len, type,
2931 &hostentry, extrabuf, ebufsize, &host, &locerr);
2932 if( res != ERANGE) break;
2934 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
2936 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
2938 EnterCriticalSection( &csWSgetXXXbyYYY );
2939 host = gethostbyaddr(addr, len, type);
2940 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
2942 if( host != NULL ) retval = WS_dup_he(host);
2943 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
2944 HeapFree(GetProcessHeap(),0,extrabuf);
2946 LeaveCriticalSection( &csWSgetXXXbyYYY );
2948 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
2952 /***********************************************************************
2953 * gethostbyname (WS2_32.52)
2955 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
2957 struct WS_hostent *retval = NULL;
2958 struct hostent* host;
2959 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
2962 struct hostent hostentry;
2963 int locerr = ENOBUFS;
2968 if( gethostname( buf, 100) == -1) {
2969 SetLastError( WSAENOBUFS); /* appropriate ? */
2973 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
2975 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
2977 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
2978 if( res != ERANGE) break;
2980 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
2982 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
2984 EnterCriticalSection( &csWSgetXXXbyYYY );
2985 host = gethostbyname(name);
2986 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
2988 if (host) retval = WS_dup_he(host);
2989 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
2990 HeapFree(GetProcessHeap(),0,extrabuf);
2992 LeaveCriticalSection( &csWSgetXXXbyYYY );
2994 TRACE( "%s ret %p\n", debugstr_a(name), retval );
2999 /***********************************************************************
3000 * getprotobyname (WS2_32.53)
3002 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3004 struct WS_protoent* retval = NULL;
3005 #ifdef HAVE_GETPROTOBYNAME
3006 struct protoent* proto;
3007 EnterCriticalSection( &csWSgetXXXbyYYY );
3008 if( (proto = getprotobyname(name)) != NULL )
3010 retval = WS_dup_pe(proto);
3013 MESSAGE("protocol %s not found; You might want to add "
3014 "this to /etc/protocols\n", debugstr_a(name) );
3015 SetLastError(WSANO_DATA);
3017 LeaveCriticalSection( &csWSgetXXXbyYYY );
3019 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3024 /***********************************************************************
3025 * getprotobynumber (WS2_32.54)
3027 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3029 struct WS_protoent* retval = NULL;
3030 #ifdef HAVE_GETPROTOBYNUMBER
3031 struct protoent* proto;
3032 EnterCriticalSection( &csWSgetXXXbyYYY );
3033 if( (proto = getprotobynumber(number)) != NULL )
3035 retval = WS_dup_pe(proto);
3038 MESSAGE("protocol number %d not found; You might want to add "
3039 "this to /etc/protocols\n", number );
3040 SetLastError(WSANO_DATA);
3042 LeaveCriticalSection( &csWSgetXXXbyYYY );
3044 TRACE("%i ret %p\n", number, retval);
3049 /***********************************************************************
3050 * getservbyname (WS2_32.55)
3052 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3054 struct WS_servent* retval = NULL;
3055 struct servent* serv;
3057 char *proto_str = NULL;
3059 if (!(name_str = strdup_lower(name))) return NULL;
3061 if (proto && *proto)
3063 if (!(proto_str = strdup_lower(proto)))
3065 HeapFree( GetProcessHeap(), 0, name_str );
3070 EnterCriticalSection( &csWSgetXXXbyYYY );
3071 serv = getservbyname(name_str, proto_str);
3074 retval = WS_dup_se(serv);
3076 else SetLastError(WSANO_DATA);
3077 LeaveCriticalSection( &csWSgetXXXbyYYY );
3078 HeapFree( GetProcessHeap(), 0, proto_str );
3079 HeapFree( GetProcessHeap(), 0, name_str );
3080 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
3084 /***********************************************************************
3085 * freeaddrinfo (WS2_32.@)
3087 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
3090 struct WS_addrinfo *next;
3092 HeapFree(GetProcessHeap(),0,res->ai_canonname);
3093 HeapFree(GetProcessHeap(),0,res->ai_addr);
3094 next = res->ai_next;
3095 HeapFree(GetProcessHeap(),0,res);
3100 /* helper functions for getaddrinfo() */
3101 static int convert_aiflag_w2u(int winflags) {
3102 int i, unixflags = 0;
3104 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3105 if (ws_aiflag_map[i][0] & winflags) {
3106 unixflags |= ws_aiflag_map[i][1];
3107 winflags &= ~ws_aiflag_map[i][0];
3110 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
3114 static int convert_aiflag_u2w(int unixflags) {
3115 int i, winflags = 0;
3117 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3118 if (ws_aiflag_map[i][1] & unixflags) {
3119 winflags |= ws_aiflag_map[i][0];
3120 unixflags &= ~ws_aiflag_map[i][1];
3122 if (unixflags) /* will warn usually */
3123 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
3127 static int convert_eai_u2w(int unixret) {
3130 for (i=0;ws_eai_map[i][0];i++)
3131 if (ws_eai_map[i][1] == unixret)
3132 return ws_eai_map[i][0];
3136 /***********************************************************************
3137 * getaddrinfo (WS2_32.@)
3139 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
3141 #if HAVE_GETADDRINFO
3142 struct addrinfo *unixaires = NULL;
3144 struct addrinfo unixhints, *punixhints = NULL;
3145 CHAR *node = NULL, *serv = NULL;
3148 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
3151 if (!(serv = strdup_lower(servname))) {
3152 HeapFree(GetProcessHeap(), 0, node);
3153 return WSA_NOT_ENOUGH_MEMORY;
3158 punixhints = &unixhints;
3160 memset(&unixhints, 0, sizeof(unixhints));
3161 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
3162 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
3163 punixhints->ai_family = 0;
3165 punixhints->ai_family = convert_af_w2u(hints->ai_family);
3166 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
3167 punixhints->ai_socktype = 0;
3169 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
3170 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
3171 punixhints->ai_protocol = 0;
3173 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
3176 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
3177 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
3179 TRACE("%s, %s %p -> %p %d\n", nodename, servname, hints, res, result);
3181 HeapFree(GetProcessHeap(), 0, node);
3182 HeapFree(GetProcessHeap(), 0, serv);
3185 struct addrinfo *xuai = unixaires;
3186 struct WS_addrinfo **xai = res;
3190 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
3196 *xai = ai;xai = &ai->ai_next;
3197 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
3198 ai->ai_family = convert_af_u2w(xuai->ai_family);
3199 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
3200 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
3201 if (xuai->ai_canonname) {
3202 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
3203 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
3204 if (!ai->ai_canonname)
3206 strcpy(ai->ai_canonname,xuai->ai_canonname);
3208 len = xuai->ai_addrlen;
3209 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
3212 ai->ai_addrlen = len;
3214 int winlen = ai->ai_addrlen;
3216 if (!ws_sockaddr_u2ws(xuai->ai_addr, xuai->ai_addrlen, ai->ai_addr, &winlen)) {
3217 ai->ai_addrlen = winlen;
3221 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
3224 ai->ai_addrlen = len;
3226 xuai = xuai->ai_next;
3228 freeaddrinfo(unixaires);
3230 result = convert_eai_u2w(result);
3235 if (*res) WS_freeaddrinfo(*res);
3236 if (unixaires) freeaddrinfo(unixaires);
3238 return WSA_NOT_ENOUGH_MEMORY;
3240 FIXME("getaddrinfo() failed, not found during buildtime.\n");
3245 /***********************************************************************
3246 * GetAddrInfoW (WS2_32.@)
3248 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
3250 FIXME("empty stub!\n");
3254 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
3255 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
3257 #if HAVE_GETNAMEINFO
3259 const struct sockaddr* sa_u;
3262 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
3263 serv, servlen, flags);
3265 sa_u = ws_sockaddr_ws2u(sa, salen, &size);
3268 WSASetLastError(WSAEFAULT);
3269 return WSA_NOT_ENOUGH_MEMORY;
3271 ret = getnameinfo(sa_u, size, host, hostlen, serv, servlen, convert_aiflag_w2u(flags));
3273 ws_sockaddr_free(sa_u, sa);
3274 return convert_eai_u2w(ret);
3276 FIXME("getnameinfo() failed, not found during buildtime.\n");
3281 /***********************************************************************
3282 * getservbyport (WS2_32.56)
3284 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
3286 struct WS_servent* retval = NULL;
3287 #ifdef HAVE_GETSERVBYPORT
3288 struct servent* serv;
3289 char *proto_str = NULL;
3291 if (proto && *proto)
3293 if (!(proto_str = strdup_lower(proto))) return NULL;
3295 EnterCriticalSection( &csWSgetXXXbyYYY );
3296 if( (serv = getservbyport(port, proto_str)) != NULL ) {
3297 retval = WS_dup_se(serv);
3299 else SetLastError(WSANO_DATA);
3300 LeaveCriticalSection( &csWSgetXXXbyYYY );
3301 HeapFree( GetProcessHeap(), 0, proto_str );
3303 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
3308 /***********************************************************************
3309 * gethostname (WS2_32.57)
3311 int WINAPI WS_gethostname(char *name, int namelen)
3313 TRACE("name %p, len %d\n", name, namelen);
3315 if (gethostname(name, namelen) == 0)
3317 TRACE("<- '%s'\n", name);
3320 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
3321 TRACE("<- ERROR !\n");
3322 return SOCKET_ERROR;
3326 /* ------------------------------------- Windows sockets extensions -- *
3328 * ------------------------------------------------------------------- */
3330 /***********************************************************************
3331 * WSAEnumNetworkEvents (WS2_32.36)
3333 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
3337 TRACE("%08x, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
3339 SERVER_START_REQ( get_socket_event )
3341 req->handle = SOCKET2HANDLE(s);
3342 req->service = TRUE;
3343 req->c_event = hEvent;
3344 wine_server_set_reply( req, lpEvent->iErrorCode, sizeof(lpEvent->iErrorCode) );
3345 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
3349 SetLastError(WSAEINVAL);
3350 return SOCKET_ERROR;
3353 /***********************************************************************
3354 * WSAEventSelect (WS2_32.39)
3356 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, long lEvent)
3360 TRACE("%08x, hEvent %p, event %08x\n", s, hEvent, (unsigned)lEvent );
3362 SERVER_START_REQ( set_socket_event )
3364 req->handle = SOCKET2HANDLE(s);
3366 req->event = hEvent;
3369 ret = wine_server_call( req );
3373 SetLastError(WSAEINVAL);
3374 return SOCKET_ERROR;
3377 /**********************************************************************
3378 * WSAGetOverlappedResult (WS2_32.40)
3380 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
3381 LPDWORD lpcbTransfer, BOOL fWait,
3386 TRACE( "socket %04x ovl %p trans %p, wait %d flags %p\n",
3387 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
3389 if ( lpOverlapped == NULL )
3391 ERR( "Invalid pointer\n" );
3392 WSASetLastError(WSA_INVALID_PARAMETER);
3398 if (lpOverlapped->hEvent)
3399 while ( WaitForSingleObjectEx(lpOverlapped->hEvent,
3400 INFINITE, TRUE) == STATUS_USER_APC );
3401 else /* busy loop */
3402 while ( ((volatile OVERLAPPED*)lpOverlapped)->Internal == STATUS_PENDING )
3406 else if ( lpOverlapped->Internal == STATUS_PENDING )
3408 /* Wait in order to give APCs a chance to run. */
3409 /* This is cheating, so we must set the event again in case of success -
3410 it may be a non-manual reset event. */
3411 while ( (r = WaitForSingleObjectEx(lpOverlapped->hEvent, 0, TRUE)) == STATUS_USER_APC );
3412 if ( r == WAIT_OBJECT_0 && lpOverlapped->hEvent )
3413 NtSetEvent( lpOverlapped->hEvent, NULL );
3417 *lpcbTransfer = lpOverlapped->InternalHigh;
3420 *lpdwFlags = lpOverlapped->u.s.Offset;
3422 switch ( lpOverlapped->Internal )
3424 case STATUS_SUCCESS:
3426 case STATUS_PENDING:
3427 WSASetLastError( WSA_IO_INCOMPLETE );
3428 if (fWait) ERR("PENDING status after waiting!\n");
3431 WSASetLastError( NtStatusToWSAError( lpOverlapped->Internal ));
3437 /***********************************************************************
3438 * WSAAsyncSelect (WS2_32.101)
3440 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, long lEvent)
3444 TRACE("%x, hWnd %p, uMsg %08x, event %08lx\n", s, hWnd, uMsg, lEvent );
3446 SERVER_START_REQ( set_socket_event )
3448 req->handle = SOCKET2HANDLE(s);
3453 ret = wine_server_call( req );
3457 SetLastError(WSAEINVAL);
3458 return SOCKET_ERROR;
3461 /***********************************************************************
3462 * WSACreateEvent (WS2_32.31)
3465 WSAEVENT WINAPI WSACreateEvent(void)
3467 /* Create a manual-reset event, with initial state: unsignaled */
3470 return CreateEventW(NULL, TRUE, FALSE, NULL);
3473 /***********************************************************************
3474 * WSACloseEvent (WS2_32.29)
3477 BOOL WINAPI WSACloseEvent(WSAEVENT event)
3479 TRACE ("event=%p\n", event);
3481 return CloseHandle(event);
3484 /***********************************************************************
3485 * WSASocketA (WS2_32.78)
3488 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
3489 LPWSAPROTOCOL_INFOA lpProtocolInfo,
3490 GROUP g, DWORD dwFlags)
3493 WSAPROTOCOL_INFOW info;
3495 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
3496 af, type, protocol, lpProtocolInfo, g, dwFlags);
3498 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
3500 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
3501 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
3502 info.szProtocol, WSAPROTOCOL_LEN + 1);
3506 WSASetLastError( WSAEINVAL);
3507 return SOCKET_ERROR;
3510 return WSASocketW(af, type, protocol, &info, g, dwFlags);
3513 /***********************************************************************
3514 * WSASocketW (WS2_32.79)
3517 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
3518 LPWSAPROTOCOL_INFOW lpProtocolInfo,
3519 GROUP g, DWORD dwFlags)
3524 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
3525 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
3528 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
3529 af, type, protocol, lpProtocolInfo, g, dwFlags );
3531 /* hack for WSADuplicateSocket */
3532 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
3533 ret = lpProtocolInfo->dwCatalogEntryId;
3534 TRACE("\tgot duplicate %04x\n", ret);
3538 /* check and convert the socket family */
3539 af = convert_af_w2u(af);
3542 FIXME("Unsupported socket family %d!\n", af);
3543 SetLastError(WSAEAFNOSUPPORT);
3544 return INVALID_SOCKET;
3547 /* check the socket type */
3548 type = convert_socktype_w2u(type);
3551 SetLastError(WSAESOCKTNOSUPPORT);
3552 return INVALID_SOCKET;
3555 /* check the protocol type */
3556 if ( protocol < 0 ) /* don't support negative values */
3558 SetLastError(WSAEPROTONOSUPPORT);
3559 return INVALID_SOCKET;
3562 if ( af == AF_UNSPEC) /* did they not specify the address family? */
3566 if (type == SOCK_STREAM) { af = AF_INET; break; }
3568 if (type == SOCK_DGRAM) { af = AF_INET; break; }
3569 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
3572 SERVER_START_REQ( create_socket )
3576 req->protocol = protocol;
3577 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
3578 req->attributes = OBJ_INHERIT;
3579 req->flags = dwFlags;
3580 set_error( wine_server_call( req ) );
3581 ret = HANDLE2SOCKET( reply->handle );
3586 TRACE("\tcreated %04x\n", ret );
3590 if (GetLastError() == WSAEACCES) /* raw socket denied */
3592 if (type == SOCK_RAW)
3593 MESSAGE("WARNING: Trying to create a socket of type SOCK_RAW, will fail unless running as root\n");
3595 MESSAGE("WS_SOCKET: not enough privileges to create socket, try running as root\n");
3596 SetLastError(WSAESOCKTNOSUPPORT);
3599 WARN("\t\tfailed!\n");
3600 return INVALID_SOCKET;
3603 /***********************************************************************
3604 * WSAJoinLeaf (WS2_32.58)
3607 SOCKET WINAPI WSAJoinLeaf(
3609 const struct WS_sockaddr *addr,
3611 LPWSABUF lpCallerData,
3612 LPWSABUF lpCalleeData,
3618 return INVALID_SOCKET;
3621 /***********************************************************************
3622 * __WSAFDIsSet (WS2_32.151)
3624 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
3626 int i = set->fd_count;
3628 TRACE("(%d,%p(%i))\n", s, set, i);
3631 if (set->fd_array[i] == s) return 1;
3635 /***********************************************************************
3636 * WSAIsBlocking (WINSOCK.114)
3637 * WSAIsBlocking (WS2_32.114)
3639 BOOL WINAPI WSAIsBlocking(void)
3641 /* By default WinSock should set all its sockets to non-blocking mode
3642 * and poll in PeekMessage loop when processing "blocking" ones. This
3643 * function is supposed to tell if the program is in this loop. Our
3644 * blocking calls are truly blocking so we always return FALSE.
3646 * Note: It is allowed to call this function without prior WSAStartup().
3653 /***********************************************************************
3654 * WSACancelBlockingCall (WINSOCK.113)
3655 * WSACancelBlockingCall (WS2_32.113)
3657 INT WINAPI WSACancelBlockingCall(void)
3663 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
3665 FIXME("How was this called?\n");
3670 /***********************************************************************
3671 * WSASetBlockingHook (WS2_32.109)
3673 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
3675 FARPROC prev = blocking_hook;
3676 blocking_hook = lpBlockFunc;
3677 TRACE("hook %p\n", lpBlockFunc);
3682 /***********************************************************************
3683 * WSAUnhookBlockingHook (WS2_32.110)
3685 INT WINAPI WSAUnhookBlockingHook(void)
3687 blocking_hook = WSA_DefaultBlockingHook;
3692 /* ----------------------------------- end of API stuff */
3694 /* ----------------------------------- helper functions -
3696 * TODO: Merge WS_dup_..() stuff into one function that
3697 * would operate with a generic structure containing internal
3698 * pointers (via a template of some kind).
3701 static int list_size(char** l, int item_size)
3706 j += (item_size) ? item_size : strlen(l[i]) + 1;
3707 j += (i + 1) * sizeof(char*); }
3711 static int list_dup(char** l_src, char** l_to, int item_size)
3716 for (i = 0; l_src[i]; i++) ;
3717 p = (char *)(l_to + i + 1);
3718 for (i = 0; l_src[i]; i++)
3720 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
3721 memcpy(p, l_src[i], count);
3726 return p - (char *)l_to;
3731 /* duplicate hostent entry
3732 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
3733 * Dito for protoent and servent.
3735 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
3738 struct WS_hostent *p_to;
3740 int size = (sizeof(*p_he) +
3741 strlen(p_he->h_name) + 1 +
3742 list_size(p_he->h_aliases, 0) +
3743 list_size(p_he->h_addr_list, p_he->h_length));
3745 if (!(p_to = check_buffer_he(size))) return NULL;
3746 p_to->h_addrtype = p_he->h_addrtype;
3747 p_to->h_length = p_he->h_length;
3749 p = (char *)(p_to + 1);
3751 strcpy(p, p_he->h_name);
3754 p_to->h_aliases = (char **)p;
3755 p += list_dup(p_he->h_aliases, p_to->h_aliases, 0);
3757 p_to->h_addr_list = (char **)p;
3758 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
3762 /* ----- protoent */
3764 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
3767 struct WS_protoent *p_to;
3769 int size = (sizeof(*p_pe) +
3770 strlen(p_pe->p_name) + 1 +
3771 list_size(p_pe->p_aliases, 0));
3773 if (!(p_to = check_buffer_pe(size))) return NULL;
3774 p_to->p_proto = p_pe->p_proto;
3776 p = (char *)(p_to + 1);
3778 strcpy(p, p_pe->p_name);
3781 p_to->p_aliases = (char **)p;
3782 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
3788 static struct WS_servent *WS_dup_se(const struct servent* p_se)
3791 struct WS_servent *p_to;
3793 int size = (sizeof(*p_se) +
3794 strlen(p_se->s_proto) + 1 +
3795 strlen(p_se->s_name) + 1 +
3796 list_size(p_se->s_aliases, 0));
3798 if (!(p_to = check_buffer_se(size))) return NULL;
3799 p_to->s_port = p_se->s_port;
3801 p = (char *)(p_to + 1);
3803 strcpy(p, p_se->s_name);
3807 strcpy(p, p_se->s_proto);
3810 p_to->s_aliases = (char **)p;
3811 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
3815 /* ----------------------------------- error handling */
3819 int loc_errno = errno;
3820 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
3824 case EINTR: return WSAEINTR;
3825 case EBADF: return WSAEBADF;
3827 case EACCES: return WSAEACCES;
3828 case EFAULT: return WSAEFAULT;
3829 case EINVAL: return WSAEINVAL;
3830 case EMFILE: return WSAEMFILE;
3831 case EWOULDBLOCK: return WSAEWOULDBLOCK;
3832 case EINPROGRESS: return WSAEINPROGRESS;
3833 case EALREADY: return WSAEALREADY;
3834 case ENOTSOCK: return WSAENOTSOCK;
3835 case EDESTADDRREQ: return WSAEDESTADDRREQ;
3836 case EMSGSIZE: return WSAEMSGSIZE;
3837 case EPROTOTYPE: return WSAEPROTOTYPE;
3838 case ENOPROTOOPT: return WSAENOPROTOOPT;
3839 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
3840 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
3841 case EOPNOTSUPP: return WSAEOPNOTSUPP;
3842 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
3843 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
3844 case EADDRINUSE: return WSAEADDRINUSE;
3845 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
3846 case ENETDOWN: return WSAENETDOWN;
3847 case ENETUNREACH: return WSAENETUNREACH;
3848 case ENETRESET: return WSAENETRESET;
3849 case ECONNABORTED: return WSAECONNABORTED;
3851 case ECONNRESET: return WSAECONNRESET;
3852 case ENOBUFS: return WSAENOBUFS;
3853 case EISCONN: return WSAEISCONN;
3854 case ENOTCONN: return WSAENOTCONN;
3855 case ESHUTDOWN: return WSAESHUTDOWN;
3856 case ETOOMANYREFS: return WSAETOOMANYREFS;
3857 case ETIMEDOUT: return WSAETIMEDOUT;
3858 case ECONNREFUSED: return WSAECONNREFUSED;
3859 case ELOOP: return WSAELOOP;
3860 case ENAMETOOLONG: return WSAENAMETOOLONG;
3861 case EHOSTDOWN: return WSAEHOSTDOWN;
3862 case EHOSTUNREACH: return WSAEHOSTUNREACH;
3863 case ENOTEMPTY: return WSAENOTEMPTY;
3865 case EPROCLIM: return WSAEPROCLIM;
3868 case EUSERS: return WSAEUSERS;
3871 case EDQUOT: return WSAEDQUOT;
3874 case ESTALE: return WSAESTALE;
3877 case EREMOTE: return WSAEREMOTE;
3880 /* just in case we ever get here and there are no problems */
3883 WARN("Unknown errno %d!\n", loc_errno);
3884 return WSAEOPNOTSUPP;
3888 UINT wsaHerrno(int loc_errno)
3891 WARN("h_errno %d.\n", loc_errno);
3895 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
3896 case TRY_AGAIN: return WSATRY_AGAIN;
3897 case NO_RECOVERY: return WSANO_RECOVERY;
3898 case NO_DATA: return WSANO_DATA;
3899 case ENOBUFS: return WSAENOBUFS;
3903 WARN("Unknown h_errno %d!\n", loc_errno);
3904 return WSAEOPNOTSUPP;
3909 /***********************************************************************
3910 * WSARecv (WS2_32.67)
3912 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3913 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
3914 LPWSAOVERLAPPED lpOverlapped,
3915 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
3917 return WSARecvFrom(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
3918 NULL, NULL, lpOverlapped, lpCompletionRoutine);
3921 /***********************************************************************
3922 * WSARecvFrom (WS2_32.69)
3924 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3925 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
3926 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
3927 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3931 int n, fd, err = WSAENOTSOCK, flags, ret;
3932 struct iovec* iovec;
3933 struct ws2_async *wsa;
3934 IO_STATUS_BLOCK* iosb;
3936 TRACE("socket %04x, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %ld, ovl %p, func %p\n",
3937 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
3938 (lpFromlen ? *lpFromlen : -1L),
3939 lpOverlapped, lpCompletionRoutine);
3941 fd = get_sock_fd( s, FILE_READ_DATA, &flags );
3942 TRACE( "fd=%d, flags=%x\n", fd, flags );
3944 if (fd == -1) return SOCKET_ERROR;
3946 if (flags & FD_FLAG_RECV_SHUTDOWN)
3948 WSASetLastError( WSAESHUTDOWN );
3952 iovec = HeapAlloc( GetProcessHeap(), 0, dwBufferCount * sizeof (struct iovec) );
3959 for (i = 0; i < dwBufferCount; i++)
3961 iovec[i].iov_base = lpBuffers[i].buf;
3962 iovec[i].iov_len = lpBuffers[i].len;
3965 if ( (lpOverlapped || lpCompletionRoutine) && flags & FD_FLAG_OVERLAPPED )
3967 wsa = WS2_make_async( s, ws2m_read, iovec, dwBufferCount,
3968 lpFlags, lpFrom, lpFromlen,
3969 lpOverlapped, lpCompletionRoutine, &iosb );
3977 if ( ( ret = ws2_queue_async( wsa, iosb )) )
3979 err = NtStatusToWSAError( ret );
3981 if ( !lpOverlapped )
3982 HeapFree( GetProcessHeap(), 0, iosb );
3983 HeapFree( GetProcessHeap(), 0, wsa );
3986 release_sock_fd( s, fd );
3988 /* Try immediate completion */
3991 if ( WSAGetOverlappedResult( s, lpOverlapped,
3992 lpNumberOfBytesRecvd, FALSE, lpFlags) )
3995 if ( (err = WSAGetLastError()) != WSA_IO_INCOMPLETE )
3999 WSASetLastError( WSA_IO_PENDING );
4000 return SOCKET_ERROR;
4003 if ( _is_blocking(s) )
4006 /* FIXME: OOB and exceptfds? */
4007 int timeout = GET_RCVTIMEO(fd);
4008 if( !do_block(fd, POLLIN, timeout)) {
4010 /* a timeout is not fatal */
4011 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4016 n = WS2_recv( fd, iovec, dwBufferCount, lpFrom, lpFromlen, lpFlags );
4023 TRACE(" -> %i bytes\n", n);
4024 *lpNumberOfBytesRecvd = n;
4026 HeapFree(GetProcessHeap(), 0, iovec);
4027 release_sock_fd( s, fd );
4028 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4033 HeapFree(GetProcessHeap(), 0, iovec);
4036 release_sock_fd( s, fd );
4039 WARN(" -> ERROR %d\n", err);
4040 WSASetLastError( err );
4041 return SOCKET_ERROR;
4044 /***********************************************************************
4045 * WSCInstallProvider (WS2_32.88)
4047 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
4048 LPCWSTR lpszProviderDllPath,
4049 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
4050 DWORD dwNumberOfEntries,
4053 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
4054 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
4055 dwNumberOfEntries, lpErrno);
4061 /***********************************************************************
4062 * WSCDeinstallProvider (WS2_32.83)
4064 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
4066 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
4072 /***********************************************************************
4073 * WSAAccept (WS2_32.26)
4075 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
4076 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
4079 int ret = 0, size = 0;
4080 WSABUF CallerId, CallerData, CalleeId, CalleeData;
4081 /* QOS SQOS, GQOS; */
4084 SOCKADDR src_addr, dst_addr;
4086 TRACE("Socket %04x, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %d\n",
4087 s, addr, addrlen, lpfnCondition, dwCallbackData);
4090 size = sizeof(src_addr);
4091 cs = WS_accept(s, &src_addr, &size);
4093 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
4095 CallerId.buf = (char *)&src_addr;
4096 CallerId.len = sizeof(src_addr);
4098 CallerData.buf = NULL;
4099 CallerData.len = (ULONG)NULL;
4101 WS_getsockname(cs, &dst_addr, &size);
4103 CalleeId.buf = (char *)&dst_addr;
4104 CalleeId.len = sizeof(dst_addr);
4107 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
4108 &CalleeId, &CalleeData, &g, dwCallbackData);
4113 if (addr && addrlen)
4114 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
4117 SERVER_START_REQ( set_socket_deferred )
4119 req->handle = SOCKET2HANDLE(s);
4120 req->deferred = SOCKET2HANDLE(cs);
4121 if ( !wine_server_call_err ( req ) )
4123 SetLastError( WSATRY_AGAIN );
4124 WS_closesocket( cs );
4128 return SOCKET_ERROR;
4131 SetLastError(WSAECONNREFUSED);
4132 return SOCKET_ERROR;
4134 FIXME("Unknown return type from Condition function\n");
4135 SetLastError(WSAENOTSOCK);
4136 return SOCKET_ERROR;
4140 /***********************************************************************
4141 * WSADuplicateSocketA (WS2_32.32)
4143 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
4147 TRACE("(%d,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4148 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4149 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
4150 /* I don't know what the real Windoze does next, this is a hack */
4151 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
4152 * the target use the global duplicate, or we could copy a reference to us to the structure
4153 * and let the target duplicate it from us, but let's do it as simple as possible */
4154 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4155 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4156 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4157 0, FALSE, DUPLICATE_SAME_ACCESS);
4158 CloseHandle(hProcess);
4159 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4163 /***********************************************************************
4164 * WSADuplicateSocketW (WS2_32.33)
4166 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
4170 TRACE("(%d,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4172 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4173 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4174 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4175 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4176 0, FALSE, DUPLICATE_SAME_ACCESS);
4177 CloseHandle(hProcess);
4178 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4182 /***********************************************************************
4183 * WSAInstallServiceClassA (WS2_32.48)
4185 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
4187 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
4188 WSASetLastError(WSAEACCES);
4189 return SOCKET_ERROR;
4192 /***********************************************************************
4193 * WSAInstallServiceClassW (WS2_32.49)
4195 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
4197 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
4198 WSASetLastError(WSAEACCES);
4199 return SOCKET_ERROR;
4202 /***********************************************************************
4203 * WSARemoveServiceClass (WS2_32.70)
4205 int WINAPI WSARemoveServiceClass(LPGUID info)
4207 FIXME("Request to remove service %p\n",info);
4208 WSASetLastError(WSATYPE_NOT_FOUND);
4209 return SOCKET_ERROR;
4212 /***********************************************************************
4213 * WSAStringToAddressA (WS2_32.80)
4215 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
4217 LPWSAPROTOCOL_INFOA lpProtocolInfo,
4218 LPSOCKADDR lpAddress,
4219 LPINT lpAddressLength)
4222 struct in_addr inetaddr;
4223 LPSTR workBuffer=NULL,ptrPort;
4225 TRACE( "(%s, %x, %p, %p, %p)\n", AddressString, AddressFamily, lpProtocolInfo,
4226 lpAddress, lpAddressLength );
4228 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
4232 workBuffer = HeapAlloc( GetProcessHeap(), 0, strlen(AddressString)+1 );
4235 strcpy(workBuffer,AddressString);
4236 switch (AddressFamily)
4239 /* caller wants to know the size of the socket buffer */
4240 if (*lpAddressLength < sizeof(SOCKADDR_IN))
4242 *lpAddressLength = sizeof(SOCKADDR_IN);
4247 /* caller wants to translate an AddressString into a SOCKADDR */
4250 memset(lpAddress,0,sizeof(SOCKADDR_IN));
4251 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
4252 ptrPort = strchr(workBuffer,':');
4255 ((LPSOCKADDR_IN)lpAddress)->sin_port = (WS_u_short)atoi(ptrPort+1);
4259 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
4260 if (inet_aton(workBuffer, &inetaddr) > 0)
4262 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
4270 FIXME("(%s, %x, %p, %p, %p) - ProtocolInfo not implemented!\n",
4271 AddressString, AddressFamily,
4272 lpProtocolInfo, lpAddress, lpAddressLength);
4276 FIXME("(%s, %x, %p, %p, %p) - AddressFamiliy not implemented!\n",
4277 AddressString, AddressFamily,
4278 lpProtocolInfo, lpAddress, lpAddressLength);
4280 HeapFree( GetProcessHeap(), 0, workBuffer );
4283 res = WSA_NOT_ENOUGH_MEMORY;
4289 WSASetLastError(res);
4290 return SOCKET_ERROR;
4293 /***********************************************************************
4294 * WSAStringToAddressW (WS2_32.81)
4296 * Does anybody know if this functions allows to use hebrew/arabic/chinese... digits?
4297 * If this should be the case, it would be required to map these digits
4298 * to Unicode digits (0-9) using FoldString first.
4300 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
4302 LPWSAPROTOCOL_INFOW lpProtocolInfo,
4303 LPSOCKADDR lpAddress,
4304 LPINT lpAddressLength)
4307 LPSTR workBuffer=NULL;
4308 WSAPROTOCOL_INFOA infoA;
4309 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
4311 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
4312 lpAddress, lpAddressLength );
4314 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
4316 /* if ProtocolInfo is available - convert to ANSI variant */
4319 lpProtoInfoA = &infoA;
4320 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
4322 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
4323 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
4325 WSASetLastError( WSAEINVAL);
4326 return SOCKET_ERROR;
4332 /* Translate AddressString to ANSI code page - assumes that only
4333 standard digits 0-9 are used with this API call */
4334 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
4335 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
4339 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
4340 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
4341 lpAddress,lpAddressLength);
4342 HeapFree( GetProcessHeap(), 0, workBuffer );
4346 res = WSA_NOT_ENOUGH_MEMORY;
4351 WSASetLastError(res);
4352 return SOCKET_ERROR;
4355 /***********************************************************************
4356 * WSAAddressToStringA (WS2_32.27)
4358 * See WSAAddressToStringW
4360 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
4361 LPWSAPROTOCOL_INFOA info, LPSTR string,
4365 CHAR buffer[22]; /* 12 digits + 3 dots + ':' + 5 digits + '\0' */
4368 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
4370 if (!sockaddr || len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
4371 if (!string || !lenstr) return SOCKET_ERROR;
4373 /* sin_family is guaranteed to be the first u_short */
4374 if (((SOCKADDR_IN *)sockaddr)->sin_family != AF_INET) return SOCKET_ERROR;
4376 sprintf( buffer, "%u.%u.%u.%u:%u",
4377 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
4378 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
4379 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
4380 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
4381 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
4383 p = strchr( buffer, ':' );
4384 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
4386 size = strlen( buffer );
4391 WSASetLastError(WSAEFAULT);
4392 return SOCKET_ERROR;
4395 strcpy( string, buffer );
4399 /***********************************************************************
4400 * WSAAddressToStringW (WS2_32.28)
4402 * Convert a sockaddr address into a readable address string.
4405 * sockaddr [I] Pointer to a sockaddr structure.
4406 * len [I] Size of the sockaddr structure.
4407 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
4408 * string [I/O] Pointer to a buffer to receive the address string.
4409 * lenstr [I/O] Size of the receive buffer in WCHARs.
4413 * Failure: SOCKET_ERROR
4416 * The 'info' parameter is ignored.
4419 * Only supports AF_INET addresses.
4421 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
4422 LPWSAPROTOCOL_INFOW info, LPWSTR string,
4426 WCHAR buffer[22]; /* 12 digits + 3 dots + ':' + 5 digits + '\0' */
4427 static const WCHAR format[] = { '%','u','.','%','u','.','%','u','.','%','u',':','%','u',0 };
4430 TRACE( "(%p, %x, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
4432 if (!sockaddr || len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
4433 if (!string || !lenstr) return SOCKET_ERROR;
4435 /* sin_family is guaranteed to be the first u_short */
4436 if (((SOCKADDR_IN *)sockaddr)->sin_family != AF_INET) return SOCKET_ERROR;
4438 sprintfW( buffer, format,
4439 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
4440 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
4441 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
4442 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
4443 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
4445 p = strchrW( buffer, ':' );
4446 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
4448 size = lstrlenW( buffer );
4453 return SOCKET_ERROR;
4456 lstrcpyW( string, buffer );
4460 /***********************************************************************
4461 * WSAEnumNameSpaceProvidersA (WS2_32.34)
4463 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
4465 FIXME( "(%p %p) Stub!\n", len, buffer );
4469 /***********************************************************************
4470 * WSAEnumNameSpaceProvidersW (WS2_32.35)
4472 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
4474 FIXME( "(%p %p) Stub!\n", len, buffer );
4478 /***********************************************************************
4479 * WSAGetQOSByName (WS2_32.41)
4481 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
4483 FIXME( "(0x%04x %p %p) Stub!\n", s, lpQOSName, lpQOS );
4487 /***********************************************************************
4488 * WSAGetServiceClassInfoA (WS2_32.42)
4490 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
4491 LPWSASERVICECLASSINFOA info )
4493 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
4495 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4496 return SOCKET_ERROR;
4499 /***********************************************************************
4500 * WSAGetServiceClassInfoW (WS2_32.43)
4502 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
4503 LPWSASERVICECLASSINFOW info )
4505 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
4507 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4508 return SOCKET_ERROR;
4511 /***********************************************************************
4512 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
4514 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
4516 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
4517 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4518 return SOCKET_ERROR;
4521 /***********************************************************************
4522 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
4524 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
4526 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
4527 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4528 return SOCKET_ERROR;
4531 /***********************************************************************
4532 * WSALookupServiceBeginA (WS2_32.59)
4534 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
4535 DWORD dwControlFlags,
4538 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
4540 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4541 return SOCKET_ERROR;
4544 /***********************************************************************
4545 * WSALookupServiceBeginW (WS2_32.60)
4547 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
4548 DWORD dwControlFlags,
4551 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
4553 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4554 return SOCKET_ERROR;
4557 /***********************************************************************
4558 * WSALookupServiceBeginW (WS2_32.61)
4560 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
4562 FIXME("(%p) Stub!\n", lookup );
4566 /***********************************************************************
4567 * WSALookupServiceNextA (WS2_32.62)
4569 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
4571 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
4575 /***********************************************************************
4576 * WSALookupServiceNextW (WS2_32.63)
4578 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
4580 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
4584 /***********************************************************************
4585 * WSANtohl (WS2_32.64)
4587 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
4589 TRACE( "(0x%04x 0x%08x %p)\n", s, netlong, lphostlong );
4591 if (!lphostlong) return WSAEFAULT;
4593 *lphostlong = ntohl( netlong );
4597 /***********************************************************************
4598 * WSANtohs (WS2_32.65)
4600 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
4602 TRACE( "(0x%04x 0x%08x %p)\n", s, netshort, lphostshort );
4604 if (!lphostshort) return WSAEFAULT;
4606 *lphostshort = ntohs( netshort );
4610 /***********************************************************************
4611 * WSAProviderConfigChange (WS2_32.66)
4613 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
4614 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4616 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
4617 return SOCKET_ERROR;
4620 /***********************************************************************
4621 * WSARecvDisconnect (WS2_32.68)
4623 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
4625 TRACE( "(0x%04x %p)\n", s, disconnectdata );
4627 return WS_shutdown( s, 0 );
4630 /***********************************************************************
4631 * WSASetServiceA (WS2_32.76)
4633 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
4635 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
4639 /***********************************************************************
4640 * WSASetServiceW (WS2_32.77)
4642 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
4644 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
4648 /***********************************************************************
4649 * WSCEnableNSProvider (WS2_32.84)
4651 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
4653 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
4657 /***********************************************************************
4658 * WSCGetProviderPath (WS2_32.86)
4660 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
4662 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
4664 if (!errcode || !provider || !len) return WSAEFAULT;
4666 *errcode = WSAEINVAL;
4667 return SOCKET_ERROR;
4670 /***********************************************************************
4671 * WSCInstallNameSpace (WS2_32.87)
4673 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
4674 DWORD version, LPGUID provider )
4676 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
4677 namespace, version, debugstr_guid(provider) );
4681 /***********************************************************************
4682 * WSCUnInstallNameSpace (WS2_32.89)
4684 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
4686 FIXME("(%p) Stub!\n", lpProviderId);
4690 /***********************************************************************
4691 * WSCWriteProviderOrder (WS2_32.91)
4693 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
4695 FIXME("(%p 0x%08x) Stub!\n", entry, number);