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);
169 WINE_DECLARE_DEBUG_CHANNEL(winediag);
171 /* critical section to protect some non-reentrant net function */
172 static CRITICAL_SECTION csWSgetXXXbyYYY;
173 static CRITICAL_SECTION_DEBUG critsect_debug =
175 0, 0, &csWSgetXXXbyYYY,
176 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
177 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
179 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
181 union generic_unix_sockaddr
183 struct sockaddr addr;
184 char data[128]; /* should be big enough for all families */
187 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
189 if (!a) return "(nil)";
190 switch (a->sa_family)
193 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
194 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
195 ntohs(((const struct sockaddr_in *)a)->sin_port));
200 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
202 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
204 p = "(unknown IPv6 address)";
205 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
206 p, ntohs(sin->sin6_port));
212 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
213 addr = ntohl( addr );
214 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
216 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
219 return wine_dbg_sprintf("{ family %d }", a->sa_family);
223 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
224 #define SOCKET2HANDLE(s) ((HANDLE)(s))
225 #define HANDLE2SOCKET(h) ((SOCKET)(h))
227 /****************************************************************
228 * Async IO declarations
229 ****************************************************************/
231 typedef struct ws2_async
235 LPWSAOVERLAPPED user_overlapped;
236 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
237 IO_STATUS_BLOCK local_iosb;
238 struct WS_sockaddr *addr;
241 int val; /* for send operations */
242 int *ptr; /* for recv operations */
245 unsigned int n_iovecs;
246 unsigned int first_iovec;
247 struct iovec iovec[1];
250 /****************************************************************/
252 /* ----------------------------------- internal data */
254 /* ws_... struct conversion flags */
256 typedef struct /* WSAAsyncSelect() control struct */
258 HANDLE service, event, sock;
264 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
265 #define WS_MAX_UDP_DATAGRAM 1024
266 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
268 /* hostent's, servent's and protent's are stored in one buffer per thread,
269 * as documented on MSDN for the functions that return any of the buffers */
270 struct per_thread_data
273 struct WS_hostent *he_buffer;
274 struct WS_servent *se_buffer;
275 struct WS_protoent *pe_buffer;
281 /* internal: routing description information */
288 static INT num_startup; /* reference counter */
289 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
291 /* function prototypes */
292 static struct WS_hostent *WS_create_he(char *name, int aliases, int addresses, int fill_addresses);
293 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
294 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
295 static struct WS_servent *WS_dup_se(const struct servent* p_se);
297 int WSAIOCTL_GetInterfaceCount(void);
298 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
300 #define MAP_OPTION(opt) { WS_##opt, opt }
302 static const int ws_sock_map[][2] =
304 MAP_OPTION( SO_DEBUG ),
305 MAP_OPTION( SO_ACCEPTCONN ),
306 MAP_OPTION( SO_REUSEADDR ),
307 MAP_OPTION( SO_KEEPALIVE ),
308 MAP_OPTION( SO_DONTROUTE ),
309 MAP_OPTION( SO_BROADCAST ),
310 MAP_OPTION( SO_LINGER ),
311 MAP_OPTION( SO_OOBINLINE ),
312 MAP_OPTION( SO_SNDBUF ),
313 MAP_OPTION( SO_RCVBUF ),
314 MAP_OPTION( SO_ERROR ),
315 MAP_OPTION( SO_TYPE ),
317 MAP_OPTION( SO_RCVTIMEO ),
320 MAP_OPTION( SO_SNDTIMEO ),
324 static const int ws_tcp_map[][2] =
327 MAP_OPTION( TCP_NODELAY ),
331 static const int ws_ip_map[][2] =
333 MAP_OPTION( IP_MULTICAST_IF ),
334 MAP_OPTION( IP_MULTICAST_TTL ),
335 MAP_OPTION( IP_MULTICAST_LOOP ),
336 MAP_OPTION( IP_ADD_MEMBERSHIP ),
337 MAP_OPTION( IP_DROP_MEMBERSHIP ),
338 MAP_OPTION( IP_OPTIONS ),
340 MAP_OPTION( IP_HDRINCL ),
342 MAP_OPTION( IP_TOS ),
343 MAP_OPTION( IP_TTL ),
346 static const int ws_af_map[][2] =
348 MAP_OPTION( AF_UNSPEC ),
349 MAP_OPTION( AF_INET ),
350 MAP_OPTION( AF_INET6 ),
352 MAP_OPTION( AF_IPX ),
355 MAP_OPTION( AF_IRDA ),
357 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
360 static const int ws_socktype_map[][2] =
362 MAP_OPTION( SOCK_DGRAM ),
363 MAP_OPTION( SOCK_STREAM ),
364 MAP_OPTION( SOCK_RAW ),
365 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
368 static const int ws_proto_map[][2] =
370 MAP_OPTION( IPPROTO_IP ),
371 MAP_OPTION( IPPROTO_TCP ),
372 MAP_OPTION( IPPROTO_UDP ),
373 MAP_OPTION( IPPROTO_ICMP ),
374 MAP_OPTION( IPPROTO_IGMP ),
375 MAP_OPTION( IPPROTO_RAW ),
376 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
379 static const int ws_aiflag_map[][2] =
381 MAP_OPTION( AI_PASSIVE ),
382 MAP_OPTION( AI_CANONNAME ),
383 MAP_OPTION( AI_NUMERICHOST ),
384 /* Linux/UNIX knows a lot more. But Windows only
385 * has 3 as far as I could see. -Marcus
389 static const int ws_niflag_map[][2] =
391 MAP_OPTION( NI_NOFQDN ),
392 MAP_OPTION( NI_NUMERICHOST ),
393 MAP_OPTION( NI_NAMEREQD ),
394 MAP_OPTION( NI_NUMERICSERV ),
395 MAP_OPTION( NI_DGRAM ),
398 static const int ws_eai_map[][2] =
400 MAP_OPTION( EAI_AGAIN ),
401 MAP_OPTION( EAI_BADFLAGS ),
402 MAP_OPTION( EAI_FAIL ),
403 MAP_OPTION( EAI_FAMILY ),
404 MAP_OPTION( EAI_MEMORY ),
405 /* Note: EAI_NODATA is deprecated, but still
406 * used by Windows and Linux... We map the newer
407 * EAI_NONAME to EAI_NODATA for now until Windows
411 MAP_OPTION( EAI_NODATA ),
414 { WS_EAI_NODATA, EAI_NONAME },
417 MAP_OPTION( EAI_SERVICE ),
418 MAP_OPTION( EAI_SOCKTYPE ),
422 static const char magic_loopback_addr[] = {127, 12, 34, 56};
424 /* ----------------------------------- error handling */
426 static UINT wsaErrno(void)
428 int loc_errno = errno;
429 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
433 case EINTR: return WSAEINTR;
434 case EBADF: return WSAEBADF;
436 case EACCES: return WSAEACCES;
437 case EFAULT: return WSAEFAULT;
438 case EINVAL: return WSAEINVAL;
439 case EMFILE: return WSAEMFILE;
440 case EWOULDBLOCK: return WSAEWOULDBLOCK;
441 case EINPROGRESS: return WSAEINPROGRESS;
442 case EALREADY: return WSAEALREADY;
443 case ENOTSOCK: return WSAENOTSOCK;
444 case EDESTADDRREQ: return WSAEDESTADDRREQ;
445 case EMSGSIZE: return WSAEMSGSIZE;
446 case EPROTOTYPE: return WSAEPROTOTYPE;
447 case ENOPROTOOPT: return WSAENOPROTOOPT;
448 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
449 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
450 case EOPNOTSUPP: return WSAEOPNOTSUPP;
451 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
452 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
453 case EADDRINUSE: return WSAEADDRINUSE;
454 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
455 case ENETDOWN: return WSAENETDOWN;
456 case ENETUNREACH: return WSAENETUNREACH;
457 case ENETRESET: return WSAENETRESET;
458 case ECONNABORTED: return WSAECONNABORTED;
460 case ECONNRESET: return WSAECONNRESET;
461 case ENOBUFS: return WSAENOBUFS;
462 case EISCONN: return WSAEISCONN;
463 case ENOTCONN: return WSAENOTCONN;
464 case ESHUTDOWN: return WSAESHUTDOWN;
465 case ETOOMANYREFS: return WSAETOOMANYREFS;
466 case ETIMEDOUT: return WSAETIMEDOUT;
467 case ECONNREFUSED: return WSAECONNREFUSED;
468 case ELOOP: return WSAELOOP;
469 case ENAMETOOLONG: return WSAENAMETOOLONG;
470 case EHOSTDOWN: return WSAEHOSTDOWN;
471 case EHOSTUNREACH: return WSAEHOSTUNREACH;
472 case ENOTEMPTY: return WSAENOTEMPTY;
474 case EPROCLIM: return WSAEPROCLIM;
477 case EUSERS: return WSAEUSERS;
480 case EDQUOT: return WSAEDQUOT;
483 case ESTALE: return WSAESTALE;
486 case EREMOTE: return WSAEREMOTE;
489 /* just in case we ever get here and there are no problems */
492 WARN("Unknown errno %d!\n", loc_errno);
493 return WSAEOPNOTSUPP;
497 static UINT wsaHerrno(int loc_errno)
500 WARN("h_errno %d.\n", loc_errno);
504 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
505 case TRY_AGAIN: return WSATRY_AGAIN;
506 case NO_RECOVERY: return WSANO_RECOVERY;
507 case NO_DATA: return WSANO_DATA;
508 case ENOBUFS: return WSAENOBUFS;
512 WARN("Unknown h_errno %d!\n", loc_errno);
513 return WSAEOPNOTSUPP;
517 static inline DWORD NtStatusToWSAError( const DWORD status )
519 /* We only need to cover the status codes set by server async request handling */
523 case STATUS_SUCCESS: wserr = 0; break;
524 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
525 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
526 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
527 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
528 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
529 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
530 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
531 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
533 if ( status >= WSABASEERR && status <= WSABASEERR+1004 )
534 /* It is not an NT status code but a winsock error */
538 wserr = RtlNtStatusToDosError( status );
539 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
545 /* set last error code from NT status without mapping WSA errors */
546 static inline unsigned int set_error( unsigned int err )
550 err = NtStatusToWSAError( err );
556 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
559 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
564 static inline void release_sock_fd( SOCKET s, int fd )
566 wine_server_release_fd( SOCKET2HANDLE(s), fd );
569 static void _enable_event( HANDLE s, unsigned int event,
570 unsigned int sstate, unsigned int cstate )
572 SERVER_START_REQ( enable_socket_event )
574 req->handle = wine_server_obj_handle( s );
576 req->sstate = sstate;
577 req->cstate = cstate;
578 wine_server_call( req );
583 static int _is_blocking(SOCKET s)
586 SERVER_START_REQ( get_socket_event )
588 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
589 req->service = FALSE;
591 wine_server_call( req );
592 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
598 static unsigned int _get_sock_mask(SOCKET s)
601 SERVER_START_REQ( get_socket_event )
603 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
604 req->service = FALSE;
606 wine_server_call( req );
613 static void _sync_sock_state(SOCKET s)
615 /* do a dummy wineserver request in order to let
616 the wineserver run through its select loop once */
617 (void)_is_blocking(s);
620 static int _get_sock_error(SOCKET s, unsigned int bit)
622 int events[FD_MAX_EVENTS];
624 SERVER_START_REQ( get_socket_event )
626 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
627 req->service = FALSE;
629 wine_server_set_reply( req, events, sizeof(events) );
630 wine_server_call( req );
636 static struct per_thread_data *get_per_thread_data(void)
638 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
639 /* lazy initialization */
642 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
643 NtCurrentTeb()->WinSockData = ptb;
648 static void free_per_thread_data(void)
650 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
654 /* delete scratch buffers */
655 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
656 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
657 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
658 ptb->he_buffer = NULL;
659 ptb->se_buffer = NULL;
660 ptb->pe_buffer = NULL;
662 HeapFree( GetProcessHeap(), 0, ptb );
663 NtCurrentTeb()->WinSockData = NULL;
666 /***********************************************************************
667 * DllMain (WS2_32.init)
669 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
671 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
673 case DLL_PROCESS_ATTACH:
675 case DLL_PROCESS_DETACH:
676 free_per_thread_data();
679 case DLL_THREAD_DETACH:
680 free_per_thread_data();
686 /***********************************************************************
689 * Converts socket flags from Windows format.
690 * Return 1 if converted, 0 if not (error).
692 static int convert_sockopt(INT *level, INT *optname)
699 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
700 if( ws_sock_map[i][0] == *optname )
702 *optname = ws_sock_map[i][1];
706 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
709 *level = IPPROTO_TCP;
710 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
711 if ( ws_tcp_map[i][0] == *optname )
713 *optname = ws_tcp_map[i][1];
717 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
721 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
722 if (ws_ip_map[i][0] == *optname )
724 *optname = ws_ip_map[i][1];
728 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
730 default: FIXME("Unimplemented or unknown socket level\n");
735 /* ----------------------------------- Per-thread info (or per-process?) */
737 static char *strdup_lower(const char *str)
740 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
744 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
747 else SetLastError(WSAENOBUFS);
751 static inline int sock_error_p(int s)
753 unsigned int optval, optlen;
755 optlen = sizeof(optval);
756 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
757 if (optval) WARN("\t[%i] error: %d\n", s, optval);
761 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
762 * from an fd and return the value converted to milli seconds
763 * or -1 if there is an infinite time out */
764 static inline int get_rcvsnd_timeo( int fd, int optname)
767 unsigned int len = sizeof(tv);
768 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
770 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
771 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
776 /* macro wrappers for portability */
778 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
780 #define GET_RCVTIMEO(fd) (-1)
784 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
786 #define GET_SNDTIMEO(fd) (-1)
789 /* utility: given an fd, will block until one of the events occurs */
790 static inline int do_block( int fd, int events, int timeout )
798 while ((ret = poll(&pfd, 1, timeout)) < 0)
809 convert_af_w2u(int windowsaf) {
812 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
813 if (ws_af_map[i][0] == windowsaf)
814 return ws_af_map[i][1];
815 FIXME("unhandled Windows address family %d\n", windowsaf);
820 convert_af_u2w(int unixaf) {
823 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
824 if (ws_af_map[i][1] == unixaf)
825 return ws_af_map[i][0];
826 FIXME("unhandled UNIX address family %d\n", unixaf);
831 convert_proto_w2u(int windowsproto) {
834 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
835 if (ws_proto_map[i][0] == windowsproto)
836 return ws_proto_map[i][1];
837 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
842 convert_proto_u2w(int unixproto) {
845 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
846 if (ws_proto_map[i][1] == unixproto)
847 return ws_proto_map[i][0];
848 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
853 convert_socktype_w2u(int windowssocktype) {
856 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
857 if (ws_socktype_map[i][0] == windowssocktype)
858 return ws_socktype_map[i][1];
859 FIXME("unhandled Windows socket type %d\n", windowssocktype);
864 convert_socktype_u2w(int unixsocktype) {
867 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
868 if (ws_socktype_map[i][1] == unixsocktype)
869 return ws_socktype_map[i][0];
870 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
874 /* ----------------------------------- API -----
876 * Init / cleanup / error checking.
879 /***********************************************************************
880 * WSAStartup (WS2_32.115)
882 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
884 TRACE("verReq=%x\n", wVersionRequested);
886 if (LOBYTE(wVersionRequested) < 1)
887 return WSAVERNOTSUPPORTED;
889 if (!lpWSAData) return WSAEINVAL;
893 /* that's the whole of the negotiation for now */
894 lpWSAData->wVersion = wVersionRequested;
895 /* return winsock information */
896 lpWSAData->wHighVersion = 0x0202;
897 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
898 strcpy(lpWSAData->szSystemStatus, "Running" );
899 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
900 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
901 /* don't do anything with lpWSAData->lpVendorInfo */
902 /* (some apps don't allocate the space for this field) */
904 TRACE("succeeded\n");
909 /***********************************************************************
910 * WSACleanup (WS2_32.116)
912 INT WINAPI WSACleanup(void)
918 SetLastError(WSANOTINITIALISED);
923 /***********************************************************************
924 * WSAGetLastError (WS2_32.111)
926 INT WINAPI WSAGetLastError(void)
928 return GetLastError();
931 /***********************************************************************
932 * WSASetLastError (WS2_32.112)
934 void WINAPI WSASetLastError(INT iError) {
935 SetLastError(iError);
938 static struct WS_hostent *check_buffer_he(int size)
940 struct per_thread_data * ptb = get_per_thread_data();
943 if (ptb->he_len >= size ) return ptb->he_buffer;
944 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
946 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
947 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
948 return ptb->he_buffer;
951 static struct WS_servent *check_buffer_se(int size)
953 struct per_thread_data * ptb = get_per_thread_data();
956 if (ptb->se_len >= size ) return ptb->se_buffer;
957 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
959 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
960 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
961 return ptb->se_buffer;
964 static struct WS_protoent *check_buffer_pe(int size)
966 struct per_thread_data * ptb = get_per_thread_data();
969 if (ptb->pe_len >= size ) return ptb->pe_buffer;
970 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
972 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
973 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
974 return ptb->pe_buffer;
977 /* ----------------------------------- i/o APIs */
979 static inline BOOL supported_pf(int pf)
1000 /**********************************************************************/
1002 /* Returns the length of the converted address if successful, 0 if it was too small to
1005 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1006 union generic_unix_sockaddr *uaddr)
1008 unsigned int uaddrlen = 0;
1010 switch (wsaddr->sa_family)
1015 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1016 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1018 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1021 uaddrlen = sizeof(struct sockaddr_ipx);
1022 memset( uaddr, 0, uaddrlen );
1023 uipx->sipx_family=AF_IPX;
1024 uipx->sipx_port=wsipx->sa_socket;
1025 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1028 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1029 #ifdef IPX_FRAME_NONE
1030 uipx->sipx_type=IPX_FRAME_NONE;
1036 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1037 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1039 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1040 * scope_id, one without.
1042 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1043 uaddrlen = sizeof(struct sockaddr_in6);
1044 memset( uaddr, 0, uaddrlen );
1045 uin6->sin6_family = AF_INET6;
1046 uin6->sin6_port = win6->sin6_port;
1047 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1048 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1049 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1051 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1054 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1058 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1059 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1061 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1063 uaddrlen = sizeof(struct sockaddr_in);
1064 memset( uaddr, 0, uaddrlen );
1065 uin->sin_family = AF_INET;
1066 uin->sin_port = win->sin_port;
1067 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1072 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1073 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1075 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1077 uaddrlen = sizeof(struct sockaddr_irda);
1078 memset( uaddr, 0, uaddrlen );
1079 uin->sir_family = AF_IRDA;
1080 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1082 unsigned int lsap_sel;
1084 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1085 uin->sir_lsap_sel = lsap_sel;
1089 uin->sir_lsap_sel = LSAP_ANY;
1090 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1092 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1096 case WS_AF_UNSPEC: {
1097 /* Try to determine the needed space by the passed windows sockaddr space */
1098 switch (wsaddrlen) {
1099 default: /* likely a ipv4 address */
1100 case sizeof(struct WS_sockaddr_in):
1101 uaddrlen = sizeof(struct sockaddr_in);
1104 case sizeof(struct WS_sockaddr_ipx):
1105 uaddrlen = sizeof(struct sockaddr_ipx);
1109 case sizeof(SOCKADDR_IRDA):
1110 uaddrlen = sizeof(struct sockaddr_irda);
1113 case sizeof(struct WS_sockaddr_in6):
1114 case sizeof(struct WS_sockaddr_in6_old):
1115 uaddrlen = sizeof(struct sockaddr_in6);
1118 memset( uaddr, 0, uaddrlen );
1122 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1128 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1130 switch (uaddr->sa_family)
1134 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
1139 static const struct sockaddr_in6 emptyAddr;
1140 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1141 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1145 static const struct sockaddr_in emptyAddr;
1146 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1147 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1152 FIXME("unknown address family %d\n", uaddr->sa_family);
1157 /* Returns 0 if successful, -1 if the buffer is too small */
1158 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1162 switch(uaddr->sa_family)
1167 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1168 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1171 switch (*wsaddrlen) /* how much can we copy? */
1175 *wsaddrlen = sizeof(*wsipx);
1176 wsipx->sa_socket=uipx->sipx_port;
1180 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1188 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1194 wsipx->sa_family=WS_AF_IPX;
1206 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1207 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1209 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1211 win->irdaAddressFamily = WS_AF_IRDA;
1212 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1213 if (uin->sir_lsap_sel != LSAP_ANY)
1214 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1216 memcpy( win->irdaServiceName, uin->sir_name,
1217 sizeof(win->irdaServiceName) );
1222 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1223 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1225 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1227 win6old->sin6_family = WS_AF_INET6;
1228 win6old->sin6_port = uin6->sin6_port;
1229 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1230 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1231 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1232 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1233 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1234 win6->sin6_scope_id = uin6->sin6_scope_id;
1235 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1238 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1240 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1245 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1246 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1248 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1250 win->sin_family = WS_AF_INET;
1251 win->sin_port = uin->sin_port;
1252 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1253 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1254 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1258 memset(wsaddr,0,*wsaddrlen);
1262 FIXME("Unknown address family %d\n", uaddr->sa_family);
1268 /**************************************************************************
1269 * Functions for handling overlapped I/O
1270 **************************************************************************/
1272 /* user APC called upon async completion */
1273 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1275 ws2_async *wsa = arg;
1277 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1278 iosb->Information, wsa->user_overlapped,
1280 HeapFree( GetProcessHeap(), 0, wsa );
1283 /***********************************************************************
1284 * WS2_recv (INTERNAL)
1286 * Workhorse for both synchronous and asynchronous recv() operations.
1288 static int WS2_recv( int fd, struct ws2_async *wsa )
1291 union generic_unix_sockaddr unix_sockaddr;
1294 hdr.msg_name = NULL;
1298 hdr.msg_namelen = sizeof(unix_sockaddr);
1299 hdr.msg_name = &unix_sockaddr;
1302 hdr.msg_namelen = 0;
1304 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1305 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1306 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1307 hdr.msg_accrights = NULL;
1308 hdr.msg_accrightslen = 0;
1310 hdr.msg_control = NULL;
1311 hdr.msg_controllen = 0;
1315 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1318 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1319 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1321 * quoting linux 2.6 net/ipv4/tcp.c:
1322 * "According to UNIX98, msg_name/msg_namelen are ignored
1323 * on connected socket. I was just happy when found this 8) --ANK"
1325 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1326 * connection-oriented sockets, so don't try to update lpFrom.
1328 if (wsa->addr && hdr.msg_namelen)
1329 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1334 /***********************************************************************
1335 * WS2_async_recv (INTERNAL)
1337 * Handler for overlapped recv() operations.
1339 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1341 ws2_async* wsa = user;
1346 case STATUS_ALERTED:
1347 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1350 result = WS2_recv( fd, wsa );
1351 wine_server_release_fd( wsa->hSocket, fd );
1354 status = STATUS_SUCCESS;
1355 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1359 if (errno == EINTR || errno == EAGAIN)
1361 status = STATUS_PENDING;
1362 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1367 status = wsaErrno(); /* FIXME: is this correct ???? */
1372 if (status != STATUS_PENDING)
1374 iosb->u.Status = status;
1375 iosb->Information = result;
1376 *apc = ws2_async_apc;
1381 /***********************************************************************
1382 * WS2_send (INTERNAL)
1384 * Workhorse for both synchronous and asynchronous send() operations.
1386 static int WS2_send( int fd, struct ws2_async *wsa )
1389 union generic_unix_sockaddr unix_addr;
1391 hdr.msg_name = NULL;
1392 hdr.msg_namelen = 0;
1396 hdr.msg_name = &unix_addr;
1397 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
1398 if ( !hdr.msg_namelen )
1404 #if defined(HAVE_IPX) && defined(SOL_IPX)
1405 if(wsa->addr->sa_family == WS_AF_IPX)
1407 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1409 unsigned int len=sizeof(int);
1411 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1412 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1413 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1414 * ipx type in the sockaddr_opx structure with the stored value.
1416 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1417 uipx->sipx_type = val;
1422 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1423 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1424 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1425 hdr.msg_accrights = NULL;
1426 hdr.msg_accrightslen = 0;
1428 hdr.msg_control = NULL;
1429 hdr.msg_controllen = 0;
1433 return sendmsg(fd, &hdr, wsa->flags);
1436 /***********************************************************************
1437 * WS2_async_send (INTERNAL)
1439 * Handler for overlapped send() operations.
1441 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1443 ws2_async* wsa = user;
1448 case STATUS_ALERTED:
1449 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1452 /* check to see if the data is ready (non-blocking) */
1453 result = WS2_send( fd, wsa );
1454 wine_server_release_fd( wsa->hSocket, fd );
1458 int totalLength = 0;
1460 status = STATUS_SUCCESS;
1461 for (i = 0; i < wsa->n_iovecs; i++)
1462 totalLength += wsa->iovec[i].iov_len;
1463 if (result < totalLength)
1464 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1468 if (errno == EINTR || errno == EAGAIN)
1470 status = STATUS_PENDING;
1471 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1475 /* We set the status to a winsock error code and check for that
1476 later in NtStatusToWSAError () */
1477 status = wsaErrno();
1483 if (status != STATUS_PENDING)
1485 iosb->u.Status = status;
1486 iosb->Information = result;
1487 *apc = ws2_async_apc;
1492 /***********************************************************************
1493 * WS2_async_shutdown (INTERNAL)
1495 * Handler for shutdown() operations on overlapped sockets.
1497 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
1499 ws2_async* wsa = user;
1504 case STATUS_ALERTED:
1505 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1508 switch ( wsa->type )
1510 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1511 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1513 wine_server_release_fd( wsa->hSocket, fd );
1514 status = err ? wsaErrno() : STATUS_SUCCESS;
1517 iosb->u.Status = status;
1518 iosb->Information = 0;
1519 *apc = ws2_async_apc;
1523 /***********************************************************************
1524 * WS2_register_async_shutdown (INTERNAL)
1526 * Helper function for WS_shutdown() on overlapped sockets.
1528 static int WS2_register_async_shutdown( SOCKET s, int type )
1530 struct ws2_async *wsa;
1533 TRACE("s %ld type %d\n", s, type);
1535 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1539 wsa->hSocket = SOCKET2HANDLE(s);
1541 wsa->completion_func = NULL;
1543 SERVER_START_REQ( register_async )
1546 req->async.handle = wine_server_obj_handle( wsa->hSocket );
1547 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
1548 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
1549 req->async.arg = wine_server_client_ptr( wsa );
1550 req->async.cvalue = 0;
1551 status = wine_server_call( req );
1555 if (status != STATUS_PENDING)
1557 HeapFree( GetProcessHeap(), 0, wsa );
1558 return NtStatusToWSAError( status );
1563 /***********************************************************************
1566 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1573 TRACE("socket %04lx\n", s );
1574 is_blocking = _is_blocking(s);
1577 /* try accepting first (if there is a deferred connection) */
1578 SERVER_START_REQ( accept_socket )
1580 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1581 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1582 req->attributes = OBJ_INHERIT;
1583 status = wine_server_call( req );
1584 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
1589 if (addr) WS_getpeername(as, addr, addrlen32);
1592 if (is_blocking && status == WSAEWOULDBLOCK)
1594 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1596 do_block(fd, POLLIN, -1);
1597 _sync_sock_state(s); /* let wineserver notice connection */
1598 release_sock_fd( s, fd );
1600 } while (is_blocking && status == WSAEWOULDBLOCK);
1603 return INVALID_SOCKET;
1606 /***********************************************************************
1609 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1611 int fd = get_sock_fd( s, 0, NULL );
1612 int res = SOCKET_ERROR;
1614 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1618 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
1620 SetLastError(WSAEAFNOSUPPORT);
1624 union generic_unix_sockaddr uaddr;
1625 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1628 SetLastError(WSAEFAULT);
1633 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
1634 if (name->sa_family == WS_AF_INET6 &&
1635 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
1638 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
1640 release_sock_fd( s, fd );
1641 SetLastError(WSAEAFNOSUPPORT);
1642 return SOCKET_ERROR;
1646 if (name->sa_family == WS_AF_INET)
1648 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1649 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1651 /* Trying to bind to the default host interface, using
1652 * INADDR_ANY instead*/
1653 WARN("Trying to bind to magic IP address, using "
1654 "INADDR_ANY instead.\n");
1655 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
1658 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
1660 int loc_errno = errno;
1661 WARN("\tfailure - errno = %i\n", errno);
1666 SetLastError(WSAENOTSOCK);
1669 SetLastError(WSAEINVAL);
1672 SetLastError(wsaErrno());
1678 res=0; /* success */
1682 release_sock_fd( s, fd );
1687 /***********************************************************************
1688 * closesocket (WS2_32.3)
1690 int WINAPI WS_closesocket(SOCKET s)
1692 TRACE("socket %04lx\n", s);
1693 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
1694 return SOCKET_ERROR;
1697 /***********************************************************************
1698 * connect (WS2_32.4)
1700 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1702 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1704 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1708 union generic_unix_sockaddr uaddr;
1709 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1713 SetLastError(WSAEFAULT);
1717 if (name->sa_family == WS_AF_INET)
1719 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1720 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1722 /* Trying to connect to magic replace-loopback address,
1723 * assuming we really want to connect to localhost */
1724 TRACE("Trying to connect to magic IP address, using "
1725 "INADDR_LOOPBACK instead.\n");
1726 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
1730 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
1731 goto connect_success;
1734 if (errno == EINPROGRESS)
1736 /* tell wineserver that a connection is in progress */
1737 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1738 FD_CONNECT|FD_READ|FD_WRITE,
1739 FD_WINE_CONNECTED|FD_WINE_LISTENING);
1740 if (_is_blocking(s))
1744 do_block(fd, POLLIN | POLLOUT, -1);
1745 _sync_sock_state(s); /* let wineserver notice connection */
1746 /* retrieve any error codes from it */
1747 result = _get_sock_error(s, FD_CONNECT_BIT);
1749 SetLastError(result);
1752 goto connect_success;
1757 SetLastError(WSAEWOULDBLOCK);
1762 SetLastError(wsaErrno());
1764 release_sock_fd( s, fd );
1766 return SOCKET_ERROR;
1769 release_sock_fd( s, fd );
1770 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1771 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1772 FD_CONNECT|FD_WINE_LISTENING);
1776 /***********************************************************************
1777 * WSAConnect (WS2_32.30)
1779 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
1780 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1781 LPQOS lpSQOS, LPQOS lpGQOS )
1783 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1784 FIXME("unsupported parameters!\n");
1785 return WS_connect( s, name, namelen );
1789 /***********************************************************************
1790 * getpeername (WS2_32.5)
1792 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1797 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, *namelen);
1799 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1800 if( (name == NULL) || (namelen == NULL) )
1802 SetLastError( WSAEFAULT );
1803 return SOCKET_ERROR;
1806 fd = get_sock_fd( s, 0, NULL );
1811 union generic_unix_sockaddr uaddr;
1812 unsigned int uaddrlen = sizeof(uaddr);
1814 if (getpeername(fd, &uaddr.addr, &uaddrlen) != 0)
1816 SetLastError(wsaErrno());
1818 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1820 /* The buffer was too small */
1821 SetLastError(WSAEFAULT);
1827 release_sock_fd( s, fd );
1832 /***********************************************************************
1833 * getsockname (WS2_32.6)
1835 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1840 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
1842 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1843 if( (name == NULL) || (namelen == NULL) )
1845 SetLastError( WSAEFAULT );
1846 return SOCKET_ERROR;
1849 fd = get_sock_fd( s, 0, NULL );
1854 union generic_unix_sockaddr uaddr;
1855 unsigned int uaddrlen = sizeof(uaddr);
1857 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
1859 SetLastError(wsaErrno());
1861 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
1863 SetLastError(WSAEINVAL);
1865 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1867 /* The buffer was too small */
1868 SetLastError(WSAEFAULT);
1874 release_sock_fd( s, fd );
1879 /***********************************************************************
1880 * getsockopt (WS2_32.7)
1882 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1883 INT optname, char *optval, INT *optlen)
1888 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
1889 s, level, optname, optval, *optlen);
1897 /* Handle common cases. The special cases are below, sorted
1899 case WS_SO_ACCEPTCONN:
1900 case WS_SO_BROADCAST:
1903 case WS_SO_KEEPALIVE:
1904 case WS_SO_OOBINLINE:
1906 case WS_SO_REUSEADDR:
1909 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1910 return SOCKET_ERROR;
1911 convert_sockopt(&level, &optname);
1912 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1914 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1917 release_sock_fd( s, fd );
1920 case WS_SO_DONTLINGER:
1922 struct linger lingval;
1923 unsigned int len = sizeof(struct linger);
1925 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
1927 SetLastError(WSAEFAULT);
1928 return SOCKET_ERROR;
1930 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1931 return SOCKET_ERROR;
1933 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1935 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1940 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
1941 *optlen = sizeof(BOOL);
1944 release_sock_fd( s, fd );
1948 /* As mentioned in setsockopt, Windows ignores this, so we
1949 * always return true here */
1950 case WS_SO_DONTROUTE:
1951 if (!optlen || *optlen < sizeof(BOOL) || !optval)
1953 SetLastError(WSAEFAULT);
1954 return SOCKET_ERROR;
1956 *(BOOL *)optval = TRUE;
1957 *optlen = sizeof(BOOL);
1962 struct linger lingval;
1963 unsigned int len = sizeof(struct linger);
1965 /* struct linger and LINGER have different sizes */
1966 if (!optlen || *optlen < sizeof(LINGER) || !optval)
1968 SetLastError(WSAEFAULT);
1969 return SOCKET_ERROR;
1971 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1972 return SOCKET_ERROR;
1974 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1976 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1981 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
1982 ((LINGER *)optval)->l_linger = lingval.l_linger;
1983 *optlen = sizeof(struct linger);
1986 release_sock_fd( s, fd );
1990 case WS_SO_MAX_MSG_SIZE:
1991 if (!optlen || *optlen < sizeof(int) || !optval)
1993 SetLastError(WSAEFAULT);
1994 return SOCKET_ERROR;
1996 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
1997 *(int *)optval = 65507;
1998 *optlen = sizeof(int);
2001 /* SO_OPENTYPE does not require a valid socket handle. */
2002 case WS_SO_OPENTYPE:
2003 if (!optlen || *optlen < sizeof(int) || !optval)
2005 SetLastError(WSAEFAULT);
2006 return SOCKET_ERROR;
2008 *(int *)optval = get_per_thread_data()->opentype;
2009 *optlen = sizeof(int);
2010 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2014 case WS_SO_RCVTIMEO:
2017 case WS_SO_SNDTIMEO:
2019 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
2022 unsigned int len = sizeof(struct timeval);
2024 if (!optlen || *optlen < sizeof(int)|| !optval)
2026 SetLastError(WSAEFAULT);
2027 return SOCKET_ERROR;
2029 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2030 return SOCKET_ERROR;
2032 convert_sockopt(&level, &optname);
2033 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
2035 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2040 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
2041 *optlen = sizeof(int);
2044 release_sock_fd( s, fd );
2049 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
2050 SetLastError(WSAENOPROTOOPT);
2051 return SOCKET_ERROR;
2052 } /* end switch(optname) */
2053 }/* end case WS_SOL_SOCKET */
2057 struct WS_sockaddr_ipx addr;
2058 IPX_ADDRESS_DATA *data;
2063 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
2065 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
2072 socklen_t len=sizeof(struct ipx);
2073 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
2076 *optval = (int)val.ipx_pt;
2079 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
2080 release_sock_fd( s, fd );
2085 * On a Win2000 system with one network card there are usually
2086 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
2087 * Using this call you can then retrieve info about this all.
2088 * In case of Linux it is a bit different. Usually you have
2089 * only "one" device active and further it is not possible to
2090 * query things like the linkspeed.
2092 FIXME("IPX_ADDRESS\n");
2093 namelen = sizeof(struct WS_sockaddr_ipx);
2094 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
2095 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
2097 data = (IPX_ADDRESS_DATA*)optval;
2098 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
2099 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
2100 data->adapternum = 0;
2101 data->wan = FALSE; /* We are not on a wan for now .. */
2102 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
2103 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
2104 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
2105 * note 1MB = 1000kB in this case */
2108 case IPX_MAX_ADAPTER_NUM:
2109 FIXME("IPX_MAX_ADAPTER_NUM\n");
2110 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
2114 FIXME("IPX optname:%x\n", optname);
2115 return SOCKET_ERROR;
2116 }/* end switch(optname) */
2117 } /* end case NSPROTO_IPX */
2124 case WS_IRLMP_ENUMDEVICES:
2126 static const int MAX_IRDA_DEVICES = 10;
2127 char buf[sizeof(struct irda_device_list) +
2128 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
2130 socklen_t len = sizeof(buf);
2132 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2133 return SOCKET_ERROR;
2134 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
2137 SetLastError(wsaErrno());
2138 return SOCKET_ERROR;
2142 struct irda_device_list *src = (struct irda_device_list *)buf;
2143 DEVICELIST *dst = (DEVICELIST *)optval;
2144 INT needed = sizeof(DEVICELIST), i;
2147 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
2148 if (*optlen < needed)
2150 SetLastError(WSAEFAULT);
2151 return SOCKET_ERROR;
2154 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
2155 dst->numDevice = src->len;
2156 for (i = 0; i < src->len; i++)
2158 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
2159 src->dev[i].saddr, src->dev[i].daddr,
2160 src->dev[i].info, src->dev[i].hints[0],
2161 src->dev[i].hints[1]);
2162 memcpy( dst->Device[i].irdaDeviceID,
2164 sizeof(dst->Device[i].irdaDeviceID) ) ;
2165 memcpy( dst->Device[i].irdaDeviceName,
2167 sizeof(dst->Device[i].irdaDeviceName) ) ;
2168 memcpy( &dst->Device[i].irdaDeviceHints1,
2169 &src->dev[i].hints[0],
2170 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
2171 memcpy( &dst->Device[i].irdaDeviceHints2,
2172 &src->dev[i].hints[1],
2173 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
2174 dst->Device[i].irdaCharSet = src->dev[i].charset;
2180 FIXME("IrDA optname:0x%x\n", optname);
2181 return SOCKET_ERROR;
2183 break; /* case WS_SOL_IRLMP */
2186 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
2187 case WS_IPPROTO_TCP:
2190 case WS_TCP_NODELAY:
2191 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2192 return SOCKET_ERROR;
2193 convert_sockopt(&level, &optname);
2194 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2196 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2199 release_sock_fd( s, fd );
2202 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
2203 return SOCKET_ERROR;
2208 case WS_IP_ADD_MEMBERSHIP:
2209 case WS_IP_DROP_MEMBERSHIP:
2213 case WS_IP_MULTICAST_IF:
2214 case WS_IP_MULTICAST_LOOP:
2215 case WS_IP_MULTICAST_TTL:
2219 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2220 return SOCKET_ERROR;
2221 convert_sockopt(&level, &optname);
2222 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2224 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2227 release_sock_fd( s, fd );
2229 case WS_IP_DONTFRAGMENT:
2230 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
2231 *(BOOL*)optval = FALSE;
2234 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
2235 return SOCKET_ERROR;
2237 case WS_IPPROTO_IPV6:
2238 FIXME("IPPROTO_IPV6 unimplemented (optname 0x%08x)\n", optname);
2239 return SOCKET_ERROR;
2242 WARN("Unknown level: 0x%08x\n", level);
2243 SetLastError(WSAEINVAL);
2244 return SOCKET_ERROR;
2245 } /* end switch(level) */
2248 /***********************************************************************
2251 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
2253 return htonl(hostlong);
2257 /***********************************************************************
2260 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
2262 return htons(hostshort);
2265 /***********************************************************************
2266 * WSAHtonl (WS2_32.46)
2267 * From MSDN description of error codes, this function should also
2268 * check if WinSock has been initialized and the socket is a valid
2269 * socket. But why? This function only translates a host byte order
2270 * u_long into a network byte order u_long...
2272 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
2276 *lpnetlong = htonl(hostlong);
2279 WSASetLastError(WSAEFAULT);
2280 return SOCKET_ERROR;
2283 /***********************************************************************
2284 * WSAHtons (WS2_32.47)
2285 * From MSDN description of error codes, this function should also
2286 * check if WinSock has been initialized and the socket is a valid
2287 * socket. But why? This function only translates a host byte order
2288 * u_short into a network byte order u_short...
2290 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2295 *lpnetshort = htons(hostshort);
2298 WSASetLastError(WSAEFAULT);
2299 return SOCKET_ERROR;
2303 /***********************************************************************
2304 * inet_addr (WS2_32.11)
2306 WS_u_long WINAPI WS_inet_addr(const char *cp)
2308 if (!cp) return INADDR_NONE;
2309 return inet_addr(cp);
2313 /***********************************************************************
2316 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2318 return ntohl(netlong);
2322 /***********************************************************************
2325 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2327 return ntohs(netshort);
2331 /***********************************************************************
2332 * inet_ntoa (WS2_32.12)
2334 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2336 /* use "buffer for dummies" here because some applications have a
2337 * propensity to decode addresses in ws_hostent structure without
2338 * saving them first...
2340 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2342 char* s = inet_ntoa(*((struct in_addr*)&in));
2348 SetLastError(wsaErrno());
2352 /**********************************************************************
2353 * WSAIoctl (WS2_32.50)
2356 INT WINAPI WSAIoctl(SOCKET s,
2357 DWORD dwIoControlCode,
2360 LPVOID lpbOutBuffer,
2362 LPDWORD lpcbBytesReturned,
2363 LPWSAOVERLAPPED lpOverlapped,
2364 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2366 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
2367 s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpbOutBuffer,
2368 cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
2370 switch( dwIoControlCode )
2373 if (cbInBuffer != sizeof(WS_u_long)) {
2374 WSASetLastError(WSAEFAULT);
2375 return SOCKET_ERROR;
2377 return WS_ioctlsocket( s, WS_FIONBIO, lpvInBuffer);
2380 if (cbOutBuffer != sizeof(WS_u_long)) {
2381 WSASetLastError(WSAEFAULT);
2382 return SOCKET_ERROR;
2384 return WS_ioctlsocket( s, WS_FIONREAD, lpbOutBuffer);
2386 case WS_SIO_GET_INTERFACE_LIST:
2388 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
2389 DWORD size, numInt, apiReturn;
2392 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
2396 WSASetLastError(WSAEFAULT);
2397 return SOCKET_ERROR;
2399 if (!lpcbBytesReturned)
2401 WSASetLastError(WSAEFAULT);
2402 return SOCKET_ERROR;
2405 fd = get_sock_fd( s, 0, NULL );
2406 if (fd == -1) return SOCKET_ERROR;
2408 apiReturn = GetAdaptersInfo(NULL, &size);
2409 if (apiReturn == ERROR_NO_DATA)
2413 else if (apiReturn == ERROR_BUFFER_OVERFLOW)
2415 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
2419 if (GetAdaptersInfo(table, &size) == NO_ERROR)
2421 PIP_ADAPTER_INFO ptr;
2423 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > cbOutBuffer)
2425 WARN("Buffer too small = %u, cbOutBuffer = %u\n", size, cbOutBuffer);
2426 HeapFree(GetProcessHeap(),0,table);
2427 release_sock_fd( s, fd );
2428 WSASetLastError(WSAEFAULT);
2429 return SOCKET_ERROR;
2431 for (ptr = table, numInt = 0; ptr;
2432 ptr = ptr->Next, intArray++, numInt++)
2434 unsigned int addr, mask, bcast;
2435 struct ifreq ifInfo;
2437 /* Socket Status Flags */
2438 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
2439 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2441 ERR("Error obtaining status flags for socket!\n");
2442 HeapFree(GetProcessHeap(),0,table);
2443 release_sock_fd( s, fd );
2444 WSASetLastError(WSAEINVAL);
2445 return SOCKET_ERROR;
2449 /* set flags; the values of IFF_* are not the same
2450 under Linux and Windows, therefore must generate
2452 intArray->iiFlags = 0;
2453 if (ifInfo.ifr_flags & IFF_BROADCAST)
2454 intArray->iiFlags |= WS_IFF_BROADCAST;
2455 #ifdef IFF_POINTOPOINT
2456 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
2457 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
2459 if (ifInfo.ifr_flags & IFF_LOOPBACK)
2460 intArray->iiFlags |= WS_IFF_LOOPBACK;
2461 if (ifInfo.ifr_flags & IFF_UP)
2462 intArray->iiFlags |= WS_IFF_UP;
2463 if (ifInfo.ifr_flags & IFF_MULTICAST)
2464 intArray->iiFlags |= WS_IFF_MULTICAST;
2467 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
2468 mask = inet_addr(ptr->IpAddressList.IpMask.String);
2469 bcast = addr | ~mask;
2470 intArray->iiAddress.AddressIn.sin_family = AF_INET;
2471 intArray->iiAddress.AddressIn.sin_port = 0;
2472 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
2474 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2475 intArray->iiNetmask.AddressIn.sin_port = 0;
2476 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
2478 intArray->iiBroadcastAddress.AddressIn.sin_family =
2480 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
2481 intArray->iiBroadcastAddress.AddressIn.sin_addr.
2487 ERR("Unable to get interface table!\n");
2488 release_sock_fd( s, fd );
2489 HeapFree(GetProcessHeap(),0,table);
2490 WSASetLastError(WSAEINVAL);
2491 return SOCKET_ERROR;
2493 HeapFree(GetProcessHeap(),0,table);
2497 release_sock_fd( s, fd );
2498 WSASetLastError(WSAEINVAL);
2499 return SOCKET_ERROR;
2504 ERR("Unable to get interface table!\n");
2505 release_sock_fd( s, fd );
2506 WSASetLastError(WSAEINVAL);
2507 return SOCKET_ERROR;
2509 /* Calculate the size of the array being returned */
2510 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2511 release_sock_fd( s, fd );
2515 case WS_SIO_ADDRESS_LIST_CHANGE:
2516 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
2517 /* FIXME: error and return code depend on whether socket was created
2518 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
2521 case WS_SIO_ADDRESS_LIST_QUERY:
2525 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
2527 if (!lpcbBytesReturned)
2529 WSASetLastError(WSAEFAULT);
2530 return SOCKET_ERROR;
2533 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
2535 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
2538 if (!table || GetAdaptersInfo(table, &size))
2540 HeapFree(GetProcessHeap(), 0, table);
2541 WSASetLastError(WSAEINVAL);
2542 return SOCKET_ERROR;
2545 for (p = table, num = 0; p; p = p->Next)
2546 if (p->IpAddressList.IpAddress.String[0]) num++;
2548 need = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
2549 need += sizeof(SOCKADDR) * num;
2550 *lpcbBytesReturned = need;
2552 if (need > cbOutBuffer)
2554 HeapFree(GetProcessHeap(), 0, table);
2555 WSASetLastError(WSAEFAULT);
2556 return SOCKET_ERROR;
2563 SOCKET_ADDRESS_LIST *sa_list = (SOCKET_ADDRESS_LIST *)lpbOutBuffer;
2564 SOCKADDR_IN *sockaddr;
2566 sa = sa_list->Address;
2567 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
2568 sa_list->iAddressCount = num;
2570 for (p = table, i = 0; p; p = p->Next)
2572 if (!p->IpAddressList.IpAddress.String[0]) continue;
2574 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
2575 sa[i].iSockaddrLength = sizeof(SOCKADDR);
2577 sockaddr[i].sin_family = AF_INET;
2578 sockaddr[i].sin_port = 0;
2579 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
2584 HeapFree(GetProcessHeap(), 0, table);
2589 WARN("unable to get IP address list\n");
2590 WSASetLastError(WSAEINVAL);
2591 return SOCKET_ERROR;
2595 FIXME("SIO_FLUSH: stub.\n");
2598 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
2599 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(lpvInBuffer));
2600 WSASetLastError(WSAEOPNOTSUPP);
2601 return SOCKET_ERROR;
2603 case WS_SIO_KEEPALIVE_VALS:
2606 struct tcp_keepalive *k = lpvInBuffer;
2607 int keepalive = k->onoff ? 1 : 0;
2608 int keepidle = k->keepalivetime / 1000;
2609 int keepintvl = k->keepaliveinterval / 1000;
2613 WSASetLastError(WSAEINVAL);
2614 return SOCKET_ERROR;
2617 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
2619 fd = get_sock_fd(s, 0, NULL);
2620 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
2622 release_sock_fd(s, fd);
2623 WSASetLastError(WSAEINVAL);
2624 return SOCKET_ERROR;
2626 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
2627 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
2629 release_sock_fd(s, fd);
2630 WSASetLastError(WSAEINVAL);
2631 return SOCKET_ERROR;
2633 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
2635 release_sock_fd(s, fd);
2636 WSASetLastError(WSAEINVAL);
2637 return SOCKET_ERROR;
2640 FIXME("ignoring keepalive interval and timeout\n");
2643 release_sock_fd(s, fd);
2647 FIXME("unsupported WS_IOCTL cmd (%08x)\n", dwIoControlCode);
2648 WSASetLastError(WSAEOPNOTSUPP);
2649 return SOCKET_ERROR;
2656 /***********************************************************************
2657 * ioctlsocket (WS2_32.10)
2659 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
2664 TRACE("socket %04lx, cmd %08x, ptr %p\n", s, cmd, argp);
2665 /* broken apps like defcon pass the argp value directly instead of a pointer to it */
2666 if(IS_INTRESOURCE(argp))
2668 SetLastError(WSAEFAULT);
2669 return SOCKET_ERROR;
2679 if( _get_sock_mask(s) )
2681 /* AsyncSelect()'ed sockets are always nonblocking */
2682 if (*argp) return 0;
2683 SetLastError(WSAEINVAL);
2684 return SOCKET_ERROR;
2687 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
2689 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
2697 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2698 SetLastError(WSAEINVAL);
2699 return SOCKET_ERROR;
2701 case SIOCGIFBRDADDR:
2702 case SIOCGIFNETMASK:
2704 /* These don't need any special handling. They are used by
2705 WsControl, and are here to suppress an unnecessary warning. */
2709 /* Netscape tries hard to use bogus ioctl 0x667e */
2710 /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
2711 * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
2713 WARN("\tunknown WS_IOCTL cmd (%08x)\n", cmd);
2717 fd = get_sock_fd( s, 0, NULL );
2720 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2722 release_sock_fd( s, fd );
2725 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2726 release_sock_fd( s, fd );
2728 return SOCKET_ERROR;
2731 /***********************************************************************
2732 * listen (WS2_32.13)
2734 int WINAPI WS_listen(SOCKET s, int backlog)
2736 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2738 TRACE("socket %04lx, backlog %d\n", s, backlog);
2741 if (listen(fd, backlog) == 0)
2743 release_sock_fd( s, fd );
2744 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
2746 FD_CONNECT|FD_WINE_CONNECTED);
2749 SetLastError(wsaErrno());
2750 release_sock_fd( s, fd );
2752 return SOCKET_ERROR;
2755 /***********************************************************************
2758 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2760 DWORD n, dwFlags = flags;
2766 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2767 return SOCKET_ERROR;
2772 /***********************************************************************
2773 * recvfrom (WS2_32.17)
2775 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2776 struct WS_sockaddr *from, int *fromlen)
2778 DWORD n, dwFlags = flags;
2784 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2785 return SOCKET_ERROR;
2790 /* allocate a poll array for the corresponding fd sets */
2791 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
2792 const WS_fd_set *exceptfds, int *count_ptr )
2794 unsigned int i, j = 0, count = 0;
2797 if (readfds) count += readfds->fd_count;
2798 if (writefds) count += writefds->fd_count;
2799 if (exceptfds) count += exceptfds->fd_count;
2801 if (!count) return NULL;
2802 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0])))) return NULL;
2804 for (i = 0; i < readfds->fd_count; i++, j++)
2806 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
2807 fds[j].events = POLLIN;
2811 for (i = 0; i < writefds->fd_count; i++, j++)
2813 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
2814 fds[j].events = POLLOUT;
2818 for (i = 0; i < exceptfds->fd_count; i++, j++)
2820 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
2821 fds[j].events = POLLHUP;
2827 /* release the file descriptor obtained in fd_sets_to_poll */
2828 /* must be called with the original fd_set arrays, before calling get_poll_results */
2829 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
2830 const WS_fd_set *exceptfds, struct pollfd *fds )
2832 unsigned int i, j = 0;
2836 for (i = 0; i < readfds->fd_count; i++, j++)
2837 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
2841 for (i = 0; i < writefds->fd_count; i++, j++)
2842 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
2846 for (i = 0; i < exceptfds->fd_count; i++, j++)
2847 if (fds[j].fd != -1)
2849 /* make sure we have a real error before releasing the fd */
2850 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
2851 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
2856 /* map the poll results back into the Windows fd sets */
2857 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
2858 const struct pollfd *fds )
2860 unsigned int i, j = 0, k, total = 0;
2864 for (i = k = 0; i < readfds->fd_count; i++, j++)
2865 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
2866 readfds->fd_count = k;
2871 for (i = k = 0; i < writefds->fd_count; i++, j++)
2872 if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
2873 writefds->fd_count = k;
2878 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
2879 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
2880 exceptfds->fd_count = k;
2887 /***********************************************************************
2888 * select (WS2_32.18)
2890 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
2891 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
2892 const struct WS_timeval* ws_timeout)
2894 struct pollfd *pollfds;
2895 struct timeval tv1, tv2;
2897 int count, ret, timeout = -1;
2899 TRACE("read %p, write %p, excp %p timeout %p\n",
2900 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
2902 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )) && count)
2904 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2905 return SOCKET_ERROR;
2910 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
2912 gettimeofday( &tv1, 0 );
2915 while ((ret = poll( pollfds, count, timeout )) < 0)
2919 if (!ws_timeout) continue;
2920 gettimeofday( &tv2, 0 );
2922 tv2.tv_sec -= tv1.tv_sec;
2923 tv2.tv_usec -= tv1.tv_usec;
2924 if (tv2.tv_usec < 0)
2926 tv2.tv_usec += 1000000;
2930 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
2931 if (timeout <= 0) break;
2934 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2936 if (ret == -1) SetLastError(wsaErrno());
2937 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2938 HeapFree( GetProcessHeap(), 0, pollfds );
2942 /* helper to send completion messages for client-only i/o operation case */
2943 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
2948 SERVER_START_REQ( add_fd_completion )
2950 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
2951 req->cvalue = CompletionValue;
2952 req->status = CompletionStatus;
2953 req->information = Information;
2954 status = wine_server_call( req );
2960 /***********************************************************************
2963 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
2969 wsabuf.buf = (char*) buf;
2971 if ( WSASendTo( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
2972 return SOCKET_ERROR;
2977 /***********************************************************************
2978 * WSASend (WS2_32.72)
2980 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2981 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2982 LPWSAOVERLAPPED lpOverlapped,
2983 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2985 return WSASendTo( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
2986 NULL, 0, lpOverlapped, lpCompletionRoutine );
2989 /***********************************************************************
2990 * WSASendDisconnect (WS2_32.73)
2992 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
2994 return WS_shutdown( s, SD_SEND );
2998 /***********************************************************************
2999 * WSASendTo (WS2_32.74)
3001 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3002 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3003 const struct WS_sockaddr *to, int tolen,
3004 LPWSAOVERLAPPED lpOverlapped,
3005 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3007 unsigned int i, options;
3009 struct ws2_async *wsa;
3010 int totalLength = 0;
3011 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
3013 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
3014 s, lpBuffers, dwBufferCount, dwFlags,
3015 to, tolen, lpOverlapped, lpCompletionRoutine);
3017 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
3018 TRACE( "fd=%d, options=%x\n", fd, options );
3020 if ( fd == -1 ) return SOCKET_ERROR;
3022 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
3028 wsa->hSocket = SOCKET2HANDLE(s);
3029 wsa->addr = (struct WS_sockaddr *)to;
3030 wsa->addrlen.val = tolen;
3031 wsa->flags = dwFlags;
3032 wsa->n_iovecs = dwBufferCount;
3033 wsa->first_iovec = 0;
3034 for ( i = 0; i < dwBufferCount; i++ )
3036 wsa->iovec[i].iov_base = lpBuffers[i].buf;
3037 wsa->iovec[i].iov_len = lpBuffers[i].len;
3038 totalLength += lpBuffers[i].len;
3041 if (!lpNumberOfBytesSent)
3049 n = WS2_send( fd, wsa );
3050 if (n != -1 || errno != EINTR) break;
3052 if (n == -1 && errno != EAGAIN)
3055 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
3059 if ((lpOverlapped || lpCompletionRoutine) &&
3060 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3062 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
3064 wsa->user_overlapped = lpOverlapped;
3065 wsa->completion_func = lpCompletionRoutine;
3066 release_sock_fd( s, fd );
3070 iosb->u.Status = STATUS_PENDING;
3071 iosb->Information = 0;
3073 SERVER_START_REQ( register_async )
3075 req->type = ASYNC_TYPE_WRITE;
3076 req->async.handle = wine_server_obj_handle( wsa->hSocket );
3077 req->async.callback = wine_server_client_ptr( WS2_async_send );
3078 req->async.iosb = wine_server_client_ptr( iosb );
3079 req->async.arg = wine_server_client_ptr( wsa );
3080 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
3081 req->async.cvalue = cvalue;
3082 err = wine_server_call( req );
3086 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
3087 WSASetLastError( NtStatusToWSAError( err ));
3088 return SOCKET_ERROR;
3091 iosb->u.Status = STATUS_SUCCESS;
3092 iosb->Information = n;
3093 *lpNumberOfBytesSent = n;
3094 if (!wsa->completion_func)
3096 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
3097 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
3098 HeapFree( GetProcessHeap(), 0, wsa );
3100 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
3101 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
3106 if ( _is_blocking(s) )
3108 /* On a blocking non-overlapped stream socket,
3109 * sending blocks until the entire buffer is sent. */
3110 DWORD timeout_start = GetTickCount();
3112 *lpNumberOfBytesSent = 0;
3114 while (wsa->first_iovec < dwBufferCount)
3117 int timeout = GET_SNDTIMEO(fd);
3121 *lpNumberOfBytesSent += n;
3122 while (wsa->first_iovec < dwBufferCount && wsa->iovec[wsa->first_iovec].iov_len <= n)
3123 n -= wsa->iovec[wsa->first_iovec++].iov_len;
3124 if (wsa->first_iovec >= dwBufferCount) break;
3125 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
3126 wsa->iovec[wsa->first_iovec].iov_len -= n;
3131 timeout -= GetTickCount() - timeout_start;
3132 if (timeout < 0) timeout = 0;
3136 pfd.events = POLLOUT;
3138 if (!timeout || !poll( &pfd, 1, timeout ))
3141 goto error; /* msdn says a timeout in send is fatal */
3144 n = WS2_send( fd, wsa );
3145 if (n == -1 && errno != EAGAIN && errno != EINTR)
3152 else /* non-blocking */
3154 if (n < totalLength)
3155 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
3158 err = WSAEWOULDBLOCK;
3161 *lpNumberOfBytesSent = n;
3164 TRACE(" -> %i bytes\n", *lpNumberOfBytesSent);
3166 HeapFree( GetProcessHeap(), 0, wsa );
3167 release_sock_fd( s, fd );
3172 HeapFree( GetProcessHeap(), 0, wsa );
3173 release_sock_fd( s, fd );
3174 WARN(" -> ERROR %d\n", err);
3175 WSASetLastError(err);
3176 return SOCKET_ERROR;
3179 /***********************************************************************
3180 * sendto (WS2_32.20)
3182 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
3183 const struct WS_sockaddr *to, int tolen)
3189 wsabuf.buf = (char*) buf;
3191 if ( WSASendTo(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
3192 return SOCKET_ERROR;
3197 /***********************************************************************
3198 * setsockopt (WS2_32.21)
3200 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
3201 const char *optval, int optlen)
3205 struct linger linger;
3206 struct timeval tval;
3208 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
3209 s, level, optname, optval, optlen);
3211 /* some broken apps pass the value directly instead of a pointer to it */
3212 if(IS_INTRESOURCE(optval))
3214 SetLastError(WSAEFAULT);
3215 return SOCKET_ERROR;
3223 /* Some options need some conversion before they can be sent to
3224 * setsockopt. The conversions are done here, then they will fall though
3225 * to the general case. Special options that are not passed to
3226 * setsockopt follow below that.*/
3228 case WS_SO_DONTLINGER:
3229 linger.l_onoff = *((const int*)optval) ? 0: 1;
3230 linger.l_linger = 0;
3232 optname = SO_LINGER;
3233 optval = (char*)&linger;
3234 optlen = sizeof(struct linger);
3238 linger.l_onoff = ((LINGER*)optval)->l_onoff;
3239 linger.l_linger = ((LINGER*)optval)->l_linger;
3240 /* FIXME: what is documented behavior if SO_LINGER optval
3243 optname = SO_LINGER;
3244 optval = (char*)&linger;
3245 optlen = sizeof(struct linger);
3249 if (*(const int*)optval < 2048)
3251 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
3256 /* The options listed here don't need any special handling. Thanks to
3257 * the conversion happening above, options from there will fall through
3259 case WS_SO_ACCEPTCONN:
3260 case WS_SO_BROADCAST:
3262 case WS_SO_KEEPALIVE:
3263 case WS_SO_OOBINLINE:
3264 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
3265 * however, using it the BSD way fixes bug 8513 and seems to be what
3266 * most programmers assume, anyway */
3267 case WS_SO_REUSEADDR:
3270 convert_sockopt(&level, &optname);
3273 /* SO_DEBUG is a privileged operation, ignore it. */
3275 TRACE("Ignoring SO_DEBUG\n");
3278 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
3279 * socket. According to MSDN, this option is silently ignored.*/
3280 case WS_SO_DONTROUTE:
3281 TRACE("Ignoring SO_DONTROUTE\n");
3284 /* Stops two sockets from being bound to the same port. Always happens
3285 * on unix systems, so just drop it. */
3286 case WS_SO_EXCLUSIVEADDRUSE:
3287 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
3290 /* SO_OPENTYPE does not require a valid socket handle. */
3291 case WS_SO_OPENTYPE:
3292 if (!optlen || optlen < sizeof(int) || !optval)
3294 SetLastError(WSAEFAULT);
3295 return SOCKET_ERROR;
3297 get_per_thread_data()->opentype = *(const int *)optval;
3298 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3302 case WS_SO_RCVTIMEO:
3305 case WS_SO_SNDTIMEO:
3307 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3308 if (optval && optlen == sizeof(UINT32)) {
3309 /* WinSock passes milliseconds instead of struct timeval */
3310 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
3311 tval.tv_sec = *(const UINT32*)optval / 1000;
3312 /* min of 500 milliseconds */
3313 if (tval.tv_sec == 0 && tval.tv_usec < 500000)
3314 tval.tv_usec = 500000;
3315 optlen = sizeof(struct timeval);
3316 optval = (char*)&tval;
3317 } else if (optlen == sizeof(struct timeval)) {
3318 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
3320 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
3323 convert_sockopt(&level, &optname);
3328 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3329 SetLastError(WSAENOPROTOOPT);
3330 return SOCKET_ERROR;
3332 break; /* case WS_SOL_SOCKET */
3339 fd = get_sock_fd( s, 0, NULL );
3340 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
3342 /* We try to set the ipx type on ipx socket level. */
3344 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
3346 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
3347 release_sock_fd( s, fd );
3348 return SOCKET_ERROR;
3353 /* Should we retrieve val using a getsockopt call and then
3354 * set the modified one? */
3355 val.ipx_pt = *optval;
3356 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
3359 release_sock_fd( s, fd );
3362 case IPX_FILTERPTYPE:
3363 /* Sets the receive filter packet type, at the moment we don't support it */
3364 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
3365 /* Returning 0 is better for now than returning a SOCKET_ERROR */
3369 FIXME("opt_name:%x\n", optname);
3370 return SOCKET_ERROR;
3372 break; /* case NSPROTO_IPX */
3375 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3376 case WS_IPPROTO_TCP:
3379 case WS_TCP_NODELAY:
3380 convert_sockopt(&level, &optname);
3383 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3384 return SOCKET_ERROR;
3391 case WS_IP_ADD_MEMBERSHIP:
3392 case WS_IP_DROP_MEMBERSHIP:
3396 case WS_IP_MULTICAST_IF:
3397 case WS_IP_MULTICAST_LOOP:
3398 case WS_IP_MULTICAST_TTL:
3402 convert_sockopt(&level, &optname);
3404 case WS_IP_DONTFRAGMENT:
3405 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
3408 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3409 return SOCKET_ERROR;
3414 WARN("Unknown level: 0x%08x\n", level);
3415 SetLastError(WSAEINVAL);
3416 return SOCKET_ERROR;
3417 } /* end switch(level) */
3419 /* avoid endianness issues if argument is a 16-bit int */
3420 if (optval && optlen < sizeof(int))
3422 woptval= *((const INT16 *) optval);
3423 optval= (char*) &woptval;
3426 fd = get_sock_fd( s, 0, NULL );
3427 if (fd == -1) return SOCKET_ERROR;
3429 if (setsockopt(fd, level, optname, optval, optlen) == 0)
3431 release_sock_fd( s, fd );
3434 TRACE("Setting socket error, %d\n", wsaErrno());
3435 SetLastError(wsaErrno());
3436 release_sock_fd( s, fd );
3438 return SOCKET_ERROR;
3441 /***********************************************************************
3442 * shutdown (WS2_32.22)
3444 int WINAPI WS_shutdown(SOCKET s, int how)
3446 int fd, err = WSAENOTSOCK;
3447 unsigned int options, clear_flags = 0;
3449 fd = get_sock_fd( s, 0, &options );
3450 TRACE("socket %04lx, how %i %x\n", s, how, options );
3453 return SOCKET_ERROR;
3457 case 0: /* drop receives */
3458 clear_flags |= FD_READ;
3460 case 1: /* drop sends */
3461 clear_flags |= FD_WRITE;
3463 case 2: /* drop all */
3464 clear_flags |= FD_READ|FD_WRITE;
3466 clear_flags |= FD_WINE_LISTENING;
3469 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3474 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3477 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3481 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3482 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3485 if (err) goto error;
3487 else /* non-overlapped mode */
3489 if ( shutdown( fd, how ) )
3496 release_sock_fd( s, fd );
3497 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3498 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
3502 release_sock_fd( s, fd );
3503 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3504 WSASetLastError( err );
3505 return SOCKET_ERROR;
3508 /***********************************************************************
3509 * socket (WS2_32.23)
3511 SOCKET WINAPI WS_socket(int af, int type, int protocol)
3513 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
3515 return WSASocketA( af, type, protocol, NULL, 0,
3516 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
3520 /***********************************************************************
3521 * gethostbyaddr (WS2_32.51)
3523 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
3525 struct WS_hostent *retval = NULL;
3526 struct hostent* host;
3528 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3531 struct hostent hostentry;
3534 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3536 int res = gethostbyaddr_r(addr, len, type,
3537 &hostentry, extrabuf, ebufsize, &host, &locerr);
3538 if( res != ERANGE) break;
3540 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3542 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3544 EnterCriticalSection( &csWSgetXXXbyYYY );
3545 host = gethostbyaddr(addr, len, type);
3546 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3548 if( host != NULL ) retval = WS_dup_he(host);
3549 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3550 HeapFree(GetProcessHeap(),0,extrabuf);
3552 LeaveCriticalSection( &csWSgetXXXbyYYY );
3554 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
3558 /***********************************************************************
3559 * WS_get_local_ips (INTERNAL)
3561 * Returns the list of local IP addresses by going through the network
3562 * adapters and using the local routing table to sort the addresses
3563 * from highest routing priority to lowest routing priority. This
3564 * functionality is inferred from the description for obtaining local
3565 * IP addresses given in the Knowledge Base Article Q160215.
3567 * Please note that the returned hostent is only freed when the thread
3568 * closes and is replaced if another hostent is requested.
3570 static struct WS_hostent* WS_get_local_ips( char *hostname )
3572 int last_metric, numroutes = 0, i, j;
3573 PIP_ADAPTER_INFO adapters = NULL, k;
3574 struct WS_hostent *hostlist = NULL;
3575 PMIB_IPFORWARDTABLE routes = NULL;
3576 struct route *route_addrs = NULL;
3577 DWORD adap_size, route_size;
3579 /* Obtain the size of the adapter list and routing table, also allocate memory */
3580 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
3582 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
3584 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
3585 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
3586 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
3587 if (adapters == NULL || routes == NULL || route_addrs == NULL)
3589 /* Obtain the adapter list and the full routing table */
3590 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
3592 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
3594 /* Store the interface associated with each route */
3595 for (i = 0; i < routes->dwNumEntries; i++)
3597 DWORD ifindex, ifmetric, exists = FALSE;
3599 if (routes->table[i].dwForwardType != MIB_IPROUTE_TYPE_DIRECT)
3601 ifindex = routes->table[i].dwForwardIfIndex;
3602 ifmetric = routes->table[i].dwForwardMetric1;
3603 /* Only store the lowest valued metric for an interface */
3604 for (j = 0; j < numroutes; j++)
3606 if (route_addrs[j].interface == ifindex)
3608 if (route_addrs[j].metric > ifmetric)
3609 route_addrs[j].metric = ifmetric;
3615 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
3616 if (route_addrs == NULL)
3617 goto cleanup; /* Memory allocation error, fail gracefully */
3618 route_addrs[numroutes].interface = ifindex;
3619 route_addrs[numroutes].metric = ifmetric;
3620 /* If no IP is found in the next step (for whatever reason)
3621 * then fall back to the magic loopback address.
3623 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
3627 goto cleanup; /* No routes, fall back to the Magic IP */
3628 /* Find the IP address associated with each found interface */
3629 for (i = 0; i < numroutes; i++)
3631 for (k = adapters; k != NULL; k = k->Next)
3633 char *ip = k->IpAddressList.IpAddress.String;
3635 if (route_addrs[i].interface == k->Index)
3636 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
3639 /* Allocate a hostent and enough memory for all the IPs,
3640 * including the NULL at the end of the list.
3642 hostlist = WS_create_he(hostname, 0, numroutes, TRUE);
3643 hostlist->h_addrtype = AF_INET;
3644 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
3645 /* Reorder the entries when placing them in the host list, Windows expects
3646 * the IP list in order from highest priority to lowest (the critical thing
3647 * is that most applications expect the first IP to be the default route).
3650 for (i = 0; i < numroutes; i++)
3652 struct in_addr addr;
3653 int metric = 0xFFFF;
3655 memcpy(&addr, magic_loopback_addr, 4);
3656 for (j = 0; j < numroutes; j++)
3658 int this_metric = route_addrs[j].metric;
3660 if (this_metric > last_metric && this_metric < metric)
3662 addr = route_addrs[j].addr;
3663 metric = this_metric;
3666 last_metric = metric;
3667 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
3670 /* Cleanup all allocated memory except the address list,
3671 * the address list is used by the calling app.
3674 HeapFree(GetProcessHeap(), 0, route_addrs);
3675 HeapFree(GetProcessHeap(), 0, adapters);
3676 HeapFree(GetProcessHeap(), 0, routes);
3680 /***********************************************************************
3681 * gethostbyname (WS2_32.52)
3683 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
3685 struct WS_hostent *retval = NULL;
3686 struct hostent* host;
3687 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3690 struct hostent hostentry;
3691 int locerr = ENOBUFS;
3694 if( gethostname( hostname, 100) == -1) {
3695 SetLastError( WSAENOBUFS); /* appropriate ? */
3698 if( !name || !name[0]) {
3701 /* If the hostname of the local machine is requested then return the
3702 * complete list of local IP addresses */
3703 if(strcmp(name, hostname) == 0)
3704 retval = WS_get_local_ips(hostname);
3705 /* If any other hostname was requested (or the routing table lookup failed)
3706 * then return the IP found by the host OS */
3709 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3711 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3713 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
3714 if( res != ERANGE) break;
3716 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3718 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3720 EnterCriticalSection( &csWSgetXXXbyYYY );
3721 host = gethostbyname(name);
3722 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3724 if (host) retval = WS_dup_he(host);
3725 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3726 HeapFree(GetProcessHeap(),0,extrabuf);
3728 LeaveCriticalSection( &csWSgetXXXbyYYY );
3731 if (retval && retval->h_addr_list[0][0] == 127 &&
3732 strcmp(name, "localhost") != 0)
3734 /* hostname != "localhost" but has loopback address. replace by our
3735 * special address.*/
3736 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
3738 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3743 /***********************************************************************
3744 * getprotobyname (WS2_32.53)
3746 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3748 struct WS_protoent* retval = NULL;
3749 #ifdef HAVE_GETPROTOBYNAME
3750 struct protoent* proto;
3751 EnterCriticalSection( &csWSgetXXXbyYYY );
3752 if( (proto = getprotobyname(name)) != NULL )
3754 retval = WS_dup_pe(proto);
3757 MESSAGE("protocol %s not found; You might want to add "
3758 "this to /etc/protocols\n", debugstr_a(name) );
3759 SetLastError(WSANO_DATA);
3761 LeaveCriticalSection( &csWSgetXXXbyYYY );
3763 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3768 /***********************************************************************
3769 * getprotobynumber (WS2_32.54)
3771 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3773 struct WS_protoent* retval = NULL;
3774 #ifdef HAVE_GETPROTOBYNUMBER
3775 struct protoent* proto;
3776 EnterCriticalSection( &csWSgetXXXbyYYY );
3777 if( (proto = getprotobynumber(number)) != NULL )
3779 retval = WS_dup_pe(proto);
3782 MESSAGE("protocol number %d not found; You might want to add "
3783 "this to /etc/protocols\n", number );
3784 SetLastError(WSANO_DATA);
3786 LeaveCriticalSection( &csWSgetXXXbyYYY );
3788 TRACE("%i ret %p\n", number, retval);
3793 /***********************************************************************
3794 * getservbyname (WS2_32.55)
3796 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3798 struct WS_servent* retval = NULL;
3799 struct servent* serv;
3801 char *proto_str = NULL;
3803 if (!(name_str = strdup_lower(name))) return NULL;
3805 if (proto && *proto)
3807 if (!(proto_str = strdup_lower(proto)))
3809 HeapFree( GetProcessHeap(), 0, name_str );
3814 EnterCriticalSection( &csWSgetXXXbyYYY );
3815 serv = getservbyname(name_str, proto_str);
3818 retval = WS_dup_se(serv);
3820 else SetLastError(WSANO_DATA);
3821 LeaveCriticalSection( &csWSgetXXXbyYYY );
3822 HeapFree( GetProcessHeap(), 0, proto_str );
3823 HeapFree( GetProcessHeap(), 0, name_str );
3824 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
3828 /***********************************************************************
3829 * freeaddrinfo (WS2_32.@)
3831 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
3834 struct WS_addrinfo *next;
3836 HeapFree(GetProcessHeap(),0,res->ai_canonname);
3837 HeapFree(GetProcessHeap(),0,res->ai_addr);
3838 next = res->ai_next;
3839 HeapFree(GetProcessHeap(),0,res);
3844 /* helper functions for getaddrinfo()/getnameinfo() */
3845 static int convert_aiflag_w2u(int winflags) {
3849 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3850 if (ws_aiflag_map[i][0] & winflags) {
3851 unixflags |= ws_aiflag_map[i][1];
3852 winflags &= ~ws_aiflag_map[i][0];
3855 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
3859 static int convert_niflag_w2u(int winflags) {
3863 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
3864 if (ws_niflag_map[i][0] & winflags) {
3865 unixflags |= ws_niflag_map[i][1];
3866 winflags &= ~ws_niflag_map[i][0];
3869 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
3873 static int convert_aiflag_u2w(int unixflags) {
3877 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3878 if (ws_aiflag_map[i][1] & unixflags) {
3879 winflags |= ws_aiflag_map[i][0];
3880 unixflags &= ~ws_aiflag_map[i][1];
3882 if (unixflags) /* will warn usually */
3883 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
3887 static int convert_eai_u2w(int unixret) {
3890 for (i=0;ws_eai_map[i][0];i++)
3891 if (ws_eai_map[i][1] == unixret)
3892 return ws_eai_map[i][0];
3896 /***********************************************************************
3897 * getaddrinfo (WS2_32.@)
3899 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
3901 #ifdef HAVE_GETADDRINFO
3902 struct addrinfo *unixaires = NULL;
3904 struct addrinfo unixhints, *punixhints = NULL;
3905 CHAR *node = NULL, *serv = NULL;
3908 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
3911 if (!(serv = strdup_lower(servname))) {
3912 HeapFree(GetProcessHeap(), 0, node);
3913 return WSA_NOT_ENOUGH_MEMORY;
3918 punixhints = &unixhints;
3920 memset(&unixhints, 0, sizeof(unixhints));
3921 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
3922 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
3923 punixhints->ai_family = 0;
3925 punixhints->ai_family = convert_af_w2u(hints->ai_family);
3926 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
3927 punixhints->ai_socktype = 0;
3929 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
3930 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
3931 punixhints->ai_protocol = 0;
3933 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
3936 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
3937 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
3939 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
3941 HeapFree(GetProcessHeap(), 0, node);
3942 HeapFree(GetProcessHeap(), 0, serv);
3945 struct addrinfo *xuai = unixaires;
3946 struct WS_addrinfo **xai = res;
3950 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
3956 *xai = ai;xai = &ai->ai_next;
3957 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
3958 ai->ai_family = convert_af_u2w(xuai->ai_family);
3959 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
3960 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
3961 if (xuai->ai_canonname) {
3962 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
3963 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
3964 if (!ai->ai_canonname)
3966 strcpy(ai->ai_canonname,xuai->ai_canonname);
3968 len = xuai->ai_addrlen;
3969 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
3972 ai->ai_addrlen = len;
3974 int winlen = ai->ai_addrlen;
3976 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
3977 ai->ai_addrlen = winlen;
3981 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
3984 ai->ai_addrlen = len;
3986 xuai = xuai->ai_next;
3988 freeaddrinfo(unixaires);
3990 result = convert_eai_u2w(result);
3996 if (*res) WS_freeaddrinfo(*res);
3997 if (unixaires) freeaddrinfo(unixaires);
3999 return WSA_NOT_ENOUGH_MEMORY;
4001 FIXME("getaddrinfo() failed, not found during buildtime.\n");
4006 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
4008 struct WS_addrinfoW *ret;
4010 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
4011 ret->ai_flags = ai->ai_flags;
4012 ret->ai_family = ai->ai_family;
4013 ret->ai_socktype = ai->ai_socktype;
4014 ret->ai_protocol = ai->ai_protocol;
4015 ret->ai_addrlen = ai->ai_addrlen;
4016 ret->ai_canonname = NULL;
4017 ret->ai_addr = NULL;
4018 ret->ai_next = NULL;
4019 if (ai->ai_canonname)
4021 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
4022 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
4024 HeapFree(GetProcessHeap(), 0, ret);
4027 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
4031 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
4033 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
4034 HeapFree(GetProcessHeap(), 0, ret);
4037 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
4042 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
4044 struct WS_addrinfoW *ret, *infoW;
4046 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
4047 while (info->ai_next)
4049 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
4054 infoW = infoW->ai_next;
4055 info = info->ai_next;
4060 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
4062 struct WS_addrinfo *ret;
4064 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
4065 ret->ai_flags = ai->ai_flags;
4066 ret->ai_family = ai->ai_family;
4067 ret->ai_socktype = ai->ai_socktype;
4068 ret->ai_protocol = ai->ai_protocol;
4069 ret->ai_addrlen = ai->ai_addrlen;
4070 ret->ai_canonname = NULL;
4071 ret->ai_addr = NULL;
4072 ret->ai_next = NULL;
4073 if (ai->ai_canonname)
4075 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
4076 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
4078 HeapFree(GetProcessHeap(), 0, ret);
4081 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
4085 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
4087 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
4088 HeapFree(GetProcessHeap(), 0, ret);
4091 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
4096 /***********************************************************************
4097 * GetAddrInfoW (WS2_32.@)
4099 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
4102 char *nodenameA, *servnameA = NULL;
4103 struct WS_addrinfo *resA, *hintsA = NULL;
4105 if (!nodename) return WSAHOST_NOT_FOUND;
4107 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
4108 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
4109 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
4113 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
4114 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
4116 HeapFree(GetProcessHeap(), 0, nodenameA);
4119 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
4122 if (hints) hintsA = addrinfo_WtoA(hints);
4123 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
4124 WS_freeaddrinfo(hintsA);
4128 *res = addrinfo_list_AtoW(resA);
4129 WS_freeaddrinfo(resA);
4132 HeapFree(GetProcessHeap(), 0, nodenameA);
4133 HeapFree(GetProcessHeap(), 0, servnameA);
4137 /***********************************************************************
4138 * FreeAddrInfoW (WS2_32.@)
4140 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
4145 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
4146 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
4148 HeapFree(GetProcessHeap(), 0, ai);
4153 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
4154 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
4156 #ifdef HAVE_GETNAMEINFO
4158 union generic_unix_sockaddr sa_u;
4161 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
4162 serv, servlen, flags);
4164 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
4167 WSASetLastError(WSAEFAULT);
4168 return WSA_NOT_ENOUGH_MEMORY;
4170 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
4171 return convert_eai_u2w(ret);
4173 FIXME("getnameinfo() failed, not found during buildtime.\n");
4178 /***********************************************************************
4179 * getservbyport (WS2_32.56)
4181 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
4183 struct WS_servent* retval = NULL;
4184 #ifdef HAVE_GETSERVBYPORT
4185 struct servent* serv;
4186 char *proto_str = NULL;
4188 if (proto && *proto)
4190 if (!(proto_str = strdup_lower(proto))) return NULL;
4192 EnterCriticalSection( &csWSgetXXXbyYYY );
4193 if( (serv = getservbyport(port, proto_str)) != NULL ) {
4194 retval = WS_dup_se(serv);
4196 else SetLastError(WSANO_DATA);
4197 LeaveCriticalSection( &csWSgetXXXbyYYY );
4198 HeapFree( GetProcessHeap(), 0, proto_str );
4200 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
4205 /***********************************************************************
4206 * gethostname (WS2_32.57)
4208 int WINAPI WS_gethostname(char *name, int namelen)
4210 TRACE("name %p, len %d\n", name, namelen);
4212 if (gethostname(name, namelen) == 0)
4214 TRACE("<- '%s'\n", name);
4217 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
4218 TRACE("<- ERROR !\n");
4219 return SOCKET_ERROR;
4223 /* ------------------------------------- Windows sockets extensions -- *
4225 * ------------------------------------------------------------------- */
4227 /***********************************************************************
4228 * WSAEnumNetworkEvents (WS2_32.36)
4230 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
4234 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
4236 SERVER_START_REQ( get_socket_event )
4238 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4239 req->service = TRUE;
4240 req->c_event = wine_server_obj_handle( hEvent );
4241 wine_server_set_reply( req, lpEvent->iErrorCode, sizeof(lpEvent->iErrorCode) );
4242 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
4246 SetLastError(WSAEINVAL);
4247 return SOCKET_ERROR;
4250 /***********************************************************************
4251 * WSAEventSelect (WS2_32.39)
4253 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
4257 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
4259 SERVER_START_REQ( set_socket_event )
4261 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4263 req->event = wine_server_obj_handle( hEvent );
4266 ret = wine_server_call( req );
4270 SetLastError(WSAEINVAL);
4271 return SOCKET_ERROR;
4274 /**********************************************************************
4275 * WSAGetOverlappedResult (WS2_32.40)
4277 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
4278 LPDWORD lpcbTransfer, BOOL fWait,
4283 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
4284 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
4286 if ( lpOverlapped == NULL )
4288 ERR( "Invalid pointer\n" );
4289 WSASetLastError(WSA_INVALID_PARAMETER);
4293 status = lpOverlapped->Internal;
4294 if (status == STATUS_PENDING)
4298 SetLastError( WSA_IO_INCOMPLETE );
4302 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
4303 INFINITE ) == WAIT_FAILED)
4305 status = lpOverlapped->Internal;
4309 *lpcbTransfer = lpOverlapped->InternalHigh;
4312 *lpdwFlags = lpOverlapped->u.s.Offset;
4314 if (status) SetLastError( RtlNtStatusToDosError(status) );
4319 /***********************************************************************
4320 * WSAAsyncSelect (WS2_32.101)
4322 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
4326 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
4328 SERVER_START_REQ( set_socket_event )
4330 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4333 req->window = wine_server_user_handle( hWnd );
4335 ret = wine_server_call( req );
4339 SetLastError(WSAEINVAL);
4340 return SOCKET_ERROR;
4343 /***********************************************************************
4344 * WSACreateEvent (WS2_32.31)
4347 WSAEVENT WINAPI WSACreateEvent(void)
4349 /* Create a manual-reset event, with initial state: unsignaled */
4352 return CreateEventW(NULL, TRUE, FALSE, NULL);
4355 /***********************************************************************
4356 * WSACloseEvent (WS2_32.29)
4359 BOOL WINAPI WSACloseEvent(WSAEVENT event)
4361 TRACE ("event=%p\n", event);
4363 return CloseHandle(event);
4366 /***********************************************************************
4367 * WSASocketA (WS2_32.78)
4370 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
4371 LPWSAPROTOCOL_INFOA lpProtocolInfo,
4372 GROUP g, DWORD dwFlags)
4375 WSAPROTOCOL_INFOW info;
4377 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
4378 af, type, protocol, lpProtocolInfo, g, dwFlags);
4380 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
4382 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
4383 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
4384 info.szProtocol, WSAPROTOCOL_LEN + 1);
4388 WSASetLastError( WSAEINVAL);
4389 return SOCKET_ERROR;
4392 return WSASocketW(af, type, protocol, &info, g, dwFlags);
4395 /***********************************************************************
4396 * WSASocketW (WS2_32.79)
4399 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
4400 LPWSAPROTOCOL_INFOW lpProtocolInfo,
4401 GROUP g, DWORD dwFlags)
4406 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
4407 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
4410 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
4411 af, type, protocol, lpProtocolInfo, g, dwFlags );
4413 /* hack for WSADuplicateSocket */
4414 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
4415 ret = lpProtocolInfo->dwCatalogEntryId;
4416 TRACE("\tgot duplicate %04lx\n", ret);
4420 /* convert the socket family and type */
4421 af = convert_af_w2u(af);
4422 type = convert_socktype_w2u(type);
4426 if (af == FROM_PROTOCOL_INFO)
4427 af = lpProtocolInfo->iAddressFamily;
4428 if (type == FROM_PROTOCOL_INFO)
4429 type = lpProtocolInfo->iSocketType;
4430 if (protocol == FROM_PROTOCOL_INFO)
4431 protocol = lpProtocolInfo->iProtocol;
4434 if ( af == AF_UNSPEC) /* did they not specify the address family? */
4438 if (type == SOCK_STREAM) { af = AF_INET; break; }
4440 if (type == SOCK_DGRAM) { af = AF_INET; break; }
4441 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
4444 SERVER_START_REQ( create_socket )
4448 req->protocol = protocol;
4449 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
4450 req->attributes = OBJ_INHERIT;
4451 req->flags = dwFlags;
4452 set_error( wine_server_call( req ) );
4453 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
4458 TRACE("\tcreated %04lx\n", ret );
4462 if (GetLastError() == WSAEACCES) /* raw socket denied */
4464 if (type == SOCK_RAW)
4465 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
4467 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
4468 SetLastError(WSAESOCKTNOSUPPORT);
4471 WARN("\t\tfailed!\n");
4472 return INVALID_SOCKET;
4475 /***********************************************************************
4476 * WSAJoinLeaf (WS2_32.58)
4479 SOCKET WINAPI WSAJoinLeaf(
4481 const struct WS_sockaddr *addr,
4483 LPWSABUF lpCallerData,
4484 LPWSABUF lpCalleeData,
4490 return INVALID_SOCKET;
4493 /***********************************************************************
4494 * __WSAFDIsSet (WS2_32.151)
4496 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
4498 int i = set->fd_count;
4500 TRACE("(%ld,%p(%i))\n", s, set, i);
4503 if (set->fd_array[i] == s) return 1;
4507 /***********************************************************************
4508 * WSAIsBlocking (WS2_32.114)
4510 BOOL WINAPI WSAIsBlocking(void)
4512 /* By default WinSock should set all its sockets to non-blocking mode
4513 * and poll in PeekMessage loop when processing "blocking" ones. This
4514 * function is supposed to tell if the program is in this loop. Our
4515 * blocking calls are truly blocking so we always return FALSE.
4517 * Note: It is allowed to call this function without prior WSAStartup().
4524 /***********************************************************************
4525 * WSACancelBlockingCall (WS2_32.113)
4527 INT WINAPI WSACancelBlockingCall(void)
4533 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
4535 FIXME("How was this called?\n");
4540 /***********************************************************************
4541 * WSASetBlockingHook (WS2_32.109)
4543 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
4545 FARPROC prev = blocking_hook;
4546 blocking_hook = lpBlockFunc;
4547 TRACE("hook %p\n", lpBlockFunc);
4552 /***********************************************************************
4553 * WSAUnhookBlockingHook (WS2_32.110)
4555 INT WINAPI WSAUnhookBlockingHook(void)
4557 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
4562 /* ----------------------------------- end of API stuff */
4564 /* ----------------------------------- helper functions -
4566 * TODO: Merge WS_dup_..() stuff into one function that
4567 * would operate with a generic structure containing internal
4568 * pointers (via a template of some kind).
4571 static int list_size(char** l, int item_size)
4576 j += (item_size) ? item_size : strlen(l[i]) + 1;
4577 j += (i + 1) * sizeof(char*); }
4581 static int list_dup(char** l_src, char** l_to, int item_size)
4586 for (i = 0; l_src[i]; i++) ;
4587 p = (char *)(l_to + i + 1);
4588 for (i = 0; l_src[i]; i++)
4590 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
4591 memcpy(p, l_src[i], count);
4596 return p - (char *)l_to;
4601 /* create a hostent entry
4603 * Creates the entry with enough memory for the name, aliases
4604 * addresses, and the address pointers. Also copies the name
4605 * and sets up all the pointers. If "fill_address" is set then
4606 * sufficient memory for the addresses is also allocated and the
4607 * address pointers are set to this memory.
4609 static struct WS_hostent *WS_create_he(char *name, int aliases, int addresses, int fill_addresses)
4611 struct WS_hostent *p_to;
4614 int size = (sizeof(struct WS_hostent) +
4616 sizeof(char *)*aliases +
4617 sizeof(char *)*addresses);
4619 /* Place addresses in the allocated memory, making sure to have enough
4620 * room for the NULL at the end of the list.
4623 size += sizeof(struct in_addr)*(addresses+1);
4625 if (!(p_to = check_buffer_he(size))) return NULL;
4626 memset(p_to, 0, size);
4628 p = (char *)(p_to + 1);
4635 p_to->h_aliases = (char **)p;
4636 p += sizeof(char *)*aliases;
4640 p_to->h_addr_list = (char **)p;
4641 p += sizeof(char *)*addresses;
4647 /* Fill in the list of address pointers and NULL-terminate the list*/
4648 for (i = 0; i < addresses; i++)
4649 p_to->h_addr_list[i] = (p += sizeof(struct in_addr));
4650 p_to->h_addr_list[i] = NULL;
4651 p += sizeof(struct in_addr);
4656 /* duplicate hostent entry
4657 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
4658 * Ditto for protoent and servent.
4660 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
4662 int addresses = list_size(p_he->h_addr_list, p_he->h_length);
4663 int aliases = list_size(p_he->h_aliases, 0);
4664 struct WS_hostent *p_to;
4666 p_to = WS_create_he(p_he->h_name, aliases, addresses, FALSE);
4668 if (!p_to) return NULL;
4669 p_to->h_addrtype = p_he->h_addrtype;
4670 p_to->h_length = p_he->h_length;
4672 list_dup(p_he->h_aliases, p_to->h_aliases, 0);
4673 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
4677 /* ----- protoent */
4679 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
4682 struct WS_protoent *p_to;
4684 int size = (sizeof(*p_pe) +
4685 strlen(p_pe->p_name) + 1 +
4686 list_size(p_pe->p_aliases, 0));
4688 if (!(p_to = check_buffer_pe(size))) return NULL;
4689 p_to->p_proto = p_pe->p_proto;
4691 p = (char *)(p_to + 1);
4693 strcpy(p, p_pe->p_name);
4696 p_to->p_aliases = (char **)p;
4697 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
4703 static struct WS_servent *WS_dup_se(const struct servent* p_se)
4706 struct WS_servent *p_to;
4708 int size = (sizeof(*p_se) +
4709 strlen(p_se->s_proto) + 1 +
4710 strlen(p_se->s_name) + 1 +
4711 list_size(p_se->s_aliases, 0));
4713 if (!(p_to = check_buffer_se(size))) return NULL;
4714 p_to->s_port = p_se->s_port;
4716 p = (char *)(p_to + 1);
4718 strcpy(p, p_se->s_name);
4722 strcpy(p, p_se->s_proto);
4725 p_to->s_aliases = (char **)p;
4726 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
4731 /***********************************************************************
4732 * WSARecv (WS2_32.67)
4734 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4735 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
4736 LPWSAOVERLAPPED lpOverlapped,
4737 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
4739 return WSARecvFrom(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
4740 NULL, NULL, lpOverlapped, lpCompletionRoutine);
4743 /***********************************************************************
4744 * WSARecvFrom (WS2_32.69)
4746 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4747 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
4748 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
4749 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4752 unsigned int i, options;
4754 struct ws2_async *wsa;
4755 DWORD timeout_start = GetTickCount();
4756 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4758 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
4759 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
4760 (lpFromlen ? *lpFromlen : -1),
4761 lpOverlapped, lpCompletionRoutine);
4763 fd = get_sock_fd( s, FILE_READ_DATA, &options );
4764 TRACE( "fd=%d, options=%x\n", fd, options );
4766 if (fd == -1) return SOCKET_ERROR;
4768 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
4774 wsa->hSocket = SOCKET2HANDLE(s);
4775 wsa->flags = *lpFlags;
4777 wsa->addrlen.ptr = lpFromlen;
4778 wsa->n_iovecs = dwBufferCount;
4779 wsa->first_iovec = 0;
4780 for (i = 0; i < dwBufferCount; i++)
4782 /* check buffer first to trigger write watches */
4783 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
4788 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4789 wsa->iovec[i].iov_len = lpBuffers[i].len;
4794 n = WS2_recv( fd, wsa );
4797 if (errno == EINTR) continue;
4798 if (errno != EAGAIN)
4801 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
4806 *lpNumberOfBytesRecvd = n;
4808 if ((lpOverlapped || lpCompletionRoutine) &&
4809 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4811 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4813 wsa->user_overlapped = lpOverlapped;
4814 wsa->completion_func = lpCompletionRoutine;
4815 release_sock_fd( s, fd );
4819 iosb->u.Status = STATUS_PENDING;
4820 iosb->Information = 0;
4822 SERVER_START_REQ( register_async )
4824 req->type = ASYNC_TYPE_READ;
4825 req->async.handle = wine_server_obj_handle( wsa->hSocket );
4826 req->async.callback = wine_server_client_ptr( WS2_async_recv );
4827 req->async.iosb = wine_server_client_ptr( iosb );
4828 req->async.arg = wine_server_client_ptr( wsa );
4829 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
4830 req->async.cvalue = cvalue;
4831 err = wine_server_call( req );
4835 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4836 WSASetLastError( NtStatusToWSAError( err ));
4837 return SOCKET_ERROR;
4840 iosb->u.Status = STATUS_SUCCESS;
4841 iosb->Information = n;
4842 if (!wsa->completion_func)
4844 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4845 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
4846 HeapFree( GetProcessHeap(), 0, wsa );
4848 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4849 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4850 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4856 if ( _is_blocking(s) )
4859 int timeout = GET_RCVTIMEO(fd);
4862 timeout -= GetTickCount() - timeout_start;
4863 if (timeout < 0) timeout = 0;
4867 pfd.events = POLLIN;
4868 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
4870 if (!timeout || !poll( &pfd, 1, timeout ))
4873 /* a timeout is not fatal */
4874 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4880 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4881 err = WSAEWOULDBLOCK;
4886 TRACE(" -> %i bytes\n", n);
4887 HeapFree( GetProcessHeap(), 0, wsa );
4888 release_sock_fd( s, fd );
4889 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4894 HeapFree( GetProcessHeap(), 0, wsa );
4895 release_sock_fd( s, fd );
4896 WARN(" -> ERROR %d\n", err);
4897 WSASetLastError( err );
4898 return SOCKET_ERROR;
4901 /***********************************************************************
4902 * WSCInstallProvider (WS2_32.88)
4904 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
4905 LPCWSTR lpszProviderDllPath,
4906 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
4907 DWORD dwNumberOfEntries,
4910 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
4911 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
4912 dwNumberOfEntries, lpErrno);
4918 /***********************************************************************
4919 * WSCDeinstallProvider (WS2_32.83)
4921 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
4923 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
4929 /***********************************************************************
4930 * WSAAccept (WS2_32.26)
4932 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
4933 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
4936 int ret = 0, size = 0;
4937 WSABUF CallerId, CallerData, CalleeId, CalleeData;
4938 /* QOS SQOS, GQOS; */
4941 SOCKADDR src_addr, dst_addr;
4943 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %d\n",
4944 s, addr, addrlen, lpfnCondition, dwCallbackData);
4947 size = sizeof(src_addr);
4948 cs = WS_accept(s, &src_addr, &size);
4950 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
4952 if (!lpfnCondition) return cs;
4954 CallerId.buf = (char *)&src_addr;
4955 CallerId.len = sizeof(src_addr);
4957 CallerData.buf = NULL;
4960 WS_getsockname(cs, &dst_addr, &size);
4962 CalleeId.buf = (char *)&dst_addr;
4963 CalleeId.len = sizeof(dst_addr);
4966 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
4967 &CalleeId, &CalleeData, &g, dwCallbackData);
4972 if (addr && addrlen)
4973 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
4976 SERVER_START_REQ( set_socket_deferred )
4978 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4979 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
4980 if ( !wine_server_call_err ( req ) )
4982 SetLastError( WSATRY_AGAIN );
4983 WS_closesocket( cs );
4987 return SOCKET_ERROR;
4990 SetLastError(WSAECONNREFUSED);
4991 return SOCKET_ERROR;
4993 FIXME("Unknown return type from Condition function\n");
4994 SetLastError(WSAENOTSOCK);
4995 return SOCKET_ERROR;
4999 /***********************************************************************
5000 * WSADuplicateSocketA (WS2_32.32)
5002 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
5006 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
5007 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
5008 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
5009 /* I don't know what the real Windoze does next, this is a hack */
5010 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
5011 * the target use the global duplicate, or we could copy a reference to us to the structure
5012 * and let the target duplicate it from us, but let's do it as simple as possible */
5013 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
5014 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
5015 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
5016 0, FALSE, DUPLICATE_SAME_ACCESS);
5017 CloseHandle(hProcess);
5018 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
5022 /***********************************************************************
5023 * WSADuplicateSocketW (WS2_32.33)
5025 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
5029 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
5031 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
5032 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
5033 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
5034 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
5035 0, FALSE, DUPLICATE_SAME_ACCESS);
5036 CloseHandle(hProcess);
5037 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
5041 /***********************************************************************
5042 * WSAInstallServiceClassA (WS2_32.48)
5044 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
5046 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
5047 WSASetLastError(WSAEACCES);
5048 return SOCKET_ERROR;
5051 /***********************************************************************
5052 * WSAInstallServiceClassW (WS2_32.49)
5054 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
5056 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
5057 WSASetLastError(WSAEACCES);
5058 return SOCKET_ERROR;
5061 /***********************************************************************
5062 * WSARemoveServiceClass (WS2_32.70)
5064 int WINAPI WSARemoveServiceClass(LPGUID info)
5066 FIXME("Request to remove service %p\n",info);
5067 WSASetLastError(WSATYPE_NOT_FOUND);
5068 return SOCKET_ERROR;
5071 /***********************************************************************
5072 * inet_ntop (WS2_32.@)
5074 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
5076 #ifdef HAVE_INET_NTOP
5077 struct WS_in6_addr *in6;
5078 struct WS_in_addr *in;
5081 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
5084 WSASetLastError( STATUS_INVALID_PARAMETER );
5093 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
5099 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
5103 WSASetLastError( WSAEAFNOSUPPORT );
5107 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
5110 FIXME( "not supported on this platform\n" );
5111 WSASetLastError( WSAEAFNOSUPPORT );
5116 /***********************************************************************
5117 * WSAStringToAddressA (WS2_32.80)
5119 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
5121 LPWSAPROTOCOL_INFOA lpProtocolInfo,
5122 LPSOCKADDR lpAddress,
5123 LPINT lpAddressLength)
5126 LPSTR workBuffer=NULL,ptrPort;
5128 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
5129 lpProtocolInfo, lpAddress, lpAddressLength );
5131 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
5135 WSASetLastError(WSAEINVAL);
5136 return SOCKET_ERROR;
5140 FIXME("ProtocolInfo not implemented.\n");
5142 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
5143 strlen(AddressString) + 1);
5146 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5147 return SOCKET_ERROR;
5150 strcpy(workBuffer, AddressString);
5152 switch(AddressFamily)
5156 struct in_addr inetaddr;
5158 /* If lpAddressLength is too small, tell caller the size we need */
5159 if (*lpAddressLength < sizeof(SOCKADDR_IN))
5161 *lpAddressLength = sizeof(SOCKADDR_IN);
5165 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
5167 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
5169 ptrPort = strchr(workBuffer, ':');
5172 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
5177 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
5180 if(inet_aton(workBuffer, &inetaddr) > 0)
5182 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
5193 struct in6_addr inetaddr;
5194 /* If lpAddressLength is too small, tell caller the size we need */
5195 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
5197 *lpAddressLength = sizeof(SOCKADDR_IN6);
5201 #ifdef HAVE_INET_PTON
5202 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
5204 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
5206 /* This one is a bit tricky. An IPv6 address contains colons, so the
5207 * check from IPv4 doesn't work like that. However, IPv6 addresses that
5208 * contain a port are written with braces like [fd12:3456:7890::1]:12345
5209 * so what we will do is to look for ']', check if the next char is a
5210 * colon, and if it is, parse the port as in IPv4. */
5212 ptrPort = strchr(workBuffer, ']');
5213 if(ptrPort && *(++ptrPort) == ':')
5215 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
5220 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
5223 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
5225 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
5226 sizeof(struct in6_addr));
5230 #endif /* HAVE_INET_PTON */
5236 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
5237 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
5241 HeapFree(GetProcessHeap(), 0, workBuffer);
5244 WSASetLastError(res);
5245 return SOCKET_ERROR;
5248 /***********************************************************************
5249 * WSAStringToAddressW (WS2_32.81)
5251 * Does anybody know if this functions allows to use hebrew/arabic/chinese... digits?
5252 * If this should be the case, it would be required to map these digits
5253 * to Unicode digits (0-9) using FoldString first.
5255 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
5257 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5258 LPSOCKADDR lpAddress,
5259 LPINT lpAddressLength)
5262 LPSTR workBuffer=NULL;
5263 WSAPROTOCOL_INFOA infoA;
5264 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
5266 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
5267 lpAddress, lpAddressLength );
5269 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
5271 /* if ProtocolInfo is available - convert to ANSI variant */
5274 lpProtoInfoA = &infoA;
5275 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
5277 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5278 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
5280 WSASetLastError( WSAEINVAL);
5281 return SOCKET_ERROR;
5287 /* Translate AddressString to ANSI code page - assumes that only
5288 standard digits 0-9 are used with this API call */
5289 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
5290 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
5294 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
5295 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
5296 lpAddress,lpAddressLength);
5297 HeapFree( GetProcessHeap(), 0, workBuffer );
5301 res = WSA_NOT_ENOUGH_MEMORY;
5306 WSASetLastError(res);
5307 return SOCKET_ERROR;
5310 /***********************************************************************
5311 * WSAAddressToStringA (WS2_32.27)
5313 * See WSAAddressToStringW
5315 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
5316 LPWSAPROTOCOL_INFOA info, LPSTR string,
5320 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
5323 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
5325 if (!sockaddr) return SOCKET_ERROR;
5326 if (!string || !lenstr) return SOCKET_ERROR;
5328 switch(sockaddr->sa_family)
5331 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
5332 sprintf( buffer, "%u.%u.%u.%u:%u",
5333 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
5334 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
5335 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
5336 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
5337 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
5339 p = strchr( buffer, ':' );
5340 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
5345 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
5348 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
5349 if ((sockaddr6->sin6_port))
5350 strcpy(buffer, "[");
5351 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
5353 WSASetLastError(WSAEINVAL);
5354 return SOCKET_ERROR;
5356 if ((sockaddr6->sin6_scope_id))
5357 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
5358 if ((sockaddr6->sin6_port))
5359 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
5364 WSASetLastError(WSAEINVAL);
5365 return SOCKET_ERROR;
5368 size = strlen( buffer ) + 1;
5373 WSASetLastError(WSAEFAULT);
5374 return SOCKET_ERROR;
5378 strcpy( string, buffer );
5382 /***********************************************************************
5383 * WSAAddressToStringW (WS2_32.28)
5385 * Convert a sockaddr address into a readable address string.
5388 * sockaddr [I] Pointer to a sockaddr structure.
5389 * len [I] Size of the sockaddr structure.
5390 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
5391 * string [I/O] Pointer to a buffer to receive the address string.
5392 * lenstr [I/O] Size of the receive buffer in WCHARs.
5396 * Failure: SOCKET_ERROR
5399 * The 'info' parameter is ignored.
5401 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
5402 LPWSAPROTOCOL_INFOW info, LPWSTR string,
5407 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
5410 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
5413 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
5415 if (ret) return ret;
5417 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
5422 WSASetLastError(WSAEFAULT);
5423 return SOCKET_ERROR;
5427 lstrcpyW( string, buffer );
5431 /***********************************************************************
5432 * WSAEnumNameSpaceProvidersA (WS2_32.34)
5434 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
5436 FIXME( "(%p %p) Stub!\n", len, buffer );
5440 /***********************************************************************
5441 * WSAEnumNameSpaceProvidersW (WS2_32.35)
5443 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
5445 FIXME( "(%p %p) Stub!\n", len, buffer );
5449 /***********************************************************************
5450 * WSAGetQOSByName (WS2_32.41)
5452 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
5454 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
5458 /***********************************************************************
5459 * WSAGetServiceClassInfoA (WS2_32.42)
5461 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
5462 LPWSASERVICECLASSINFOA info )
5464 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
5466 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5467 return SOCKET_ERROR;
5470 /***********************************************************************
5471 * WSAGetServiceClassInfoW (WS2_32.43)
5473 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
5474 LPWSASERVICECLASSINFOW info )
5476 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
5478 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5479 return SOCKET_ERROR;
5482 /***********************************************************************
5483 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
5485 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
5487 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
5488 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5489 return SOCKET_ERROR;
5492 /***********************************************************************
5493 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
5495 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
5497 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
5498 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5499 return SOCKET_ERROR;
5502 /***********************************************************************
5503 * WSALookupServiceBeginA (WS2_32.59)
5505 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
5506 DWORD dwControlFlags,
5509 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
5511 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5512 return SOCKET_ERROR;
5515 /***********************************************************************
5516 * WSALookupServiceBeginW (WS2_32.60)
5518 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
5519 DWORD dwControlFlags,
5522 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
5524 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5525 return SOCKET_ERROR;
5528 /***********************************************************************
5529 * WSALookupServiceBeginW (WS2_32.61)
5531 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
5533 FIXME("(%p) Stub!\n", lookup );
5537 /***********************************************************************
5538 * WSALookupServiceNextA (WS2_32.62)
5540 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
5542 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
5546 /***********************************************************************
5547 * WSALookupServiceNextW (WS2_32.63)
5549 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
5551 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
5555 /***********************************************************************
5556 * WSANtohl (WS2_32.64)
5558 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
5560 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
5562 if (!lphostlong) return WSAEFAULT;
5564 *lphostlong = ntohl( netlong );
5568 /***********************************************************************
5569 * WSANtohs (WS2_32.65)
5571 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
5573 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
5575 if (!lphostshort) return WSAEFAULT;
5577 *lphostshort = ntohs( netshort );
5581 /***********************************************************************
5582 * WSAProviderConfigChange (WS2_32.66)
5584 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
5585 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
5587 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
5588 return SOCKET_ERROR;
5591 /***********************************************************************
5592 * WSARecvDisconnect (WS2_32.68)
5594 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
5596 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
5598 return WS_shutdown( s, 0 );
5601 /***********************************************************************
5602 * WSASetServiceA (WS2_32.76)
5604 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
5606 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5610 /***********************************************************************
5611 * WSASetServiceW (WS2_32.77)
5613 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
5615 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5619 /***********************************************************************
5620 * WSCEnableNSProvider (WS2_32.84)
5622 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
5624 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
5628 /***********************************************************************
5629 * WSCGetProviderPath (WS2_32.86)
5631 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
5633 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
5635 if (!errcode || !provider || !len) return WSAEFAULT;
5637 *errcode = WSAEINVAL;
5638 return SOCKET_ERROR;
5641 /***********************************************************************
5642 * WSCInstallNameSpace (WS2_32.87)
5644 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
5645 DWORD version, LPGUID provider )
5647 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
5648 namespace, version, debugstr_guid(provider) );
5652 /***********************************************************************
5653 * WSCUnInstallNameSpace (WS2_32.89)
5655 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
5657 FIXME("(%p) Stub!\n", lpProviderId);
5661 /***********************************************************************
5662 * WSCWriteProviderOrder (WS2_32.91)
5664 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
5666 FIXME("(%p 0x%08x) Stub!\n", entry, number);