2 * based on Windows Sockets 1.1 specs
4 * Copyright (C) 1993,1994,1996,1997 John Brezak, Erik Bos, Alex Korobka.
5 * Copyright (C) 2005 Marcus Meissner
6 * Copyright (C) 2006-2008 Kai Blin
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 * NOTE: If you make any changes to fix a particular app, make sure
23 * they don't break something else like Netscape or telnet and ftp
24 * clients and servers (www.winsite.com got a lot of those).
28 #include "wine/port.h"
33 #include <sys/types.h>
37 #ifdef HAVE_SYS_IOCTL_H
38 # include <sys/ioctl.h>
40 #ifdef HAVE_SYS_FILIO_H
41 # include <sys/filio.h>
43 #ifdef HAVE_SYS_SOCKIO_H
44 # include <sys/sockio.h>
48 # include <sys/so_ioctl.h>
51 #ifdef HAVE_SYS_PARAM_H
52 # include <sys/param.h>
58 #ifdef HAVE_SYS_WAIT_H
59 # include <sys/wait.h>
64 #ifdef HAVE_SYS_SOCKET_H
65 #include <sys/socket.h>
67 #ifdef HAVE_NETINET_IN_H
68 # include <netinet/in.h>
70 #ifdef HAVE_NETINET_TCP_H
71 # include <netinet/tcp.h>
73 #ifdef HAVE_ARPA_INET_H
74 # include <arpa/inet.h>
79 #ifdef HAVE_SYS_ERRNO_H
80 #include <sys/errno.h>
89 #ifdef HAVE_ARPA_NAMESER_H
90 # include <arpa/nameser.h>
99 #ifdef HAVE_NETIPX_IPX_H
100 # include <netipx/ipx.h>
102 #elif defined(HAVE_LINUX_IPX_H)
103 # ifdef HAVE_ASM_TYPES_H
104 # include <asm/types.h>
106 # ifdef HAVE_LINUX_TYPES_H
107 # include <linux/types.h>
109 # include <linux/ipx.h>
113 #ifdef HAVE_LINUX_IRDA_H
114 # ifdef HAVE_LINUX_TYPES_H
115 # include <linux/types.h>
117 # include <linux/irda.h>
124 #ifdef HAVE_SYS_POLL_H
125 # include <sys/poll.h>
127 #ifdef HAVE_SYS_TIME_H
128 # include <sys/time.h>
131 #define NONAMELESSUNION
132 #define NONAMELESSSTRUCT
133 #include "ntstatus.h"
134 #define WIN32_NO_STATUS
139 #include "winerror.h"
141 #include "winsock2.h"
143 #include "ws2tcpip.h"
149 #include "iphlpapi.h"
150 #include "wine/server.h"
151 #include "wine/debug.h"
152 #include "wine/unicode.h"
155 # include "wsnwlink.h"
159 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
160 # define sipx_network sipx_addr.x_net
161 # define sipx_node sipx_addr.x_host.c_host
162 #endif /* __FreeBSD__ */
165 #define INADDR_NONE ~0UL
168 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
170 /* critical section to protect some non-reentrant net function */
171 static CRITICAL_SECTION csWSgetXXXbyYYY;
172 static CRITICAL_SECTION_DEBUG critsect_debug =
174 0, 0, &csWSgetXXXbyYYY,
175 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
176 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
178 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
180 union generic_unix_sockaddr
182 struct sockaddr addr;
183 char data[128]; /* should be big enough for all families */
186 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
188 if (!a) return "(nil)";
189 switch (a->sa_family)
192 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
193 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
194 ntohs(((const struct sockaddr_in *)a)->sin_port));
199 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
201 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
203 p = "(unknown IPv6 address)";
204 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
205 p, ntohs(sin->sin6_port));
211 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
212 addr = ntohl( addr );
213 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
215 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
218 return wine_dbg_sprintf("{ family %d }", a->sa_family);
222 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
223 #define SOCKET2HANDLE(s) ((HANDLE)(s))
224 #define HANDLE2SOCKET(h) ((SOCKET)(h))
226 /****************************************************************
227 * Async IO declarations
228 ****************************************************************/
230 typedef struct ws2_async
234 LPWSAOVERLAPPED user_overlapped;
235 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
236 IO_STATUS_BLOCK local_iosb;
237 struct WS_sockaddr *addr;
240 int val; /* for send operations */
241 int *ptr; /* for recv operations */
244 unsigned int n_iovecs;
245 unsigned int first_iovec;
246 struct iovec iovec[1];
249 /****************************************************************/
251 /* ----------------------------------- internal data */
253 /* ws_... struct conversion flags */
255 typedef struct /* WSAAsyncSelect() control struct */
257 HANDLE service, event, sock;
263 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
264 #define WS_MAX_UDP_DATAGRAM 1024
265 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
267 /* hostent's, servent's and protent's are stored in one buffer per thread,
268 * as documented on MSDN for the functions that return any of the buffers */
269 struct per_thread_data
272 struct WS_hostent *he_buffer;
273 struct WS_servent *se_buffer;
274 struct WS_protoent *pe_buffer;
280 static INT num_startup; /* reference counter */
281 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
283 /* function prototypes */
284 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
285 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
286 static struct WS_servent *WS_dup_se(const struct servent* p_se);
288 int WSAIOCTL_GetInterfaceCount(void);
289 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
291 #define MAP_OPTION(opt) { WS_##opt, opt }
293 static const int ws_sock_map[][2] =
295 MAP_OPTION( SO_DEBUG ),
296 MAP_OPTION( SO_ACCEPTCONN ),
297 MAP_OPTION( SO_REUSEADDR ),
298 MAP_OPTION( SO_KEEPALIVE ),
299 MAP_OPTION( SO_DONTROUTE ),
300 MAP_OPTION( SO_BROADCAST ),
301 MAP_OPTION( SO_LINGER ),
302 MAP_OPTION( SO_OOBINLINE ),
303 MAP_OPTION( SO_SNDBUF ),
304 MAP_OPTION( SO_RCVBUF ),
305 MAP_OPTION( SO_ERROR ),
306 MAP_OPTION( SO_TYPE ),
308 MAP_OPTION( SO_RCVTIMEO ),
311 MAP_OPTION( SO_SNDTIMEO ),
315 static const int ws_tcp_map[][2] =
318 MAP_OPTION( TCP_NODELAY ),
322 static const int ws_ip_map[][2] =
324 MAP_OPTION( IP_MULTICAST_IF ),
325 MAP_OPTION( IP_MULTICAST_TTL ),
326 MAP_OPTION( IP_MULTICAST_LOOP ),
327 MAP_OPTION( IP_ADD_MEMBERSHIP ),
328 MAP_OPTION( IP_DROP_MEMBERSHIP ),
329 MAP_OPTION( IP_OPTIONS ),
331 MAP_OPTION( IP_HDRINCL ),
333 MAP_OPTION( IP_TOS ),
334 MAP_OPTION( IP_TTL ),
337 static const int ws_af_map[][2] =
339 MAP_OPTION( AF_UNSPEC ),
340 MAP_OPTION( AF_INET ),
341 MAP_OPTION( AF_INET6 ),
343 MAP_OPTION( AF_IPX ),
346 MAP_OPTION( AF_IRDA ),
348 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
351 static const int ws_socktype_map[][2] =
353 MAP_OPTION( SOCK_DGRAM ),
354 MAP_OPTION( SOCK_STREAM ),
355 MAP_OPTION( SOCK_RAW ),
356 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
359 static const int ws_proto_map[][2] =
361 MAP_OPTION( IPPROTO_IP ),
362 MAP_OPTION( IPPROTO_TCP ),
363 MAP_OPTION( IPPROTO_UDP ),
364 MAP_OPTION( IPPROTO_ICMP ),
365 MAP_OPTION( IPPROTO_IGMP ),
366 MAP_OPTION( IPPROTO_RAW ),
367 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
370 static const int ws_aiflag_map[][2] =
372 MAP_OPTION( AI_PASSIVE ),
373 MAP_OPTION( AI_CANONNAME ),
374 MAP_OPTION( AI_NUMERICHOST ),
375 /* Linux/UNIX knows a lot more. But Windows only
376 * has 3 as far as I could see. -Marcus
380 static const int ws_niflag_map[][2] =
382 MAP_OPTION( NI_NOFQDN ),
383 MAP_OPTION( NI_NUMERICHOST ),
384 MAP_OPTION( NI_NAMEREQD ),
385 MAP_OPTION( NI_NUMERICSERV ),
386 MAP_OPTION( NI_DGRAM ),
389 static const int ws_eai_map[][2] =
391 MAP_OPTION( EAI_AGAIN ),
392 MAP_OPTION( EAI_BADFLAGS ),
393 MAP_OPTION( EAI_FAIL ),
394 MAP_OPTION( EAI_FAMILY ),
395 MAP_OPTION( EAI_MEMORY ),
396 /* Note: EAI_NODATA is deprecated, but still
397 * used by Windows and Linux... We map the newer
398 * EAI_NONAME to EAI_NODATA for now until Windows
402 MAP_OPTION( EAI_NODATA ),
405 { WS_EAI_NODATA, EAI_NONAME },
408 MAP_OPTION( EAI_SERVICE ),
409 MAP_OPTION( EAI_SOCKTYPE ),
413 static const char magic_loopback_addr[] = {127, 12, 34, 56};
415 /* ----------------------------------- error handling */
417 static UINT wsaErrno(void)
419 int loc_errno = errno;
420 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
424 case EINTR: return WSAEINTR;
425 case EBADF: return WSAEBADF;
427 case EACCES: return WSAEACCES;
428 case EFAULT: return WSAEFAULT;
429 case EINVAL: return WSAEINVAL;
430 case EMFILE: return WSAEMFILE;
431 case EWOULDBLOCK: return WSAEWOULDBLOCK;
432 case EINPROGRESS: return WSAEINPROGRESS;
433 case EALREADY: return WSAEALREADY;
434 case ENOTSOCK: return WSAENOTSOCK;
435 case EDESTADDRREQ: return WSAEDESTADDRREQ;
436 case EMSGSIZE: return WSAEMSGSIZE;
437 case EPROTOTYPE: return WSAEPROTOTYPE;
438 case ENOPROTOOPT: return WSAENOPROTOOPT;
439 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
440 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
441 case EOPNOTSUPP: return WSAEOPNOTSUPP;
442 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
443 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
444 case EADDRINUSE: return WSAEADDRINUSE;
445 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
446 case ENETDOWN: return WSAENETDOWN;
447 case ENETUNREACH: return WSAENETUNREACH;
448 case ENETRESET: return WSAENETRESET;
449 case ECONNABORTED: return WSAECONNABORTED;
451 case ECONNRESET: return WSAECONNRESET;
452 case ENOBUFS: return WSAENOBUFS;
453 case EISCONN: return WSAEISCONN;
454 case ENOTCONN: return WSAENOTCONN;
455 case ESHUTDOWN: return WSAESHUTDOWN;
456 case ETOOMANYREFS: return WSAETOOMANYREFS;
457 case ETIMEDOUT: return WSAETIMEDOUT;
458 case ECONNREFUSED: return WSAECONNREFUSED;
459 case ELOOP: return WSAELOOP;
460 case ENAMETOOLONG: return WSAENAMETOOLONG;
461 case EHOSTDOWN: return WSAEHOSTDOWN;
462 case EHOSTUNREACH: return WSAEHOSTUNREACH;
463 case ENOTEMPTY: return WSAENOTEMPTY;
465 case EPROCLIM: return WSAEPROCLIM;
468 case EUSERS: return WSAEUSERS;
471 case EDQUOT: return WSAEDQUOT;
474 case ESTALE: return WSAESTALE;
477 case EREMOTE: return WSAEREMOTE;
480 /* just in case we ever get here and there are no problems */
483 WARN("Unknown errno %d!\n", loc_errno);
484 return WSAEOPNOTSUPP;
488 static UINT wsaHerrno(int loc_errno)
491 WARN("h_errno %d.\n", loc_errno);
495 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
496 case TRY_AGAIN: return WSATRY_AGAIN;
497 case NO_RECOVERY: return WSANO_RECOVERY;
498 case NO_DATA: return WSANO_DATA;
499 case ENOBUFS: return WSAENOBUFS;
503 WARN("Unknown h_errno %d!\n", loc_errno);
504 return WSAEOPNOTSUPP;
508 static inline DWORD NtStatusToWSAError( const DWORD status )
510 /* We only need to cover the status codes set by server async request handling */
514 case STATUS_SUCCESS: wserr = 0; break;
515 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
516 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
517 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
518 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
519 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
520 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
521 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
522 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
524 if ( status >= WSABASEERR && status <= WSABASEERR+1004 )
525 /* It is not an NT status code but a winsock error */
529 wserr = RtlNtStatusToDosError( status );
530 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
536 /* set last error code from NT status without mapping WSA errors */
537 static inline unsigned int set_error( unsigned int err )
541 err = NtStatusToWSAError( err );
547 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
550 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
555 static inline void release_sock_fd( SOCKET s, int fd )
557 wine_server_release_fd( SOCKET2HANDLE(s), fd );
560 static void _enable_event( HANDLE s, unsigned int event,
561 unsigned int sstate, unsigned int cstate )
563 SERVER_START_REQ( enable_socket_event )
565 req->handle = wine_server_obj_handle( s );
567 req->sstate = sstate;
568 req->cstate = cstate;
569 wine_server_call( req );
574 static int _is_blocking(SOCKET s)
577 SERVER_START_REQ( get_socket_event )
579 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
580 req->service = FALSE;
582 wine_server_call( req );
583 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
589 static unsigned int _get_sock_mask(SOCKET s)
592 SERVER_START_REQ( get_socket_event )
594 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
595 req->service = FALSE;
597 wine_server_call( req );
604 static void _sync_sock_state(SOCKET s)
606 /* do a dummy wineserver request in order to let
607 the wineserver run through its select loop once */
608 (void)_is_blocking(s);
611 static int _get_sock_error(SOCKET s, unsigned int bit)
613 int events[FD_MAX_EVENTS];
615 SERVER_START_REQ( get_socket_event )
617 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
618 req->service = FALSE;
620 wine_server_set_reply( req, events, sizeof(events) );
621 wine_server_call( req );
627 static struct per_thread_data *get_per_thread_data(void)
629 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
630 /* lazy initialization */
633 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
634 NtCurrentTeb()->WinSockData = ptb;
639 static void free_per_thread_data(void)
641 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
645 /* delete scratch buffers */
646 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
647 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
648 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
649 ptb->he_buffer = NULL;
650 ptb->se_buffer = NULL;
651 ptb->pe_buffer = NULL;
653 HeapFree( GetProcessHeap(), 0, ptb );
654 NtCurrentTeb()->WinSockData = NULL;
657 /***********************************************************************
658 * DllMain (WS2_32.init)
660 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
662 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
664 case DLL_PROCESS_ATTACH:
666 case DLL_PROCESS_DETACH:
667 free_per_thread_data();
670 case DLL_THREAD_DETACH:
671 free_per_thread_data();
677 /***********************************************************************
680 * Converts socket flags from Windows format.
681 * Return 1 if converted, 0 if not (error).
683 static int convert_sockopt(INT *level, INT *optname)
690 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
691 if( ws_sock_map[i][0] == *optname )
693 *optname = ws_sock_map[i][1];
697 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
700 *level = IPPROTO_TCP;
701 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
702 if ( ws_tcp_map[i][0] == *optname )
704 *optname = ws_tcp_map[i][1];
708 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
712 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
713 if (ws_ip_map[i][0] == *optname )
715 *optname = ws_ip_map[i][1];
719 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
721 default: FIXME("Unimplemented or unknown socket level\n");
726 /* ----------------------------------- Per-thread info (or per-process?) */
728 static char *strdup_lower(const char *str)
731 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
735 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
738 else SetLastError(WSAENOBUFS);
742 static inline int sock_error_p(int s)
744 unsigned int optval, optlen;
746 optlen = sizeof(optval);
747 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
748 if (optval) WARN("\t[%i] error: %d\n", s, optval);
752 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
753 * from an fd and return the value converted to milli seconds
754 * or -1 if there is an infinite time out */
755 static inline int get_rcvsnd_timeo( int fd, int optname)
758 unsigned int len = sizeof(tv);
759 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
761 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
762 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
767 /* macro wrappers for portability */
769 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
771 #define GET_RCVTIMEO(fd) (-1)
775 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
777 #define GET_SNDTIMEO(fd) (-1)
780 /* utility: given an fd, will block until one of the events occurs */
781 static inline int do_block( int fd, int events, int timeout )
789 while ((ret = poll(&pfd, 1, timeout)) < 0)
800 convert_af_w2u(int windowsaf) {
803 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
804 if (ws_af_map[i][0] == windowsaf)
805 return ws_af_map[i][1];
806 FIXME("unhandled Windows address family %d\n", windowsaf);
811 convert_af_u2w(int unixaf) {
814 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
815 if (ws_af_map[i][1] == unixaf)
816 return ws_af_map[i][0];
817 FIXME("unhandled UNIX address family %d\n", unixaf);
822 convert_proto_w2u(int windowsproto) {
825 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
826 if (ws_proto_map[i][0] == windowsproto)
827 return ws_proto_map[i][1];
828 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
833 convert_proto_u2w(int unixproto) {
836 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
837 if (ws_proto_map[i][1] == unixproto)
838 return ws_proto_map[i][0];
839 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
844 convert_socktype_w2u(int windowssocktype) {
847 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
848 if (ws_socktype_map[i][0] == windowssocktype)
849 return ws_socktype_map[i][1];
850 FIXME("unhandled Windows socket type %d\n", windowssocktype);
855 convert_socktype_u2w(int unixsocktype) {
858 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
859 if (ws_socktype_map[i][1] == unixsocktype)
860 return ws_socktype_map[i][0];
861 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
865 /* ----------------------------------- API -----
867 * Init / cleanup / error checking.
870 /***********************************************************************
871 * WSAStartup (WS2_32.115)
873 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
875 TRACE("verReq=%x\n", wVersionRequested);
877 if (LOBYTE(wVersionRequested) < 1)
878 return WSAVERNOTSUPPORTED;
880 if (!lpWSAData) return WSAEINVAL;
884 /* that's the whole of the negotiation for now */
885 lpWSAData->wVersion = wVersionRequested;
886 /* return winsock information */
887 lpWSAData->wHighVersion = 0x0202;
888 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
889 strcpy(lpWSAData->szSystemStatus, "Running" );
890 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
891 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
892 /* don't do anything with lpWSAData->lpVendorInfo */
893 /* (some apps don't allocate the space for this field) */
895 TRACE("succeeded\n");
900 /***********************************************************************
901 * WSACleanup (WS2_32.116)
903 INT WINAPI WSACleanup(void)
909 SetLastError(WSANOTINITIALISED);
914 /***********************************************************************
915 * WSAGetLastError (WS2_32.111)
917 INT WINAPI WSAGetLastError(void)
919 return GetLastError();
922 /***********************************************************************
923 * WSASetLastError (WS2_32.112)
925 void WINAPI WSASetLastError(INT iError) {
926 SetLastError(iError);
929 static struct WS_hostent *check_buffer_he(int size)
931 struct per_thread_data * ptb = get_per_thread_data();
934 if (ptb->he_len >= size ) return ptb->he_buffer;
935 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
937 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
938 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
939 return ptb->he_buffer;
942 static struct WS_servent *check_buffer_se(int size)
944 struct per_thread_data * ptb = get_per_thread_data();
947 if (ptb->se_len >= size ) return ptb->se_buffer;
948 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
950 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
951 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
952 return ptb->se_buffer;
955 static struct WS_protoent *check_buffer_pe(int size)
957 struct per_thread_data * ptb = get_per_thread_data();
960 if (ptb->pe_len >= size ) return ptb->pe_buffer;
961 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
963 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
964 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
965 return ptb->pe_buffer;
968 /* ----------------------------------- i/o APIs */
970 static inline BOOL supported_pf(int pf)
991 /**********************************************************************/
993 /* Returns the length of the converted address if successful, 0 if it was too small to
996 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
997 union generic_unix_sockaddr *uaddr)
999 unsigned int uaddrlen = 0;
1001 switch (wsaddr->sa_family)
1006 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1007 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1009 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1012 uaddrlen = sizeof(struct sockaddr_ipx);
1013 memset( uaddr, 0, uaddrlen );
1014 uipx->sipx_family=AF_IPX;
1015 uipx->sipx_port=wsipx->sa_socket;
1016 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1019 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1020 #ifdef IPX_FRAME_NONE
1021 uipx->sipx_type=IPX_FRAME_NONE;
1027 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1028 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1030 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1031 * scope_id, one without.
1033 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1034 uaddrlen = sizeof(struct sockaddr_in6);
1035 memset( uaddr, 0, uaddrlen );
1036 uin6->sin6_family = AF_INET6;
1037 uin6->sin6_port = win6->sin6_port;
1038 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1039 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1040 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1042 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1045 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1049 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1050 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1052 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1054 uaddrlen = sizeof(struct sockaddr_in);
1055 memset( uaddr, 0, uaddrlen );
1056 uin->sin_family = AF_INET;
1057 uin->sin_port = win->sin_port;
1058 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1063 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1064 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1066 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1068 uaddrlen = sizeof(struct sockaddr_irda);
1069 memset( uaddr, 0, uaddrlen );
1070 uin->sir_family = AF_IRDA;
1071 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1073 unsigned int lsap_sel;
1075 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1076 uin->sir_lsap_sel = lsap_sel;
1080 uin->sir_lsap_sel = LSAP_ANY;
1081 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1083 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1087 case WS_AF_UNSPEC: {
1088 /* Try to determine the needed space by the passed windows sockaddr space */
1089 switch (wsaddrlen) {
1090 default: /* likely a ipv4 address */
1091 case sizeof(struct WS_sockaddr_in):
1092 uaddrlen = sizeof(struct sockaddr_in);
1095 case sizeof(struct WS_sockaddr_ipx):
1096 uaddrlen = sizeof(struct sockaddr_ipx);
1100 case sizeof(SOCKADDR_IRDA):
1101 uaddrlen = sizeof(struct sockaddr_irda);
1104 case sizeof(struct WS_sockaddr_in6):
1105 case sizeof(struct WS_sockaddr_in6_old):
1106 uaddrlen = sizeof(struct sockaddr_in6);
1109 memset( uaddr, 0, uaddrlen );
1113 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1119 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1121 switch (uaddr->sa_family)
1125 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
1130 static const struct sockaddr_in6 emptyAddr;
1131 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1132 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1136 static const struct sockaddr_in emptyAddr;
1137 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1138 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1143 FIXME("unknown address family %d\n", uaddr->sa_family);
1148 /* Returns 0 if successful, -1 if the buffer is too small */
1149 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1153 switch(uaddr->sa_family)
1158 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1159 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1162 switch (*wsaddrlen) /* how much can we copy? */
1166 *wsaddrlen = sizeof(*wsipx);
1167 wsipx->sa_socket=uipx->sipx_port;
1171 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1179 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1185 wsipx->sa_family=WS_AF_IPX;
1197 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1198 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1200 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1202 win->irdaAddressFamily = WS_AF_IRDA;
1203 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1204 if (uin->sir_lsap_sel != LSAP_ANY)
1205 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1207 memcpy( win->irdaServiceName, uin->sir_name,
1208 sizeof(win->irdaServiceName) );
1213 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1214 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1216 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1218 win6old->sin6_family = WS_AF_INET6;
1219 win6old->sin6_port = uin6->sin6_port;
1220 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1221 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1222 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1223 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1224 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1225 win6->sin6_scope_id = uin6->sin6_scope_id;
1226 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1229 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1231 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1236 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1237 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1239 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1241 win->sin_family = WS_AF_INET;
1242 win->sin_port = uin->sin_port;
1243 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1244 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1245 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1249 memset(wsaddr,0,*wsaddrlen);
1253 FIXME("Unknown address family %d\n", uaddr->sa_family);
1259 /**************************************************************************
1260 * Functions for handling overlapped I/O
1261 **************************************************************************/
1263 /* user APC called upon async completion */
1264 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1266 ws2_async *wsa = arg;
1268 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1269 iosb->Information, wsa->user_overlapped,
1271 HeapFree( GetProcessHeap(), 0, wsa );
1274 /***********************************************************************
1275 * WS2_recv (INTERNAL)
1277 * Workhorse for both synchronous and asynchronous recv() operations.
1279 static int WS2_recv( int fd, struct ws2_async *wsa )
1282 union generic_unix_sockaddr unix_sockaddr;
1285 hdr.msg_name = NULL;
1289 hdr.msg_namelen = sizeof(unix_sockaddr);
1290 hdr.msg_name = &unix_sockaddr;
1293 hdr.msg_namelen = 0;
1295 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1296 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1297 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1298 hdr.msg_accrights = NULL;
1299 hdr.msg_accrightslen = 0;
1301 hdr.msg_control = NULL;
1302 hdr.msg_controllen = 0;
1306 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1309 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1310 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1312 * quoting linux 2.6 net/ipv4/tcp.c:
1313 * "According to UNIX98, msg_name/msg_namelen are ignored
1314 * on connected socket. I was just happy when found this 8) --ANK"
1316 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1317 * connection-oriented sockets, so don't try to update lpFrom.
1319 if (wsa->addr && hdr.msg_namelen)
1320 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1325 /***********************************************************************
1326 * WS2_async_recv (INTERNAL)
1328 * Handler for overlapped recv() operations.
1330 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1332 ws2_async* wsa = user;
1337 case STATUS_ALERTED:
1338 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1341 result = WS2_recv( fd, wsa );
1342 wine_server_release_fd( wsa->hSocket, fd );
1345 status = STATUS_SUCCESS;
1346 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1350 if (errno == EINTR || errno == EAGAIN)
1352 status = STATUS_PENDING;
1353 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1358 status = wsaErrno(); /* FIXME: is this correct ???? */
1363 if (status != STATUS_PENDING)
1365 iosb->u.Status = status;
1366 iosb->Information = result;
1367 *apc = ws2_async_apc;
1372 /***********************************************************************
1373 * WS2_send (INTERNAL)
1375 * Workhorse for both synchronous and asynchronous send() operations.
1377 static int WS2_send( int fd, struct ws2_async *wsa )
1380 union generic_unix_sockaddr unix_addr;
1382 hdr.msg_name = NULL;
1383 hdr.msg_namelen = 0;
1387 hdr.msg_name = &unix_addr;
1388 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
1389 if ( !hdr.msg_namelen )
1395 #if defined(HAVE_IPX) && defined(SOL_IPX)
1396 if(wsa->addr->sa_family == WS_AF_IPX)
1398 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1400 unsigned int len=sizeof(int);
1402 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1403 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1404 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1405 * ipx type in the sockaddr_opx structure with the stored value.
1407 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1408 uipx->sipx_type = val;
1413 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1414 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1415 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1416 hdr.msg_accrights = NULL;
1417 hdr.msg_accrightslen = 0;
1419 hdr.msg_control = NULL;
1420 hdr.msg_controllen = 0;
1424 return sendmsg(fd, &hdr, wsa->flags);
1427 /***********************************************************************
1428 * WS2_async_send (INTERNAL)
1430 * Handler for overlapped send() operations.
1432 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1434 ws2_async* wsa = user;
1439 case STATUS_ALERTED:
1440 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1443 /* check to see if the data is ready (non-blocking) */
1444 result = WS2_send( fd, wsa );
1445 wine_server_release_fd( wsa->hSocket, fd );
1449 int totalLength = 0;
1451 status = STATUS_SUCCESS;
1452 for (i = 0; i < wsa->n_iovecs; i++)
1453 totalLength += wsa->iovec[i].iov_len;
1454 if (result < totalLength)
1455 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1459 if (errno == EINTR || errno == EAGAIN)
1461 status = STATUS_PENDING;
1462 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1466 /* We set the status to a winsock error code and check for that
1467 later in NtStatusToWSAError () */
1468 status = wsaErrno();
1474 if (status != STATUS_PENDING)
1476 iosb->u.Status = status;
1477 iosb->Information = result;
1478 *apc = ws2_async_apc;
1483 /***********************************************************************
1484 * WS2_async_shutdown (INTERNAL)
1486 * Handler for shutdown() operations on overlapped sockets.
1488 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
1490 ws2_async* wsa = user;
1495 case STATUS_ALERTED:
1496 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1499 switch ( wsa->type )
1501 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1502 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1504 wine_server_release_fd( wsa->hSocket, fd );
1505 status = err ? wsaErrno() : STATUS_SUCCESS;
1508 iosb->u.Status = status;
1509 iosb->Information = 0;
1510 *apc = ws2_async_apc;
1514 /***********************************************************************
1515 * WS2_register_async_shutdown (INTERNAL)
1517 * Helper function for WS_shutdown() on overlapped sockets.
1519 static int WS2_register_async_shutdown( SOCKET s, int type )
1521 struct ws2_async *wsa;
1524 TRACE("s %ld type %d\n", s, type);
1526 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1530 wsa->hSocket = SOCKET2HANDLE(s);
1532 wsa->completion_func = NULL;
1534 SERVER_START_REQ( register_async )
1537 req->async.handle = wine_server_obj_handle( wsa->hSocket );
1538 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
1539 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
1540 req->async.arg = wine_server_client_ptr( wsa );
1541 req->async.cvalue = 0;
1542 status = wine_server_call( req );
1546 if (status != STATUS_PENDING)
1548 HeapFree( GetProcessHeap(), 0, wsa );
1549 return NtStatusToWSAError( status );
1554 /***********************************************************************
1557 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1564 TRACE("socket %04lx\n", s );
1565 is_blocking = _is_blocking(s);
1568 /* try accepting first (if there is a deferred connection) */
1569 SERVER_START_REQ( accept_socket )
1571 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1572 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1573 req->attributes = OBJ_INHERIT;
1574 status = wine_server_call( req );
1575 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
1580 if (addr) WS_getpeername(as, addr, addrlen32);
1583 if (is_blocking && status == WSAEWOULDBLOCK)
1585 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1587 do_block(fd, POLLIN, -1);
1588 _sync_sock_state(s); /* let wineserver notice connection */
1589 release_sock_fd( s, fd );
1591 } while (is_blocking && status == WSAEWOULDBLOCK);
1594 return INVALID_SOCKET;
1597 /***********************************************************************
1600 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1602 int fd = get_sock_fd( s, 0, NULL );
1603 int res = SOCKET_ERROR;
1605 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1609 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
1611 SetLastError(WSAEAFNOSUPPORT);
1615 union generic_unix_sockaddr uaddr;
1616 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1619 SetLastError(WSAEFAULT);
1624 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
1625 if (name->sa_family == WS_AF_INET6 &&
1626 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
1629 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
1631 release_sock_fd( s, fd );
1632 SetLastError(WSAEAFNOSUPPORT);
1633 return SOCKET_ERROR;
1637 if (name->sa_family == WS_AF_INET)
1639 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1640 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1642 /* Trying to bind to the default host interface, using
1643 * INADDR_ANY instead*/
1644 WARN("Trying to bind to magic IP address, using "
1645 "INADDR_ANY instead.\n");
1646 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
1649 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
1651 int loc_errno = errno;
1652 WARN("\tfailure - errno = %i\n", errno);
1657 SetLastError(WSAENOTSOCK);
1660 SetLastError(WSAEINVAL);
1663 SetLastError(wsaErrno());
1669 res=0; /* success */
1673 release_sock_fd( s, fd );
1678 /***********************************************************************
1679 * closesocket (WS2_32.3)
1681 int WINAPI WS_closesocket(SOCKET s)
1683 TRACE("socket %04lx\n", s);
1684 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
1685 return SOCKET_ERROR;
1688 /***********************************************************************
1689 * connect (WS2_32.4)
1691 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1693 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1695 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1699 union generic_unix_sockaddr uaddr;
1700 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1704 SetLastError(WSAEFAULT);
1708 if (name->sa_family == WS_AF_INET)
1710 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1711 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1713 /* Trying to connect to magic replace-loopback address,
1714 * assuming we really want to connect to localhost */
1715 TRACE("Trying to connect to magic IP address, using "
1716 "INADDR_LOOPBACK instead.\n");
1717 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
1721 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
1722 goto connect_success;
1725 if (errno == EINPROGRESS)
1727 /* tell wineserver that a connection is in progress */
1728 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1729 FD_CONNECT|FD_READ|FD_WRITE,
1730 FD_WINE_CONNECTED|FD_WINE_LISTENING);
1731 if (_is_blocking(s))
1735 do_block(fd, POLLIN | POLLOUT, -1);
1736 _sync_sock_state(s); /* let wineserver notice connection */
1737 /* retrieve any error codes from it */
1738 result = _get_sock_error(s, FD_CONNECT_BIT);
1740 SetLastError(result);
1743 goto connect_success;
1748 SetLastError(WSAEWOULDBLOCK);
1753 SetLastError(wsaErrno());
1755 release_sock_fd( s, fd );
1757 return SOCKET_ERROR;
1760 release_sock_fd( s, fd );
1761 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1762 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1763 FD_CONNECT|FD_WINE_LISTENING);
1767 /***********************************************************************
1768 * WSAConnect (WS2_32.30)
1770 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
1771 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1772 LPQOS lpSQOS, LPQOS lpGQOS )
1774 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1775 FIXME("unsupported parameters!\n");
1776 return WS_connect( s, name, namelen );
1780 /***********************************************************************
1781 * getpeername (WS2_32.5)
1783 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1788 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, *namelen);
1790 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1791 if( (name == NULL) || (namelen == NULL) )
1793 SetLastError( WSAEFAULT );
1794 return SOCKET_ERROR;
1797 fd = get_sock_fd( s, 0, NULL );
1802 union generic_unix_sockaddr uaddr;
1803 unsigned int uaddrlen = sizeof(uaddr);
1805 if (getpeername(fd, &uaddr.addr, &uaddrlen) != 0)
1807 SetLastError(wsaErrno());
1809 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1811 /* The buffer was too small */
1812 SetLastError(WSAEFAULT);
1818 release_sock_fd( s, fd );
1823 /***********************************************************************
1824 * getsockname (WS2_32.6)
1826 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1831 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
1833 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1834 if( (name == NULL) || (namelen == NULL) )
1836 SetLastError( WSAEFAULT );
1837 return SOCKET_ERROR;
1840 fd = get_sock_fd( s, 0, NULL );
1845 union generic_unix_sockaddr uaddr;
1846 unsigned int uaddrlen = sizeof(uaddr);
1848 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
1850 SetLastError(wsaErrno());
1852 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
1854 SetLastError(WSAEINVAL);
1856 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1858 /* The buffer was too small */
1859 SetLastError(WSAEFAULT);
1865 release_sock_fd( s, fd );
1870 /***********************************************************************
1871 * getsockopt (WS2_32.7)
1873 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1874 INT optname, char *optval, INT *optlen)
1879 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
1880 s, level, optname, optval, *optlen);
1888 /* Handle common cases. The special cases are below, sorted
1890 case WS_SO_ACCEPTCONN:
1891 case WS_SO_BROADCAST:
1894 case WS_SO_KEEPALIVE:
1895 case WS_SO_OOBINLINE:
1897 case WS_SO_REUSEADDR:
1900 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1901 return SOCKET_ERROR;
1902 convert_sockopt(&level, &optname);
1903 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1905 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1908 release_sock_fd( s, fd );
1911 case WS_SO_DONTLINGER:
1913 struct linger lingval;
1914 unsigned int len = sizeof(struct linger);
1916 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
1918 SetLastError(WSAEFAULT);
1919 return SOCKET_ERROR;
1921 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1922 return SOCKET_ERROR;
1924 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1926 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1931 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
1932 *optlen = sizeof(BOOL);
1935 release_sock_fd( s, fd );
1939 /* As mentioned in setsockopt, Windows ignores this, so we
1940 * always return true here */
1941 case WS_SO_DONTROUTE:
1942 if (!optlen || *optlen < sizeof(BOOL) || !optval)
1944 SetLastError(WSAEFAULT);
1945 return SOCKET_ERROR;
1947 *(BOOL *)optval = TRUE;
1948 *optlen = sizeof(BOOL);
1953 struct linger lingval;
1954 unsigned int len = sizeof(struct linger);
1956 /* struct linger and LINGER have different sizes */
1957 if (!optlen || *optlen < sizeof(LINGER) || !optval)
1959 SetLastError(WSAEFAULT);
1960 return SOCKET_ERROR;
1962 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1963 return SOCKET_ERROR;
1965 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1967 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1972 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
1973 ((LINGER *)optval)->l_linger = lingval.l_linger;
1974 *optlen = sizeof(struct linger);
1977 release_sock_fd( s, fd );
1981 case WS_SO_MAX_MSG_SIZE:
1982 if (!optlen || *optlen < sizeof(int) || !optval)
1984 SetLastError(WSAEFAULT);
1985 return SOCKET_ERROR;
1987 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
1988 *(int *)optval = 65507;
1989 *optlen = sizeof(int);
1992 /* SO_OPENTYPE does not require a valid socket handle. */
1993 case WS_SO_OPENTYPE:
1994 if (!optlen || *optlen < sizeof(int) || !optval)
1996 SetLastError(WSAEFAULT);
1997 return SOCKET_ERROR;
1999 *(int *)optval = get_per_thread_data()->opentype;
2000 *optlen = sizeof(int);
2001 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2005 case WS_SO_RCVTIMEO:
2008 case WS_SO_SNDTIMEO:
2010 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
2013 unsigned int len = sizeof(struct timeval);
2015 if (!optlen || *optlen < sizeof(int)|| !optval)
2017 SetLastError(WSAEFAULT);
2018 return SOCKET_ERROR;
2020 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2021 return SOCKET_ERROR;
2023 convert_sockopt(&level, &optname);
2024 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
2026 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2031 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
2032 *optlen = sizeof(int);
2035 release_sock_fd( s, fd );
2040 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
2041 SetLastError(WSAENOPROTOOPT);
2042 return SOCKET_ERROR;
2043 } /* end switch(optname) */
2044 }/* end case WS_SOL_SOCKET */
2048 struct WS_sockaddr_ipx addr;
2049 IPX_ADDRESS_DATA *data;
2054 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
2056 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
2063 socklen_t len=sizeof(struct ipx);
2064 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
2067 *optval = (int)val.ipx_pt;
2070 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
2071 release_sock_fd( s, fd );
2076 * On a Win2000 system with one network card there are usually
2077 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
2078 * Using this call you can then retrieve info about this all.
2079 * In case of Linux it is a bit different. Usually you have
2080 * only "one" device active and further it is not possible to
2081 * query things like the linkspeed.
2083 FIXME("IPX_ADDRESS\n");
2084 namelen = sizeof(struct WS_sockaddr_ipx);
2085 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
2086 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
2088 data = (IPX_ADDRESS_DATA*)optval;
2089 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
2090 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
2091 data->adapternum = 0;
2092 data->wan = FALSE; /* We are not on a wan for now .. */
2093 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
2094 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
2095 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
2096 * note 1MB = 1000kB in this case */
2099 case IPX_MAX_ADAPTER_NUM:
2100 FIXME("IPX_MAX_ADAPTER_NUM\n");
2101 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
2105 FIXME("IPX optname:%x\n", optname);
2106 return SOCKET_ERROR;
2107 }/* end switch(optname) */
2108 } /* end case NSPROTO_IPX */
2115 case WS_IRLMP_ENUMDEVICES:
2117 static const int MAX_IRDA_DEVICES = 10;
2118 char buf[sizeof(struct irda_device_list) +
2119 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
2121 socklen_t len = sizeof(buf);
2123 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2124 return SOCKET_ERROR;
2125 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
2128 SetLastError(wsaErrno());
2129 return SOCKET_ERROR;
2133 struct irda_device_list *src = (struct irda_device_list *)buf;
2134 DEVICELIST *dst = (DEVICELIST *)optval;
2135 INT needed = sizeof(DEVICELIST), i;
2138 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
2139 if (*optlen < needed)
2141 SetLastError(WSAEFAULT);
2142 return SOCKET_ERROR;
2145 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
2146 dst->numDevice = src->len;
2147 for (i = 0; i < src->len; i++)
2149 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
2150 src->dev[i].saddr, src->dev[i].daddr,
2151 src->dev[i].info, src->dev[i].hints[0],
2152 src->dev[i].hints[1]);
2153 memcpy( dst->Device[i].irdaDeviceID,
2155 sizeof(dst->Device[i].irdaDeviceID) ) ;
2156 memcpy( dst->Device[i].irdaDeviceName,
2158 sizeof(dst->Device[i].irdaDeviceName) ) ;
2159 memcpy( &dst->Device[i].irdaDeviceHints1,
2160 &src->dev[i].hints[0],
2161 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
2162 memcpy( &dst->Device[i].irdaDeviceHints2,
2163 &src->dev[i].hints[1],
2164 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
2165 dst->Device[i].irdaCharSet = src->dev[i].charset;
2171 FIXME("IrDA optname:0x%x\n", optname);
2172 return SOCKET_ERROR;
2174 break; /* case WS_SOL_IRLMP */
2177 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
2178 case WS_IPPROTO_TCP:
2181 case WS_TCP_NODELAY:
2182 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2183 return SOCKET_ERROR;
2184 convert_sockopt(&level, &optname);
2185 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2187 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2190 release_sock_fd( s, fd );
2193 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
2194 return SOCKET_ERROR;
2199 case WS_IP_ADD_MEMBERSHIP:
2200 case WS_IP_DROP_MEMBERSHIP:
2204 case WS_IP_MULTICAST_IF:
2205 case WS_IP_MULTICAST_LOOP:
2206 case WS_IP_MULTICAST_TTL:
2210 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2211 return SOCKET_ERROR;
2212 convert_sockopt(&level, &optname);
2213 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2215 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2218 release_sock_fd( s, fd );
2220 case WS_IP_DONTFRAGMENT:
2221 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
2222 *(BOOL*)optval = FALSE;
2225 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
2226 return SOCKET_ERROR;
2228 case WS_IPPROTO_IPV6:
2229 FIXME("IPPROTO_IPV6 unimplemented (optname 0x%08x)\n", optname);
2230 return SOCKET_ERROR;
2233 WARN("Unknown level: 0x%08x\n", level);
2234 SetLastError(WSAEINVAL);
2235 return SOCKET_ERROR;
2236 } /* end switch(level) */
2239 /***********************************************************************
2242 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
2244 return htonl(hostlong);
2248 /***********************************************************************
2251 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
2253 return htons(hostshort);
2256 /***********************************************************************
2257 * WSAHtonl (WS2_32.46)
2258 * From MSDN description of error codes, this function should also
2259 * check if WinSock has been initialized and the socket is a valid
2260 * socket. But why? This function only translates a host byte order
2261 * u_long into a network byte order u_long...
2263 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
2267 *lpnetlong = htonl(hostlong);
2270 WSASetLastError(WSAEFAULT);
2271 return SOCKET_ERROR;
2274 /***********************************************************************
2275 * WSAHtons (WS2_32.47)
2276 * From MSDN description of error codes, this function should also
2277 * check if WinSock has been initialized and the socket is a valid
2278 * socket. But why? This function only translates a host byte order
2279 * u_short into a network byte order u_short...
2281 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2286 *lpnetshort = htons(hostshort);
2289 WSASetLastError(WSAEFAULT);
2290 return SOCKET_ERROR;
2294 /***********************************************************************
2295 * inet_addr (WS2_32.11)
2297 WS_u_long WINAPI WS_inet_addr(const char *cp)
2299 if (!cp) return INADDR_NONE;
2300 return inet_addr(cp);
2304 /***********************************************************************
2307 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2309 return ntohl(netlong);
2313 /***********************************************************************
2316 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2318 return ntohs(netshort);
2322 /***********************************************************************
2323 * inet_ntoa (WS2_32.12)
2325 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2327 /* use "buffer for dummies" here because some applications have a
2328 * propensity to decode addresses in ws_hostent structure without
2329 * saving them first...
2331 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2333 char* s = inet_ntoa(*((struct in_addr*)&in));
2339 SetLastError(wsaErrno());
2343 /**********************************************************************
2344 * WSAIoctl (WS2_32.50)
2347 INT WINAPI WSAIoctl(SOCKET s,
2348 DWORD dwIoControlCode,
2351 LPVOID lpbOutBuffer,
2353 LPDWORD lpcbBytesReturned,
2354 LPWSAOVERLAPPED lpOverlapped,
2355 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2357 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
2358 s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpbOutBuffer,
2359 cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
2361 switch( dwIoControlCode )
2364 if (cbInBuffer != sizeof(WS_u_long)) {
2365 WSASetLastError(WSAEFAULT);
2366 return SOCKET_ERROR;
2368 return WS_ioctlsocket( s, WS_FIONBIO, lpvInBuffer);
2371 if (cbOutBuffer != sizeof(WS_u_long)) {
2372 WSASetLastError(WSAEFAULT);
2373 return SOCKET_ERROR;
2375 return WS_ioctlsocket( s, WS_FIONREAD, lpbOutBuffer);
2377 case WS_SIO_GET_INTERFACE_LIST:
2379 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
2380 DWORD size, numInt, apiReturn;
2383 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
2387 WSASetLastError(WSAEFAULT);
2388 return SOCKET_ERROR;
2390 if (!lpcbBytesReturned)
2392 WSASetLastError(WSAEFAULT);
2393 return SOCKET_ERROR;
2396 fd = get_sock_fd( s, 0, NULL );
2397 if (fd == -1) return SOCKET_ERROR;
2399 apiReturn = GetAdaptersInfo(NULL, &size);
2400 if (apiReturn == ERROR_NO_DATA)
2404 else if (apiReturn == ERROR_BUFFER_OVERFLOW)
2406 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
2410 if (GetAdaptersInfo(table, &size) == NO_ERROR)
2412 PIP_ADAPTER_INFO ptr;
2414 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > cbOutBuffer)
2416 WARN("Buffer too small = %u, cbOutBuffer = %u\n", size, cbOutBuffer);
2417 HeapFree(GetProcessHeap(),0,table);
2418 release_sock_fd( s, fd );
2419 WSASetLastError(WSAEFAULT);
2420 return SOCKET_ERROR;
2422 for (ptr = table, numInt = 0; ptr;
2423 ptr = ptr->Next, intArray++, numInt++)
2425 unsigned int addr, mask, bcast;
2426 struct ifreq ifInfo;
2428 /* Socket Status Flags */
2429 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
2430 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2432 ERR("Error obtaining status flags for socket!\n");
2433 HeapFree(GetProcessHeap(),0,table);
2434 release_sock_fd( s, fd );
2435 WSASetLastError(WSAEINVAL);
2436 return SOCKET_ERROR;
2440 /* set flags; the values of IFF_* are not the same
2441 under Linux and Windows, therefore must generate
2443 intArray->iiFlags = 0;
2444 if (ifInfo.ifr_flags & IFF_BROADCAST)
2445 intArray->iiFlags |= WS_IFF_BROADCAST;
2446 #ifdef IFF_POINTOPOINT
2447 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
2448 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
2450 if (ifInfo.ifr_flags & IFF_LOOPBACK)
2451 intArray->iiFlags |= WS_IFF_LOOPBACK;
2452 if (ifInfo.ifr_flags & IFF_UP)
2453 intArray->iiFlags |= WS_IFF_UP;
2454 if (ifInfo.ifr_flags & IFF_MULTICAST)
2455 intArray->iiFlags |= WS_IFF_MULTICAST;
2458 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
2459 mask = inet_addr(ptr->IpAddressList.IpMask.String);
2460 bcast = addr | ~mask;
2461 intArray->iiAddress.AddressIn.sin_family = AF_INET;
2462 intArray->iiAddress.AddressIn.sin_port = 0;
2463 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
2465 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2466 intArray->iiNetmask.AddressIn.sin_port = 0;
2467 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
2469 intArray->iiBroadcastAddress.AddressIn.sin_family =
2471 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
2472 intArray->iiBroadcastAddress.AddressIn.sin_addr.
2478 ERR("Unable to get interface table!\n");
2479 release_sock_fd( s, fd );
2480 HeapFree(GetProcessHeap(),0,table);
2481 WSASetLastError(WSAEINVAL);
2482 return SOCKET_ERROR;
2484 HeapFree(GetProcessHeap(),0,table);
2488 release_sock_fd( s, fd );
2489 WSASetLastError(WSAEINVAL);
2490 return SOCKET_ERROR;
2495 ERR("Unable to get interface table!\n");
2496 release_sock_fd( s, fd );
2497 WSASetLastError(WSAEINVAL);
2498 return SOCKET_ERROR;
2500 /* Calculate the size of the array being returned */
2501 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2502 release_sock_fd( s, fd );
2506 case WS_SIO_ADDRESS_LIST_CHANGE:
2507 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
2508 /* FIXME: error and return code depend on whether socket was created
2509 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
2512 case WS_SIO_ADDRESS_LIST_QUERY:
2516 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
2518 if (!lpcbBytesReturned)
2520 WSASetLastError(WSAEFAULT);
2521 return SOCKET_ERROR;
2524 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
2526 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
2529 if (!table || GetAdaptersInfo(table, &size))
2531 HeapFree(GetProcessHeap(), 0, table);
2532 WSASetLastError(WSAEINVAL);
2533 return SOCKET_ERROR;
2536 for (p = table, num = 0; p; p = p->Next)
2537 if (p->IpAddressList.IpAddress.String[0]) num++;
2539 need = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
2540 need += sizeof(SOCKADDR) * num;
2541 *lpcbBytesReturned = need;
2543 if (need > cbOutBuffer)
2545 HeapFree(GetProcessHeap(), 0, table);
2546 WSASetLastError(WSAEFAULT);
2547 return SOCKET_ERROR;
2554 SOCKET_ADDRESS_LIST *sa_list = (SOCKET_ADDRESS_LIST *)lpbOutBuffer;
2555 SOCKADDR_IN *sockaddr;
2557 sa = sa_list->Address;
2558 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
2559 sa_list->iAddressCount = num;
2561 for (p = table, i = 0; p; p = p->Next)
2563 if (!p->IpAddressList.IpAddress.String[0]) continue;
2565 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
2566 sa[i].iSockaddrLength = sizeof(SOCKADDR);
2568 sockaddr[i].sin_family = AF_INET;
2569 sockaddr[i].sin_port = 0;
2570 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
2575 HeapFree(GetProcessHeap(), 0, table);
2580 WARN("unable to get IP address list\n");
2581 WSASetLastError(WSAEINVAL);
2582 return SOCKET_ERROR;
2586 FIXME("SIO_FLUSH: stub.\n");
2589 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
2590 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(lpvInBuffer));
2591 WSASetLastError(WSAEOPNOTSUPP);
2592 return SOCKET_ERROR;
2594 case WS_SIO_KEEPALIVE_VALS:
2597 struct tcp_keepalive *k = lpvInBuffer;
2598 int keepalive = k->onoff ? 1 : 0;
2599 int keepidle = k->keepalivetime / 1000;
2600 int keepintvl = k->keepaliveinterval / 1000;
2604 WSASetLastError(WSAEINVAL);
2605 return SOCKET_ERROR;
2608 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
2610 fd = get_sock_fd(s, 0, NULL);
2611 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
2613 release_sock_fd(s, fd);
2614 WSASetLastError(WSAEINVAL);
2615 return SOCKET_ERROR;
2617 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
2618 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
2620 release_sock_fd(s, fd);
2621 WSASetLastError(WSAEINVAL);
2622 return SOCKET_ERROR;
2624 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
2626 release_sock_fd(s, fd);
2627 WSASetLastError(WSAEINVAL);
2628 return SOCKET_ERROR;
2631 FIXME("ignoring keepalive interval and timeout\n");
2634 release_sock_fd(s, fd);
2638 FIXME("unsupported WS_IOCTL cmd (%08x)\n", dwIoControlCode);
2639 WSASetLastError(WSAEOPNOTSUPP);
2640 return SOCKET_ERROR;
2647 /***********************************************************************
2648 * ioctlsocket (WS2_32.10)
2650 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
2655 TRACE("socket %04lx, cmd %08x, ptr %p\n", s, cmd, argp);
2656 /* broken apps like defcon pass the argp value directly instead of a pointer to it */
2657 if(IS_INTRESOURCE(argp))
2659 SetLastError(WSAEFAULT);
2660 return SOCKET_ERROR;
2670 if( _get_sock_mask(s) )
2672 /* AsyncSelect()'ed sockets are always nonblocking */
2673 if (*argp) return 0;
2674 SetLastError(WSAEINVAL);
2675 return SOCKET_ERROR;
2678 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
2680 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
2688 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2689 SetLastError(WSAEINVAL);
2690 return SOCKET_ERROR;
2692 case SIOCGIFBRDADDR:
2693 case SIOCGIFNETMASK:
2695 /* These don't need any special handling. They are used by
2696 WsControl, and are here to suppress an unnecessary warning. */
2700 /* Netscape tries hard to use bogus ioctl 0x667e */
2701 /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
2702 * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
2704 WARN("\tunknown WS_IOCTL cmd (%08x)\n", cmd);
2708 fd = get_sock_fd( s, 0, NULL );
2711 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2713 release_sock_fd( s, fd );
2716 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2717 release_sock_fd( s, fd );
2719 return SOCKET_ERROR;
2722 /***********************************************************************
2723 * listen (WS2_32.13)
2725 int WINAPI WS_listen(SOCKET s, int backlog)
2727 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2729 TRACE("socket %04lx, backlog %d\n", s, backlog);
2732 if (listen(fd, backlog) == 0)
2734 release_sock_fd( s, fd );
2735 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
2737 FD_CONNECT|FD_WINE_CONNECTED);
2740 SetLastError(wsaErrno());
2741 release_sock_fd( s, fd );
2743 return SOCKET_ERROR;
2746 /***********************************************************************
2749 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2751 DWORD n, dwFlags = flags;
2757 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2758 return SOCKET_ERROR;
2763 /***********************************************************************
2764 * recvfrom (WS2_32.17)
2766 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2767 struct WS_sockaddr *from, int *fromlen)
2769 DWORD n, dwFlags = flags;
2775 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2776 return SOCKET_ERROR;
2781 /* allocate a poll array for the corresponding fd sets */
2782 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
2783 const WS_fd_set *exceptfds, int *count_ptr )
2785 unsigned int i, j = 0, count = 0;
2788 if (readfds) count += readfds->fd_count;
2789 if (writefds) count += writefds->fd_count;
2790 if (exceptfds) count += exceptfds->fd_count;
2792 if (!count) return NULL;
2793 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0])))) return NULL;
2795 for (i = 0; i < readfds->fd_count; i++, j++)
2797 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
2798 fds[j].events = POLLIN;
2802 for (i = 0; i < writefds->fd_count; i++, j++)
2804 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
2805 fds[j].events = POLLOUT;
2809 for (i = 0; i < exceptfds->fd_count; i++, j++)
2811 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
2812 fds[j].events = POLLHUP;
2818 /* release the file descriptor obtained in fd_sets_to_poll */
2819 /* must be called with the original fd_set arrays, before calling get_poll_results */
2820 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
2821 const WS_fd_set *exceptfds, struct pollfd *fds )
2823 unsigned int i, j = 0;
2827 for (i = 0; i < readfds->fd_count; i++, j++)
2828 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
2832 for (i = 0; i < writefds->fd_count; i++, j++)
2833 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
2837 for (i = 0; i < exceptfds->fd_count; i++, j++)
2838 if (fds[j].fd != -1)
2840 /* make sure we have a real error before releasing the fd */
2841 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
2842 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
2847 /* map the poll results back into the Windows fd sets */
2848 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
2849 const struct pollfd *fds )
2851 unsigned int i, j = 0, k, total = 0;
2855 for (i = k = 0; i < readfds->fd_count; i++, j++)
2856 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
2857 readfds->fd_count = k;
2862 for (i = k = 0; i < writefds->fd_count; i++, j++)
2863 if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
2864 writefds->fd_count = k;
2869 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
2870 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
2871 exceptfds->fd_count = k;
2878 /***********************************************************************
2879 * select (WS2_32.18)
2881 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
2882 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
2883 const struct WS_timeval* ws_timeout)
2885 struct pollfd *pollfds;
2886 int count, ret, timeout = -1;
2888 TRACE("read %p, write %p, excp %p timeout %p\n",
2889 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
2891 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )) && count)
2893 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2894 return SOCKET_ERROR;
2897 if (ws_timeout) timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
2899 ret = poll( pollfds, count, timeout );
2900 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2902 if (ret == -1) SetLastError(wsaErrno());
2903 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2904 HeapFree( GetProcessHeap(), 0, pollfds );
2908 /* helper to send completion messages for client-only i/o operation case */
2909 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
2914 SERVER_START_REQ( add_fd_completion )
2916 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
2917 req->cvalue = CompletionValue;
2918 req->status = CompletionStatus;
2919 req->information = Information;
2920 status = wine_server_call( req );
2926 /***********************************************************************
2929 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
2935 wsabuf.buf = (char*) buf;
2937 if ( WSASendTo( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
2938 return SOCKET_ERROR;
2943 /***********************************************************************
2944 * WSASend (WS2_32.72)
2946 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2947 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2948 LPWSAOVERLAPPED lpOverlapped,
2949 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2951 return WSASendTo( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
2952 NULL, 0, lpOverlapped, lpCompletionRoutine );
2955 /***********************************************************************
2956 * WSASendDisconnect (WS2_32.73)
2958 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
2960 return WS_shutdown( s, SD_SEND );
2964 /***********************************************************************
2965 * WSASendTo (WS2_32.74)
2967 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2968 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2969 const struct WS_sockaddr *to, int tolen,
2970 LPWSAOVERLAPPED lpOverlapped,
2971 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2973 unsigned int i, options;
2975 struct ws2_async *wsa;
2976 int totalLength = 0;
2977 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
2979 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
2980 s, lpBuffers, dwBufferCount, dwFlags,
2981 to, tolen, lpOverlapped, lpCompletionRoutine);
2983 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
2984 TRACE( "fd=%d, options=%x\n", fd, options );
2986 if ( fd == -1 ) return SOCKET_ERROR;
2988 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
2994 wsa->hSocket = SOCKET2HANDLE(s);
2995 wsa->addr = (struct WS_sockaddr *)to;
2996 wsa->addrlen.val = tolen;
2997 wsa->flags = dwFlags;
2998 wsa->n_iovecs = dwBufferCount;
2999 wsa->first_iovec = 0;
3000 for ( i = 0; i < dwBufferCount; i++ )
3002 wsa->iovec[i].iov_base = lpBuffers[i].buf;
3003 wsa->iovec[i].iov_len = lpBuffers[i].len;
3004 totalLength += lpBuffers[i].len;
3007 if (!lpNumberOfBytesSent)
3015 n = WS2_send( fd, wsa );
3016 if (n != -1 || errno != EINTR) break;
3018 if (n == -1 && errno != EAGAIN)
3021 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
3025 if ((lpOverlapped || lpCompletionRoutine) &&
3026 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3028 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
3030 wsa->user_overlapped = lpOverlapped;
3031 wsa->completion_func = lpCompletionRoutine;
3032 release_sock_fd( s, fd );
3036 iosb->u.Status = STATUS_PENDING;
3037 iosb->Information = 0;
3039 SERVER_START_REQ( register_async )
3041 req->type = ASYNC_TYPE_WRITE;
3042 req->async.handle = wine_server_obj_handle( wsa->hSocket );
3043 req->async.callback = wine_server_client_ptr( WS2_async_send );
3044 req->async.iosb = wine_server_client_ptr( iosb );
3045 req->async.arg = wine_server_client_ptr( wsa );
3046 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
3047 req->async.cvalue = cvalue;
3048 err = wine_server_call( req );
3052 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
3053 WSASetLastError( NtStatusToWSAError( err ));
3054 return SOCKET_ERROR;
3057 iosb->u.Status = STATUS_SUCCESS;
3058 iosb->Information = n;
3059 *lpNumberOfBytesSent = n;
3060 if (!wsa->completion_func)
3062 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
3063 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
3064 HeapFree( GetProcessHeap(), 0, wsa );
3066 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
3067 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
3072 if ( _is_blocking(s) )
3074 /* On a blocking non-overlapped stream socket,
3075 * sending blocks until the entire buffer is sent. */
3076 DWORD timeout_start = GetTickCount();
3078 *lpNumberOfBytesSent = 0;
3080 while (wsa->first_iovec < dwBufferCount)
3083 int timeout = GET_SNDTIMEO(fd);
3087 *lpNumberOfBytesSent += n;
3088 while (wsa->first_iovec < dwBufferCount && wsa->iovec[wsa->first_iovec].iov_len <= n)
3089 n -= wsa->iovec[wsa->first_iovec++].iov_len;
3090 if (wsa->first_iovec >= dwBufferCount) break;
3091 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
3092 wsa->iovec[wsa->first_iovec].iov_len -= n;
3097 timeout -= GetTickCount() - timeout_start;
3098 if (timeout < 0) timeout = 0;
3102 pfd.events = POLLOUT;
3104 if (!timeout || !poll( &pfd, 1, timeout ))
3107 goto error; /* msdn says a timeout in send is fatal */
3110 n = WS2_send( fd, wsa );
3111 if (n == -1 && errno != EAGAIN && errno != EINTR)
3118 else /* non-blocking */
3120 if (n < totalLength)
3121 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
3124 err = WSAEWOULDBLOCK;
3127 *lpNumberOfBytesSent = n;
3130 TRACE(" -> %i bytes\n", *lpNumberOfBytesSent);
3132 HeapFree( GetProcessHeap(), 0, wsa );
3133 release_sock_fd( s, fd );
3138 HeapFree( GetProcessHeap(), 0, wsa );
3139 release_sock_fd( s, fd );
3140 WARN(" -> ERROR %d\n", err);
3141 WSASetLastError(err);
3142 return SOCKET_ERROR;
3145 /***********************************************************************
3146 * sendto (WS2_32.20)
3148 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
3149 const struct WS_sockaddr *to, int tolen)
3155 wsabuf.buf = (char*) buf;
3157 if ( WSASendTo(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
3158 return SOCKET_ERROR;
3163 /***********************************************************************
3164 * setsockopt (WS2_32.21)
3166 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
3167 const char *optval, int optlen)
3171 struct linger linger;
3172 struct timeval tval;
3174 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
3175 s, level, optname, optval, optlen);
3177 /* some broken apps pass the value directly instead of a pointer to it */
3178 if(IS_INTRESOURCE(optval))
3180 SetLastError(WSAEFAULT);
3181 return SOCKET_ERROR;
3189 /* Some options need some conversion before they can be sent to
3190 * setsockopt. The conversions are done here, then they will fall though
3191 * to the general case. Special options that are not passed to
3192 * setsockopt follow below that.*/
3194 case WS_SO_DONTLINGER:
3195 linger.l_onoff = *((const int*)optval) ? 0: 1;
3196 linger.l_linger = 0;
3198 optname = SO_LINGER;
3199 optval = (char*)&linger;
3200 optlen = sizeof(struct linger);
3204 linger.l_onoff = ((LINGER*)optval)->l_onoff;
3205 linger.l_linger = ((LINGER*)optval)->l_linger;
3206 /* FIXME: what is documented behavior if SO_LINGER optval
3209 optname = SO_LINGER;
3210 optval = (char*)&linger;
3211 optlen = sizeof(struct linger);
3215 if (*(const int*)optval < 2048)
3217 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
3222 /* The options listed here don't need any special handling. Thanks to
3223 * the conversion happening above, options from there will fall through
3225 case WS_SO_ACCEPTCONN:
3226 case WS_SO_BROADCAST:
3228 case WS_SO_KEEPALIVE:
3229 case WS_SO_OOBINLINE:
3230 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
3231 * however, using it the BSD way fixes bug 8513 and seems to be what
3232 * most programmers assume, anyway */
3233 case WS_SO_REUSEADDR:
3236 convert_sockopt(&level, &optname);
3239 /* SO_DEBUG is a privileged operation, ignore it. */
3241 TRACE("Ignoring SO_DEBUG\n");
3244 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
3245 * socket. According to MSDN, this option is silently ignored.*/
3246 case WS_SO_DONTROUTE:
3247 TRACE("Ignoring SO_DONTROUTE\n");
3250 /* Stops two sockets from being bound to the same port. Always happens
3251 * on unix systems, so just drop it. */
3252 case WS_SO_EXCLUSIVEADDRUSE:
3253 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
3256 /* SO_OPENTYPE does not require a valid socket handle. */
3257 case WS_SO_OPENTYPE:
3258 if (!optlen || optlen < sizeof(int) || !optval)
3260 SetLastError(WSAEFAULT);
3261 return SOCKET_ERROR;
3263 get_per_thread_data()->opentype = *(const int *)optval;
3264 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3268 case WS_SO_RCVTIMEO:
3271 case WS_SO_SNDTIMEO:
3273 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3274 if (optval && optlen == sizeof(UINT32)) {
3275 /* WinSock passes milliseconds instead of struct timeval */
3276 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
3277 tval.tv_sec = *(const UINT32*)optval / 1000;
3278 /* min of 500 milliseconds */
3279 if (tval.tv_sec == 0 && tval.tv_usec < 500000)
3280 tval.tv_usec = 500000;
3281 optlen = sizeof(struct timeval);
3282 optval = (char*)&tval;
3283 } else if (optlen == sizeof(struct timeval)) {
3284 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
3286 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
3289 convert_sockopt(&level, &optname);
3294 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3295 SetLastError(WSAENOPROTOOPT);
3296 return SOCKET_ERROR;
3298 break; /* case WS_SOL_SOCKET */
3305 fd = get_sock_fd( s, 0, NULL );
3306 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
3308 /* We try to set the ipx type on ipx socket level. */
3310 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
3312 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
3313 release_sock_fd( s, fd );
3314 return SOCKET_ERROR;
3319 /* Should we retrieve val using a getsockopt call and then
3320 * set the modified one? */
3321 val.ipx_pt = *optval;
3322 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
3325 release_sock_fd( s, fd );
3328 case IPX_FILTERPTYPE:
3329 /* Sets the receive filter packet type, at the moment we don't support it */
3330 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
3331 /* Returning 0 is better for now than returning a SOCKET_ERROR */
3335 FIXME("opt_name:%x\n", optname);
3336 return SOCKET_ERROR;
3338 break; /* case NSPROTO_IPX */
3341 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3342 case WS_IPPROTO_TCP:
3345 case WS_TCP_NODELAY:
3346 convert_sockopt(&level, &optname);
3349 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3350 return SOCKET_ERROR;
3357 case WS_IP_ADD_MEMBERSHIP:
3358 case WS_IP_DROP_MEMBERSHIP:
3362 case WS_IP_MULTICAST_IF:
3363 case WS_IP_MULTICAST_LOOP:
3364 case WS_IP_MULTICAST_TTL:
3368 convert_sockopt(&level, &optname);
3370 case WS_IP_DONTFRAGMENT:
3371 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
3374 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3375 return SOCKET_ERROR;
3380 WARN("Unknown level: 0x%08x\n", level);
3381 SetLastError(WSAEINVAL);
3382 return SOCKET_ERROR;
3383 } /* end switch(level) */
3385 /* avoid endianness issues if argument is a 16-bit int */
3386 if (optval && optlen < sizeof(int))
3388 woptval= *((const INT16 *) optval);
3389 optval= (char*) &woptval;
3392 fd = get_sock_fd( s, 0, NULL );
3393 if (fd == -1) return SOCKET_ERROR;
3395 if (setsockopt(fd, level, optname, optval, optlen) == 0)
3397 release_sock_fd( s, fd );
3400 TRACE("Setting socket error, %d\n", wsaErrno());
3401 SetLastError(wsaErrno());
3402 release_sock_fd( s, fd );
3404 return SOCKET_ERROR;
3407 /***********************************************************************
3408 * shutdown (WS2_32.22)
3410 int WINAPI WS_shutdown(SOCKET s, int how)
3412 int fd, err = WSAENOTSOCK;
3413 unsigned int options, clear_flags = 0;
3415 fd = get_sock_fd( s, 0, &options );
3416 TRACE("socket %04lx, how %i %x\n", s, how, options );
3419 return SOCKET_ERROR;
3423 case 0: /* drop receives */
3424 clear_flags |= FD_READ;
3426 case 1: /* drop sends */
3427 clear_flags |= FD_WRITE;
3429 case 2: /* drop all */
3430 clear_flags |= FD_READ|FD_WRITE;
3432 clear_flags |= FD_WINE_LISTENING;
3435 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3440 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3443 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3447 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3448 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3451 if (err) goto error;
3453 else /* non-overlapped mode */
3455 if ( shutdown( fd, how ) )
3462 release_sock_fd( s, fd );
3463 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3464 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
3468 release_sock_fd( s, fd );
3469 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3470 WSASetLastError( err );
3471 return SOCKET_ERROR;
3474 /***********************************************************************
3475 * socket (WS2_32.23)
3477 SOCKET WINAPI WS_socket(int af, int type, int protocol)
3479 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
3481 return WSASocketA( af, type, protocol, NULL, 0,
3482 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
3486 /***********************************************************************
3487 * gethostbyaddr (WS2_32.51)
3489 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
3491 struct WS_hostent *retval = NULL;
3492 struct hostent* host;
3494 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3497 struct hostent hostentry;
3500 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3502 int res = gethostbyaddr_r(addr, len, type,
3503 &hostentry, extrabuf, ebufsize, &host, &locerr);
3504 if( res != ERANGE) break;
3506 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3508 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3510 EnterCriticalSection( &csWSgetXXXbyYYY );
3511 host = gethostbyaddr(addr, len, type);
3512 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3514 if( host != NULL ) retval = WS_dup_he(host);
3515 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3516 HeapFree(GetProcessHeap(),0,extrabuf);
3518 LeaveCriticalSection( &csWSgetXXXbyYYY );
3520 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
3524 /***********************************************************************
3525 * gethostbyname (WS2_32.52)
3527 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
3529 struct WS_hostent *retval = NULL;
3530 struct hostent* host;
3531 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3534 struct hostent hostentry;
3535 int locerr = ENOBUFS;
3538 if( !name || !name[0]) {
3540 if( gethostname( buf, 100) == -1) {
3541 SetLastError( WSAENOBUFS); /* appropriate ? */
3545 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3547 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3549 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
3550 if( res != ERANGE) break;
3552 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3554 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3556 EnterCriticalSection( &csWSgetXXXbyYYY );
3557 host = gethostbyname(name);
3558 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3560 if (host) retval = WS_dup_he(host);
3561 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3562 HeapFree(GetProcessHeap(),0,extrabuf);
3564 LeaveCriticalSection( &csWSgetXXXbyYYY );
3566 if (retval && retval->h_addr_list[0][0] == 127 &&
3567 strcmp(name, "localhost") != 0)
3569 /* hostname != "localhost" but has loopback address. replace by our
3570 * special address.*/
3571 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
3573 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3578 /***********************************************************************
3579 * getprotobyname (WS2_32.53)
3581 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3583 struct WS_protoent* retval = NULL;
3584 #ifdef HAVE_GETPROTOBYNAME
3585 struct protoent* proto;
3586 EnterCriticalSection( &csWSgetXXXbyYYY );
3587 if( (proto = getprotobyname(name)) != NULL )
3589 retval = WS_dup_pe(proto);
3592 MESSAGE("protocol %s not found; You might want to add "
3593 "this to /etc/protocols\n", debugstr_a(name) );
3594 SetLastError(WSANO_DATA);
3596 LeaveCriticalSection( &csWSgetXXXbyYYY );
3598 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3603 /***********************************************************************
3604 * getprotobynumber (WS2_32.54)
3606 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3608 struct WS_protoent* retval = NULL;
3609 #ifdef HAVE_GETPROTOBYNUMBER
3610 struct protoent* proto;
3611 EnterCriticalSection( &csWSgetXXXbyYYY );
3612 if( (proto = getprotobynumber(number)) != NULL )
3614 retval = WS_dup_pe(proto);
3617 MESSAGE("protocol number %d not found; You might want to add "
3618 "this to /etc/protocols\n", number );
3619 SetLastError(WSANO_DATA);
3621 LeaveCriticalSection( &csWSgetXXXbyYYY );
3623 TRACE("%i ret %p\n", number, retval);
3628 /***********************************************************************
3629 * getservbyname (WS2_32.55)
3631 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3633 struct WS_servent* retval = NULL;
3634 struct servent* serv;
3636 char *proto_str = NULL;
3638 if (!(name_str = strdup_lower(name))) return NULL;
3640 if (proto && *proto)
3642 if (!(proto_str = strdup_lower(proto)))
3644 HeapFree( GetProcessHeap(), 0, name_str );
3649 EnterCriticalSection( &csWSgetXXXbyYYY );
3650 serv = getservbyname(name_str, proto_str);
3653 retval = WS_dup_se(serv);
3655 else SetLastError(WSANO_DATA);
3656 LeaveCriticalSection( &csWSgetXXXbyYYY );
3657 HeapFree( GetProcessHeap(), 0, proto_str );
3658 HeapFree( GetProcessHeap(), 0, name_str );
3659 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
3663 /***********************************************************************
3664 * freeaddrinfo (WS2_32.@)
3666 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
3669 struct WS_addrinfo *next;
3671 HeapFree(GetProcessHeap(),0,res->ai_canonname);
3672 HeapFree(GetProcessHeap(),0,res->ai_addr);
3673 next = res->ai_next;
3674 HeapFree(GetProcessHeap(),0,res);
3679 /* helper functions for getaddrinfo()/getnameinfo() */
3680 static int convert_aiflag_w2u(int winflags) {
3684 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3685 if (ws_aiflag_map[i][0] & winflags) {
3686 unixflags |= ws_aiflag_map[i][1];
3687 winflags &= ~ws_aiflag_map[i][0];
3690 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
3694 static int convert_niflag_w2u(int winflags) {
3698 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
3699 if (ws_niflag_map[i][0] & winflags) {
3700 unixflags |= ws_niflag_map[i][1];
3701 winflags &= ~ws_niflag_map[i][0];
3704 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
3708 static int convert_aiflag_u2w(int unixflags) {
3712 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3713 if (ws_aiflag_map[i][1] & unixflags) {
3714 winflags |= ws_aiflag_map[i][0];
3715 unixflags &= ~ws_aiflag_map[i][1];
3717 if (unixflags) /* will warn usually */
3718 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
3722 static int convert_eai_u2w(int unixret) {
3725 for (i=0;ws_eai_map[i][0];i++)
3726 if (ws_eai_map[i][1] == unixret)
3727 return ws_eai_map[i][0];
3731 /***********************************************************************
3732 * getaddrinfo (WS2_32.@)
3734 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
3736 #ifdef HAVE_GETADDRINFO
3737 struct addrinfo *unixaires = NULL;
3739 struct addrinfo unixhints, *punixhints = NULL;
3740 CHAR *node = NULL, *serv = NULL;
3743 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
3746 if (!(serv = strdup_lower(servname))) {
3747 HeapFree(GetProcessHeap(), 0, node);
3748 return WSA_NOT_ENOUGH_MEMORY;
3753 punixhints = &unixhints;
3755 memset(&unixhints, 0, sizeof(unixhints));
3756 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
3757 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
3758 punixhints->ai_family = 0;
3760 punixhints->ai_family = convert_af_w2u(hints->ai_family);
3761 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
3762 punixhints->ai_socktype = 0;
3764 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
3765 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
3766 punixhints->ai_protocol = 0;
3768 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
3771 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
3772 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
3774 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
3776 HeapFree(GetProcessHeap(), 0, node);
3777 HeapFree(GetProcessHeap(), 0, serv);
3780 struct addrinfo *xuai = unixaires;
3781 struct WS_addrinfo **xai = res;
3785 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
3791 *xai = ai;xai = &ai->ai_next;
3792 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
3793 ai->ai_family = convert_af_u2w(xuai->ai_family);
3794 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
3795 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
3796 if (xuai->ai_canonname) {
3797 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
3798 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
3799 if (!ai->ai_canonname)
3801 strcpy(ai->ai_canonname,xuai->ai_canonname);
3803 len = xuai->ai_addrlen;
3804 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
3807 ai->ai_addrlen = len;
3809 int winlen = ai->ai_addrlen;
3811 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
3812 ai->ai_addrlen = winlen;
3816 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
3819 ai->ai_addrlen = len;
3821 xuai = xuai->ai_next;
3823 freeaddrinfo(unixaires);
3825 result = convert_eai_u2w(result);
3831 if (*res) WS_freeaddrinfo(*res);
3832 if (unixaires) freeaddrinfo(unixaires);
3834 return WSA_NOT_ENOUGH_MEMORY;
3836 FIXME("getaddrinfo() failed, not found during buildtime.\n");
3841 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
3843 struct WS_addrinfoW *ret;
3845 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
3846 ret->ai_flags = ai->ai_flags;
3847 ret->ai_family = ai->ai_family;
3848 ret->ai_socktype = ai->ai_socktype;
3849 ret->ai_protocol = ai->ai_protocol;
3850 ret->ai_addrlen = ai->ai_addrlen;
3851 ret->ai_canonname = NULL;
3852 ret->ai_addr = NULL;
3853 ret->ai_next = NULL;
3854 if (ai->ai_canonname)
3856 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
3857 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
3859 HeapFree(GetProcessHeap(), 0, ret);
3862 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
3866 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
3868 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
3869 HeapFree(GetProcessHeap(), 0, ret);
3872 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
3877 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
3879 struct WS_addrinfoW *ret, *infoW;
3881 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
3882 while (info->ai_next)
3884 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
3889 infoW = infoW->ai_next;
3890 info = info->ai_next;
3895 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
3897 struct WS_addrinfo *ret;
3899 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
3900 ret->ai_flags = ai->ai_flags;
3901 ret->ai_family = ai->ai_family;
3902 ret->ai_socktype = ai->ai_socktype;
3903 ret->ai_protocol = ai->ai_protocol;
3904 ret->ai_addrlen = ai->ai_addrlen;
3905 ret->ai_canonname = NULL;
3906 ret->ai_addr = NULL;
3907 ret->ai_next = NULL;
3908 if (ai->ai_canonname)
3910 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
3911 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
3913 HeapFree(GetProcessHeap(), 0, ret);
3916 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
3920 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
3922 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
3923 HeapFree(GetProcessHeap(), 0, ret);
3926 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
3931 /***********************************************************************
3932 * GetAddrInfoW (WS2_32.@)
3934 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
3937 char *nodenameA, *servnameA = NULL;
3938 struct WS_addrinfo *resA, *hintsA = NULL;
3940 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
3941 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
3942 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
3946 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
3947 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
3949 HeapFree(GetProcessHeap(), 0, nodenameA);
3952 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
3955 if (hints) hintsA = addrinfo_WtoA(hints);
3956 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
3957 WS_freeaddrinfo(hintsA);
3961 *res = addrinfo_list_AtoW(resA);
3962 WS_freeaddrinfo(resA);
3965 HeapFree(GetProcessHeap(), 0, nodenameA);
3966 HeapFree(GetProcessHeap(), 0, servnameA);
3970 /***********************************************************************
3971 * FreeAddrInfoW (WS2_32.@)
3973 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
3978 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
3979 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
3981 HeapFree(GetProcessHeap(), 0, ai);
3986 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
3987 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
3989 #ifdef HAVE_GETNAMEINFO
3991 union generic_unix_sockaddr sa_u;
3994 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
3995 serv, servlen, flags);
3997 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
4000 WSASetLastError(WSAEFAULT);
4001 return WSA_NOT_ENOUGH_MEMORY;
4003 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
4004 return convert_eai_u2w(ret);
4006 FIXME("getnameinfo() failed, not found during buildtime.\n");
4011 /***********************************************************************
4012 * getservbyport (WS2_32.56)
4014 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
4016 struct WS_servent* retval = NULL;
4017 #ifdef HAVE_GETSERVBYPORT
4018 struct servent* serv;
4019 char *proto_str = NULL;
4021 if (proto && *proto)
4023 if (!(proto_str = strdup_lower(proto))) return NULL;
4025 EnterCriticalSection( &csWSgetXXXbyYYY );
4026 if( (serv = getservbyport(port, proto_str)) != NULL ) {
4027 retval = WS_dup_se(serv);
4029 else SetLastError(WSANO_DATA);
4030 LeaveCriticalSection( &csWSgetXXXbyYYY );
4031 HeapFree( GetProcessHeap(), 0, proto_str );
4033 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
4038 /***********************************************************************
4039 * gethostname (WS2_32.57)
4041 int WINAPI WS_gethostname(char *name, int namelen)
4043 TRACE("name %p, len %d\n", name, namelen);
4045 if (gethostname(name, namelen) == 0)
4047 TRACE("<- '%s'\n", name);
4050 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
4051 TRACE("<- ERROR !\n");
4052 return SOCKET_ERROR;
4056 /* ------------------------------------- Windows sockets extensions -- *
4058 * ------------------------------------------------------------------- */
4060 /***********************************************************************
4061 * WSAEnumNetworkEvents (WS2_32.36)
4063 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
4067 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
4069 SERVER_START_REQ( get_socket_event )
4071 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4072 req->service = TRUE;
4073 req->c_event = wine_server_obj_handle( hEvent );
4074 wine_server_set_reply( req, lpEvent->iErrorCode, sizeof(lpEvent->iErrorCode) );
4075 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
4079 SetLastError(WSAEINVAL);
4080 return SOCKET_ERROR;
4083 /***********************************************************************
4084 * WSAEventSelect (WS2_32.39)
4086 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
4090 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
4092 SERVER_START_REQ( set_socket_event )
4094 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4096 req->event = wine_server_obj_handle( hEvent );
4099 ret = wine_server_call( req );
4103 SetLastError(WSAEINVAL);
4104 return SOCKET_ERROR;
4107 /**********************************************************************
4108 * WSAGetOverlappedResult (WS2_32.40)
4110 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
4111 LPDWORD lpcbTransfer, BOOL fWait,
4116 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
4117 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
4119 if ( lpOverlapped == NULL )
4121 ERR( "Invalid pointer\n" );
4122 WSASetLastError(WSA_INVALID_PARAMETER);
4126 status = lpOverlapped->Internal;
4127 if (status == STATUS_PENDING)
4131 SetLastError( WSA_IO_INCOMPLETE );
4135 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
4136 INFINITE ) == WAIT_FAILED)
4138 status = lpOverlapped->Internal;
4142 *lpcbTransfer = lpOverlapped->InternalHigh;
4145 *lpdwFlags = lpOverlapped->u.s.Offset;
4147 if (status) SetLastError( RtlNtStatusToDosError(status) );
4152 /***********************************************************************
4153 * WSAAsyncSelect (WS2_32.101)
4155 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
4159 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
4161 SERVER_START_REQ( set_socket_event )
4163 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4166 req->window = wine_server_user_handle( hWnd );
4168 ret = wine_server_call( req );
4172 SetLastError(WSAEINVAL);
4173 return SOCKET_ERROR;
4176 /***********************************************************************
4177 * WSACreateEvent (WS2_32.31)
4180 WSAEVENT WINAPI WSACreateEvent(void)
4182 /* Create a manual-reset event, with initial state: unsignaled */
4185 return CreateEventW(NULL, TRUE, FALSE, NULL);
4188 /***********************************************************************
4189 * WSACloseEvent (WS2_32.29)
4192 BOOL WINAPI WSACloseEvent(WSAEVENT event)
4194 TRACE ("event=%p\n", event);
4196 return CloseHandle(event);
4199 /***********************************************************************
4200 * WSASocketA (WS2_32.78)
4203 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
4204 LPWSAPROTOCOL_INFOA lpProtocolInfo,
4205 GROUP g, DWORD dwFlags)
4208 WSAPROTOCOL_INFOW info;
4210 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
4211 af, type, protocol, lpProtocolInfo, g, dwFlags);
4213 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
4215 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
4216 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
4217 info.szProtocol, WSAPROTOCOL_LEN + 1);
4221 WSASetLastError( WSAEINVAL);
4222 return SOCKET_ERROR;
4225 return WSASocketW(af, type, protocol, &info, g, dwFlags);
4228 /***********************************************************************
4229 * WSASocketW (WS2_32.79)
4232 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
4233 LPWSAPROTOCOL_INFOW lpProtocolInfo,
4234 GROUP g, DWORD dwFlags)
4239 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
4240 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
4243 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
4244 af, type, protocol, lpProtocolInfo, g, dwFlags );
4246 /* hack for WSADuplicateSocket */
4247 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
4248 ret = lpProtocolInfo->dwCatalogEntryId;
4249 TRACE("\tgot duplicate %04lx\n", ret);
4253 /* convert the socket family and type */
4254 af = convert_af_w2u(af);
4255 type = convert_socktype_w2u(type);
4259 if (af == FROM_PROTOCOL_INFO)
4260 af = lpProtocolInfo->iAddressFamily;
4261 if (type == FROM_PROTOCOL_INFO)
4262 type = lpProtocolInfo->iSocketType;
4263 if (protocol == FROM_PROTOCOL_INFO)
4264 protocol = lpProtocolInfo->iProtocol;
4267 if ( af == AF_UNSPEC) /* did they not specify the address family? */
4271 if (type == SOCK_STREAM) { af = AF_INET; break; }
4273 if (type == SOCK_DGRAM) { af = AF_INET; break; }
4274 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
4277 SERVER_START_REQ( create_socket )
4281 req->protocol = protocol;
4282 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
4283 req->attributes = OBJ_INHERIT;
4284 req->flags = dwFlags;
4285 set_error( wine_server_call( req ) );
4286 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
4291 TRACE("\tcreated %04lx\n", ret );
4295 if (GetLastError() == WSAEACCES) /* raw socket denied */
4297 if (type == SOCK_RAW)
4298 MESSAGE("WARNING: Trying to create a socket of type SOCK_RAW, this"
4299 " will fail unless you have special permissions.\n");
4301 MESSAGE("WS_SOCKET: Failed to create socket, this requires"
4302 " special permissions.\n");
4303 SetLastError(WSAESOCKTNOSUPPORT);
4306 WARN("\t\tfailed!\n");
4307 return INVALID_SOCKET;
4310 /***********************************************************************
4311 * WSAJoinLeaf (WS2_32.58)
4314 SOCKET WINAPI WSAJoinLeaf(
4316 const struct WS_sockaddr *addr,
4318 LPWSABUF lpCallerData,
4319 LPWSABUF lpCalleeData,
4325 return INVALID_SOCKET;
4328 /***********************************************************************
4329 * __WSAFDIsSet (WS2_32.151)
4331 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
4333 int i = set->fd_count;
4335 TRACE("(%ld,%p(%i))\n", s, set, i);
4338 if (set->fd_array[i] == s) return 1;
4342 /***********************************************************************
4343 * WSAIsBlocking (WS2_32.114)
4345 BOOL WINAPI WSAIsBlocking(void)
4347 /* By default WinSock should set all its sockets to non-blocking mode
4348 * and poll in PeekMessage loop when processing "blocking" ones. This
4349 * function is supposed to tell if the program is in this loop. Our
4350 * blocking calls are truly blocking so we always return FALSE.
4352 * Note: It is allowed to call this function without prior WSAStartup().
4359 /***********************************************************************
4360 * WSACancelBlockingCall (WS2_32.113)
4362 INT WINAPI WSACancelBlockingCall(void)
4368 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
4370 FIXME("How was this called?\n");
4375 /***********************************************************************
4376 * WSASetBlockingHook (WS2_32.109)
4378 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
4380 FARPROC prev = blocking_hook;
4381 blocking_hook = lpBlockFunc;
4382 TRACE("hook %p\n", lpBlockFunc);
4387 /***********************************************************************
4388 * WSAUnhookBlockingHook (WS2_32.110)
4390 INT WINAPI WSAUnhookBlockingHook(void)
4392 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
4397 /* ----------------------------------- end of API stuff */
4399 /* ----------------------------------- helper functions -
4401 * TODO: Merge WS_dup_..() stuff into one function that
4402 * would operate with a generic structure containing internal
4403 * pointers (via a template of some kind).
4406 static int list_size(char** l, int item_size)
4411 j += (item_size) ? item_size : strlen(l[i]) + 1;
4412 j += (i + 1) * sizeof(char*); }
4416 static int list_dup(char** l_src, char** l_to, int item_size)
4421 for (i = 0; l_src[i]; i++) ;
4422 p = (char *)(l_to + i + 1);
4423 for (i = 0; l_src[i]; i++)
4425 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
4426 memcpy(p, l_src[i], count);
4431 return p - (char *)l_to;
4436 /* duplicate hostent entry
4437 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
4438 * Ditto for protoent and servent.
4440 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
4443 struct WS_hostent *p_to;
4445 int size = (sizeof(*p_he) +
4446 strlen(p_he->h_name) + 1 +
4447 list_size(p_he->h_aliases, 0) +
4448 list_size(p_he->h_addr_list, p_he->h_length));
4450 if (!(p_to = check_buffer_he(size))) return NULL;
4451 p_to->h_addrtype = p_he->h_addrtype;
4452 p_to->h_length = p_he->h_length;
4454 p = (char *)(p_to + 1);
4456 strcpy(p, p_he->h_name);
4459 p_to->h_aliases = (char **)p;
4460 p += list_dup(p_he->h_aliases, p_to->h_aliases, 0);
4462 p_to->h_addr_list = (char **)p;
4463 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
4467 /* ----- protoent */
4469 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
4472 struct WS_protoent *p_to;
4474 int size = (sizeof(*p_pe) +
4475 strlen(p_pe->p_name) + 1 +
4476 list_size(p_pe->p_aliases, 0));
4478 if (!(p_to = check_buffer_pe(size))) return NULL;
4479 p_to->p_proto = p_pe->p_proto;
4481 p = (char *)(p_to + 1);
4483 strcpy(p, p_pe->p_name);
4486 p_to->p_aliases = (char **)p;
4487 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
4493 static struct WS_servent *WS_dup_se(const struct servent* p_se)
4496 struct WS_servent *p_to;
4498 int size = (sizeof(*p_se) +
4499 strlen(p_se->s_proto) + 1 +
4500 strlen(p_se->s_name) + 1 +
4501 list_size(p_se->s_aliases, 0));
4503 if (!(p_to = check_buffer_se(size))) return NULL;
4504 p_to->s_port = p_se->s_port;
4506 p = (char *)(p_to + 1);
4508 strcpy(p, p_se->s_name);
4512 strcpy(p, p_se->s_proto);
4515 p_to->s_aliases = (char **)p;
4516 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
4521 /***********************************************************************
4522 * WSARecv (WS2_32.67)
4524 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4525 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
4526 LPWSAOVERLAPPED lpOverlapped,
4527 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
4529 return WSARecvFrom(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
4530 NULL, NULL, lpOverlapped, lpCompletionRoutine);
4533 /***********************************************************************
4534 * WSARecvFrom (WS2_32.69)
4536 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4537 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
4538 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
4539 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4542 unsigned int i, options;
4544 struct ws2_async *wsa;
4545 DWORD timeout_start = GetTickCount();
4546 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4548 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
4549 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
4550 (lpFromlen ? *lpFromlen : -1),
4551 lpOverlapped, lpCompletionRoutine);
4553 fd = get_sock_fd( s, FILE_READ_DATA, &options );
4554 TRACE( "fd=%d, options=%x\n", fd, options );
4556 if (fd == -1) return SOCKET_ERROR;
4558 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
4564 wsa->hSocket = SOCKET2HANDLE(s);
4565 wsa->flags = *lpFlags;
4567 wsa->addrlen.ptr = lpFromlen;
4568 wsa->n_iovecs = dwBufferCount;
4569 wsa->first_iovec = 0;
4570 for (i = 0; i < dwBufferCount; i++)
4572 /* check buffer first to trigger write watches */
4573 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
4578 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4579 wsa->iovec[i].iov_len = lpBuffers[i].len;
4584 n = WS2_recv( fd, wsa );
4587 if (errno == EINTR) continue;
4588 if (errno != EAGAIN)
4591 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
4596 *lpNumberOfBytesRecvd = n;
4598 if ((lpOverlapped || lpCompletionRoutine) &&
4599 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4601 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4603 wsa->user_overlapped = lpOverlapped;
4604 wsa->completion_func = lpCompletionRoutine;
4605 release_sock_fd( s, fd );
4609 iosb->u.Status = STATUS_PENDING;
4610 iosb->Information = 0;
4612 SERVER_START_REQ( register_async )
4614 req->type = ASYNC_TYPE_READ;
4615 req->async.handle = wine_server_obj_handle( wsa->hSocket );
4616 req->async.callback = wine_server_client_ptr( WS2_async_recv );
4617 req->async.iosb = wine_server_client_ptr( iosb );
4618 req->async.arg = wine_server_client_ptr( wsa );
4619 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
4620 req->async.cvalue = cvalue;
4621 err = wine_server_call( req );
4625 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4626 WSASetLastError( NtStatusToWSAError( err ));
4627 return SOCKET_ERROR;
4630 iosb->u.Status = STATUS_SUCCESS;
4631 iosb->Information = n;
4632 if (!wsa->completion_func)
4634 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4635 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
4636 HeapFree( GetProcessHeap(), 0, wsa );
4638 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4639 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4640 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4646 if ( _is_blocking(s) )
4649 int timeout = GET_RCVTIMEO(fd);
4652 timeout -= GetTickCount() - timeout_start;
4653 if (timeout < 0) timeout = 0;
4657 pfd.events = POLLIN;
4658 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
4660 if (!timeout || !poll( &pfd, 1, timeout ))
4663 /* a timeout is not fatal */
4664 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4670 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4671 err = WSAEWOULDBLOCK;
4676 TRACE(" -> %i bytes\n", n);
4677 HeapFree( GetProcessHeap(), 0, wsa );
4678 release_sock_fd( s, fd );
4679 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4684 HeapFree( GetProcessHeap(), 0, wsa );
4685 release_sock_fd( s, fd );
4686 WARN(" -> ERROR %d\n", err);
4687 WSASetLastError( err );
4688 return SOCKET_ERROR;
4691 /***********************************************************************
4692 * WSCInstallProvider (WS2_32.88)
4694 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
4695 LPCWSTR lpszProviderDllPath,
4696 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
4697 DWORD dwNumberOfEntries,
4700 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
4701 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
4702 dwNumberOfEntries, lpErrno);
4708 /***********************************************************************
4709 * WSCDeinstallProvider (WS2_32.83)
4711 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
4713 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
4719 /***********************************************************************
4720 * WSAAccept (WS2_32.26)
4722 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
4723 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
4726 int ret = 0, size = 0;
4727 WSABUF CallerId, CallerData, CalleeId, CalleeData;
4728 /* QOS SQOS, GQOS; */
4731 SOCKADDR src_addr, dst_addr;
4733 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %d\n",
4734 s, addr, addrlen, lpfnCondition, dwCallbackData);
4737 size = sizeof(src_addr);
4738 cs = WS_accept(s, &src_addr, &size);
4740 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
4742 if (!lpfnCondition) return cs;
4744 CallerId.buf = (char *)&src_addr;
4745 CallerId.len = sizeof(src_addr);
4747 CallerData.buf = NULL;
4750 WS_getsockname(cs, &dst_addr, &size);
4752 CalleeId.buf = (char *)&dst_addr;
4753 CalleeId.len = sizeof(dst_addr);
4756 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
4757 &CalleeId, &CalleeData, &g, dwCallbackData);
4762 if (addr && addrlen)
4763 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
4766 SERVER_START_REQ( set_socket_deferred )
4768 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4769 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
4770 if ( !wine_server_call_err ( req ) )
4772 SetLastError( WSATRY_AGAIN );
4773 WS_closesocket( cs );
4777 return SOCKET_ERROR;
4780 SetLastError(WSAECONNREFUSED);
4781 return SOCKET_ERROR;
4783 FIXME("Unknown return type from Condition function\n");
4784 SetLastError(WSAENOTSOCK);
4785 return SOCKET_ERROR;
4789 /***********************************************************************
4790 * WSADuplicateSocketA (WS2_32.32)
4792 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
4796 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4797 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4798 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
4799 /* I don't know what the real Windoze does next, this is a hack */
4800 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
4801 * the target use the global duplicate, or we could copy a reference to us to the structure
4802 * and let the target duplicate it from us, but let's do it as simple as possible */
4803 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4804 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4805 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4806 0, FALSE, DUPLICATE_SAME_ACCESS);
4807 CloseHandle(hProcess);
4808 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4812 /***********************************************************************
4813 * WSADuplicateSocketW (WS2_32.33)
4815 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
4819 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4821 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4822 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4823 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4824 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4825 0, FALSE, DUPLICATE_SAME_ACCESS);
4826 CloseHandle(hProcess);
4827 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4831 /***********************************************************************
4832 * WSAInstallServiceClassA (WS2_32.48)
4834 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
4836 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
4837 WSASetLastError(WSAEACCES);
4838 return SOCKET_ERROR;
4841 /***********************************************************************
4842 * WSAInstallServiceClassW (WS2_32.49)
4844 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
4846 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
4847 WSASetLastError(WSAEACCES);
4848 return SOCKET_ERROR;
4851 /***********************************************************************
4852 * WSARemoveServiceClass (WS2_32.70)
4854 int WINAPI WSARemoveServiceClass(LPGUID info)
4856 FIXME("Request to remove service %p\n",info);
4857 WSASetLastError(WSATYPE_NOT_FOUND);
4858 return SOCKET_ERROR;
4861 /***********************************************************************
4862 * inet_ntop (WS2_32.@)
4864 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
4866 #ifdef HAVE_INET_NTOP
4867 struct WS_in6_addr *in6;
4868 struct WS_in_addr *in;
4871 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
4874 WSASetLastError( STATUS_INVALID_PARAMETER );
4883 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
4889 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
4893 WSASetLastError( WSAEAFNOSUPPORT );
4897 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
4900 FIXME( "not supported on this platform\n" );
4901 WSASetLastError( WSAEAFNOSUPPORT );
4906 /***********************************************************************
4907 * WSAStringToAddressA (WS2_32.80)
4909 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
4911 LPWSAPROTOCOL_INFOA lpProtocolInfo,
4912 LPSOCKADDR lpAddress,
4913 LPINT lpAddressLength)
4916 LPSTR workBuffer=NULL,ptrPort;
4918 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
4919 lpProtocolInfo, lpAddress, lpAddressLength );
4921 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
4925 WSASetLastError(WSAEINVAL);
4926 return SOCKET_ERROR;
4930 FIXME("ProtocolInfo not implemented.\n");
4932 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
4933 strlen(AddressString) + 1);
4936 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4937 return SOCKET_ERROR;
4940 strcpy(workBuffer, AddressString);
4942 switch(AddressFamily)
4946 struct in_addr inetaddr;
4948 /* If lpAddressLength is too small, tell caller the size we need */
4949 if (*lpAddressLength < sizeof(SOCKADDR_IN))
4951 *lpAddressLength = sizeof(SOCKADDR_IN);
4955 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
4957 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
4959 ptrPort = strchr(workBuffer, ':');
4962 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
4967 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
4970 if(inet_aton(workBuffer, &inetaddr) > 0)
4972 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
4983 struct in6_addr inetaddr;
4984 /* If lpAddressLength is too small, tell caller the size we need */
4985 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
4987 *lpAddressLength = sizeof(SOCKADDR_IN6);
4991 #ifdef HAVE_INET_PTON
4992 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
4994 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
4996 /* This one is a bit tricky. An IPv6 address contains colons, so the
4997 * check from IPv4 doesn't work like that. However, IPv6 addresses that
4998 * contain a port are written with braces like [fd12:3456:7890::1]:12345
4999 * so what we will do is to look for ']', check if the next char is a
5000 * colon, and if it is, parse the port as in IPv4. */
5002 ptrPort = strchr(workBuffer, ']');
5003 if(ptrPort && *(++ptrPort) == ':')
5005 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
5010 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
5013 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
5015 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
5016 sizeof(struct in6_addr));
5020 #endif /* HAVE_INET_PTON */
5026 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
5027 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
5031 HeapFree(GetProcessHeap(), 0, workBuffer);
5034 WSASetLastError(res);
5035 return SOCKET_ERROR;
5038 /***********************************************************************
5039 * WSAStringToAddressW (WS2_32.81)
5041 * Does anybody know if this functions allows to use hebrew/arabic/chinese... digits?
5042 * If this should be the case, it would be required to map these digits
5043 * to Unicode digits (0-9) using FoldString first.
5045 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
5047 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5048 LPSOCKADDR lpAddress,
5049 LPINT lpAddressLength)
5052 LPSTR workBuffer=NULL;
5053 WSAPROTOCOL_INFOA infoA;
5054 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
5056 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
5057 lpAddress, lpAddressLength );
5059 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
5061 /* if ProtocolInfo is available - convert to ANSI variant */
5064 lpProtoInfoA = &infoA;
5065 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
5067 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5068 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
5070 WSASetLastError( WSAEINVAL);
5071 return SOCKET_ERROR;
5077 /* Translate AddressString to ANSI code page - assumes that only
5078 standard digits 0-9 are used with this API call */
5079 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
5080 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
5084 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
5085 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
5086 lpAddress,lpAddressLength);
5087 HeapFree( GetProcessHeap(), 0, workBuffer );
5091 res = WSA_NOT_ENOUGH_MEMORY;
5096 WSASetLastError(res);
5097 return SOCKET_ERROR;
5100 /***********************************************************************
5101 * WSAAddressToStringA (WS2_32.27)
5103 * See WSAAddressToStringW
5105 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
5106 LPWSAPROTOCOL_INFOA info, LPSTR string,
5110 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
5113 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
5115 if (!sockaddr) return SOCKET_ERROR;
5116 if (!string || !lenstr) return SOCKET_ERROR;
5118 switch(sockaddr->sa_family)
5121 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
5122 sprintf( buffer, "%u.%u.%u.%u:%u",
5123 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
5124 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
5125 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
5126 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
5127 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
5129 p = strchr( buffer, ':' );
5130 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
5135 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
5138 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
5139 if ((sockaddr6->sin6_port))
5140 strcpy(buffer, "[");
5141 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
5143 WSASetLastError(WSAEINVAL);
5144 return SOCKET_ERROR;
5146 if ((sockaddr6->sin6_scope_id))
5147 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
5148 if ((sockaddr6->sin6_port))
5149 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
5154 WSASetLastError(WSAEINVAL);
5155 return SOCKET_ERROR;
5158 size = strlen( buffer ) + 1;
5163 WSASetLastError(WSAEFAULT);
5164 return SOCKET_ERROR;
5168 strcpy( string, buffer );
5172 /***********************************************************************
5173 * WSAAddressToStringW (WS2_32.28)
5175 * Convert a sockaddr address into a readable address string.
5178 * sockaddr [I] Pointer to a sockaddr structure.
5179 * len [I] Size of the sockaddr structure.
5180 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
5181 * string [I/O] Pointer to a buffer to receive the address string.
5182 * lenstr [I/O] Size of the receive buffer in WCHARs.
5186 * Failure: SOCKET_ERROR
5189 * The 'info' parameter is ignored.
5191 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
5192 LPWSAPROTOCOL_INFOW info, LPWSTR string,
5197 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
5200 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
5203 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
5205 if (ret) return ret;
5207 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
5212 WSASetLastError(WSAEFAULT);
5213 return SOCKET_ERROR;
5217 lstrcpyW( string, buffer );
5221 /***********************************************************************
5222 * WSAEnumNameSpaceProvidersA (WS2_32.34)
5224 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
5226 FIXME( "(%p %p) Stub!\n", len, buffer );
5230 /***********************************************************************
5231 * WSAEnumNameSpaceProvidersW (WS2_32.35)
5233 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
5235 FIXME( "(%p %p) Stub!\n", len, buffer );
5239 /***********************************************************************
5240 * WSAGetQOSByName (WS2_32.41)
5242 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
5244 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
5248 /***********************************************************************
5249 * WSAGetServiceClassInfoA (WS2_32.42)
5251 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
5252 LPWSASERVICECLASSINFOA info )
5254 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
5256 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5257 return SOCKET_ERROR;
5260 /***********************************************************************
5261 * WSAGetServiceClassInfoW (WS2_32.43)
5263 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
5264 LPWSASERVICECLASSINFOW info )
5266 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
5268 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5269 return SOCKET_ERROR;
5272 /***********************************************************************
5273 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
5275 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
5277 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
5278 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5279 return SOCKET_ERROR;
5282 /***********************************************************************
5283 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
5285 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
5287 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
5288 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5289 return SOCKET_ERROR;
5292 /***********************************************************************
5293 * WSALookupServiceBeginA (WS2_32.59)
5295 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
5296 DWORD dwControlFlags,
5299 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
5301 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5302 return SOCKET_ERROR;
5305 /***********************************************************************
5306 * WSALookupServiceBeginW (WS2_32.60)
5308 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
5309 DWORD dwControlFlags,
5312 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
5314 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5315 return SOCKET_ERROR;
5318 /***********************************************************************
5319 * WSALookupServiceBeginW (WS2_32.61)
5321 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
5323 FIXME("(%p) Stub!\n", lookup );
5327 /***********************************************************************
5328 * WSALookupServiceNextA (WS2_32.62)
5330 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
5332 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
5336 /***********************************************************************
5337 * WSALookupServiceNextW (WS2_32.63)
5339 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
5341 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
5345 /***********************************************************************
5346 * WSANtohl (WS2_32.64)
5348 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
5350 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
5352 if (!lphostlong) return WSAEFAULT;
5354 *lphostlong = ntohl( netlong );
5358 /***********************************************************************
5359 * WSANtohs (WS2_32.65)
5361 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
5363 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
5365 if (!lphostshort) return WSAEFAULT;
5367 *lphostshort = ntohs( netshort );
5371 /***********************************************************************
5372 * WSAProviderConfigChange (WS2_32.66)
5374 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
5375 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
5377 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
5378 return SOCKET_ERROR;
5381 /***********************************************************************
5382 * WSARecvDisconnect (WS2_32.68)
5384 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
5386 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
5388 return WS_shutdown( s, 0 );
5391 /***********************************************************************
5392 * WSASetServiceA (WS2_32.76)
5394 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
5396 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5400 /***********************************************************************
5401 * WSASetServiceW (WS2_32.77)
5403 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
5405 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5409 /***********************************************************************
5410 * WSCEnableNSProvider (WS2_32.84)
5412 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
5414 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
5418 /***********************************************************************
5419 * WSCGetProviderPath (WS2_32.86)
5421 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
5423 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
5425 if (!errcode || !provider || !len) return WSAEFAULT;
5427 *errcode = WSAEINVAL;
5428 return SOCKET_ERROR;
5431 /***********************************************************************
5432 * WSCInstallNameSpace (WS2_32.87)
5434 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
5435 DWORD version, LPGUID provider )
5437 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
5438 namespace, version, debugstr_guid(provider) );
5442 /***********************************************************************
5443 * WSCUnInstallNameSpace (WS2_32.89)
5445 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
5447 FIXME("(%p) Stub!\n", lpProviderId);
5451 /***********************************************************************
5452 * WSCWriteProviderOrder (WS2_32.91)
5454 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
5456 FIXME("(%p 0x%08x) Stub!\n", entry, number);