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;
1090 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1091 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1093 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1095 win6old->sin6_family = WS_AF_INET6;
1096 win6old->sin6_port = uin6->sin6_port;
1097 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1098 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1099 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1100 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1101 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1102 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1103 win6->sin6_scope_id = uin6->sin6_scope_id;
1104 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1110 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1111 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1113 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1115 win->sin_family = WS_AF_INET;
1116 win->sin_port = uin->sin_port;
1117 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1118 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1119 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1123 memset(wsaddr,0,*wsaddrlen);
1127 FIXME("Unknown address family %d\n", uaddr->sa_family);
1133 /**************************************************************************
1134 * Functions for handling overlapped I/O
1135 **************************************************************************/
1137 /* user APC called upon async completion */
1138 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1140 ws2_async *wsa = arg;
1142 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1143 iosb->Information, wsa->user_overlapped,
1145 HeapFree( GetProcessHeap(), 0, wsa );
1148 /***********************************************************************
1149 * WS2_recv (INTERNAL)
1151 * Workhorse for both synchronous and asynchronous recv() operations.
1153 static int WS2_recv( int fd, struct ws2_async *wsa )
1156 union generic_unix_sockaddr unix_sockaddr;
1159 hdr.msg_name = NULL;
1163 hdr.msg_namelen = sizeof(unix_sockaddr);
1164 hdr.msg_name = &unix_sockaddr;
1167 hdr.msg_namelen = 0;
1169 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1170 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1171 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1172 hdr.msg_accrights = NULL;
1173 hdr.msg_accrightslen = 0;
1175 hdr.msg_control = NULL;
1176 hdr.msg_controllen = 0;
1180 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1183 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1184 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1186 * quoting linux 2.6 net/ipv4/tcp.c:
1187 * "According to UNIX98, msg_name/msg_namelen are ignored
1188 * on connected socket. I was just happy when found this 8) --ANK"
1190 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1191 * connection-oriented sockets, so don't try to update lpFrom.
1193 if (wsa->addr && hdr.msg_namelen)
1194 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1199 /***********************************************************************
1200 * WS2_async_recv (INTERNAL)
1202 * Handler for overlapped recv() operations.
1204 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1206 ws2_async* wsa = user;
1211 case STATUS_ALERTED:
1212 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1215 result = WS2_recv( fd, wsa );
1216 wine_server_release_fd( wsa->hSocket, fd );
1219 status = STATUS_SUCCESS;
1220 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1224 if (errno == EINTR || errno == EAGAIN)
1226 status = STATUS_PENDING;
1227 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1232 status = wsaErrno(); /* FIXME: is this correct ???? */
1237 if (status != STATUS_PENDING)
1239 iosb->u.Status = status;
1240 iosb->Information = result;
1241 *apc = ws2_async_apc;
1246 /***********************************************************************
1247 * WS2_send (INTERNAL)
1249 * Workhorse for both synchronous and asynchronous send() operations.
1251 static int WS2_send( int fd, struct ws2_async *wsa )
1254 union generic_unix_sockaddr unix_addr;
1256 hdr.msg_name = NULL;
1257 hdr.msg_namelen = 0;
1261 hdr.msg_name = &unix_addr;
1262 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
1263 if ( !hdr.msg_namelen )
1269 #if defined(HAVE_IPX) && defined(SOL_IPX)
1270 if(wsa->addr->sa_family == WS_AF_IPX)
1272 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1274 unsigned int len=sizeof(int);
1276 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1277 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1278 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1279 * ipx type in the sockaddr_opx structure with the stored value.
1281 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1282 uipx->sipx_type = val;
1287 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1288 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1289 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1290 hdr.msg_accrights = NULL;
1291 hdr.msg_accrightslen = 0;
1293 hdr.msg_control = NULL;
1294 hdr.msg_controllen = 0;
1298 return sendmsg(fd, &hdr, wsa->flags);
1301 /***********************************************************************
1302 * WS2_async_send (INTERNAL)
1304 * Handler for overlapped send() operations.
1306 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1308 ws2_async* wsa = user;
1313 case STATUS_ALERTED:
1314 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1317 /* check to see if the data is ready (non-blocking) */
1318 result = WS2_send( fd, wsa );
1319 wine_server_release_fd( wsa->hSocket, fd );
1323 int totalLength = 0;
1325 status = STATUS_SUCCESS;
1326 for (i = 0; i < wsa->n_iovecs; i++)
1327 totalLength += wsa->iovec[i].iov_len;
1328 if (result < totalLength)
1329 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1333 if (errno == EINTR || errno == EAGAIN)
1335 status = STATUS_PENDING;
1336 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1340 /* We set the status to a winsock error code and check for that
1341 later in NtStatusToWSAError () */
1342 status = wsaErrno();
1348 if (status != STATUS_PENDING)
1350 iosb->u.Status = status;
1351 iosb->Information = result;
1352 *apc = ws2_async_apc;
1357 /***********************************************************************
1358 * WS2_async_shutdown (INTERNAL)
1360 * Handler for shutdown() operations on overlapped sockets.
1362 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
1364 ws2_async* wsa = user;
1369 case STATUS_ALERTED:
1370 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1373 switch ( wsa->type )
1375 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1376 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1378 wine_server_release_fd( wsa->hSocket, fd );
1379 status = err ? wsaErrno() : STATUS_SUCCESS;
1382 iosb->u.Status = status;
1383 *apc = ws2_async_apc;
1387 /***********************************************************************
1388 * WS2_register_async_shutdown (INTERNAL)
1390 * Helper function for WS_shutdown() on overlapped sockets.
1392 static int WS2_register_async_shutdown( SOCKET s, int type )
1394 struct ws2_async *wsa;
1397 TRACE("s %ld type %d\n", s, type);
1399 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1403 wsa->hSocket = SOCKET2HANDLE(s);
1405 wsa->completion_func = NULL;
1407 SERVER_START_REQ( register_async )
1410 req->async.handle = wine_server_obj_handle( wsa->hSocket );
1411 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
1412 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
1413 req->async.arg = wine_server_client_ptr( wsa );
1414 req->async.cvalue = 0;
1415 status = wine_server_call( req );
1419 if (status != STATUS_PENDING)
1421 HeapFree( GetProcessHeap(), 0, wsa );
1422 return NtStatusToWSAError( status );
1427 /***********************************************************************
1430 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1436 TRACE("socket %04lx\n", s );
1437 is_blocking = _is_blocking(s);
1442 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1443 if (fd == -1) return INVALID_SOCKET;
1445 do_block(fd, POLLIN, -1);
1446 _sync_sock_state(s); /* let wineserver notice connection */
1447 release_sock_fd( s, fd );
1448 /* retrieve any error codes from it */
1449 SetLastError(_get_sock_error(s, FD_ACCEPT_BIT));
1450 /* FIXME: care about the error? */
1452 SERVER_START_REQ( accept_socket )
1454 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1455 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1456 req->attributes = OBJ_INHERIT;
1457 set_error( wine_server_call( req ) );
1458 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
1463 if (addr) WS_getpeername(as, addr, addrlen32);
1466 } while (is_blocking);
1467 return INVALID_SOCKET;
1470 /***********************************************************************
1473 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1475 int fd = get_sock_fd( s, 0, NULL );
1476 int res = SOCKET_ERROR;
1478 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1482 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
1484 SetLastError(WSAEAFNOSUPPORT);
1488 union generic_unix_sockaddr uaddr;
1489 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1492 SetLastError(WSAEFAULT);
1497 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
1498 if (name->sa_family == WS_AF_INET6 &&
1499 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
1502 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
1504 release_sock_fd( s, fd );
1505 SetLastError(WSAEAFNOSUPPORT);
1506 return SOCKET_ERROR;
1510 if (name->sa_family == WS_AF_INET)
1512 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1513 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1515 /* Trying to bind to the default host interface, using
1516 * INADDR_ANY instead*/
1517 WARN("Trying to bind to magic IP address, using "
1518 "INADDR_ANY instead.\n");
1519 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
1522 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
1524 int loc_errno = errno;
1525 WARN("\tfailure - errno = %i\n", errno);
1530 SetLastError(WSAENOTSOCK);
1533 SetLastError(WSAEINVAL);
1536 SetLastError(wsaErrno());
1542 res=0; /* success */
1546 release_sock_fd( s, fd );
1551 /***********************************************************************
1552 * closesocket (WS2_32.3)
1554 int WINAPI WS_closesocket(SOCKET s)
1556 TRACE("socket %04lx\n", s);
1557 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
1558 return SOCKET_ERROR;
1561 /***********************************************************************
1562 * connect (WS2_32.4)
1564 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1566 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1568 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1572 union generic_unix_sockaddr uaddr;
1573 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1577 SetLastError(WSAEFAULT);
1581 if (name->sa_family == WS_AF_INET)
1583 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1584 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1586 /* Trying to connect to magic replace-loopback address,
1587 * assuming we really want to connect to localhost */
1588 TRACE("Trying to connect to magic IP address, using "
1589 "INADDR_LOOPBACK instead.\n");
1590 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
1594 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
1595 goto connect_success;
1598 if (errno == EINPROGRESS)
1600 /* tell wineserver that a connection is in progress */
1601 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1602 FD_CONNECT|FD_READ|FD_WRITE,
1603 FD_WINE_CONNECTED|FD_WINE_LISTENING);
1604 if (_is_blocking(s))
1608 do_block(fd, POLLIN | POLLOUT, -1);
1609 _sync_sock_state(s); /* let wineserver notice connection */
1610 /* retrieve any error codes from it */
1611 result = _get_sock_error(s, FD_CONNECT_BIT);
1613 SetLastError(result);
1616 goto connect_success;
1621 SetLastError(WSAEWOULDBLOCK);
1626 SetLastError(wsaErrno());
1628 release_sock_fd( s, fd );
1630 return SOCKET_ERROR;
1633 release_sock_fd( s, fd );
1634 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1635 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1636 FD_CONNECT|FD_WINE_LISTENING);
1640 /***********************************************************************
1641 * WSAConnect (WS2_32.30)
1643 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
1644 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1645 LPQOS lpSQOS, LPQOS lpGQOS )
1647 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1648 FIXME("unsupported parameters!\n");
1649 return WS_connect( s, name, namelen );
1653 /***********************************************************************
1654 * getpeername (WS2_32.5)
1656 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1661 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, *namelen);
1663 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1664 if( (name == NULL) || (namelen == NULL) )
1666 SetLastError( WSAEFAULT );
1667 return SOCKET_ERROR;
1670 fd = get_sock_fd( s, 0, NULL );
1675 union generic_unix_sockaddr uaddr;
1676 unsigned int uaddrlen = sizeof(uaddr);
1678 if (getpeername(fd, &uaddr.addr, &uaddrlen) != 0)
1680 SetLastError(wsaErrno());
1682 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1684 /* The buffer was too small */
1685 SetLastError(WSAEFAULT);
1691 release_sock_fd( s, fd );
1696 /***********************************************************************
1697 * getsockname (WS2_32.6)
1699 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1704 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
1706 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1707 if( (name == NULL) || (namelen == NULL) )
1709 SetLastError( WSAEFAULT );
1710 return SOCKET_ERROR;
1713 fd = get_sock_fd( s, 0, NULL );
1718 union generic_unix_sockaddr uaddr;
1719 unsigned int uaddrlen = sizeof(uaddr);
1721 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
1723 SetLastError(wsaErrno());
1725 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
1727 SetLastError(WSAEINVAL);
1729 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1731 /* The buffer was too small */
1732 SetLastError(WSAEFAULT);
1738 release_sock_fd( s, fd );
1743 /***********************************************************************
1744 * getsockopt (WS2_32.7)
1746 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1747 INT optname, char *optval, INT *optlen)
1752 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
1753 s, level, optname, optval, *optlen);
1761 /* Handle common cases. The special cases are below, sorted
1763 case WS_SO_ACCEPTCONN:
1764 case WS_SO_BROADCAST:
1767 case WS_SO_KEEPALIVE:
1768 case WS_SO_OOBINLINE:
1770 case WS_SO_REUSEADDR:
1773 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1774 return SOCKET_ERROR;
1775 convert_sockopt(&level, &optname);
1776 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1778 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1781 release_sock_fd( s, fd );
1784 case WS_SO_DONTLINGER:
1786 struct linger lingval;
1787 unsigned int len = sizeof(struct linger);
1789 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
1791 SetLastError(WSAEFAULT);
1792 return SOCKET_ERROR;
1794 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1795 return SOCKET_ERROR;
1797 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1799 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1804 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
1805 *optlen = sizeof(BOOL);
1808 release_sock_fd( s, fd );
1812 /* As mentioned in setsockopt, Windows ignores this, so we
1813 * always return true here */
1814 case WS_SO_DONTROUTE:
1815 if (!optlen || *optlen < sizeof(BOOL) || !optval)
1817 SetLastError(WSAEFAULT);
1818 return SOCKET_ERROR;
1820 *(BOOL *)optval = TRUE;
1821 *optlen = sizeof(BOOL);
1826 struct linger lingval;
1827 unsigned int len = sizeof(struct linger);
1829 /* struct linger and LINGER have different sizes */
1830 if (!optlen || *optlen < sizeof(LINGER) || !optval)
1832 SetLastError(WSAEFAULT);
1833 return SOCKET_ERROR;
1835 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1836 return SOCKET_ERROR;
1838 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1840 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1845 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
1846 ((LINGER *)optval)->l_linger = lingval.l_linger;
1847 *optlen = sizeof(struct linger);
1850 release_sock_fd( s, fd );
1854 case WS_SO_MAX_MSG_SIZE:
1855 if (!optlen || *optlen < sizeof(int) || !optval)
1857 SetLastError(WSAEFAULT);
1858 return SOCKET_ERROR;
1860 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
1861 *(int *)optval = 65507;
1862 *optlen = sizeof(int);
1865 /* SO_OPENTYPE does not require a valid socket handle. */
1866 case WS_SO_OPENTYPE:
1867 if (!optlen || *optlen < sizeof(int) || !optval)
1869 SetLastError(WSAEFAULT);
1870 return SOCKET_ERROR;
1872 *(int *)optval = get_per_thread_data()->opentype;
1873 *optlen = sizeof(int);
1874 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
1878 case WS_SO_RCVTIMEO:
1881 case WS_SO_SNDTIMEO:
1883 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
1886 unsigned int len = sizeof(struct timeval);
1888 if (!optlen || *optlen < sizeof(int)|| !optval)
1890 SetLastError(WSAEFAULT);
1891 return SOCKET_ERROR;
1893 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1894 return SOCKET_ERROR;
1896 convert_sockopt(&level, &optname);
1897 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
1899 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1904 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1905 *optlen = sizeof(int);
1908 release_sock_fd( s, fd );
1913 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
1914 SetLastError(WSAENOPROTOOPT);
1915 return SOCKET_ERROR;
1916 } /* end switch(optname) */
1917 }/* end case WS_SOL_SOCKET */
1921 struct WS_sockaddr_ipx addr;
1922 IPX_ADDRESS_DATA *data;
1927 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
1929 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
1936 socklen_t len=sizeof(struct ipx);
1937 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
1940 *optval = (int)val.ipx_pt;
1943 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
1944 release_sock_fd( s, fd );
1949 * On a Win2000 system with one network card there are usually
1950 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
1951 * Using this call you can then retrieve info about this all.
1952 * In case of Linux it is a bit different. Usually you have
1953 * only "one" device active and further it is not possible to
1954 * query things like the linkspeed.
1956 FIXME("IPX_ADDRESS\n");
1957 namelen = sizeof(struct WS_sockaddr_ipx);
1958 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
1959 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
1961 data = (IPX_ADDRESS_DATA*)optval;
1962 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
1963 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
1964 data->adapternum = 0;
1965 data->wan = FALSE; /* We are not on a wan for now .. */
1966 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
1967 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
1968 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
1969 * note 1MB = 1000kB in this case */
1972 case IPX_MAX_ADAPTER_NUM:
1973 FIXME("IPX_MAX_ADAPTER_NUM\n");
1974 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
1978 FIXME("IPX optname:%x\n", optname);
1979 return SOCKET_ERROR;
1980 }/* end switch(optname) */
1981 } /* end case NSPROTO_IPX */
1983 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
1984 case WS_IPPROTO_TCP:
1987 case WS_TCP_NODELAY:
1988 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1989 return SOCKET_ERROR;
1990 convert_sockopt(&level, &optname);
1991 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1993 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1996 release_sock_fd( s, fd );
1999 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
2000 return SOCKET_ERROR;
2005 case WS_IP_ADD_MEMBERSHIP:
2006 case WS_IP_DROP_MEMBERSHIP:
2010 case WS_IP_MULTICAST_IF:
2011 case WS_IP_MULTICAST_LOOP:
2012 case WS_IP_MULTICAST_TTL:
2016 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2017 return SOCKET_ERROR;
2018 convert_sockopt(&level, &optname);
2019 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2021 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2024 release_sock_fd( s, fd );
2026 case WS_IP_DONTFRAGMENT:
2027 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
2028 *(BOOL*)optval = FALSE;
2031 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
2032 return SOCKET_ERROR;
2035 FIXME("Unknown level: 0x%08x\n", level);
2036 return SOCKET_ERROR;
2037 } /* end switch(level) */
2040 /***********************************************************************
2044 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
2046 return htonl(hostlong);
2050 /***********************************************************************
2054 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
2056 return htons(hostshort);
2059 /***********************************************************************
2060 * WSAHtonl (WS2_32.46)
2061 * From MSDN description of error codes, this function should also
2062 * check if WinSock has been initialized and the socket is a valid
2063 * socket. But why? This function only translates a host byte order
2064 * u_long into a network byte order u_long...
2066 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
2070 *lpnetlong = htonl(hostlong);
2073 WSASetLastError(WSAEFAULT);
2074 return SOCKET_ERROR;
2077 /***********************************************************************
2078 * WSAHtons (WS2_32.47)
2079 * From MSDN description of error codes, this function should also
2080 * check if WinSock has been initialized and the socket is a valid
2081 * socket. But why? This function only translates a host byte order
2082 * u_short into a network byte order u_short...
2084 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2089 *lpnetshort = htons(hostshort);
2092 WSASetLastError(WSAEFAULT);
2093 return SOCKET_ERROR;
2097 /***********************************************************************
2098 * inet_addr (WINSOCK.10)
2099 * inet_addr (WS2_32.11)
2101 WS_u_long WINAPI WS_inet_addr(const char *cp)
2103 if (!cp) return INADDR_NONE;
2104 return inet_addr(cp);
2108 /***********************************************************************
2109 * ntohl (WINSOCK.14)
2112 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2114 return ntohl(netlong);
2118 /***********************************************************************
2119 * ntohs (WINSOCK.15)
2122 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2124 return ntohs(netshort);
2128 /***********************************************************************
2129 * inet_ntoa (WS2_32.12)
2131 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2133 /* use "buffer for dummies" here because some applications have a
2134 * propensity to decode addresses in ws_hostent structure without
2135 * saving them first...
2137 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2139 char* s = inet_ntoa(*((struct in_addr*)&in));
2145 SetLastError(wsaErrno());
2149 /**********************************************************************
2150 * WSAIoctl (WS2_32.50)
2153 INT WINAPI WSAIoctl(SOCKET s,
2154 DWORD dwIoControlCode,
2157 LPVOID lpbOutBuffer,
2159 LPDWORD lpcbBytesReturned,
2160 LPWSAOVERLAPPED lpOverlapped,
2161 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2163 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
2164 s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpbOutBuffer,
2165 cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
2167 switch( dwIoControlCode )
2170 if (cbInBuffer != sizeof(WS_u_long)) {
2171 WSASetLastError(WSAEFAULT);
2172 return SOCKET_ERROR;
2174 return WS_ioctlsocket( s, WS_FIONBIO, lpvInBuffer);
2177 if (cbOutBuffer != sizeof(WS_u_long)) {
2178 WSASetLastError(WSAEFAULT);
2179 return SOCKET_ERROR;
2181 return WS_ioctlsocket( s, WS_FIONREAD, lpbOutBuffer);
2183 case WS_SIO_GET_INTERFACE_LIST:
2185 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
2186 DWORD size, numInt, apiReturn;
2189 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
2193 WSASetLastError(WSAEFAULT);
2194 return SOCKET_ERROR;
2196 if (!lpcbBytesReturned)
2198 WSASetLastError(WSAEFAULT);
2199 return SOCKET_ERROR;
2202 fd = get_sock_fd( s, 0, NULL );
2203 if (fd == -1) return SOCKET_ERROR;
2205 apiReturn = GetAdaptersInfo(NULL, &size);
2206 if (apiReturn == ERROR_NO_DATA)
2210 else if (apiReturn == ERROR_BUFFER_OVERFLOW)
2212 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
2216 if (GetAdaptersInfo(table, &size) == NO_ERROR)
2218 PIP_ADAPTER_INFO ptr;
2220 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > cbOutBuffer)
2222 WARN("Buffer too small = %u, cbOutBuffer = %u\n", size, cbOutBuffer);
2223 HeapFree(GetProcessHeap(),0,table);
2224 release_sock_fd( s, fd );
2225 WSASetLastError(WSAEFAULT);
2226 return SOCKET_ERROR;
2228 for (ptr = table, numInt = 0; ptr;
2229 ptr = ptr->Next, intArray++, numInt++)
2231 unsigned int addr, mask, bcast;
2232 struct ifreq ifInfo;
2234 /* Socket Status Flags */
2235 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
2236 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2238 ERR("Error obtaining status flags for socket!\n");
2239 HeapFree(GetProcessHeap(),0,table);
2240 release_sock_fd( s, fd );
2241 WSASetLastError(WSAEINVAL);
2242 return SOCKET_ERROR;
2246 /* set flags; the values of IFF_* are not the same
2247 under Linux and Windows, therefore must generate
2249 intArray->iiFlags = 0;
2250 if (ifInfo.ifr_flags & IFF_BROADCAST)
2251 intArray->iiFlags |= WS_IFF_BROADCAST;
2252 #ifdef IFF_POINTOPOINT
2253 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
2254 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
2256 if (ifInfo.ifr_flags & IFF_LOOPBACK)
2257 intArray->iiFlags |= WS_IFF_LOOPBACK;
2258 if (ifInfo.ifr_flags & IFF_UP)
2259 intArray->iiFlags |= WS_IFF_UP;
2260 if (ifInfo.ifr_flags & IFF_MULTICAST)
2261 intArray->iiFlags |= WS_IFF_MULTICAST;
2264 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
2265 mask = inet_addr(ptr->IpAddressList.IpMask.String);
2266 bcast = addr | ~mask;
2267 intArray->iiAddress.AddressIn.sin_family = AF_INET;
2268 intArray->iiAddress.AddressIn.sin_port = 0;
2269 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
2271 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2272 intArray->iiNetmask.AddressIn.sin_port = 0;
2273 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
2275 intArray->iiBroadcastAddress.AddressIn.sin_family =
2277 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
2278 intArray->iiBroadcastAddress.AddressIn.sin_addr.
2284 ERR("Unable to get interface table!\n");
2285 release_sock_fd( s, fd );
2286 HeapFree(GetProcessHeap(),0,table);
2287 WSASetLastError(WSAEINVAL);
2288 return SOCKET_ERROR;
2290 HeapFree(GetProcessHeap(),0,table);
2294 release_sock_fd( s, fd );
2295 WSASetLastError(WSAEINVAL);
2296 return SOCKET_ERROR;
2301 ERR("Unable to get interface table!\n");
2302 release_sock_fd( s, fd );
2303 WSASetLastError(WSAEINVAL);
2304 return SOCKET_ERROR;
2306 /* Calculate the size of the array being returned */
2307 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2308 release_sock_fd( s, fd );
2312 case WS_SIO_ADDRESS_LIST_CHANGE:
2313 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
2314 /* FIXME: error and return code depend on whether socket was created
2315 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
2318 case WS_SIO_ADDRESS_LIST_QUERY:
2322 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
2324 if (!lpcbBytesReturned)
2326 WSASetLastError(WSAEFAULT);
2327 return SOCKET_ERROR;
2330 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
2332 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
2335 if (!table || GetAdaptersInfo(table, &size))
2337 HeapFree(GetProcessHeap(), 0, table);
2338 WSASetLastError(WSAEINVAL);
2339 return SOCKET_ERROR;
2342 for (p = table, num = 0; p; p = p->Next)
2343 if (p->IpAddressList.IpAddress.String[0]) num++;
2345 need = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
2346 need += sizeof(SOCKADDR) * num;
2347 *lpcbBytesReturned = need;
2349 if (need > cbOutBuffer)
2351 HeapFree(GetProcessHeap(), 0, table);
2352 WSASetLastError(WSAEFAULT);
2353 return SOCKET_ERROR;
2360 SOCKET_ADDRESS_LIST *sa_list = (SOCKET_ADDRESS_LIST *)lpbOutBuffer;
2361 SOCKADDR_IN *sockaddr;
2363 sa = sa_list->Address;
2364 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
2365 sa_list->iAddressCount = num;
2367 for (p = table, i = 0; p; p = p->Next)
2369 if (!p->IpAddressList.IpAddress.String[0]) continue;
2371 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
2372 sa[i].iSockaddrLength = sizeof(SOCKADDR);
2374 sockaddr[i].sin_family = AF_INET;
2375 sockaddr[i].sin_port = 0;
2376 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
2381 HeapFree(GetProcessHeap(), 0, table);
2386 WARN("unable to get IP address list\n");
2387 WSASetLastError(WSAEINVAL);
2388 return SOCKET_ERROR;
2392 FIXME("SIO_FLUSH: stub.\n");
2395 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
2396 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(lpvInBuffer));
2397 WSASetLastError(WSAEOPNOTSUPP);
2398 return SOCKET_ERROR;
2400 case WS_SIO_KEEPALIVE_VALS:
2403 struct tcp_keepalive *k = lpvInBuffer;
2404 int keepalive = k->onoff ? 1 : 0;
2405 int keepidle = k->keepalivetime / 1000;
2406 int keepintvl = k->keepaliveinterval / 1000;
2410 WSASetLastError(WSAEINVAL);
2411 return SOCKET_ERROR;
2414 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
2416 fd = get_sock_fd(s, 0, NULL);
2417 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
2419 release_sock_fd(s, fd);
2420 WSASetLastError(WSAEINVAL);
2421 return SOCKET_ERROR;
2423 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
2424 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
2426 release_sock_fd(s, fd);
2427 WSASetLastError(WSAEINVAL);
2428 return SOCKET_ERROR;
2430 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
2432 release_sock_fd(s, fd);
2433 WSASetLastError(WSAEINVAL);
2434 return SOCKET_ERROR;
2437 FIXME("ignoring keepalive interval and timeout\n");
2440 release_sock_fd(s, fd);
2444 FIXME("unsupported WS_IOCTL cmd (%08x)\n", dwIoControlCode);
2445 WSASetLastError(WSAEOPNOTSUPP);
2446 return SOCKET_ERROR;
2453 /***********************************************************************
2454 * ioctlsocket (WS2_32.10)
2456 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
2461 TRACE("socket %04lx, cmd %08x, ptr %p\n", s, cmd, argp);
2462 /* broken apps like defcon pass the argp value directly instead of a pointer to it */
2463 if(IS_INTRESOURCE(argp))
2465 SetLastError(WSAEFAULT);
2466 return SOCKET_ERROR;
2476 if( _get_sock_mask(s) )
2478 /* AsyncSelect()'ed sockets are always nonblocking */
2479 if (*argp) return 0;
2480 SetLastError(WSAEINVAL);
2481 return SOCKET_ERROR;
2484 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
2486 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
2494 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2495 SetLastError(WSAEINVAL);
2496 return SOCKET_ERROR;
2498 case SIOCGIFBRDADDR:
2499 case SIOCGIFNETMASK:
2501 /* These don't need any special handling. They are used by
2502 WsControl, and are here to suppress an unnecessary warning. */
2506 /* Netscape tries hard to use bogus ioctl 0x667e */
2507 /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
2508 * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
2510 WARN("\tunknown WS_IOCTL cmd (%08x)\n", cmd);
2514 fd = get_sock_fd( s, 0, NULL );
2517 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2519 release_sock_fd( s, fd );
2522 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2523 release_sock_fd( s, fd );
2525 return SOCKET_ERROR;
2528 /***********************************************************************
2529 * listen (WS2_32.13)
2531 int WINAPI WS_listen(SOCKET s, int backlog)
2533 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2535 TRACE("socket %04lx, backlog %d\n", s, backlog);
2538 if (listen(fd, backlog) == 0)
2540 release_sock_fd( s, fd );
2541 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
2543 FD_CONNECT|FD_WINE_CONNECTED);
2546 SetLastError(wsaErrno());
2547 release_sock_fd( s, fd );
2549 return SOCKET_ERROR;
2552 /***********************************************************************
2555 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2557 DWORD n, dwFlags = flags;
2563 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2564 return SOCKET_ERROR;
2569 /***********************************************************************
2570 * recvfrom (WS2_32.17)
2572 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2573 struct WS_sockaddr *from, int *fromlen)
2575 DWORD n, dwFlags = flags;
2581 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2582 return SOCKET_ERROR;
2587 /* allocate a poll array for the corresponding fd sets */
2588 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
2589 const WS_fd_set *exceptfds, int *count_ptr )
2591 unsigned int i, j = 0, count = 0;
2594 if (readfds) count += readfds->fd_count;
2595 if (writefds) count += writefds->fd_count;
2596 if (exceptfds) count += exceptfds->fd_count;
2598 if (!count) return NULL;
2599 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0])))) return NULL;
2601 for (i = 0; i < readfds->fd_count; i++, j++)
2603 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
2604 fds[j].events = POLLIN;
2608 for (i = 0; i < writefds->fd_count; i++, j++)
2610 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
2611 fds[j].events = POLLOUT;
2615 for (i = 0; i < exceptfds->fd_count; i++, j++)
2617 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
2618 fds[j].events = POLLHUP;
2624 /* release the file descriptor obtained in fd_sets_to_poll */
2625 /* must be called with the original fd_set arrays, before calling get_poll_results */
2626 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
2627 const WS_fd_set *exceptfds, struct pollfd *fds )
2629 unsigned int i, j = 0;
2633 for (i = 0; i < readfds->fd_count; i++, j++)
2634 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
2638 for (i = 0; i < writefds->fd_count; i++, j++)
2639 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
2643 for (i = 0; i < exceptfds->fd_count; i++, j++)
2644 if (fds[j].fd != -1)
2646 /* make sure we have a real error before releasing the fd */
2647 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
2648 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
2653 /* map the poll results back into the Windows fd sets */
2654 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
2655 const struct pollfd *fds )
2657 unsigned int i, j = 0, k, total = 0;
2661 for (i = k = 0; i < readfds->fd_count; i++, j++)
2662 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
2663 readfds->fd_count = k;
2668 for (i = k = 0; i < writefds->fd_count; i++, j++)
2669 if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
2670 writefds->fd_count = k;
2675 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
2676 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
2677 exceptfds->fd_count = k;
2684 /***********************************************************************
2685 * select (WS2_32.18)
2687 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
2688 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
2689 const struct WS_timeval* ws_timeout)
2691 struct pollfd *pollfds;
2692 int count, ret, timeout = -1;
2694 TRACE("read %p, write %p, excp %p timeout %p\n",
2695 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
2697 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )) && count)
2699 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2700 return SOCKET_ERROR;
2703 if (ws_timeout) timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
2705 ret = poll( pollfds, count, timeout );
2706 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2708 if (ret == -1) SetLastError(wsaErrno());
2709 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2710 HeapFree( GetProcessHeap(), 0, pollfds );
2714 /* helper to send completion messages for client-only i/o operation case */
2715 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
2720 SERVER_START_REQ( add_fd_completion )
2722 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
2723 req->cvalue = CompletionValue;
2724 req->status = CompletionStatus;
2725 req->information = Information;
2726 status = wine_server_call( req );
2732 /***********************************************************************
2735 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
2741 wsabuf.buf = (char*) buf;
2743 if ( WSASendTo( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
2744 return SOCKET_ERROR;
2749 /***********************************************************************
2750 * WSASend (WS2_32.72)
2752 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2753 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2754 LPWSAOVERLAPPED lpOverlapped,
2755 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2757 return WSASendTo( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
2758 NULL, 0, lpOverlapped, lpCompletionRoutine );
2761 /***********************************************************************
2762 * WSASendDisconnect (WS2_32.73)
2764 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
2766 return WS_shutdown( s, SD_SEND );
2770 /***********************************************************************
2771 * WSASendTo (WS2_32.74)
2773 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2774 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2775 const struct WS_sockaddr *to, int tolen,
2776 LPWSAOVERLAPPED lpOverlapped,
2777 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2779 unsigned int i, options;
2781 struct ws2_async *wsa;
2782 int totalLength = 0;
2783 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
2785 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
2786 s, lpBuffers, dwBufferCount, dwFlags,
2787 to, tolen, lpOverlapped, lpCompletionRoutine);
2789 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
2790 TRACE( "fd=%d, options=%x\n", fd, options );
2792 if ( fd == -1 ) return SOCKET_ERROR;
2794 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
2800 wsa->hSocket = SOCKET2HANDLE(s);
2801 wsa->addr = (struct WS_sockaddr *)to;
2802 wsa->addrlen.val = tolen;
2803 wsa->flags = dwFlags;
2804 wsa->n_iovecs = dwBufferCount;
2805 wsa->first_iovec = 0;
2806 for ( i = 0; i < dwBufferCount; i++ )
2808 wsa->iovec[i].iov_base = lpBuffers[i].buf;
2809 wsa->iovec[i].iov_len = lpBuffers[i].len;
2810 totalLength += lpBuffers[i].len;
2813 if (!lpNumberOfBytesSent)
2821 n = WS2_send( fd, wsa );
2822 if (n != -1 || errno != EINTR) break;
2824 if (n == -1 && errno != EAGAIN)
2827 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
2831 if ((lpOverlapped || lpCompletionRoutine) &&
2832 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
2834 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
2836 wsa->user_overlapped = lpOverlapped;
2837 wsa->completion_func = lpCompletionRoutine;
2838 release_sock_fd( s, fd );
2842 iosb->u.Status = STATUS_PENDING;
2843 iosb->Information = 0;
2845 SERVER_START_REQ( register_async )
2847 req->type = ASYNC_TYPE_WRITE;
2848 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2849 req->async.callback = wine_server_client_ptr( WS2_async_send );
2850 req->async.iosb = wine_server_client_ptr( iosb );
2851 req->async.arg = wine_server_client_ptr( wsa );
2852 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
2853 req->async.cvalue = cvalue;
2854 err = wine_server_call( req );
2858 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
2859 WSASetLastError( NtStatusToWSAError( err ));
2860 return SOCKET_ERROR;
2863 iosb->u.Status = STATUS_SUCCESS;
2864 iosb->Information = n;
2865 *lpNumberOfBytesSent = n;
2866 if (!wsa->completion_func)
2868 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
2869 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
2870 HeapFree( GetProcessHeap(), 0, wsa );
2872 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
2873 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
2878 if ( _is_blocking(s) )
2880 /* On a blocking non-overlapped stream socket,
2881 * sending blocks until the entire buffer is sent. */
2882 DWORD timeout_start = GetTickCount();
2884 *lpNumberOfBytesSent = 0;
2886 while (wsa->first_iovec < dwBufferCount)
2889 int timeout = GET_SNDTIMEO(fd);
2893 *lpNumberOfBytesSent += n;
2894 while (wsa->first_iovec < dwBufferCount && wsa->iovec[wsa->first_iovec].iov_len <= n)
2895 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2896 if (wsa->first_iovec >= dwBufferCount) break;
2897 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2898 wsa->iovec[wsa->first_iovec].iov_len -= n;
2903 timeout -= GetTickCount() - timeout_start;
2904 if (timeout < 0) timeout = 0;
2908 pfd.events = POLLOUT;
2910 if (!timeout || !poll( &pfd, 1, timeout ))
2913 goto error; /* msdn says a timeout in send is fatal */
2916 n = WS2_send( fd, wsa );
2917 if (n == -1 && errno != EAGAIN && errno != EINTR)
2924 else /* non-blocking */
2926 if (n < totalLength)
2927 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
2930 err = WSAEWOULDBLOCK;
2933 *lpNumberOfBytesSent = n;
2936 TRACE(" -> %i bytes\n", *lpNumberOfBytesSent);
2938 HeapFree( GetProcessHeap(), 0, wsa );
2939 release_sock_fd( s, fd );
2944 HeapFree( GetProcessHeap(), 0, wsa );
2945 release_sock_fd( s, fd );
2946 WARN(" -> ERROR %d\n", err);
2947 WSASetLastError(err);
2948 return SOCKET_ERROR;
2951 /***********************************************************************
2952 * sendto (WS2_32.20)
2954 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
2955 const struct WS_sockaddr *to, int tolen)
2961 wsabuf.buf = (char*) buf;
2963 if ( WSASendTo(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
2964 return SOCKET_ERROR;
2969 /***********************************************************************
2970 * setsockopt (WS2_32.21)
2972 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
2973 const char *optval, int optlen)
2977 struct linger linger;
2978 struct timeval tval;
2980 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2981 s, level, optname, optval, optlen);
2983 /* some broken apps pass the value directly instead of a pointer to it */
2984 if(IS_INTRESOURCE(optval))
2986 SetLastError(WSAEFAULT);
2987 return SOCKET_ERROR;
2995 /* Some options need some conversion before they can be sent to
2996 * setsockopt. The conversions are done here, then they will fall though
2997 * to the general case. Special options that are not passed to
2998 * setsockopt follow below that.*/
3000 case WS_SO_DONTLINGER:
3001 linger.l_onoff = *((const int*)optval) ? 0: 1;
3002 linger.l_linger = 0;
3004 optname = SO_LINGER;
3005 optval = (char*)&linger;
3006 optlen = sizeof(struct linger);
3010 linger.l_onoff = ((LINGER*)optval)->l_onoff;
3011 linger.l_linger = ((LINGER*)optval)->l_linger;
3012 /* FIXME: what is documented behavior if SO_LINGER optval
3015 optname = SO_LINGER;
3016 optval = (char*)&linger;
3017 optlen = sizeof(struct linger);
3021 if (*(const int*)optval < 2048)
3023 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
3028 /* The options listed here don't need any special handling. Thanks to
3029 * the conversion happening above, options from there will fall through
3031 case WS_SO_ACCEPTCONN:
3032 case WS_SO_BROADCAST:
3034 case WS_SO_KEEPALIVE:
3035 case WS_SO_OOBINLINE:
3036 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
3037 * however, using it the BSD way fixes bug 8513 and seems to be what
3038 * most programmers assume, anyway */
3039 case WS_SO_REUSEADDR:
3042 convert_sockopt(&level, &optname);
3045 /* SO_DEBUG is a privileged operation, ignore it. */
3047 TRACE("Ignoring SO_DEBUG\n");
3050 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
3051 * socket. According to MSDN, this option is silently ignored.*/
3052 case WS_SO_DONTROUTE:
3053 TRACE("Ignoring SO_DONTROUTE\n");
3056 /* Stops two sockets from being bound to the same port. Always happens
3057 * on unix systems, so just drop it. */
3058 case WS_SO_EXCLUSIVEADDRUSE:
3059 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
3062 /* SO_OPENTYPE does not require a valid socket handle. */
3063 case WS_SO_OPENTYPE:
3064 if (!optlen || optlen < sizeof(int) || !optval)
3066 SetLastError(WSAEFAULT);
3067 return SOCKET_ERROR;
3069 get_per_thread_data()->opentype = *(const int *)optval;
3070 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3074 case WS_SO_RCVTIMEO:
3077 case WS_SO_SNDTIMEO:
3079 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3080 if (optval && optlen == sizeof(UINT32)) {
3081 /* WinSock passes milliseconds instead of struct timeval */
3082 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
3083 tval.tv_sec = *(const UINT32*)optval / 1000;
3084 /* min of 500 milliseconds */
3085 if (tval.tv_sec == 0 && tval.tv_usec < 500000)
3086 tval.tv_usec = 500000;
3087 optlen = sizeof(struct timeval);
3088 optval = (char*)&tval;
3089 } else if (optlen == sizeof(struct timeval)) {
3090 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
3092 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
3095 convert_sockopt(&level, &optname);
3100 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3101 SetLastError(WSAENOPROTOOPT);
3102 return SOCKET_ERROR;
3104 break; /* case WS_SOL_SOCKET */
3111 fd = get_sock_fd( s, 0, NULL );
3112 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
3114 /* We try to set the ipx type on ipx socket level. */
3116 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
3118 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
3119 release_sock_fd( s, fd );
3120 return SOCKET_ERROR;
3125 /* Should we retrieve val using a getsockopt call and then
3126 * set the modified one? */
3127 val.ipx_pt = *optval;
3128 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
3131 release_sock_fd( s, fd );
3134 case IPX_FILTERPTYPE:
3135 /* Sets the receive filter packet type, at the moment we don't support it */
3136 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
3137 /* Returning 0 is better for now than returning a SOCKET_ERROR */
3141 FIXME("opt_name:%x\n", optname);
3142 return SOCKET_ERROR;
3144 break; /* case NSPROTO_IPX */
3147 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3148 case WS_IPPROTO_TCP:
3151 case WS_TCP_NODELAY:
3152 convert_sockopt(&level, &optname);
3155 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3156 return SOCKET_ERROR;
3163 case WS_IP_ADD_MEMBERSHIP:
3164 case WS_IP_DROP_MEMBERSHIP:
3168 case WS_IP_MULTICAST_IF:
3169 case WS_IP_MULTICAST_LOOP:
3170 case WS_IP_MULTICAST_TTL:
3174 convert_sockopt(&level, &optname);
3176 case WS_IP_DONTFRAGMENT:
3177 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
3180 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3181 return SOCKET_ERROR;
3186 FIXME("Unknown level: 0x%08x\n", level);
3187 return SOCKET_ERROR;
3188 } /* end switch(level) */
3190 /* avoid endianness issues if argument is a 16-bit int */
3191 if (optval && optlen < sizeof(int))
3193 woptval= *((const INT16 *) optval);
3194 optval= (char*) &woptval;
3197 fd = get_sock_fd( s, 0, NULL );
3198 if (fd == -1) return SOCKET_ERROR;
3200 if (setsockopt(fd, level, optname, optval, optlen) == 0)
3202 release_sock_fd( s, fd );
3205 TRACE("Setting socket error, %d\n", wsaErrno());
3206 SetLastError(wsaErrno());
3207 release_sock_fd( s, fd );
3209 return SOCKET_ERROR;
3212 /***********************************************************************
3213 * shutdown (WS2_32.22)
3215 int WINAPI WS_shutdown(SOCKET s, int how)
3217 int fd, err = WSAENOTSOCK;
3218 unsigned int options, clear_flags = 0;
3220 fd = get_sock_fd( s, 0, &options );
3221 TRACE("socket %04lx, how %i %x\n", s, how, options );
3224 return SOCKET_ERROR;
3228 case 0: /* drop receives */
3229 clear_flags |= FD_READ;
3231 case 1: /* drop sends */
3232 clear_flags |= FD_WRITE;
3234 case 2: /* drop all */
3235 clear_flags |= FD_READ|FD_WRITE;
3237 clear_flags |= FD_WINE_LISTENING;
3240 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3245 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3248 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3252 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3253 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3256 if (err) goto error;
3258 else /* non-overlapped mode */
3260 if ( shutdown( fd, how ) )
3267 release_sock_fd( s, fd );
3268 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3269 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
3273 release_sock_fd( s, fd );
3274 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3275 WSASetLastError( err );
3276 return SOCKET_ERROR;
3279 /***********************************************************************
3280 * socket (WS2_32.23)
3282 SOCKET WINAPI WS_socket(int af, int type, int protocol)
3284 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
3286 return WSASocketA( af, type, protocol, NULL, 0,
3287 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
3291 /***********************************************************************
3292 * gethostbyaddr (WS2_32.51)
3294 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
3296 struct WS_hostent *retval = NULL;
3297 struct hostent* host;
3299 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3302 struct hostent hostentry;
3305 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3307 int res = gethostbyaddr_r(addr, len, type,
3308 &hostentry, extrabuf, ebufsize, &host, &locerr);
3309 if( res != ERANGE) break;
3311 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3313 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3315 EnterCriticalSection( &csWSgetXXXbyYYY );
3316 host = gethostbyaddr(addr, len, type);
3317 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3319 if( host != NULL ) retval = WS_dup_he(host);
3320 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3321 HeapFree(GetProcessHeap(),0,extrabuf);
3323 LeaveCriticalSection( &csWSgetXXXbyYYY );
3325 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
3329 /***********************************************************************
3330 * gethostbyname (WS2_32.52)
3332 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
3334 struct WS_hostent *retval = NULL;
3335 struct hostent* host;
3336 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3339 struct hostent hostentry;
3340 int locerr = ENOBUFS;
3343 if( !name || !name[0]) {
3345 if( gethostname( buf, 100) == -1) {
3346 SetLastError( WSAENOBUFS); /* appropriate ? */
3350 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3352 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3354 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
3355 if( res != ERANGE) break;
3357 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3359 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3361 EnterCriticalSection( &csWSgetXXXbyYYY );
3362 host = gethostbyname(name);
3363 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3365 if (host) retval = WS_dup_he(host);
3366 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3367 HeapFree(GetProcessHeap(),0,extrabuf);
3369 LeaveCriticalSection( &csWSgetXXXbyYYY );
3371 if (retval && retval->h_addr_list[0][0] == 127 &&
3372 strcmp(name, "localhost") != 0)
3374 /* hostname != "localhost" but has loopback address. replace by our
3375 * special address.*/
3376 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
3378 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3383 /***********************************************************************
3384 * getprotobyname (WS2_32.53)
3386 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3388 struct WS_protoent* retval = NULL;
3389 #ifdef HAVE_GETPROTOBYNAME
3390 struct protoent* proto;
3391 EnterCriticalSection( &csWSgetXXXbyYYY );
3392 if( (proto = getprotobyname(name)) != NULL )
3394 retval = WS_dup_pe(proto);
3397 MESSAGE("protocol %s not found; You might want to add "
3398 "this to /etc/protocols\n", debugstr_a(name) );
3399 SetLastError(WSANO_DATA);
3401 LeaveCriticalSection( &csWSgetXXXbyYYY );
3403 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3408 /***********************************************************************
3409 * getprotobynumber (WS2_32.54)
3411 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3413 struct WS_protoent* retval = NULL;
3414 #ifdef HAVE_GETPROTOBYNUMBER
3415 struct protoent* proto;
3416 EnterCriticalSection( &csWSgetXXXbyYYY );
3417 if( (proto = getprotobynumber(number)) != NULL )
3419 retval = WS_dup_pe(proto);
3422 MESSAGE("protocol number %d not found; You might want to add "
3423 "this to /etc/protocols\n", number );
3424 SetLastError(WSANO_DATA);
3426 LeaveCriticalSection( &csWSgetXXXbyYYY );
3428 TRACE("%i ret %p\n", number, retval);
3433 /***********************************************************************
3434 * getservbyname (WS2_32.55)
3436 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3438 struct WS_servent* retval = NULL;
3439 struct servent* serv;
3441 char *proto_str = NULL;
3443 if (!(name_str = strdup_lower(name))) return NULL;
3445 if (proto && *proto)
3447 if (!(proto_str = strdup_lower(proto)))
3449 HeapFree( GetProcessHeap(), 0, name_str );
3454 EnterCriticalSection( &csWSgetXXXbyYYY );
3455 serv = getservbyname(name_str, proto_str);
3458 retval = WS_dup_se(serv);
3460 else SetLastError(WSANO_DATA);
3461 LeaveCriticalSection( &csWSgetXXXbyYYY );
3462 HeapFree( GetProcessHeap(), 0, proto_str );
3463 HeapFree( GetProcessHeap(), 0, name_str );
3464 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
3468 /***********************************************************************
3469 * freeaddrinfo (WS2_32.@)
3471 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
3474 struct WS_addrinfo *next;
3476 HeapFree(GetProcessHeap(),0,res->ai_canonname);
3477 HeapFree(GetProcessHeap(),0,res->ai_addr);
3478 next = res->ai_next;
3479 HeapFree(GetProcessHeap(),0,res);
3484 /* helper functions for getaddrinfo()/getnameinfo() */
3485 static int convert_aiflag_w2u(int winflags) {
3489 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3490 if (ws_aiflag_map[i][0] & winflags) {
3491 unixflags |= ws_aiflag_map[i][1];
3492 winflags &= ~ws_aiflag_map[i][0];
3495 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
3499 static int convert_niflag_w2u(int winflags) {
3503 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
3504 if (ws_niflag_map[i][0] & winflags) {
3505 unixflags |= ws_niflag_map[i][1];
3506 winflags &= ~ws_niflag_map[i][0];
3509 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
3513 static int convert_aiflag_u2w(int unixflags) {
3517 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3518 if (ws_aiflag_map[i][1] & unixflags) {
3519 winflags |= ws_aiflag_map[i][0];
3520 unixflags &= ~ws_aiflag_map[i][1];
3522 if (unixflags) /* will warn usually */
3523 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
3527 static int convert_eai_u2w(int unixret) {
3530 for (i=0;ws_eai_map[i][0];i++)
3531 if (ws_eai_map[i][1] == unixret)
3532 return ws_eai_map[i][0];
3536 /***********************************************************************
3537 * getaddrinfo (WS2_32.@)
3539 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
3541 #ifdef HAVE_GETADDRINFO
3542 struct addrinfo *unixaires = NULL;
3544 struct addrinfo unixhints, *punixhints = NULL;
3545 CHAR *node = NULL, *serv = NULL;
3548 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
3551 if (!(serv = strdup_lower(servname))) {
3552 HeapFree(GetProcessHeap(), 0, node);
3553 return WSA_NOT_ENOUGH_MEMORY;
3558 punixhints = &unixhints;
3560 memset(&unixhints, 0, sizeof(unixhints));
3561 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
3562 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
3563 punixhints->ai_family = 0;
3565 punixhints->ai_family = convert_af_w2u(hints->ai_family);
3566 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
3567 punixhints->ai_socktype = 0;
3569 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
3570 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
3571 punixhints->ai_protocol = 0;
3573 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
3576 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
3577 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
3579 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
3581 HeapFree(GetProcessHeap(), 0, node);
3582 HeapFree(GetProcessHeap(), 0, serv);
3585 struct addrinfo *xuai = unixaires;
3586 struct WS_addrinfo **xai = res;
3590 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
3596 *xai = ai;xai = &ai->ai_next;
3597 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
3598 ai->ai_family = convert_af_u2w(xuai->ai_family);
3599 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
3600 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
3601 if (xuai->ai_canonname) {
3602 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
3603 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
3604 if (!ai->ai_canonname)
3606 strcpy(ai->ai_canonname,xuai->ai_canonname);
3608 len = xuai->ai_addrlen;
3609 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
3612 ai->ai_addrlen = len;
3614 int winlen = ai->ai_addrlen;
3616 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
3617 ai->ai_addrlen = winlen;
3621 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
3624 ai->ai_addrlen = len;
3626 xuai = xuai->ai_next;
3628 freeaddrinfo(unixaires);
3630 result = convert_eai_u2w(result);
3636 if (*res) WS_freeaddrinfo(*res);
3637 if (unixaires) freeaddrinfo(unixaires);
3639 return WSA_NOT_ENOUGH_MEMORY;
3641 FIXME("getaddrinfo() failed, not found during buildtime.\n");
3646 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
3648 struct WS_addrinfoW *ret;
3650 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
3651 ret->ai_flags = ai->ai_flags;
3652 ret->ai_family = ai->ai_family;
3653 ret->ai_socktype = ai->ai_socktype;
3654 ret->ai_protocol = ai->ai_protocol;
3655 ret->ai_addrlen = ai->ai_addrlen;
3656 ret->ai_canonname = NULL;
3657 ret->ai_addr = NULL;
3658 ret->ai_next = NULL;
3659 if (ai->ai_canonname)
3661 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
3662 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
3664 HeapFree(GetProcessHeap(), 0, ret);
3667 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
3671 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
3673 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
3674 HeapFree(GetProcessHeap(), 0, ret);
3677 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
3682 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
3684 struct WS_addrinfoW *ret, *infoW;
3686 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
3687 while (info->ai_next)
3689 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
3694 infoW = infoW->ai_next;
3695 info = info->ai_next;
3700 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
3702 struct WS_addrinfo *ret;
3704 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
3705 ret->ai_flags = ai->ai_flags;
3706 ret->ai_family = ai->ai_family;
3707 ret->ai_socktype = ai->ai_socktype;
3708 ret->ai_protocol = ai->ai_protocol;
3709 ret->ai_addrlen = ai->ai_addrlen;
3710 ret->ai_canonname = NULL;
3711 ret->ai_addr = NULL;
3712 ret->ai_next = NULL;
3713 if (ai->ai_canonname)
3715 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
3716 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
3718 HeapFree(GetProcessHeap(), 0, ret);
3721 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
3725 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
3727 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
3728 HeapFree(GetProcessHeap(), 0, ret);
3731 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
3736 /***********************************************************************
3737 * GetAddrInfoW (WS2_32.@)
3739 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
3742 char *nodenameA, *servnameA = NULL;
3743 struct WS_addrinfo *resA, *hintsA = NULL;
3745 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
3746 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
3747 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
3751 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
3752 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
3754 HeapFree(GetProcessHeap(), 0, nodenameA);
3757 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
3760 if (hints) hintsA = addrinfo_WtoA(hints);
3761 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
3762 WS_freeaddrinfo(hintsA);
3766 *res = addrinfo_list_AtoW(resA);
3767 WS_freeaddrinfo(resA);
3770 HeapFree(GetProcessHeap(), 0, nodenameA);
3771 HeapFree(GetProcessHeap(), 0, servnameA);
3775 /***********************************************************************
3776 * FreeAddrInfoW (WS2_32.@)
3778 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
3783 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
3784 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
3786 HeapFree(GetProcessHeap(), 0, ai);
3791 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
3792 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
3794 #ifdef HAVE_GETNAMEINFO
3796 union generic_unix_sockaddr sa_u;
3799 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
3800 serv, servlen, flags);
3802 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
3805 WSASetLastError(WSAEFAULT);
3806 return WSA_NOT_ENOUGH_MEMORY;
3808 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
3809 return convert_eai_u2w(ret);
3811 FIXME("getnameinfo() failed, not found during buildtime.\n");
3816 /***********************************************************************
3817 * getservbyport (WS2_32.56)
3819 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
3821 struct WS_servent* retval = NULL;
3822 #ifdef HAVE_GETSERVBYPORT
3823 struct servent* serv;
3824 char *proto_str = NULL;
3826 if (proto && *proto)
3828 if (!(proto_str = strdup_lower(proto))) return NULL;
3830 EnterCriticalSection( &csWSgetXXXbyYYY );
3831 if( (serv = getservbyport(port, proto_str)) != NULL ) {
3832 retval = WS_dup_se(serv);
3834 else SetLastError(WSANO_DATA);
3835 LeaveCriticalSection( &csWSgetXXXbyYYY );
3836 HeapFree( GetProcessHeap(), 0, proto_str );
3838 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
3843 /***********************************************************************
3844 * gethostname (WS2_32.57)
3846 int WINAPI WS_gethostname(char *name, int namelen)
3848 TRACE("name %p, len %d\n", name, namelen);
3850 if (gethostname(name, namelen) == 0)
3852 TRACE("<- '%s'\n", name);
3855 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
3856 TRACE("<- ERROR !\n");
3857 return SOCKET_ERROR;
3861 /* ------------------------------------- Windows sockets extensions -- *
3863 * ------------------------------------------------------------------- */
3865 /***********************************************************************
3866 * WSAEnumNetworkEvents (WS2_32.36)
3868 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
3872 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
3874 SERVER_START_REQ( get_socket_event )
3876 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
3877 req->service = TRUE;
3878 req->c_event = wine_server_obj_handle( hEvent );
3879 wine_server_set_reply( req, lpEvent->iErrorCode, sizeof(lpEvent->iErrorCode) );
3880 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
3884 SetLastError(WSAEINVAL);
3885 return SOCKET_ERROR;
3888 /***********************************************************************
3889 * WSAEventSelect (WS2_32.39)
3891 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
3895 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
3897 SERVER_START_REQ( set_socket_event )
3899 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
3901 req->event = wine_server_obj_handle( hEvent );
3904 ret = wine_server_call( req );
3908 SetLastError(WSAEINVAL);
3909 return SOCKET_ERROR;
3912 /**********************************************************************
3913 * WSAGetOverlappedResult (WS2_32.40)
3915 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
3916 LPDWORD lpcbTransfer, BOOL fWait,
3921 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
3922 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
3924 if ( lpOverlapped == NULL )
3926 ERR( "Invalid pointer\n" );
3927 WSASetLastError(WSA_INVALID_PARAMETER);
3931 status = lpOverlapped->Internal;
3932 if (status == STATUS_PENDING)
3936 SetLastError( WSA_IO_INCOMPLETE );
3940 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
3941 INFINITE ) == WAIT_FAILED)
3943 status = lpOverlapped->Internal;
3947 *lpcbTransfer = lpOverlapped->InternalHigh;
3950 *lpdwFlags = lpOverlapped->u.s.Offset;
3952 if (status) SetLastError( RtlNtStatusToDosError(status) );
3957 /***********************************************************************
3958 * WSAAsyncSelect (WS2_32.101)
3960 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
3964 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
3966 SERVER_START_REQ( set_socket_event )
3968 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
3971 req->window = wine_server_user_handle( hWnd );
3973 ret = wine_server_call( req );
3977 SetLastError(WSAEINVAL);
3978 return SOCKET_ERROR;
3981 /***********************************************************************
3982 * WSACreateEvent (WS2_32.31)
3985 WSAEVENT WINAPI WSACreateEvent(void)
3987 /* Create a manual-reset event, with initial state: unsignaled */
3990 return CreateEventW(NULL, TRUE, FALSE, NULL);
3993 /***********************************************************************
3994 * WSACloseEvent (WS2_32.29)
3997 BOOL WINAPI WSACloseEvent(WSAEVENT event)
3999 TRACE ("event=%p\n", event);
4001 return CloseHandle(event);
4004 /***********************************************************************
4005 * WSASocketA (WS2_32.78)
4008 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
4009 LPWSAPROTOCOL_INFOA lpProtocolInfo,
4010 GROUP g, DWORD dwFlags)
4013 WSAPROTOCOL_INFOW info;
4015 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
4016 af, type, protocol, lpProtocolInfo, g, dwFlags);
4018 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
4020 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
4021 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
4022 info.szProtocol, WSAPROTOCOL_LEN + 1);
4026 WSASetLastError( WSAEINVAL);
4027 return SOCKET_ERROR;
4030 return WSASocketW(af, type, protocol, &info, g, dwFlags);
4033 /***********************************************************************
4034 * WSASocketW (WS2_32.79)
4037 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
4038 LPWSAPROTOCOL_INFOW lpProtocolInfo,
4039 GROUP g, DWORD dwFlags)
4044 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
4045 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
4048 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
4049 af, type, protocol, lpProtocolInfo, g, dwFlags );
4051 /* hack for WSADuplicateSocket */
4052 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
4053 ret = lpProtocolInfo->dwCatalogEntryId;
4054 TRACE("\tgot duplicate %04lx\n", ret);
4058 /* convert the socket family and type */
4059 af = convert_af_w2u(af);
4060 type = convert_socktype_w2u(type);
4064 if (af == FROM_PROTOCOL_INFO)
4065 af = lpProtocolInfo->iAddressFamily;
4066 if (type == FROM_PROTOCOL_INFO)
4067 type = lpProtocolInfo->iSocketType;
4068 if (protocol == FROM_PROTOCOL_INFO)
4069 protocol = lpProtocolInfo->iProtocol;
4072 if ( af == AF_UNSPEC) /* did they not specify the address family? */
4076 if (type == SOCK_STREAM) { af = AF_INET; break; }
4078 if (type == SOCK_DGRAM) { af = AF_INET; break; }
4079 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
4082 SERVER_START_REQ( create_socket )
4086 req->protocol = protocol;
4087 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
4088 req->attributes = OBJ_INHERIT;
4089 req->flags = dwFlags;
4090 set_error( wine_server_call( req ) );
4091 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
4096 TRACE("\tcreated %04lx\n", ret );
4100 if (GetLastError() == WSAEACCES) /* raw socket denied */
4102 if (type == SOCK_RAW)
4103 MESSAGE("WARNING: Trying to create a socket of type SOCK_RAW, this"
4104 " will fail unless you have special permissions.\n");
4106 MESSAGE("WS_SOCKET: Failed to create socket, this requires"
4107 " special permissions.\n");
4108 SetLastError(WSAESOCKTNOSUPPORT);
4111 WARN("\t\tfailed!\n");
4112 return INVALID_SOCKET;
4115 /***********************************************************************
4116 * WSAJoinLeaf (WS2_32.58)
4119 SOCKET WINAPI WSAJoinLeaf(
4121 const struct WS_sockaddr *addr,
4123 LPWSABUF lpCallerData,
4124 LPWSABUF lpCalleeData,
4130 return INVALID_SOCKET;
4133 /***********************************************************************
4134 * __WSAFDIsSet (WS2_32.151)
4136 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
4138 int i = set->fd_count;
4140 TRACE("(%ld,%p(%i))\n", s, set, i);
4143 if (set->fd_array[i] == s) return 1;
4147 /***********************************************************************
4148 * WSAIsBlocking (WINSOCK.114)
4149 * WSAIsBlocking (WS2_32.114)
4151 BOOL WINAPI WSAIsBlocking(void)
4153 /* By default WinSock should set all its sockets to non-blocking mode
4154 * and poll in PeekMessage loop when processing "blocking" ones. This
4155 * function is supposed to tell if the program is in this loop. Our
4156 * blocking calls are truly blocking so we always return FALSE.
4158 * Note: It is allowed to call this function without prior WSAStartup().
4165 /***********************************************************************
4166 * WSACancelBlockingCall (WINSOCK.113)
4167 * WSACancelBlockingCall (WS2_32.113)
4169 INT WINAPI WSACancelBlockingCall(void)
4175 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
4177 FIXME("How was this called?\n");
4182 /***********************************************************************
4183 * WSASetBlockingHook (WS2_32.109)
4185 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
4187 FARPROC prev = blocking_hook;
4188 blocking_hook = lpBlockFunc;
4189 TRACE("hook %p\n", lpBlockFunc);
4194 /***********************************************************************
4195 * WSAUnhookBlockingHook (WS2_32.110)
4197 INT WINAPI WSAUnhookBlockingHook(void)
4199 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
4204 /* ----------------------------------- end of API stuff */
4206 /* ----------------------------------- helper functions -
4208 * TODO: Merge WS_dup_..() stuff into one function that
4209 * would operate with a generic structure containing internal
4210 * pointers (via a template of some kind).
4213 static int list_size(char** l, int item_size)
4218 j += (item_size) ? item_size : strlen(l[i]) + 1;
4219 j += (i + 1) * sizeof(char*); }
4223 static int list_dup(char** l_src, char** l_to, int item_size)
4228 for (i = 0; l_src[i]; i++) ;
4229 p = (char *)(l_to + i + 1);
4230 for (i = 0; l_src[i]; i++)
4232 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
4233 memcpy(p, l_src[i], count);
4238 return p - (char *)l_to;
4243 /* duplicate hostent entry
4244 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
4245 * Ditto for protoent and servent.
4247 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
4250 struct WS_hostent *p_to;
4252 int size = (sizeof(*p_he) +
4253 strlen(p_he->h_name) + 1 +
4254 list_size(p_he->h_aliases, 0) +
4255 list_size(p_he->h_addr_list, p_he->h_length));
4257 if (!(p_to = check_buffer_he(size))) return NULL;
4258 p_to->h_addrtype = p_he->h_addrtype;
4259 p_to->h_length = p_he->h_length;
4261 p = (char *)(p_to + 1);
4263 strcpy(p, p_he->h_name);
4266 p_to->h_aliases = (char **)p;
4267 p += list_dup(p_he->h_aliases, p_to->h_aliases, 0);
4269 p_to->h_addr_list = (char **)p;
4270 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
4274 /* ----- protoent */
4276 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
4279 struct WS_protoent *p_to;
4281 int size = (sizeof(*p_pe) +
4282 strlen(p_pe->p_name) + 1 +
4283 list_size(p_pe->p_aliases, 0));
4285 if (!(p_to = check_buffer_pe(size))) return NULL;
4286 p_to->p_proto = p_pe->p_proto;
4288 p = (char *)(p_to + 1);
4290 strcpy(p, p_pe->p_name);
4293 p_to->p_aliases = (char **)p;
4294 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
4300 static struct WS_servent *WS_dup_se(const struct servent* p_se)
4303 struct WS_servent *p_to;
4305 int size = (sizeof(*p_se) +
4306 strlen(p_se->s_proto) + 1 +
4307 strlen(p_se->s_name) + 1 +
4308 list_size(p_se->s_aliases, 0));
4310 if (!(p_to = check_buffer_se(size))) return NULL;
4311 p_to->s_port = p_se->s_port;
4313 p = (char *)(p_to + 1);
4315 strcpy(p, p_se->s_name);
4319 strcpy(p, p_se->s_proto);
4322 p_to->s_aliases = (char **)p;
4323 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
4327 /* ----------------------------------- error handling */
4331 int loc_errno = errno;
4332 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
4336 case EINTR: return WSAEINTR;
4337 case EBADF: return WSAEBADF;
4339 case EACCES: return WSAEACCES;
4340 case EFAULT: return WSAEFAULT;
4341 case EINVAL: return WSAEINVAL;
4342 case EMFILE: return WSAEMFILE;
4343 case EWOULDBLOCK: return WSAEWOULDBLOCK;
4344 case EINPROGRESS: return WSAEINPROGRESS;
4345 case EALREADY: return WSAEALREADY;
4346 case ENOTSOCK: return WSAENOTSOCK;
4347 case EDESTADDRREQ: return WSAEDESTADDRREQ;
4348 case EMSGSIZE: return WSAEMSGSIZE;
4349 case EPROTOTYPE: return WSAEPROTOTYPE;
4350 case ENOPROTOOPT: return WSAENOPROTOOPT;
4351 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
4352 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
4353 case EOPNOTSUPP: return WSAEOPNOTSUPP;
4354 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
4355 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
4356 case EADDRINUSE: return WSAEADDRINUSE;
4357 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
4358 case ENETDOWN: return WSAENETDOWN;
4359 case ENETUNREACH: return WSAENETUNREACH;
4360 case ENETRESET: return WSAENETRESET;
4361 case ECONNABORTED: return WSAECONNABORTED;
4363 case ECONNRESET: return WSAECONNRESET;
4364 case ENOBUFS: return WSAENOBUFS;
4365 case EISCONN: return WSAEISCONN;
4366 case ENOTCONN: return WSAENOTCONN;
4367 case ESHUTDOWN: return WSAESHUTDOWN;
4368 case ETOOMANYREFS: return WSAETOOMANYREFS;
4369 case ETIMEDOUT: return WSAETIMEDOUT;
4370 case ECONNREFUSED: return WSAECONNREFUSED;
4371 case ELOOP: return WSAELOOP;
4372 case ENAMETOOLONG: return WSAENAMETOOLONG;
4373 case EHOSTDOWN: return WSAEHOSTDOWN;
4374 case EHOSTUNREACH: return WSAEHOSTUNREACH;
4375 case ENOTEMPTY: return WSAENOTEMPTY;
4377 case EPROCLIM: return WSAEPROCLIM;
4380 case EUSERS: return WSAEUSERS;
4383 case EDQUOT: return WSAEDQUOT;
4386 case ESTALE: return WSAESTALE;
4389 case EREMOTE: return WSAEREMOTE;
4392 /* just in case we ever get here and there are no problems */
4395 WARN("Unknown errno %d!\n", loc_errno);
4396 return WSAEOPNOTSUPP;
4400 UINT wsaHerrno(int loc_errno)
4403 WARN("h_errno %d.\n", loc_errno);
4407 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
4408 case TRY_AGAIN: return WSATRY_AGAIN;
4409 case NO_RECOVERY: return WSANO_RECOVERY;
4410 case NO_DATA: return WSANO_DATA;
4411 case ENOBUFS: return WSAENOBUFS;
4415 WARN("Unknown h_errno %d!\n", loc_errno);
4416 return WSAEOPNOTSUPP;
4421 /***********************************************************************
4422 * WSARecv (WS2_32.67)
4424 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4425 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
4426 LPWSAOVERLAPPED lpOverlapped,
4427 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
4429 return WSARecvFrom(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
4430 NULL, NULL, lpOverlapped, lpCompletionRoutine);
4433 /***********************************************************************
4434 * WSARecvFrom (WS2_32.69)
4436 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4437 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
4438 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
4439 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4442 unsigned int i, options;
4444 struct ws2_async *wsa;
4445 DWORD timeout_start = GetTickCount();
4446 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4448 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
4449 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
4450 (lpFromlen ? *lpFromlen : -1),
4451 lpOverlapped, lpCompletionRoutine);
4453 fd = get_sock_fd( s, FILE_READ_DATA, &options );
4454 TRACE( "fd=%d, options=%x\n", fd, options );
4456 if (fd == -1) return SOCKET_ERROR;
4458 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
4464 wsa->hSocket = SOCKET2HANDLE(s);
4465 wsa->flags = *lpFlags;
4467 wsa->addrlen.ptr = lpFromlen;
4468 wsa->n_iovecs = dwBufferCount;
4469 wsa->first_iovec = 0;
4470 for (i = 0; i < dwBufferCount; i++)
4472 /* check buffer first to trigger write watches */
4473 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
4478 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4479 wsa->iovec[i].iov_len = lpBuffers[i].len;
4484 n = WS2_recv( fd, wsa );
4487 if (errno == EINTR) continue;
4488 if (errno != EAGAIN)
4491 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
4496 *lpNumberOfBytesRecvd = n;
4498 if ((lpOverlapped || lpCompletionRoutine) &&
4499 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4501 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4503 wsa->user_overlapped = lpOverlapped;
4504 wsa->completion_func = lpCompletionRoutine;
4505 release_sock_fd( s, fd );
4509 iosb->u.Status = STATUS_PENDING;
4510 iosb->Information = 0;
4512 SERVER_START_REQ( register_async )
4514 req->type = ASYNC_TYPE_READ;
4515 req->async.handle = wine_server_obj_handle( wsa->hSocket );
4516 req->async.callback = wine_server_client_ptr( WS2_async_recv );
4517 req->async.iosb = wine_server_client_ptr( iosb );
4518 req->async.arg = wine_server_client_ptr( wsa );
4519 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
4520 req->async.cvalue = cvalue;
4521 err = wine_server_call( req );
4525 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4526 WSASetLastError( NtStatusToWSAError( err ));
4527 return SOCKET_ERROR;
4530 iosb->u.Status = STATUS_SUCCESS;
4531 iosb->Information = n;
4532 if (!wsa->completion_func)
4534 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4535 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
4536 HeapFree( GetProcessHeap(), 0, wsa );
4538 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4539 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4540 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4546 if ( _is_blocking(s) )
4549 int timeout = GET_RCVTIMEO(fd);
4552 timeout -= GetTickCount() - timeout_start;
4553 if (timeout < 0) timeout = 0;
4557 pfd.events = POLLIN;
4558 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
4560 if (!timeout || !poll( &pfd, 1, timeout ))
4563 /* a timeout is not fatal */
4564 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4570 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4571 err = WSAEWOULDBLOCK;
4576 TRACE(" -> %i bytes\n", n);
4577 HeapFree( GetProcessHeap(), 0, wsa );
4578 release_sock_fd( s, fd );
4579 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4584 HeapFree( GetProcessHeap(), 0, wsa );
4585 release_sock_fd( s, fd );
4586 WARN(" -> ERROR %d\n", err);
4587 WSASetLastError( err );
4588 return SOCKET_ERROR;
4591 /***********************************************************************
4592 * WSCInstallProvider (WS2_32.88)
4594 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
4595 LPCWSTR lpszProviderDllPath,
4596 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
4597 DWORD dwNumberOfEntries,
4600 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
4601 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
4602 dwNumberOfEntries, lpErrno);
4608 /***********************************************************************
4609 * WSCDeinstallProvider (WS2_32.83)
4611 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
4613 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
4619 /***********************************************************************
4620 * WSAAccept (WS2_32.26)
4622 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
4623 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
4626 int ret = 0, size = 0;
4627 WSABUF CallerId, CallerData, CalleeId, CalleeData;
4628 /* QOS SQOS, GQOS; */
4631 SOCKADDR src_addr, dst_addr;
4633 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %d\n",
4634 s, addr, addrlen, lpfnCondition, dwCallbackData);
4637 size = sizeof(src_addr);
4638 cs = WS_accept(s, &src_addr, &size);
4640 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
4642 if (!lpfnCondition) return cs;
4644 CallerId.buf = (char *)&src_addr;
4645 CallerId.len = sizeof(src_addr);
4647 CallerData.buf = NULL;
4650 WS_getsockname(cs, &dst_addr, &size);
4652 CalleeId.buf = (char *)&dst_addr;
4653 CalleeId.len = sizeof(dst_addr);
4656 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
4657 &CalleeId, &CalleeData, &g, dwCallbackData);
4662 if (addr && addrlen)
4663 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
4666 SERVER_START_REQ( set_socket_deferred )
4668 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4669 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
4670 if ( !wine_server_call_err ( req ) )
4672 SetLastError( WSATRY_AGAIN );
4673 WS_closesocket( cs );
4677 return SOCKET_ERROR;
4680 SetLastError(WSAECONNREFUSED);
4681 return SOCKET_ERROR;
4683 FIXME("Unknown return type from Condition function\n");
4684 SetLastError(WSAENOTSOCK);
4685 return SOCKET_ERROR;
4689 /***********************************************************************
4690 * WSADuplicateSocketA (WS2_32.32)
4692 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
4696 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4697 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4698 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
4699 /* I don't know what the real Windoze does next, this is a hack */
4700 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
4701 * the target use the global duplicate, or we could copy a reference to us to the structure
4702 * and let the target duplicate it from us, but let's do it as simple as possible */
4703 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4704 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4705 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4706 0, FALSE, DUPLICATE_SAME_ACCESS);
4707 CloseHandle(hProcess);
4708 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4712 /***********************************************************************
4713 * WSADuplicateSocketW (WS2_32.33)
4715 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
4719 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4721 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4722 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4723 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4724 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4725 0, FALSE, DUPLICATE_SAME_ACCESS);
4726 CloseHandle(hProcess);
4727 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4731 /***********************************************************************
4732 * WSAInstallServiceClassA (WS2_32.48)
4734 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
4736 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
4737 WSASetLastError(WSAEACCES);
4738 return SOCKET_ERROR;
4741 /***********************************************************************
4742 * WSAInstallServiceClassW (WS2_32.49)
4744 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
4746 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
4747 WSASetLastError(WSAEACCES);
4748 return SOCKET_ERROR;
4751 /***********************************************************************
4752 * WSARemoveServiceClass (WS2_32.70)
4754 int WINAPI WSARemoveServiceClass(LPGUID info)
4756 FIXME("Request to remove service %p\n",info);
4757 WSASetLastError(WSATYPE_NOT_FOUND);
4758 return SOCKET_ERROR;
4761 /***********************************************************************
4762 * inet_ntop (WS2_32.@)
4764 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
4766 #ifdef HAVE_INET_NTOP
4767 struct WS_in6_addr *in6;
4768 struct WS_in_addr *in;
4771 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
4774 WSASetLastError( STATUS_INVALID_PARAMETER );
4783 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
4789 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
4793 WSASetLastError( WSAEAFNOSUPPORT );
4797 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
4800 FIXME( "not supported on this platform\n" );
4801 WSASetLastError( WSAEAFNOSUPPORT );
4806 /***********************************************************************
4807 * WSAStringToAddressA (WS2_32.80)
4809 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
4811 LPWSAPROTOCOL_INFOA lpProtocolInfo,
4812 LPSOCKADDR lpAddress,
4813 LPINT lpAddressLength)
4816 LPSTR workBuffer=NULL,ptrPort;
4818 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
4819 lpProtocolInfo, lpAddress, lpAddressLength );
4821 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
4825 WSASetLastError(WSAEINVAL);
4826 return SOCKET_ERROR;
4830 FIXME("ProtocolInfo not implemented.\n");
4832 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
4833 strlen(AddressString) + 1);
4836 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4837 return SOCKET_ERROR;
4840 strcpy(workBuffer, AddressString);
4842 switch(AddressFamily)
4846 struct in_addr inetaddr;
4848 /* If lpAddressLength is too small, tell caller the size we need */
4849 if (*lpAddressLength < sizeof(SOCKADDR_IN))
4851 *lpAddressLength = sizeof(SOCKADDR_IN);
4855 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
4857 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
4859 ptrPort = strchr(workBuffer, ':');
4862 ((LPSOCKADDR_IN)lpAddress)->sin_port = (WS_u_short)atoi(ptrPort+1);
4867 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
4870 if(inet_aton(workBuffer, &inetaddr) > 0)
4872 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
4883 struct in6_addr inetaddr;
4884 /* If lpAddressLength is too small, tell caller the size we need */
4885 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
4887 *lpAddressLength = sizeof(SOCKADDR_IN6);
4891 #ifdef HAVE_INET_PTON
4892 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
4894 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
4896 /* This one is a bit tricky. An IPv6 address contains colons, so the
4897 * check from IPv4 doesn't work like that. However, IPv6 addresses that
4898 * contain a port are written with braces like [fd12:3456:7890::1]:12345
4899 * so what we will do is to look for ']', check if the next char is a
4900 * colon, and if it is, parse the port as in IPv4. */
4902 ptrPort = strchr(workBuffer, ']');
4903 if(ptrPort && *(++ptrPort) == ':')
4905 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = (WS_u_short)atoi(ptrPort+1);
4910 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
4913 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
4915 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
4916 sizeof(struct in6_addr));
4920 #endif /* HAVE_INET_PTON */
4926 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
4927 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
4931 HeapFree(GetProcessHeap(), 0, workBuffer);
4934 WSASetLastError(res);
4935 return SOCKET_ERROR;
4938 /***********************************************************************
4939 * WSAStringToAddressW (WS2_32.81)
4941 * Does anybody know if this functions allows to use hebrew/arabic/chinese... digits?
4942 * If this should be the case, it would be required to map these digits
4943 * to Unicode digits (0-9) using FoldString first.
4945 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
4947 LPWSAPROTOCOL_INFOW lpProtocolInfo,
4948 LPSOCKADDR lpAddress,
4949 LPINT lpAddressLength)
4952 LPSTR workBuffer=NULL;
4953 WSAPROTOCOL_INFOA infoA;
4954 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
4956 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
4957 lpAddress, lpAddressLength );
4959 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
4961 /* if ProtocolInfo is available - convert to ANSI variant */
4964 lpProtoInfoA = &infoA;
4965 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
4967 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
4968 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
4970 WSASetLastError( WSAEINVAL);
4971 return SOCKET_ERROR;
4977 /* Translate AddressString to ANSI code page - assumes that only
4978 standard digits 0-9 are used with this API call */
4979 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
4980 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
4984 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
4985 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
4986 lpAddress,lpAddressLength);
4987 HeapFree( GetProcessHeap(), 0, workBuffer );
4991 res = WSA_NOT_ENOUGH_MEMORY;
4996 WSASetLastError(res);
4997 return SOCKET_ERROR;
5000 /***********************************************************************
5001 * WSAAddressToStringA (WS2_32.27)
5003 * See WSAAddressToStringW
5005 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
5006 LPWSAPROTOCOL_INFOA info, LPSTR string,
5010 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
5013 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
5015 if (!sockaddr) return SOCKET_ERROR;
5016 if (!string || !lenstr) return SOCKET_ERROR;
5018 switch(sockaddr->sa_family)
5021 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
5022 sprintf( buffer, "%u.%u.%u.%u:%u",
5023 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
5024 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
5025 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
5026 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
5027 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
5029 p = strchr( buffer, ':' );
5030 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
5035 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
5038 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
5039 if ((sockaddr6->sin6_port))
5040 strcpy(buffer, "[");
5041 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
5043 WSASetLastError(WSAEINVAL);
5044 return SOCKET_ERROR;
5046 if ((sockaddr6->sin6_scope_id))
5047 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
5048 if ((sockaddr6->sin6_port))
5049 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
5054 WSASetLastError(WSAEINVAL);
5055 return SOCKET_ERROR;
5058 size = strlen( buffer ) + 1;
5063 WSASetLastError(WSAEFAULT);
5064 return SOCKET_ERROR;
5068 strcpy( string, buffer );
5072 /***********************************************************************
5073 * WSAAddressToStringW (WS2_32.28)
5075 * Convert a sockaddr address into a readable address string.
5078 * sockaddr [I] Pointer to a sockaddr structure.
5079 * len [I] Size of the sockaddr structure.
5080 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
5081 * string [I/O] Pointer to a buffer to receive the address string.
5082 * lenstr [I/O] Size of the receive buffer in WCHARs.
5086 * Failure: SOCKET_ERROR
5089 * The 'info' parameter is ignored.
5091 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
5092 LPWSAPROTOCOL_INFOW info, LPWSTR string,
5097 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
5100 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
5103 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
5105 if (ret) return ret;
5107 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
5112 WSASetLastError(WSAEFAULT);
5113 return SOCKET_ERROR;
5117 lstrcpyW( string, buffer );
5121 /***********************************************************************
5122 * WSAEnumNameSpaceProvidersA (WS2_32.34)
5124 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
5126 FIXME( "(%p %p) Stub!\n", len, buffer );
5130 /***********************************************************************
5131 * WSAEnumNameSpaceProvidersW (WS2_32.35)
5133 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
5135 FIXME( "(%p %p) Stub!\n", len, buffer );
5139 /***********************************************************************
5140 * WSAGetQOSByName (WS2_32.41)
5142 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
5144 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
5148 /***********************************************************************
5149 * WSAGetServiceClassInfoA (WS2_32.42)
5151 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
5152 LPWSASERVICECLASSINFOA info )
5154 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
5156 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5157 return SOCKET_ERROR;
5160 /***********************************************************************
5161 * WSAGetServiceClassInfoW (WS2_32.43)
5163 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
5164 LPWSASERVICECLASSINFOW info )
5166 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
5168 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5169 return SOCKET_ERROR;
5172 /***********************************************************************
5173 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
5175 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
5177 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
5178 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5179 return SOCKET_ERROR;
5182 /***********************************************************************
5183 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
5185 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
5187 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
5188 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5189 return SOCKET_ERROR;
5192 /***********************************************************************
5193 * WSALookupServiceBeginA (WS2_32.59)
5195 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
5196 DWORD dwControlFlags,
5199 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
5201 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5202 return SOCKET_ERROR;
5205 /***********************************************************************
5206 * WSALookupServiceBeginW (WS2_32.60)
5208 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
5209 DWORD dwControlFlags,
5212 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
5214 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5215 return SOCKET_ERROR;
5218 /***********************************************************************
5219 * WSALookupServiceBeginW (WS2_32.61)
5221 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
5223 FIXME("(%p) Stub!\n", lookup );
5227 /***********************************************************************
5228 * WSALookupServiceNextA (WS2_32.62)
5230 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
5232 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
5236 /***********************************************************************
5237 * WSALookupServiceNextW (WS2_32.63)
5239 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
5241 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
5245 /***********************************************************************
5246 * WSANtohl (WS2_32.64)
5248 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
5250 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
5252 if (!lphostlong) return WSAEFAULT;
5254 *lphostlong = ntohl( netlong );
5258 /***********************************************************************
5259 * WSANtohs (WS2_32.65)
5261 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
5263 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
5265 if (!lphostshort) return WSAEFAULT;
5267 *lphostshort = ntohs( netshort );
5271 /***********************************************************************
5272 * WSAProviderConfigChange (WS2_32.66)
5274 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
5275 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
5277 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
5278 return SOCKET_ERROR;
5281 /***********************************************************************
5282 * WSARecvDisconnect (WS2_32.68)
5284 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
5286 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
5288 return WS_shutdown( s, 0 );
5291 /***********************************************************************
5292 * WSASetServiceA (WS2_32.76)
5294 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
5296 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5300 /***********************************************************************
5301 * WSASetServiceW (WS2_32.77)
5303 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
5305 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5309 /***********************************************************************
5310 * WSCEnableNSProvider (WS2_32.84)
5312 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
5314 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
5318 /***********************************************************************
5319 * WSCGetProviderPath (WS2_32.86)
5321 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
5323 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
5325 if (!errcode || !provider || !len) return WSAEFAULT;
5327 *errcode = WSAEINVAL;
5328 return SOCKET_ERROR;
5331 /***********************************************************************
5332 * WSCInstallNameSpace (WS2_32.87)
5334 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
5335 DWORD version, LPGUID provider )
5337 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
5338 namespace, version, debugstr_guid(provider) );
5342 /***********************************************************************
5343 * WSCUnInstallNameSpace (WS2_32.89)
5345 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
5347 FIXME("(%p) Stub!\n", lpProviderId);
5351 /***********************************************************************
5352 * WSCWriteProviderOrder (WS2_32.91)
5354 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
5356 FIXME("(%p 0x%08x) Stub!\n", entry, number);