2 * based on Windows Sockets 1.1 specs
4 * Copyright (C) 1993,1994,1996,1997 John Brezak, Erik Bos, Alex Korobka.
5 * Copyright (C) 2005 Marcus Meissner
6 * Copyright (C) 2006-2008 Kai Blin
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 * NOTE: If you make any changes to fix a particular app, make sure
23 * they don't break something else like Netscape or telnet and ftp
24 * clients and servers (www.winsite.com got a lot of those).
28 #include "wine/port.h"
33 #include <sys/types.h>
37 #ifdef HAVE_SYS_IOCTL_H
38 # include <sys/ioctl.h>
40 #ifdef HAVE_SYS_FILIO_H
41 # include <sys/filio.h>
43 #ifdef HAVE_SYS_SOCKIO_H
44 # include <sys/sockio.h>
48 # include <sys/so_ioctl.h>
51 #ifdef HAVE_SYS_PARAM_H
52 # include <sys/param.h>
58 #ifdef HAVE_SYS_WAIT_H
59 # include <sys/wait.h>
64 #ifdef HAVE_SYS_SOCKET_H
65 #include <sys/socket.h>
67 #ifdef HAVE_NETINET_IN_H
68 # include <netinet/in.h>
70 #ifdef HAVE_NETINET_TCP_H
71 # include <netinet/tcp.h>
73 #ifdef HAVE_ARPA_INET_H
74 # include <arpa/inet.h>
79 #ifdef HAVE_SYS_ERRNO_H
80 #include <sys/errno.h>
89 #ifdef HAVE_ARPA_NAMESER_H
90 # include <arpa/nameser.h>
99 #ifdef HAVE_NETIPX_IPX_H
100 # include <netipx/ipx.h>
102 #elif defined(HAVE_LINUX_IPX_H)
103 # ifdef HAVE_ASM_TYPES_H
104 # include <asm/types.h>
106 # ifdef HAVE_LINUX_TYPES_H
107 # include <linux/types.h>
109 # include <linux/ipx.h>
113 #ifdef HAVE_LINUX_IRDA_H
114 # ifdef HAVE_LINUX_TYPES_H
115 # include <linux/types.h>
117 # include <linux/irda.h>
124 #ifdef HAVE_SYS_POLL_H
125 # include <sys/poll.h>
127 #ifdef HAVE_SYS_TIME_H
128 # include <sys/time.h>
131 #define NONAMELESSUNION
132 #define NONAMELESSSTRUCT
133 #include "ntstatus.h"
134 #define WIN32_NO_STATUS
139 #include "winerror.h"
141 #include "winsock2.h"
143 #include "ws2tcpip.h"
149 #include "iphlpapi.h"
150 #include "wine/server.h"
151 #include "wine/debug.h"
152 #include "wine/unicode.h"
155 # include "wsnwlink.h"
159 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
160 # define sipx_network sipx_addr.x_net
161 # define sipx_node sipx_addr.x_host.c_host
162 #endif /* __FreeBSD__ */
165 #define INADDR_NONE ~0UL
168 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
170 /* critical section to protect some non-reentrant net function */
171 extern CRITICAL_SECTION csWSgetXXXbyYYY;
173 union generic_unix_sockaddr
175 struct sockaddr addr;
176 char data[128]; /* should be big enough for all families */
179 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
181 if (!a) return "(nil)";
182 switch (a->sa_family)
185 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
186 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
187 ntohs(((const struct sockaddr_in *)a)->sin_port));
192 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
194 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
196 p = "(unknown IPv6 address)";
197 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
198 p, ntohs(sin->sin6_port));
201 return wine_dbg_sprintf("{ family %d }", a->sa_family);
205 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
206 #define SOCKET2HANDLE(s) ((HANDLE)(s))
207 #define HANDLE2SOCKET(h) ((SOCKET)(h))
209 /****************************************************************
210 * Async IO declarations
211 ****************************************************************/
213 typedef struct ws2_async
217 LPWSAOVERLAPPED user_overlapped;
218 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
219 IO_STATUS_BLOCK local_iosb;
220 struct WS_sockaddr *addr;
223 int val; /* for send operations */
224 int *ptr; /* for recv operations */
227 unsigned int n_iovecs;
228 unsigned int first_iovec;
229 struct iovec iovec[1];
232 /****************************************************************/
234 /* ----------------------------------- internal data */
236 /* ws_... struct conversion flags */
238 typedef struct /* WSAAsyncSelect() control struct */
240 HANDLE service, event, sock;
246 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
247 #define WS_MAX_UDP_DATAGRAM 1024
248 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
250 /* hostent's, servent's and protent's are stored in one buffer per thread,
251 * as documented on MSDN for the functions that return any of the buffers */
252 struct per_thread_data
255 struct WS_hostent *he_buffer;
256 struct WS_servent *se_buffer;
257 struct WS_protoent *pe_buffer;
263 static INT num_startup; /* reference counter */
264 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
266 /* function prototypes */
267 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
268 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
269 static struct WS_servent *WS_dup_se(const struct servent* p_se);
271 int WSAIOCTL_GetInterfaceCount(void);
272 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
275 UINT wsaHerrno(int errnr);
277 #define MAP_OPTION(opt) { WS_##opt, opt }
279 static const int ws_sock_map[][2] =
281 MAP_OPTION( SO_DEBUG ),
282 MAP_OPTION( SO_ACCEPTCONN ),
283 MAP_OPTION( SO_REUSEADDR ),
284 MAP_OPTION( SO_KEEPALIVE ),
285 MAP_OPTION( SO_DONTROUTE ),
286 MAP_OPTION( SO_BROADCAST ),
287 MAP_OPTION( SO_LINGER ),
288 MAP_OPTION( SO_OOBINLINE ),
289 MAP_OPTION( SO_SNDBUF ),
290 MAP_OPTION( SO_RCVBUF ),
291 MAP_OPTION( SO_ERROR ),
292 MAP_OPTION( SO_TYPE ),
294 MAP_OPTION( SO_RCVTIMEO ),
297 MAP_OPTION( SO_SNDTIMEO ),
301 static const int ws_tcp_map[][2] =
304 MAP_OPTION( TCP_NODELAY ),
308 static const int ws_ip_map[][2] =
310 MAP_OPTION( IP_MULTICAST_IF ),
311 MAP_OPTION( IP_MULTICAST_TTL ),
312 MAP_OPTION( IP_MULTICAST_LOOP ),
313 MAP_OPTION( IP_ADD_MEMBERSHIP ),
314 MAP_OPTION( IP_DROP_MEMBERSHIP ),
315 MAP_OPTION( IP_OPTIONS ),
317 MAP_OPTION( IP_HDRINCL ),
319 MAP_OPTION( IP_TOS ),
320 MAP_OPTION( IP_TTL ),
323 static const int ws_af_map[][2] =
325 MAP_OPTION( AF_UNSPEC ),
326 MAP_OPTION( AF_INET ),
327 MAP_OPTION( AF_INET6 ),
329 MAP_OPTION( AF_IPX ),
332 MAP_OPTION( AF_IRDA ),
334 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
337 static const int ws_socktype_map[][2] =
339 MAP_OPTION( SOCK_DGRAM ),
340 MAP_OPTION( SOCK_STREAM ),
341 MAP_OPTION( SOCK_RAW ),
342 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
345 static const int ws_proto_map[][2] =
347 MAP_OPTION( IPPROTO_IP ),
348 MAP_OPTION( IPPROTO_TCP ),
349 MAP_OPTION( IPPROTO_UDP ),
350 MAP_OPTION( IPPROTO_ICMP ),
351 MAP_OPTION( IPPROTO_IGMP ),
352 MAP_OPTION( IPPROTO_RAW ),
353 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
356 static const int ws_aiflag_map[][2] =
358 MAP_OPTION( AI_PASSIVE ),
359 MAP_OPTION( AI_CANONNAME ),
360 MAP_OPTION( AI_NUMERICHOST ),
361 /* Linux/UNIX knows a lot more. But Windows only
362 * has 3 as far as I could see. -Marcus
366 static const int ws_niflag_map[][2] =
368 MAP_OPTION( NI_NOFQDN ),
369 MAP_OPTION( NI_NUMERICHOST ),
370 MAP_OPTION( NI_NAMEREQD ),
371 MAP_OPTION( NI_NUMERICSERV ),
372 MAP_OPTION( NI_DGRAM ),
375 static const int ws_eai_map[][2] =
377 MAP_OPTION( EAI_AGAIN ),
378 MAP_OPTION( EAI_BADFLAGS ),
379 MAP_OPTION( EAI_FAIL ),
380 MAP_OPTION( EAI_FAMILY ),
381 MAP_OPTION( EAI_MEMORY ),
382 /* Note: EAI_NODATA is deprecated, but still
383 * used by Windows and Linux... We map the newer
384 * EAI_NONAME to EAI_NODATA for now until Windows
388 MAP_OPTION( EAI_NODATA ),
391 { WS_EAI_NODATA, EAI_NONAME },
394 MAP_OPTION( EAI_SERVICE ),
395 MAP_OPTION( EAI_SOCKTYPE ),
399 static const char magic_loopback_addr[] = {127, 12, 34, 56};
401 static inline DWORD NtStatusToWSAError( const DWORD status )
403 /* We only need to cover the status codes set by server async request handling */
407 case STATUS_SUCCESS: wserr = 0; break;
408 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
409 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
410 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
411 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
412 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
413 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
414 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
415 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
417 if ( status >= WSABASEERR && status <= WSABASEERR+1004 )
418 /* It is not an NT status code but a winsock error */
422 wserr = RtlNtStatusToDosError( status );
423 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
429 /* set last error code from NT status without mapping WSA errors */
430 static inline unsigned int set_error( unsigned int err )
434 err = NtStatusToWSAError( err );
440 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
443 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
448 static inline void release_sock_fd( SOCKET s, int fd )
450 wine_server_release_fd( SOCKET2HANDLE(s), fd );
453 static void _enable_event( HANDLE s, unsigned int event,
454 unsigned int sstate, unsigned int cstate )
456 SERVER_START_REQ( enable_socket_event )
458 req->handle = wine_server_obj_handle( s );
460 req->sstate = sstate;
461 req->cstate = cstate;
462 wine_server_call( req );
467 static int _is_blocking(SOCKET s)
470 SERVER_START_REQ( get_socket_event )
472 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
473 req->service = FALSE;
475 wine_server_call( req );
476 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
482 static unsigned int _get_sock_mask(SOCKET s)
485 SERVER_START_REQ( get_socket_event )
487 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
488 req->service = FALSE;
490 wine_server_call( req );
497 static void _sync_sock_state(SOCKET s)
499 /* do a dummy wineserver request in order to let
500 the wineserver run through its select loop once */
501 (void)_is_blocking(s);
504 static int _get_sock_error(SOCKET s, unsigned int bit)
506 int events[FD_MAX_EVENTS];
508 SERVER_START_REQ( get_socket_event )
510 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
511 req->service = FALSE;
513 wine_server_set_reply( req, events, sizeof(events) );
514 wine_server_call( req );
520 static struct per_thread_data *get_per_thread_data(void)
522 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
523 /* lazy initialization */
526 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
527 NtCurrentTeb()->WinSockData = ptb;
532 static void free_per_thread_data(void)
534 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
538 /* delete scratch buffers */
539 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
540 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
541 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
542 ptb->he_buffer = NULL;
543 ptb->se_buffer = NULL;
544 ptb->pe_buffer = NULL;
546 HeapFree( GetProcessHeap(), 0, ptb );
547 NtCurrentTeb()->WinSockData = NULL;
550 /***********************************************************************
551 * DllMain (WS2_32.init)
553 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
555 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
557 case DLL_PROCESS_ATTACH:
559 case DLL_PROCESS_DETACH:
560 free_per_thread_data();
563 case DLL_THREAD_DETACH:
564 free_per_thread_data();
570 /***********************************************************************
573 * Converts socket flags from Windows format.
574 * Return 1 if converted, 0 if not (error).
576 static int convert_sockopt(INT *level, INT *optname)
583 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
584 if( ws_sock_map[i][0] == *optname )
586 *optname = ws_sock_map[i][1];
590 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
593 *level = IPPROTO_TCP;
594 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
595 if ( ws_tcp_map[i][0] == *optname )
597 *optname = ws_tcp_map[i][1];
601 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
605 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
606 if (ws_ip_map[i][0] == *optname )
608 *optname = ws_ip_map[i][1];
612 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
614 default: FIXME("Unimplemented or unknown socket level\n");
619 /* ----------------------------------- Per-thread info (or per-process?) */
621 static char *strdup_lower(const char *str)
624 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
628 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
631 else SetLastError(WSAENOBUFS);
635 static inline int sock_error_p(int s)
637 unsigned int optval, optlen;
639 optlen = sizeof(optval);
640 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
641 if (optval) WARN("\t[%i] error: %d\n", s, optval);
645 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
646 * from an fd and return the value converted to milli seconds
647 * or -1 if there is an infinite time out */
648 static inline int get_rcvsnd_timeo( int fd, int optname)
651 unsigned int len = sizeof(tv);
652 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
654 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
655 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
660 /* macro wrappers for portability */
662 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
664 #define GET_RCVTIMEO(fd) (-1)
668 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
670 #define GET_SNDTIMEO(fd) (-1)
673 /* utility: given an fd, will block until one of the events occurs */
674 static inline int do_block( int fd, int events, int timeout )
682 while ((ret = poll(&pfd, 1, timeout)) < 0)
693 convert_af_w2u(int windowsaf) {
696 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
697 if (ws_af_map[i][0] == windowsaf)
698 return ws_af_map[i][1];
699 FIXME("unhandled Windows address family %d\n", windowsaf);
704 convert_af_u2w(int unixaf) {
707 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
708 if (ws_af_map[i][1] == unixaf)
709 return ws_af_map[i][0];
710 FIXME("unhandled UNIX address family %d\n", unixaf);
715 convert_proto_w2u(int windowsproto) {
718 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
719 if (ws_proto_map[i][0] == windowsproto)
720 return ws_proto_map[i][1];
721 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
726 convert_proto_u2w(int unixproto) {
729 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
730 if (ws_proto_map[i][1] == unixproto)
731 return ws_proto_map[i][0];
732 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
737 convert_socktype_w2u(int windowssocktype) {
740 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
741 if (ws_socktype_map[i][0] == windowssocktype)
742 return ws_socktype_map[i][1];
743 FIXME("unhandled Windows socket type %d\n", windowssocktype);
748 convert_socktype_u2w(int unixsocktype) {
751 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
752 if (ws_socktype_map[i][1] == unixsocktype)
753 return ws_socktype_map[i][0];
754 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
758 /* ----------------------------------- API -----
760 * Init / cleanup / error checking.
763 /***********************************************************************
764 * WSAStartup (WS2_32.115)
766 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
768 TRACE("verReq=%x\n", wVersionRequested);
770 if (LOBYTE(wVersionRequested) < 1)
771 return WSAVERNOTSUPPORTED;
773 if (!lpWSAData) return WSAEINVAL;
777 /* that's the whole of the negotiation for now */
778 lpWSAData->wVersion = wVersionRequested;
779 /* return winsock information */
780 lpWSAData->wHighVersion = 0x0202;
781 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
782 strcpy(lpWSAData->szSystemStatus, "Running" );
783 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
784 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
785 /* don't do anything with lpWSAData->lpVendorInfo */
786 /* (some apps don't allocate the space for this field) */
788 TRACE("succeeded\n");
793 /***********************************************************************
794 * WSACleanup (WS2_32.116)
796 INT WINAPI WSACleanup(void)
802 SetLastError(WSANOTINITIALISED);
807 /***********************************************************************
808 * WSAGetLastError (WINSOCK.111)
809 * WSAGetLastError (WS2_32.111)
811 INT WINAPI WSAGetLastError(void)
813 return GetLastError();
816 /***********************************************************************
817 * WSASetLastError (WS2_32.112)
819 void WINAPI WSASetLastError(INT iError) {
820 SetLastError(iError);
823 static struct WS_hostent *check_buffer_he(int size)
825 struct per_thread_data * ptb = get_per_thread_data();
828 if (ptb->he_len >= size ) return ptb->he_buffer;
829 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
831 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
832 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
833 return ptb->he_buffer;
836 static struct WS_servent *check_buffer_se(int size)
838 struct per_thread_data * ptb = get_per_thread_data();
841 if (ptb->se_len >= size ) return ptb->se_buffer;
842 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
844 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
845 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
846 return ptb->se_buffer;
849 static struct WS_protoent *check_buffer_pe(int size)
851 struct per_thread_data * ptb = get_per_thread_data();
854 if (ptb->pe_len >= size ) return ptb->pe_buffer;
855 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
857 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
858 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
859 return ptb->pe_buffer;
862 /* ----------------------------------- i/o APIs */
864 static inline BOOL supported_pf(int pf)
885 /**********************************************************************/
887 /* Returns the length of the converted address if successful, 0 if it was too small to
890 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
891 union generic_unix_sockaddr *uaddr)
893 unsigned int uaddrlen = 0;
895 switch (wsaddr->sa_family)
900 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
901 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
903 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
906 uaddrlen = sizeof(struct sockaddr_ipx);
907 memset( uaddr, 0, uaddrlen );
908 uipx->sipx_family=AF_IPX;
909 uipx->sipx_port=wsipx->sa_socket;
910 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
913 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
914 #ifdef IPX_FRAME_NONE
915 uipx->sipx_type=IPX_FRAME_NONE;
921 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
922 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
924 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
925 * scope_id, one without.
927 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
928 uaddrlen = sizeof(struct sockaddr_in6);
929 memset( uaddr, 0, uaddrlen );
930 uin6->sin6_family = AF_INET6;
931 uin6->sin6_port = win6->sin6_port;
932 uin6->sin6_flowinfo = win6->sin6_flowinfo;
933 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
934 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
936 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
939 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
943 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
944 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
946 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
948 uaddrlen = sizeof(struct sockaddr_in);
949 memset( uaddr, 0, uaddrlen );
950 uin->sin_family = AF_INET;
951 uin->sin_port = win->sin_port;
952 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
957 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
958 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
960 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
962 uaddrlen = sizeof(struct sockaddr_irda);
963 memset( uaddr, 0, uaddrlen );
964 uin->sir_family = AF_IRDA;
965 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
967 unsigned int lsap_sel;
969 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
970 uin->sir_lsap_sel = lsap_sel;
974 uin->sir_lsap_sel = LSAP_ANY;
975 memcpy( uin->sir_name, win->irdaServiceName, 25 );
977 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
982 /* Try to determine the needed space by the passed windows sockaddr space */
984 default: /* likely a ipv4 address */
985 case sizeof(struct WS_sockaddr_in):
986 uaddrlen = sizeof(struct sockaddr_in);
989 case sizeof(struct WS_sockaddr_ipx):
990 uaddrlen = sizeof(struct sockaddr_ipx);
994 case sizeof(SOCKADDR_IRDA):
995 uaddrlen = sizeof(struct sockaddr_irda);
998 case sizeof(struct WS_sockaddr_in6):
999 case sizeof(struct WS_sockaddr_in6_old):
1000 uaddrlen = sizeof(struct sockaddr_in6);
1003 memset( uaddr, 0, uaddrlen );
1007 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1013 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1015 switch (uaddr->sa_family)
1019 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
1024 static const struct sockaddr_in6 emptyAddr;
1025 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1026 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1030 static const struct sockaddr_in emptyAddr;
1031 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1032 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1037 FIXME("unknown address family %d\n", uaddr->sa_family);
1042 /* Returns 0 if successful, -1 if the buffer is too small */
1043 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1047 switch(uaddr->sa_family)
1052 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1053 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1056 switch (*wsaddrlen) /* how much can we copy? */
1060 *wsaddrlen = sizeof(*wsipx);
1061 wsipx->sa_socket=uipx->sipx_port;
1065 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1073 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1079 wsipx->sa_family=WS_AF_IPX;
1091 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1092 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1094 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1096 win->irdaAddressFamily = WS_AF_IRDA;
1097 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1098 if (uin->sir_lsap_sel != LSAP_ANY)
1099 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1101 memcpy( win->irdaServiceName, uin->sir_name,
1102 sizeof(win->irdaServiceName) );
1107 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1108 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1110 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1112 win6old->sin6_family = WS_AF_INET6;
1113 win6old->sin6_port = uin6->sin6_port;
1114 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1115 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1116 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1117 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1118 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1119 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1120 win6->sin6_scope_id = uin6->sin6_scope_id;
1121 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1127 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1128 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1130 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1132 win->sin_family = WS_AF_INET;
1133 win->sin_port = uin->sin_port;
1134 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1135 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1136 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1140 memset(wsaddr,0,*wsaddrlen);
1144 FIXME("Unknown address family %d\n", uaddr->sa_family);
1150 /**************************************************************************
1151 * Functions for handling overlapped I/O
1152 **************************************************************************/
1154 /* user APC called upon async completion */
1155 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1157 ws2_async *wsa = arg;
1159 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1160 iosb->Information, wsa->user_overlapped,
1162 HeapFree( GetProcessHeap(), 0, wsa );
1165 /***********************************************************************
1166 * WS2_recv (INTERNAL)
1168 * Workhorse for both synchronous and asynchronous recv() operations.
1170 static int WS2_recv( int fd, struct ws2_async *wsa )
1173 union generic_unix_sockaddr unix_sockaddr;
1176 hdr.msg_name = NULL;
1180 hdr.msg_namelen = sizeof(unix_sockaddr);
1181 hdr.msg_name = &unix_sockaddr;
1184 hdr.msg_namelen = 0;
1186 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1187 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1188 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1189 hdr.msg_accrights = NULL;
1190 hdr.msg_accrightslen = 0;
1192 hdr.msg_control = NULL;
1193 hdr.msg_controllen = 0;
1197 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1200 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1201 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1203 * quoting linux 2.6 net/ipv4/tcp.c:
1204 * "According to UNIX98, msg_name/msg_namelen are ignored
1205 * on connected socket. I was just happy when found this 8) --ANK"
1207 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1208 * connection-oriented sockets, so don't try to update lpFrom.
1210 if (wsa->addr && hdr.msg_namelen)
1211 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1216 /***********************************************************************
1217 * WS2_async_recv (INTERNAL)
1219 * Handler for overlapped recv() operations.
1221 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1223 ws2_async* wsa = user;
1228 case STATUS_ALERTED:
1229 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1232 result = WS2_recv( fd, wsa );
1233 wine_server_release_fd( wsa->hSocket, fd );
1236 status = STATUS_SUCCESS;
1237 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1241 if (errno == EINTR || errno == EAGAIN)
1243 status = STATUS_PENDING;
1244 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1249 status = wsaErrno(); /* FIXME: is this correct ???? */
1254 if (status != STATUS_PENDING)
1256 iosb->u.Status = status;
1257 iosb->Information = result;
1258 *apc = ws2_async_apc;
1263 /***********************************************************************
1264 * WS2_send (INTERNAL)
1266 * Workhorse for both synchronous and asynchronous send() operations.
1268 static int WS2_send( int fd, struct ws2_async *wsa )
1271 union generic_unix_sockaddr unix_addr;
1273 hdr.msg_name = NULL;
1274 hdr.msg_namelen = 0;
1278 hdr.msg_name = &unix_addr;
1279 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
1280 if ( !hdr.msg_namelen )
1286 #if defined(HAVE_IPX) && defined(SOL_IPX)
1287 if(wsa->addr->sa_family == WS_AF_IPX)
1289 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1291 unsigned int len=sizeof(int);
1293 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1294 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1295 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1296 * ipx type in the sockaddr_opx structure with the stored value.
1298 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1299 uipx->sipx_type = val;
1304 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1305 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1306 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1307 hdr.msg_accrights = NULL;
1308 hdr.msg_accrightslen = 0;
1310 hdr.msg_control = NULL;
1311 hdr.msg_controllen = 0;
1315 return sendmsg(fd, &hdr, wsa->flags);
1318 /***********************************************************************
1319 * WS2_async_send (INTERNAL)
1321 * Handler for overlapped send() operations.
1323 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1325 ws2_async* wsa = user;
1330 case STATUS_ALERTED:
1331 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1334 /* check to see if the data is ready (non-blocking) */
1335 result = WS2_send( fd, wsa );
1336 wine_server_release_fd( wsa->hSocket, fd );
1340 int totalLength = 0;
1342 status = STATUS_SUCCESS;
1343 for (i = 0; i < wsa->n_iovecs; i++)
1344 totalLength += wsa->iovec[i].iov_len;
1345 if (result < totalLength)
1346 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1350 if (errno == EINTR || errno == EAGAIN)
1352 status = STATUS_PENDING;
1353 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1357 /* We set the status to a winsock error code and check for that
1358 later in NtStatusToWSAError () */
1359 status = wsaErrno();
1365 if (status != STATUS_PENDING)
1367 iosb->u.Status = status;
1368 iosb->Information = result;
1369 *apc = ws2_async_apc;
1374 /***********************************************************************
1375 * WS2_async_shutdown (INTERNAL)
1377 * Handler for shutdown() operations on overlapped sockets.
1379 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
1381 ws2_async* wsa = user;
1386 case STATUS_ALERTED:
1387 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1390 switch ( wsa->type )
1392 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1393 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1395 wine_server_release_fd( wsa->hSocket, fd );
1396 status = err ? wsaErrno() : STATUS_SUCCESS;
1399 iosb->u.Status = status;
1400 *apc = ws2_async_apc;
1404 /***********************************************************************
1405 * WS2_register_async_shutdown (INTERNAL)
1407 * Helper function for WS_shutdown() on overlapped sockets.
1409 static int WS2_register_async_shutdown( SOCKET s, int type )
1411 struct ws2_async *wsa;
1414 TRACE("s %ld type %d\n", s, type);
1416 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1420 wsa->hSocket = SOCKET2HANDLE(s);
1422 wsa->completion_func = NULL;
1424 SERVER_START_REQ( register_async )
1427 req->async.handle = wine_server_obj_handle( wsa->hSocket );
1428 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
1429 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
1430 req->async.arg = wine_server_client_ptr( wsa );
1431 req->async.cvalue = 0;
1432 status = wine_server_call( req );
1436 if (status != STATUS_PENDING)
1438 HeapFree( GetProcessHeap(), 0, wsa );
1439 return NtStatusToWSAError( status );
1444 /***********************************************************************
1447 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1453 TRACE("socket %04lx\n", s );
1454 is_blocking = _is_blocking(s);
1459 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1460 if (fd == -1) return INVALID_SOCKET;
1462 do_block(fd, POLLIN, -1);
1463 _sync_sock_state(s); /* let wineserver notice connection */
1464 release_sock_fd( s, fd );
1465 /* retrieve any error codes from it */
1466 SetLastError(_get_sock_error(s, FD_ACCEPT_BIT));
1467 /* FIXME: care about the error? */
1469 SERVER_START_REQ( accept_socket )
1471 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1472 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1473 req->attributes = OBJ_INHERIT;
1474 set_error( wine_server_call( req ) );
1475 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
1480 if (addr) WS_getpeername(as, addr, addrlen32);
1483 } while (is_blocking);
1484 return INVALID_SOCKET;
1487 /***********************************************************************
1490 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1492 int fd = get_sock_fd( s, 0, NULL );
1493 int res = SOCKET_ERROR;
1495 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1499 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
1501 SetLastError(WSAEAFNOSUPPORT);
1505 union generic_unix_sockaddr uaddr;
1506 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1509 SetLastError(WSAEFAULT);
1514 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
1515 if (name->sa_family == WS_AF_INET6 &&
1516 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
1519 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
1521 release_sock_fd( s, fd );
1522 SetLastError(WSAEAFNOSUPPORT);
1523 return SOCKET_ERROR;
1527 if (name->sa_family == WS_AF_INET)
1529 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1530 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1532 /* Trying to bind to the default host interface, using
1533 * INADDR_ANY instead*/
1534 WARN("Trying to bind to magic IP address, using "
1535 "INADDR_ANY instead.\n");
1536 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
1539 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
1541 int loc_errno = errno;
1542 WARN("\tfailure - errno = %i\n", errno);
1547 SetLastError(WSAENOTSOCK);
1550 SetLastError(WSAEINVAL);
1553 SetLastError(wsaErrno());
1559 res=0; /* success */
1563 release_sock_fd( s, fd );
1568 /***********************************************************************
1569 * closesocket (WS2_32.3)
1571 int WINAPI WS_closesocket(SOCKET s)
1573 TRACE("socket %04lx\n", s);
1574 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
1575 return SOCKET_ERROR;
1578 /***********************************************************************
1579 * connect (WS2_32.4)
1581 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1583 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1585 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1589 union generic_unix_sockaddr uaddr;
1590 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1594 SetLastError(WSAEFAULT);
1598 if (name->sa_family == WS_AF_INET)
1600 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1601 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1603 /* Trying to connect to magic replace-loopback address,
1604 * assuming we really want to connect to localhost */
1605 TRACE("Trying to connect to magic IP address, using "
1606 "INADDR_LOOPBACK instead.\n");
1607 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
1611 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
1612 goto connect_success;
1615 if (errno == EINPROGRESS)
1617 /* tell wineserver that a connection is in progress */
1618 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1619 FD_CONNECT|FD_READ|FD_WRITE,
1620 FD_WINE_CONNECTED|FD_WINE_LISTENING);
1621 if (_is_blocking(s))
1625 do_block(fd, POLLIN | POLLOUT, -1);
1626 _sync_sock_state(s); /* let wineserver notice connection */
1627 /* retrieve any error codes from it */
1628 result = _get_sock_error(s, FD_CONNECT_BIT);
1630 SetLastError(result);
1633 goto connect_success;
1638 SetLastError(WSAEWOULDBLOCK);
1643 SetLastError(wsaErrno());
1645 release_sock_fd( s, fd );
1647 return SOCKET_ERROR;
1650 release_sock_fd( s, fd );
1651 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1652 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1653 FD_CONNECT|FD_WINE_LISTENING);
1657 /***********************************************************************
1658 * WSAConnect (WS2_32.30)
1660 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
1661 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1662 LPQOS lpSQOS, LPQOS lpGQOS )
1664 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1665 FIXME("unsupported parameters!\n");
1666 return WS_connect( s, name, namelen );
1670 /***********************************************************************
1671 * getpeername (WS2_32.5)
1673 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1678 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, *namelen);
1680 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1681 if( (name == NULL) || (namelen == NULL) )
1683 SetLastError( WSAEFAULT );
1684 return SOCKET_ERROR;
1687 fd = get_sock_fd( s, 0, NULL );
1692 union generic_unix_sockaddr uaddr;
1693 unsigned int uaddrlen = sizeof(uaddr);
1695 if (getpeername(fd, &uaddr.addr, &uaddrlen) != 0)
1697 SetLastError(wsaErrno());
1699 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1701 /* The buffer was too small */
1702 SetLastError(WSAEFAULT);
1708 release_sock_fd( s, fd );
1713 /***********************************************************************
1714 * getsockname (WS2_32.6)
1716 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1721 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
1723 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1724 if( (name == NULL) || (namelen == NULL) )
1726 SetLastError( WSAEFAULT );
1727 return SOCKET_ERROR;
1730 fd = get_sock_fd( s, 0, NULL );
1735 union generic_unix_sockaddr uaddr;
1736 unsigned int uaddrlen = sizeof(uaddr);
1738 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
1740 SetLastError(wsaErrno());
1742 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
1744 SetLastError(WSAEINVAL);
1746 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1748 /* The buffer was too small */
1749 SetLastError(WSAEFAULT);
1755 release_sock_fd( s, fd );
1760 /***********************************************************************
1761 * getsockopt (WS2_32.7)
1763 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1764 INT optname, char *optval, INT *optlen)
1769 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
1770 s, level, optname, optval, *optlen);
1778 /* Handle common cases. The special cases are below, sorted
1780 case WS_SO_ACCEPTCONN:
1781 case WS_SO_BROADCAST:
1784 case WS_SO_KEEPALIVE:
1785 case WS_SO_OOBINLINE:
1787 case WS_SO_REUSEADDR:
1790 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1791 return SOCKET_ERROR;
1792 convert_sockopt(&level, &optname);
1793 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1795 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1798 release_sock_fd( s, fd );
1801 case WS_SO_DONTLINGER:
1803 struct linger lingval;
1804 unsigned int len = sizeof(struct linger);
1806 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
1808 SetLastError(WSAEFAULT);
1809 return SOCKET_ERROR;
1811 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1812 return SOCKET_ERROR;
1814 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1816 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1821 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
1822 *optlen = sizeof(BOOL);
1825 release_sock_fd( s, fd );
1829 /* As mentioned in setsockopt, Windows ignores this, so we
1830 * always return true here */
1831 case WS_SO_DONTROUTE:
1832 if (!optlen || *optlen < sizeof(BOOL) || !optval)
1834 SetLastError(WSAEFAULT);
1835 return SOCKET_ERROR;
1837 *(BOOL *)optval = TRUE;
1838 *optlen = sizeof(BOOL);
1843 struct linger lingval;
1844 unsigned int len = sizeof(struct linger);
1846 /* struct linger and LINGER have different sizes */
1847 if (!optlen || *optlen < sizeof(LINGER) || !optval)
1849 SetLastError(WSAEFAULT);
1850 return SOCKET_ERROR;
1852 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1853 return SOCKET_ERROR;
1855 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1857 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1862 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
1863 ((LINGER *)optval)->l_linger = lingval.l_linger;
1864 *optlen = sizeof(struct linger);
1867 release_sock_fd( s, fd );
1871 case WS_SO_MAX_MSG_SIZE:
1872 if (!optlen || *optlen < sizeof(int) || !optval)
1874 SetLastError(WSAEFAULT);
1875 return SOCKET_ERROR;
1877 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
1878 *(int *)optval = 65507;
1879 *optlen = sizeof(int);
1882 /* SO_OPENTYPE does not require a valid socket handle. */
1883 case WS_SO_OPENTYPE:
1884 if (!optlen || *optlen < sizeof(int) || !optval)
1886 SetLastError(WSAEFAULT);
1887 return SOCKET_ERROR;
1889 *(int *)optval = get_per_thread_data()->opentype;
1890 *optlen = sizeof(int);
1891 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
1895 case WS_SO_RCVTIMEO:
1898 case WS_SO_SNDTIMEO:
1900 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
1903 unsigned int len = sizeof(struct timeval);
1905 if (!optlen || *optlen < sizeof(int)|| !optval)
1907 SetLastError(WSAEFAULT);
1908 return SOCKET_ERROR;
1910 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1911 return SOCKET_ERROR;
1913 convert_sockopt(&level, &optname);
1914 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
1916 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1921 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1922 *optlen = sizeof(int);
1925 release_sock_fd( s, fd );
1930 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
1931 SetLastError(WSAENOPROTOOPT);
1932 return SOCKET_ERROR;
1933 } /* end switch(optname) */
1934 }/* end case WS_SOL_SOCKET */
1938 struct WS_sockaddr_ipx addr;
1939 IPX_ADDRESS_DATA *data;
1944 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
1946 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
1953 socklen_t len=sizeof(struct ipx);
1954 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
1957 *optval = (int)val.ipx_pt;
1960 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
1961 release_sock_fd( s, fd );
1966 * On a Win2000 system with one network card there are usually
1967 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
1968 * Using this call you can then retrieve info about this all.
1969 * In case of Linux it is a bit different. Usually you have
1970 * only "one" device active and further it is not possible to
1971 * query things like the linkspeed.
1973 FIXME("IPX_ADDRESS\n");
1974 namelen = sizeof(struct WS_sockaddr_ipx);
1975 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
1976 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
1978 data = (IPX_ADDRESS_DATA*)optval;
1979 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
1980 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
1981 data->adapternum = 0;
1982 data->wan = FALSE; /* We are not on a wan for now .. */
1983 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
1984 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
1985 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
1986 * note 1MB = 1000kB in this case */
1989 case IPX_MAX_ADAPTER_NUM:
1990 FIXME("IPX_MAX_ADAPTER_NUM\n");
1991 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
1995 FIXME("IPX optname:%x\n", optname);
1996 return SOCKET_ERROR;
1997 }/* end switch(optname) */
1998 } /* end case NSPROTO_IPX */
2000 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
2001 case WS_IPPROTO_TCP:
2004 case WS_TCP_NODELAY:
2005 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2006 return SOCKET_ERROR;
2007 convert_sockopt(&level, &optname);
2008 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2010 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2013 release_sock_fd( s, fd );
2016 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
2017 return SOCKET_ERROR;
2022 case WS_IP_ADD_MEMBERSHIP:
2023 case WS_IP_DROP_MEMBERSHIP:
2027 case WS_IP_MULTICAST_IF:
2028 case WS_IP_MULTICAST_LOOP:
2029 case WS_IP_MULTICAST_TTL:
2033 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2034 return SOCKET_ERROR;
2035 convert_sockopt(&level, &optname);
2036 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2038 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2041 release_sock_fd( s, fd );
2043 case WS_IP_DONTFRAGMENT:
2044 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
2045 *(BOOL*)optval = FALSE;
2048 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
2049 return SOCKET_ERROR;
2052 FIXME("Unknown level: 0x%08x\n", level);
2053 return SOCKET_ERROR;
2054 } /* end switch(level) */
2057 /***********************************************************************
2061 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
2063 return htonl(hostlong);
2067 /***********************************************************************
2071 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
2073 return htons(hostshort);
2076 /***********************************************************************
2077 * WSAHtonl (WS2_32.46)
2078 * From MSDN description of error codes, this function should also
2079 * check if WinSock has been initialized and the socket is a valid
2080 * socket. But why? This function only translates a host byte order
2081 * u_long into a network byte order u_long...
2083 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
2087 *lpnetlong = htonl(hostlong);
2090 WSASetLastError(WSAEFAULT);
2091 return SOCKET_ERROR;
2094 /***********************************************************************
2095 * WSAHtons (WS2_32.47)
2096 * From MSDN description of error codes, this function should also
2097 * check if WinSock has been initialized and the socket is a valid
2098 * socket. But why? This function only translates a host byte order
2099 * u_short into a network byte order u_short...
2101 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2106 *lpnetshort = htons(hostshort);
2109 WSASetLastError(WSAEFAULT);
2110 return SOCKET_ERROR;
2114 /***********************************************************************
2115 * inet_addr (WINSOCK.10)
2116 * inet_addr (WS2_32.11)
2118 WS_u_long WINAPI WS_inet_addr(const char *cp)
2120 if (!cp) return INADDR_NONE;
2121 return inet_addr(cp);
2125 /***********************************************************************
2126 * ntohl (WINSOCK.14)
2129 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2131 return ntohl(netlong);
2135 /***********************************************************************
2136 * ntohs (WINSOCK.15)
2139 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2141 return ntohs(netshort);
2145 /***********************************************************************
2146 * inet_ntoa (WS2_32.12)
2148 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2150 /* use "buffer for dummies" here because some applications have a
2151 * propensity to decode addresses in ws_hostent structure without
2152 * saving them first...
2154 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2156 char* s = inet_ntoa(*((struct in_addr*)&in));
2162 SetLastError(wsaErrno());
2166 /**********************************************************************
2167 * WSAIoctl (WS2_32.50)
2170 INT WINAPI WSAIoctl(SOCKET s,
2171 DWORD dwIoControlCode,
2174 LPVOID lpbOutBuffer,
2176 LPDWORD lpcbBytesReturned,
2177 LPWSAOVERLAPPED lpOverlapped,
2178 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2180 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
2181 s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpbOutBuffer,
2182 cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
2184 switch( dwIoControlCode )
2187 if (cbInBuffer != sizeof(WS_u_long)) {
2188 WSASetLastError(WSAEFAULT);
2189 return SOCKET_ERROR;
2191 return WS_ioctlsocket( s, WS_FIONBIO, lpvInBuffer);
2194 if (cbOutBuffer != sizeof(WS_u_long)) {
2195 WSASetLastError(WSAEFAULT);
2196 return SOCKET_ERROR;
2198 return WS_ioctlsocket( s, WS_FIONREAD, lpbOutBuffer);
2200 case WS_SIO_GET_INTERFACE_LIST:
2202 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
2203 DWORD size, numInt, apiReturn;
2206 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
2210 WSASetLastError(WSAEFAULT);
2211 return SOCKET_ERROR;
2213 if (!lpcbBytesReturned)
2215 WSASetLastError(WSAEFAULT);
2216 return SOCKET_ERROR;
2219 fd = get_sock_fd( s, 0, NULL );
2220 if (fd == -1) return SOCKET_ERROR;
2222 apiReturn = GetAdaptersInfo(NULL, &size);
2223 if (apiReturn == ERROR_NO_DATA)
2227 else if (apiReturn == ERROR_BUFFER_OVERFLOW)
2229 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
2233 if (GetAdaptersInfo(table, &size) == NO_ERROR)
2235 PIP_ADAPTER_INFO ptr;
2237 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > cbOutBuffer)
2239 WARN("Buffer too small = %u, cbOutBuffer = %u\n", size, cbOutBuffer);
2240 HeapFree(GetProcessHeap(),0,table);
2241 release_sock_fd( s, fd );
2242 WSASetLastError(WSAEFAULT);
2243 return SOCKET_ERROR;
2245 for (ptr = table, numInt = 0; ptr;
2246 ptr = ptr->Next, intArray++, numInt++)
2248 unsigned int addr, mask, bcast;
2249 struct ifreq ifInfo;
2251 /* Socket Status Flags */
2252 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
2253 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2255 ERR("Error obtaining status flags for socket!\n");
2256 HeapFree(GetProcessHeap(),0,table);
2257 release_sock_fd( s, fd );
2258 WSASetLastError(WSAEINVAL);
2259 return SOCKET_ERROR;
2263 /* set flags; the values of IFF_* are not the same
2264 under Linux and Windows, therefore must generate
2266 intArray->iiFlags = 0;
2267 if (ifInfo.ifr_flags & IFF_BROADCAST)
2268 intArray->iiFlags |= WS_IFF_BROADCAST;
2269 #ifdef IFF_POINTOPOINT
2270 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
2271 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
2273 if (ifInfo.ifr_flags & IFF_LOOPBACK)
2274 intArray->iiFlags |= WS_IFF_LOOPBACK;
2275 if (ifInfo.ifr_flags & IFF_UP)
2276 intArray->iiFlags |= WS_IFF_UP;
2277 if (ifInfo.ifr_flags & IFF_MULTICAST)
2278 intArray->iiFlags |= WS_IFF_MULTICAST;
2281 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
2282 mask = inet_addr(ptr->IpAddressList.IpMask.String);
2283 bcast = addr | ~mask;
2284 intArray->iiAddress.AddressIn.sin_family = AF_INET;
2285 intArray->iiAddress.AddressIn.sin_port = 0;
2286 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
2288 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2289 intArray->iiNetmask.AddressIn.sin_port = 0;
2290 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
2292 intArray->iiBroadcastAddress.AddressIn.sin_family =
2294 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
2295 intArray->iiBroadcastAddress.AddressIn.sin_addr.
2301 ERR("Unable to get interface table!\n");
2302 release_sock_fd( s, fd );
2303 HeapFree(GetProcessHeap(),0,table);
2304 WSASetLastError(WSAEINVAL);
2305 return SOCKET_ERROR;
2307 HeapFree(GetProcessHeap(),0,table);
2311 release_sock_fd( s, fd );
2312 WSASetLastError(WSAEINVAL);
2313 return SOCKET_ERROR;
2318 ERR("Unable to get interface table!\n");
2319 release_sock_fd( s, fd );
2320 WSASetLastError(WSAEINVAL);
2321 return SOCKET_ERROR;
2323 /* Calculate the size of the array being returned */
2324 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2325 release_sock_fd( s, fd );
2329 case WS_SIO_ADDRESS_LIST_CHANGE:
2330 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
2331 /* FIXME: error and return code depend on whether socket was created
2332 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
2335 case WS_SIO_ADDRESS_LIST_QUERY:
2339 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
2341 if (!lpcbBytesReturned)
2343 WSASetLastError(WSAEFAULT);
2344 return SOCKET_ERROR;
2347 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
2349 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
2352 if (!table || GetAdaptersInfo(table, &size))
2354 HeapFree(GetProcessHeap(), 0, table);
2355 WSASetLastError(WSAEINVAL);
2356 return SOCKET_ERROR;
2359 for (p = table, num = 0; p; p = p->Next)
2360 if (p->IpAddressList.IpAddress.String[0]) num++;
2362 need = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
2363 need += sizeof(SOCKADDR) * num;
2364 *lpcbBytesReturned = need;
2366 if (need > cbOutBuffer)
2368 HeapFree(GetProcessHeap(), 0, table);
2369 WSASetLastError(WSAEFAULT);
2370 return SOCKET_ERROR;
2377 SOCKET_ADDRESS_LIST *sa_list = (SOCKET_ADDRESS_LIST *)lpbOutBuffer;
2378 SOCKADDR_IN *sockaddr;
2380 sa = sa_list->Address;
2381 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
2382 sa_list->iAddressCount = num;
2384 for (p = table, i = 0; p; p = p->Next)
2386 if (!p->IpAddressList.IpAddress.String[0]) continue;
2388 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
2389 sa[i].iSockaddrLength = sizeof(SOCKADDR);
2391 sockaddr[i].sin_family = AF_INET;
2392 sockaddr[i].sin_port = 0;
2393 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
2398 HeapFree(GetProcessHeap(), 0, table);
2403 WARN("unable to get IP address list\n");
2404 WSASetLastError(WSAEINVAL);
2405 return SOCKET_ERROR;
2409 FIXME("SIO_FLUSH: stub.\n");
2412 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
2413 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(lpvInBuffer));
2414 WSASetLastError(WSAEOPNOTSUPP);
2415 return SOCKET_ERROR;
2417 case WS_SIO_KEEPALIVE_VALS:
2420 struct tcp_keepalive *k = lpvInBuffer;
2421 int keepalive = k->onoff ? 1 : 0;
2422 int keepidle = k->keepalivetime / 1000;
2423 int keepintvl = k->keepaliveinterval / 1000;
2427 WSASetLastError(WSAEINVAL);
2428 return SOCKET_ERROR;
2431 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
2433 fd = get_sock_fd(s, 0, NULL);
2434 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
2436 release_sock_fd(s, fd);
2437 WSASetLastError(WSAEINVAL);
2438 return SOCKET_ERROR;
2440 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
2441 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
2443 release_sock_fd(s, fd);
2444 WSASetLastError(WSAEINVAL);
2445 return SOCKET_ERROR;
2447 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
2449 release_sock_fd(s, fd);
2450 WSASetLastError(WSAEINVAL);
2451 return SOCKET_ERROR;
2454 FIXME("ignoring keepalive interval and timeout\n");
2457 release_sock_fd(s, fd);
2461 FIXME("unsupported WS_IOCTL cmd (%08x)\n", dwIoControlCode);
2462 WSASetLastError(WSAEOPNOTSUPP);
2463 return SOCKET_ERROR;
2470 /***********************************************************************
2471 * ioctlsocket (WS2_32.10)
2473 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
2478 TRACE("socket %04lx, cmd %08x, ptr %p\n", s, cmd, argp);
2479 /* broken apps like defcon pass the argp value directly instead of a pointer to it */
2480 if(IS_INTRESOURCE(argp))
2482 SetLastError(WSAEFAULT);
2483 return SOCKET_ERROR;
2493 if( _get_sock_mask(s) )
2495 /* AsyncSelect()'ed sockets are always nonblocking */
2496 if (*argp) return 0;
2497 SetLastError(WSAEINVAL);
2498 return SOCKET_ERROR;
2501 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
2503 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
2511 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2512 SetLastError(WSAEINVAL);
2513 return SOCKET_ERROR;
2515 case SIOCGIFBRDADDR:
2516 case SIOCGIFNETMASK:
2518 /* These don't need any special handling. They are used by
2519 WsControl, and are here to suppress an unnecessary warning. */
2523 /* Netscape tries hard to use bogus ioctl 0x667e */
2524 /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
2525 * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
2527 WARN("\tunknown WS_IOCTL cmd (%08x)\n", cmd);
2531 fd = get_sock_fd( s, 0, NULL );
2534 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2536 release_sock_fd( s, fd );
2539 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2540 release_sock_fd( s, fd );
2542 return SOCKET_ERROR;
2545 /***********************************************************************
2546 * listen (WS2_32.13)
2548 int WINAPI WS_listen(SOCKET s, int backlog)
2550 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2552 TRACE("socket %04lx, backlog %d\n", s, backlog);
2555 if (listen(fd, backlog) == 0)
2557 release_sock_fd( s, fd );
2558 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
2560 FD_CONNECT|FD_WINE_CONNECTED);
2563 SetLastError(wsaErrno());
2564 release_sock_fd( s, fd );
2566 return SOCKET_ERROR;
2569 /***********************************************************************
2572 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2574 DWORD n, dwFlags = flags;
2580 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2581 return SOCKET_ERROR;
2586 /***********************************************************************
2587 * recvfrom (WS2_32.17)
2589 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2590 struct WS_sockaddr *from, int *fromlen)
2592 DWORD n, dwFlags = flags;
2598 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2599 return SOCKET_ERROR;
2604 /* allocate a poll array for the corresponding fd sets */
2605 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
2606 const WS_fd_set *exceptfds, int *count_ptr )
2608 unsigned int i, j = 0, count = 0;
2611 if (readfds) count += readfds->fd_count;
2612 if (writefds) count += writefds->fd_count;
2613 if (exceptfds) count += exceptfds->fd_count;
2615 if (!count) return NULL;
2616 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0])))) return NULL;
2618 for (i = 0; i < readfds->fd_count; i++, j++)
2620 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
2621 fds[j].events = POLLIN;
2625 for (i = 0; i < writefds->fd_count; i++, j++)
2627 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
2628 fds[j].events = POLLOUT;
2632 for (i = 0; i < exceptfds->fd_count; i++, j++)
2634 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
2635 fds[j].events = POLLHUP;
2641 /* release the file descriptor obtained in fd_sets_to_poll */
2642 /* must be called with the original fd_set arrays, before calling get_poll_results */
2643 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
2644 const WS_fd_set *exceptfds, struct pollfd *fds )
2646 unsigned int i, j = 0;
2650 for (i = 0; i < readfds->fd_count; i++, j++)
2651 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
2655 for (i = 0; i < writefds->fd_count; i++, j++)
2656 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
2660 for (i = 0; i < exceptfds->fd_count; i++, j++)
2661 if (fds[j].fd != -1)
2663 /* make sure we have a real error before releasing the fd */
2664 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
2665 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
2670 /* map the poll results back into the Windows fd sets */
2671 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
2672 const struct pollfd *fds )
2674 unsigned int i, j = 0, k, total = 0;
2678 for (i = k = 0; i < readfds->fd_count; i++, j++)
2679 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
2680 readfds->fd_count = k;
2685 for (i = k = 0; i < writefds->fd_count; i++, j++)
2686 if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
2687 writefds->fd_count = k;
2692 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
2693 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
2694 exceptfds->fd_count = k;
2701 /***********************************************************************
2702 * select (WS2_32.18)
2704 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
2705 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
2706 const struct WS_timeval* ws_timeout)
2708 struct pollfd *pollfds;
2709 int count, ret, timeout = -1;
2711 TRACE("read %p, write %p, excp %p timeout %p\n",
2712 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
2714 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )) && count)
2716 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2717 return SOCKET_ERROR;
2720 if (ws_timeout) timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
2722 ret = poll( pollfds, count, timeout );
2723 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2725 if (ret == -1) SetLastError(wsaErrno());
2726 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2727 HeapFree( GetProcessHeap(), 0, pollfds );
2731 /* helper to send completion messages for client-only i/o operation case */
2732 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
2737 SERVER_START_REQ( add_fd_completion )
2739 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
2740 req->cvalue = CompletionValue;
2741 req->status = CompletionStatus;
2742 req->information = Information;
2743 status = wine_server_call( req );
2749 /***********************************************************************
2752 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
2758 wsabuf.buf = (char*) buf;
2760 if ( WSASendTo( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
2761 return SOCKET_ERROR;
2766 /***********************************************************************
2767 * WSASend (WS2_32.72)
2769 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2770 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2771 LPWSAOVERLAPPED lpOverlapped,
2772 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2774 return WSASendTo( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
2775 NULL, 0, lpOverlapped, lpCompletionRoutine );
2778 /***********************************************************************
2779 * WSASendDisconnect (WS2_32.73)
2781 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
2783 return WS_shutdown( s, SD_SEND );
2787 /***********************************************************************
2788 * WSASendTo (WS2_32.74)
2790 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2791 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2792 const struct WS_sockaddr *to, int tolen,
2793 LPWSAOVERLAPPED lpOverlapped,
2794 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2796 unsigned int i, options;
2798 struct ws2_async *wsa;
2799 int totalLength = 0;
2800 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
2802 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
2803 s, lpBuffers, dwBufferCount, dwFlags,
2804 to, tolen, lpOverlapped, lpCompletionRoutine);
2806 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
2807 TRACE( "fd=%d, options=%x\n", fd, options );
2809 if ( fd == -1 ) return SOCKET_ERROR;
2811 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
2817 wsa->hSocket = SOCKET2HANDLE(s);
2818 wsa->addr = (struct WS_sockaddr *)to;
2819 wsa->addrlen.val = tolen;
2820 wsa->flags = dwFlags;
2821 wsa->n_iovecs = dwBufferCount;
2822 wsa->first_iovec = 0;
2823 for ( i = 0; i < dwBufferCount; i++ )
2825 wsa->iovec[i].iov_base = lpBuffers[i].buf;
2826 wsa->iovec[i].iov_len = lpBuffers[i].len;
2827 totalLength += lpBuffers[i].len;
2830 if (!lpNumberOfBytesSent)
2838 n = WS2_send( fd, wsa );
2839 if (n != -1 || errno != EINTR) break;
2841 if (n == -1 && errno != EAGAIN)
2844 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
2848 if ((lpOverlapped || lpCompletionRoutine) &&
2849 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
2851 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
2853 wsa->user_overlapped = lpOverlapped;
2854 wsa->completion_func = lpCompletionRoutine;
2855 release_sock_fd( s, fd );
2859 iosb->u.Status = STATUS_PENDING;
2860 iosb->Information = 0;
2862 SERVER_START_REQ( register_async )
2864 req->type = ASYNC_TYPE_WRITE;
2865 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2866 req->async.callback = wine_server_client_ptr( WS2_async_send );
2867 req->async.iosb = wine_server_client_ptr( iosb );
2868 req->async.arg = wine_server_client_ptr( wsa );
2869 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
2870 req->async.cvalue = cvalue;
2871 err = wine_server_call( req );
2875 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
2876 WSASetLastError( NtStatusToWSAError( err ));
2877 return SOCKET_ERROR;
2880 iosb->u.Status = STATUS_SUCCESS;
2881 iosb->Information = n;
2882 *lpNumberOfBytesSent = n;
2883 if (!wsa->completion_func)
2885 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
2886 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
2887 HeapFree( GetProcessHeap(), 0, wsa );
2889 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
2890 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
2895 if ( _is_blocking(s) )
2897 /* On a blocking non-overlapped stream socket,
2898 * sending blocks until the entire buffer is sent. */
2899 DWORD timeout_start = GetTickCount();
2901 *lpNumberOfBytesSent = 0;
2903 while (wsa->first_iovec < dwBufferCount)
2906 int timeout = GET_SNDTIMEO(fd);
2910 *lpNumberOfBytesSent += n;
2911 while (wsa->first_iovec < dwBufferCount && wsa->iovec[wsa->first_iovec].iov_len <= n)
2912 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2913 if (wsa->first_iovec >= dwBufferCount) break;
2914 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2915 wsa->iovec[wsa->first_iovec].iov_len -= n;
2920 timeout -= GetTickCount() - timeout_start;
2921 if (timeout < 0) timeout = 0;
2925 pfd.events = POLLOUT;
2927 if (!timeout || !poll( &pfd, 1, timeout ))
2930 goto error; /* msdn says a timeout in send is fatal */
2933 n = WS2_send( fd, wsa );
2934 if (n == -1 && errno != EAGAIN && errno != EINTR)
2941 else /* non-blocking */
2943 if (n < totalLength)
2944 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
2947 err = WSAEWOULDBLOCK;
2950 *lpNumberOfBytesSent = n;
2953 TRACE(" -> %i bytes\n", *lpNumberOfBytesSent);
2955 HeapFree( GetProcessHeap(), 0, wsa );
2956 release_sock_fd( s, fd );
2961 HeapFree( GetProcessHeap(), 0, wsa );
2962 release_sock_fd( s, fd );
2963 WARN(" -> ERROR %d\n", err);
2964 WSASetLastError(err);
2965 return SOCKET_ERROR;
2968 /***********************************************************************
2969 * sendto (WS2_32.20)
2971 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
2972 const struct WS_sockaddr *to, int tolen)
2978 wsabuf.buf = (char*) buf;
2980 if ( WSASendTo(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
2981 return SOCKET_ERROR;
2986 /***********************************************************************
2987 * setsockopt (WS2_32.21)
2989 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
2990 const char *optval, int optlen)
2994 struct linger linger;
2995 struct timeval tval;
2997 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2998 s, level, optname, optval, optlen);
3000 /* some broken apps pass the value directly instead of a pointer to it */
3001 if(IS_INTRESOURCE(optval))
3003 SetLastError(WSAEFAULT);
3004 return SOCKET_ERROR;
3012 /* Some options need some conversion before they can be sent to
3013 * setsockopt. The conversions are done here, then they will fall though
3014 * to the general case. Special options that are not passed to
3015 * setsockopt follow below that.*/
3017 case WS_SO_DONTLINGER:
3018 linger.l_onoff = *((const int*)optval) ? 0: 1;
3019 linger.l_linger = 0;
3021 optname = SO_LINGER;
3022 optval = (char*)&linger;
3023 optlen = sizeof(struct linger);
3027 linger.l_onoff = ((LINGER*)optval)->l_onoff;
3028 linger.l_linger = ((LINGER*)optval)->l_linger;
3029 /* FIXME: what is documented behavior if SO_LINGER optval
3032 optname = SO_LINGER;
3033 optval = (char*)&linger;
3034 optlen = sizeof(struct linger);
3038 if (*(const int*)optval < 2048)
3040 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
3045 /* The options listed here don't need any special handling. Thanks to
3046 * the conversion happening above, options from there will fall through
3048 case WS_SO_ACCEPTCONN:
3049 case WS_SO_BROADCAST:
3051 case WS_SO_KEEPALIVE:
3052 case WS_SO_OOBINLINE:
3053 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
3054 * however, using it the BSD way fixes bug 8513 and seems to be what
3055 * most programmers assume, anyway */
3056 case WS_SO_REUSEADDR:
3059 convert_sockopt(&level, &optname);
3062 /* SO_DEBUG is a privileged operation, ignore it. */
3064 TRACE("Ignoring SO_DEBUG\n");
3067 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
3068 * socket. According to MSDN, this option is silently ignored.*/
3069 case WS_SO_DONTROUTE:
3070 TRACE("Ignoring SO_DONTROUTE\n");
3073 /* Stops two sockets from being bound to the same port. Always happens
3074 * on unix systems, so just drop it. */
3075 case WS_SO_EXCLUSIVEADDRUSE:
3076 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
3079 /* SO_OPENTYPE does not require a valid socket handle. */
3080 case WS_SO_OPENTYPE:
3081 if (!optlen || optlen < sizeof(int) || !optval)
3083 SetLastError(WSAEFAULT);
3084 return SOCKET_ERROR;
3086 get_per_thread_data()->opentype = *(const int *)optval;
3087 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3091 case WS_SO_RCVTIMEO:
3094 case WS_SO_SNDTIMEO:
3096 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3097 if (optval && optlen == sizeof(UINT32)) {
3098 /* WinSock passes milliseconds instead of struct timeval */
3099 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
3100 tval.tv_sec = *(const UINT32*)optval / 1000;
3101 /* min of 500 milliseconds */
3102 if (tval.tv_sec == 0 && tval.tv_usec < 500000)
3103 tval.tv_usec = 500000;
3104 optlen = sizeof(struct timeval);
3105 optval = (char*)&tval;
3106 } else if (optlen == sizeof(struct timeval)) {
3107 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
3109 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
3112 convert_sockopt(&level, &optname);
3117 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3118 SetLastError(WSAENOPROTOOPT);
3119 return SOCKET_ERROR;
3121 break; /* case WS_SOL_SOCKET */
3128 fd = get_sock_fd( s, 0, NULL );
3129 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
3131 /* We try to set the ipx type on ipx socket level. */
3133 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
3135 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
3136 release_sock_fd( s, fd );
3137 return SOCKET_ERROR;
3142 /* Should we retrieve val using a getsockopt call and then
3143 * set the modified one? */
3144 val.ipx_pt = *optval;
3145 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
3148 release_sock_fd( s, fd );
3151 case IPX_FILTERPTYPE:
3152 /* Sets the receive filter packet type, at the moment we don't support it */
3153 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
3154 /* Returning 0 is better for now than returning a SOCKET_ERROR */
3158 FIXME("opt_name:%x\n", optname);
3159 return SOCKET_ERROR;
3161 break; /* case NSPROTO_IPX */
3164 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3165 case WS_IPPROTO_TCP:
3168 case WS_TCP_NODELAY:
3169 convert_sockopt(&level, &optname);
3172 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3173 return SOCKET_ERROR;
3180 case WS_IP_ADD_MEMBERSHIP:
3181 case WS_IP_DROP_MEMBERSHIP:
3185 case WS_IP_MULTICAST_IF:
3186 case WS_IP_MULTICAST_LOOP:
3187 case WS_IP_MULTICAST_TTL:
3191 convert_sockopt(&level, &optname);
3193 case WS_IP_DONTFRAGMENT:
3194 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
3197 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3198 return SOCKET_ERROR;
3203 FIXME("Unknown level: 0x%08x\n", level);
3204 return SOCKET_ERROR;
3205 } /* end switch(level) */
3207 /* avoid endianness issues if argument is a 16-bit int */
3208 if (optval && optlen < sizeof(int))
3210 woptval= *((const INT16 *) optval);
3211 optval= (char*) &woptval;
3214 fd = get_sock_fd( s, 0, NULL );
3215 if (fd == -1) return SOCKET_ERROR;
3217 if (setsockopt(fd, level, optname, optval, optlen) == 0)
3219 release_sock_fd( s, fd );
3222 TRACE("Setting socket error, %d\n", wsaErrno());
3223 SetLastError(wsaErrno());
3224 release_sock_fd( s, fd );
3226 return SOCKET_ERROR;
3229 /***********************************************************************
3230 * shutdown (WS2_32.22)
3232 int WINAPI WS_shutdown(SOCKET s, int how)
3234 int fd, err = WSAENOTSOCK;
3235 unsigned int options, clear_flags = 0;
3237 fd = get_sock_fd( s, 0, &options );
3238 TRACE("socket %04lx, how %i %x\n", s, how, options );
3241 return SOCKET_ERROR;
3245 case 0: /* drop receives */
3246 clear_flags |= FD_READ;
3248 case 1: /* drop sends */
3249 clear_flags |= FD_WRITE;
3251 case 2: /* drop all */
3252 clear_flags |= FD_READ|FD_WRITE;
3254 clear_flags |= FD_WINE_LISTENING;
3257 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3262 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3265 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3269 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3270 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3273 if (err) goto error;
3275 else /* non-overlapped mode */
3277 if ( shutdown( fd, how ) )
3284 release_sock_fd( s, fd );
3285 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3286 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
3290 release_sock_fd( s, fd );
3291 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3292 WSASetLastError( err );
3293 return SOCKET_ERROR;
3296 /***********************************************************************
3297 * socket (WS2_32.23)
3299 SOCKET WINAPI WS_socket(int af, int type, int protocol)
3301 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
3303 return WSASocketA( af, type, protocol, NULL, 0,
3304 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
3308 /***********************************************************************
3309 * gethostbyaddr (WS2_32.51)
3311 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
3313 struct WS_hostent *retval = NULL;
3314 struct hostent* host;
3316 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3319 struct hostent hostentry;
3322 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3324 int res = gethostbyaddr_r(addr, len, type,
3325 &hostentry, extrabuf, ebufsize, &host, &locerr);
3326 if( res != ERANGE) break;
3328 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3330 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3332 EnterCriticalSection( &csWSgetXXXbyYYY );
3333 host = gethostbyaddr(addr, len, type);
3334 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3336 if( host != NULL ) retval = WS_dup_he(host);
3337 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3338 HeapFree(GetProcessHeap(),0,extrabuf);
3340 LeaveCriticalSection( &csWSgetXXXbyYYY );
3342 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
3346 /***********************************************************************
3347 * gethostbyname (WS2_32.52)
3349 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
3351 struct WS_hostent *retval = NULL;
3352 struct hostent* host;
3353 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3356 struct hostent hostentry;
3357 int locerr = ENOBUFS;
3360 if( !name || !name[0]) {
3362 if( gethostname( buf, 100) == -1) {
3363 SetLastError( WSAENOBUFS); /* appropriate ? */
3367 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3369 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3371 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
3372 if( res != ERANGE) break;
3374 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3376 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3378 EnterCriticalSection( &csWSgetXXXbyYYY );
3379 host = gethostbyname(name);
3380 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3382 if (host) retval = WS_dup_he(host);
3383 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3384 HeapFree(GetProcessHeap(),0,extrabuf);
3386 LeaveCriticalSection( &csWSgetXXXbyYYY );
3388 if (retval && retval->h_addr_list[0][0] == 127 &&
3389 strcmp(name, "localhost") != 0)
3391 /* hostname != "localhost" but has loopback address. replace by our
3392 * special address.*/
3393 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
3395 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3400 /***********************************************************************
3401 * getprotobyname (WS2_32.53)
3403 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3405 struct WS_protoent* retval = NULL;
3406 #ifdef HAVE_GETPROTOBYNAME
3407 struct protoent* proto;
3408 EnterCriticalSection( &csWSgetXXXbyYYY );
3409 if( (proto = getprotobyname(name)) != NULL )
3411 retval = WS_dup_pe(proto);
3414 MESSAGE("protocol %s not found; You might want to add "
3415 "this to /etc/protocols\n", debugstr_a(name) );
3416 SetLastError(WSANO_DATA);
3418 LeaveCriticalSection( &csWSgetXXXbyYYY );
3420 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3425 /***********************************************************************
3426 * getprotobynumber (WS2_32.54)
3428 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3430 struct WS_protoent* retval = NULL;
3431 #ifdef HAVE_GETPROTOBYNUMBER
3432 struct protoent* proto;
3433 EnterCriticalSection( &csWSgetXXXbyYYY );
3434 if( (proto = getprotobynumber(number)) != NULL )
3436 retval = WS_dup_pe(proto);
3439 MESSAGE("protocol number %d not found; You might want to add "
3440 "this to /etc/protocols\n", number );
3441 SetLastError(WSANO_DATA);
3443 LeaveCriticalSection( &csWSgetXXXbyYYY );
3445 TRACE("%i ret %p\n", number, retval);
3450 /***********************************************************************
3451 * getservbyname (WS2_32.55)
3453 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3455 struct WS_servent* retval = NULL;
3456 struct servent* serv;
3458 char *proto_str = NULL;
3460 if (!(name_str = strdup_lower(name))) return NULL;
3462 if (proto && *proto)
3464 if (!(proto_str = strdup_lower(proto)))
3466 HeapFree( GetProcessHeap(), 0, name_str );
3471 EnterCriticalSection( &csWSgetXXXbyYYY );
3472 serv = getservbyname(name_str, proto_str);
3475 retval = WS_dup_se(serv);
3477 else SetLastError(WSANO_DATA);
3478 LeaveCriticalSection( &csWSgetXXXbyYYY );
3479 HeapFree( GetProcessHeap(), 0, proto_str );
3480 HeapFree( GetProcessHeap(), 0, name_str );
3481 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
3485 /***********************************************************************
3486 * freeaddrinfo (WS2_32.@)
3488 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
3491 struct WS_addrinfo *next;
3493 HeapFree(GetProcessHeap(),0,res->ai_canonname);
3494 HeapFree(GetProcessHeap(),0,res->ai_addr);
3495 next = res->ai_next;
3496 HeapFree(GetProcessHeap(),0,res);
3501 /* helper functions for getaddrinfo()/getnameinfo() */
3502 static int convert_aiflag_w2u(int winflags) {
3506 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3507 if (ws_aiflag_map[i][0] & winflags) {
3508 unixflags |= ws_aiflag_map[i][1];
3509 winflags &= ~ws_aiflag_map[i][0];
3512 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
3516 static int convert_niflag_w2u(int winflags) {
3520 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
3521 if (ws_niflag_map[i][0] & winflags) {
3522 unixflags |= ws_niflag_map[i][1];
3523 winflags &= ~ws_niflag_map[i][0];
3526 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
3530 static int convert_aiflag_u2w(int unixflags) {
3534 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3535 if (ws_aiflag_map[i][1] & unixflags) {
3536 winflags |= ws_aiflag_map[i][0];
3537 unixflags &= ~ws_aiflag_map[i][1];
3539 if (unixflags) /* will warn usually */
3540 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
3544 static int convert_eai_u2w(int unixret) {
3547 for (i=0;ws_eai_map[i][0];i++)
3548 if (ws_eai_map[i][1] == unixret)
3549 return ws_eai_map[i][0];
3553 /***********************************************************************
3554 * getaddrinfo (WS2_32.@)
3556 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
3558 #ifdef HAVE_GETADDRINFO
3559 struct addrinfo *unixaires = NULL;
3561 struct addrinfo unixhints, *punixhints = NULL;
3562 CHAR *node = NULL, *serv = NULL;
3565 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
3568 if (!(serv = strdup_lower(servname))) {
3569 HeapFree(GetProcessHeap(), 0, node);
3570 return WSA_NOT_ENOUGH_MEMORY;
3575 punixhints = &unixhints;
3577 memset(&unixhints, 0, sizeof(unixhints));
3578 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
3579 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
3580 punixhints->ai_family = 0;
3582 punixhints->ai_family = convert_af_w2u(hints->ai_family);
3583 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
3584 punixhints->ai_socktype = 0;
3586 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
3587 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
3588 punixhints->ai_protocol = 0;
3590 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
3593 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
3594 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
3596 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
3598 HeapFree(GetProcessHeap(), 0, node);
3599 HeapFree(GetProcessHeap(), 0, serv);
3602 struct addrinfo *xuai = unixaires;
3603 struct WS_addrinfo **xai = res;
3607 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
3613 *xai = ai;xai = &ai->ai_next;
3614 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
3615 ai->ai_family = convert_af_u2w(xuai->ai_family);
3616 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
3617 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
3618 if (xuai->ai_canonname) {
3619 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
3620 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
3621 if (!ai->ai_canonname)
3623 strcpy(ai->ai_canonname,xuai->ai_canonname);
3625 len = xuai->ai_addrlen;
3626 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
3629 ai->ai_addrlen = len;
3631 int winlen = ai->ai_addrlen;
3633 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
3634 ai->ai_addrlen = winlen;
3638 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
3641 ai->ai_addrlen = len;
3643 xuai = xuai->ai_next;
3645 freeaddrinfo(unixaires);
3647 result = convert_eai_u2w(result);
3653 if (*res) WS_freeaddrinfo(*res);
3654 if (unixaires) freeaddrinfo(unixaires);
3656 return WSA_NOT_ENOUGH_MEMORY;
3658 FIXME("getaddrinfo() failed, not found during buildtime.\n");
3663 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
3665 struct WS_addrinfoW *ret;
3667 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
3668 ret->ai_flags = ai->ai_flags;
3669 ret->ai_family = ai->ai_family;
3670 ret->ai_socktype = ai->ai_socktype;
3671 ret->ai_protocol = ai->ai_protocol;
3672 ret->ai_addrlen = ai->ai_addrlen;
3673 ret->ai_canonname = NULL;
3674 ret->ai_addr = NULL;
3675 ret->ai_next = NULL;
3676 if (ai->ai_canonname)
3678 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
3679 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
3681 HeapFree(GetProcessHeap(), 0, ret);
3684 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
3688 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
3690 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
3691 HeapFree(GetProcessHeap(), 0, ret);
3694 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
3699 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
3701 struct WS_addrinfoW *ret, *infoW;
3703 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
3704 while (info->ai_next)
3706 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
3711 infoW = infoW->ai_next;
3712 info = info->ai_next;
3717 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
3719 struct WS_addrinfo *ret;
3721 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
3722 ret->ai_flags = ai->ai_flags;
3723 ret->ai_family = ai->ai_family;
3724 ret->ai_socktype = ai->ai_socktype;
3725 ret->ai_protocol = ai->ai_protocol;
3726 ret->ai_addrlen = ai->ai_addrlen;
3727 ret->ai_canonname = NULL;
3728 ret->ai_addr = NULL;
3729 ret->ai_next = NULL;
3730 if (ai->ai_canonname)
3732 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
3733 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
3735 HeapFree(GetProcessHeap(), 0, ret);
3738 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
3742 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
3744 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
3745 HeapFree(GetProcessHeap(), 0, ret);
3748 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
3753 /***********************************************************************
3754 * GetAddrInfoW (WS2_32.@)
3756 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
3759 char *nodenameA, *servnameA = NULL;
3760 struct WS_addrinfo *resA, *hintsA = NULL;
3762 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
3763 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
3764 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
3768 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
3769 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
3771 HeapFree(GetProcessHeap(), 0, nodenameA);
3774 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
3777 if (hints) hintsA = addrinfo_WtoA(hints);
3778 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
3779 WS_freeaddrinfo(hintsA);
3783 *res = addrinfo_list_AtoW(resA);
3784 WS_freeaddrinfo(resA);
3787 HeapFree(GetProcessHeap(), 0, nodenameA);
3788 HeapFree(GetProcessHeap(), 0, servnameA);
3792 /***********************************************************************
3793 * FreeAddrInfoW (WS2_32.@)
3795 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
3800 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
3801 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
3803 HeapFree(GetProcessHeap(), 0, ai);
3808 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
3809 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
3811 #ifdef HAVE_GETNAMEINFO
3813 union generic_unix_sockaddr sa_u;
3816 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
3817 serv, servlen, flags);
3819 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
3822 WSASetLastError(WSAEFAULT);
3823 return WSA_NOT_ENOUGH_MEMORY;
3825 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
3826 return convert_eai_u2w(ret);
3828 FIXME("getnameinfo() failed, not found during buildtime.\n");
3833 /***********************************************************************
3834 * getservbyport (WS2_32.56)
3836 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
3838 struct WS_servent* retval = NULL;
3839 #ifdef HAVE_GETSERVBYPORT
3840 struct servent* serv;
3841 char *proto_str = NULL;
3843 if (proto && *proto)
3845 if (!(proto_str = strdup_lower(proto))) return NULL;
3847 EnterCriticalSection( &csWSgetXXXbyYYY );
3848 if( (serv = getservbyport(port, proto_str)) != NULL ) {
3849 retval = WS_dup_se(serv);
3851 else SetLastError(WSANO_DATA);
3852 LeaveCriticalSection( &csWSgetXXXbyYYY );
3853 HeapFree( GetProcessHeap(), 0, proto_str );
3855 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
3860 /***********************************************************************
3861 * gethostname (WS2_32.57)
3863 int WINAPI WS_gethostname(char *name, int namelen)
3865 TRACE("name %p, len %d\n", name, namelen);
3867 if (gethostname(name, namelen) == 0)
3869 TRACE("<- '%s'\n", name);
3872 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
3873 TRACE("<- ERROR !\n");
3874 return SOCKET_ERROR;
3878 /* ------------------------------------- Windows sockets extensions -- *
3880 * ------------------------------------------------------------------- */
3882 /***********************************************************************
3883 * WSAEnumNetworkEvents (WS2_32.36)
3885 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
3889 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
3891 SERVER_START_REQ( get_socket_event )
3893 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
3894 req->service = TRUE;
3895 req->c_event = wine_server_obj_handle( hEvent );
3896 wine_server_set_reply( req, lpEvent->iErrorCode, sizeof(lpEvent->iErrorCode) );
3897 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
3901 SetLastError(WSAEINVAL);
3902 return SOCKET_ERROR;
3905 /***********************************************************************
3906 * WSAEventSelect (WS2_32.39)
3908 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
3912 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
3914 SERVER_START_REQ( set_socket_event )
3916 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
3918 req->event = wine_server_obj_handle( hEvent );
3921 ret = wine_server_call( req );
3925 SetLastError(WSAEINVAL);
3926 return SOCKET_ERROR;
3929 /**********************************************************************
3930 * WSAGetOverlappedResult (WS2_32.40)
3932 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
3933 LPDWORD lpcbTransfer, BOOL fWait,
3938 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
3939 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
3941 if ( lpOverlapped == NULL )
3943 ERR( "Invalid pointer\n" );
3944 WSASetLastError(WSA_INVALID_PARAMETER);
3948 status = lpOverlapped->Internal;
3949 if (status == STATUS_PENDING)
3953 SetLastError( WSA_IO_INCOMPLETE );
3957 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
3958 INFINITE ) == WAIT_FAILED)
3960 status = lpOverlapped->Internal;
3964 *lpcbTransfer = lpOverlapped->InternalHigh;
3967 *lpdwFlags = lpOverlapped->u.s.Offset;
3969 if (status) SetLastError( RtlNtStatusToDosError(status) );
3974 /***********************************************************************
3975 * WSAAsyncSelect (WS2_32.101)
3977 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
3981 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
3983 SERVER_START_REQ( set_socket_event )
3985 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
3988 req->window = wine_server_user_handle( hWnd );
3990 ret = wine_server_call( req );
3994 SetLastError(WSAEINVAL);
3995 return SOCKET_ERROR;
3998 /***********************************************************************
3999 * WSACreateEvent (WS2_32.31)
4002 WSAEVENT WINAPI WSACreateEvent(void)
4004 /* Create a manual-reset event, with initial state: unsignaled */
4007 return CreateEventW(NULL, TRUE, FALSE, NULL);
4010 /***********************************************************************
4011 * WSACloseEvent (WS2_32.29)
4014 BOOL WINAPI WSACloseEvent(WSAEVENT event)
4016 TRACE ("event=%p\n", event);
4018 return CloseHandle(event);
4021 /***********************************************************************
4022 * WSASocketA (WS2_32.78)
4025 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
4026 LPWSAPROTOCOL_INFOA lpProtocolInfo,
4027 GROUP g, DWORD dwFlags)
4030 WSAPROTOCOL_INFOW info;
4032 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
4033 af, type, protocol, lpProtocolInfo, g, dwFlags);
4035 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
4037 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
4038 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
4039 info.szProtocol, WSAPROTOCOL_LEN + 1);
4043 WSASetLastError( WSAEINVAL);
4044 return SOCKET_ERROR;
4047 return WSASocketW(af, type, protocol, &info, g, dwFlags);
4050 /***********************************************************************
4051 * WSASocketW (WS2_32.79)
4054 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
4055 LPWSAPROTOCOL_INFOW lpProtocolInfo,
4056 GROUP g, DWORD dwFlags)
4061 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
4062 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
4065 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
4066 af, type, protocol, lpProtocolInfo, g, dwFlags );
4068 /* hack for WSADuplicateSocket */
4069 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
4070 ret = lpProtocolInfo->dwCatalogEntryId;
4071 TRACE("\tgot duplicate %04lx\n", ret);
4075 /* convert the socket family and type */
4076 af = convert_af_w2u(af);
4077 type = convert_socktype_w2u(type);
4081 if (af == FROM_PROTOCOL_INFO)
4082 af = lpProtocolInfo->iAddressFamily;
4083 if (type == FROM_PROTOCOL_INFO)
4084 type = lpProtocolInfo->iSocketType;
4085 if (protocol == FROM_PROTOCOL_INFO)
4086 protocol = lpProtocolInfo->iProtocol;
4089 if ( af == AF_UNSPEC) /* did they not specify the address family? */
4093 if (type == SOCK_STREAM) { af = AF_INET; break; }
4095 if (type == SOCK_DGRAM) { af = AF_INET; break; }
4096 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
4099 SERVER_START_REQ( create_socket )
4103 req->protocol = protocol;
4104 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
4105 req->attributes = OBJ_INHERIT;
4106 req->flags = dwFlags;
4107 set_error( wine_server_call( req ) );
4108 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
4113 TRACE("\tcreated %04lx\n", ret );
4117 if (GetLastError() == WSAEACCES) /* raw socket denied */
4119 if (type == SOCK_RAW)
4120 MESSAGE("WARNING: Trying to create a socket of type SOCK_RAW, this"
4121 " will fail unless you have special permissions.\n");
4123 MESSAGE("WS_SOCKET: Failed to create socket, this requires"
4124 " special permissions.\n");
4125 SetLastError(WSAESOCKTNOSUPPORT);
4128 WARN("\t\tfailed!\n");
4129 return INVALID_SOCKET;
4132 /***********************************************************************
4133 * WSAJoinLeaf (WS2_32.58)
4136 SOCKET WINAPI WSAJoinLeaf(
4138 const struct WS_sockaddr *addr,
4140 LPWSABUF lpCallerData,
4141 LPWSABUF lpCalleeData,
4147 return INVALID_SOCKET;
4150 /***********************************************************************
4151 * __WSAFDIsSet (WS2_32.151)
4153 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
4155 int i = set->fd_count;
4157 TRACE("(%ld,%p(%i))\n", s, set, i);
4160 if (set->fd_array[i] == s) return 1;
4164 /***********************************************************************
4165 * WSAIsBlocking (WINSOCK.114)
4166 * WSAIsBlocking (WS2_32.114)
4168 BOOL WINAPI WSAIsBlocking(void)
4170 /* By default WinSock should set all its sockets to non-blocking mode
4171 * and poll in PeekMessage loop when processing "blocking" ones. This
4172 * function is supposed to tell if the program is in this loop. Our
4173 * blocking calls are truly blocking so we always return FALSE.
4175 * Note: It is allowed to call this function without prior WSAStartup().
4182 /***********************************************************************
4183 * WSACancelBlockingCall (WINSOCK.113)
4184 * WSACancelBlockingCall (WS2_32.113)
4186 INT WINAPI WSACancelBlockingCall(void)
4192 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
4194 FIXME("How was this called?\n");
4199 /***********************************************************************
4200 * WSASetBlockingHook (WS2_32.109)
4202 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
4204 FARPROC prev = blocking_hook;
4205 blocking_hook = lpBlockFunc;
4206 TRACE("hook %p\n", lpBlockFunc);
4211 /***********************************************************************
4212 * WSAUnhookBlockingHook (WS2_32.110)
4214 INT WINAPI WSAUnhookBlockingHook(void)
4216 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
4221 /* ----------------------------------- end of API stuff */
4223 /* ----------------------------------- helper functions -
4225 * TODO: Merge WS_dup_..() stuff into one function that
4226 * would operate with a generic structure containing internal
4227 * pointers (via a template of some kind).
4230 static int list_size(char** l, int item_size)
4235 j += (item_size) ? item_size : strlen(l[i]) + 1;
4236 j += (i + 1) * sizeof(char*); }
4240 static int list_dup(char** l_src, char** l_to, int item_size)
4245 for (i = 0; l_src[i]; i++) ;
4246 p = (char *)(l_to + i + 1);
4247 for (i = 0; l_src[i]; i++)
4249 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
4250 memcpy(p, l_src[i], count);
4255 return p - (char *)l_to;
4260 /* duplicate hostent entry
4261 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
4262 * Ditto for protoent and servent.
4264 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
4267 struct WS_hostent *p_to;
4269 int size = (sizeof(*p_he) +
4270 strlen(p_he->h_name) + 1 +
4271 list_size(p_he->h_aliases, 0) +
4272 list_size(p_he->h_addr_list, p_he->h_length));
4274 if (!(p_to = check_buffer_he(size))) return NULL;
4275 p_to->h_addrtype = p_he->h_addrtype;
4276 p_to->h_length = p_he->h_length;
4278 p = (char *)(p_to + 1);
4280 strcpy(p, p_he->h_name);
4283 p_to->h_aliases = (char **)p;
4284 p += list_dup(p_he->h_aliases, p_to->h_aliases, 0);
4286 p_to->h_addr_list = (char **)p;
4287 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
4291 /* ----- protoent */
4293 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
4296 struct WS_protoent *p_to;
4298 int size = (sizeof(*p_pe) +
4299 strlen(p_pe->p_name) + 1 +
4300 list_size(p_pe->p_aliases, 0));
4302 if (!(p_to = check_buffer_pe(size))) return NULL;
4303 p_to->p_proto = p_pe->p_proto;
4305 p = (char *)(p_to + 1);
4307 strcpy(p, p_pe->p_name);
4310 p_to->p_aliases = (char **)p;
4311 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
4317 static struct WS_servent *WS_dup_se(const struct servent* p_se)
4320 struct WS_servent *p_to;
4322 int size = (sizeof(*p_se) +
4323 strlen(p_se->s_proto) + 1 +
4324 strlen(p_se->s_name) + 1 +
4325 list_size(p_se->s_aliases, 0));
4327 if (!(p_to = check_buffer_se(size))) return NULL;
4328 p_to->s_port = p_se->s_port;
4330 p = (char *)(p_to + 1);
4332 strcpy(p, p_se->s_name);
4336 strcpy(p, p_se->s_proto);
4339 p_to->s_aliases = (char **)p;
4340 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
4344 /* ----------------------------------- error handling */
4348 int loc_errno = errno;
4349 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
4353 case EINTR: return WSAEINTR;
4354 case EBADF: return WSAEBADF;
4356 case EACCES: return WSAEACCES;
4357 case EFAULT: return WSAEFAULT;
4358 case EINVAL: return WSAEINVAL;
4359 case EMFILE: return WSAEMFILE;
4360 case EWOULDBLOCK: return WSAEWOULDBLOCK;
4361 case EINPROGRESS: return WSAEINPROGRESS;
4362 case EALREADY: return WSAEALREADY;
4363 case ENOTSOCK: return WSAENOTSOCK;
4364 case EDESTADDRREQ: return WSAEDESTADDRREQ;
4365 case EMSGSIZE: return WSAEMSGSIZE;
4366 case EPROTOTYPE: return WSAEPROTOTYPE;
4367 case ENOPROTOOPT: return WSAENOPROTOOPT;
4368 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
4369 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
4370 case EOPNOTSUPP: return WSAEOPNOTSUPP;
4371 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
4372 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
4373 case EADDRINUSE: return WSAEADDRINUSE;
4374 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
4375 case ENETDOWN: return WSAENETDOWN;
4376 case ENETUNREACH: return WSAENETUNREACH;
4377 case ENETRESET: return WSAENETRESET;
4378 case ECONNABORTED: return WSAECONNABORTED;
4380 case ECONNRESET: return WSAECONNRESET;
4381 case ENOBUFS: return WSAENOBUFS;
4382 case EISCONN: return WSAEISCONN;
4383 case ENOTCONN: return WSAENOTCONN;
4384 case ESHUTDOWN: return WSAESHUTDOWN;
4385 case ETOOMANYREFS: return WSAETOOMANYREFS;
4386 case ETIMEDOUT: return WSAETIMEDOUT;
4387 case ECONNREFUSED: return WSAECONNREFUSED;
4388 case ELOOP: return WSAELOOP;
4389 case ENAMETOOLONG: return WSAENAMETOOLONG;
4390 case EHOSTDOWN: return WSAEHOSTDOWN;
4391 case EHOSTUNREACH: return WSAEHOSTUNREACH;
4392 case ENOTEMPTY: return WSAENOTEMPTY;
4394 case EPROCLIM: return WSAEPROCLIM;
4397 case EUSERS: return WSAEUSERS;
4400 case EDQUOT: return WSAEDQUOT;
4403 case ESTALE: return WSAESTALE;
4406 case EREMOTE: return WSAEREMOTE;
4409 /* just in case we ever get here and there are no problems */
4412 WARN("Unknown errno %d!\n", loc_errno);
4413 return WSAEOPNOTSUPP;
4417 UINT wsaHerrno(int loc_errno)
4420 WARN("h_errno %d.\n", loc_errno);
4424 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
4425 case TRY_AGAIN: return WSATRY_AGAIN;
4426 case NO_RECOVERY: return WSANO_RECOVERY;
4427 case NO_DATA: return WSANO_DATA;
4428 case ENOBUFS: return WSAENOBUFS;
4432 WARN("Unknown h_errno %d!\n", loc_errno);
4433 return WSAEOPNOTSUPP;
4438 /***********************************************************************
4439 * WSARecv (WS2_32.67)
4441 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4442 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
4443 LPWSAOVERLAPPED lpOverlapped,
4444 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
4446 return WSARecvFrom(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
4447 NULL, NULL, lpOverlapped, lpCompletionRoutine);
4450 /***********************************************************************
4451 * WSARecvFrom (WS2_32.69)
4453 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4454 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
4455 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
4456 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4459 unsigned int i, options;
4461 struct ws2_async *wsa;
4462 DWORD timeout_start = GetTickCount();
4463 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4465 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
4466 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
4467 (lpFromlen ? *lpFromlen : -1),
4468 lpOverlapped, lpCompletionRoutine);
4470 fd = get_sock_fd( s, FILE_READ_DATA, &options );
4471 TRACE( "fd=%d, options=%x\n", fd, options );
4473 if (fd == -1) return SOCKET_ERROR;
4475 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
4481 wsa->hSocket = SOCKET2HANDLE(s);
4482 wsa->flags = *lpFlags;
4484 wsa->addrlen.ptr = lpFromlen;
4485 wsa->n_iovecs = dwBufferCount;
4486 wsa->first_iovec = 0;
4487 for (i = 0; i < dwBufferCount; i++)
4489 /* check buffer first to trigger write watches */
4490 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
4495 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4496 wsa->iovec[i].iov_len = lpBuffers[i].len;
4501 n = WS2_recv( fd, wsa );
4504 if (errno == EINTR) continue;
4505 if (errno != EAGAIN)
4508 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
4513 *lpNumberOfBytesRecvd = n;
4515 if ((lpOverlapped || lpCompletionRoutine) &&
4516 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4518 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4520 wsa->user_overlapped = lpOverlapped;
4521 wsa->completion_func = lpCompletionRoutine;
4522 release_sock_fd( s, fd );
4526 iosb->u.Status = STATUS_PENDING;
4527 iosb->Information = 0;
4529 SERVER_START_REQ( register_async )
4531 req->type = ASYNC_TYPE_READ;
4532 req->async.handle = wine_server_obj_handle( wsa->hSocket );
4533 req->async.callback = wine_server_client_ptr( WS2_async_recv );
4534 req->async.iosb = wine_server_client_ptr( iosb );
4535 req->async.arg = wine_server_client_ptr( wsa );
4536 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
4537 req->async.cvalue = cvalue;
4538 err = wine_server_call( req );
4542 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4543 WSASetLastError( NtStatusToWSAError( err ));
4544 return SOCKET_ERROR;
4547 iosb->u.Status = STATUS_SUCCESS;
4548 iosb->Information = n;
4549 if (!wsa->completion_func)
4551 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4552 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
4553 HeapFree( GetProcessHeap(), 0, wsa );
4555 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4556 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4557 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4563 if ( _is_blocking(s) )
4566 int timeout = GET_RCVTIMEO(fd);
4569 timeout -= GetTickCount() - timeout_start;
4570 if (timeout < 0) timeout = 0;
4574 pfd.events = POLLIN;
4575 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
4577 if (!timeout || !poll( &pfd, 1, timeout ))
4580 /* a timeout is not fatal */
4581 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4587 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4588 err = WSAEWOULDBLOCK;
4593 TRACE(" -> %i bytes\n", n);
4594 HeapFree( GetProcessHeap(), 0, wsa );
4595 release_sock_fd( s, fd );
4596 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4601 HeapFree( GetProcessHeap(), 0, wsa );
4602 release_sock_fd( s, fd );
4603 WARN(" -> ERROR %d\n", err);
4604 WSASetLastError( err );
4605 return SOCKET_ERROR;
4608 /***********************************************************************
4609 * WSCInstallProvider (WS2_32.88)
4611 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
4612 LPCWSTR lpszProviderDllPath,
4613 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
4614 DWORD dwNumberOfEntries,
4617 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
4618 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
4619 dwNumberOfEntries, lpErrno);
4625 /***********************************************************************
4626 * WSCDeinstallProvider (WS2_32.83)
4628 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
4630 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
4636 /***********************************************************************
4637 * WSAAccept (WS2_32.26)
4639 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
4640 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
4643 int ret = 0, size = 0;
4644 WSABUF CallerId, CallerData, CalleeId, CalleeData;
4645 /* QOS SQOS, GQOS; */
4648 SOCKADDR src_addr, dst_addr;
4650 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %d\n",
4651 s, addr, addrlen, lpfnCondition, dwCallbackData);
4654 size = sizeof(src_addr);
4655 cs = WS_accept(s, &src_addr, &size);
4657 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
4659 if (!lpfnCondition) return cs;
4661 CallerId.buf = (char *)&src_addr;
4662 CallerId.len = sizeof(src_addr);
4664 CallerData.buf = NULL;
4667 WS_getsockname(cs, &dst_addr, &size);
4669 CalleeId.buf = (char *)&dst_addr;
4670 CalleeId.len = sizeof(dst_addr);
4673 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
4674 &CalleeId, &CalleeData, &g, dwCallbackData);
4679 if (addr && addrlen)
4680 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
4683 SERVER_START_REQ( set_socket_deferred )
4685 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4686 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
4687 if ( !wine_server_call_err ( req ) )
4689 SetLastError( WSATRY_AGAIN );
4690 WS_closesocket( cs );
4694 return SOCKET_ERROR;
4697 SetLastError(WSAECONNREFUSED);
4698 return SOCKET_ERROR;
4700 FIXME("Unknown return type from Condition function\n");
4701 SetLastError(WSAENOTSOCK);
4702 return SOCKET_ERROR;
4706 /***********************************************************************
4707 * WSADuplicateSocketA (WS2_32.32)
4709 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
4713 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4714 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4715 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
4716 /* I don't know what the real Windoze does next, this is a hack */
4717 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
4718 * the target use the global duplicate, or we could copy a reference to us to the structure
4719 * and let the target duplicate it from us, but let's do it as simple as possible */
4720 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4721 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4722 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4723 0, FALSE, DUPLICATE_SAME_ACCESS);
4724 CloseHandle(hProcess);
4725 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4729 /***********************************************************************
4730 * WSADuplicateSocketW (WS2_32.33)
4732 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
4736 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4738 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4739 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4740 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4741 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4742 0, FALSE, DUPLICATE_SAME_ACCESS);
4743 CloseHandle(hProcess);
4744 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4748 /***********************************************************************
4749 * WSAInstallServiceClassA (WS2_32.48)
4751 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
4753 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
4754 WSASetLastError(WSAEACCES);
4755 return SOCKET_ERROR;
4758 /***********************************************************************
4759 * WSAInstallServiceClassW (WS2_32.49)
4761 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
4763 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
4764 WSASetLastError(WSAEACCES);
4765 return SOCKET_ERROR;
4768 /***********************************************************************
4769 * WSARemoveServiceClass (WS2_32.70)
4771 int WINAPI WSARemoveServiceClass(LPGUID info)
4773 FIXME("Request to remove service %p\n",info);
4774 WSASetLastError(WSATYPE_NOT_FOUND);
4775 return SOCKET_ERROR;
4778 /***********************************************************************
4779 * inet_ntop (WS2_32.@)
4781 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
4783 #ifdef HAVE_INET_NTOP
4784 struct WS_in6_addr *in6;
4785 struct WS_in_addr *in;
4788 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
4791 WSASetLastError( STATUS_INVALID_PARAMETER );
4800 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
4806 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
4810 WSASetLastError( WSAEAFNOSUPPORT );
4814 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
4817 FIXME( "not supported on this platform\n" );
4818 WSASetLastError( WSAEAFNOSUPPORT );
4823 /***********************************************************************
4824 * WSAStringToAddressA (WS2_32.80)
4826 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
4828 LPWSAPROTOCOL_INFOA lpProtocolInfo,
4829 LPSOCKADDR lpAddress,
4830 LPINT lpAddressLength)
4833 LPSTR workBuffer=NULL,ptrPort;
4835 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
4836 lpProtocolInfo, lpAddress, lpAddressLength );
4838 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
4842 WSASetLastError(WSAEINVAL);
4843 return SOCKET_ERROR;
4847 FIXME("ProtocolInfo not implemented.\n");
4849 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
4850 strlen(AddressString) + 1);
4853 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4854 return SOCKET_ERROR;
4857 strcpy(workBuffer, AddressString);
4859 switch(AddressFamily)
4863 struct in_addr inetaddr;
4865 /* If lpAddressLength is too small, tell caller the size we need */
4866 if (*lpAddressLength < sizeof(SOCKADDR_IN))
4868 *lpAddressLength = sizeof(SOCKADDR_IN);
4872 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
4874 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
4876 ptrPort = strchr(workBuffer, ':');
4879 ((LPSOCKADDR_IN)lpAddress)->sin_port = (WS_u_short)atoi(ptrPort+1);
4884 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
4887 if(inet_aton(workBuffer, &inetaddr) > 0)
4889 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
4900 struct in6_addr inetaddr;
4901 /* If lpAddressLength is too small, tell caller the size we need */
4902 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
4904 *lpAddressLength = sizeof(SOCKADDR_IN6);
4908 #ifdef HAVE_INET_PTON
4909 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
4911 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
4913 /* This one is a bit tricky. An IPv6 address contains colons, so the
4914 * check from IPv4 doesn't work like that. However, IPv6 addresses that
4915 * contain a port are written with braces like [fd12:3456:7890::1]:12345
4916 * so what we will do is to look for ']', check if the next char is a
4917 * colon, and if it is, parse the port as in IPv4. */
4919 ptrPort = strchr(workBuffer, ']');
4920 if(ptrPort && *(++ptrPort) == ':')
4922 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = (WS_u_short)atoi(ptrPort+1);
4927 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
4930 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
4932 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
4933 sizeof(struct in6_addr));
4937 #endif /* HAVE_INET_PTON */
4943 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
4944 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
4948 HeapFree(GetProcessHeap(), 0, workBuffer);
4951 WSASetLastError(res);
4952 return SOCKET_ERROR;
4955 /***********************************************************************
4956 * WSAStringToAddressW (WS2_32.81)
4958 * Does anybody know if this functions allows to use hebrew/arabic/chinese... digits?
4959 * If this should be the case, it would be required to map these digits
4960 * to Unicode digits (0-9) using FoldString first.
4962 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
4964 LPWSAPROTOCOL_INFOW lpProtocolInfo,
4965 LPSOCKADDR lpAddress,
4966 LPINT lpAddressLength)
4969 LPSTR workBuffer=NULL;
4970 WSAPROTOCOL_INFOA infoA;
4971 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
4973 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
4974 lpAddress, lpAddressLength );
4976 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
4978 /* if ProtocolInfo is available - convert to ANSI variant */
4981 lpProtoInfoA = &infoA;
4982 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
4984 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
4985 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
4987 WSASetLastError( WSAEINVAL);
4988 return SOCKET_ERROR;
4994 /* Translate AddressString to ANSI code page - assumes that only
4995 standard digits 0-9 are used with this API call */
4996 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
4997 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
5001 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
5002 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
5003 lpAddress,lpAddressLength);
5004 HeapFree( GetProcessHeap(), 0, workBuffer );
5008 res = WSA_NOT_ENOUGH_MEMORY;
5013 WSASetLastError(res);
5014 return SOCKET_ERROR;
5017 /***********************************************************************
5018 * WSAAddressToStringA (WS2_32.27)
5020 * See WSAAddressToStringW
5022 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
5023 LPWSAPROTOCOL_INFOA info, LPSTR string,
5027 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
5030 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
5032 if (!sockaddr) return SOCKET_ERROR;
5033 if (!string || !lenstr) return SOCKET_ERROR;
5035 switch(sockaddr->sa_family)
5038 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
5039 sprintf( buffer, "%u.%u.%u.%u:%u",
5040 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
5041 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
5042 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
5043 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
5044 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
5046 p = strchr( buffer, ':' );
5047 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
5052 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
5055 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
5056 if ((sockaddr6->sin6_port))
5057 strcpy(buffer, "[");
5058 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
5060 WSASetLastError(WSAEINVAL);
5061 return SOCKET_ERROR;
5063 if ((sockaddr6->sin6_scope_id))
5064 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
5065 if ((sockaddr6->sin6_port))
5066 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
5071 WSASetLastError(WSAEINVAL);
5072 return SOCKET_ERROR;
5075 size = strlen( buffer ) + 1;
5080 WSASetLastError(WSAEFAULT);
5081 return SOCKET_ERROR;
5085 strcpy( string, buffer );
5089 /***********************************************************************
5090 * WSAAddressToStringW (WS2_32.28)
5092 * Convert a sockaddr address into a readable address string.
5095 * sockaddr [I] Pointer to a sockaddr structure.
5096 * len [I] Size of the sockaddr structure.
5097 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
5098 * string [I/O] Pointer to a buffer to receive the address string.
5099 * lenstr [I/O] Size of the receive buffer in WCHARs.
5103 * Failure: SOCKET_ERROR
5106 * The 'info' parameter is ignored.
5108 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
5109 LPWSAPROTOCOL_INFOW info, LPWSTR string,
5114 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
5117 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
5120 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
5122 if (ret) return ret;
5124 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
5129 WSASetLastError(WSAEFAULT);
5130 return SOCKET_ERROR;
5134 lstrcpyW( string, buffer );
5138 /***********************************************************************
5139 * WSAEnumNameSpaceProvidersA (WS2_32.34)
5141 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
5143 FIXME( "(%p %p) Stub!\n", len, buffer );
5147 /***********************************************************************
5148 * WSAEnumNameSpaceProvidersW (WS2_32.35)
5150 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
5152 FIXME( "(%p %p) Stub!\n", len, buffer );
5156 /***********************************************************************
5157 * WSAGetQOSByName (WS2_32.41)
5159 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
5161 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
5165 /***********************************************************************
5166 * WSAGetServiceClassInfoA (WS2_32.42)
5168 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
5169 LPWSASERVICECLASSINFOA info )
5171 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
5173 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5174 return SOCKET_ERROR;
5177 /***********************************************************************
5178 * WSAGetServiceClassInfoW (WS2_32.43)
5180 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
5181 LPWSASERVICECLASSINFOW info )
5183 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
5185 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5186 return SOCKET_ERROR;
5189 /***********************************************************************
5190 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
5192 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
5194 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
5195 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5196 return SOCKET_ERROR;
5199 /***********************************************************************
5200 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
5202 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
5204 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
5205 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5206 return SOCKET_ERROR;
5209 /***********************************************************************
5210 * WSALookupServiceBeginA (WS2_32.59)
5212 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
5213 DWORD dwControlFlags,
5216 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
5218 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5219 return SOCKET_ERROR;
5222 /***********************************************************************
5223 * WSALookupServiceBeginW (WS2_32.60)
5225 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
5226 DWORD dwControlFlags,
5229 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
5231 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5232 return SOCKET_ERROR;
5235 /***********************************************************************
5236 * WSALookupServiceBeginW (WS2_32.61)
5238 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
5240 FIXME("(%p) Stub!\n", lookup );
5244 /***********************************************************************
5245 * WSALookupServiceNextA (WS2_32.62)
5247 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
5249 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
5253 /***********************************************************************
5254 * WSALookupServiceNextW (WS2_32.63)
5256 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
5258 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
5262 /***********************************************************************
5263 * WSANtohl (WS2_32.64)
5265 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
5267 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
5269 if (!lphostlong) return WSAEFAULT;
5271 *lphostlong = ntohl( netlong );
5275 /***********************************************************************
5276 * WSANtohs (WS2_32.65)
5278 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
5280 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
5282 if (!lphostshort) return WSAEFAULT;
5284 *lphostshort = ntohs( netshort );
5288 /***********************************************************************
5289 * WSAProviderConfigChange (WS2_32.66)
5291 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
5292 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
5294 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
5295 return SOCKET_ERROR;
5298 /***********************************************************************
5299 * WSARecvDisconnect (WS2_32.68)
5301 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
5303 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
5305 return WS_shutdown( s, 0 );
5308 /***********************************************************************
5309 * WSASetServiceA (WS2_32.76)
5311 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
5313 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5317 /***********************************************************************
5318 * WSASetServiceW (WS2_32.77)
5320 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
5322 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5326 /***********************************************************************
5327 * WSCEnableNSProvider (WS2_32.84)
5329 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
5331 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
5335 /***********************************************************************
5336 * WSCGetProviderPath (WS2_32.86)
5338 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
5340 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
5342 if (!errcode || !provider || !len) return WSAEFAULT;
5344 *errcode = WSAEINVAL;
5345 return SOCKET_ERROR;
5348 /***********************************************************************
5349 * WSCInstallNameSpace (WS2_32.87)
5351 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
5352 DWORD version, LPGUID provider )
5354 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
5355 namespace, version, debugstr_guid(provider) );
5359 /***********************************************************************
5360 * WSCUnInstallNameSpace (WS2_32.89)
5362 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
5364 FIXME("(%p) Stub!\n", lpProviderId);
5368 /***********************************************************************
5369 * WSCWriteProviderOrder (WS2_32.91)
5371 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
5373 FIXME("(%p 0x%08x) Stub!\n", entry, number);